]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
Simplify target_async hook interface
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
32d0add0 3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
c906108c 47
9846de1b 48#include <sys/time.h>
c906108c 49
43ff13b4 50#include "event-loop.h"
c2c6d25f 51#include "event-top.h"
2acceee2 52#include "inf-loop.h"
43ff13b4 53
c906108c
SS
54#include <signal.h>
55#include "serial.h"
56
6240bebf
MS
57#include "gdbcore.h" /* for exec_bfd */
58
449092f6 59#include "remote-fileio.h"
a6b151f1 60#include "gdb/fileio.h"
53ce3c39 61#include <sys/stat.h>
dc146f7c 62#include "xml-support.h"
449092f6 63
fd79ecee
DJ
64#include "memory-map.h"
65
35b1e5cc
SS
66#include "tracepoint.h"
67#include "ax.h"
68#include "ax-gdb.h"
d1feda86 69#include "agent.h"
9accd112 70#include "btrace.h"
35b1e5cc 71
0df8b418 72/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
73static char *target_buf;
74static long target_buf_size;
35b1e5cc 75
6765f3e5
DJ
76/* The size to align memory write packets, when practical. The protocol
77 does not guarantee any alignment, and gdb will generate short
78 writes and unaligned writes, but even as a best-effort attempt this
79 can improve bulk transfers. For instance, if a write is misaligned
80 relative to the target's data bus, the stub may need to make an extra
81 round trip fetching data from the target. This doesn't make a
82 huge difference, but it's easy to do, so we try to be helpful.
83
84 The alignment chosen is arbitrary; usually data bus width is
85 important here, not the possibly larger cache line size. */
86enum { REMOTE_ALIGN_WRITES = 16 };
87
23860348 88/* Prototypes for local functions. */
934b9bac 89static void async_cleanup_sigint_signal_handler (void *dummy);
6d820c5c 90static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 91static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 92 int forever, int *is_notif);
6426a772 93
934b9bac
JK
94static void async_handle_remote_sigint (int);
95static void async_handle_remote_sigint_twice (int);
43ff13b4 96
a14ed312 97static void remote_files_info (struct target_ops *ignore);
c906108c 98
f32dbf8c
MM
99static void remote_prepare_to_store (struct target_ops *self,
100 struct regcache *regcache);
c906108c 101
014f9477
TT
102static void remote_open_1 (const char *, int, struct target_ops *,
103 int extended_p);
c906108c 104
de90e03d 105static void remote_close (struct target_ops *self);
c906108c 106
136d6dae 107static void remote_mourn (struct target_ops *ops);
c906108c 108
a14ed312 109static void extended_remote_restart (void);
c906108c 110
136d6dae 111static void extended_remote_mourn (struct target_ops *);
c906108c 112
a14ed312 113static void remote_mourn_1 (struct target_ops *);
c906108c 114
6d820c5c 115static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 116
a14ed312 117static int readchar (int timeout);
c906108c 118
c33e31fd
PA
119static void remote_serial_write (const char *str, int len);
120
7d85a9c0 121static void remote_kill (struct target_ops *ops);
c906108c 122
6a109b6b 123static int remote_can_async_p (struct target_ops *);
75c99385 124
6a109b6b 125static int remote_is_async_p (struct target_ops *);
75c99385 126
6a3753b3 127static void remote_async (struct target_ops *ops, int enable);
75c99385 128
934b9bac 129static void sync_remote_interrupt_twice (int signo);
7a292a7a 130
a14ed312 131static void interrupt_query (void);
c906108c 132
79d7f229
PA
133static void set_general_thread (struct ptid ptid);
134static void set_continue_thread (struct ptid ptid);
c906108c 135
a14ed312 136static void get_offsets (void);
c906108c 137
6d820c5c
DJ
138static void skip_frame (void);
139
140static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 141
a14ed312 142static int hexnumlen (ULONGEST num);
c906108c 143
a14ed312 144static void init_remote_ops (void);
c906108c 145
a14ed312 146static void init_extended_remote_ops (void);
c906108c 147
1eab8a48 148static void remote_stop (struct target_ops *self, ptid_t);
c906108c 149
a14ed312 150static int stubhex (int ch);
c906108c 151
a14ed312 152static int hexnumstr (char *, ULONGEST);
c906108c 153
a14ed312 154static int hexnumnstr (char *, ULONGEST, int);
2df3850c 155
a14ed312 156static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 157
baa336ce 158static void print_packet (const char *);
c906108c 159
a14ed312 160static void compare_sections_command (char *, int);
c906108c 161
a14ed312 162static void packet_command (char *, int);
c906108c 163
a14ed312 164static int stub_unpack_int (char *buff, int fieldlength);
c906108c 165
39f77062 166static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 167
baa336ce 168static int putpkt_binary (const char *buf, int cnt);
c906108c 169
a14ed312 170static void check_binary_download (CORE_ADDR addr);
c906108c 171
5a2468f5 172struct packet_config;
5a2468f5 173
a14ed312 174static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 175
bb572ddd
DJ
176static void show_remote_protocol_packet_cmd (struct ui_file *file,
177 int from_tty,
178 struct cmd_list_element *c,
179 const char *value);
180
82f73884
PA
181static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
182static ptid_t read_ptid (char *buf, char **obuf);
183
c378d69d 184static void remote_set_permissions (struct target_ops *self);
d914c394 185
d5551862 186struct remote_state;
8bd200f1
TT
187static int remote_get_trace_status (struct target_ops *self,
188 struct trace_status *ts);
d5551862 189
ab6617cc
TT
190static int remote_upload_tracepoints (struct target_ops *self,
191 struct uploaded_tp **utpp);
00bf0b85 192
181e3713
TT
193static int remote_upload_trace_state_variables (struct target_ops *self,
194 struct uploaded_tsv **utsvp);
00bf0b85 195
c8d104ad
PA
196static void remote_query_supported (void);
197
36d25514 198static void remote_check_symbols (void);
c8d104ad 199
a14ed312 200void _initialize_remote (void);
c906108c 201
74531fed 202struct stop_reply;
74531fed 203static void stop_reply_xfree (struct stop_reply *);
722247f1 204static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 205static void push_stop_reply (struct stop_reply *);
bcc75809 206static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
207static int peek_stop_reply (ptid_t ptid);
208
209static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 210
e3594fd1 211static void remote_terminal_ours (struct target_ops *self);
d3fd5342 212
d962ef82
DJ
213static int remote_read_description_p (struct target_ops *target);
214
176a6961 215static void remote_console_output (char *msg);
dde08ee1 216
efcc2da7 217static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 218
78eff0ec 219static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 220
f4abbc16
MM
221static void remote_btrace_reset (void);
222
a6b151f1
DJ
223/* For "remote". */
224
225static struct cmd_list_element *remote_cmdlist;
226
bb572ddd
DJ
227/* For "set remote" and "show remote". */
228
229static struct cmd_list_element *remote_set_cmdlist;
230static struct cmd_list_element *remote_show_cmdlist;
231
d458bd84
PA
232/* Stub vCont actions support.
233
234 Each field is a boolean flag indicating whether the stub reports
235 support for the corresponding action. */
236
237struct vCont_action_support
238{
239 /* vCont;t */
240 int t;
c1e36e3e
PA
241
242 /* vCont;r */
243 int r;
d458bd84
PA
244};
245
c1e36e3e
PA
246/* Controls whether GDB is willing to use range stepping. */
247
248static int use_range_stepping = 1;
249
0d031856
TT
250#define OPAQUETHREADBYTES 8
251
252/* a 64 bit opaque identifier */
253typedef unsigned char threadref[OPAQUETHREADBYTES];
254
255/* About this many threadisds fit in a packet. */
256
257#define MAXTHREADLISTRESULTS 32
258
ea9c271d
DJ
259/* Description of the remote protocol state for the currently
260 connected target. This is per-target state, and independent of the
261 selected architecture. */
262
263struct remote_state
264{
265 /* A buffer to use for incoming packets, and its current size. The
266 buffer is grown dynamically for larger incoming packets.
267 Outgoing packets may also be constructed in this buffer.
268 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
269 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
270 packets. */
271 char *buf;
272 long buf_size;
be2a5f71 273
1e51243a
PA
274 /* True if we're going through initial connection setup (finding out
275 about the remote side's threads, relocating symbols, etc.). */
276 int starting_up;
277
be2a5f71
DJ
278 /* If we negotiated packet size explicitly (and thus can bypass
279 heuristics for the largest packet size that will not overflow
280 a buffer in the stub), this will be set to that packet size.
281 Otherwise zero, meaning to use the guessed size. */
282 long explicit_packet_size;
2d717e4f
DJ
283
284 /* remote_wait is normally called when the target is running and
285 waits for a stop reply packet. But sometimes we need to call it
286 when the target is already stopped. We can send a "?" packet
287 and have remote_wait read the response. Or, if we already have
288 the response, we can stash it in BUF and tell remote_wait to
289 skip calling getpkt. This flag is set when BUF contains a
290 stop reply packet and the target is not waiting. */
291 int cached_wait_status;
a6f3e723
SL
292
293 /* True, if in no ack mode. That is, neither GDB nor the stub will
294 expect acks from each other. The connection is assumed to be
295 reliable. */
296 int noack_mode;
82f73884
PA
297
298 /* True if we're connected in extended remote mode. */
299 int extended;
300
e24a49d8
PA
301 /* True if we resumed the target and we're waiting for the target to
302 stop. In the mean time, we can't start another command/query.
303 The remote server wouldn't be ready to process it, so we'd
304 timeout waiting for a reply that would never come and eventually
305 we'd close the connection. This can happen in asynchronous mode
306 because we allow GDB commands while the target is running. */
307 int waiting_for_stop_reply;
74531fed 308
d458bd84
PA
309 /* The status of the stub support for the various vCont actions. */
310 struct vCont_action_support supports_vCont;
782b2b07 311
3a29589a
DJ
312 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
313 responded to that. */
314 int ctrlc_pending_p;
5d93a237
TT
315
316 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
317 remote_open knows that we don't have a file open when the program
318 starts. */
319 struct serial *remote_desc;
47f8a51d
TT
320
321 /* These are the threads which we last sent to the remote system. The
322 TID member will be -1 for all or -2 for not sent yet. */
323 ptid_t general_thread;
324 ptid_t continue_thread;
262e1174
TT
325
326 /* This is the traceframe which we last selected on the remote system.
327 It will be -1 if no traceframe is selected. */
328 int remote_traceframe_number;
747dc59d
TT
329
330 char *last_pass_packet;
5e4a05c4
TT
331
332 /* The last QProgramSignals packet sent to the target. We bypass
333 sending a new program signals list down to the target if the new
334 packet is exactly the same as the last we sent. IOW, we only let
335 the target know about program signals list changes. */
336 char *last_program_signals_packet;
b73be471
TT
337
338 enum gdb_signal last_sent_signal;
280ceea3
TT
339
340 int last_sent_step;
8e88304f
TT
341
342 char *finished_object;
343 char *finished_annex;
344 ULONGEST finished_offset;
b80fafe3
TT
345
346 /* Should we try the 'ThreadInfo' query packet?
347
348 This variable (NOT available to the user: auto-detect only!)
349 determines whether GDB will use the new, simpler "ThreadInfo"
350 query or the older, more complex syntax for thread queries.
351 This is an auto-detect variable (set to true at each connect,
352 and set to false when the target fails to recognize it). */
353 int use_threadinfo_query;
354 int use_threadextra_query;
88b496c3 355
ee154bee
TT
356 /* This is set to the data address of the access causing the target
357 to stop for a watchpoint. */
358 CORE_ADDR remote_watch_data_address;
359
f7e6eed5
PA
360 /* Whether the target stopped for a breakpoint/watchpoint. */
361 enum target_stop_reason stop_reason;
0d031856
TT
362
363 threadref echo_nextthread;
364 threadref nextthread;
365 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
366
367 /* The state of remote notification. */
368 struct remote_notif_state *notif_state;
f4abbc16
MM
369
370 /* The branch trace configuration. */
371 struct btrace_config btrace_config;
ea9c271d
DJ
372};
373
dc146f7c
VP
374/* Private data that we'll store in (struct thread_info)->private. */
375struct private_thread_info
376{
377 char *extra;
378 int core;
379};
380
381static void
382free_private_thread_info (struct private_thread_info *info)
383{
384 xfree (info->extra);
385 xfree (info);
386}
387
ea9c271d
DJ
388/* This data could be associated with a target, but we do not always
389 have access to the current target when we need it, so for now it is
390 static. This will be fine for as long as only one target is in use
391 at a time. */
cf792862 392static struct remote_state *remote_state;
ea9c271d
DJ
393
394static struct remote_state *
0b83947e 395get_remote_state_raw (void)
ea9c271d 396{
cf792862
TT
397 return remote_state;
398}
399
400/* Allocate a new struct remote_state with xmalloc, initialize it, and
401 return it. */
402
403static struct remote_state *
404new_remote_state (void)
405{
406 struct remote_state *result = XCNEW (struct remote_state);
407
408 /* The default buffer size is unimportant; it will be expanded
409 whenever a larger buffer is needed. */
410 result->buf_size = 400;
411 result->buf = xmalloc (result->buf_size);
262e1174 412 result->remote_traceframe_number = -1;
b73be471 413 result->last_sent_signal = GDB_SIGNAL_0;
cf792862
TT
414
415 return result;
ea9c271d
DJ
416}
417
418/* Description of the remote protocol for a given architecture. */
d01949b6 419
ad10f812
AC
420struct packet_reg
421{
422 long offset; /* Offset into G packet. */
423 long regnum; /* GDB's internal register number. */
424 LONGEST pnum; /* Remote protocol register number. */
b323314b 425 int in_g_packet; /* Always part of G packet. */
f5656ead 426 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 427 at present. */
f5656ead 428 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 429 at present. */
ad10f812
AC
430};
431
ea9c271d 432struct remote_arch_state
d01949b6 433{
ad10f812
AC
434 /* Description of the remote protocol registers. */
435 long sizeof_g_packet;
b323314b
AC
436
437 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 438 (making an array gdbarch_num_regs in size). */
b323314b 439 struct packet_reg *regs;
ad10f812 440
d01949b6
AC
441 /* This is the size (in chars) of the first response to the ``g''
442 packet. It is used as a heuristic when determining the maximum
443 size of memory-read and memory-write packets. A target will
444 typically only reserve a buffer large enough to hold the ``g''
445 packet. The size does not include packet overhead (headers and
23860348 446 trailers). */
d01949b6
AC
447 long actual_register_packet_size;
448
449 /* This is the maximum size (in chars) of a non read/write packet.
23860348 450 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
451 long remote_packet_size;
452};
453
35b1e5cc
SS
454/* Utility: generate error from an incoming stub packet. */
455static void
456trace_error (char *buf)
457{
458 if (*buf++ != 'E')
459 return; /* not an error msg */
460 switch (*buf)
461 {
462 case '1': /* malformed packet error */
463 if (*++buf == '0') /* general case: */
464 error (_("remote.c: error in outgoing packet."));
465 else
466 error (_("remote.c: error in outgoing packet at field #%ld."),
467 strtol (buf, NULL, 16));
35b1e5cc
SS
468 default:
469 error (_("Target returns error code '%s'."), buf);
470 }
471}
472
473/* Utility: wait for reply from stub, while accepting "O" packets. */
474static char *
475remote_get_noisy_reply (char **buf_p,
476 long *sizeof_buf)
477{
478 do /* Loop on reply from remote stub. */
479 {
480 char *buf;
a744cf53 481
0df8b418 482 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
483 getpkt (buf_p, sizeof_buf, 0);
484 buf = *buf_p;
ad91cd99 485 if (buf[0] == 'E')
35b1e5cc 486 trace_error (buf);
61012eef 487 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
488 {
489 ULONGEST ul;
490 CORE_ADDR from, to, org_to;
491 char *p, *pp;
492 int adjusted_size = 0;
7556d4a4 493 int relocated = 0;
dde08ee1
PA
494
495 p = buf + strlen ("qRelocInsn:");
496 pp = unpack_varlen_hex (p, &ul);
497 if (*pp != ';')
cb91c06a 498 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
499 from = ul;
500
501 p = pp + 1;
a9cbf802 502 unpack_varlen_hex (p, &ul);
dde08ee1
PA
503 to = ul;
504
505 org_to = to;
506
492d29ea 507 TRY
dde08ee1 508 {
f5656ead 509 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 510 relocated = 1;
dde08ee1 511 }
492d29ea 512 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
513 {
514 if (ex.error == MEMORY_ERROR)
515 {
516 /* Propagate memory errors silently back to the
517 target. The stub may have limited the range of
518 addresses we can write to, for example. */
519 }
520 else
521 {
522 /* Something unexpectedly bad happened. Be verbose
523 so we can tell what, and propagate the error back
524 to the stub, so it doesn't get stuck waiting for
525 a response. */
526 exception_fprintf (gdb_stderr, ex,
527 _("warning: relocating instruction: "));
528 }
529 putpkt ("E01");
530 }
492d29ea 531 END_CATCH
7556d4a4
PA
532
533 if (relocated)
dde08ee1
PA
534 {
535 adjusted_size = to - org_to;
536
bba74b36 537 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
538 putpkt (buf);
539 }
dde08ee1 540 }
ad91cd99 541 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
542 remote_console_output (buf + 1); /* 'O' message from stub */
543 else
0df8b418 544 return buf; /* Here's the actual reply. */
35b1e5cc
SS
545 }
546 while (1);
547}
3c3bea1c 548
d01949b6
AC
549/* Handle for retreving the remote protocol data from gdbarch. */
550static struct gdbarch_data *remote_gdbarch_data_handle;
551
ea9c271d
DJ
552static struct remote_arch_state *
553get_remote_arch_state (void)
d01949b6 554{
f5656ead 555 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
d01949b6
AC
556}
557
0b83947e
DJ
558/* Fetch the global remote target state. */
559
560static struct remote_state *
561get_remote_state (void)
562{
563 /* Make sure that the remote architecture state has been
564 initialized, because doing so might reallocate rs->buf. Any
565 function which calls getpkt also needs to be mindful of changes
566 to rs->buf, but this call limits the number of places which run
567 into trouble. */
568 get_remote_arch_state ();
569
570 return get_remote_state_raw ();
571}
572
74ca34ce
DJ
573static int
574compare_pnums (const void *lhs_, const void *rhs_)
575{
576 const struct packet_reg * const *lhs = lhs_;
577 const struct packet_reg * const *rhs = rhs_;
578
579 if ((*lhs)->pnum < (*rhs)->pnum)
580 return -1;
581 else if ((*lhs)->pnum == (*rhs)->pnum)
582 return 0;
583 else
584 return 1;
585}
586
c21236dc
PA
587static int
588map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 589{
74ca34ce 590 int regnum, num_remote_regs, offset;
74ca34ce 591 struct packet_reg **remote_regs;
ea9c271d 592
4a22f64d 593 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 594 {
c21236dc 595 struct packet_reg *r = &regs[regnum];
baef701f 596
4a22f64d 597 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
598 /* Do not try to fetch zero-sized (placeholder) registers. */
599 r->pnum = -1;
600 else
601 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
602
b323314b 603 r->regnum = regnum;
74ca34ce
DJ
604 }
605
606 /* Define the g/G packet format as the contents of each register
607 with a remote protocol number, in order of ascending protocol
608 number. */
609
4a22f64d 610 remote_regs = alloca (gdbarch_num_regs (gdbarch)
c21236dc 611 * sizeof (struct packet_reg *));
f57d151a 612 for (num_remote_regs = 0, regnum = 0;
4a22f64d 613 regnum < gdbarch_num_regs (gdbarch);
f57d151a 614 regnum++)
c21236dc
PA
615 if (regs[regnum].pnum != -1)
616 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 617
74ca34ce
DJ
618 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
619 compare_pnums);
620
621 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
622 {
623 remote_regs[regnum]->in_g_packet = 1;
624 remote_regs[regnum]->offset = offset;
4a22f64d 625 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
626 }
627
c21236dc
PA
628 return offset;
629}
630
631/* Given the architecture described by GDBARCH, return the remote
632 protocol register's number and the register's offset in the g/G
633 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
634 If the target does not have a mapping for REGNUM, return false,
635 otherwise, return true. */
636
637int
638remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
639 int *pnum, int *poffset)
640{
641 int sizeof_g_packet;
642 struct packet_reg *regs;
643 struct cleanup *old_chain;
644
645 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
646
647 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
648 old_chain = make_cleanup (xfree, regs);
649
650 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
651
652 *pnum = regs[regnum].pnum;
653 *poffset = regs[regnum].offset;
654
655 do_cleanups (old_chain);
656
657 return *pnum != -1;
658}
659
660static void *
661init_remote_state (struct gdbarch *gdbarch)
662{
663 struct remote_state *rs = get_remote_state_raw ();
664 struct remote_arch_state *rsa;
665
666 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
667
668 /* Use the architecture to build a regnum<->pnum table, which will be
669 1:1 unless a feature set specifies otherwise. */
670 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
671 gdbarch_num_regs (gdbarch),
672 struct packet_reg);
673
74ca34ce
DJ
674 /* Record the maximum possible size of the g packet - it may turn out
675 to be smaller. */
c21236dc 676 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 677
0df8b418 678 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
679 remote stubs have a hardwired buffer size of 400 bytes
680 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
681 as the maximum packet-size to ensure that the packet and an extra
682 NUL character can always fit in the buffer. This stops GDB
683 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
684 already a full buffer (As of 1999-12-04 that was most stubs). */
685 rsa->remote_packet_size = 400 - 1;
d01949b6 686
ea9c271d
DJ
687 /* This one is filled in when a ``g'' packet is received. */
688 rsa->actual_register_packet_size = 0;
689
690 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
691 default, adjust the size accordingly. Remember that each byte is
692 encoded as two characters. 32 is the overhead for the packet
693 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 694 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 695 little. */
ea9c271d
DJ
696 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
697 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 698
ea9c271d
DJ
699 /* Make sure that the packet buffer is plenty big enough for
700 this architecture. */
701 if (rs->buf_size < rsa->remote_packet_size)
702 {
703 rs->buf_size = 2 * rsa->remote_packet_size;
7fca722e 704 rs->buf = xrealloc (rs->buf, rs->buf_size);
ea9c271d 705 }
6d820c5c 706
ea9c271d
DJ
707 return rsa;
708}
709
710/* Return the current allowed size of a remote packet. This is
711 inferred from the current architecture, and should be used to
712 limit the length of outgoing packets. */
713static long
714get_remote_packet_size (void)
715{
be2a5f71 716 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
717 struct remote_arch_state *rsa = get_remote_arch_state ();
718
be2a5f71
DJ
719 if (rs->explicit_packet_size)
720 return rs->explicit_packet_size;
721
ea9c271d 722 return rsa->remote_packet_size;
d01949b6
AC
723}
724
ad10f812 725static struct packet_reg *
ea9c271d 726packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 727{
f5656ead 728 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
729 return NULL;
730 else
ad10f812 731 {
ea9c271d 732 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 733
b323314b
AC
734 gdb_assert (r->regnum == regnum);
735 return r;
ad10f812 736 }
ad10f812
AC
737}
738
739static struct packet_reg *
ea9c271d 740packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 741{
b323314b 742 int i;
a744cf53 743
f5656ead 744 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 745 {
ea9c271d 746 struct packet_reg *r = &rsa->regs[i];
a744cf53 747
b323314b
AC
748 if (r->pnum == pnum)
749 return r;
ad10f812
AC
750 }
751 return NULL;
d01949b6
AC
752}
753
c906108c
SS
754static struct target_ops remote_ops;
755
756static struct target_ops extended_remote_ops;
757
6426a772
JM
758/* FIXME: cagney/1999-09-23: Even though getpkt was called with
759 ``forever'' still use the normal timeout mechanism. This is
760 currently used by the ASYNC code to guarentee that target reads
761 during the initial connect always time-out. Once getpkt has been
762 modified to return a timeout indication and, in turn
763 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 764 this can go away. */
6426a772
JM
765static int wait_forever_enabled_p = 1;
766
9a7071a8
JB
767/* Allow the user to specify what sequence to send to the remote
768 when he requests a program interruption: Although ^C is usually
769 what remote systems expect (this is the default, here), it is
770 sometimes preferable to send a break. On other systems such
771 as the Linux kernel, a break followed by g, which is Magic SysRq g
772 is required in order to interrupt the execution. */
773const char interrupt_sequence_control_c[] = "Ctrl-C";
774const char interrupt_sequence_break[] = "BREAK";
775const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 776static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
777 {
778 interrupt_sequence_control_c,
779 interrupt_sequence_break,
780 interrupt_sequence_break_g,
781 NULL
782 };
783static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
784
785static void
786show_interrupt_sequence (struct ui_file *file, int from_tty,
787 struct cmd_list_element *c,
788 const char *value)
789{
790 if (interrupt_sequence_mode == interrupt_sequence_control_c)
791 fprintf_filtered (file,
792 _("Send the ASCII ETX character (Ctrl-c) "
793 "to the remote target to interrupt the "
794 "execution of the program.\n"));
795 else if (interrupt_sequence_mode == interrupt_sequence_break)
796 fprintf_filtered (file,
797 _("send a break signal to the remote target "
798 "to interrupt the execution of the program.\n"));
799 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
800 fprintf_filtered (file,
801 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
802 "the remote target to interrupt the execution "
803 "of Linux kernel.\n"));
804 else
805 internal_error (__FILE__, __LINE__,
806 _("Invalid value for interrupt_sequence_mode: %s."),
807 interrupt_sequence_mode);
808}
6426a772 809
9a7071a8
JB
810/* This boolean variable specifies whether interrupt_sequence is sent
811 to the remote target when gdb connects to it.
812 This is mostly needed when you debug the Linux kernel: The Linux kernel
813 expects BREAK g which is Magic SysRq g for connecting gdb. */
814static int interrupt_on_connect = 0;
c906108c 815
9a7071a8
JB
816/* This variable is used to implement the "set/show remotebreak" commands.
817 Since these commands are now deprecated in favor of "set/show remote
818 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
819static int remote_break;
820
9a7071a8
JB
821static void
822set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
823{
824 if (remote_break)
825 interrupt_sequence_mode = interrupt_sequence_break;
826 else
827 interrupt_sequence_mode = interrupt_sequence_control_c;
828}
829
830static void
831show_remotebreak (struct ui_file *file, int from_tty,
832 struct cmd_list_element *c,
833 const char *value)
834{
835}
836
c906108c
SS
837/* This variable sets the number of bits in an address that are to be
838 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 839 leading zeros, the entire address would be sent. This variable
c906108c
SS
840 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
841 initial implementation of remote.c restricted the address sent in
842 memory packets to ``host::sizeof long'' bytes - (typically 32
843 bits). Consequently, for 64 bit targets, the upper 32 bits of an
844 address was never sent. Since fixing this bug may cause a break in
845 some remote targets this variable is principly provided to
23860348 846 facilitate backward compatibility. */
c906108c 847
883b9c6c 848static unsigned int remote_address_size;
c906108c 849
75c99385
PA
850/* Temporary to track who currently owns the terminal. See
851 remote_terminal_* for more details. */
6426a772
JM
852
853static int remote_async_terminal_ours_p;
854
2d717e4f
DJ
855/* The executable file to use for "run" on the remote side. */
856
857static char *remote_exec_file = "";
858
11cf8741 859\f
11cf8741 860/* User configurable variables for the number of characters in a
ea9c271d
DJ
861 memory read/write packet. MIN (rsa->remote_packet_size,
862 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 863 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
864 (speed up transfers). The variables ``preferred_*'' (the user
865 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 866 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
867
868struct memory_packet_config
869{
870 char *name;
871 long size;
872 int fixed_p;
873};
874
875/* Compute the current size of a read/write packet. Since this makes
876 use of ``actual_register_packet_size'' the computation is dynamic. */
877
878static long
879get_memory_packet_size (struct memory_packet_config *config)
880{
d01949b6 881 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
882 struct remote_arch_state *rsa = get_remote_arch_state ();
883
11cf8741
JM
884 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
885 law?) that some hosts don't cope very well with large alloca()
886 calls. Eventually the alloca() code will be replaced by calls to
887 xmalloc() and make_cleanups() allowing this restriction to either
23860348 888 be lifted or removed. */
11cf8741
JM
889#ifndef MAX_REMOTE_PACKET_SIZE
890#define MAX_REMOTE_PACKET_SIZE 16384
891#endif
3de11b2e 892 /* NOTE: 20 ensures we can write at least one byte. */
11cf8741 893#ifndef MIN_REMOTE_PACKET_SIZE
3de11b2e 894#define MIN_REMOTE_PACKET_SIZE 20
11cf8741
JM
895#endif
896 long what_they_get;
897 if (config->fixed_p)
898 {
899 if (config->size <= 0)
900 what_they_get = MAX_REMOTE_PACKET_SIZE;
901 else
902 what_they_get = config->size;
903 }
904 else
905 {
ea9c271d 906 what_they_get = get_remote_packet_size ();
23860348 907 /* Limit the packet to the size specified by the user. */
11cf8741
JM
908 if (config->size > 0
909 && what_they_get > config->size)
910 what_they_get = config->size;
be2a5f71
DJ
911
912 /* Limit it to the size of the targets ``g'' response unless we have
913 permission from the stub to use a larger packet size. */
914 if (rs->explicit_packet_size == 0
915 && rsa->actual_register_packet_size > 0
916 && what_they_get > rsa->actual_register_packet_size)
917 what_they_get = rsa->actual_register_packet_size;
11cf8741
JM
918 }
919 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
920 what_they_get = MAX_REMOTE_PACKET_SIZE;
921 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
922 what_they_get = MIN_REMOTE_PACKET_SIZE;
6d820c5c
DJ
923
924 /* Make sure there is room in the global buffer for this packet
925 (including its trailing NUL byte). */
926 if (rs->buf_size < what_they_get + 1)
927 {
928 rs->buf_size = 2 * what_they_get;
929 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
930 }
931
11cf8741
JM
932 return what_they_get;
933}
934
0df8b418 935/* Update the size of a read/write packet. If they user wants
23860348 936 something really big then do a sanity check. */
11cf8741
JM
937
938static void
939set_memory_packet_size (char *args, struct memory_packet_config *config)
940{
941 int fixed_p = config->fixed_p;
942 long size = config->size;
a744cf53 943
11cf8741 944 if (args == NULL)
8a3fe4f8 945 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
946 else if (strcmp (args, "hard") == 0
947 || strcmp (args, "fixed") == 0)
948 fixed_p = 1;
949 else if (strcmp (args, "soft") == 0
950 || strcmp (args, "limit") == 0)
951 fixed_p = 0;
952 else
953 {
954 char *end;
a744cf53 955
11cf8741
JM
956 size = strtoul (args, &end, 0);
957 if (args == end)
8a3fe4f8 958 error (_("Invalid %s (bad syntax)."), config->name);
11cf8741
JM
959#if 0
960 /* Instead of explicitly capping the size of a packet to
961 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
962 instead allowed to set the size to something arbitrarily
23860348 963 large. */
11cf8741 964 if (size > MAX_REMOTE_PACKET_SIZE)
8a3fe4f8 965 error (_("Invalid %s (too large)."), config->name);
11cf8741
JM
966#endif
967 }
23860348 968 /* Extra checks? */
11cf8741
JM
969 if (fixed_p && !config->fixed_p)
970 {
e2e0b3e5
AC
971 if (! query (_("The target may not be able to correctly handle a %s\n"
972 "of %ld bytes. Change the packet size? "),
11cf8741 973 config->name, size))
8a3fe4f8 974 error (_("Packet size not changed."));
11cf8741 975 }
23860348 976 /* Update the config. */
11cf8741
JM
977 config->fixed_p = fixed_p;
978 config->size = size;
979}
980
981static void
982show_memory_packet_size (struct memory_packet_config *config)
983{
a3f17187 984 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 985 if (config->fixed_p)
a3f17187 986 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
987 get_memory_packet_size (config));
988 else
a3f17187 989 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
990 get_memory_packet_size (config));
991}
992
993static struct memory_packet_config memory_write_packet_config =
994{
995 "memory-write-packet-size",
996};
997
998static void
999set_memory_write_packet_size (char *args, int from_tty)
1000{
1001 set_memory_packet_size (args, &memory_write_packet_config);
1002}
1003
1004static void
1005show_memory_write_packet_size (char *args, int from_tty)
1006{
1007 show_memory_packet_size (&memory_write_packet_config);
1008}
1009
1010static long
1011get_memory_write_packet_size (void)
1012{
1013 return get_memory_packet_size (&memory_write_packet_config);
1014}
1015
1016static struct memory_packet_config memory_read_packet_config =
1017{
1018 "memory-read-packet-size",
1019};
1020
1021static void
1022set_memory_read_packet_size (char *args, int from_tty)
1023{
1024 set_memory_packet_size (args, &memory_read_packet_config);
1025}
1026
1027static void
1028show_memory_read_packet_size (char *args, int from_tty)
1029{
1030 show_memory_packet_size (&memory_read_packet_config);
1031}
1032
1033static long
1034get_memory_read_packet_size (void)
1035{
1036 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1037
11cf8741
JM
1038 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1039 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1040 increased beyond this. */
1041 if (size > get_remote_packet_size ())
1042 size = get_remote_packet_size ();
11cf8741
JM
1043 return size;
1044}
1045
11cf8741 1046\f
5a2468f5 1047/* Generic configuration support for packets the stub optionally
0df8b418 1048 supports. Allows the user to specify the use of the packet as well
23860348 1049 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1050
1051enum packet_support
1052 {
1053 PACKET_SUPPORT_UNKNOWN = 0,
1054 PACKET_ENABLE,
1055 PACKET_DISABLE
1056 };
1057
5a2468f5
JM
1058struct packet_config
1059 {
bb572ddd
DJ
1060 const char *name;
1061 const char *title;
4082afcc
PA
1062
1063 /* If auto, GDB auto-detects support for this packet or feature,
1064 either through qSupported, or by trying the packet and looking
1065 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1066 packet. If false, the packet is disabled. Configs that don't
1067 have an associated command always have this set to auto. */
7f19b9a2 1068 enum auto_boolean detect;
4082afcc
PA
1069
1070 /* Does the target support this packet? */
5a2468f5
JM
1071 enum packet_support support;
1072 };
1073
d471ea57 1074/* Analyze a packet's return value and update the packet config
23860348 1075 accordingly. */
d471ea57
AC
1076
1077enum packet_result
1078{
1079 PACKET_ERROR,
1080 PACKET_OK,
1081 PACKET_UNKNOWN
1082};
1083
4082afcc
PA
1084static enum packet_support packet_config_support (struct packet_config *config);
1085static enum packet_support packet_support (int packet);
5a2468f5
JM
1086
1087static void
fba45db2 1088show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1089{
1090 char *support = "internal-error";
a744cf53 1091
4082afcc 1092 switch (packet_config_support (config))
5a2468f5
JM
1093 {
1094 case PACKET_ENABLE:
1095 support = "enabled";
1096 break;
1097 case PACKET_DISABLE:
1098 support = "disabled";
1099 break;
1100 case PACKET_SUPPORT_UNKNOWN:
1101 support = "unknown";
1102 break;
1103 }
1104 switch (config->detect)
1105 {
7f19b9a2 1106 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1107 printf_filtered (_("Support for the `%s' packet "
1108 "is auto-detected, currently %s.\n"),
37a105a1 1109 config->name, support);
5a2468f5 1110 break;
7f19b9a2
AC
1111 case AUTO_BOOLEAN_TRUE:
1112 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1113 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1114 config->name, support);
8e248173 1115 break;
5a2468f5
JM
1116 }
1117}
1118
1119static void
bb572ddd
DJ
1120add_packet_config_cmd (struct packet_config *config, const char *name,
1121 const char *title, int legacy)
d471ea57 1122{
5a2468f5
JM
1123 char *set_doc;
1124 char *show_doc;
d471ea57 1125 char *cmd_name;
3ed07be4 1126
5a2468f5
JM
1127 config->name = name;
1128 config->title = title;
b435e160
AC
1129 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1130 name, title);
3e43a32a
MS
1131 show_doc = xstrprintf ("Show current use of remote "
1132 "protocol `%s' (%s) packet",
b435e160 1133 name, title);
d471ea57 1134 /* set/show TITLE-packet {auto,on,off} */
b435e160 1135 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1136 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1137 &config->detect, set_doc,
1138 show_doc, NULL, /* help_doc */
4082afcc 1139 NULL,
bb572ddd
DJ
1140 show_remote_protocol_packet_cmd,
1141 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1142 /* The command code copies the documentation strings. */
1143 xfree (set_doc);
1144 xfree (show_doc);
23860348 1145 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1146 if (legacy)
1147 {
1148 char *legacy_name;
a744cf53 1149
b435e160 1150 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1151 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1152 &remote_set_cmdlist);
d471ea57 1153 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1154 &remote_show_cmdlist);
d471ea57 1155 }
5a2468f5
JM
1156}
1157
d471ea57 1158static enum packet_result
a76d924d 1159packet_check_result (const char *buf)
5a2468f5 1160{
d471ea57 1161 if (buf[0] != '\0')
5a2468f5 1162 {
d471ea57 1163 /* The stub recognized the packet request. Check that the
23860348 1164 operation succeeded. */
a76d924d
DJ
1165 if (buf[0] == 'E'
1166 && isxdigit (buf[1]) && isxdigit (buf[2])
1167 && buf[3] == '\0')
1168 /* "Enn" - definitly an error. */
1169 return PACKET_ERROR;
1170
1171 /* Always treat "E." as an error. This will be used for
1172 more verbose error messages, such as E.memtypes. */
1173 if (buf[0] == 'E' && buf[1] == '.')
1174 return PACKET_ERROR;
1175
1176 /* The packet may or may not be OK. Just assume it is. */
1177 return PACKET_OK;
1178 }
1179 else
1180 /* The stub does not support the packet. */
1181 return PACKET_UNKNOWN;
1182}
1183
1184static enum packet_result
1185packet_ok (const char *buf, struct packet_config *config)
1186{
1187 enum packet_result result;
1188
4082afcc
PA
1189 if (config->detect != AUTO_BOOLEAN_TRUE
1190 && config->support == PACKET_DISABLE)
1191 internal_error (__FILE__, __LINE__,
1192 _("packet_ok: attempt to use a disabled packet"));
1193
a76d924d
DJ
1194 result = packet_check_result (buf);
1195 switch (result)
1196 {
1197 case PACKET_OK:
1198 case PACKET_ERROR:
1199 /* The stub recognized the packet request. */
4082afcc 1200 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1201 {
d471ea57
AC
1202 if (remote_debug)
1203 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1204 "Packet %s (%s) is supported\n",
1205 config->name, config->title);
d471ea57 1206 config->support = PACKET_ENABLE;
d471ea57 1207 }
a76d924d
DJ
1208 break;
1209 case PACKET_UNKNOWN:
23860348 1210 /* The stub does not support the packet. */
4082afcc
PA
1211 if (config->detect == AUTO_BOOLEAN_AUTO
1212 && config->support == PACKET_ENABLE)
d471ea57 1213 {
4082afcc
PA
1214 /* If the stub previously indicated that the packet was
1215 supported then there is a protocol error. */
1216 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1217 config->name, config->title);
1218 }
1219 else if (config->detect == AUTO_BOOLEAN_TRUE)
1220 {
1221 /* The user set it wrong. */
1222 error (_("Enabled packet %s (%s) not recognized by stub"),
1223 config->name, config->title);
d471ea57 1224 }
4082afcc
PA
1225
1226 if (remote_debug)
1227 fprintf_unfiltered (gdb_stdlog,
1228 "Packet %s (%s) is NOT supported\n",
1229 config->name, config->title);
1230 config->support = PACKET_DISABLE;
a76d924d 1231 break;
5a2468f5 1232 }
a76d924d
DJ
1233
1234 return result;
5a2468f5
JM
1235}
1236
444abaca
DJ
1237enum {
1238 PACKET_vCont = 0,
1239 PACKET_X,
1240 PACKET_qSymbol,
1241 PACKET_P,
1242 PACKET_p,
1243 PACKET_Z0,
1244 PACKET_Z1,
1245 PACKET_Z2,
1246 PACKET_Z3,
1247 PACKET_Z4,
a6b151f1
DJ
1248 PACKET_vFile_open,
1249 PACKET_vFile_pread,
1250 PACKET_vFile_pwrite,
1251 PACKET_vFile_close,
1252 PACKET_vFile_unlink,
b9e7b9c3 1253 PACKET_vFile_readlink,
0a93529c 1254 PACKET_vFile_fstat,
0876f84a 1255 PACKET_qXfer_auxv,
23181151 1256 PACKET_qXfer_features,
cfa9d6d9 1257 PACKET_qXfer_libraries,
2268b414 1258 PACKET_qXfer_libraries_svr4,
fd79ecee 1259 PACKET_qXfer_memory_map,
0e7f50da
UW
1260 PACKET_qXfer_spu_read,
1261 PACKET_qXfer_spu_write,
07e059b5 1262 PACKET_qXfer_osdata,
dc146f7c 1263 PACKET_qXfer_threads,
0fb4aa4b 1264 PACKET_qXfer_statictrace_read,
b3b9301e 1265 PACKET_qXfer_traceframe_info,
169081d0 1266 PACKET_qXfer_uib,
711e434b 1267 PACKET_qGetTIBAddr,
444abaca 1268 PACKET_qGetTLSAddr,
be2a5f71 1269 PACKET_qSupported,
bd3eecc3 1270 PACKET_qTStatus,
89be2091 1271 PACKET_QPassSignals,
9b224c5e 1272 PACKET_QProgramSignals,
936d2992 1273 PACKET_qCRC,
08388c79 1274 PACKET_qSearch_memory,
2d717e4f
DJ
1275 PACKET_vAttach,
1276 PACKET_vRun,
a6f3e723 1277 PACKET_QStartNoAckMode,
82f73884 1278 PACKET_vKill,
4aa995e1
PA
1279 PACKET_qXfer_siginfo_read,
1280 PACKET_qXfer_siginfo_write,
0b16c5cf 1281 PACKET_qAttached,
4082afcc
PA
1282
1283 /* Support for conditional tracepoints. */
782b2b07 1284 PACKET_ConditionalTracepoints,
4082afcc
PA
1285
1286 /* Support for target-side breakpoint conditions. */
3788aec7 1287 PACKET_ConditionalBreakpoints,
4082afcc
PA
1288
1289 /* Support for target-side breakpoint commands. */
d3ce09f5 1290 PACKET_BreakpointCommands,
4082afcc
PA
1291
1292 /* Support for fast tracepoints. */
7a697b8d 1293 PACKET_FastTracepoints,
4082afcc
PA
1294
1295 /* Support for static tracepoints. */
0fb4aa4b 1296 PACKET_StaticTracepoints,
4082afcc
PA
1297
1298 /* Support for installing tracepoints while a trace experiment is
1299 running. */
1e4d1764 1300 PACKET_InstallInTrace,
4082afcc 1301
40ab02ce
MS
1302 PACKET_bc,
1303 PACKET_bs,
409873ef 1304 PACKET_TracepointSource,
d914c394 1305 PACKET_QAllow,
78d85199 1306 PACKET_qXfer_fdpic,
03583c20 1307 PACKET_QDisableRandomization,
d1feda86 1308 PACKET_QAgent,
f6f899bf 1309 PACKET_QTBuffer_size,
9accd112
MM
1310 PACKET_Qbtrace_off,
1311 PACKET_Qbtrace_bts,
1312 PACKET_qXfer_btrace,
4082afcc
PA
1313
1314 /* Support for the QNonStop packet. */
1315 PACKET_QNonStop,
1316
1317 /* Support for multi-process extensions. */
1318 PACKET_multiprocess_feature,
1319
1320 /* Support for enabling and disabling tracepoints while a trace
1321 experiment is running. */
1322 PACKET_EnableDisableTracepoints_feature,
1323
1324 /* Support for collecting strings using the tracenz bytecode. */
1325 PACKET_tracenz_feature,
1326
1327 /* Support for continuing to run a trace experiment while GDB is
1328 disconnected. */
1329 PACKET_DisconnectedTracing_feature,
1330
1331 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1332 PACKET_augmented_libraries_svr4_read_feature,
1333
f4abbc16
MM
1334 /* Support for the qXfer:btrace-conf:read packet. */
1335 PACKET_qXfer_btrace_conf,
1336
d33501a5
MM
1337 /* Support for the Qbtrace-conf:bts:size packet. */
1338 PACKET_Qbtrace_conf_bts_size,
1339
f7e6eed5
PA
1340 /* Support for swbreak+ feature. */
1341 PACKET_swbreak_feature,
1342
1343 /* Support for hwbreak+ feature. */
1344 PACKET_hwbreak_feature,
1345
444abaca
DJ
1346 PACKET_MAX
1347};
506fb367 1348
444abaca 1349static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1350
f7e6eed5
PA
1351/* Returns the packet's corresponding "set remote foo-packet" command
1352 state. See struct packet_config for more details. */
1353
1354static enum auto_boolean
1355packet_set_cmd_state (int packet)
1356{
1357 return remote_protocol_packets[packet].detect;
1358}
1359
4082afcc
PA
1360/* Returns whether a given packet or feature is supported. This takes
1361 into account the state of the corresponding "set remote foo-packet"
1362 command, which may be used to bypass auto-detection. */
dc8acb97 1363
4082afcc
PA
1364static enum packet_support
1365packet_config_support (struct packet_config *config)
1366{
1367 switch (config->detect)
444abaca 1368 {
4082afcc
PA
1369 case AUTO_BOOLEAN_TRUE:
1370 return PACKET_ENABLE;
1371 case AUTO_BOOLEAN_FALSE:
1372 return PACKET_DISABLE;
1373 case AUTO_BOOLEAN_AUTO:
1374 return config->support;
1375 default:
1376 gdb_assert_not_reached (_("bad switch"));
444abaca 1377 }
4082afcc
PA
1378}
1379
1380/* Same as packet_config_support, but takes the packet's enum value as
1381 argument. */
1382
1383static enum packet_support
1384packet_support (int packet)
1385{
1386 struct packet_config *config = &remote_protocol_packets[packet];
1387
1388 return packet_config_support (config);
dc8acb97
MS
1389}
1390
5a2468f5 1391static void
444abaca
DJ
1392show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1393 struct cmd_list_element *c,
1394 const char *value)
5a2468f5 1395{
444abaca 1396 struct packet_config *packet;
5a2468f5 1397
444abaca
DJ
1398 for (packet = remote_protocol_packets;
1399 packet < &remote_protocol_packets[PACKET_MAX];
1400 packet++)
1401 {
1402 if (&packet->detect == c->var)
1403 {
1404 show_packet_config_cmd (packet);
1405 return;
1406 }
1407 }
9b20d036 1408 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1409 c->name);
5a2468f5
JM
1410}
1411
d471ea57
AC
1412/* Should we try one of the 'Z' requests? */
1413
1414enum Z_packet_type
1415{
1416 Z_PACKET_SOFTWARE_BP,
1417 Z_PACKET_HARDWARE_BP,
1418 Z_PACKET_WRITE_WP,
1419 Z_PACKET_READ_WP,
1420 Z_PACKET_ACCESS_WP,
1421 NR_Z_PACKET_TYPES
1422};
96baa820 1423
d471ea57 1424/* For compatibility with older distributions. Provide a ``set remote
23860348 1425 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1426
7f19b9a2 1427static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1428
1429static void
fba45db2
KB
1430set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1431 struct cmd_list_element *c)
96baa820 1432{
d471ea57 1433 int i;
a744cf53 1434
d471ea57 1435 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1436 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1437}
1438
1439static void
08546159
AC
1440show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1441 struct cmd_list_element *c,
1442 const char *value)
96baa820 1443{
d471ea57 1444 int i;
a744cf53 1445
d471ea57
AC
1446 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1447 {
444abaca 1448 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1449 }
96baa820
JM
1450}
1451
4082afcc
PA
1452/* Returns true if the multi-process extensions are in effect. */
1453
1454static int
1455remote_multi_process_p (struct remote_state *rs)
1456{
1457 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1458}
1459
23860348 1460/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1461static struct async_signal_handler *async_sigint_remote_twice_token;
1462static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1463
74531fed
PA
1464\f
1465/* Asynchronous signal handle registered as event loop source for
1466 when we have pending events ready to be passed to the core. */
1467
1468static struct async_event_handler *remote_async_inferior_event_token;
1469
c906108c
SS
1470\f
1471
79d7f229
PA
1472static ptid_t magic_null_ptid;
1473static ptid_t not_sent_ptid;
1474static ptid_t any_thread_ptid;
1475
0b16c5cf
PA
1476/* Find out if the stub attached to PID (and hence GDB should offer to
1477 detach instead of killing it when bailing out). */
1478
1479static int
1480remote_query_attached (int pid)
1481{
1482 struct remote_state *rs = get_remote_state ();
bba74b36 1483 size_t size = get_remote_packet_size ();
0b16c5cf 1484
4082afcc 1485 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1486 return 0;
1487
1488 if (remote_multi_process_p (rs))
bba74b36 1489 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1490 else
bba74b36 1491 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1492
1493 putpkt (rs->buf);
1494 getpkt (&rs->buf, &rs->buf_size, 0);
1495
1496 switch (packet_ok (rs->buf,
1554e9be 1497 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1498 {
1499 case PACKET_OK:
1500 if (strcmp (rs->buf, "1") == 0)
1501 return 1;
1502 break;
1503 case PACKET_ERROR:
1504 warning (_("Remote failure reply: %s"), rs->buf);
1505 break;
1506 case PACKET_UNKNOWN:
1507 break;
1508 }
1509
1510 return 0;
1511}
1512
49c62f2e
PA
1513/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1514 has been invented by GDB, instead of reported by the target. Since
1515 we can be connected to a remote system before before knowing about
1516 any inferior, mark the target with execution when we find the first
1517 inferior. If ATTACHED is 1, then we had just attached to this
1518 inferior. If it is 0, then we just created this inferior. If it
1519 is -1, then try querying the remote stub to find out if it had
1520 attached to the inferior or not. */
1941c569
PA
1521
1522static struct inferior *
49c62f2e 1523remote_add_inferior (int fake_pid_p, int pid, int attached)
1941c569 1524{
1941c569
PA
1525 struct inferior *inf;
1526
0b16c5cf
PA
1527 /* Check whether this process we're learning about is to be
1528 considered attached, or if is to be considered to have been
1529 spawned by the stub. */
1530 if (attached == -1)
1531 attached = remote_query_attached (pid);
1532
f5656ead 1533 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1534 {
1535 /* If the target shares code across all inferiors, then every
1536 attach adds a new inferior. */
1537 inf = add_inferior (pid);
1538
1539 /* ... and every inferior is bound to the same program space.
1540 However, each inferior may still have its own address
1541 space. */
1542 inf->aspace = maybe_new_address_space ();
1543 inf->pspace = current_program_space;
1544 }
1545 else
1546 {
1547 /* In the traditional debugging scenario, there's a 1-1 match
1548 between program/address spaces. We simply bind the inferior
1549 to the program space's address space. */
1550 inf = current_inferior ();
1551 inferior_appeared (inf, pid);
1552 }
1941c569 1553
0b16c5cf 1554 inf->attach_flag = attached;
49c62f2e 1555 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1556
1941c569
PA
1557 return inf;
1558}
1559
1560/* Add thread PTID to GDB's thread list. Tag it as executing/running
1561 according to RUNNING. */
1562
c906108c 1563static void
1941c569 1564remote_add_thread (ptid_t ptid, int running)
c906108c 1565{
b7ea362b
PA
1566 struct remote_state *rs = get_remote_state ();
1567
1568 /* GDB historically didn't pull threads in the initial connection
1569 setup. If the remote target doesn't even have a concept of
1570 threads (e.g., a bare-metal target), even if internally we
1571 consider that a single-threaded target, mentioning a new thread
1572 might be confusing to the user. Be silent then, preserving the
1573 age old behavior. */
1574 if (rs->starting_up)
1575 add_thread_silent (ptid);
1576 else
1577 add_thread (ptid);
1941c569
PA
1578
1579 set_executing (ptid, running);
1580 set_running (ptid, running);
1581}
1582
1583/* Come here when we learn about a thread id from the remote target.
1584 It may be the first time we hear about such thread, so take the
1585 opportunity to add it to GDB's thread list. In case this is the
1586 first time we're noticing its corresponding inferior, add it to
1587 GDB's inferior list as well. */
1588
1589static void
1590remote_notice_new_inferior (ptid_t currthread, int running)
1591{
c906108c
SS
1592 /* If this is a new thread, add it to GDB's thread list.
1593 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1594
1595 if (in_thread_list (currthread) && is_exited (currthread))
1596 {
1597 /* We're seeing an event on a thread id we knew had exited.
1598 This has to be a new thread reusing the old id. Add it. */
1941c569 1599 remote_add_thread (currthread, running);
82f73884
PA
1600 return;
1601 }
1602
79d7f229 1603 if (!in_thread_list (currthread))
c0a2216e 1604 {
1941c569 1605 struct inferior *inf = NULL;
bad34192 1606 int pid = ptid_get_pid (currthread);
1941c569 1607
bad34192
PA
1608 if (ptid_is_pid (inferior_ptid)
1609 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1610 {
1611 /* inferior_ptid has no thread member yet. This can happen
1612 with the vAttach -> remote_wait,"TAAthread:" path if the
1613 stub doesn't support qC. This is the first stop reported
1614 after an attach, so this is the main thread. Update the
1615 ptid in the thread list. */
bad34192
PA
1616 if (in_thread_list (pid_to_ptid (pid)))
1617 thread_change_ptid (inferior_ptid, currthread);
1618 else
1619 {
1620 remote_add_thread (currthread, running);
1621 inferior_ptid = currthread;
1622 }
dc146f7c 1623 return;
c0a2216e 1624 }
82f73884
PA
1625
1626 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1627 {
1628 /* inferior_ptid is not set yet. This can happen with the
1629 vRun -> remote_wait,"TAAthread:" path if the stub
1630 doesn't support qC. This is the first stop reported
1631 after an attach, so this is the main thread. Update the
1632 ptid in the thread list. */
dc146f7c 1633 thread_change_ptid (inferior_ptid, currthread);
82f73884 1634 return;
c0a2216e 1635 }
82f73884 1636
29c87f7f
PA
1637 /* When connecting to a target remote, or to a target
1638 extended-remote which already was debugging an inferior, we
1639 may not know about it yet. Add it before adding its child
1640 thread, so notifications are emitted in a sensible order. */
1641 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1642 {
1643 struct remote_state *rs = get_remote_state ();
1644 int fake_pid_p = !remote_multi_process_p (rs);
1645
1646 inf = remote_add_inferior (fake_pid_p,
1647 ptid_get_pid (currthread), -1);
1648 }
29c87f7f 1649
82f73884 1650 /* This is really a new thread. Add it. */
1941c569
PA
1651 remote_add_thread (currthread, running);
1652
1653 /* If we found a new inferior, let the common code do whatever
1654 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1655 breakpoints), unless we're just setting up an all-stop
1656 connection. */
1941c569 1657 if (inf != NULL)
b7ea362b
PA
1658 {
1659 struct remote_state *rs = get_remote_state ();
1660
1661 if (non_stop || !rs->starting_up)
1662 notice_new_inferior (currthread, running, 0);
1663 }
c0a2216e 1664 }
c906108c
SS
1665}
1666
dc146f7c
VP
1667/* Return the private thread data, creating it if necessary. */
1668
70221824 1669static struct private_thread_info *
dc146f7c
VP
1670demand_private_info (ptid_t ptid)
1671{
1672 struct thread_info *info = find_thread_ptid (ptid);
1673
1674 gdb_assert (info);
1675
fe978cb0 1676 if (!info->priv)
dc146f7c 1677 {
fe978cb0 1678 info->priv = xmalloc (sizeof (*(info->priv)));
dc146f7c 1679 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1680 info->priv->core = -1;
1681 info->priv->extra = 0;
dc146f7c
VP
1682 }
1683
fe978cb0 1684 return info->priv;
dc146f7c
VP
1685}
1686
74531fed
PA
1687/* Call this function as a result of
1688 1) A halt indication (T packet) containing a thread id
1689 2) A direct query of currthread
0df8b418 1690 3) Successful execution of set thread */
74531fed
PA
1691
1692static void
47f8a51d 1693record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1694{
47f8a51d 1695 rs->general_thread = currthread;
74531fed
PA
1696}
1697
89be2091
DJ
1698/* If 'QPassSignals' is supported, tell the remote stub what signals
1699 it can simply pass through to the inferior without reporting. */
1700
1701static void
94bedb42
TT
1702remote_pass_signals (struct target_ops *self,
1703 int numsigs, unsigned char *pass_signals)
89be2091 1704{
4082afcc 1705 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1706 {
1707 char *pass_packet, *p;
89be2091 1708 int count = 0, i;
747dc59d 1709 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1710
1711 gdb_assert (numsigs < 256);
1712 for (i = 0; i < numsigs; i++)
1713 {
2455069d 1714 if (pass_signals[i])
89be2091
DJ
1715 count++;
1716 }
1717 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1718 strcpy (pass_packet, "QPassSignals:");
1719 p = pass_packet + strlen (pass_packet);
1720 for (i = 0; i < numsigs; i++)
1721 {
2455069d 1722 if (pass_signals[i])
89be2091
DJ
1723 {
1724 if (i >= 16)
1725 *p++ = tohex (i >> 4);
1726 *p++ = tohex (i & 15);
1727 if (count)
1728 *p++ = ';';
1729 else
1730 break;
1731 count--;
1732 }
1733 }
1734 *p = 0;
747dc59d 1735 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1736 {
89be2091
DJ
1737 putpkt (pass_packet);
1738 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1739 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1740 if (rs->last_pass_packet)
1741 xfree (rs->last_pass_packet);
1742 rs->last_pass_packet = pass_packet;
89be2091
DJ
1743 }
1744 else
1745 xfree (pass_packet);
1746 }
1747}
1748
9b224c5e
PA
1749/* If 'QProgramSignals' is supported, tell the remote stub what
1750 signals it should pass through to the inferior when detaching. */
1751
1752static void
daf5e9b6
TT
1753remote_program_signals (struct target_ops *self,
1754 int numsigs, unsigned char *signals)
9b224c5e 1755{
4082afcc 1756 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1757 {
1758 char *packet, *p;
1759 int count = 0, i;
5e4a05c4 1760 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1761
1762 gdb_assert (numsigs < 256);
1763 for (i = 0; i < numsigs; i++)
1764 {
1765 if (signals[i])
1766 count++;
1767 }
1768 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1769 strcpy (packet, "QProgramSignals:");
1770 p = packet + strlen (packet);
1771 for (i = 0; i < numsigs; i++)
1772 {
1773 if (signal_pass_state (i))
1774 {
1775 if (i >= 16)
1776 *p++ = tohex (i >> 4);
1777 *p++ = tohex (i & 15);
1778 if (count)
1779 *p++ = ';';
1780 else
1781 break;
1782 count--;
1783 }
1784 }
1785 *p = 0;
5e4a05c4
TT
1786 if (!rs->last_program_signals_packet
1787 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 1788 {
9b224c5e
PA
1789 putpkt (packet);
1790 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1791 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
1792 xfree (rs->last_program_signals_packet);
1793 rs->last_program_signals_packet = packet;
9b224c5e
PA
1794 }
1795 else
1796 xfree (packet);
1797 }
1798}
1799
79d7f229
PA
1800/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1801 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1802 thread. If GEN is set, set the general thread, if not, then set
1803 the step/continue thread. */
c906108c 1804static void
79d7f229 1805set_thread (struct ptid ptid, int gen)
c906108c 1806{
d01949b6 1807 struct remote_state *rs = get_remote_state ();
47f8a51d 1808 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 1809 char *buf = rs->buf;
79d7f229 1810 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1811
79d7f229 1812 if (ptid_equal (state, ptid))
c906108c
SS
1813 return;
1814
79d7f229
PA
1815 *buf++ = 'H';
1816 *buf++ = gen ? 'g' : 'c';
1817 if (ptid_equal (ptid, magic_null_ptid))
1818 xsnprintf (buf, endbuf - buf, "0");
1819 else if (ptid_equal (ptid, any_thread_ptid))
1820 xsnprintf (buf, endbuf - buf, "0");
1821 else if (ptid_equal (ptid, minus_one_ptid))
1822 xsnprintf (buf, endbuf - buf, "-1");
1823 else
82f73884 1824 write_ptid (buf, endbuf, ptid);
79d7f229 1825 putpkt (rs->buf);
6d820c5c 1826 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1827 if (gen)
47f8a51d 1828 rs->general_thread = ptid;
c906108c 1829 else
47f8a51d 1830 rs->continue_thread = ptid;
c906108c 1831}
79d7f229
PA
1832
1833static void
1834set_general_thread (struct ptid ptid)
1835{
1836 set_thread (ptid, 1);
1837}
1838
1839static void
1840set_continue_thread (struct ptid ptid)
1841{
1842 set_thread (ptid, 0);
1843}
1844
3c9c4b83
PA
1845/* Change the remote current process. Which thread within the process
1846 ends up selected isn't important, as long as it is the same process
1847 as what INFERIOR_PTID points to.
1848
1849 This comes from that fact that there is no explicit notion of
1850 "selected process" in the protocol. The selected process for
1851 general operations is the process the selected general thread
1852 belongs to. */
1853
1854static void
1855set_general_process (void)
1856{
1857 struct remote_state *rs = get_remote_state ();
1858
1859 /* If the remote can't handle multiple processes, don't bother. */
901f9912 1860 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
1861 return;
1862
1863 /* We only need to change the remote current thread if it's pointing
1864 at some other process. */
47f8a51d 1865 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
1866 set_general_thread (inferior_ptid);
1867}
1868
c906108c 1869\f
7d1a114c
PA
1870/* Return nonzero if this is the main thread that we made up ourselves
1871 to model non-threaded targets as single-threaded. */
c906108c
SS
1872
1873static int
7d1a114c 1874remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 1875{
6d820c5c 1876 struct remote_state *rs = get_remote_state ();
82f73884 1877 char *p, *endp;
c906108c 1878
c0a2216e
PA
1879 if (ptid_equal (ptid, magic_null_ptid))
1880 /* The main thread is always alive. */
1881 return 1;
1882
ba348170 1883 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
1884 /* The main thread is always alive. This can happen after a
1885 vAttach, if the remote side doesn't support
1886 multi-threading. */
1887 return 1;
1888
7d1a114c
PA
1889 return 0;
1890}
1891
1892/* Return nonzero if the thread PTID is still alive on the remote
1893 system. */
1894
1895static int
1896remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1897{
1898 struct remote_state *rs = get_remote_state ();
1899 char *p, *endp;
1900
1901 /* Check if this is a thread that we made up ourselves to model
1902 non-threaded targets as single-threaded. */
1903 if (remote_thread_always_alive (ops, ptid))
1904 return 1;
1905
82f73884
PA
1906 p = rs->buf;
1907 endp = rs->buf + get_remote_packet_size ();
1908
1909 *p++ = 'T';
1910 write_ptid (p, endp, ptid);
1911
2e9f7625 1912 putpkt (rs->buf);
6d820c5c 1913 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1914 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
1915}
1916
1917/* About these extended threadlist and threadinfo packets. They are
1918 variable length packets but, the fields within them are often fixed
1919 length. They are redundent enough to send over UDP as is the
1920 remote protocol in general. There is a matching unit test module
1921 in libstub. */
1922
23860348 1923/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 1924 libstub protocol encoding, and remote.c. It is not particularly
23860348 1925 changable. */
cce74817
JM
1926
1927/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 1928 Plan to fix this. */
cce74817 1929
23860348 1930typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 1931
9d1f7ab2 1932/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 1933 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
1934
1935struct gdb_ext_thread_info
c5aa993b 1936 {
23860348 1937 threadref threadid; /* External form of thread reference. */
2bc416ba 1938 int active; /* Has state interesting to GDB?
23860348 1939 regs, stack. */
2bc416ba 1940 char display[256]; /* Brief state display, name,
cedea757 1941 blocked/suspended. */
23860348 1942 char shortname[32]; /* To be used to name threads. */
2bc416ba 1943 char more_display[256]; /* Long info, statistics, queue depth,
23860348 1944 whatever. */
c5aa993b 1945 };
cce74817
JM
1946
1947/* The volume of remote transfers can be limited by submitting
1948 a mask containing bits specifying the desired information.
1949 Use a union of these values as the 'selection' parameter to
0df8b418 1950 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
1951
1952#define TAG_THREADID 1
1953#define TAG_EXISTS 2
1954#define TAG_DISPLAY 4
1955#define TAG_THREADNAME 8
c5aa993b 1956#define TAG_MOREDISPLAY 16
cce74817 1957
23860348 1958#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 1959
a14ed312 1960static char *unpack_nibble (char *buf, int *val);
cce74817 1961
a14ed312 1962static char *unpack_byte (char *buf, int *value);
cce74817 1963
a14ed312 1964static char *pack_int (char *buf, int value);
cce74817 1965
a14ed312 1966static char *unpack_int (char *buf, int *value);
cce74817 1967
a14ed312 1968static char *unpack_string (char *src, char *dest, int length);
cce74817 1969
23860348 1970static char *pack_threadid (char *pkt, threadref *id);
cce74817 1971
23860348 1972static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 1973
23860348 1974void int_to_threadref (threadref *id, int value);
cce74817 1975
23860348 1976static int threadref_to_int (threadref *ref);
cce74817 1977
23860348 1978static void copy_threadref (threadref *dest, threadref *src);
cce74817 1979
23860348 1980static int threadmatch (threadref *dest, threadref *src);
cce74817 1981
2bc416ba 1982static char *pack_threadinfo_request (char *pkt, int mode,
23860348 1983 threadref *id);
cce74817 1984
a14ed312 1985static int remote_unpack_thread_info_response (char *pkt,
23860348 1986 threadref *expectedref,
a14ed312
KB
1987 struct gdb_ext_thread_info
1988 *info);
cce74817
JM
1989
1990
2bc416ba 1991static int remote_get_threadinfo (threadref *threadid,
23860348 1992 int fieldset, /*TAG mask */
a14ed312 1993 struct gdb_ext_thread_info *info);
cce74817 1994
a14ed312
KB
1995static char *pack_threadlist_request (char *pkt, int startflag,
1996 int threadcount,
23860348 1997 threadref *nextthread);
cce74817 1998
a14ed312
KB
1999static int parse_threadlist_response (char *pkt,
2000 int result_limit,
23860348 2001 threadref *original_echo,
2bc416ba 2002 threadref *resultlist,
23860348 2003 int *doneflag);
cce74817 2004
a14ed312 2005static int remote_get_threadlist (int startflag,
23860348 2006 threadref *nextthread,
a14ed312
KB
2007 int result_limit,
2008 int *done,
2bc416ba 2009 int *result_count,
23860348 2010 threadref *threadlist);
cce74817 2011
23860348 2012typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2013
a14ed312
KB
2014static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2015 void *context, int looplimit);
cce74817 2016
23860348 2017static int remote_newthread_step (threadref *ref, void *context);
cce74817 2018
82f73884
PA
2019
2020/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2021 buffer we're allowed to write to. Returns
2022 BUF+CHARACTERS_WRITTEN. */
2023
2024static char *
2025write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2026{
2027 int pid, tid;
2028 struct remote_state *rs = get_remote_state ();
2029
2030 if (remote_multi_process_p (rs))
2031 {
2032 pid = ptid_get_pid (ptid);
2033 if (pid < 0)
2034 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2035 else
2036 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2037 }
ba348170 2038 tid = ptid_get_lwp (ptid);
82f73884
PA
2039 if (tid < 0)
2040 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2041 else
2042 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2043
2044 return buf;
2045}
2046
2047/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2048 passed the last parsed char. Returns null_ptid on error. */
2049
2050static ptid_t
2051read_ptid (char *buf, char **obuf)
2052{
2053 char *p = buf;
2054 char *pp;
2055 ULONGEST pid = 0, tid = 0;
82f73884
PA
2056
2057 if (*p == 'p')
2058 {
2059 /* Multi-process ptid. */
2060 pp = unpack_varlen_hex (p + 1, &pid);
2061 if (*pp != '.')
b37520b6 2062 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2063
2064 p = pp;
2065 pp = unpack_varlen_hex (p + 1, &tid);
2066 if (obuf)
2067 *obuf = pp;
ba348170 2068 return ptid_build (pid, tid, 0);
82f73884
PA
2069 }
2070
2071 /* No multi-process. Just a tid. */
2072 pp = unpack_varlen_hex (p, &tid);
2073
2074 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2075 what's in inferior_ptid, unless it's null at this point. If so,
2076 then since there's no way to know the pid of the reported
2077 threads, use the magic number. */
2078 if (ptid_equal (inferior_ptid, null_ptid))
2079 pid = ptid_get_pid (magic_null_ptid);
2080 else
2081 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2082
2083 if (obuf)
2084 *obuf = pp;
ba348170 2085 return ptid_build (pid, tid, 0);
82f73884
PA
2086}
2087
c906108c 2088static int
fba45db2 2089stubhex (int ch)
c906108c
SS
2090{
2091 if (ch >= 'a' && ch <= 'f')
2092 return ch - 'a' + 10;
2093 if (ch >= '0' && ch <= '9')
2094 return ch - '0';
2095 if (ch >= 'A' && ch <= 'F')
2096 return ch - 'A' + 10;
2097 return -1;
2098}
2099
2100static int
fba45db2 2101stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2102{
2103 int nibble;
2104 int retval = 0;
2105
2106 while (fieldlength)
2107 {
2108 nibble = stubhex (*buff++);
2109 retval |= nibble;
2110 fieldlength--;
2111 if (fieldlength)
2112 retval = retval << 4;
2113 }
2114 return retval;
2115}
2116
c906108c 2117static char *
fba45db2 2118unpack_nibble (char *buf, int *val)
c906108c 2119{
b7589f7d 2120 *val = fromhex (*buf++);
c906108c
SS
2121 return buf;
2122}
2123
c906108c 2124static char *
fba45db2 2125unpack_byte (char *buf, int *value)
c906108c
SS
2126{
2127 *value = stub_unpack_int (buf, 2);
2128 return buf + 2;
2129}
2130
2131static char *
fba45db2 2132pack_int (char *buf, int value)
c906108c
SS
2133{
2134 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2135 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2136 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2137 buf = pack_hex_byte (buf, (value & 0xff));
2138 return buf;
2139}
2140
2141static char *
fba45db2 2142unpack_int (char *buf, int *value)
c906108c
SS
2143{
2144 *value = stub_unpack_int (buf, 8);
2145 return buf + 8;
2146}
2147
23860348 2148#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2149static char *pack_string (char *pkt, char *string);
c906108c
SS
2150
2151static char *
fba45db2 2152pack_string (char *pkt, char *string)
c906108c
SS
2153{
2154 char ch;
2155 int len;
2156
2157 len = strlen (string);
2158 if (len > 200)
23860348 2159 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2160 pkt = pack_hex_byte (pkt, len);
2161 while (len-- > 0)
2162 {
2163 ch = *string++;
2164 if ((ch == '\0') || (ch == '#'))
23860348 2165 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2166 *pkt++ = ch;
2167 }
2168 return pkt;
2169}
2170#endif /* 0 (unused) */
2171
2172static char *
fba45db2 2173unpack_string (char *src, char *dest, int length)
c906108c
SS
2174{
2175 while (length--)
2176 *dest++ = *src++;
2177 *dest = '\0';
2178 return src;
2179}
2180
2181static char *
fba45db2 2182pack_threadid (char *pkt, threadref *id)
c906108c
SS
2183{
2184 char *limit;
2185 unsigned char *altid;
2186
2187 altid = (unsigned char *) id;
2188 limit = pkt + BUF_THREAD_ID_SIZE;
2189 while (pkt < limit)
2190 pkt = pack_hex_byte (pkt, *altid++);
2191 return pkt;
2192}
2193
2194
2195static char *
fba45db2 2196unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2197{
2198 char *altref;
2199 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2200 int x, y;
2201
2202 altref = (char *) id;
2203
2204 while (inbuf < limit)
2205 {
2206 x = stubhex (*inbuf++);
2207 y = stubhex (*inbuf++);
2208 *altref++ = (x << 4) | y;
2209 }
2210 return inbuf;
2211}
2212
2213/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2214 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2215 to use 64bit thread references internally. This is an adapter
2216 function. */
2217
2218void
fba45db2 2219int_to_threadref (threadref *id, int value)
c906108c
SS
2220{
2221 unsigned char *scan;
2222
2223 scan = (unsigned char *) id;
2224 {
2225 int i = 4;
2226 while (i--)
2227 *scan++ = 0;
2228 }
2229 *scan++ = (value >> 24) & 0xff;
2230 *scan++ = (value >> 16) & 0xff;
2231 *scan++ = (value >> 8) & 0xff;
2232 *scan++ = (value & 0xff);
2233}
2234
2235static int
fba45db2 2236threadref_to_int (threadref *ref)
c906108c
SS
2237{
2238 int i, value = 0;
2239 unsigned char *scan;
2240
cfd77fa1 2241 scan = *ref;
c906108c
SS
2242 scan += 4;
2243 i = 4;
2244 while (i-- > 0)
2245 value = (value << 8) | ((*scan++) & 0xff);
2246 return value;
2247}
2248
2249static void
fba45db2 2250copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2251{
2252 int i;
2253 unsigned char *csrc, *cdest;
2254
2255 csrc = (unsigned char *) src;
2256 cdest = (unsigned char *) dest;
2257 i = 8;
2258 while (i--)
2259 *cdest++ = *csrc++;
2260}
2261
2262static int
fba45db2 2263threadmatch (threadref *dest, threadref *src)
c906108c 2264{
23860348 2265 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2266#if 0
2267 unsigned char *srcp, *destp;
2268 int i, result;
2269 srcp = (char *) src;
2270 destp = (char *) dest;
2271
2272 result = 1;
2273 while (i-- > 0)
2274 result &= (*srcp++ == *destp++) ? 1 : 0;
2275 return result;
2276#endif
2277 return 1;
2278}
2279
2280/*
c5aa993b
JM
2281 threadid:1, # always request threadid
2282 context_exists:2,
2283 display:4,
2284 unique_name:8,
2285 more_display:16
2286 */
c906108c
SS
2287
2288/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2289
2290static char *
fba45db2 2291pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2292{
23860348
MS
2293 *pkt++ = 'q'; /* Info Query */
2294 *pkt++ = 'P'; /* process or thread info */
2295 pkt = pack_int (pkt, mode); /* mode */
c906108c 2296 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2297 *pkt = '\0'; /* terminate */
c906108c
SS
2298 return pkt;
2299}
2300
23860348 2301/* These values tag the fields in a thread info response packet. */
c906108c 2302/* Tagging the fields allows us to request specific fields and to
23860348 2303 add more fields as time goes by. */
c906108c 2304
23860348 2305#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2306#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2307 fetch registers and its stack? */
c5aa993b 2308#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2309#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2310#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2311 the process. */
c906108c
SS
2312
2313static int
fba45db2
KB
2314remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2315 struct gdb_ext_thread_info *info)
c906108c 2316{
d01949b6 2317 struct remote_state *rs = get_remote_state ();
c906108c 2318 int mask, length;
cfd77fa1 2319 int tag;
c906108c 2320 threadref ref;
6d820c5c 2321 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2322 int retval = 1;
2323
23860348 2324 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2325 info->active = 0;
2326 info->display[0] = '\0';
2327 info->shortname[0] = '\0';
2328 info->more_display[0] = '\0';
2329
23860348
MS
2330 /* Assume the characters indicating the packet type have been
2331 stripped. */
c906108c
SS
2332 pkt = unpack_int (pkt, &mask); /* arg mask */
2333 pkt = unpack_threadid (pkt, &ref);
2334
2335 if (mask == 0)
8a3fe4f8 2336 warning (_("Incomplete response to threadinfo request."));
c906108c 2337 if (!threadmatch (&ref, expectedref))
23860348 2338 { /* This is an answer to a different request. */
8a3fe4f8 2339 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2340 return 0;
2341 }
2342 copy_threadref (&info->threadid, &ref);
2343
23860348 2344 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2345
23860348
MS
2346 /* Packets are terminated with nulls. */
2347 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2348 {
2349 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2350 pkt = unpack_byte (pkt, &length); /* length */
2351 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2352 {
8a3fe4f8 2353 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2354 retval = 0;
2355 break;
2356 }
2357 if (tag == TAG_THREADID)
2358 {
2359 if (length != 16)
2360 {
8a3fe4f8 2361 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2362 retval = 0;
2363 break;
2364 }
2365 pkt = unpack_threadid (pkt, &ref);
2366 mask = mask & ~TAG_THREADID;
2367 continue;
2368 }
2369 if (tag == TAG_EXISTS)
2370 {
2371 info->active = stub_unpack_int (pkt, length);
2372 pkt += length;
2373 mask = mask & ~(TAG_EXISTS);
2374 if (length > 8)
2375 {
8a3fe4f8 2376 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2377 retval = 0;
2378 break;
2379 }
2380 continue;
2381 }
2382 if (tag == TAG_THREADNAME)
2383 {
2384 pkt = unpack_string (pkt, &info->shortname[0], length);
2385 mask = mask & ~TAG_THREADNAME;
2386 continue;
2387 }
2388 if (tag == TAG_DISPLAY)
2389 {
2390 pkt = unpack_string (pkt, &info->display[0], length);
2391 mask = mask & ~TAG_DISPLAY;
2392 continue;
2393 }
2394 if (tag == TAG_MOREDISPLAY)
2395 {
2396 pkt = unpack_string (pkt, &info->more_display[0], length);
2397 mask = mask & ~TAG_MOREDISPLAY;
2398 continue;
2399 }
8a3fe4f8 2400 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2401 break; /* Not a tag we know about. */
c906108c
SS
2402 }
2403 return retval;
2404}
2405
2406static int
fba45db2
KB
2407remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2408 struct gdb_ext_thread_info *info)
c906108c 2409{
d01949b6 2410 struct remote_state *rs = get_remote_state ();
c906108c 2411 int result;
c906108c 2412
2e9f7625
DJ
2413 pack_threadinfo_request (rs->buf, fieldset, threadid);
2414 putpkt (rs->buf);
6d820c5c 2415 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2416
2417 if (rs->buf[0] == '\0')
2418 return 0;
2419
2e9f7625 2420 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2421 threadid, info);
c906108c
SS
2422 return result;
2423}
2424
c906108c
SS
2425/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2426
2427static char *
fba45db2
KB
2428pack_threadlist_request (char *pkt, int startflag, int threadcount,
2429 threadref *nextthread)
c906108c
SS
2430{
2431 *pkt++ = 'q'; /* info query packet */
2432 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2433 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2434 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2435 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2436 *pkt = '\0';
2437 return pkt;
2438}
2439
2440/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2441
2442static int
fba45db2
KB
2443parse_threadlist_response (char *pkt, int result_limit,
2444 threadref *original_echo, threadref *resultlist,
2445 int *doneflag)
c906108c 2446{
d01949b6 2447 struct remote_state *rs = get_remote_state ();
c906108c
SS
2448 char *limit;
2449 int count, resultcount, done;
2450
2451 resultcount = 0;
2452 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2453 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2454 /* done parse past here */
c906108c
SS
2455 pkt = unpack_byte (pkt, &count); /* count field */
2456 pkt = unpack_nibble (pkt, &done);
2457 /* The first threadid is the argument threadid. */
2458 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2459 while ((count-- > 0) && (pkt < limit))
2460 {
2461 pkt = unpack_threadid (pkt, resultlist++);
2462 if (resultcount++ >= result_limit)
2463 break;
2464 }
2465 if (doneflag)
2466 *doneflag = done;
2467 return resultcount;
2468}
2469
6dc54d91
PA
2470/* Fetch the next batch of threads from the remote. Returns -1 if the
2471 qL packet is not supported, 0 on error and 1 on success. */
2472
c906108c 2473static int
fba45db2
KB
2474remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2475 int *done, int *result_count, threadref *threadlist)
c906108c 2476{
d01949b6 2477 struct remote_state *rs = get_remote_state ();
c906108c
SS
2478 int result = 1;
2479
23860348 2480 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2481 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2482 >= get_remote_packet_size ())
ea9c271d 2483 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2484
6d820c5c
DJ
2485 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2486 putpkt (rs->buf);
2487 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2488 if (*rs->buf == '\0')
6dc54d91
PA
2489 {
2490 /* Packet not supported. */
2491 return -1;
2492 }
2493
2494 *result_count =
2495 parse_threadlist_response (rs->buf + 2, result_limit,
2496 &rs->echo_nextthread, threadlist, done);
c906108c 2497
0d031856 2498 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2499 {
23860348
MS
2500 /* FIXME: This is a good reason to drop the packet. */
2501 /* Possably, there is a duplicate response. */
c906108c
SS
2502 /* Possabilities :
2503 retransmit immediatly - race conditions
2504 retransmit after timeout - yes
2505 exit
2506 wait for packet, then exit
2507 */
8a3fe4f8 2508 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2509 return 0; /* I choose simply exiting. */
c906108c
SS
2510 }
2511 if (*result_count <= 0)
2512 {
2513 if (*done != 1)
2514 {
8a3fe4f8 2515 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2516 result = 0;
2517 }
2518 return result; /* break; */
2519 }
2520 if (*result_count > result_limit)
2521 {
2522 *result_count = 0;
8a3fe4f8 2523 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2524 return 0;
2525 }
2526 return result;
2527}
2528
6dc54d91
PA
2529/* Fetch the list of remote threads, with the qL packet, and call
2530 STEPFUNCTION for each thread found. Stops iterating and returns 1
2531 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2532 STEPFUNCTION returns false. If the packet is not supported,
2533 returns -1. */
c906108c 2534
c906108c 2535static int
fba45db2
KB
2536remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2537 int looplimit)
c906108c 2538{
0d031856 2539 struct remote_state *rs = get_remote_state ();
c906108c
SS
2540 int done, i, result_count;
2541 int startflag = 1;
2542 int result = 1;
2543 int loopcount = 0;
c906108c
SS
2544
2545 done = 0;
2546 while (!done)
2547 {
2548 if (loopcount++ > looplimit)
2549 {
2550 result = 0;
8a3fe4f8 2551 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2552 break;
2553 }
6dc54d91
PA
2554 result = remote_get_threadlist (startflag, &rs->nextthread,
2555 MAXTHREADLISTRESULTS,
2556 &done, &result_count,
2557 rs->resultthreadlist);
2558 if (result <= 0)
2559 break;
23860348 2560 /* Clear for later iterations. */
c906108c
SS
2561 startflag = 0;
2562 /* Setup to resume next batch of thread references, set nextthread. */
2563 if (result_count >= 1)
0d031856
TT
2564 copy_threadref (&rs->nextthread,
2565 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2566 i = 0;
2567 while (result_count--)
6dc54d91
PA
2568 {
2569 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2570 {
2571 result = 0;
2572 break;
2573 }
2574 }
c906108c
SS
2575 }
2576 return result;
2577}
2578
6dc54d91
PA
2579/* A thread found on the remote target. */
2580
2581typedef struct thread_item
2582{
2583 /* The thread's PTID. */
2584 ptid_t ptid;
2585
2586 /* The thread's extra info. May be NULL. */
2587 char *extra;
2588
2589 /* The core the thread was running on. -1 if not known. */
2590 int core;
2591} thread_item_t;
2592DEF_VEC_O(thread_item_t);
2593
2594/* Context passed around to the various methods listing remote
2595 threads. As new threads are found, they're added to the ITEMS
2596 vector. */
2597
2598struct threads_listing_context
2599{
2600 /* The threads found on the remote target. */
2601 VEC (thread_item_t) *items;
2602};
2603
80134cf5
PA
2604/* Discard the contents of the constructed thread listing context. */
2605
2606static void
2607clear_threads_listing_context (void *p)
2608{
2609 struct threads_listing_context *context = p;
2610 int i;
2611 struct thread_item *item;
2612
2613 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2614 xfree (item->extra);
2615
2616 VEC_free (thread_item_t, context->items);
2617}
2618
c906108c 2619static int
6dc54d91 2620remote_newthread_step (threadref *ref, void *data)
c906108c 2621{
6dc54d91
PA
2622 struct threads_listing_context *context = data;
2623 struct thread_item item;
79d7f229 2624 int pid = ptid_get_pid (inferior_ptid);
39f77062 2625
6dc54d91
PA
2626 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2627 item.core = -1;
2628 item.extra = NULL;
2629
2630 VEC_safe_push (thread_item_t, context->items, &item);
2631
c906108c
SS
2632 return 1; /* continue iterator */
2633}
2634
2635#define CRAZY_MAX_THREADS 1000
2636
39f77062
KB
2637static ptid_t
2638remote_current_thread (ptid_t oldpid)
c906108c 2639{
d01949b6 2640 struct remote_state *rs = get_remote_state ();
c906108c
SS
2641
2642 putpkt ("qC");
6d820c5c 2643 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2644 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
82f73884 2645 return read_ptid (&rs->buf[2], NULL);
c906108c
SS
2646 else
2647 return oldpid;
2648}
2649
6dc54d91 2650/* List remote threads using the deprecated qL packet. */
cce74817 2651
6dc54d91
PA
2652static int
2653remote_get_threads_with_ql (struct target_ops *ops,
2654 struct threads_listing_context *context)
c906108c 2655{
6dc54d91
PA
2656 if (remote_threadlist_iterator (remote_newthread_step, context,
2657 CRAZY_MAX_THREADS) >= 0)
2658 return 1;
2659
2660 return 0;
c906108c
SS
2661}
2662
dc146f7c
VP
2663#if defined(HAVE_LIBEXPAT)
2664
dc146f7c
VP
2665static void
2666start_thread (struct gdb_xml_parser *parser,
2667 const struct gdb_xml_element *element,
2668 void *user_data, VEC(gdb_xml_value_s) *attributes)
2669{
6dc54d91 2670 struct threads_listing_context *data = user_data;
dc146f7c
VP
2671
2672 struct thread_item item;
2673 char *id;
3d2c1d41 2674 struct gdb_xml_value *attr;
dc146f7c 2675
3d2c1d41 2676 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2677 item.ptid = read_ptid (id, NULL);
2678
3d2c1d41
PA
2679 attr = xml_find_attribute (attributes, "core");
2680 if (attr != NULL)
2681 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2682 else
2683 item.core = -1;
2684
2685 item.extra = 0;
2686
2687 VEC_safe_push (thread_item_t, data->items, &item);
2688}
2689
2690static void
2691end_thread (struct gdb_xml_parser *parser,
2692 const struct gdb_xml_element *element,
2693 void *user_data, const char *body_text)
2694{
6dc54d91 2695 struct threads_listing_context *data = user_data;
dc146f7c
VP
2696
2697 if (body_text && *body_text)
2ae2a0b7 2698 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2699}
2700
2701const struct gdb_xml_attribute thread_attributes[] = {
2702 { "id", GDB_XML_AF_NONE, NULL, NULL },
2703 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2704 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2705};
2706
2707const struct gdb_xml_element thread_children[] = {
2708 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2709};
2710
2711const struct gdb_xml_element threads_children[] = {
2712 { "thread", thread_attributes, thread_children,
2713 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2714 start_thread, end_thread },
2715 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2716};
2717
2718const struct gdb_xml_element threads_elements[] = {
2719 { "threads", NULL, threads_children,
2720 GDB_XML_EF_NONE, NULL, NULL },
2721 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2722};
2723
2724#endif
2725
6dc54d91 2726/* List remote threads using qXfer:threads:read. */
9d1f7ab2 2727
6dc54d91
PA
2728static int
2729remote_get_threads_with_qxfer (struct target_ops *ops,
2730 struct threads_listing_context *context)
0f71a2f6 2731{
dc146f7c 2732#if defined(HAVE_LIBEXPAT)
4082afcc 2733 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 2734 {
6dc54d91 2735 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 2736 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2737
6dc54d91 2738 if (xml != NULL && *xml != '\0')
dc146f7c 2739 {
6dc54d91
PA
2740 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2741 threads_elements, xml, context);
dc146f7c
VP
2742 }
2743
2744 do_cleanups (back_to);
6dc54d91 2745 return 1;
dc146f7c
VP
2746 }
2747#endif
2748
6dc54d91
PA
2749 return 0;
2750}
2751
2752/* List remote threads using qfThreadInfo/qsThreadInfo. */
2753
2754static int
2755remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2756 struct threads_listing_context *context)
2757{
2758 struct remote_state *rs = get_remote_state ();
2759
b80fafe3 2760 if (rs->use_threadinfo_query)
9d1f7ab2 2761 {
6dc54d91
PA
2762 char *bufp;
2763
9d1f7ab2 2764 putpkt ("qfThreadInfo");
6d820c5c 2765 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2766 bufp = rs->buf;
9d1f7ab2 2767 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2768 {
9d1f7ab2
MS
2769 while (*bufp++ == 'm') /* reply contains one or more TID */
2770 {
2771 do
2772 {
6dc54d91
PA
2773 struct thread_item item;
2774
2775 item.ptid = read_ptid (bufp, &bufp);
2776 item.core = -1;
2777 item.extra = NULL;
2778
2779 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
2780 }
2781 while (*bufp++ == ','); /* comma-separated list */
2782 putpkt ("qsThreadInfo");
6d820c5c 2783 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 2784 bufp = rs->buf;
9d1f7ab2 2785 }
6dc54d91
PA
2786 return 1;
2787 }
2788 else
2789 {
2790 /* Packet not recognized. */
2791 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
2792 }
2793 }
2794
6dc54d91
PA
2795 return 0;
2796}
2797
e8032dde 2798/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
2799 targets. */
2800
2801static void
e8032dde 2802remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
2803{
2804 struct remote_state *rs = get_remote_state ();
2805 struct threads_listing_context context;
2806 struct cleanup *old_chain;
ab970af1 2807 int got_list = 0;
e8032dde 2808
6dc54d91
PA
2809 context.items = NULL;
2810 old_chain = make_cleanup (clear_threads_listing_context, &context);
2811
2812 /* We have a few different mechanisms to fetch the thread list. Try
2813 them all, starting with the most preferred one first, falling
2814 back to older methods. */
2815 if (remote_get_threads_with_qxfer (ops, &context)
2816 || remote_get_threads_with_qthreadinfo (ops, &context)
2817 || remote_get_threads_with_ql (ops, &context))
2818 {
2819 int i;
2820 struct thread_item *item;
ab970af1
PA
2821 struct thread_info *tp, *tmp;
2822
2823 got_list = 1;
2824
7d1a114c
PA
2825 if (VEC_empty (thread_item_t, context.items)
2826 && remote_thread_always_alive (ops, inferior_ptid))
2827 {
2828 /* Some targets don't really support threads, but still
2829 reply an (empty) thread list in response to the thread
2830 listing packets, instead of replying "packet not
2831 supported". Exit early so we don't delete the main
2832 thread. */
2833 do_cleanups (old_chain);
2834 return;
2835 }
2836
ab970af1
PA
2837 /* CONTEXT now holds the current thread list on the remote
2838 target end. Delete GDB-side threads no longer found on the
2839 target. */
2840 ALL_NON_EXITED_THREADS_SAFE (tp, tmp)
2841 {
2842 for (i = 0;
2843 VEC_iterate (thread_item_t, context.items, i, item);
2844 ++i)
2845 {
2846 if (ptid_equal (item->ptid, tp->ptid))
2847 break;
2848 }
2849
2850 if (i == VEC_length (thread_item_t, context.items))
2851 {
2852 /* Not found. */
2853 delete_thread (tp->ptid);
2854 }
2855 }
74531fed 2856
ab970af1 2857 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
2858 for (i = 0;
2859 VEC_iterate (thread_item_t, context.items, i, item);
2860 ++i)
2861 {
2862 if (!ptid_equal (item->ptid, null_ptid))
2863 {
2864 struct private_thread_info *info;
2865 /* In non-stop mode, we assume new found threads are
2866 running until proven otherwise with a stop reply. In
2867 all-stop, we can only get here if all threads are
2868 stopped. */
2869 int running = non_stop ? 1 : 0;
2870
2871 remote_notice_new_inferior (item->ptid, running);
2872
2873 info = demand_private_info (item->ptid);
2874 info->core = item->core;
2875 info->extra = item->extra;
2876 item->extra = NULL;
2877 }
2878 }
2879 }
2880
ab970af1
PA
2881 if (!got_list)
2882 {
2883 /* If no thread listing method is supported, then query whether
2884 each known thread is alive, one by one, with the T packet.
2885 If the target doesn't support threads at all, then this is a
2886 no-op. See remote_thread_alive. */
2887 prune_threads ();
2888 }
2889
6dc54d91 2890 do_cleanups (old_chain);
9d1f7ab2
MS
2891}
2892
802188a7 2893/*
9d1f7ab2
MS
2894 * Collect a descriptive string about the given thread.
2895 * The target may say anything it wants to about the thread
2896 * (typically info about its blocked / runnable state, name, etc.).
2897 * This string will appear in the info threads display.
802188a7 2898 *
9d1f7ab2
MS
2899 * Optional: targets are not required to implement this function.
2900 */
2901
2902static char *
c15906d8 2903remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 2904{
d01949b6 2905 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
2906 int result;
2907 int set;
2908 threadref id;
2909 struct gdb_ext_thread_info threadinfo;
23860348 2910 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
2911 int n = 0; /* position in display_buf */
2912
5d93a237 2913 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 2914 internal_error (__FILE__, __LINE__,
e2e0b3e5 2915 _("remote_threads_extra_info"));
9d1f7ab2 2916
60e569b9 2917 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 2918 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
2919 /* This is the main thread which was added by GDB. The remote
2920 server doesn't know about it. */
2921 return NULL;
2922
4082afcc 2923 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
2924 {
2925 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 2926
fe978cb0
PA
2927 if (info && info->priv)
2928 return info->priv->extra;
dc146f7c
VP
2929 else
2930 return NULL;
2931 }
2932
b80fafe3 2933 if (rs->use_threadextra_query)
9d1f7ab2 2934 {
82f73884
PA
2935 char *b = rs->buf;
2936 char *endb = rs->buf + get_remote_packet_size ();
2937
2938 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2939 b += strlen (b);
2940 write_ptid (b, endb, tp->ptid);
2941
2e9f7625 2942 putpkt (rs->buf);
6d820c5c 2943 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2944 if (rs->buf[0] != 0)
9d1f7ab2 2945 {
2e9f7625
DJ
2946 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2947 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 2948 display_buf [result] = '\0';
9d1f7ab2
MS
2949 return display_buf;
2950 }
0f71a2f6 2951 }
9d1f7ab2
MS
2952
2953 /* If the above query fails, fall back to the old method. */
b80fafe3 2954 rs->use_threadextra_query = 0;
9d1f7ab2
MS
2955 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2956 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 2957 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
2958 if (remote_get_threadinfo (&id, set, &threadinfo))
2959 if (threadinfo.active)
0f71a2f6 2960 {
9d1f7ab2 2961 if (*threadinfo.shortname)
2bc416ba 2962 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 2963 " Name: %s,", threadinfo.shortname);
9d1f7ab2 2964 if (*threadinfo.display)
2bc416ba 2965 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2966 " State: %s,", threadinfo.display);
9d1f7ab2 2967 if (*threadinfo.more_display)
2bc416ba 2968 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2969 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
2970
2971 if (n > 0)
c5aa993b 2972 {
23860348 2973 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
2974 if (',' == display_buf[n-1])
2975 display_buf[n-1] = ' ';
2976 return display_buf;
c5aa993b 2977 }
0f71a2f6 2978 }
9d1f7ab2 2979 return NULL;
0f71a2f6 2980}
c906108c 2981\f
c5aa993b 2982
0fb4aa4b 2983static int
61fc905d 2984remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
2985 struct static_tracepoint_marker *marker)
2986{
2987 struct remote_state *rs = get_remote_state ();
2988 char *p = rs->buf;
2989
bba74b36 2990 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
2991 p += strlen (p);
2992 p += hexnumstr (p, addr);
2993 putpkt (rs->buf);
2994 getpkt (&rs->buf, &rs->buf_size, 0);
2995 p = rs->buf;
2996
2997 if (*p == 'E')
2998 error (_("Remote failure reply: %s"), p);
2999
3000 if (*p++ == 'm')
3001 {
3002 parse_static_tracepoint_marker_definition (p, &p, marker);
3003 return 1;
3004 }
3005
3006 return 0;
3007}
3008
0fb4aa4b 3009static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3010remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3011 const char *strid)
0fb4aa4b
PA
3012{
3013 struct remote_state *rs = get_remote_state ();
3014 VEC(static_tracepoint_marker_p) *markers = NULL;
3015 struct static_tracepoint_marker *marker = NULL;
3016 struct cleanup *old_chain;
3017 char *p;
3018
3019 /* Ask for a first packet of static tracepoint marker
3020 definition. */
3021 putpkt ("qTfSTM");
3022 getpkt (&rs->buf, &rs->buf_size, 0);
3023 p = rs->buf;
3024 if (*p == 'E')
3025 error (_("Remote failure reply: %s"), p);
3026
3027 old_chain = make_cleanup (free_current_marker, &marker);
3028
3029 while (*p++ == 'm')
3030 {
3031 if (marker == NULL)
3032 marker = XCNEW (struct static_tracepoint_marker);
3033
3034 do
3035 {
3036 parse_static_tracepoint_marker_definition (p, &p, marker);
3037
3038 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3039 {
3040 VEC_safe_push (static_tracepoint_marker_p,
3041 markers, marker);
3042 marker = NULL;
3043 }
3044 else
3045 {
3046 release_static_tracepoint_marker (marker);
3047 memset (marker, 0, sizeof (*marker));
3048 }
3049 }
3050 while (*p++ == ','); /* comma-separated list */
3051 /* Ask for another packet of static tracepoint definition. */
3052 putpkt ("qTsSTM");
3053 getpkt (&rs->buf, &rs->buf_size, 0);
3054 p = rs->buf;
3055 }
3056
3057 do_cleanups (old_chain);
3058 return markers;
3059}
3060
3061\f
10760264
JB
3062/* Implement the to_get_ada_task_ptid function for the remote targets. */
3063
3064static ptid_t
1e6b91a4 3065remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3066{
ba348170 3067 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3068}
3069\f
3070
24b06219 3071/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3072
3073static void
fba45db2 3074extended_remote_restart (void)
c906108c 3075{
d01949b6 3076 struct remote_state *rs = get_remote_state ();
c906108c
SS
3077
3078 /* Send the restart command; for reasons I don't understand the
3079 remote side really expects a number after the "R". */
ea9c271d 3080 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3081 putpkt (rs->buf);
c906108c 3082
ad9a8f3f 3083 remote_fileio_reset ();
c906108c
SS
3084}
3085\f
3086/* Clean up connection to a remote debugger. */
3087
c906108c 3088static void
de90e03d 3089remote_close (struct target_ops *self)
c906108c 3090{
5d93a237
TT
3091 struct remote_state *rs = get_remote_state ();
3092
3093 if (rs->remote_desc == NULL)
d3fd5342
PA
3094 return; /* already closed */
3095
3096 /* Make sure we leave stdin registered in the event loop, and we
3097 don't leave the async SIGINT signal handler installed. */
e3594fd1 3098 remote_terminal_ours (self);
ce5ce7ed 3099
5d93a237
TT
3100 serial_close (rs->remote_desc);
3101 rs->remote_desc = NULL;
ce5ce7ed
PA
3102
3103 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3104 of all the inferiors and their threads we were controlling.
3105 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3106 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3107 inferior_ptid = null_ptid;
f67fd822 3108 discard_all_inferiors ();
ce5ce7ed 3109
f48ff2a7
YQ
3110 /* We are closing the remote target, so we should discard
3111 everything of this target. */
bcc75809 3112 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3113
3114 if (remote_async_inferior_event_token)
3115 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3116
5965e028 3117 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3118
3119 trace_reset_local_state ();
c906108c
SS
3120}
3121
23860348 3122/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3123
3124static void
fba45db2 3125get_offsets (void)
c906108c 3126{
d01949b6 3127 struct remote_state *rs = get_remote_state ();
2e9f7625 3128 char *buf;
085dd6e6 3129 char *ptr;
31d99776
DJ
3130 int lose, num_segments = 0, do_sections, do_segments;
3131 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3132 struct section_offsets *offs;
31d99776
DJ
3133 struct symfile_segment_data *data;
3134
3135 if (symfile_objfile == NULL)
3136 return;
c906108c
SS
3137
3138 putpkt ("qOffsets");
6d820c5c 3139 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3140 buf = rs->buf;
c906108c
SS
3141
3142 if (buf[0] == '\000')
3143 return; /* Return silently. Stub doesn't support
23860348 3144 this command. */
c906108c
SS
3145 if (buf[0] == 'E')
3146 {
8a3fe4f8 3147 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3148 return;
3149 }
3150
3151 /* Pick up each field in turn. This used to be done with scanf, but
3152 scanf will make trouble if CORE_ADDR size doesn't match
3153 conversion directives correctly. The following code will work
3154 with any size of CORE_ADDR. */
3155 text_addr = data_addr = bss_addr = 0;
3156 ptr = buf;
3157 lose = 0;
3158
61012eef 3159 if (startswith (ptr, "Text="))
c906108c
SS
3160 {
3161 ptr += 5;
3162 /* Don't use strtol, could lose on big values. */
3163 while (*ptr && *ptr != ';')
3164 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3165
61012eef 3166 if (startswith (ptr, ";Data="))
31d99776
DJ
3167 {
3168 ptr += 6;
3169 while (*ptr && *ptr != ';')
3170 data_addr = (data_addr << 4) + fromhex (*ptr++);
3171 }
3172 else
3173 lose = 1;
3174
61012eef 3175 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3176 {
3177 ptr += 5;
3178 while (*ptr && *ptr != ';')
3179 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3180
31d99776
DJ
3181 if (bss_addr != data_addr)
3182 warning (_("Target reported unsupported offsets: %s"), buf);
3183 }
3184 else
3185 lose = 1;
3186 }
61012eef 3187 else if (startswith (ptr, "TextSeg="))
c906108c 3188 {
31d99776
DJ
3189 ptr += 8;
3190 /* Don't use strtol, could lose on big values. */
c906108c 3191 while (*ptr && *ptr != ';')
31d99776
DJ
3192 text_addr = (text_addr << 4) + fromhex (*ptr++);
3193 num_segments = 1;
3194
61012eef 3195 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3196 {
3197 ptr += 9;
3198 while (*ptr && *ptr != ';')
3199 data_addr = (data_addr << 4) + fromhex (*ptr++);
3200 num_segments++;
3201 }
c906108c
SS
3202 }
3203 else
3204 lose = 1;
3205
3206 if (lose)
8a3fe4f8 3207 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3208 else if (*ptr != '\0')
3209 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3210
802188a7 3211 offs = ((struct section_offsets *)
a39a16c4 3212 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3213 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3214 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3215
31d99776
DJ
3216 data = get_symfile_segment_data (symfile_objfile->obfd);
3217 do_segments = (data != NULL);
3218 do_sections = num_segments == 0;
c906108c 3219
28c32713 3220 if (num_segments > 0)
31d99776 3221 {
31d99776
DJ
3222 segments[0] = text_addr;
3223 segments[1] = data_addr;
3224 }
28c32713
JB
3225 /* If we have two segments, we can still try to relocate everything
3226 by assuming that the .text and .data offsets apply to the whole
3227 text and data segments. Convert the offsets given in the packet
3228 to base addresses for symfile_map_offsets_to_segments. */
3229 else if (data && data->num_segments == 2)
3230 {
3231 segments[0] = data->segment_bases[0] + text_addr;
3232 segments[1] = data->segment_bases[1] + data_addr;
3233 num_segments = 2;
3234 }
8d385431
DJ
3235 /* If the object file has only one segment, assume that it is text
3236 rather than data; main programs with no writable data are rare,
3237 but programs with no code are useless. Of course the code might
3238 have ended up in the data segment... to detect that we would need
3239 the permissions here. */
3240 else if (data && data->num_segments == 1)
3241 {
3242 segments[0] = data->segment_bases[0] + text_addr;
3243 num_segments = 1;
3244 }
28c32713
JB
3245 /* There's no way to relocate by segment. */
3246 else
3247 do_segments = 0;
31d99776
DJ
3248
3249 if (do_segments)
3250 {
3251 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3252 offs, num_segments, segments);
3253
3254 if (ret == 0 && !do_sections)
3e43a32a
MS
3255 error (_("Can not handle qOffsets TextSeg "
3256 "response with this symbol file"));
31d99776
DJ
3257
3258 if (ret > 0)
3259 do_sections = 0;
3260 }
c906108c 3261
9ef895d6
DJ
3262 if (data)
3263 free_symfile_segment_data (data);
31d99776
DJ
3264
3265 if (do_sections)
3266 {
3267 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3268
3e43a32a
MS
3269 /* This is a temporary kludge to force data and bss to use the
3270 same offsets because that's what nlmconv does now. The real
3271 solution requires changes to the stub and remote.c that I
3272 don't have time to do right now. */
31d99776
DJ
3273
3274 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3275 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3276 }
c906108c
SS
3277
3278 objfile_relocate (symfile_objfile, offs);
3279}
3280
74531fed
PA
3281/* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3282 threads we know are stopped already. This is used during the
3283 initial remote connection in non-stop mode --- threads that are
3284 reported as already being stopped are left stopped. */
3285
3286static int
3287set_stop_requested_callback (struct thread_info *thread, void *data)
3288{
3289 /* If we have a stop reply for this thread, it must be stopped. */
3290 if (peek_stop_reply (thread->ptid))
3291 set_stop_requested (thread->ptid, 1);
3292
3293 return 0;
3294}
3295
9a7071a8
JB
3296/* Send interrupt_sequence to remote target. */
3297static void
eeae04df 3298send_interrupt_sequence (void)
9a7071a8 3299{
5d93a237
TT
3300 struct remote_state *rs = get_remote_state ();
3301
9a7071a8 3302 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3303 remote_serial_write ("\x03", 1);
9a7071a8 3304 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3305 serial_send_break (rs->remote_desc);
9a7071a8
JB
3306 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3307 {
5d93a237 3308 serial_send_break (rs->remote_desc);
c33e31fd 3309 remote_serial_write ("g", 1);
9a7071a8
JB
3310 }
3311 else
3312 internal_error (__FILE__, __LINE__,
3313 _("Invalid value for interrupt_sequence_mode: %s."),
3314 interrupt_sequence_mode);
3315}
3316
3405876a
PA
3317
3318/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3319 and extract the PTID. Returns NULL_PTID if not found. */
3320
3321static ptid_t
3322stop_reply_extract_thread (char *stop_reply)
3323{
3324 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3325 {
3326 char *p;
3327
3328 /* Txx r:val ; r:val (...) */
3329 p = &stop_reply[3];
3330
3331 /* Look for "register" named "thread". */
3332 while (*p != '\0')
3333 {
3334 char *p1;
3335
3336 p1 = strchr (p, ':');
3337 if (p1 == NULL)
3338 return null_ptid;
3339
3340 if (strncmp (p, "thread", p1 - p) == 0)
3341 return read_ptid (++p1, &p);
3342
3343 p1 = strchr (p, ';');
3344 if (p1 == NULL)
3345 return null_ptid;
3346 p1++;
3347
3348 p = p1;
3349 }
3350 }
3351
3352 return null_ptid;
3353}
3354
b7ea362b
PA
3355/* Determine the remote side's current thread. If we have a stop
3356 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3357 "thread" register we can extract the current thread from. If not,
3358 ask the remote which is the current thread with qC. The former
3359 method avoids a roundtrip. */
3360
3361static ptid_t
3362get_current_thread (char *wait_status)
3363{
3364 ptid_t ptid;
3365
3366 /* Note we don't use remote_parse_stop_reply as that makes use of
3367 the target architecture, which we haven't yet fully determined at
3368 this point. */
3369 if (wait_status != NULL)
3370 ptid = stop_reply_extract_thread (wait_status);
3371 if (ptid_equal (ptid, null_ptid))
3372 ptid = remote_current_thread (inferior_ptid);
3373
3374 return ptid;
3375}
3376
49c62f2e
PA
3377/* Query the remote target for which is the current thread/process,
3378 add it to our tables, and update INFERIOR_PTID. The caller is
3379 responsible for setting the state such that the remote end is ready
3405876a
PA
3380 to return the current thread.
3381
3382 This function is called after handling the '?' or 'vRun' packets,
3383 whose response is a stop reply from which we can also try
3384 extracting the thread. If the target doesn't support the explicit
3385 qC query, we infer the current thread from that stop reply, passed
3386 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3387
3388static void
3405876a 3389add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3390{
3391 struct remote_state *rs = get_remote_state ();
3392 int fake_pid_p = 0;
3405876a 3393 ptid_t ptid = null_ptid;
49c62f2e
PA
3394
3395 inferior_ptid = null_ptid;
3396
b7ea362b
PA
3397 /* Now, if we have thread information, update inferior_ptid. */
3398 ptid = get_current_thread (wait_status);
3405876a 3399
49c62f2e
PA
3400 if (!ptid_equal (ptid, null_ptid))
3401 {
3402 if (!remote_multi_process_p (rs))
3403 fake_pid_p = 1;
3404
3405 inferior_ptid = ptid;
3406 }
3407 else
3408 {
3409 /* Without this, some commands which require an active target
3410 (such as kill) won't work. This variable serves (at least)
3411 double duty as both the pid of the target process (if it has
3412 such), and as a flag indicating that a target is active. */
3413 inferior_ptid = magic_null_ptid;
3414 fake_pid_p = 1;
3415 }
3416
3417 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1);
3418
3419 /* Add the main thread. */
3420 add_thread_silent (inferior_ptid);
3421}
3422
9cbc821d 3423static void
04bd08de 3424remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3425{
c8d104ad
PA
3426 struct remote_state *rs = get_remote_state ();
3427 struct packet_config *noack_config;
2d717e4f 3428 char *wait_status = NULL;
8621d6a9 3429
23860348 3430 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3431 QUIT;
c906108c 3432
9a7071a8
JB
3433 if (interrupt_on_connect)
3434 send_interrupt_sequence ();
3435
57e12211 3436 /* Ack any packet which the remote side has already sent. */
5d93a237 3437 serial_write (rs->remote_desc, "+", 1);
57e12211 3438
1e51243a
PA
3439 /* Signal other parts that we're going through the initial setup,
3440 and so things may not be stable yet. */
3441 rs->starting_up = 1;
3442
c8d104ad
PA
3443 /* The first packet we send to the target is the optional "supported
3444 packets" request. If the target can answer this, it will tell us
3445 which later probes to skip. */
3446 remote_query_supported ();
3447
d914c394 3448 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3449 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3450 remote_set_permissions (target);
d914c394 3451
c8d104ad
PA
3452 /* Next, we possibly activate noack mode.
3453
3454 If the QStartNoAckMode packet configuration is set to AUTO,
3455 enable noack mode if the stub reported a wish for it with
3456 qSupported.
3457
3458 If set to TRUE, then enable noack mode even if the stub didn't
3459 report it in qSupported. If the stub doesn't reply OK, the
3460 session ends with an error.
3461
3462 If FALSE, then don't activate noack mode, regardless of what the
3463 stub claimed should be the default with qSupported. */
3464
3465 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3466 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3467 {
3468 putpkt ("QStartNoAckMode");
3469 getpkt (&rs->buf, &rs->buf_size, 0);
3470 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3471 rs->noack_mode = 1;
3472 }
3473
04bd08de 3474 if (extended_p)
5fe04517
PA
3475 {
3476 /* Tell the remote that we are using the extended protocol. */
3477 putpkt ("!");
3478 getpkt (&rs->buf, &rs->buf_size, 0);
3479 }
3480
9b224c5e
PA
3481 /* Let the target know which signals it is allowed to pass down to
3482 the program. */
3483 update_signals_program_target ();
3484
d962ef82
DJ
3485 /* Next, if the target can specify a description, read it. We do
3486 this before anything involving memory or registers. */
3487 target_find_description ();
3488
6c95b8df
PA
3489 /* Next, now that we know something about the target, update the
3490 address spaces in the program spaces. */
3491 update_address_spaces ();
3492
50c71eaf
PA
3493 /* On OSs where the list of libraries is global to all
3494 processes, we fetch them early. */
f5656ead 3495 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3496 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3497
74531fed
PA
3498 if (non_stop)
3499 {
4082afcc 3500 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3501 error (_("Non-stop mode requested, but remote "
3502 "does not support non-stop"));
74531fed
PA
3503
3504 putpkt ("QNonStop:1");
3505 getpkt (&rs->buf, &rs->buf_size, 0);
3506
3507 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3508 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3509
3510 /* Find about threads and processes the stub is already
3511 controlling. We default to adding them in the running state.
3512 The '?' query below will then tell us about which threads are
3513 stopped. */
e8032dde 3514 remote_update_thread_list (target);
74531fed 3515 }
4082afcc 3516 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3517 {
3518 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3519 Request it explicitly. */
74531fed
PA
3520 putpkt ("QNonStop:0");
3521 getpkt (&rs->buf, &rs->buf_size, 0);
3522
3523 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3524 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3525 }
3526
a0743c90
YQ
3527 /* Upload TSVs regardless of whether the target is running or not. The
3528 remote stub, such as GDBserver, may have some predefined or builtin
3529 TSVs, even if the target is not running. */
8bd200f1 3530 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
3531 {
3532 struct uploaded_tsv *uploaded_tsvs = NULL;
3533
181e3713 3534 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
3535 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3536 }
3537
2d717e4f
DJ
3538 /* Check whether the target is running now. */
3539 putpkt ("?");
3540 getpkt (&rs->buf, &rs->buf_size, 0);
3541
74531fed 3542 if (!non_stop)
2d717e4f 3543 {
e714e1bf
UW
3544 ptid_t ptid;
3545 int fake_pid_p = 0;
3546 struct inferior *inf;
3547
74531fed 3548 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3549 {
04bd08de 3550 if (!extended_p)
74531fed 3551 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3552
3553 /* We're connected, but not running. Drop out before we
3554 call start_remote. */
e278ad5b 3555 rs->starting_up = 0;
c35b1492 3556 return;
2d717e4f
DJ
3557 }
3558 else
74531fed 3559 {
74531fed
PA
3560 /* Save the reply for later. */
3561 wait_status = alloca (strlen (rs->buf) + 1);
3562 strcpy (wait_status, rs->buf);
3563 }
3564
b7ea362b 3565 /* Fetch thread list. */
e8032dde 3566 target_update_thread_list ();
b7ea362b 3567
74531fed
PA
3568 /* Let the stub know that we want it to return the thread. */
3569 set_continue_thread (minus_one_ptid);
3570
b7ea362b
PA
3571 if (thread_count () == 0)
3572 {
3573 /* Target has no concept of threads at all. GDB treats
3574 non-threaded target as single-threaded; add a main
3575 thread. */
3576 add_current_inferior_and_thread (wait_status);
3577 }
3578 else
3579 {
3580 /* We have thread information; select the thread the target
3581 says should be current. If we're reconnecting to a
3582 multi-threaded program, this will ideally be the thread
3583 that last reported an event before GDB disconnected. */
3584 inferior_ptid = get_current_thread (wait_status);
3585 if (ptid_equal (inferior_ptid, null_ptid))
3586 {
3587 /* Odd... The target was able to list threads, but not
3588 tell us which thread was current (no "thread"
3589 register in T stop reply?). Just pick the first
3590 thread in the thread list then. */
3591 inferior_ptid = thread_list->ptid;
3592 }
3593 }
74531fed 3594
6e586cc5
YQ
3595 /* init_wait_for_inferior should be called before get_offsets in order
3596 to manage `inserted' flag in bp loc in a correct state.
3597 breakpoint_init_inferior, called from init_wait_for_inferior, set
3598 `inserted' flag to 0, while before breakpoint_re_set, called from
3599 start_remote, set `inserted' flag to 1. In the initialization of
3600 inferior, breakpoint_init_inferior should be called first, and then
3601 breakpoint_re_set can be called. If this order is broken, state of
3602 `inserted' flag is wrong, and cause some problems on breakpoint
3603 manipulation. */
3604 init_wait_for_inferior ();
3605
74531fed
PA
3606 get_offsets (); /* Get text, data & bss offsets. */
3607
d962ef82
DJ
3608 /* If we could not find a description using qXfer, and we know
3609 how to do it some other way, try again. This is not
3610 supported for non-stop; it could be, but it is tricky if
3611 there are no stopped threads when we connect. */
04bd08de 3612 if (remote_read_description_p (target)
f5656ead 3613 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
3614 {
3615 target_clear_description ();
3616 target_find_description ();
3617 }
3618
74531fed
PA
3619 /* Use the previously fetched status. */
3620 gdb_assert (wait_status != NULL);
3621 strcpy (rs->buf, wait_status);
3622 rs->cached_wait_status = 1;
3623
3624 immediate_quit--;
04bd08de 3625 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3626 }
3627 else
3628 {
68c97600
PA
3629 /* Clear WFI global state. Do this before finding about new
3630 threads and inferiors, and setting the current inferior.
3631 Otherwise we would clear the proceed status of the current
3632 inferior when we want its stop_soon state to be preserved
3633 (see notice_new_inferior). */
3634 init_wait_for_inferior ();
3635
74531fed
PA
3636 /* In non-stop, we will either get an "OK", meaning that there
3637 are no stopped threads at this time; or, a regular stop
3638 reply. In the latter case, there may be more than one thread
3639 stopped --- we pull them all out using the vStopped
3640 mechanism. */
3641 if (strcmp (rs->buf, "OK") != 0)
3642 {
722247f1 3643 struct notif_client *notif = &notif_client_stop;
2d717e4f 3644
722247f1
YQ
3645 /* remote_notif_get_pending_replies acks this one, and gets
3646 the rest out. */
f48ff2a7 3647 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
3648 = remote_notif_parse (notif, rs->buf);
3649 remote_notif_get_pending_events (notif);
c906108c 3650
74531fed
PA
3651 /* Make sure that threads that were stopped remain
3652 stopped. */
3653 iterate_over_threads (set_stop_requested_callback, NULL);
3654 }
2d717e4f 3655
74531fed 3656 if (target_can_async_p ())
6a3753b3 3657 target_async (1);
c906108c 3658
74531fed
PA
3659 if (thread_count () == 0)
3660 {
04bd08de 3661 if (!extended_p)
74531fed 3662 error (_("The target is not running (try extended-remote?)"));
82f73884 3663
c35b1492
PA
3664 /* We're connected, but not running. Drop out before we
3665 call start_remote. */
e278ad5b 3666 rs->starting_up = 0;
c35b1492
PA
3667 return;
3668 }
74531fed
PA
3669
3670 /* Let the stub know that we want it to return the thread. */
c0a2216e 3671
74531fed
PA
3672 /* Force the stub to choose a thread. */
3673 set_general_thread (null_ptid);
c906108c 3674
74531fed
PA
3675 /* Query it. */
3676 inferior_ptid = remote_current_thread (minus_one_ptid);
3677 if (ptid_equal (inferior_ptid, minus_one_ptid))
3678 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3679
74531fed
PA
3680 get_offsets (); /* Get text, data & bss offsets. */
3681
3682 /* In non-stop mode, any cached wait status will be stored in
3683 the stop reply queue. */
3684 gdb_assert (wait_status == NULL);
f0223081 3685
2455069d 3686 /* Report all signals during attach/startup. */
94bedb42 3687 remote_pass_signals (target, 0, NULL);
74531fed 3688 }
c8d104ad 3689
c8d104ad
PA
3690 /* If we connected to a live target, do some additional setup. */
3691 if (target_has_execution)
3692 {
f4ccffad 3693 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 3694 remote_check_symbols ();
c8d104ad 3695 }
50c71eaf 3696
d5551862
SS
3697 /* Possibly the target has been engaged in a trace run started
3698 previously; find out where things are at. */
8bd200f1 3699 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 3700 {
00bf0b85 3701 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 3702
00bf0b85
SS
3703 if (current_trace_status ()->running)
3704 printf_filtered (_("Trace is already running on the target.\n"));
3705
ab6617cc 3706 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
3707
3708 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3709 }
3710
1e51243a
PA
3711 /* The thread and inferior lists are now synchronized with the
3712 target, our symbols have been relocated, and we're merged the
3713 target's tracepoints with ours. We're done with basic start
3714 up. */
3715 rs->starting_up = 0;
3716
a25a5a45
PA
3717 /* Maybe breakpoints are global and need to be inserted now. */
3718 if (breakpoints_should_be_inserted_now ())
50c71eaf 3719 insert_breakpoints ();
c906108c
SS
3720}
3721
3722/* Open a connection to a remote debugger.
3723 NAME is the filename used for communication. */
3724
3725static void
014f9477 3726remote_open (const char *name, int from_tty)
c906108c 3727{
75c99385 3728 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3729}
3730
c906108c
SS
3731/* Open a connection to a remote debugger using the extended
3732 remote gdb protocol. NAME is the filename used for communication. */
3733
3734static void
014f9477 3735extended_remote_open (const char *name, int from_tty)
c906108c 3736{
75c99385 3737 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3738}
3739
ca4f7f8b
PA
3740/* Reset all packets back to "unknown support". Called when opening a
3741 new connection to a remote target. */
c906108c 3742
d471ea57 3743static void
ca4f7f8b 3744reset_all_packet_configs_support (void)
d471ea57
AC
3745{
3746 int i;
a744cf53 3747
444abaca 3748 for (i = 0; i < PACKET_MAX; i++)
4082afcc 3749 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
3750}
3751
ca4f7f8b
PA
3752/* Initialize all packet configs. */
3753
3754static void
3755init_all_packet_configs (void)
3756{
3757 int i;
3758
3759 for (i = 0; i < PACKET_MAX; i++)
3760 {
3761 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3762 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3763 }
3764}
3765
23860348 3766/* Symbol look-up. */
dc8acb97
MS
3767
3768static void
36d25514 3769remote_check_symbols (void)
dc8acb97 3770{
d01949b6 3771 struct remote_state *rs = get_remote_state ();
dc8acb97 3772 char *msg, *reply, *tmp;
3b7344d5 3773 struct bound_minimal_symbol sym;
dc8acb97
MS
3774 int end;
3775
63154eca
PA
3776 /* The remote side has no concept of inferiors that aren't running
3777 yet, it only knows about running processes. If we're connected
3778 but our current inferior is not running, we should not invite the
3779 remote target to request symbol lookups related to its
3780 (unrelated) current process. */
3781 if (!target_has_execution)
3782 return;
3783
4082afcc 3784 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
3785 return;
3786
63154eca
PA
3787 /* Make sure the remote is pointing at the right process. Note
3788 there's no way to select "no process". */
3c9c4b83
PA
3789 set_general_process ();
3790
6d820c5c
DJ
3791 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3792 because we need both at the same time. */
ea9c271d 3793 msg = alloca (get_remote_packet_size ());
6d820c5c 3794
23860348 3795 /* Invite target to request symbol lookups. */
dc8acb97
MS
3796
3797 putpkt ("qSymbol::");
6d820c5c
DJ
3798 getpkt (&rs->buf, &rs->buf_size, 0);
3799 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 3800 reply = rs->buf;
dc8acb97 3801
61012eef 3802 while (startswith (reply, "qSymbol:"))
dc8acb97 3803 {
77e371c0
TT
3804 struct bound_minimal_symbol sym;
3805
dc8acb97 3806 tmp = &reply[8];
cfd77fa1 3807 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
3808 msg[end] = '\0';
3809 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 3810 if (sym.minsym == NULL)
ea9c271d 3811 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 3812 else
2bbe3cc1 3813 {
f5656ead 3814 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 3815 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
3816
3817 /* If this is a function address, return the start of code
3818 instead of any data function descriptor. */
f5656ead 3819 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
3820 sym_addr,
3821 &current_target);
3822
3823 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 3824 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
3825 }
3826
dc8acb97 3827 putpkt (msg);
6d820c5c 3828 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3829 reply = rs->buf;
dc8acb97
MS
3830 }
3831}
3832
9db8d71f 3833static struct serial *
baa336ce 3834remote_serial_open (const char *name)
9db8d71f
DJ
3835{
3836 static int udp_warning = 0;
3837
3838 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3839 of in ser-tcp.c, because it is the remote protocol assuming that the
3840 serial connection is reliable and not the serial connection promising
3841 to be. */
61012eef 3842 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 3843 {
3e43a32a
MS
3844 warning (_("The remote protocol may be unreliable over UDP.\n"
3845 "Some events may be lost, rendering further debugging "
3846 "impossible."));
9db8d71f
DJ
3847 udp_warning = 1;
3848 }
3849
3850 return serial_open (name);
3851}
3852
d914c394
SS
3853/* Inform the target of our permission settings. The permission flags
3854 work without this, but if the target knows the settings, it can do
3855 a couple things. First, it can add its own check, to catch cases
3856 that somehow manage to get by the permissions checks in target
3857 methods. Second, if the target is wired to disallow particular
3858 settings (for instance, a system in the field that is not set up to
3859 be able to stop at a breakpoint), it can object to any unavailable
3860 permissions. */
3861
3862void
c378d69d 3863remote_set_permissions (struct target_ops *self)
d914c394
SS
3864{
3865 struct remote_state *rs = get_remote_state ();
3866
bba74b36
YQ
3867 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3868 "WriteReg:%x;WriteMem:%x;"
3869 "InsertBreak:%x;InsertTrace:%x;"
3870 "InsertFastTrace:%x;Stop:%x",
3871 may_write_registers, may_write_memory,
3872 may_insert_breakpoints, may_insert_tracepoints,
3873 may_insert_fast_tracepoints, may_stop);
d914c394
SS
3874 putpkt (rs->buf);
3875 getpkt (&rs->buf, &rs->buf_size, 0);
3876
3877 /* If the target didn't like the packet, warn the user. Do not try
3878 to undo the user's settings, that would just be maddening. */
3879 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 3880 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
3881}
3882
be2a5f71
DJ
3883/* This type describes each known response to the qSupported
3884 packet. */
3885struct protocol_feature
3886{
3887 /* The name of this protocol feature. */
3888 const char *name;
3889
3890 /* The default for this protocol feature. */
3891 enum packet_support default_support;
3892
3893 /* The function to call when this feature is reported, or after
3894 qSupported processing if the feature is not supported.
3895 The first argument points to this structure. The second
3896 argument indicates whether the packet requested support be
3897 enabled, disabled, or probed (or the default, if this function
3898 is being called at the end of processing and this feature was
3899 not reported). The third argument may be NULL; if not NULL, it
3900 is a NUL-terminated string taken from the packet following
3901 this feature's name and an equals sign. */
3902 void (*func) (const struct protocol_feature *, enum packet_support,
3903 const char *);
3904
3905 /* The corresponding packet for this feature. Only used if
3906 FUNC is remote_supported_packet. */
3907 int packet;
3908};
3909
be2a5f71
DJ
3910static void
3911remote_supported_packet (const struct protocol_feature *feature,
3912 enum packet_support support,
3913 const char *argument)
3914{
3915 if (argument)
3916 {
3917 warning (_("Remote qSupported response supplied an unexpected value for"
3918 " \"%s\"."), feature->name);
3919 return;
3920 }
3921
4082afcc 3922 remote_protocol_packets[feature->packet].support = support;
be2a5f71 3923}
be2a5f71
DJ
3924
3925static void
3926remote_packet_size (const struct protocol_feature *feature,
3927 enum packet_support support, const char *value)
3928{
3929 struct remote_state *rs = get_remote_state ();
3930
3931 int packet_size;
3932 char *value_end;
3933
3934 if (support != PACKET_ENABLE)
3935 return;
3936
3937 if (value == NULL || *value == '\0')
3938 {
3939 warning (_("Remote target reported \"%s\" without a size."),
3940 feature->name);
3941 return;
3942 }
3943
3944 errno = 0;
3945 packet_size = strtol (value, &value_end, 16);
3946 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3947 {
3948 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3949 feature->name, value);
3950 return;
3951 }
3952
3953 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3954 {
3955 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3956 packet_size, MAX_REMOTE_PACKET_SIZE);
3957 packet_size = MAX_REMOTE_PACKET_SIZE;
3958 }
3959
3960 /* Record the new maximum packet size. */
3961 rs->explicit_packet_size = packet_size;
3962}
3963
dc473cfb 3964static const struct protocol_feature remote_protocol_features[] = {
0876f84a 3965 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 3966 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 3967 PACKET_qXfer_auxv },
23181151
DJ
3968 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3969 PACKET_qXfer_features },
cfa9d6d9
DJ
3970 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3971 PACKET_qXfer_libraries },
2268b414
JK
3972 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3973 PACKET_qXfer_libraries_svr4 },
ced63ec0 3974 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 3975 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 3976 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 3977 PACKET_qXfer_memory_map },
4de6483e
UW
3978 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3979 PACKET_qXfer_spu_read },
3980 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3981 PACKET_qXfer_spu_write },
07e059b5
VP
3982 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3983 PACKET_qXfer_osdata },
dc146f7c
VP
3984 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3985 PACKET_qXfer_threads },
b3b9301e
PA
3986 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3987 PACKET_qXfer_traceframe_info },
89be2091
DJ
3988 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3989 PACKET_QPassSignals },
9b224c5e
PA
3990 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
3991 PACKET_QProgramSignals },
a6f3e723
SL
3992 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3993 PACKET_QStartNoAckMode },
4082afcc
PA
3994 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
3995 PACKET_multiprocess_feature },
3996 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
3997 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3998 PACKET_qXfer_siginfo_read },
3999 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4000 PACKET_qXfer_siginfo_write },
4082afcc 4001 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4002 PACKET_ConditionalTracepoints },
4082afcc 4003 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4004 PACKET_ConditionalBreakpoints },
4082afcc 4005 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4006 PACKET_BreakpointCommands },
4082afcc 4007 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4008 PACKET_FastTracepoints },
4082afcc 4009 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4010 PACKET_StaticTracepoints },
4082afcc 4011 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4012 PACKET_InstallInTrace},
4082afcc
PA
4013 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4014 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4015 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4016 PACKET_bc },
4017 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4018 PACKET_bs },
409873ef
SS
4019 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4020 PACKET_TracepointSource },
d914c394
SS
4021 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4022 PACKET_QAllow },
4082afcc
PA
4023 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4024 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4025 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4026 PACKET_qXfer_fdpic },
169081d0
TG
4027 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4028 PACKET_qXfer_uib },
03583c20
UW
4029 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4030 PACKET_QDisableRandomization },
d1feda86 4031 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4032 { "QTBuffer:size", PACKET_DISABLE,
4033 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4034 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4035 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4036 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4037 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4038 PACKET_qXfer_btrace },
4039 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4040 PACKET_qXfer_btrace_conf },
4041 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4042 PACKET_Qbtrace_conf_bts_size },
4043 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4044 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
be2a5f71
DJ
4045};
4046
c8d5aac9
L
4047static char *remote_support_xml;
4048
4049/* Register string appended to "xmlRegisters=" in qSupported query. */
4050
4051void
6e39997a 4052register_remote_support_xml (const char *xml)
c8d5aac9
L
4053{
4054#if defined(HAVE_LIBEXPAT)
4055 if (remote_support_xml == NULL)
c4f7c687 4056 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4057 else
4058 {
4059 char *copy = xstrdup (remote_support_xml + 13);
4060 char *p = strtok (copy, ",");
4061
4062 do
4063 {
4064 if (strcmp (p, xml) == 0)
4065 {
4066 /* already there */
4067 xfree (copy);
4068 return;
4069 }
4070 }
4071 while ((p = strtok (NULL, ",")) != NULL);
4072 xfree (copy);
4073
94b0dee1
PA
4074 remote_support_xml = reconcat (remote_support_xml,
4075 remote_support_xml, ",", xml,
4076 (char *) NULL);
c8d5aac9
L
4077 }
4078#endif
4079}
4080
4081static char *
4082remote_query_supported_append (char *msg, const char *append)
4083{
4084 if (msg)
94b0dee1 4085 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4086 else
4087 return xstrdup (append);
4088}
4089
be2a5f71
DJ
4090static void
4091remote_query_supported (void)
4092{
4093 struct remote_state *rs = get_remote_state ();
4094 char *next;
4095 int i;
4096 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4097
4098 /* The packet support flags are handled differently for this packet
4099 than for most others. We treat an error, a disabled packet, and
4100 an empty response identically: any features which must be reported
4101 to be used will be automatically disabled. An empty buffer
4102 accomplishes this, since that is also the representation for a list
4103 containing no features. */
4104
4105 rs->buf[0] = 0;
4082afcc 4106 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4107 {
c8d5aac9 4108 char *q = NULL;
94b0dee1 4109 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4110
901f9912 4111 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4112
f7e6eed5
PA
4113 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4114 q = remote_query_supported_append (q, "swbreak+");
4115 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4116 q = remote_query_supported_append (q, "hwbreak+");
4117
c8d5aac9
L
4118 if (remote_support_xml)
4119 q = remote_query_supported_append (q, remote_support_xml);
4120
dde08ee1
PA
4121 q = remote_query_supported_append (q, "qRelocInsn+");
4122
4123 q = reconcat (q, "qSupported:", q, (char *) NULL);
4124 putpkt (q);
82f73884 4125
94b0dee1
PA
4126 do_cleanups (old_chain);
4127
be2a5f71
DJ
4128 getpkt (&rs->buf, &rs->buf_size, 0);
4129
4130 /* If an error occured, warn, but do not return - just reset the
4131 buffer to empty and go on to disable features. */
4132 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4133 == PACKET_ERROR)
4134 {
4135 warning (_("Remote failure reply: %s"), rs->buf);
4136 rs->buf[0] = 0;
4137 }
4138 }
4139
4140 memset (seen, 0, sizeof (seen));
4141
4142 next = rs->buf;
4143 while (*next)
4144 {
4145 enum packet_support is_supported;
4146 char *p, *end, *name_end, *value;
4147
4148 /* First separate out this item from the rest of the packet. If
4149 there's another item after this, we overwrite the separator
4150 (terminated strings are much easier to work with). */
4151 p = next;
4152 end = strchr (p, ';');
4153 if (end == NULL)
4154 {
4155 end = p + strlen (p);
4156 next = end;
4157 }
4158 else
4159 {
89be2091
DJ
4160 *end = '\0';
4161 next = end + 1;
4162
be2a5f71
DJ
4163 if (end == p)
4164 {
4165 warning (_("empty item in \"qSupported\" response"));
4166 continue;
4167 }
be2a5f71
DJ
4168 }
4169
4170 name_end = strchr (p, '=');
4171 if (name_end)
4172 {
4173 /* This is a name=value entry. */
4174 is_supported = PACKET_ENABLE;
4175 value = name_end + 1;
4176 *name_end = '\0';
4177 }
4178 else
4179 {
4180 value = NULL;
4181 switch (end[-1])
4182 {
4183 case '+':
4184 is_supported = PACKET_ENABLE;
4185 break;
4186
4187 case '-':
4188 is_supported = PACKET_DISABLE;
4189 break;
4190
4191 case '?':
4192 is_supported = PACKET_SUPPORT_UNKNOWN;
4193 break;
4194
4195 default:
3e43a32a
MS
4196 warning (_("unrecognized item \"%s\" "
4197 "in \"qSupported\" response"), p);
be2a5f71
DJ
4198 continue;
4199 }
4200 end[-1] = '\0';
4201 }
4202
4203 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4204 if (strcmp (remote_protocol_features[i].name, p) == 0)
4205 {
4206 const struct protocol_feature *feature;
4207
4208 seen[i] = 1;
4209 feature = &remote_protocol_features[i];
4210 feature->func (feature, is_supported, value);
4211 break;
4212 }
4213 }
4214
4215 /* If we increased the packet size, make sure to increase the global
4216 buffer size also. We delay this until after parsing the entire
4217 qSupported packet, because this is the same buffer we were
4218 parsing. */
4219 if (rs->buf_size < rs->explicit_packet_size)
4220 {
4221 rs->buf_size = rs->explicit_packet_size;
4222 rs->buf = xrealloc (rs->buf, rs->buf_size);
4223 }
4224
4225 /* Handle the defaults for unmentioned features. */
4226 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4227 if (!seen[i])
4228 {
4229 const struct protocol_feature *feature;
4230
4231 feature = &remote_protocol_features[i];
4232 feature->func (feature, feature->default_support, NULL);
4233 }
4234}
4235
78a095c3
JK
4236/* Remove any of the remote.c targets from target stack. Upper targets depend
4237 on it so remove them first. */
4238
4239static void
4240remote_unpush_target (void)
4241{
4242 pop_all_targets_above (process_stratum - 1);
4243}
be2a5f71 4244
c906108c 4245static void
014f9477 4246remote_open_1 (const char *name, int from_tty,
3e43a32a 4247 struct target_ops *target, int extended_p)
c906108c 4248{
d01949b6 4249 struct remote_state *rs = get_remote_state ();
a6f3e723 4250
c906108c 4251 if (name == 0)
8a3fe4f8 4252 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4253 "serial device is attached to the remote system\n"
8a3fe4f8 4254 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4255
23860348 4256 /* See FIXME above. */
c6ebd6cf 4257 if (!target_async_permitted)
92d1e331 4258 wait_forever_enabled_p = 1;
6426a772 4259
2d717e4f 4260 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4261 Ask this question first, before target_preopen has a chance to kill
4262 anything. */
5d93a237 4263 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4264 {
78a095c3
JK
4265 if (from_tty
4266 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4267 error (_("Still connected."));
4268 }
4269
78a095c3 4270 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4271 target_preopen (from_tty);
4272
89be2091 4273 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4274 xfree (rs->last_pass_packet);
4275 rs->last_pass_packet = NULL;
89be2091 4276
9b224c5e
PA
4277 /* Make sure we send the program signals list the next time we
4278 resume. */
5e4a05c4
TT
4279 xfree (rs->last_program_signals_packet);
4280 rs->last_program_signals_packet = NULL;
9b224c5e 4281
ad9a8f3f 4282 remote_fileio_reset ();
1dd41f16
NS
4283 reopen_exec_file ();
4284 reread_symbols ();
4285
5d93a237
TT
4286 rs->remote_desc = remote_serial_open (name);
4287 if (!rs->remote_desc)
c906108c
SS
4288 perror_with_name (name);
4289
4290 if (baud_rate != -1)
4291 {
5d93a237 4292 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4293 {
9b74d5d3
KB
4294 /* The requested speed could not be set. Error out to
4295 top level after closing remote_desc. Take care to
4296 set remote_desc to NULL to avoid closing remote_desc
4297 more than once. */
5d93a237
TT
4298 serial_close (rs->remote_desc);
4299 rs->remote_desc = NULL;
c906108c
SS
4300 perror_with_name (name);
4301 }
4302 }
4303
236af5e3 4304 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4305 serial_raw (rs->remote_desc);
c906108c
SS
4306
4307 /* If there is something sitting in the buffer we might take it as a
4308 response to a command, which would be bad. */
5d93a237 4309 serial_flush_input (rs->remote_desc);
c906108c
SS
4310
4311 if (from_tty)
4312 {
4313 puts_filtered ("Remote debugging using ");
4314 puts_filtered (name);
4315 puts_filtered ("\n");
4316 }
23860348 4317 push_target (target); /* Switch to using remote target now. */
c906108c 4318
74531fed
PA
4319 /* Register extra event sources in the event loop. */
4320 remote_async_inferior_event_token
4321 = create_async_event_handler (remote_async_inferior_event_handler,
4322 NULL);
5965e028 4323 rs->notif_state = remote_notif_state_allocate ();
74531fed 4324
be2a5f71
DJ
4325 /* Reset the target state; these things will be queried either by
4326 remote_query_supported or as they are needed. */
ca4f7f8b 4327 reset_all_packet_configs_support ();
74531fed 4328 rs->cached_wait_status = 0;
be2a5f71 4329 rs->explicit_packet_size = 0;
a6f3e723 4330 rs->noack_mode = 0;
82f73884 4331 rs->extended = extended_p;
e24a49d8 4332 rs->waiting_for_stop_reply = 0;
3a29589a 4333 rs->ctrlc_pending_p = 0;
802188a7 4334
47f8a51d
TT
4335 rs->general_thread = not_sent_ptid;
4336 rs->continue_thread = not_sent_ptid;
262e1174 4337 rs->remote_traceframe_number = -1;
c906108c 4338
9d1f7ab2 4339 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4340 rs->use_threadinfo_query = 1;
4341 rs->use_threadextra_query = 1;
9d1f7ab2 4342
c6ebd6cf 4343 if (target_async_permitted)
92d1e331 4344 {
23860348 4345 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4346 remote_async_terminal_ours_p = 1;
4347
4348 /* FIXME: cagney/1999-09-23: During the initial connection it is
4349 assumed that the target is already ready and able to respond to
0df8b418 4350 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4351 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4352 around this. Eventually a mechanism that allows
92d1e331 4353 wait_for_inferior() to expect/get timeouts will be
23860348 4354 implemented. */
92d1e331
DJ
4355 wait_forever_enabled_p = 0;
4356 }
4357
23860348 4358 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4359 no_shared_libraries (NULL, 0);
f78f6cf1 4360
74531fed
PA
4361 /* Start afresh. */
4362 init_thread_list ();
4363
36918e70 4364 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4365 target (we'd otherwise be in an inconsistent state) and then
4366 propogate the error on up the exception chain. This ensures that
4367 the caller doesn't stumble along blindly assuming that the
4368 function succeeded. The CLI doesn't have this problem but other
4369 UI's, such as MI do.
36918e70
AC
4370
4371 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4372 this function should return an error indication letting the
ce2826aa 4373 caller restore the previous state. Unfortunately the command
36918e70
AC
4374 ``target remote'' is directly wired to this function making that
4375 impossible. On a positive note, the CLI side of this problem has
4376 been fixed - the function set_cmd_context() makes it possible for
4377 all the ``target ....'' commands to share a common callback
4378 function. See cli-dump.c. */
109c3e39 4379 {
2d717e4f 4380
492d29ea 4381 TRY
04bd08de
TT
4382 {
4383 remote_start_remote (from_tty, target, extended_p);
4384 }
492d29ea 4385 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4386 {
c8d104ad
PA
4387 /* Pop the partially set up target - unless something else did
4388 already before throwing the exception. */
5d93a237 4389 if (rs->remote_desc != NULL)
78a095c3 4390 remote_unpush_target ();
c6ebd6cf 4391 if (target_async_permitted)
109c3e39
AC
4392 wait_forever_enabled_p = 1;
4393 throw_exception (ex);
4394 }
492d29ea 4395 END_CATCH
109c3e39 4396 }
c906108c 4397
f4abbc16
MM
4398 remote_btrace_reset ();
4399
c6ebd6cf 4400 if (target_async_permitted)
92d1e331 4401 wait_forever_enabled_p = 1;
43ff13b4
JM
4402}
4403
c906108c
SS
4404/* This takes a program previously attached to and detaches it. After
4405 this is done, GDB can be used to debug some other program. We
4406 better not have left any breakpoints in the target program or it'll
4407 die when it hits one. */
4408
4409static void
52554a0e 4410remote_detach_1 (const char *args, int from_tty, int extended)
c906108c 4411{
82f73884 4412 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4413 struct remote_state *rs = get_remote_state ();
c906108c
SS
4414
4415 if (args)
8a3fe4f8 4416 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4417
2d717e4f
DJ
4418 if (!target_has_execution)
4419 error (_("No process to detach from."));
4420
7cee1e54
PA
4421 if (from_tty)
4422 {
4423 char *exec_file = get_exec_file (0);
4424 if (exec_file == NULL)
4425 exec_file = "";
4426 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4427 target_pid_to_str (pid_to_ptid (pid)));
4428 gdb_flush (gdb_stdout);
4429 }
4430
c906108c 4431 /* Tell the remote target to detach. */
82f73884 4432 if (remote_multi_process_p (rs))
bba74b36 4433 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
82f73884
PA
4434 else
4435 strcpy (rs->buf, "D");
4436
4ddda9b5
PA
4437 putpkt (rs->buf);
4438 getpkt (&rs->buf, &rs->buf_size, 0);
4439
82f73884
PA
4440 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4441 ;
4442 else if (rs->buf[0] == '\0')
4443 error (_("Remote doesn't know how to detach"));
4444 else
4ddda9b5 4445 error (_("Can't detach process."));
c906108c 4446
7cee1e54
PA
4447 if (from_tty && !extended)
4448 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4449
82f73884 4450 target_mourn_inferior ();
2d717e4f
DJ
4451}
4452
4453static void
52554a0e 4454remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4455{
4456 remote_detach_1 (args, from_tty, 0);
4457}
4458
4459static void
52554a0e 4460extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f
DJ
4461{
4462 remote_detach_1 (args, from_tty, 1);
c906108c
SS
4463}
4464
6ad8ae5c
DJ
4465/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4466
43ff13b4 4467static void
fee354ee 4468remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 4469{
43ff13b4 4470 if (args)
2d717e4f 4471 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4472
2d717e4f
DJ
4473 /* Make sure we unpush even the extended remote targets; mourn
4474 won't do it. So call remote_mourn_1 directly instead of
4475 target_mourn_inferior. */
4476 remote_mourn_1 (target);
4477
43ff13b4
JM
4478 if (from_tty)
4479 puts_filtered ("Ending remote debugging.\n");
4480}
4481
2d717e4f
DJ
4482/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4483 be chatty about it. */
4484
4485static void
c0939df1
TT
4486extended_remote_attach_1 (struct target_ops *target, const char *args,
4487 int from_tty)
2d717e4f
DJ
4488{
4489 struct remote_state *rs = get_remote_state ();
be86555c 4490 int pid;
96ef3384 4491 char *wait_status = NULL;
2d717e4f 4492
74164c56 4493 pid = parse_pid_to_attach (args);
2d717e4f 4494
74164c56
JK
4495 /* Remote PID can be freely equal to getpid, do not check it here the same
4496 way as in other targets. */
2d717e4f 4497
4082afcc 4498 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
4499 error (_("This target does not support attaching to a process"));
4500
7cee1e54
PA
4501 if (from_tty)
4502 {
4503 char *exec_file = get_exec_file (0);
4504
4505 if (exec_file)
4506 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4507 target_pid_to_str (pid_to_ptid (pid)));
4508 else
4509 printf_unfiltered (_("Attaching to %s\n"),
4510 target_pid_to_str (pid_to_ptid (pid)));
4511
4512 gdb_flush (gdb_stdout);
4513 }
4514
bba74b36 4515 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4516 putpkt (rs->buf);
4517 getpkt (&rs->buf, &rs->buf_size, 0);
4518
4082afcc
PA
4519 switch (packet_ok (rs->buf,
4520 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 4521 {
4082afcc 4522 case PACKET_OK:
74531fed
PA
4523 if (!non_stop)
4524 {
4525 /* Save the reply for later. */
4526 wait_status = alloca (strlen (rs->buf) + 1);
4527 strcpy (wait_status, rs->buf);
4528 }
4529 else if (strcmp (rs->buf, "OK") != 0)
4530 error (_("Attaching to %s failed with: %s"),
4531 target_pid_to_str (pid_to_ptid (pid)),
4532 rs->buf);
4082afcc
PA
4533 break;
4534 case PACKET_UNKNOWN:
4535 error (_("This target does not support attaching to a process"));
4536 default:
4537 error (_("Attaching to %s failed"),
4538 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4539 }
2d717e4f 4540
49c62f2e 4541 set_current_inferior (remote_add_inferior (0, pid, 1));
bad34192 4542
2d717e4f 4543 inferior_ptid = pid_to_ptid (pid);
79d7f229 4544
bad34192
PA
4545 if (non_stop)
4546 {
4547 struct thread_info *thread;
79d7f229 4548
bad34192 4549 /* Get list of threads. */
e8032dde 4550 remote_update_thread_list (target);
82f73884 4551
bad34192
PA
4552 thread = first_thread_of_process (pid);
4553 if (thread)
4554 inferior_ptid = thread->ptid;
4555 else
4556 inferior_ptid = pid_to_ptid (pid);
4557
4558 /* Invalidate our notion of the remote current thread. */
47f8a51d 4559 record_currthread (rs, minus_one_ptid);
bad34192 4560 }
74531fed 4561 else
bad34192
PA
4562 {
4563 /* Now, if we have thread information, update inferior_ptid. */
4564 inferior_ptid = remote_current_thread (inferior_ptid);
4565
4566 /* Add the main thread to the thread list. */
4567 add_thread_silent (inferior_ptid);
4568 }
c0a2216e 4569
96ef3384
UW
4570 /* Next, if the target can specify a description, read it. We do
4571 this before anything involving memory or registers. */
4572 target_find_description ();
4573
74531fed
PA
4574 if (!non_stop)
4575 {
4576 /* Use the previously fetched status. */
4577 gdb_assert (wait_status != NULL);
4578
4579 if (target_can_async_p ())
4580 {
722247f1
YQ
4581 struct notif_event *reply
4582 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4583
722247f1 4584 push_stop_reply ((struct stop_reply *) reply);
74531fed 4585
6a3753b3 4586 target_async (1);
74531fed
PA
4587 }
4588 else
4589 {
4590 gdb_assert (wait_status != NULL);
4591 strcpy (rs->buf, wait_status);
4592 rs->cached_wait_status = 1;
4593 }
4594 }
4595 else
4596 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4597}
4598
4599static void
c0939df1 4600extended_remote_attach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4601{
136d6dae 4602 extended_remote_attach_1 (ops, args, from_tty);
2d717e4f
DJ
4603}
4604
b9c1d481
AS
4605/* Implementation of the to_post_attach method. */
4606
4607static void
4608extended_remote_post_attach (struct target_ops *ops, int pid)
4609{
4610 /* In certain cases GDB might not have had the chance to start
4611 symbol lookup up until now. This could happen if the debugged
4612 binary is not using shared libraries, the vsyscall page is not
4613 present (on Linux) and the binary itself hadn't changed since the
4614 debugging process was started. */
4615 if (symfile_objfile != NULL)
4616 remote_check_symbols();
4617}
4618
c906108c 4619\f
506fb367
DJ
4620/* Check for the availability of vCont. This function should also check
4621 the response. */
c906108c
SS
4622
4623static void
6d820c5c 4624remote_vcont_probe (struct remote_state *rs)
c906108c 4625{
2e9f7625 4626 char *buf;
6d820c5c 4627
2e9f7625
DJ
4628 strcpy (rs->buf, "vCont?");
4629 putpkt (rs->buf);
6d820c5c 4630 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4631 buf = rs->buf;
c906108c 4632
506fb367 4633 /* Make sure that the features we assume are supported. */
61012eef 4634 if (startswith (buf, "vCont"))
506fb367
DJ
4635 {
4636 char *p = &buf[5];
4637 int support_s, support_S, support_c, support_C;
4638
4639 support_s = 0;
4640 support_S = 0;
4641 support_c = 0;
4642 support_C = 0;
d458bd84 4643 rs->supports_vCont.t = 0;
c1e36e3e 4644 rs->supports_vCont.r = 0;
506fb367
DJ
4645 while (p && *p == ';')
4646 {
4647 p++;
4648 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4649 support_s = 1;
4650 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4651 support_S = 1;
4652 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4653 support_c = 1;
4654 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4655 support_C = 1;
74531fed 4656 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4657 rs->supports_vCont.t = 1;
c1e36e3e
PA
4658 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4659 rs->supports_vCont.r = 1;
506fb367
DJ
4660
4661 p = strchr (p, ';');
4662 }
c906108c 4663
506fb367
DJ
4664 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4665 BUF will make packet_ok disable the packet. */
4666 if (!support_s || !support_S || !support_c || !support_C)
4667 buf[0] = 0;
4668 }
c906108c 4669
444abaca 4670 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4671}
c906108c 4672
0d8f58ca
PA
4673/* Helper function for building "vCont" resumptions. Write a
4674 resumption to P. ENDP points to one-passed-the-end of the buffer
4675 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4676 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4677 resumed thread should be single-stepped and/or signalled. If PTID
4678 equals minus_one_ptid, then all threads are resumed; if PTID
4679 represents a process, then all threads of the process are resumed;
4680 the thread to be stepped and/or signalled is given in the global
4681 INFERIOR_PTID. */
4682
4683static char *
4684append_resumption (char *p, char *endp,
2ea28649 4685 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
4686{
4687 struct remote_state *rs = get_remote_state ();
4688
a493e3e2 4689 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 4690 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
4691 else if (step
4692 /* GDB is willing to range step. */
4693 && use_range_stepping
4694 /* Target supports range stepping. */
4695 && rs->supports_vCont.r
4696 /* We don't currently support range stepping multiple
4697 threads with a wildcard (though the protocol allows it,
4698 so stubs shouldn't make an active effort to forbid
4699 it). */
4700 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4701 {
4702 struct thread_info *tp;
4703
4704 if (ptid_equal (ptid, minus_one_ptid))
4705 {
4706 /* If we don't know about the target thread's tid, then
4707 we're resuming magic_null_ptid (see caller). */
4708 tp = find_thread_ptid (magic_null_ptid);
4709 }
4710 else
4711 tp = find_thread_ptid (ptid);
4712 gdb_assert (tp != NULL);
4713
4714 if (tp->control.may_range_step)
4715 {
4716 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4717
4718 p += xsnprintf (p, endp - p, ";r%s,%s",
4719 phex_nz (tp->control.step_range_start,
4720 addr_size),
4721 phex_nz (tp->control.step_range_end,
4722 addr_size));
4723 }
4724 else
4725 p += xsnprintf (p, endp - p, ";s");
4726 }
0d8f58ca
PA
4727 else if (step)
4728 p += xsnprintf (p, endp - p, ";s");
a493e3e2 4729 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
4730 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4731 else
4732 p += xsnprintf (p, endp - p, ";c");
4733
4734 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4735 {
4736 ptid_t nptid;
4737
4738 /* All (-1) threads of process. */
ba348170 4739 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
4740
4741 p += xsnprintf (p, endp - p, ":");
4742 p = write_ptid (p, endp, nptid);
4743 }
4744 else if (!ptid_equal (ptid, minus_one_ptid))
4745 {
4746 p += xsnprintf (p, endp - p, ":");
4747 p = write_ptid (p, endp, ptid);
4748 }
4749
4750 return p;
4751}
4752
e5ef252a
PA
4753/* Append a vCont continue-with-signal action for threads that have a
4754 non-zero stop signal. */
4755
4756static char *
4757append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4758{
4759 struct thread_info *thread;
4760
034f788c 4761 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
4762 if (ptid_match (thread->ptid, ptid)
4763 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 4764 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
4765 {
4766 p = append_resumption (p, endp, thread->ptid,
4767 0, thread->suspend.stop_signal);
4768 thread->suspend.stop_signal = GDB_SIGNAL_0;
4769 }
4770
4771 return p;
4772}
4773
506fb367
DJ
4774/* Resume the remote inferior by using a "vCont" packet. The thread
4775 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
4776 resumed thread should be single-stepped and/or signalled. If PTID
4777 equals minus_one_ptid, then all threads are resumed; the thread to
4778 be stepped and/or signalled is given in the global INFERIOR_PTID.
4779 This function returns non-zero iff it resumes the inferior.
44eaed12 4780
506fb367
DJ
4781 This function issues a strict subset of all possible vCont commands at the
4782 moment. */
44eaed12 4783
506fb367 4784static int
2ea28649 4785remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
4786{
4787 struct remote_state *rs = get_remote_state ();
82f73884
PA
4788 char *p;
4789 char *endp;
44eaed12 4790
4082afcc 4791 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 4792 remote_vcont_probe (rs);
44eaed12 4793
4082afcc 4794 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 4795 return 0;
44eaed12 4796
82f73884
PA
4797 p = rs->buf;
4798 endp = rs->buf + get_remote_packet_size ();
4799
506fb367
DJ
4800 /* If we could generate a wider range of packets, we'd have to worry
4801 about overflowing BUF. Should there be a generic
4802 "multi-part-packet" packet? */
4803
0d8f58ca
PA
4804 p += xsnprintf (p, endp - p, "vCont");
4805
79d7f229 4806 if (ptid_equal (ptid, magic_null_ptid))
c906108c 4807 {
79d7f229
PA
4808 /* MAGIC_NULL_PTID means that we don't have any active threads,
4809 so we don't have any TID numbers the inferior will
4810 understand. Make sure to only send forms that do not specify
4811 a TID. */
a9cbf802 4812 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 4813 }
0d8f58ca 4814 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 4815 {
0d8f58ca
PA
4816 /* Resume all threads (of all processes, or of a single
4817 process), with preference for INFERIOR_PTID. This assumes
4818 inferior_ptid belongs to the set of all threads we are about
4819 to resume. */
a493e3e2 4820 if (step || siggnal != GDB_SIGNAL_0)
82f73884 4821 {
0d8f58ca
PA
4822 /* Step inferior_ptid, with or without signal. */
4823 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 4824 }
0d8f58ca 4825
e5ef252a
PA
4826 /* Also pass down any pending signaled resumption for other
4827 threads not the current. */
4828 p = append_pending_thread_resumptions (p, endp, ptid);
4829
0d8f58ca 4830 /* And continue others without a signal. */
a493e3e2 4831 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
4832 }
4833 else
506fb367
DJ
4834 {
4835 /* Scheduler locking; resume only PTID. */
a9cbf802 4836 append_resumption (p, endp, ptid, step, siggnal);
506fb367 4837 }
c906108c 4838
82f73884
PA
4839 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4840 putpkt (rs->buf);
506fb367 4841
74531fed
PA
4842 if (non_stop)
4843 {
4844 /* In non-stop, the stub replies to vCont with "OK". The stop
4845 reply will be reported asynchronously by means of a `%Stop'
4846 notification. */
4847 getpkt (&rs->buf, &rs->buf_size, 0);
4848 if (strcmp (rs->buf, "OK") != 0)
4849 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4850 }
4851
506fb367 4852 return 1;
c906108c 4853}
43ff13b4 4854
506fb367
DJ
4855/* Tell the remote machine to resume. */
4856
43ff13b4 4857static void
28439f5e 4858remote_resume (struct target_ops *ops,
2ea28649 4859 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 4860{
d01949b6 4861 struct remote_state *rs = get_remote_state ();
2e9f7625 4862 char *buf;
43ff13b4 4863
722247f1
YQ
4864 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
4865 (explained in remote-notif.c:handle_notification) so
4866 remote_notif_process is not called. We need find a place where
4867 it is safe to start a 'vNotif' sequence. It is good to do it
4868 before resuming inferior, because inferior was stopped and no RSP
4869 traffic at that moment. */
4870 if (!non_stop)
5965e028 4871 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 4872
b73be471 4873 rs->last_sent_signal = siggnal;
280ceea3 4874 rs->last_sent_step = step;
43ff13b4 4875
506fb367 4876 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
4877 /* No reverse support (yet) for vCont. */
4878 if (execution_direction != EXEC_REVERSE)
4879 if (remote_vcont_resume (ptid, step, siggnal))
4880 goto done;
506fb367 4881
79d7f229
PA
4882 /* All other supported resume packets do use Hc, so set the continue
4883 thread. */
4884 if (ptid_equal (ptid, minus_one_ptid))
4885 set_continue_thread (any_thread_ptid);
506fb367 4886 else
79d7f229 4887 set_continue_thread (ptid);
506fb367 4888
2e9f7625 4889 buf = rs->buf;
b2175913
MS
4890 if (execution_direction == EXEC_REVERSE)
4891 {
4892 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 4893 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 4894 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 4895 siggnal);
40ab02ce 4896
4082afcc 4897 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 4898 error (_("Remote reverse-step not supported."));
4082afcc 4899 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 4900 error (_("Remote reverse-continue not supported."));
40ab02ce 4901
b2175913
MS
4902 strcpy (buf, step ? "bs" : "bc");
4903 }
a493e3e2 4904 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
4905 {
4906 buf[0] = step ? 'S' : 'C';
c5aa993b 4907 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 4908 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
4909 buf[3] = '\0';
4910 }
4911 else
c5aa993b 4912 strcpy (buf, step ? "s" : "c");
506fb367 4913
44eaed12 4914 putpkt (buf);
43ff13b4 4915
75c99385 4916 done:
2acceee2 4917 /* We are about to start executing the inferior, let's register it
0df8b418
MS
4918 with the event loop. NOTE: this is the one place where all the
4919 execution commands end up. We could alternatively do this in each
23860348 4920 of the execution commands in infcmd.c. */
2acceee2
JM
4921 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4922 into infcmd.c in order to allow inferior function calls to work
23860348 4923 NOT asynchronously. */
362646f5 4924 if (target_can_async_p ())
6a3753b3 4925 target_async (1);
e24a49d8
PA
4926
4927 /* We've just told the target to resume. The remote server will
4928 wait for the inferior to stop, and then send a stop reply. In
4929 the mean time, we can't start another command/query ourselves
74531fed
PA
4930 because the stub wouldn't be ready to process it. This applies
4931 only to the base all-stop protocol, however. In non-stop (which
4932 only supports vCont), the stub replies with an "OK", and is
4933 immediate able to process further serial input. */
4934 if (!non_stop)
4935 rs->waiting_for_stop_reply = 1;
43ff13b4 4936}
c906108c 4937\f
43ff13b4
JM
4938
4939/* Set up the signal handler for SIGINT, while the target is
23860348 4940 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 4941static void
934b9bac 4942async_initialize_sigint_signal_handler (void)
43ff13b4 4943{
934b9bac 4944 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
4945}
4946
23860348 4947/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 4948static void
934b9bac 4949async_handle_remote_sigint (int sig)
43ff13b4 4950{
934b9bac 4951 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
4952 /* Note we need to go through gdb_call_async_signal_handler in order
4953 to wake up the event loop on Windows. */
4954 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
4955}
4956
4957/* Signal handler for SIGINT, installed after SIGINT has already been
4958 sent once. It will take effect the second time that the user sends
23860348 4959 a ^C. */
43ff13b4 4960static void
934b9bac 4961async_handle_remote_sigint_twice (int sig)
43ff13b4 4962{
934b9bac 4963 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
4964 /* See note in async_handle_remote_sigint. */
4965 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
4966}
4967
6426a772 4968/* Perform the real interruption of the target execution, in response
23860348 4969 to a ^C. */
c5aa993b 4970static void
fba45db2 4971async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
4972{
4973 if (remote_debug)
248fd3bf 4974 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 4975
94cc34af 4976 target_stop (inferior_ptid);
43ff13b4
JM
4977}
4978
0df8b418 4979/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 4980 up on the target alltogether. */
47e1ce27 4981static void
fba45db2 4982async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 4983{
2df3850c 4984 if (remote_debug)
248fd3bf 4985 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
4986
4987 interrupt_query ();
43ff13b4
JM
4988}
4989
4990/* Reinstall the usual SIGINT handlers, after the target has
23860348 4991 stopped. */
6426a772 4992static void
934b9bac 4993async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
4994{
4995 signal (SIGINT, handle_sigint);
43ff13b4
JM
4996}
4997
c906108c
SS
4998/* Send ^C to target to halt it. Target will respond, and send us a
4999 packet. */
507f3c78 5000static void (*ofunc) (int);
c906108c 5001
0df8b418
MS
5002/* The command line interface's stop routine. This function is installed
5003 as a signal handler for SIGINT. The first time a user requests a
5004 stop, we call remote_stop to send a break or ^C. If there is no
7a292a7a 5005 response from the target (it didn't stop when the user requested it),
23860348 5006 we ask the user if he'd like to detach from the target. */
c906108c 5007static void
934b9bac 5008sync_remote_interrupt (int signo)
c906108c 5009{
23860348 5010 /* If this doesn't work, try more severe steps. */
934b9bac 5011 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5012
934b9bac 5013 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5014}
5015
5016/* The user typed ^C twice. */
5017
5018static void
934b9bac 5019sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5020{
5021 signal (signo, ofunc);
934b9bac
JK
5022 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5023 signal (signo, sync_remote_interrupt);
c906108c 5024}
7a292a7a 5025
74531fed
PA
5026/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5027 thread, all threads of a remote process, or all threads of all
5028 processes. */
5029
5030static void
5031remote_stop_ns (ptid_t ptid)
5032{
5033 struct remote_state *rs = get_remote_state ();
5034 char *p = rs->buf;
5035 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5036
4082afcc 5037 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5038 remote_vcont_probe (rs);
5039
d458bd84 5040 if (!rs->supports_vCont.t)
74531fed
PA
5041 error (_("Remote server does not support stopping threads"));
5042
f91d3df5
PA
5043 if (ptid_equal (ptid, minus_one_ptid)
5044 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5045 p += xsnprintf (p, endp - p, "vCont;t");
5046 else
5047 {
5048 ptid_t nptid;
5049
74531fed
PA
5050 p += xsnprintf (p, endp - p, "vCont;t:");
5051
5052 if (ptid_is_pid (ptid))
5053 /* All (-1) threads of process. */
ba348170 5054 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5055 else
5056 {
5057 /* Small optimization: if we already have a stop reply for
5058 this thread, no use in telling the stub we want this
5059 stopped. */
5060 if (peek_stop_reply (ptid))
5061 return;
5062
5063 nptid = ptid;
5064 }
5065
a9cbf802 5066 write_ptid (p, endp, nptid);
74531fed
PA
5067 }
5068
5069 /* In non-stop, we get an immediate OK reply. The stop reply will
5070 come in asynchronously by notification. */
5071 putpkt (rs->buf);
5072 getpkt (&rs->buf, &rs->buf_size, 0);
5073 if (strcmp (rs->buf, "OK") != 0)
5074 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5075}
5076
5077/* All-stop version of target_stop. Sends a break or a ^C to stop the
5078 remote target. It is undefined which thread of which process
5079 reports the stop. */
5080
5081static void
5082remote_stop_as (ptid_t ptid)
5083{
5084 struct remote_state *rs = get_remote_state ();
5085
3a29589a
DJ
5086 rs->ctrlc_pending_p = 1;
5087
74531fed
PA
5088 /* If the inferior is stopped already, but the core didn't know
5089 about it yet, just ignore the request. The cached wait status
5090 will be collected in remote_wait. */
5091 if (rs->cached_wait_status)
5092 return;
5093
9a7071a8
JB
5094 /* Send interrupt_sequence to remote target. */
5095 send_interrupt_sequence ();
74531fed
PA
5096}
5097
0df8b418 5098/* This is the generic stop called via the target vector. When a target
7a292a7a 5099 interrupt is requested, either by the command line or the GUI, we
23860348 5100 will eventually end up here. */
74531fed 5101
c906108c 5102static void
1eab8a48 5103remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5104{
7a292a7a 5105 if (remote_debug)
0f71a2f6 5106 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5107
74531fed
PA
5108 if (non_stop)
5109 remote_stop_ns (ptid);
c906108c 5110 else
74531fed 5111 remote_stop_as (ptid);
c906108c
SS
5112}
5113
5114/* Ask the user what to do when an interrupt is received. */
5115
5116static void
fba45db2 5117interrupt_query (void)
c906108c
SS
5118{
5119 target_terminal_ours ();
5120
d9d41e78 5121 if (target_is_async_p ())
c906108c 5122 {
74531fed 5123 signal (SIGINT, handle_sigint);
039e3c22 5124 quit ();
c906108c 5125 }
74531fed
PA
5126 else
5127 {
9e2f0ad4
HZ
5128 if (query (_("Interrupted while waiting for the program.\n\
5129Give up (and stop debugging it)? ")))
74531fed 5130 {
78a095c3 5131 remote_unpush_target ();
039e3c22 5132 quit ();
74531fed
PA
5133 }
5134 }
c906108c
SS
5135
5136 target_terminal_inferior ();
5137}
5138
6426a772
JM
5139/* Enable/disable target terminal ownership. Most targets can use
5140 terminal groups to control terminal ownership. Remote targets are
5141 different in that explicit transfer of ownership to/from GDB/target
23860348 5142 is required. */
6426a772
JM
5143
5144static void
d2f640d4 5145remote_terminal_inferior (struct target_ops *self)
6426a772 5146{
c6ebd6cf 5147 if (!target_async_permitted)
75c99385
PA
5148 /* Nothing to do. */
5149 return;
5150
d9d2d8b6
PA
5151 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5152 idempotent. The event-loop GDB talking to an asynchronous target
5153 with a synchronous command calls this function from both
5154 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5155 transfer the terminal to the target when it shouldn't this guard
5156 can go away. */
6426a772
JM
5157 if (!remote_async_terminal_ours_p)
5158 return;
5159 delete_file_handler (input_fd);
5160 remote_async_terminal_ours_p = 0;
934b9bac 5161 async_initialize_sigint_signal_handler ();
6426a772
JM
5162 /* NOTE: At this point we could also register our selves as the
5163 recipient of all input. Any characters typed could then be
23860348 5164 passed on down to the target. */
6426a772
JM
5165}
5166
5167static void
e3594fd1 5168remote_terminal_ours (struct target_ops *self)
6426a772 5169{
c6ebd6cf 5170 if (!target_async_permitted)
75c99385
PA
5171 /* Nothing to do. */
5172 return;
5173
5174 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5175 if (remote_async_terminal_ours_p)
5176 return;
934b9bac 5177 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5178 add_file_handler (input_fd, stdin_event_handler, 0);
5179 remote_async_terminal_ours_p = 1;
5180}
5181
176a6961 5182static void
917317f4 5183remote_console_output (char *msg)
c906108c
SS
5184{
5185 char *p;
5186
c5aa993b 5187 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5188 {
5189 char tb[2];
5190 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5191
c906108c
SS
5192 tb[0] = c;
5193 tb[1] = 0;
43ff13b4 5194 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5195 }
00db5b94
PA
5196 gdb_flush (gdb_stdtarg);
5197}
74531fed
PA
5198
5199typedef struct cached_reg
5200{
5201 int num;
5202 gdb_byte data[MAX_REGISTER_SIZE];
5203} cached_reg_t;
5204
5205DEF_VEC_O(cached_reg_t);
5206
722247f1 5207typedef struct stop_reply
74531fed 5208{
722247f1 5209 struct notif_event base;
74531fed 5210
722247f1 5211 /* The identifier of the thread about this event */
74531fed
PA
5212 ptid_t ptid;
5213
340e3c99 5214 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5215 connection, represented by a remote_state object, is closed,
5216 all the associated stop_reply events should be released. */
5217 struct remote_state *rs;
5218
74531fed
PA
5219 struct target_waitstatus ws;
5220
15148d6a
PA
5221 /* Expedited registers. This makes remote debugging a bit more
5222 efficient for those targets that provide critical registers as
5223 part of their normal status mechanism (as another roundtrip to
5224 fetch them is avoided). */
74531fed
PA
5225 VEC(cached_reg_t) *regcache;
5226
f7e6eed5
PA
5227 enum target_stop_reason stop_reason;
5228
74531fed
PA
5229 CORE_ADDR watch_data_address;
5230
dc146f7c 5231 int core;
722247f1 5232} *stop_reply_p;
a744cf53 5233
722247f1
YQ
5234DECLARE_QUEUE_P (stop_reply_p);
5235DEFINE_QUEUE_P (stop_reply_p);
5236/* The list of already fetched and acknowledged stop events. This
5237 queue is used for notification Stop, and other notifications
5238 don't need queue for their events, because the notification events
5239 of Stop can't be consumed immediately, so that events should be
5240 queued first, and be consumed by remote_wait_{ns,as} one per
5241 time. Other notifications can consume their events immediately,
5242 so queue is not needed for them. */
5243static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5244
5245static void
5246stop_reply_xfree (struct stop_reply *r)
5247{
f48ff2a7 5248 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5249}
5250
722247f1
YQ
5251static void
5252remote_notif_stop_parse (struct notif_client *self, char *buf,
5253 struct notif_event *event)
5254{
5255 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5256}
5257
5258static void
5259remote_notif_stop_ack (struct notif_client *self, char *buf,
5260 struct notif_event *event)
5261{
5262 struct stop_reply *stop_reply = (struct stop_reply *) event;
5263
5264 /* acknowledge */
5265 putpkt ((char *) self->ack_command);
5266
5267 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5268 /* We got an unknown stop reply. */
5269 error (_("Unknown stop reply"));
5270
5271 push_stop_reply (stop_reply);
5272}
5273
5274static int
5275remote_notif_stop_can_get_pending_events (struct notif_client *self)
5276{
5277 /* We can't get pending events in remote_notif_process for
5278 notification stop, and we have to do this in remote_wait_ns
5279 instead. If we fetch all queued events from stub, remote stub
5280 may exit and we have no chance to process them back in
5281 remote_wait_ns. */
5282 mark_async_event_handler (remote_async_inferior_event_token);
5283 return 0;
5284}
5285
5286static void
5287stop_reply_dtr (struct notif_event *event)
5288{
5289 struct stop_reply *r = (struct stop_reply *) event;
5290
5291 VEC_free (cached_reg_t, r->regcache);
5292}
5293
5294static struct notif_event *
5295remote_notif_stop_alloc_reply (void)
5296{
5297 struct notif_event *r
70ba0933 5298 = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5299
5300 r->dtr = stop_reply_dtr;
5301
5302 return r;
5303}
5304
5305/* A client of notification Stop. */
5306
5307struct notif_client notif_client_stop =
5308{
5309 "Stop",
5310 "vStopped",
5311 remote_notif_stop_parse,
5312 remote_notif_stop_ack,
5313 remote_notif_stop_can_get_pending_events,
5314 remote_notif_stop_alloc_reply,
f48ff2a7 5315 REMOTE_NOTIF_STOP,
722247f1
YQ
5316};
5317
5318/* A parameter to pass data in and out. */
5319
5320struct queue_iter_param
5321{
5322 void *input;
5323 struct stop_reply *output;
5324};
5325
f48ff2a7
YQ
5326/* Remove stop replies in the queue if its pid is equal to the given
5327 inferior's pid. */
722247f1
YQ
5328
5329static int
f48ff2a7
YQ
5330remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5331 QUEUE_ITER (stop_reply_p) *iter,
5332 stop_reply_p event,
5333 void *data)
722247f1
YQ
5334{
5335 struct queue_iter_param *param = data;
5336 struct inferior *inf = param->input;
5337
f48ff2a7 5338 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5339 {
5340 stop_reply_xfree (event);
5341 QUEUE_remove_elem (stop_reply_p, q, iter);
5342 }
5343
5344 return 1;
5345}
5346
f48ff2a7 5347/* Discard all pending stop replies of inferior INF. */
c906108c 5348
74531fed 5349static void
5f4cf0bb 5350discard_pending_stop_replies (struct inferior *inf)
c906108c 5351{
722247f1
YQ
5352 int i;
5353 struct queue_iter_param param;
f48ff2a7
YQ
5354 struct stop_reply *reply;
5355 struct remote_state *rs = get_remote_state ();
5356 struct remote_notif_state *rns = rs->notif_state;
5357
5358 /* This function can be notified when an inferior exists. When the
5359 target is not remote, the notification state is NULL. */
5360 if (rs->remote_desc == NULL)
5361 return;
5362
5363 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5364
74531fed 5365 /* Discard the in-flight notification. */
f48ff2a7 5366 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5367 {
722247f1 5368 stop_reply_xfree (reply);
f48ff2a7 5369 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5370 }
c906108c 5371
722247f1
YQ
5372 param.input = inf;
5373 param.output = NULL;
74531fed
PA
5374 /* Discard the stop replies we have already pulled with
5375 vStopped. */
722247f1 5376 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5377 remove_stop_reply_for_inferior, &param);
5378}
5379
bcc75809
YQ
5380/* If its remote state is equal to the given remote state,
5381 remove EVENT from the stop reply queue. */
5382
5383static int
5384remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5385 QUEUE_ITER (stop_reply_p) *iter,
5386 stop_reply_p event,
5387 void *data)
5388{
5389 struct queue_iter_param *param = data;
5390 struct remote_state *rs = param->input;
5391
5392 if (event->rs == rs)
5393 {
5394 stop_reply_xfree (event);
5395 QUEUE_remove_elem (stop_reply_p, q, iter);
5396 }
5397
5398 return 1;
5399}
5400
5401/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5402
5403static void
bcc75809 5404discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5405{
5406 struct queue_iter_param param;
5407
bcc75809 5408 param.input = rs;
f48ff2a7
YQ
5409 param.output = NULL;
5410 /* Discard the stop replies we have already pulled with
5411 vStopped. */
5412 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5413 remove_stop_reply_of_remote_state, &param);
722247f1 5414}
74531fed 5415
722247f1
YQ
5416/* A parameter to pass data in and out. */
5417
5418static int
5419remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5420 QUEUE_ITER (stop_reply_p) *iter,
5421 stop_reply_p event,
5422 void *data)
5423{
5424 struct queue_iter_param *param = data;
5425 ptid_t *ptid = param->input;
5426
5427 if (ptid_match (event->ptid, *ptid))
5428 {
5429 param->output = event;
5430 QUEUE_remove_elem (stop_reply_p, q, iter);
5431 return 0;
c8e38a49 5432 }
722247f1
YQ
5433
5434 return 1;
74531fed 5435}
43ff13b4 5436
722247f1
YQ
5437/* Remove the first reply in 'stop_reply_queue' which matches
5438 PTID. */
2e9f7625 5439
722247f1
YQ
5440static struct stop_reply *
5441remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5442{
722247f1
YQ
5443 struct queue_iter_param param;
5444
5445 param.input = &ptid;
5446 param.output = NULL;
5447
5448 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5449 remote_notif_remove_once_on_match, &param);
5450 if (notif_debug)
5451 fprintf_unfiltered (gdb_stdlog,
5452 "notif: discard queued event: 'Stop' in %s\n",
5453 target_pid_to_str (ptid));
a744cf53 5454
722247f1 5455 return param.output;
74531fed 5456}
75c99385 5457
74531fed
PA
5458/* Look for a queued stop reply belonging to PTID. If one is found,
5459 remove it from the queue, and return it. Returns NULL if none is
5460 found. If there are still queued events left to process, tell the
5461 event loop to get back to target_wait soon. */
e24a49d8 5462
74531fed
PA
5463static struct stop_reply *
5464queued_stop_reply (ptid_t ptid)
5465{
722247f1 5466 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5467
722247f1 5468 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5469 /* There's still at least an event left. */
5470 mark_async_event_handler (remote_async_inferior_event_token);
5471
722247f1 5472 return r;
74531fed
PA
5473}
5474
5475/* Push a fully parsed stop reply in the stop reply queue. Since we
5476 know that we now have at least one queued event left to pass to the
5477 core side, tell the event loop to get back to target_wait soon. */
5478
5479static void
5480push_stop_reply (struct stop_reply *new_event)
5481{
722247f1 5482 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5483
722247f1
YQ
5484 if (notif_debug)
5485 fprintf_unfiltered (gdb_stdlog,
5486 "notif: push 'Stop' %s to queue %d\n",
5487 target_pid_to_str (new_event->ptid),
5488 QUEUE_length (stop_reply_p,
5489 stop_reply_queue));
74531fed
PA
5490
5491 mark_async_event_handler (remote_async_inferior_event_token);
5492}
5493
722247f1
YQ
5494static int
5495stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5496 QUEUE_ITER (stop_reply_p) *iter,
5497 struct stop_reply *event,
5498 void *data)
5499{
5500 ptid_t *ptid = data;
5501
5502 return !(ptid_equal (*ptid, event->ptid)
5503 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5504}
5505
74531fed
PA
5506/* Returns true if we have a stop reply for PTID. */
5507
5508static int
5509peek_stop_reply (ptid_t ptid)
5510{
722247f1
YQ
5511 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5512 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5513}
5514
1f10ba14
PA
5515/* Skip PACKET until the next semi-colon (or end of string). */
5516
5517static char *
5518skip_to_semicolon (char *p)
5519{
5520 while (*p != '\0' && *p != ';')
5521 p++;
5522 return p;
5523}
5524
74531fed
PA
5525/* Parse the stop reply in BUF. Either the function succeeds, and the
5526 result is stored in EVENT, or throws an error. */
5527
5528static void
5529remote_parse_stop_reply (char *buf, struct stop_reply *event)
5530{
5531 struct remote_arch_state *rsa = get_remote_arch_state ();
5532 ULONGEST addr;
5533 char *p;
5534
5535 event->ptid = null_ptid;
bcc75809 5536 event->rs = get_remote_state ();
74531fed
PA
5537 event->ws.kind = TARGET_WAITKIND_IGNORE;
5538 event->ws.value.integer = 0;
f7e6eed5 5539 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 5540 event->regcache = NULL;
dc146f7c 5541 event->core = -1;
74531fed
PA
5542
5543 switch (buf[0])
5544 {
5545 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5546 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5547 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5548 ss = signal number
5549 n... = register number
5550 r... = register contents
5551 */
5552
5553 p = &buf[3]; /* after Txx */
5554 while (*p)
5555 {
5556 char *p1;
cea39f65 5557 int fieldsize;
43ff13b4 5558
1f10ba14
PA
5559 p1 = strchr (p, ':');
5560 if (p1 == NULL)
5561 error (_("Malformed packet(a) (missing colon): %s\n\
5562Packet: '%s'\n"),
5563 p, buf);
5564 if (p == p1)
5565 error (_("Malformed packet(a) (missing register number): %s\n\
5566Packet: '%s'\n"),
5567 p, buf);
3c3bea1c 5568
1f10ba14
PA
5569 /* Some "registers" are actually extended stop information.
5570 Note if you're adding a new entry here: GDB 7.9 and
5571 earlier assume that all register "numbers" that start
5572 with an hex digit are real register numbers. Make sure
5573 the server only sends such a packet if it knows the
5574 client understands it. */
c8e38a49 5575
1f10ba14
PA
5576 if (strncmp (p, "thread", p1 - p) == 0)
5577 event->ptid = read_ptid (++p1, &p);
5578 else if ((strncmp (p, "watch", p1 - p) == 0)
5579 || (strncmp (p, "rwatch", p1 - p) == 0)
5580 || (strncmp (p, "awatch", p1 - p) == 0))
cea39f65 5581 {
f7e6eed5 5582 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
5583 p = unpack_varlen_hex (++p1, &addr);
5584 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 5585 }
f7e6eed5
PA
5586 else if (strncmp (p, "swbreak", p1 - p) == 0)
5587 {
5588 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5589
5590 /* Make sure the stub doesn't forget to indicate support
5591 with qSupported. */
5592 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5593 error (_("Unexpected swbreak stop reason"));
5594
5595 /* The value part is documented as "must be empty",
5596 though we ignore it, in case we ever decide to make
5597 use of it in a backward compatible way. */
5598 p = skip_to_semicolon (p1 + 1);
5599 }
5600 else if (strncmp (p, "hwbreak", p1 - p) == 0)
5601 {
5602 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5603
5604 /* Make sure the stub doesn't forget to indicate support
5605 with qSupported. */
5606 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5607 error (_("Unexpected hwbreak stop reason"));
5608
5609 /* See above. */
5610 p = skip_to_semicolon (p1 + 1);
5611 }
1f10ba14 5612 else if (strncmp (p, "library", p1 - p) == 0)
cea39f65 5613 {
1f10ba14
PA
5614 event->ws.kind = TARGET_WAITKIND_LOADED;
5615 p = skip_to_semicolon (p1 + 1);
5616 }
5617 else if (strncmp (p, "replaylog", p1 - p) == 0)
5618 {
5619 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5620 /* p1 will indicate "begin" or "end", but it makes
5621 no difference for now, so ignore it. */
5622 p = skip_to_semicolon (p1 + 1);
5623 }
5624 else if (strncmp (p, "core", p1 - p) == 0)
5625 {
5626 ULONGEST c;
a744cf53 5627
1f10ba14
PA
5628 p = unpack_varlen_hex (++p1, &c);
5629 event->core = c;
cea39f65
MS
5630 }
5631 else
5632 {
1f10ba14
PA
5633 ULONGEST pnum;
5634 char *p_temp;
5635
5636 /* Maybe a real ``P'' register number. */
5637 p_temp = unpack_varlen_hex (p, &pnum);
5638 /* If the first invalid character is the colon, we got a
5639 register number. Otherwise, it's an unknown stop
5640 reason. */
5641 if (p_temp == p1)
5642 {
5643 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5644 cached_reg_t cached_reg;
43ff13b4 5645
1f10ba14
PA
5646 if (reg == NULL)
5647 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 5648Packet: '%s'\n"),
1f10ba14 5649 hex_string (pnum), p, buf);
c8e38a49 5650
1f10ba14 5651 cached_reg.num = reg->regnum;
4100683b 5652
1f10ba14
PA
5653 p = p1 + 1;
5654 fieldsize = hex2bin (p, cached_reg.data,
5655 register_size (target_gdbarch (),
5656 reg->regnum));
5657 p += 2 * fieldsize;
5658 if (fieldsize < register_size (target_gdbarch (),
5659 reg->regnum))
5660 warning (_("Remote reply is too short: %s"), buf);
74531fed 5661
1f10ba14
PA
5662 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5663 }
5664 else
5665 {
5666 /* Not a number. Silently skip unknown optional
5667 info. */
5668 p = skip_to_semicolon (p1 + 1);
5669 }
cea39f65 5670 }
c8e38a49 5671
cea39f65
MS
5672 if (*p != ';')
5673 error (_("Remote register badly formatted: %s\nhere: %s"),
5674 buf, p);
5675 ++p;
5676 }
5b5596ff
PA
5677
5678 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5679 break;
5680
c8e38a49
PA
5681 /* fall through */
5682 case 'S': /* Old style status, just signal only. */
3a09da41
PA
5683 {
5684 int sig;
5685
5686 event->ws.kind = TARGET_WAITKIND_STOPPED;
5687 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5688 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5689 event->ws.value.sig = (enum gdb_signal) sig;
5690 else
5691 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5692 }
c8e38a49
PA
5693 break;
5694 case 'W': /* Target exited. */
5695 case 'X':
5696 {
5697 char *p;
5698 int pid;
5699 ULONGEST value;
82f73884 5700
c8e38a49
PA
5701 /* GDB used to accept only 2 hex chars here. Stubs should
5702 only send more if they detect GDB supports multi-process
5703 support. */
5704 p = unpack_varlen_hex (&buf[1], &value);
82f73884 5705
c8e38a49
PA
5706 if (buf[0] == 'W')
5707 {
5708 /* The remote process exited. */
74531fed
PA
5709 event->ws.kind = TARGET_WAITKIND_EXITED;
5710 event->ws.value.integer = value;
c8e38a49
PA
5711 }
5712 else
5713 {
5714 /* The remote process exited with a signal. */
74531fed 5715 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
5716 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5717 event->ws.value.sig = (enum gdb_signal) value;
5718 else
5719 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 5720 }
82f73884 5721
c8e38a49
PA
5722 /* If no process is specified, assume inferior_ptid. */
5723 pid = ptid_get_pid (inferior_ptid);
5724 if (*p == '\0')
5725 ;
5726 else if (*p == ';')
5727 {
5728 p++;
5729
0b24eb2d 5730 if (*p == '\0')
82f73884 5731 ;
61012eef 5732 else if (startswith (p, "process:"))
82f73884 5733 {
c8e38a49 5734 ULONGEST upid;
a744cf53 5735
c8e38a49
PA
5736 p += sizeof ("process:") - 1;
5737 unpack_varlen_hex (p, &upid);
5738 pid = upid;
82f73884
PA
5739 }
5740 else
5741 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 5742 }
c8e38a49
PA
5743 else
5744 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
5745 event->ptid = pid_to_ptid (pid);
5746 }
5747 break;
5748 }
5749
5750 if (non_stop && ptid_equal (event->ptid, null_ptid))
5751 error (_("No process or thread specified in stop reply: %s"), buf);
5752}
5753
722247f1
YQ
5754/* When the stub wants to tell GDB about a new notification reply, it
5755 sends a notification (%Stop, for example). Those can come it at
5756 any time, hence, we have to make sure that any pending
5757 putpkt/getpkt sequence we're making is finished, before querying
5758 the stub for more events with the corresponding ack command
5759 (vStopped, for example). E.g., if we started a vStopped sequence
5760 immediately upon receiving the notification, something like this
5761 could happen:
74531fed
PA
5762
5763 1.1) --> Hg 1
5764 1.2) <-- OK
5765 1.3) --> g
5766 1.4) <-- %Stop
5767 1.5) --> vStopped
5768 1.6) <-- (registers reply to step #1.3)
5769
5770 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5771 query.
5772
796cb314 5773 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
5774 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5775 doing whatever we were doing:
5776
5777 2.1) --> Hg 1
5778 2.2) <-- OK
5779 2.3) --> g
5780 2.4) <-- %Stop
5781 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5782 2.5) <-- (registers reply to step #2.3)
5783
5784 Eventualy after step #2.5, we return to the event loop, which
5785 notices there's an event on the
5786 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5787 associated callback --- the function below. At this point, we're
5788 always safe to start a vStopped sequence. :
5789
5790 2.6) --> vStopped
5791 2.7) <-- T05 thread:2
5792 2.8) --> vStopped
5793 2.9) --> OK
5794*/
5795
722247f1
YQ
5796void
5797remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
5798{
5799 struct remote_state *rs = get_remote_state ();
74531fed 5800
f48ff2a7 5801 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 5802 {
722247f1
YQ
5803 if (notif_debug)
5804 fprintf_unfiltered (gdb_stdlog,
5805 "notif: process: '%s' ack pending event\n",
5806 nc->name);
74531fed 5807
722247f1 5808 /* acknowledge */
f48ff2a7
YQ
5809 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
5810 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
5811
5812 while (1)
5813 {
5814 getpkt (&rs->buf, &rs->buf_size, 0);
5815 if (strcmp (rs->buf, "OK") == 0)
5816 break;
5817 else
722247f1 5818 remote_notif_ack (nc, rs->buf);
74531fed
PA
5819 }
5820 }
722247f1
YQ
5821 else
5822 {
5823 if (notif_debug)
5824 fprintf_unfiltered (gdb_stdlog,
5825 "notif: process: '%s' no pending reply\n",
5826 nc->name);
5827 }
74531fed
PA
5828}
5829
74531fed
PA
5830/* Called when it is decided that STOP_REPLY holds the info of the
5831 event that is to be returned to the core. This function always
5832 destroys STOP_REPLY. */
5833
5834static ptid_t
5835process_stop_reply (struct stop_reply *stop_reply,
5836 struct target_waitstatus *status)
5837{
5838 ptid_t ptid;
5839
5840 *status = stop_reply->ws;
5841 ptid = stop_reply->ptid;
5842
5843 /* If no thread/process was reported by the stub, assume the current
5844 inferior. */
5845 if (ptid_equal (ptid, null_ptid))
5846 ptid = inferior_ptid;
5847
5f3563ea
PA
5848 if (status->kind != TARGET_WAITKIND_EXITED
5849 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 5850 {
ee154bee
TT
5851 struct remote_state *rs = get_remote_state ();
5852
5f3563ea
PA
5853 /* Expedited registers. */
5854 if (stop_reply->regcache)
5855 {
217f1f79 5856 struct regcache *regcache
f5656ead 5857 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
5858 cached_reg_t *reg;
5859 int ix;
5860
5861 for (ix = 0;
5862 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5863 ix++)
217f1f79 5864 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
5865 VEC_free (cached_reg_t, stop_reply->regcache);
5866 }
74531fed 5867
f7e6eed5 5868 rs->stop_reason = stop_reply->stop_reason;
ee154bee 5869 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
5870
5871 remote_notice_new_inferior (ptid, 0);
dc146f7c 5872 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
5873 }
5874
74531fed
PA
5875 stop_reply_xfree (stop_reply);
5876 return ptid;
5877}
5878
5879/* The non-stop mode version of target_wait. */
5880
5881static ptid_t
47608cb1 5882remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5883{
5884 struct remote_state *rs = get_remote_state ();
74531fed
PA
5885 struct stop_reply *stop_reply;
5886 int ret;
fee9eda9 5887 int is_notif = 0;
74531fed
PA
5888
5889 /* If in non-stop mode, get out of getpkt even if a
5890 notification is received. */
5891
5892 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5893 0 /* forever */, &is_notif);
74531fed
PA
5894 while (1)
5895 {
fee9eda9 5896 if (ret != -1 && !is_notif)
74531fed
PA
5897 switch (rs->buf[0])
5898 {
5899 case 'E': /* Error of some sort. */
5900 /* We're out of sync with the target now. Did it continue
5901 or not? We can't tell which thread it was in non-stop,
5902 so just ignore this. */
5903 warning (_("Remote failure reply: %s"), rs->buf);
5904 break;
5905 case 'O': /* Console output. */
5906 remote_console_output (rs->buf + 1);
5907 break;
5908 default:
5909 warning (_("Invalid remote reply: %s"), rs->buf);
5910 break;
5911 }
5912
5913 /* Acknowledge a pending stop reply that may have arrived in the
5914 mean time. */
f48ff2a7 5915 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 5916 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
5917
5918 /* If indeed we noticed a stop reply, we're done. */
5919 stop_reply = queued_stop_reply (ptid);
5920 if (stop_reply != NULL)
5921 return process_stop_reply (stop_reply, status);
5922
47608cb1 5923 /* Still no event. If we're just polling for an event, then
74531fed 5924 return to the event loop. */
47608cb1 5925 if (options & TARGET_WNOHANG)
74531fed
PA
5926 {
5927 status->kind = TARGET_WAITKIND_IGNORE;
5928 return minus_one_ptid;
5929 }
5930
47608cb1 5931 /* Otherwise do a blocking wait. */
74531fed 5932 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 5933 1 /* forever */, &is_notif);
74531fed
PA
5934 }
5935}
5936
5937/* Wait until the remote machine stops, then return, storing status in
5938 STATUS just as `wait' would. */
5939
5940static ptid_t
47608cb1 5941remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5942{
5943 struct remote_state *rs = get_remote_state ();
74531fed 5944 ptid_t event_ptid = null_ptid;
cea39f65 5945 char *buf;
74531fed
PA
5946 struct stop_reply *stop_reply;
5947
47608cb1
PA
5948 again:
5949
74531fed
PA
5950 status->kind = TARGET_WAITKIND_IGNORE;
5951 status->value.integer = 0;
5952
5953 stop_reply = queued_stop_reply (ptid);
5954 if (stop_reply != NULL)
5955 return process_stop_reply (stop_reply, status);
5956
5957 if (rs->cached_wait_status)
5958 /* Use the cached wait status, but only once. */
5959 rs->cached_wait_status = 0;
5960 else
5961 {
5962 int ret;
722247f1 5963 int is_notif;
74531fed
PA
5964
5965 if (!target_is_async_p ())
5966 {
934b9bac 5967 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
5968 /* If the user hit C-c before this packet, or between packets,
5969 pretend that it was hit right here. */
522002f9 5970 if (check_quit_flag ())
74531fed 5971 {
522002f9 5972 clear_quit_flag ();
934b9bac 5973 sync_remote_interrupt (SIGINT);
74531fed
PA
5974 }
5975 }
5976
5977 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5978 _never_ wait for ever -> test on target_is_async_p().
5979 However, before we do that we need to ensure that the caller
5980 knows how to take the target into/out of async mode. */
722247f1
YQ
5981 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5982 wait_forever_enabled_p, &is_notif);
5983
5e1b953b
SDJ
5984 if (!target_is_async_p ())
5985 signal (SIGINT, ofunc);
5986
722247f1
YQ
5987 /* GDB gets a notification. Return to core as this event is
5988 not interesting. */
5989 if (ret != -1 && is_notif)
5990 return minus_one_ptid;
74531fed
PA
5991 }
5992
5993 buf = rs->buf;
5994
f7e6eed5 5995 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed
PA
5996
5997 /* We got something. */
5998 rs->waiting_for_stop_reply = 0;
5999
3a29589a
DJ
6000 /* Assume that the target has acknowledged Ctrl-C unless we receive
6001 an 'F' or 'O' packet. */
6002 if (buf[0] != 'F' && buf[0] != 'O')
6003 rs->ctrlc_pending_p = 0;
6004
74531fed
PA
6005 switch (buf[0])
6006 {
6007 case 'E': /* Error of some sort. */
6008 /* We're out of sync with the target now. Did it continue or
6009 not? Not is more likely, so report a stop. */
6010 warning (_("Remote failure reply: %s"), buf);
6011 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6012 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6013 break;
6014 case 'F': /* File-I/O request. */
3a29589a
DJ
6015 remote_fileio_request (buf, rs->ctrlc_pending_p);
6016 rs->ctrlc_pending_p = 0;
74531fed
PA
6017 break;
6018 case 'T': case 'S': case 'X': case 'W':
6019 {
722247f1
YQ
6020 struct stop_reply *stop_reply
6021 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6022 rs->buf);
74531fed 6023
74531fed 6024 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6025 break;
6026 }
6027 case 'O': /* Console output. */
6028 remote_console_output (buf + 1);
e24a49d8 6029
c8e38a49
PA
6030 /* The target didn't really stop; keep waiting. */
6031 rs->waiting_for_stop_reply = 1;
e24a49d8 6032
c8e38a49
PA
6033 break;
6034 case '\0':
b73be471 6035 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6036 {
6037 /* Zero length reply means that we tried 'S' or 'C' and the
6038 remote system doesn't support it. */
6039 target_terminal_ours_for_output ();
6040 printf_filtered
6041 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6042 gdb_signal_to_name (rs->last_sent_signal));
6043 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6044 target_terminal_inferior ();
6045
280ceea3 6046 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6047 putpkt ((char *) buf);
6048
6049 /* We just told the target to resume, so a stop reply is in
6050 order. */
e24a49d8 6051 rs->waiting_for_stop_reply = 1;
c8e38a49 6052 break;
43ff13b4 6053 }
c8e38a49
PA
6054 /* else fallthrough */
6055 default:
6056 warning (_("Invalid remote reply: %s"), buf);
6057 /* Keep waiting. */
6058 rs->waiting_for_stop_reply = 1;
6059 break;
43ff13b4 6060 }
c8e38a49 6061
c8e38a49 6062 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6063 {
6064 /* Nothing interesting happened. If we're doing a non-blocking
6065 poll, we're done. Otherwise, go back to waiting. */
6066 if (options & TARGET_WNOHANG)
6067 return minus_one_ptid;
6068 else
6069 goto again;
6070 }
74531fed
PA
6071 else if (status->kind != TARGET_WAITKIND_EXITED
6072 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6073 {
6074 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6075 record_currthread (rs, event_ptid);
82f73884
PA
6076 else
6077 event_ptid = inferior_ptid;
43ff13b4 6078 }
74531fed
PA
6079 else
6080 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6081 record_currthread (rs, minus_one_ptid);
79d7f229 6082
82f73884 6083 return event_ptid;
43ff13b4
JM
6084}
6085
74531fed
PA
6086/* Wait until the remote machine stops, then return, storing status in
6087 STATUS just as `wait' would. */
6088
c8e38a49 6089static ptid_t
117de6a9 6090remote_wait (struct target_ops *ops,
47608cb1 6091 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6092{
6093 ptid_t event_ptid;
6094
74531fed 6095 if (non_stop)
47608cb1 6096 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6097 else
47608cb1 6098 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6099
d9d41e78 6100 if (target_is_async_p ())
c8e38a49 6101 {
74531fed
PA
6102 /* If there are are events left in the queue tell the event loop
6103 to return here. */
722247f1 6104 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6105 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6106 }
c8e38a49
PA
6107
6108 return event_ptid;
6109}
6110
74ca34ce 6111/* Fetch a single register using a 'p' packet. */
c906108c 6112
b96ec7ac 6113static int
56be3814 6114fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6115{
6116 struct remote_state *rs = get_remote_state ();
2e9f7625 6117 char *buf, *p;
b96ec7ac
AC
6118 char regp[MAX_REGISTER_SIZE];
6119 int i;
6120
4082afcc 6121 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6122 return 0;
6123
6124 if (reg->pnum == -1)
6125 return 0;
6126
2e9f7625 6127 p = rs->buf;
fcad0fa4 6128 *p++ = 'p';
74ca34ce 6129 p += hexnumstr (p, reg->pnum);
fcad0fa4 6130 *p++ = '\0';
1f4437a4
MS
6131 putpkt (rs->buf);
6132 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6133
2e9f7625
DJ
6134 buf = rs->buf;
6135
74ca34ce
DJ
6136 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6137 {
6138 case PACKET_OK:
6139 break;
6140 case PACKET_UNKNOWN:
6141 return 0;
6142 case PACKET_ERROR:
27a9c0bf
MS
6143 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6144 gdbarch_register_name (get_regcache_arch (regcache),
6145 reg->regnum),
6146 buf);
74ca34ce 6147 }
3f9a994c
JB
6148
6149 /* If this register is unfetchable, tell the regcache. */
6150 if (buf[0] == 'x')
8480adf2 6151 {
56be3814 6152 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6153 return 1;
b96ec7ac 6154 }
b96ec7ac 6155
3f9a994c
JB
6156 /* Otherwise, parse and supply the value. */
6157 p = buf;
6158 i = 0;
6159 while (p[0] != 0)
6160 {
6161 if (p[1] == 0)
74ca34ce 6162 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6163
6164 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6165 p += 2;
6166 }
56be3814 6167 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6168 return 1;
b96ec7ac
AC
6169}
6170
74ca34ce
DJ
6171/* Fetch the registers included in the target's 'g' packet. */
6172
29709017
DJ
6173static int
6174send_g_packet (void)
c906108c 6175{
d01949b6 6176 struct remote_state *rs = get_remote_state ();
cea39f65 6177 int buf_len;
c906108c 6178
bba74b36 6179 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6180 remote_send (&rs->buf, &rs->buf_size);
c906108c 6181
29709017
DJ
6182 /* We can get out of synch in various cases. If the first character
6183 in the buffer is not a hex character, assume that has happened
6184 and try to fetch another packet to read. */
6185 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6186 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6187 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6188 && rs->buf[0] != 'x') /* New: unavailable register value. */
6189 {
6190 if (remote_debug)
6191 fprintf_unfiltered (gdb_stdlog,
6192 "Bad register packet; fetching a new packet\n");
6193 getpkt (&rs->buf, &rs->buf_size, 0);
6194 }
6195
74ca34ce
DJ
6196 buf_len = strlen (rs->buf);
6197
6198 /* Sanity check the received packet. */
6199 if (buf_len % 2 != 0)
6200 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6201
6202 return buf_len / 2;
6203}
6204
6205static void
56be3814 6206process_g_packet (struct regcache *regcache)
29709017 6207{
4a22f64d 6208 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6209 struct remote_state *rs = get_remote_state ();
6210 struct remote_arch_state *rsa = get_remote_arch_state ();
6211 int i, buf_len;
6212 char *p;
6213 char *regs;
6214
6215 buf_len = strlen (rs->buf);
6216
6217 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6218 if (buf_len > 2 * rsa->sizeof_g_packet)
6219 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6220
6221 /* Save the size of the packet sent to us by the target. It is used
6222 as a heuristic when determining the max size of packets that the
6223 target can safely receive. */
6224 if (rsa->actual_register_packet_size == 0)
6225 rsa->actual_register_packet_size = buf_len;
6226
6227 /* If this is smaller than we guessed the 'g' packet would be,
6228 update our records. A 'g' reply that doesn't include a register's
6229 value implies either that the register is not available, or that
6230 the 'p' packet must be used. */
6231 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6232 {
74ca34ce
DJ
6233 rsa->sizeof_g_packet = buf_len / 2;
6234
4a22f64d 6235 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6236 {
74ca34ce
DJ
6237 if (rsa->regs[i].pnum == -1)
6238 continue;
6239
6240 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6241 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6242 else
74ca34ce 6243 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6244 }
74ca34ce 6245 }
b323314b 6246
74ca34ce 6247 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6248
6249 /* Unimplemented registers read as all bits zero. */
ea9c271d 6250 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6251
c906108c
SS
6252 /* Reply describes registers byte by byte, each byte encoded as two
6253 hex characters. Suck them all up, then supply them to the
6254 register cacheing/storage mechanism. */
6255
74ca34ce 6256 p = rs->buf;
ea9c271d 6257 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6258 {
74ca34ce
DJ
6259 if (p[0] == 0 || p[1] == 0)
6260 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6261 internal_error (__FILE__, __LINE__,
9b20d036 6262 _("unexpected end of 'g' packet reply"));
74ca34ce 6263
c906108c 6264 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6265 regs[i] = 0; /* 'x' */
c906108c
SS
6266 else
6267 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6268 p += 2;
6269 }
6270
a744cf53
MS
6271 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6272 {
6273 struct packet_reg *r = &rsa->regs[i];
6274
6275 if (r->in_g_packet)
6276 {
6277 if (r->offset * 2 >= strlen (rs->buf))
6278 /* This shouldn't happen - we adjusted in_g_packet above. */
6279 internal_error (__FILE__, __LINE__,
9b20d036 6280 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6281 else if (rs->buf[r->offset * 2] == 'x')
6282 {
6283 gdb_assert (r->offset * 2 < strlen (rs->buf));
6284 /* The register isn't available, mark it as such (at
6285 the same time setting the value to zero). */
6286 regcache_raw_supply (regcache, r->regnum, NULL);
6287 }
6288 else
6289 regcache_raw_supply (regcache, r->regnum,
6290 regs + r->offset);
6291 }
6292 }
c906108c
SS
6293}
6294
29709017 6295static void
56be3814 6296fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6297{
6298 send_g_packet ();
56be3814 6299 process_g_packet (regcache);
29709017
DJ
6300}
6301
e6e4e701
PA
6302/* Make the remote selected traceframe match GDB's selected
6303 traceframe. */
6304
6305static void
6306set_remote_traceframe (void)
6307{
6308 int newnum;
262e1174 6309 struct remote_state *rs = get_remote_state ();
e6e4e701 6310
262e1174 6311 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6312 return;
6313
6314 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6315 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6316
6317 newnum = target_trace_find (tfind_number,
6318 get_traceframe_number (), 0, 0, NULL);
6319
6320 /* Should not happen. If it does, all bets are off. */
6321 if (newnum != get_traceframe_number ())
6322 warning (_("could not set remote traceframe"));
6323}
6324
74ca34ce 6325static void
28439f5e
PA
6326remote_fetch_registers (struct target_ops *ops,
6327 struct regcache *regcache, int regnum)
74ca34ce 6328{
74ca34ce
DJ
6329 struct remote_arch_state *rsa = get_remote_arch_state ();
6330 int i;
6331
e6e4e701 6332 set_remote_traceframe ();
79d7f229 6333 set_general_thread (inferior_ptid);
74ca34ce
DJ
6334
6335 if (regnum >= 0)
6336 {
6337 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6338
74ca34ce
DJ
6339 gdb_assert (reg != NULL);
6340
6341 /* If this register might be in the 'g' packet, try that first -
6342 we are likely to read more than one register. If this is the
6343 first 'g' packet, we might be overly optimistic about its
6344 contents, so fall back to 'p'. */
6345 if (reg->in_g_packet)
6346 {
56be3814 6347 fetch_registers_using_g (regcache);
74ca34ce
DJ
6348 if (reg->in_g_packet)
6349 return;
6350 }
6351
56be3814 6352 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6353 return;
6354
6355 /* This register is not available. */
56be3814 6356 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6357
6358 return;
6359 }
6360
56be3814 6361 fetch_registers_using_g (regcache);
74ca34ce 6362
4a22f64d 6363 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6364 if (!rsa->regs[i].in_g_packet)
56be3814 6365 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6366 {
6367 /* This register is not available. */
56be3814 6368 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6369 }
6370}
6371
c906108c
SS
6372/* Prepare to store registers. Since we may send them all (using a
6373 'G' request), we have to read out the ones we don't want to change
6374 first. */
6375
c5aa993b 6376static void
f32dbf8c 6377remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6378{
ea9c271d 6379 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6380 int i;
cfd77fa1 6381 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6382
c906108c 6383 /* Make sure the entire registers array is valid. */
4082afcc 6384 switch (packet_support (PACKET_P))
5a2468f5
JM
6385 {
6386 case PACKET_DISABLE:
6387 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6388 /* Make sure all the necessary registers are cached. */
4a22f64d 6389 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6390 if (rsa->regs[i].in_g_packet)
316f2060 6391 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6392 break;
6393 case PACKET_ENABLE:
6394 break;
6395 }
6396}
6397
ad10f812 6398/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6399 packet was not recognized. */
5a2468f5
JM
6400
6401static int
1f4437a4
MS
6402store_register_using_P (const struct regcache *regcache,
6403 struct packet_reg *reg)
5a2468f5 6404{
4a22f64d 6405 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6406 struct remote_state *rs = get_remote_state ();
5a2468f5 6407 /* Try storing a single register. */
6d820c5c 6408 char *buf = rs->buf;
cfd77fa1 6409 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6410 char *p;
5a2468f5 6411
4082afcc 6412 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
6413 return 0;
6414
6415 if (reg->pnum == -1)
6416 return 0;
6417
ea9c271d 6418 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6419 p = buf + strlen (buf);
56be3814 6420 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6421 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6422 putpkt (rs->buf);
6423 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6424
74ca34ce
DJ
6425 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6426 {
6427 case PACKET_OK:
6428 return 1;
6429 case PACKET_ERROR:
27a9c0bf
MS
6430 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6431 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6432 case PACKET_UNKNOWN:
6433 return 0;
6434 default:
6435 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6436 }
c906108c
SS
6437}
6438
23860348
MS
6439/* Store register REGNUM, or all registers if REGNUM == -1, from the
6440 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6441
6442static void
56be3814 6443store_registers_using_G (const struct regcache *regcache)
c906108c 6444{
d01949b6 6445 struct remote_state *rs = get_remote_state ();
ea9c271d 6446 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6447 gdb_byte *regs;
c906108c
SS
6448 char *p;
6449
193cb69f
AC
6450 /* Extract all the registers in the regcache copying them into a
6451 local buffer. */
6452 {
b323314b 6453 int i;
a744cf53 6454
ea9c271d
DJ
6455 regs = alloca (rsa->sizeof_g_packet);
6456 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6457 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6458 {
ea9c271d 6459 struct packet_reg *r = &rsa->regs[i];
a744cf53 6460
b323314b 6461 if (r->in_g_packet)
56be3814 6462 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6463 }
6464 }
c906108c
SS
6465
6466 /* Command describes registers byte by byte,
6467 each byte encoded as two hex characters. */
6d820c5c 6468 p = rs->buf;
193cb69f 6469 *p++ = 'G';
74ca34ce
DJ
6470 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6471 updated. */
6472 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6473 putpkt (rs->buf);
6474 getpkt (&rs->buf, &rs->buf_size, 0);
6475 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6476 error (_("Could not write registers; remote failure reply '%s'"),
6477 rs->buf);
c906108c 6478}
74ca34ce
DJ
6479
6480/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6481 of the register cache buffer. FIXME: ignores errors. */
6482
6483static void
28439f5e
PA
6484remote_store_registers (struct target_ops *ops,
6485 struct regcache *regcache, int regnum)
74ca34ce 6486{
74ca34ce
DJ
6487 struct remote_arch_state *rsa = get_remote_arch_state ();
6488 int i;
6489
e6e4e701 6490 set_remote_traceframe ();
79d7f229 6491 set_general_thread (inferior_ptid);
74ca34ce
DJ
6492
6493 if (regnum >= 0)
6494 {
6495 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6496
74ca34ce
DJ
6497 gdb_assert (reg != NULL);
6498
6499 /* Always prefer to store registers using the 'P' packet if
6500 possible; we often change only a small number of registers.
6501 Sometimes we change a larger number; we'd need help from a
6502 higher layer to know to use 'G'. */
56be3814 6503 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6504 return;
6505
6506 /* For now, don't complain if we have no way to write the
6507 register. GDB loses track of unavailable registers too
6508 easily. Some day, this may be an error. We don't have
0df8b418 6509 any way to read the register, either... */
74ca34ce
DJ
6510 if (!reg->in_g_packet)
6511 return;
6512
56be3814 6513 store_registers_using_G (regcache);
74ca34ce
DJ
6514 return;
6515 }
6516
56be3814 6517 store_registers_using_G (regcache);
74ca34ce 6518
4a22f64d 6519 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6520 if (!rsa->regs[i].in_g_packet)
56be3814 6521 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6522 /* See above for why we do not issue an error here. */
6523 continue;
6524}
c906108c
SS
6525\f
6526
6527/* Return the number of hex digits in num. */
6528
6529static int
fba45db2 6530hexnumlen (ULONGEST num)
c906108c
SS
6531{
6532 int i;
6533
6534 for (i = 0; num != 0; i++)
6535 num >>= 4;
6536
6537 return max (i, 1);
6538}
6539
2df3850c 6540/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
6541
6542static int
fba45db2 6543hexnumstr (char *buf, ULONGEST num)
c906108c 6544{
c906108c 6545 int len = hexnumlen (num);
a744cf53 6546
2df3850c
JM
6547 return hexnumnstr (buf, num, len);
6548}
6549
c906108c 6550
2df3850c 6551/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 6552
2df3850c 6553static int
fba45db2 6554hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
6555{
6556 int i;
6557
6558 buf[width] = '\0';
6559
6560 for (i = width - 1; i >= 0; i--)
c906108c 6561 {
c5aa993b 6562 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
6563 num >>= 4;
6564 }
6565
2df3850c 6566 return width;
c906108c
SS
6567}
6568
23860348 6569/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
6570
6571static CORE_ADDR
fba45db2 6572remote_address_masked (CORE_ADDR addr)
c906108c 6573{
883b9c6c 6574 unsigned int address_size = remote_address_size;
a744cf53 6575
911c95a5
UW
6576 /* If "remoteaddresssize" was not set, default to target address size. */
6577 if (!address_size)
f5656ead 6578 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
6579
6580 if (address_size > 0
6581 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
6582 {
6583 /* Only create a mask when that mask can safely be constructed
23860348 6584 in a ULONGEST variable. */
c906108c 6585 ULONGEST mask = 1;
a744cf53 6586
911c95a5 6587 mask = (mask << address_size) - 1;
c906108c
SS
6588 addr &= mask;
6589 }
6590 return addr;
6591}
6592
6593/* Determine whether the remote target supports binary downloading.
6594 This is accomplished by sending a no-op memory write of zero length
6595 to the target at the specified address. It does not suffice to send
23860348
MS
6596 the whole packet, since many stubs strip the eighth bit and
6597 subsequently compute a wrong checksum, which causes real havoc with
6598 remote_write_bytes.
7a292a7a 6599
96baa820 6600 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 6601 clean. In cases like this, the user should clear "remote
23860348 6602 X-packet". */
96baa820 6603
c906108c 6604static void
fba45db2 6605check_binary_download (CORE_ADDR addr)
c906108c 6606{
d01949b6 6607 struct remote_state *rs = get_remote_state ();
24b06219 6608
4082afcc 6609 switch (packet_support (PACKET_X))
c906108c 6610 {
96baa820
JM
6611 case PACKET_DISABLE:
6612 break;
6613 case PACKET_ENABLE:
6614 break;
6615 case PACKET_SUPPORT_UNKNOWN:
6616 {
96baa820 6617 char *p;
802188a7 6618
2e9f7625 6619 p = rs->buf;
96baa820
JM
6620 *p++ = 'X';
6621 p += hexnumstr (p, (ULONGEST) addr);
6622 *p++ = ',';
6623 p += hexnumstr (p, (ULONGEST) 0);
6624 *p++ = ':';
6625 *p = '\0';
802188a7 6626
2e9f7625 6627 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6628 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6629
2e9f7625 6630 if (rs->buf[0] == '\0')
96baa820
JM
6631 {
6632 if (remote_debug)
6633 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
6634 "binary downloading NOT "
6635 "supported by target\n");
444abaca 6636 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
6637 }
6638 else
6639 {
6640 if (remote_debug)
6641 fprintf_unfiltered (gdb_stdlog,
64b9b334 6642 "binary downloading supported by target\n");
444abaca 6643 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
6644 }
6645 break;
6646 }
c906108c
SS
6647 }
6648}
6649
6650/* Write memory data directly to the remote machine.
6651 This does not inform the data cache; the data cache uses this.
a76d924d 6652 HEADER is the starting part of the packet.
c906108c
SS
6653 MEMADDR is the address in the remote memory space.
6654 MYADDR is the address of the buffer in our space.
6655 LEN is the number of bytes.
a76d924d
DJ
6656 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6657 should send data as binary ('X'), or hex-encoded ('M').
6658
6659 The function creates packet of the form
6660 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6661
6662 where encoding of <DATA> is termined by PACKET_FORMAT.
6663
6664 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6665 are omitted.
6666
9b409511
YQ
6667 Return the transferred status, error or OK (an
6668 'enum target_xfer_status' value). Save the number of bytes
6669 transferred in *XFERED_LEN. Only transfer a single packet. */
c906108c 6670
9b409511 6671static enum target_xfer_status
a76d924d 6672remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5d6df423 6673 const gdb_byte *myaddr, ULONGEST len,
9b409511
YQ
6674 ULONGEST *xfered_len, char packet_format,
6675 int use_length)
c906108c 6676{
6d820c5c 6677 struct remote_state *rs = get_remote_state ();
cfd77fa1 6678 char *p;
a76d924d
DJ
6679 char *plen = NULL;
6680 int plenlen = 0;
917317f4
JM
6681 int todo;
6682 int nr_bytes;
a257b5bb 6683 int payload_size;
6765f3e5 6684 int payload_length;
a76d924d
DJ
6685 int header_length;
6686
6687 if (packet_format != 'X' && packet_format != 'M')
6688 internal_error (__FILE__, __LINE__,
9b20d036 6689 _("remote_write_bytes_aux: bad packet format"));
c906108c 6690
5d6df423 6691 if (len == 0)
9b409511 6692 return TARGET_XFER_EOF;
b2182ed2 6693
3de11b2e 6694 payload_size = get_memory_write_packet_size ();
2bc416ba 6695
6d820c5c
DJ
6696 /* The packet buffer will be large enough for the payload;
6697 get_memory_packet_size ensures this. */
a76d924d 6698 rs->buf[0] = '\0';
c906108c 6699
a257b5bb 6700 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
6701 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6702
a76d924d
DJ
6703 payload_size -= strlen ("$,:#NN");
6704 if (!use_length)
0df8b418 6705 /* The comma won't be used. */
a76d924d
DJ
6706 payload_size += 1;
6707 header_length = strlen (header);
6708 payload_size -= header_length;
3de11b2e 6709 payload_size -= hexnumlen (memaddr);
c906108c 6710
a76d924d 6711 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 6712
a76d924d
DJ
6713 strcat (rs->buf, header);
6714 p = rs->buf + strlen (header);
6715
6716 /* Compute a best guess of the number of bytes actually transfered. */
6717 if (packet_format == 'X')
c906108c 6718 {
23860348 6719 /* Best guess at number of bytes that will fit. */
a257b5bb 6720 todo = min (len, payload_size);
a76d924d
DJ
6721 if (use_length)
6722 payload_size -= hexnumlen (todo);
3de11b2e 6723 todo = min (todo, payload_size);
a76d924d
DJ
6724 }
6725 else
6726 {
23860348 6727 /* Num bytes that will fit. */
a257b5bb 6728 todo = min (len, payload_size / 2);
a76d924d
DJ
6729 if (use_length)
6730 payload_size -= hexnumlen (todo);
3de11b2e 6731 todo = min (todo, payload_size / 2);
917317f4 6732 }
a76d924d 6733
3de11b2e
NS
6734 if (todo <= 0)
6735 internal_error (__FILE__, __LINE__,
405f8e94 6736 _("minimum packet size too small to write data"));
802188a7 6737
6765f3e5
DJ
6738 /* If we already need another packet, then try to align the end
6739 of this packet to a useful boundary. */
6740 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6741 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6742
a257b5bb 6743 /* Append "<memaddr>". */
917317f4
JM
6744 memaddr = remote_address_masked (memaddr);
6745 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 6746
a76d924d
DJ
6747 if (use_length)
6748 {
6749 /* Append ",". */
6750 *p++ = ',';
802188a7 6751
a76d924d
DJ
6752 /* Append <len>. Retain the location/size of <len>. It may need to
6753 be adjusted once the packet body has been created. */
6754 plen = p;
6755 plenlen = hexnumstr (p, (ULONGEST) todo);
6756 p += plenlen;
6757 }
a257b5bb
AC
6758
6759 /* Append ":". */
917317f4
JM
6760 *p++ = ':';
6761 *p = '\0';
802188a7 6762
a257b5bb 6763 /* Append the packet body. */
a76d924d 6764 if (packet_format == 'X')
917317f4 6765 {
917317f4
JM
6766 /* Binary mode. Send target system values byte by byte, in
6767 increasing byte addresses. Only escape certain critical
6768 characters. */
bc20a4af
PA
6769 payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
6770 &nr_bytes, payload_size);
6765f3e5
DJ
6771
6772 /* If not all TODO bytes fit, then we'll need another packet. Make
9b7194bc
DJ
6773 a second try to keep the end of the packet aligned. Don't do
6774 this if the packet is tiny. */
6775 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6765f3e5
DJ
6776 {
6777 int new_nr_bytes;
6778
6779 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6780 - memaddr);
6781 if (new_nr_bytes != nr_bytes)
6782 payload_length = remote_escape_output (myaddr, new_nr_bytes,
bc20a4af 6783 (gdb_byte *) p, &nr_bytes,
6765f3e5
DJ
6784 payload_size);
6785 }
6786
6787 p += payload_length;
a76d924d 6788 if (use_length && nr_bytes < todo)
c906108c 6789 {
802188a7 6790 /* Escape chars have filled up the buffer prematurely,
917317f4
JM
6791 and we have actually sent fewer bytes than planned.
6792 Fix-up the length field of the packet. Use the same
6793 number of characters as before. */
917317f4
JM
6794 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6795 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 6796 }
a76d924d
DJ
6797 }
6798 else
6799 {
917317f4
JM
6800 /* Normal mode: Send target system values byte by byte, in
6801 increasing byte addresses. Each byte is encoded as a two hex
6802 value. */
2644f393 6803 nr_bytes = bin2hex (myaddr, p, todo);
aa6c0017 6804 p += 2 * nr_bytes;
c906108c 6805 }
802188a7 6806
2e9f7625 6807 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6808 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 6809
2e9f7625 6810 if (rs->buf[0] == 'E')
00d84524 6811 return TARGET_XFER_E_IO;
802188a7 6812
23860348
MS
6813 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6814 fewer bytes than we'd planned. */
9b409511
YQ
6815 *xfered_len = (ULONGEST) nr_bytes;
6816 return TARGET_XFER_OK;
c906108c
SS
6817}
6818
a76d924d
DJ
6819/* Write memory data directly to the remote machine.
6820 This does not inform the data cache; the data cache uses this.
6821 MEMADDR is the address in the remote memory space.
6822 MYADDR is the address of the buffer in our space.
6823 LEN is the number of bytes.
6824
9b409511
YQ
6825 Return the transferred status, error or OK (an
6826 'enum target_xfer_status' value). Save the number of bytes
6827 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 6828
9b409511
YQ
6829static enum target_xfer_status
6830remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
6831 ULONGEST *xfered_len)
a76d924d
DJ
6832{
6833 char *packet_format = 0;
6834
6835 /* Check whether the target supports binary download. */
6836 check_binary_download (memaddr);
6837
4082afcc 6838 switch (packet_support (PACKET_X))
a76d924d
DJ
6839 {
6840 case PACKET_ENABLE:
6841 packet_format = "X";
6842 break;
6843 case PACKET_DISABLE:
6844 packet_format = "M";
6845 break;
6846 case PACKET_SUPPORT_UNKNOWN:
6847 internal_error (__FILE__, __LINE__,
6848 _("remote_write_bytes: bad internal state"));
6849 default:
6850 internal_error (__FILE__, __LINE__, _("bad switch"));
6851 }
6852
6853 return remote_write_bytes_aux (packet_format,
9b409511
YQ
6854 memaddr, myaddr, len, xfered_len,
6855 packet_format[0], 1);
a76d924d
DJ
6856}
6857
9217e74e
YQ
6858/* Read memory data directly from the remote machine.
6859 This does not use the data cache; the data cache uses this.
6860 MEMADDR is the address in the remote memory space.
6861 MYADDR is the address of the buffer in our space.
6862 LEN is the number of bytes.
6863
6864 Return the transferred status, error or OK (an
6865 'enum target_xfer_status' value). Save the number of bytes
6866 transferred in *XFERED_LEN. */
6867
6868static enum target_xfer_status
6869remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
6870 ULONGEST *xfered_len)
6871{
6872 struct remote_state *rs = get_remote_state ();
6873 int max_buf_size; /* Max size of packet output buffer. */
6874 char *p;
6875 int todo;
6876 int i;
6877
6878 max_buf_size = get_memory_read_packet_size ();
6879 /* The packet buffer will be large enough for the payload;
6880 get_memory_packet_size ensures this. */
6881
6882 /* Number if bytes that will fit. */
6883 todo = min (len, max_buf_size / 2);
6884
6885 /* Construct "m"<memaddr>","<len>". */
6886 memaddr = remote_address_masked (memaddr);
6887 p = rs->buf;
6888 *p++ = 'm';
6889 p += hexnumstr (p, (ULONGEST) memaddr);
6890 *p++ = ',';
6891 p += hexnumstr (p, (ULONGEST) todo);
6892 *p = '\0';
6893 putpkt (rs->buf);
6894 getpkt (&rs->buf, &rs->buf_size, 0);
6895 if (rs->buf[0] == 'E'
6896 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6897 && rs->buf[3] == '\0')
6898 return TARGET_XFER_E_IO;
6899 /* Reply describes memory byte by byte, each byte encoded as two hex
6900 characters. */
6901 p = rs->buf;
6902 i = hex2bin (p, myaddr, todo);
6903 /* Return what we have. Let higher layers handle partial reads. */
6904 *xfered_len = (ULONGEST) i;
6905 return TARGET_XFER_OK;
6906}
6907
b55fbac4
YQ
6908/* Using the set of read-only target sections of remote, read live
6909 read-only memory.
8acf9577
YQ
6910
6911 For interface/parameters/return description see target.h,
6912 to_xfer_partial. */
6913
6914static enum target_xfer_status
b55fbac4
YQ
6915remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
6916 ULONGEST memaddr, ULONGEST len,
6917 ULONGEST *xfered_len)
8acf9577
YQ
6918{
6919 struct target_section *secp;
6920 struct target_section_table *table;
6921
6922 secp = target_section_by_addr (ops, memaddr);
6923 if (secp != NULL
6924 && (bfd_get_section_flags (secp->the_bfd_section->owner,
6925 secp->the_bfd_section)
6926 & SEC_READONLY))
6927 {
6928 struct target_section *p;
6929 ULONGEST memend = memaddr + len;
6930
6931 table = target_get_section_table (ops);
6932
6933 for (p = table->sections; p < table->sections_end; p++)
6934 {
6935 if (memaddr >= p->addr)
6936 {
6937 if (memend <= p->endaddr)
6938 {
6939 /* Entire transfer is within this section. */
b55fbac4
YQ
6940 return remote_read_bytes_1 (memaddr, readbuf, len,
6941 xfered_len);
8acf9577
YQ
6942 }
6943 else if (memaddr >= p->endaddr)
6944 {
6945 /* This section ends before the transfer starts. */
6946 continue;
6947 }
6948 else
6949 {
6950 /* This section overlaps the transfer. Just do half. */
6951 len = p->endaddr - memaddr;
b55fbac4
YQ
6952 return remote_read_bytes_1 (memaddr, readbuf, len,
6953 xfered_len);
8acf9577
YQ
6954 }
6955 }
6956 }
6957 }
6958
6959 return TARGET_XFER_EOF;
6960}
6961
9217e74e
YQ
6962/* Similar to remote_read_bytes_1, but it reads from the remote stub
6963 first if the requested memory is unavailable in traceframe.
6964 Otherwise, fall back to remote_read_bytes_1. */
c906108c 6965
9b409511 6966static enum target_xfer_status
8acf9577
YQ
6967remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
6968 gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
c906108c 6969{
6b6aa828 6970 if (len == 0)
96c4f946 6971 return TARGET_XFER_EOF;
b2182ed2 6972
8acf9577
YQ
6973 if (get_traceframe_number () != -1)
6974 {
6975 VEC(mem_range_s) *available;
6976
6977 /* If we fail to get the set of available memory, then the
6978 target does not support querying traceframe info, and so we
6979 attempt reading from the traceframe anyway (assuming the
6980 target implements the old QTro packet then). */
6981 if (traceframe_available_memory (&available, memaddr, len))
6982 {
6983 struct cleanup *old_chain;
6984
6985 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
6986
6987 if (VEC_empty (mem_range_s, available)
6988 || VEC_index (mem_range_s, available, 0)->start != memaddr)
6989 {
6990 enum target_xfer_status res;
6991
6992 /* Don't read into the traceframe's available
6993 memory. */
6994 if (!VEC_empty (mem_range_s, available))
6995 {
6996 LONGEST oldlen = len;
6997
6998 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
6999 gdb_assert (len <= oldlen);
7000 }
7001
7002 do_cleanups (old_chain);
7003
7004 /* This goes through the topmost target again. */
b55fbac4 7005 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8acf9577
YQ
7006 len, xfered_len);
7007 if (res == TARGET_XFER_OK)
7008 return TARGET_XFER_OK;
7009 else
7010 {
7011 /* No use trying further, we know some memory starting
7012 at MEMADDR isn't available. */
7013 *xfered_len = len;
7014 return TARGET_XFER_UNAVAILABLE;
7015 }
7016 }
7017
7018 /* Don't try to read more than how much is available, in
7019 case the target implements the deprecated QTro packet to
7020 cater for older GDBs (the target's knowledge of read-only
7021 sections may be outdated by now). */
7022 len = VEC_index (mem_range_s, available, 0)->length;
7023
7024 do_cleanups (old_chain);
7025 }
7026 }
7027
9217e74e 7028 return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
c906108c 7029}
74531fed 7030
c906108c 7031\f
c906108c 7032
a76d924d
DJ
7033/* Sends a packet with content determined by the printf format string
7034 FORMAT and the remaining arguments, then gets the reply. Returns
7035 whether the packet was a success, a failure, or unknown. */
7036
77b64a49
PA
7037static enum packet_result remote_send_printf (const char *format, ...)
7038 ATTRIBUTE_PRINTF (1, 2);
7039
2c0b251b 7040static enum packet_result
a76d924d
DJ
7041remote_send_printf (const char *format, ...)
7042{
7043 struct remote_state *rs = get_remote_state ();
7044 int max_size = get_remote_packet_size ();
a76d924d 7045 va_list ap;
a744cf53 7046
a76d924d
DJ
7047 va_start (ap, format);
7048
7049 rs->buf[0] = '\0';
7050 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7051 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7052
7053 if (putpkt (rs->buf) < 0)
7054 error (_("Communication problem with target."));
7055
7056 rs->buf[0] = '\0';
7057 getpkt (&rs->buf, &rs->buf_size, 0);
7058
7059 return packet_check_result (rs->buf);
7060}
7061
7062static void
7063restore_remote_timeout (void *p)
7064{
7065 int value = *(int *)p;
a744cf53 7066
a76d924d
DJ
7067 remote_timeout = value;
7068}
7069
7070/* Flash writing can take quite some time. We'll set
7071 effectively infinite timeout for flash operations.
7072 In future, we'll need to decide on a better approach. */
7073static const int remote_flash_timeout = 1000;
7074
7075static void
7076remote_flash_erase (struct target_ops *ops,
7077 ULONGEST address, LONGEST length)
7078{
f5656ead 7079 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7080 int saved_remote_timeout = remote_timeout;
7081 enum packet_result ret;
a76d924d
DJ
7082 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7083 &saved_remote_timeout);
a744cf53 7084
a76d924d
DJ
7085 remote_timeout = remote_flash_timeout;
7086
7087 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7088 phex (address, addr_size),
a76d924d
DJ
7089 phex (length, 4));
7090 switch (ret)
7091 {
7092 case PACKET_UNKNOWN:
7093 error (_("Remote target does not support flash erase"));
7094 case PACKET_ERROR:
7095 error (_("Error erasing flash with vFlashErase packet"));
7096 default:
7097 break;
7098 }
7099
7100 do_cleanups (back_to);
7101}
7102
9b409511
YQ
7103static enum target_xfer_status
7104remote_flash_write (struct target_ops *ops, ULONGEST address,
7105 ULONGEST length, ULONGEST *xfered_len,
7106 const gdb_byte *data)
a76d924d
DJ
7107{
7108 int saved_remote_timeout = remote_timeout;
9b409511 7109 enum target_xfer_status ret;
a76d924d 7110 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7111 &saved_remote_timeout);
a76d924d
DJ
7112
7113 remote_timeout = remote_flash_timeout;
9b409511
YQ
7114 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7115 xfered_len,'X', 0);
a76d924d
DJ
7116 do_cleanups (back_to);
7117
7118 return ret;
7119}
7120
7121static void
7122remote_flash_done (struct target_ops *ops)
7123{
7124 int saved_remote_timeout = remote_timeout;
7125 int ret;
7126 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7127 &saved_remote_timeout);
7128
7129 remote_timeout = remote_flash_timeout;
7130 ret = remote_send_printf ("vFlashDone");
7131 do_cleanups (back_to);
7132
7133 switch (ret)
7134 {
7135 case PACKET_UNKNOWN:
7136 error (_("Remote target does not support vFlashDone"));
7137 case PACKET_ERROR:
7138 error (_("Error finishing flash operation"));
7139 default:
7140 break;
7141 }
7142}
7143
c906108c 7144static void
fba45db2 7145remote_files_info (struct target_ops *ignore)
c906108c
SS
7146{
7147 puts_filtered ("Debugging a target over a serial line.\n");
7148}
7149\f
7150/* Stuff for dealing with the packets which are part of this protocol.
7151 See comment at top of file for details. */
7152
1927e618
PA
7153/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7154 error to higher layers. Called when a serial error is detected.
7155 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7156 the system error message for errno at function entry and final dot
7157 for output compatibility with throw_perror_with_name. */
1927e618
PA
7158
7159static void
7160unpush_and_perror (const char *string)
7161{
d6cb50a2 7162 int saved_errno = errno;
1927e618
PA
7163
7164 remote_unpush_target ();
d6cb50a2
JK
7165 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7166 safe_strerror (saved_errno));
1927e618
PA
7167}
7168
0876f84a 7169/* Read a single character from the remote end. */
c906108c
SS
7170
7171static int
fba45db2 7172readchar (int timeout)
c906108c
SS
7173{
7174 int ch;
5d93a237 7175 struct remote_state *rs = get_remote_state ();
c906108c 7176
5d93a237 7177 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7178
2acceee2 7179 if (ch >= 0)
0876f84a 7180 return ch;
2acceee2
JM
7181
7182 switch ((enum serial_rc) ch)
c906108c
SS
7183 {
7184 case SERIAL_EOF:
78a095c3 7185 remote_unpush_target ();
598d3636 7186 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7187 /* no return */
c906108c 7188 case SERIAL_ERROR:
1927e618
PA
7189 unpush_and_perror (_("Remote communication error. "
7190 "Target disconnected."));
2acceee2 7191 /* no return */
c906108c 7192 case SERIAL_TIMEOUT:
2acceee2 7193 break;
c906108c 7194 }
2acceee2 7195 return ch;
c906108c
SS
7196}
7197
c33e31fd
PA
7198/* Wrapper for serial_write that closes the target and throws if
7199 writing fails. */
7200
7201static void
7202remote_serial_write (const char *str, int len)
7203{
5d93a237
TT
7204 struct remote_state *rs = get_remote_state ();
7205
7206 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7207 {
1927e618
PA
7208 unpush_and_perror (_("Remote communication error. "
7209 "Target disconnected."));
c33e31fd
PA
7210 }
7211}
7212
6d820c5c
DJ
7213/* Send the command in *BUF to the remote machine, and read the reply
7214 into *BUF. Report an error if we get an error reply. Resize
7215 *BUF using xrealloc if necessary to hold the result, and update
7216 *SIZEOF_BUF. */
c906108c
SS
7217
7218static void
6d820c5c
DJ
7219remote_send (char **buf,
7220 long *sizeof_buf)
c906108c 7221{
6d820c5c 7222 putpkt (*buf);
c2d11a7d 7223 getpkt (buf, sizeof_buf, 0);
c906108c 7224
6d820c5c
DJ
7225 if ((*buf)[0] == 'E')
7226 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7227}
7228
6e5abd65
PA
7229/* Return a pointer to an xmalloc'ed string representing an escaped
7230 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7231 etc. The caller is responsible for releasing the returned
7232 memory. */
7233
7234static char *
7235escape_buffer (const char *buf, int n)
7236{
7237 struct cleanup *old_chain;
7238 struct ui_file *stb;
7239 char *str;
6e5abd65
PA
7240
7241 stb = mem_fileopen ();
7242 old_chain = make_cleanup_ui_file_delete (stb);
7243
6ef284bd 7244 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 7245 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7246 do_cleanups (old_chain);
7247 return str;
7248}
7249
c906108c
SS
7250/* Display a null-terminated packet on stdout, for debugging, using C
7251 string notation. */
7252
7253static void
baa336ce 7254print_packet (const char *buf)
c906108c
SS
7255{
7256 puts_filtered ("\"");
43e526b9 7257 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7258 puts_filtered ("\"");
7259}
7260
7261int
baa336ce 7262putpkt (const char *buf)
c906108c
SS
7263{
7264 return putpkt_binary (buf, strlen (buf));
7265}
7266
7267/* Send a packet to the remote machine, with error checking. The data
23860348 7268 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7269 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7270 and for a possible /0 if we are debugging (remote_debug) and want
7271 to print the sent packet as a string. */
c906108c
SS
7272
7273static int
baa336ce 7274putpkt_binary (const char *buf, int cnt)
c906108c 7275{
2d717e4f 7276 struct remote_state *rs = get_remote_state ();
c906108c
SS
7277 int i;
7278 unsigned char csum = 0;
11cf8741 7279 char *buf2 = alloca (cnt + 6);
085dd6e6 7280
c906108c
SS
7281 int ch;
7282 int tcount = 0;
7283 char *p;
dd61ec5c 7284 char *message;
c906108c 7285
e24a49d8
PA
7286 /* Catch cases like trying to read memory or listing threads while
7287 we're waiting for a stop reply. The remote server wouldn't be
7288 ready to handle this request, so we'd hang and timeout. We don't
7289 have to worry about this in synchronous mode, because in that
7290 case it's not possible to issue a command while the target is
74531fed
PA
7291 running. This is not a problem in non-stop mode, because in that
7292 case, the stub is always ready to process serial input. */
d9d41e78 7293 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
9597b22a
DE
7294 {
7295 error (_("Cannot execute this command while the target is running.\n"
7296 "Use the \"interrupt\" command to stop the target\n"
7297 "and then try again."));
7298 }
e24a49d8 7299
2d717e4f
DJ
7300 /* We're sending out a new packet. Make sure we don't look at a
7301 stale cached response. */
7302 rs->cached_wait_status = 0;
7303
c906108c
SS
7304 /* Copy the packet into buffer BUF2, encapsulating it
7305 and giving it a checksum. */
7306
c906108c
SS
7307 p = buf2;
7308 *p++ = '$';
7309
7310 for (i = 0; i < cnt; i++)
7311 {
7312 csum += buf[i];
7313 *p++ = buf[i];
7314 }
7315 *p++ = '#';
7316 *p++ = tohex ((csum >> 4) & 0xf);
7317 *p++ = tohex (csum & 0xf);
7318
7319 /* Send it over and over until we get a positive ack. */
7320
7321 while (1)
7322 {
7323 int started_error_output = 0;
7324
7325 if (remote_debug)
7326 {
6e5abd65
PA
7327 struct cleanup *old_chain;
7328 char *str;
7329
c906108c 7330 *p = '\0';
6e5abd65
PA
7331 str = escape_buffer (buf2, p - buf2);
7332 old_chain = make_cleanup (xfree, str);
7333 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7334 gdb_flush (gdb_stdlog);
6e5abd65 7335 do_cleanups (old_chain);
c906108c 7336 }
c33e31fd 7337 remote_serial_write (buf2, p - buf2);
c906108c 7338
a6f3e723
SL
7339 /* If this is a no acks version of the remote protocol, send the
7340 packet and move on. */
7341 if (rs->noack_mode)
7342 break;
7343
74531fed
PA
7344 /* Read until either a timeout occurs (-2) or '+' is read.
7345 Handle any notification that arrives in the mean time. */
c906108c
SS
7346 while (1)
7347 {
7348 ch = readchar (remote_timeout);
7349
c5aa993b 7350 if (remote_debug)
c906108c
SS
7351 {
7352 switch (ch)
7353 {
7354 case '+':
1216fa2c 7355 case '-':
c906108c
SS
7356 case SERIAL_TIMEOUT:
7357 case '$':
74531fed 7358 case '%':
c906108c
SS
7359 if (started_error_output)
7360 {
7361 putchar_unfiltered ('\n');
7362 started_error_output = 0;
7363 }
7364 }
7365 }
7366
7367 switch (ch)
7368 {
7369 case '+':
7370 if (remote_debug)
0f71a2f6 7371 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7372 return 1;
1216fa2c
AC
7373 case '-':
7374 if (remote_debug)
7375 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7376 /* FALLTHROUGH */
c906108c 7377 case SERIAL_TIMEOUT:
c5aa993b 7378 tcount++;
c906108c
SS
7379 if (tcount > 3)
7380 return 0;
23860348 7381 break; /* Retransmit buffer. */
c906108c
SS
7382 case '$':
7383 {
40e3f985 7384 if (remote_debug)
2bc416ba 7385 fprintf_unfiltered (gdb_stdlog,
23860348 7386 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7387 /* It's probably an old response sent because an ACK
7388 was lost. Gobble up the packet and ack it so it
7389 doesn't get retransmitted when we resend this
7390 packet. */
6d820c5c 7391 skip_frame ();
c33e31fd 7392 remote_serial_write ("+", 1);
23860348 7393 continue; /* Now, go look for +. */
c906108c 7394 }
74531fed
PA
7395
7396 case '%':
7397 {
7398 int val;
7399
7400 /* If we got a notification, handle it, and go back to looking
7401 for an ack. */
7402 /* We've found the start of a notification. Now
7403 collect the data. */
7404 val = read_frame (&rs->buf, &rs->buf_size);
7405 if (val >= 0)
7406 {
7407 if (remote_debug)
7408 {
6e5abd65
PA
7409 struct cleanup *old_chain;
7410 char *str;
7411
7412 str = escape_buffer (rs->buf, val);
7413 old_chain = make_cleanup (xfree, str);
7414 fprintf_unfiltered (gdb_stdlog,
7415 " Notification received: %s\n",
7416 str);
7417 do_cleanups (old_chain);
74531fed 7418 }
5965e028 7419 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7420 /* We're in sync now, rewait for the ack. */
7421 tcount = 0;
7422 }
7423 else
7424 {
7425 if (remote_debug)
7426 {
7427 if (!started_error_output)
7428 {
7429 started_error_output = 1;
7430 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7431 }
7432 fputc_unfiltered (ch & 0177, gdb_stdlog);
7433 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7434 }
7435 }
7436 continue;
7437 }
7438 /* fall-through */
c906108c
SS
7439 default:
7440 if (remote_debug)
7441 {
7442 if (!started_error_output)
7443 {
7444 started_error_output = 1;
0f71a2f6 7445 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7446 }
0f71a2f6 7447 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7448 }
7449 continue;
7450 }
23860348 7451 break; /* Here to retransmit. */
c906108c
SS
7452 }
7453
7454#if 0
7455 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7456 able to get out next time we call QUIT, without anything as
7457 violent as interrupt_query. If we want to provide a way out of
7458 here without getting to the next QUIT, it should be based on
7459 hitting ^C twice as in remote_wait. */
c906108c
SS
7460 if (quit_flag)
7461 {
7462 quit_flag = 0;
7463 interrupt_query ();
7464 }
7465#endif
7466 }
a6f3e723 7467 return 0;
c906108c
SS
7468}
7469
6d820c5c
DJ
7470/* Come here after finding the start of a frame when we expected an
7471 ack. Do our best to discard the rest of this packet. */
7472
7473static void
7474skip_frame (void)
7475{
7476 int c;
7477
7478 while (1)
7479 {
7480 c = readchar (remote_timeout);
7481 switch (c)
7482 {
7483 case SERIAL_TIMEOUT:
7484 /* Nothing we can do. */
7485 return;
7486 case '#':
7487 /* Discard the two bytes of checksum and stop. */
7488 c = readchar (remote_timeout);
7489 if (c >= 0)
7490 c = readchar (remote_timeout);
7491
7492 return;
7493 case '*': /* Run length encoding. */
7494 /* Discard the repeat count. */
7495 c = readchar (remote_timeout);
7496 if (c < 0)
7497 return;
7498 break;
7499 default:
7500 /* A regular character. */
7501 break;
7502 }
7503 }
7504}
7505
c906108c 7506/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
7507 into *BUF, verifying the checksum, length, and handling run-length
7508 compression. NUL terminate the buffer. If there is not enough room,
7509 expand *BUF using xrealloc.
c906108c 7510
c2d11a7d
JM
7511 Returns -1 on error, number of characters in buffer (ignoring the
7512 trailing NULL) on success. (could be extended to return one of the
23860348 7513 SERIAL status indications). */
c2d11a7d
JM
7514
7515static long
6d820c5c
DJ
7516read_frame (char **buf_p,
7517 long *sizeof_buf)
c906108c
SS
7518{
7519 unsigned char csum;
c2d11a7d 7520 long bc;
c906108c 7521 int c;
6d820c5c 7522 char *buf = *buf_p;
a6f3e723 7523 struct remote_state *rs = get_remote_state ();
c906108c
SS
7524
7525 csum = 0;
c2d11a7d 7526 bc = 0;
c906108c
SS
7527
7528 while (1)
7529 {
7530 c = readchar (remote_timeout);
c906108c
SS
7531 switch (c)
7532 {
7533 case SERIAL_TIMEOUT:
7534 if (remote_debug)
0f71a2f6 7535 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 7536 return -1;
c906108c
SS
7537 case '$':
7538 if (remote_debug)
0f71a2f6
JM
7539 fputs_filtered ("Saw new packet start in middle of old one\n",
7540 gdb_stdlog);
23860348 7541 return -1; /* Start a new packet, count retries. */
c906108c
SS
7542 case '#':
7543 {
7544 unsigned char pktcsum;
e1b09194
AC
7545 int check_0 = 0;
7546 int check_1 = 0;
c906108c 7547
c2d11a7d 7548 buf[bc] = '\0';
c906108c 7549
e1b09194
AC
7550 check_0 = readchar (remote_timeout);
7551 if (check_0 >= 0)
7552 check_1 = readchar (remote_timeout);
802188a7 7553
e1b09194
AC
7554 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7555 {
7556 if (remote_debug)
2bc416ba 7557 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 7558 gdb_stdlog);
e1b09194
AC
7559 return -1;
7560 }
7561 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
7562 {
7563 if (remote_debug)
2bc416ba 7564 fputs_filtered ("Communication error in checksum\n",
23860348 7565 gdb_stdlog);
40e3f985
FN
7566 return -1;
7567 }
c906108c 7568
a6f3e723
SL
7569 /* Don't recompute the checksum; with no ack packets we
7570 don't have any way to indicate a packet retransmission
7571 is necessary. */
7572 if (rs->noack_mode)
7573 return bc;
7574
e1b09194 7575 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 7576 if (csum == pktcsum)
c2d11a7d 7577 return bc;
c906108c 7578
c5aa993b 7579 if (remote_debug)
c906108c 7580 {
6e5abd65
PA
7581 struct cleanup *old_chain;
7582 char *str;
7583
7584 str = escape_buffer (buf, bc);
7585 old_chain = make_cleanup (xfree, str);
7586 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7587 "Bad checksum, sentsum=0x%x, "
7588 "csum=0x%x, buf=%s\n",
6e5abd65
PA
7589 pktcsum, csum, str);
7590 do_cleanups (old_chain);
c906108c 7591 }
c2d11a7d 7592 /* Number of characters in buffer ignoring trailing
23860348 7593 NULL. */
c2d11a7d 7594 return -1;
c906108c 7595 }
23860348 7596 case '*': /* Run length encoding. */
c2c6d25f
JM
7597 {
7598 int repeat;
c906108c 7599
a744cf53 7600 csum += c;
b4501125
AC
7601 c = readchar (remote_timeout);
7602 csum += c;
23860348 7603 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 7604
23860348 7605 /* The character before ``*'' is repeated. */
c2d11a7d 7606
6d820c5c 7607 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 7608 {
6d820c5c
DJ
7609 if (bc + repeat - 1 >= *sizeof_buf - 1)
7610 {
7611 /* Make some more room in the buffer. */
7612 *sizeof_buf += repeat;
7613 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7614 buf = *buf_p;
7615 }
7616
c2d11a7d
JM
7617 memset (&buf[bc], buf[bc - 1], repeat);
7618 bc += repeat;
c2c6d25f
JM
7619 continue;
7620 }
7621
c2d11a7d 7622 buf[bc] = '\0';
6d820c5c 7623 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 7624 return -1;
c2c6d25f 7625 }
c906108c 7626 default:
6d820c5c 7627 if (bc >= *sizeof_buf - 1)
c906108c 7628 {
6d820c5c
DJ
7629 /* Make some more room in the buffer. */
7630 *sizeof_buf *= 2;
7631 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7632 buf = *buf_p;
c906108c
SS
7633 }
7634
6d820c5c
DJ
7635 buf[bc++] = c;
7636 csum += c;
7637 continue;
c906108c
SS
7638 }
7639 }
7640}
7641
7642/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7643 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7644 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7645 rather than timing out; this is used (in synchronous mode) to wait
7646 for a target that is is executing user code to stop. */
d9fcf2fb
JM
7647/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7648 don't have to change all the calls to getpkt to deal with the
7649 return value, because at the moment I don't know what the right
23860348 7650 thing to do it for those. */
c906108c 7651void
6d820c5c
DJ
7652getpkt (char **buf,
7653 long *sizeof_buf,
c2d11a7d 7654 int forever)
d9fcf2fb
JM
7655{
7656 int timed_out;
7657
7658 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7659}
7660
7661
7662/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7663 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7664 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7665 rather than timing out; this is used (in synchronous mode) to wait
7666 for a target that is is executing user code to stop. If FOREVER ==
7667 0, this function is allowed to time out gracefully and return an
74531fed
PA
7668 indication of this to the caller. Otherwise return the number of
7669 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
7670 enough reason to return to the caller. *IS_NOTIF is an output
7671 boolean that indicates whether *BUF holds a notification or not
7672 (a regular packet). */
74531fed 7673
3172dc30 7674static int
74531fed 7675getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 7676 int expecting_notif, int *is_notif)
c906108c 7677{
2d717e4f 7678 struct remote_state *rs = get_remote_state ();
c906108c
SS
7679 int c;
7680 int tries;
7681 int timeout;
df4b58fe 7682 int val = -1;
c906108c 7683
2d717e4f
DJ
7684 /* We're reading a new response. Make sure we don't look at a
7685 previously cached response. */
7686 rs->cached_wait_status = 0;
7687
6d820c5c 7688 strcpy (*buf, "timeout");
c906108c
SS
7689
7690 if (forever)
74531fed
PA
7691 timeout = watchdog > 0 ? watchdog : -1;
7692 else if (expecting_notif)
7693 timeout = 0; /* There should already be a char in the buffer. If
7694 not, bail out. */
c906108c
SS
7695 else
7696 timeout = remote_timeout;
7697
7698#define MAX_TRIES 3
7699
74531fed
PA
7700 /* Process any number of notifications, and then return when
7701 we get a packet. */
7702 for (;;)
c906108c 7703 {
d9c43928 7704 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
7705 times. */
7706 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 7707 {
74531fed
PA
7708 /* This can loop forever if the remote side sends us
7709 characters continuously, but if it pauses, we'll get
7710 SERIAL_TIMEOUT from readchar because of timeout. Then
7711 we'll count that as a retry.
7712
7713 Note that even when forever is set, we will only wait
7714 forever prior to the start of a packet. After that, we
7715 expect characters to arrive at a brisk pace. They should
7716 show up within remote_timeout intervals. */
7717 do
7718 c = readchar (timeout);
7719 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
7720
7721 if (c == SERIAL_TIMEOUT)
7722 {
74531fed
PA
7723 if (expecting_notif)
7724 return -1; /* Don't complain, it's normal to not get
7725 anything in this case. */
7726
23860348 7727 if (forever) /* Watchdog went off? Kill the target. */
c906108c 7728 {
2acceee2 7729 QUIT;
78a095c3 7730 remote_unpush_target ();
598d3636
JK
7731 throw_error (TARGET_CLOSE_ERROR,
7732 _("Watchdog timeout has expired. "
7733 "Target detached."));
c906108c 7734 }
c906108c 7735 if (remote_debug)
0f71a2f6 7736 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 7737 }
74531fed
PA
7738 else
7739 {
7740 /* We've found the start of a packet or notification.
7741 Now collect the data. */
7742 val = read_frame (buf, sizeof_buf);
7743 if (val >= 0)
7744 break;
7745 }
7746
c33e31fd 7747 remote_serial_write ("-", 1);
c906108c 7748 }
c906108c 7749
74531fed
PA
7750 if (tries > MAX_TRIES)
7751 {
7752 /* We have tried hard enough, and just can't receive the
7753 packet/notification. Give up. */
7754 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 7755
74531fed
PA
7756 /* Skip the ack char if we're in no-ack mode. */
7757 if (!rs->noack_mode)
c33e31fd 7758 remote_serial_write ("+", 1);
74531fed
PA
7759 return -1;
7760 }
c906108c 7761
74531fed
PA
7762 /* If we got an ordinary packet, return that to our caller. */
7763 if (c == '$')
c906108c
SS
7764 {
7765 if (remote_debug)
43e526b9 7766 {
6e5abd65
PA
7767 struct cleanup *old_chain;
7768 char *str;
7769
7770 str = escape_buffer (*buf, val);
7771 old_chain = make_cleanup (xfree, str);
7772 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7773 do_cleanups (old_chain);
43e526b9 7774 }
a6f3e723
SL
7775
7776 /* Skip the ack char if we're in no-ack mode. */
7777 if (!rs->noack_mode)
c33e31fd 7778 remote_serial_write ("+", 1);
fee9eda9
YQ
7779 if (is_notif != NULL)
7780 *is_notif = 0;
0876f84a 7781 return val;
c906108c
SS
7782 }
7783
74531fed
PA
7784 /* If we got a notification, handle it, and go back to looking
7785 for a packet. */
7786 else
7787 {
7788 gdb_assert (c == '%');
7789
7790 if (remote_debug)
7791 {
6e5abd65
PA
7792 struct cleanup *old_chain;
7793 char *str;
7794
7795 str = escape_buffer (*buf, val);
7796 old_chain = make_cleanup (xfree, str);
7797 fprintf_unfiltered (gdb_stdlog,
7798 " Notification received: %s\n",
7799 str);
7800 do_cleanups (old_chain);
74531fed 7801 }
fee9eda9
YQ
7802 if (is_notif != NULL)
7803 *is_notif = 1;
c906108c 7804
5965e028 7805 handle_notification (rs->notif_state, *buf);
c906108c 7806
74531fed 7807 /* Notifications require no acknowledgement. */
a6f3e723 7808
74531fed 7809 if (expecting_notif)
fee9eda9 7810 return val;
74531fed
PA
7811 }
7812 }
7813}
7814
7815static int
7816getpkt_sane (char **buf, long *sizeof_buf, int forever)
7817{
fee9eda9 7818 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
7819}
7820
7821static int
fee9eda9
YQ
7822getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
7823 int *is_notif)
74531fed 7824{
fee9eda9
YQ
7825 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
7826 is_notif);
c906108c 7827}
74531fed 7828
c906108c
SS
7829\f
7830static void
7d85a9c0 7831remote_kill (struct target_ops *ops)
43ff13b4 7832{
0fdf84ca
PA
7833
7834 /* Catch errors so the user can quit from gdb even when we
23860348 7835 aren't on speaking terms with the remote system. */
492d29ea 7836 TRY
0fdf84ca
PA
7837 {
7838 putpkt ("k");
7839 }
492d29ea 7840 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
7841 {
7842 if (ex.error == TARGET_CLOSE_ERROR)
7843 {
7844 /* If we got an (EOF) error that caused the target
7845 to go away, then we're done, that's what we wanted.
7846 "k" is susceptible to cause a premature EOF, given
7847 that the remote server isn't actually required to
7848 reply to "k", and it can happen that it doesn't
7849 even get to reply ACK to the "k". */
7850 return;
7851 }
7852
7853 /* Otherwise, something went wrong. We didn't actually kill
7854 the target. Just propagate the exception, and let the
7855 user or higher layers decide what to do. */
7856 throw_exception (ex);
7857 }
492d29ea 7858 END_CATCH
43ff13b4 7859
0fdf84ca
PA
7860 /* We've killed the remote end, we get to mourn it. Since this is
7861 target remote, single-process, mourning the inferior also
7862 unpushes remote_ops. */
43ff13b4
JM
7863 target_mourn_inferior ();
7864}
7865
82f73884
PA
7866static int
7867remote_vkill (int pid, struct remote_state *rs)
7868{
4082afcc 7869 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
7870 return -1;
7871
7872 /* Tell the remote target to detach. */
bba74b36 7873 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
7874 putpkt (rs->buf);
7875 getpkt (&rs->buf, &rs->buf_size, 0);
7876
4082afcc
PA
7877 switch (packet_ok (rs->buf,
7878 &remote_protocol_packets[PACKET_vKill]))
7879 {
7880 case PACKET_OK:
7881 return 0;
7882 case PACKET_ERROR:
7883 return 1;
7884 case PACKET_UNKNOWN:
7885 return -1;
7886 default:
7887 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7888 }
82f73884
PA
7889}
7890
7891static void
7d85a9c0 7892extended_remote_kill (struct target_ops *ops)
82f73884
PA
7893{
7894 int res;
7895 int pid = ptid_get_pid (inferior_ptid);
7896 struct remote_state *rs = get_remote_state ();
7897
7898 res = remote_vkill (pid, rs);
901f9912 7899 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
7900 {
7901 /* Don't try 'k' on a multi-process aware stub -- it has no way
7902 to specify the pid. */
7903
7904 putpkt ("k");
7905#if 0
7906 getpkt (&rs->buf, &rs->buf_size, 0);
7907 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7908 res = 1;
7909#else
7910 /* Don't wait for it to die. I'm not really sure it matters whether
7911 we do or not. For the existing stubs, kill is a noop. */
7912 res = 0;
7913#endif
7914 }
7915
7916 if (res != 0)
7917 error (_("Can't kill process"));
7918
82f73884
PA
7919 target_mourn_inferior ();
7920}
7921
c906108c 7922static void
136d6dae 7923remote_mourn (struct target_ops *ops)
c906108c 7924{
136d6dae 7925 remote_mourn_1 (ops);
c906108c
SS
7926}
7927
c906108c
SS
7928/* Worker function for remote_mourn. */
7929static void
fba45db2 7930remote_mourn_1 (struct target_ops *target)
c906108c
SS
7931{
7932 unpush_target (target);
ce5ce7ed 7933
8a2492ee
PA
7934 /* remote_close takes care of doing most of the clean up. */
7935 generic_mourn_inferior ();
c906108c
SS
7936}
7937
2d717e4f
DJ
7938static void
7939extended_remote_mourn_1 (struct target_ops *target)
7940{
7941 struct remote_state *rs = get_remote_state ();
c906108c 7942
e24a49d8
PA
7943 /* In case we got here due to an error, but we're going to stay
7944 connected. */
7945 rs->waiting_for_stop_reply = 0;
7946
dc1981d7
PA
7947 /* If the current general thread belonged to the process we just
7948 detached from or has exited, the remote side current general
7949 thread becomes undefined. Considering a case like this:
7950
7951 - We just got here due to a detach.
7952 - The process that we're detaching from happens to immediately
7953 report a global breakpoint being hit in non-stop mode, in the
7954 same thread we had selected before.
7955 - GDB attaches to this process again.
7956 - This event happens to be the next event we handle.
7957
7958 GDB would consider that the current general thread didn't need to
7959 be set on the stub side (with Hg), since for all it knew,
7960 GENERAL_THREAD hadn't changed.
7961
7962 Notice that although in all-stop mode, the remote server always
7963 sets the current thread to the thread reporting the stop event,
7964 that doesn't happen in non-stop mode; in non-stop, the stub *must
7965 not* change the current thread when reporting a breakpoint hit,
7966 due to the decoupling of event reporting and event handling.
7967
7968 To keep things simple, we always invalidate our notion of the
7969 current thread. */
47f8a51d 7970 record_currthread (rs, minus_one_ptid);
dc1981d7 7971
2d717e4f
DJ
7972 /* Unlike "target remote", we do not want to unpush the target; then
7973 the next time the user says "run", we won't be connected. */
7974
48aa3c27
PA
7975 /* Call common code to mark the inferior as not running. */
7976 generic_mourn_inferior ();
7977
d729566a 7978 if (!have_inferiors ())
2d717e4f 7979 {
82f73884
PA
7980 if (!remote_multi_process_p (rs))
7981 {
7982 /* Check whether the target is running now - some remote stubs
7983 automatically restart after kill. */
7984 putpkt ("?");
7985 getpkt (&rs->buf, &rs->buf_size, 0);
7986
7987 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7988 {
3e43a32a
MS
7989 /* Assume that the target has been restarted. Set
7990 inferior_ptid so that bits of core GDB realizes
7991 there's something here, e.g., so that the user can
7992 say "kill" again. */
82f73884
PA
7993 inferior_ptid = magic_null_ptid;
7994 }
82f73884 7995 }
2d717e4f
DJ
7996 }
7997}
c906108c
SS
7998
7999static void
136d6dae 8000extended_remote_mourn (struct target_ops *ops)
c906108c 8001{
136d6dae 8002 extended_remote_mourn_1 (ops);
2d717e4f 8003}
c906108c 8004
03583c20 8005static int
2bfc0540 8006extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8007{
4082afcc 8008 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8009}
8010
8011static void
8012extended_remote_disable_randomization (int val)
8013{
8014 struct remote_state *rs = get_remote_state ();
8015 char *reply;
8016
bba74b36
YQ
8017 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8018 val);
03583c20
UW
8019 putpkt (rs->buf);
8020 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8021 if (*reply == '\0')
8022 error (_("Target does not support QDisableRandomization."));
8023 if (strcmp (reply, "OK") != 0)
8024 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8025}
8026
2d717e4f
DJ
8027static int
8028extended_remote_run (char *args)
8029{
8030 struct remote_state *rs = get_remote_state ();
2d717e4f 8031 int len;
c906108c 8032
2d717e4f
DJ
8033 /* If the user has disabled vRun support, or we have detected that
8034 support is not available, do not try it. */
4082afcc 8035 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8036 return -1;
424163ea 8037
2d717e4f
DJ
8038 strcpy (rs->buf, "vRun;");
8039 len = strlen (rs->buf);
c906108c 8040
2d717e4f
DJ
8041 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8042 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8043 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8044 strlen (remote_exec_file));
2d717e4f 8045
d1a41061 8046 gdb_assert (args != NULL);
2d717e4f
DJ
8047 if (*args)
8048 {
8049 struct cleanup *back_to;
8050 int i;
8051 char **argv;
8052
d1a41061 8053 argv = gdb_buildargv (args);
6e366df1 8054 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
8055 for (i = 0; argv[i] != NULL; i++)
8056 {
8057 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8058 error (_("Argument list too long for run packet"));
8059 rs->buf[len++] = ';';
9f1b45b0
TT
8060 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8061 strlen (argv[i]));
2d717e4f
DJ
8062 }
8063 do_cleanups (back_to);
8064 }
8065
8066 rs->buf[len++] = '\0';
8067
8068 putpkt (rs->buf);
8069 getpkt (&rs->buf, &rs->buf_size, 0);
8070
4082afcc 8071 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 8072 {
4082afcc 8073 case PACKET_OK:
3405876a 8074 /* We have a wait response. All is well. */
2d717e4f 8075 return 0;
4082afcc
PA
8076 case PACKET_UNKNOWN:
8077 return -1;
8078 case PACKET_ERROR:
2d717e4f
DJ
8079 if (remote_exec_file[0] == '\0')
8080 error (_("Running the default executable on the remote target failed; "
8081 "try \"set remote exec-file\"?"));
8082 else
8083 error (_("Running \"%s\" on the remote target failed"),
8084 remote_exec_file);
4082afcc
PA
8085 default:
8086 gdb_assert_not_reached (_("bad switch"));
2d717e4f 8087 }
c906108c
SS
8088}
8089
2d717e4f
DJ
8090/* In the extended protocol we want to be able to do things like
8091 "run" and have them basically work as expected. So we need
8092 a special create_inferior function. We support changing the
8093 executable file and the command line arguments, but not the
8094 environment. */
8095
43ff13b4 8096static void
77a19445
TT
8097extended_remote_create_inferior (struct target_ops *ops,
8098 char *exec_file, char *args,
8099 char **env, int from_tty)
43ff13b4 8100{
3405876a
PA
8101 int run_worked;
8102 char *stop_reply;
8103 struct remote_state *rs = get_remote_state ();
8104
43ff13b4 8105 /* If running asynchronously, register the target file descriptor
23860348 8106 with the event loop. */
75c99385 8107 if (target_can_async_p ())
6a3753b3 8108 target_async (1);
43ff13b4 8109
03583c20 8110 /* Disable address space randomization if requested (and supported). */
2bfc0540 8111 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
8112 extended_remote_disable_randomization (disable_randomization);
8113
43ff13b4 8114 /* Now restart the remote server. */
3405876a
PA
8115 run_worked = extended_remote_run (args) != -1;
8116 if (!run_worked)
2d717e4f
DJ
8117 {
8118 /* vRun was not supported. Fail if we need it to do what the
8119 user requested. */
8120 if (remote_exec_file[0])
8121 error (_("Remote target does not support \"set remote exec-file\""));
8122 if (args[0])
8123 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 8124
2d717e4f
DJ
8125 /* Fall back to "R". */
8126 extended_remote_restart ();
8127 }
424163ea 8128
6c95b8df
PA
8129 if (!have_inferiors ())
8130 {
8131 /* Clean up from the last time we ran, before we mark the target
8132 running again. This will mark breakpoints uninserted, and
8133 get_offsets may insert breakpoints. */
8134 init_thread_list ();
8135 init_wait_for_inferior ();
8136 }
45280a52 8137
3405876a
PA
8138 /* vRun's success return is a stop reply. */
8139 stop_reply = run_worked ? rs->buf : NULL;
8140 add_current_inferior_and_thread (stop_reply);
c0a2216e 8141
2d717e4f
DJ
8142 /* Get updated offsets, if the stub uses qOffsets. */
8143 get_offsets ();
2d717e4f 8144}
c906108c 8145\f
c5aa993b 8146
b775012e
LM
8147/* Given a location's target info BP_TGT and the packet buffer BUF, output
8148 the list of conditions (in agent expression bytecode format), if any, the
8149 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8150 started from BUF and ended at BUF_END. */
b775012e
LM
8151
8152static int
8153remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8154 struct bp_target_info *bp_tgt, char *buf,
8155 char *buf_end)
b775012e
LM
8156{
8157 struct agent_expr *aexpr = NULL;
8158 int i, ix;
8159 char *pkt;
8160 char *buf_start = buf;
8161
8162 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8163 return 0;
8164
8165 buf += strlen (buf);
bba74b36 8166 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8167 buf++;
8168
8169 /* Send conditions to the target and free the vector. */
8170 for (ix = 0;
8171 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8172 ix++)
8173 {
bba74b36 8174 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8175 buf += strlen (buf);
8176 for (i = 0; i < aexpr->len; ++i)
8177 buf = pack_hex_byte (buf, aexpr->buf[i]);
8178 *buf = '\0';
8179 }
b775012e
LM
8180 return 0;
8181}
8182
d3ce09f5
SS
8183static void
8184remote_add_target_side_commands (struct gdbarch *gdbarch,
8185 struct bp_target_info *bp_tgt, char *buf)
8186{
8187 struct agent_expr *aexpr = NULL;
8188 int i, ix;
8189
8190 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8191 return;
8192
8193 buf += strlen (buf);
8194
8195 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8196 buf += strlen (buf);
8197
8198 /* Concatenate all the agent expressions that are commands into the
8199 cmds parameter. */
8200 for (ix = 0;
8201 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8202 ix++)
8203 {
8204 sprintf (buf, "X%x,", aexpr->len);
8205 buf += strlen (buf);
8206 for (i = 0; i < aexpr->len; ++i)
8207 buf = pack_hex_byte (buf, aexpr->buf[i]);
8208 *buf = '\0';
8209 }
d3ce09f5
SS
8210}
8211
8181d85f
DJ
8212/* Insert a breakpoint. On targets that have software breakpoint
8213 support, we ask the remote target to do the work; on targets
8214 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8215
8216static int
3db08215
MM
8217remote_insert_breakpoint (struct target_ops *ops,
8218 struct gdbarch *gdbarch,
a6d9a66e 8219 struct bp_target_info *bp_tgt)
c906108c 8220{
d471ea57
AC
8221 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8222 If it succeeds, then set the support to PACKET_ENABLE. If it
8223 fails, and the user has explicitly requested the Z support then
23860348 8224 report an error, otherwise, mark it disabled and go on. */
802188a7 8225
4082afcc 8226 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8227 {
0d5ed153 8228 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8229 struct remote_state *rs;
bba74b36 8230 char *p, *endbuf;
7c0f6dcc 8231 int bpsize;
b775012e 8232 struct condition_list *cond = NULL;
4fff2411 8233
28439a30
PA
8234 /* Make sure the remote is pointing at the right process, if
8235 necessary. */
8236 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8237 set_general_process ();
8238
a1dcb23a 8239 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8240
8241 rs = get_remote_state ();
8242 p = rs->buf;
bba74b36 8243 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8244
96baa820
JM
8245 *(p++) = 'Z';
8246 *(p++) = '0';
8247 *(p++) = ',';
7c0f6dcc 8248 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8249 p += hexnumstr (p, addr);
bba74b36 8250 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8251
efcc2da7 8252 if (remote_supports_cond_breakpoints (ops))
bba74b36 8253 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8254
78eff0ec 8255 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8256 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8257
6d820c5c
DJ
8258 putpkt (rs->buf);
8259 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8260
6d820c5c 8261 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8262 {
d471ea57
AC
8263 case PACKET_ERROR:
8264 return -1;
8265 case PACKET_OK:
7c0f6dcc
JL
8266 bp_tgt->placed_address = addr;
8267 bp_tgt->placed_size = bpsize;
d471ea57
AC
8268 return 0;
8269 case PACKET_UNKNOWN:
8270 break;
96baa820
JM
8271 }
8272 }
c906108c 8273
0000e5cc
PA
8274 /* If this breakpoint has target-side commands but this stub doesn't
8275 support Z0 packets, throw error. */
8276 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8277 throw_error (NOT_SUPPORTED_ERROR, _("\
8278Target doesn't support breakpoints that have target side commands."));
8279
3db08215 8280 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8281}
8282
8283static int
3db08215
MM
8284remote_remove_breakpoint (struct target_ops *ops,
8285 struct gdbarch *gdbarch,
a6d9a66e 8286 struct bp_target_info *bp_tgt)
c906108c 8287{
8181d85f 8288 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8289 struct remote_state *rs = get_remote_state ();
96baa820 8290
4082afcc 8291 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8292 {
6d820c5c 8293 char *p = rs->buf;
bba74b36 8294 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8295
28439a30
PA
8296 /* Make sure the remote is pointing at the right process, if
8297 necessary. */
8298 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8299 set_general_process ();
8300
96baa820
JM
8301 *(p++) = 'z';
8302 *(p++) = '0';
8303 *(p++) = ',';
8304
8181d85f
DJ
8305 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8306 p += hexnumstr (p, addr);
bba74b36 8307 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8308
6d820c5c
DJ
8309 putpkt (rs->buf);
8310 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8311
6d820c5c 8312 return (rs->buf[0] == 'E');
96baa820
JM
8313 }
8314
3db08215 8315 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8316}
8317
d471ea57
AC
8318static int
8319watchpoint_to_Z_packet (int type)
8320{
8321 switch (type)
8322 {
8323 case hw_write:
bb858e6a 8324 return Z_PACKET_WRITE_WP;
d471ea57
AC
8325 break;
8326 case hw_read:
bb858e6a 8327 return Z_PACKET_READ_WP;
d471ea57
AC
8328 break;
8329 case hw_access:
bb858e6a 8330 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8331 break;
8332 default:
8e65ff28 8333 internal_error (__FILE__, __LINE__,
e2e0b3e5 8334 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8335 }
8336}
8337
3c3bea1c 8338static int
7bb99c53
TT
8339remote_insert_watchpoint (struct target_ops *self,
8340 CORE_ADDR addr, int len, int type,
0cf6dd15 8341 struct expression *cond)
96baa820 8342{
d01949b6 8343 struct remote_state *rs = get_remote_state ();
bba74b36 8344 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8345 char *p;
d471ea57 8346 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8347
4082afcc 8348 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 8349 return 1;
802188a7 8350
28439a30
PA
8351 /* Make sure the remote is pointing at the right process, if
8352 necessary. */
8353 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8354 set_general_process ();
8355
bba74b36 8356 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8357 p = strchr (rs->buf, '\0');
96baa820
JM
8358 addr = remote_address_masked (addr);
8359 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8360 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8361
6d820c5c
DJ
8362 putpkt (rs->buf);
8363 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8364
6d820c5c 8365 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8366 {
8367 case PACKET_ERROR:
d471ea57 8368 return -1;
85d721b8
PA
8369 case PACKET_UNKNOWN:
8370 return 1;
d471ea57
AC
8371 case PACKET_OK:
8372 return 0;
8373 }
8e65ff28 8374 internal_error (__FILE__, __LINE__,
e2e0b3e5 8375 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8376}
8377
283002cf
MR
8378static int
8379remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8380 CORE_ADDR start, int length)
8381{
8382 CORE_ADDR diff = remote_address_masked (addr - start);
8383
8384 return diff < length;
8385}
8386
d471ea57 8387
3c3bea1c 8388static int
11b5219a
TT
8389remote_remove_watchpoint (struct target_ops *self,
8390 CORE_ADDR addr, int len, int type,
0cf6dd15 8391 struct expression *cond)
96baa820 8392{
d01949b6 8393 struct remote_state *rs = get_remote_state ();
bba74b36 8394 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8395 char *p;
d471ea57
AC
8396 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8397
4082afcc 8398 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 8399 return -1;
802188a7 8400
28439a30
PA
8401 /* Make sure the remote is pointing at the right process, if
8402 necessary. */
8403 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8404 set_general_process ();
8405
bba74b36 8406 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8407 p = strchr (rs->buf, '\0');
96baa820
JM
8408 addr = remote_address_masked (addr);
8409 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8410 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8411 putpkt (rs->buf);
8412 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8413
6d820c5c 8414 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8415 {
8416 case PACKET_ERROR:
8417 case PACKET_UNKNOWN:
8418 return -1;
8419 case PACKET_OK:
8420 return 0;
8421 }
8e65ff28 8422 internal_error (__FILE__, __LINE__,
e2e0b3e5 8423 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8424}
8425
3c3bea1c 8426
501eef12 8427int remote_hw_watchpoint_limit = -1;
480a3f21 8428int remote_hw_watchpoint_length_limit = -1;
501eef12 8429int remote_hw_breakpoint_limit = -1;
d471ea57 8430
480a3f21 8431static int
31568a15
TT
8432remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8433 CORE_ADDR addr, int len)
480a3f21
PW
8434{
8435 if (remote_hw_watchpoint_length_limit == 0)
8436 return 0;
8437 else if (remote_hw_watchpoint_length_limit < 0)
8438 return 1;
8439 else if (len <= remote_hw_watchpoint_length_limit)
8440 return 1;
8441 else
8442 return 0;
8443}
8444
b9362cc7 8445static int
5461485a
TT
8446remote_check_watch_resources (struct target_ops *self,
8447 int type, int cnt, int ot)
96baa820 8448{
3c3bea1c
GS
8449 if (type == bp_hardware_breakpoint)
8450 {
8451 if (remote_hw_breakpoint_limit == 0)
8452 return 0;
501eef12
AC
8453 else if (remote_hw_breakpoint_limit < 0)
8454 return 1;
3c3bea1c
GS
8455 else if (cnt <= remote_hw_breakpoint_limit)
8456 return 1;
8457 }
8458 else
8459 {
8460 if (remote_hw_watchpoint_limit == 0)
8461 return 0;
501eef12
AC
8462 else if (remote_hw_watchpoint_limit < 0)
8463 return 1;
3c3bea1c
GS
8464 else if (ot)
8465 return -1;
8466 else if (cnt <= remote_hw_watchpoint_limit)
8467 return 1;
8468 }
8469 return -1;
8470}
8471
f7e6eed5
PA
8472/* The to_stopped_by_sw_breakpoint method of target remote. */
8473
8474static int
8475remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8476{
8477 struct remote_state *rs = get_remote_state ();
8478
8479 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8480}
8481
8482/* The to_supports_stopped_by_sw_breakpoint method of target
8483 remote. */
8484
8485static int
8486remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8487{
8488 struct remote_state *rs = get_remote_state ();
8489
8490 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8491}
8492
8493/* The to_stopped_by_hw_breakpoint method of target remote. */
8494
8495static int
8496remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8497{
8498 struct remote_state *rs = get_remote_state ();
8499
8500 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8501}
8502
8503/* The to_supports_stopped_by_hw_breakpoint method of target
8504 remote. */
8505
8506static int
8507remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8508{
8509 struct remote_state *rs = get_remote_state ();
8510
8511 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8512}
8513
b9362cc7 8514static int
6a109b6b 8515remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 8516{
ee154bee
TT
8517 struct remote_state *rs = get_remote_state ();
8518
f7e6eed5 8519 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
3c3bea1c
GS
8520}
8521
4aa7a7f5
JJ
8522static int
8523remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 8524{
ee154bee 8525 struct remote_state *rs = get_remote_state ();
4aa7a7f5 8526 int rc = 0;
a744cf53 8527
6a109b6b 8528 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 8529 {
ee154bee 8530 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
8531 rc = 1;
8532 }
8533
8534 return rc;
3c3bea1c
GS
8535}
8536
8537
8538static int
23a26771 8539remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8540 struct bp_target_info *bp_tgt)
3c3bea1c 8541{
0d5ed153 8542 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8543 struct remote_state *rs;
bba74b36 8544 char *p, *endbuf;
dd61ec5c 8545 char *message;
0d5ed153 8546 int bpsize;
802188a7 8547
c8189ed1 8548 /* The length field should be set to the size of a breakpoint
8181d85f 8549 instruction, even though we aren't inserting one ourselves. */
c8189ed1 8550
0d5ed153 8551 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 8552
4082afcc 8553 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 8554 return -1;
2bc416ba 8555
28439a30
PA
8556 /* Make sure the remote is pointing at the right process, if
8557 necessary. */
8558 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8559 set_general_process ();
8560
4fff2411
JZ
8561 rs = get_remote_state ();
8562 p = rs->buf;
bba74b36 8563 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 8564
96baa820
JM
8565 *(p++) = 'Z';
8566 *(p++) = '1';
8567 *(p++) = ',';
802188a7 8568
0d5ed153 8569 addr = remote_address_masked (addr);
96baa820 8570 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 8571 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 8572
efcc2da7 8573 if (remote_supports_cond_breakpoints (self))
bba74b36 8574 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8575
78eff0ec 8576 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
8577 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8578
6d820c5c
DJ
8579 putpkt (rs->buf);
8580 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8581
6d820c5c 8582 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8583 {
8584 case PACKET_ERROR:
dd61ec5c
MW
8585 if (rs->buf[1] == '.')
8586 {
8587 message = strchr (rs->buf + 2, '.');
8588 if (message)
0316657e 8589 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
8590 }
8591 return -1;
d471ea57
AC
8592 case PACKET_UNKNOWN:
8593 return -1;
8594 case PACKET_OK:
0d5ed153
MR
8595 bp_tgt->placed_address = addr;
8596 bp_tgt->placed_size = bpsize;
d471ea57
AC
8597 return 0;
8598 }
8e65ff28 8599 internal_error (__FILE__, __LINE__,
e2e0b3e5 8600 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
8601}
8602
d471ea57 8603
802188a7 8604static int
a64dc96c 8605remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 8606 struct bp_target_info *bp_tgt)
96baa820 8607{
8181d85f 8608 CORE_ADDR addr;
d01949b6 8609 struct remote_state *rs = get_remote_state ();
6d820c5c 8610 char *p = rs->buf;
bba74b36 8611 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 8612
4082afcc 8613 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 8614 return -1;
802188a7 8615
28439a30
PA
8616 /* Make sure the remote is pointing at the right process, if
8617 necessary. */
8618 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8619 set_general_process ();
8620
96baa820
JM
8621 *(p++) = 'z';
8622 *(p++) = '1';
8623 *(p++) = ',';
802188a7 8624
8181d85f 8625 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 8626 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8627 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 8628
6d820c5c
DJ
8629 putpkt (rs->buf);
8630 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8631
6d820c5c 8632 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
8633 {
8634 case PACKET_ERROR:
8635 case PACKET_UNKNOWN:
8636 return -1;
8637 case PACKET_OK:
8638 return 0;
8639 }
8e65ff28 8640 internal_error (__FILE__, __LINE__,
e2e0b3e5 8641 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 8642}
96baa820 8643
4a5e7a5b
PA
8644/* Verify memory using the "qCRC:" request. */
8645
8646static int
8647remote_verify_memory (struct target_ops *ops,
8648 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8649{
8650 struct remote_state *rs = get_remote_state ();
8651 unsigned long host_crc, target_crc;
8652 char *tmp;
8653
936d2992
PA
8654 /* It doesn't make sense to use qCRC if the remote target is
8655 connected but not running. */
8656 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8657 {
8658 enum packet_result result;
28439a30 8659
936d2992
PA
8660 /* Make sure the remote is pointing at the right process. */
8661 set_general_process ();
4a5e7a5b 8662
936d2992
PA
8663 /* FIXME: assumes lma can fit into long. */
8664 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8665 (long) lma, (long) size);
8666 putpkt (rs->buf);
4a5e7a5b 8667
936d2992
PA
8668 /* Be clever; compute the host_crc before waiting for target
8669 reply. */
8670 host_crc = xcrc32 (data, size, 0xffffffff);
8671
8672 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 8673
936d2992
PA
8674 result = packet_ok (rs->buf,
8675 &remote_protocol_packets[PACKET_qCRC]);
8676 if (result == PACKET_ERROR)
8677 return -1;
8678 else if (result == PACKET_OK)
8679 {
8680 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8681 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 8682
936d2992
PA
8683 return (host_crc == target_crc);
8684 }
8685 }
4a5e7a5b 8686
936d2992 8687 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
8688}
8689
c906108c
SS
8690/* compare-sections command
8691
8692 With no arguments, compares each loadable section in the exec bfd
8693 with the same memory range on the target, and reports mismatches.
4a5e7a5b 8694 Useful for verifying the image on the target against the exec file. */
e514a9d6 8695
c906108c 8696static void
fba45db2 8697compare_sections_command (char *args, int from_tty)
c906108c
SS
8698{
8699 asection *s;
c906108c 8700 struct cleanup *old_chain;
948f8e3d 8701 gdb_byte *sectdata;
ce359b09 8702 const char *sectname;
c906108c
SS
8703 bfd_size_type size;
8704 bfd_vma lma;
8705 int matched = 0;
8706 int mismatched = 0;
4a5e7a5b 8707 int res;
95cf3b38 8708 int read_only = 0;
c906108c
SS
8709
8710 if (!exec_bfd)
8a3fe4f8 8711 error (_("command cannot be used without an exec file"));
c906108c 8712
28439a30
PA
8713 /* Make sure the remote is pointing at the right process. */
8714 set_general_process ();
8715
95cf3b38
DT
8716 if (args != NULL && strcmp (args, "-r") == 0)
8717 {
8718 read_only = 1;
8719 args = NULL;
8720 }
8721
c5aa993b 8722 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
8723 {
8724 if (!(s->flags & SEC_LOAD))
0df8b418 8725 continue; /* Skip non-loadable section. */
c906108c 8726
95cf3b38
DT
8727 if (read_only && (s->flags & SEC_READONLY) == 0)
8728 continue; /* Skip writeable sections */
8729
2c500098 8730 size = bfd_get_section_size (s);
c906108c 8731 if (size == 0)
0df8b418 8732 continue; /* Skip zero-length section. */
c906108c 8733
ce359b09 8734 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 8735 if (args && strcmp (args, sectname) != 0)
0df8b418 8736 continue; /* Not the section selected by user. */
c906108c 8737
0df8b418 8738 matched = 1; /* Do this section. */
c906108c 8739 lma = s->lma;
c906108c 8740
c906108c 8741 sectdata = xmalloc (size);
b8c9b27d 8742 old_chain = make_cleanup (xfree, sectdata);
c906108c 8743 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 8744
4a5e7a5b
PA
8745 res = target_verify_memory (sectdata, lma, size);
8746
8747 if (res == -1)
5af949e3 8748 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
8749 paddress (target_gdbarch (), lma),
8750 paddress (target_gdbarch (), lma + size));
c906108c 8751
5af949e3 8752 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
8753 paddress (target_gdbarch (), lma),
8754 paddress (target_gdbarch (), lma + size));
4a5e7a5b 8755 if (res)
c906108c
SS
8756 printf_filtered ("matched.\n");
8757 else
c5aa993b
JM
8758 {
8759 printf_filtered ("MIS-MATCHED!\n");
8760 mismatched++;
8761 }
c906108c
SS
8762
8763 do_cleanups (old_chain);
8764 }
8765 if (mismatched > 0)
936d2992 8766 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 8767the loaded file\n"));
c906108c 8768 if (args && !matched)
a3f17187 8769 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
8770}
8771
0e7f50da
UW
8772/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8773 into remote target. The number of bytes written to the remote
8774 target is returned, or -1 for error. */
8775
9b409511 8776static enum target_xfer_status
0e7f50da
UW
8777remote_write_qxfer (struct target_ops *ops, const char *object_name,
8778 const char *annex, const gdb_byte *writebuf,
9b409511 8779 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
8780 struct packet_config *packet)
8781{
8782 int i, buf_len;
8783 ULONGEST n;
0e7f50da
UW
8784 struct remote_state *rs = get_remote_state ();
8785 int max_size = get_memory_write_packet_size ();
8786
8787 if (packet->support == PACKET_DISABLE)
2ed4b548 8788 return TARGET_XFER_E_IO;
0e7f50da
UW
8789
8790 /* Insert header. */
8791 i = snprintf (rs->buf, max_size,
8792 "qXfer:%s:write:%s:%s:",
8793 object_name, annex ? annex : "",
8794 phex_nz (offset, sizeof offset));
8795 max_size -= (i + 1);
8796
8797 /* Escape as much data as fits into rs->buf. */
8798 buf_len = remote_escape_output
bc20a4af 8799 (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
8800
8801 if (putpkt_binary (rs->buf, i + buf_len) < 0
8802 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8803 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8804 return TARGET_XFER_E_IO;
0e7f50da
UW
8805
8806 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
8807
8808 *xfered_len = n;
8809 return TARGET_XFER_OK;
0e7f50da
UW
8810}
8811
0876f84a
DJ
8812/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8813 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8814 number of bytes read is returned, or 0 for EOF, or -1 for error.
8815 The number of bytes read may be less than LEN without indicating an
8816 EOF. PACKET is checked and updated to indicate whether the remote
8817 target supports this object. */
8818
9b409511 8819static enum target_xfer_status
0876f84a
DJ
8820remote_read_qxfer (struct target_ops *ops, const char *object_name,
8821 const char *annex,
8822 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 8823 ULONGEST *xfered_len,
0876f84a
DJ
8824 struct packet_config *packet)
8825{
0876f84a 8826 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
8827 LONGEST i, n, packet_len;
8828
8829 if (packet->support == PACKET_DISABLE)
2ed4b548 8830 return TARGET_XFER_E_IO;
0876f84a
DJ
8831
8832 /* Check whether we've cached an end-of-object packet that matches
8833 this request. */
8e88304f 8834 if (rs->finished_object)
0876f84a 8835 {
8e88304f
TT
8836 if (strcmp (object_name, rs->finished_object) == 0
8837 && strcmp (annex ? annex : "", rs->finished_annex) == 0
8838 && offset == rs->finished_offset)
9b409511
YQ
8839 return TARGET_XFER_EOF;
8840
0876f84a
DJ
8841
8842 /* Otherwise, we're now reading something different. Discard
8843 the cache. */
8e88304f
TT
8844 xfree (rs->finished_object);
8845 xfree (rs->finished_annex);
8846 rs->finished_object = NULL;
8847 rs->finished_annex = NULL;
0876f84a
DJ
8848 }
8849
8850 /* Request only enough to fit in a single packet. The actual data
8851 may not, since we don't know how much of it will need to be escaped;
8852 the target is free to respond with slightly less data. We subtract
8853 five to account for the response type and the protocol frame. */
8854 n = min (get_remote_packet_size () - 5, len);
8855 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8856 object_name, annex ? annex : "",
8857 phex_nz (offset, sizeof offset),
8858 phex_nz (n, sizeof n));
8859 i = putpkt (rs->buf);
8860 if (i < 0)
2ed4b548 8861 return TARGET_XFER_E_IO;
0876f84a
DJ
8862
8863 rs->buf[0] = '\0';
8864 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8865 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 8866 return TARGET_XFER_E_IO;
0876f84a
DJ
8867
8868 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8869 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8870
8871 /* 'm' means there is (or at least might be) more data after this
8872 batch. That does not make sense unless there's at least one byte
8873 of data in this reply. */
8874 if (rs->buf[0] == 'm' && packet_len == 1)
8875 error (_("Remote qXfer reply contained no data."));
8876
8877 /* Got some data. */
bc20a4af
PA
8878 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
8879 packet_len - 1, readbuf, n);
0876f84a
DJ
8880
8881 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
8882 or possibly empty. If we have the final block of a non-empty
8883 object, record this fact to bypass a subsequent partial read. */
8884 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 8885 {
8e88304f
TT
8886 rs->finished_object = xstrdup (object_name);
8887 rs->finished_annex = xstrdup (annex ? annex : "");
8888 rs->finished_offset = offset + i;
0876f84a
DJ
8889 }
8890
9b409511
YQ
8891 if (i == 0)
8892 return TARGET_XFER_EOF;
8893 else
8894 {
8895 *xfered_len = i;
8896 return TARGET_XFER_OK;
8897 }
0876f84a
DJ
8898}
8899
9b409511 8900static enum target_xfer_status
4b8a223f 8901remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 8902 const char *annex, gdb_byte *readbuf,
9b409511
YQ
8903 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
8904 ULONGEST *xfered_len)
c906108c 8905{
82f73884 8906 struct remote_state *rs;
c906108c 8907 int i;
6d820c5c 8908 char *p2;
1e3ff5ad 8909 char query_type;
c906108c 8910
e6e4e701 8911 set_remote_traceframe ();
82f73884
PA
8912 set_general_thread (inferior_ptid);
8913
8914 rs = get_remote_state ();
8915
b2182ed2 8916 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
8917 if (object == TARGET_OBJECT_MEMORY)
8918 {
2d717e4f
DJ
8919 /* If the remote target is connected but not running, we should
8920 pass this request down to a lower stratum (e.g. the executable
8921 file). */
8922 if (!target_has_execution)
9b409511 8923 return TARGET_XFER_EOF;
2d717e4f 8924
21e3b9b9 8925 if (writebuf != NULL)
9b409511 8926 return remote_write_bytes (offset, writebuf, len, xfered_len);
21e3b9b9 8927 else
8acf9577 8928 return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
21e3b9b9
DJ
8929 }
8930
0df8b418 8931 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
8932 if (object == TARGET_OBJECT_SPU)
8933 {
8934 if (readbuf)
8935 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
8936 xfered_len, &remote_protocol_packets
8937 [PACKET_qXfer_spu_read]);
0e7f50da
UW
8938 else
8939 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
8940 xfered_len, &remote_protocol_packets
8941 [PACKET_qXfer_spu_write]);
0e7f50da
UW
8942 }
8943
4aa995e1
PA
8944 /* Handle extra signal info using qxfer packets. */
8945 if (object == TARGET_OBJECT_SIGNAL_INFO)
8946 {
8947 if (readbuf)
8948 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 8949 xfered_len, &remote_protocol_packets
4aa995e1
PA
8950 [PACKET_qXfer_siginfo_read]);
8951 else
3e43a32a 8952 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 8953 writebuf, offset, len, xfered_len,
4aa995e1
PA
8954 &remote_protocol_packets
8955 [PACKET_qXfer_siginfo_write]);
8956 }
8957
0fb4aa4b
PA
8958 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8959 {
8960 if (readbuf)
3e43a32a 8961 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 8962 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
8963 &remote_protocol_packets
8964 [PACKET_qXfer_statictrace_read]);
8965 else
2ed4b548 8966 return TARGET_XFER_E_IO;
0fb4aa4b
PA
8967 }
8968
a76d924d
DJ
8969 /* Only handle flash writes. */
8970 if (writebuf != NULL)
8971 {
8972 LONGEST xfered;
8973
8974 switch (object)
8975 {
8976 case TARGET_OBJECT_FLASH:
9b409511
YQ
8977 return remote_flash_write (ops, offset, len, xfered_len,
8978 writebuf);
a76d924d
DJ
8979
8980 default:
2ed4b548 8981 return TARGET_XFER_E_IO;
a76d924d
DJ
8982 }
8983 }
4b8a223f 8984
1e3ff5ad
AC
8985 /* Map pre-existing objects onto letters. DO NOT do this for new
8986 objects!!! Instead specify new query packets. */
8987 switch (object)
c906108c 8988 {
1e3ff5ad
AC
8989 case TARGET_OBJECT_AVR:
8990 query_type = 'R';
8991 break;
802188a7
RM
8992
8993 case TARGET_OBJECT_AUXV:
0876f84a
DJ
8994 gdb_assert (annex == NULL);
8995 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 8996 xfered_len,
0876f84a 8997 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 8998
23181151
DJ
8999 case TARGET_OBJECT_AVAILABLE_FEATURES:
9000 return remote_read_qxfer
9b409511 9001 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9002 &remote_protocol_packets[PACKET_qXfer_features]);
9003
cfa9d6d9
DJ
9004 case TARGET_OBJECT_LIBRARIES:
9005 return remote_read_qxfer
9b409511 9006 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9007 &remote_protocol_packets[PACKET_qXfer_libraries]);
9008
2268b414
JK
9009 case TARGET_OBJECT_LIBRARIES_SVR4:
9010 return remote_read_qxfer
9b409511 9011 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9012 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9013
fd79ecee
DJ
9014 case TARGET_OBJECT_MEMORY_MAP:
9015 gdb_assert (annex == NULL);
9016 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9017 xfered_len,
fd79ecee
DJ
9018 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9019
07e059b5
VP
9020 case TARGET_OBJECT_OSDATA:
9021 /* Should only get here if we're connected. */
5d93a237 9022 gdb_assert (rs->remote_desc);
07e059b5 9023 return remote_read_qxfer
9b409511 9024 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9025 &remote_protocol_packets[PACKET_qXfer_osdata]);
9026
dc146f7c
VP
9027 case TARGET_OBJECT_THREADS:
9028 gdb_assert (annex == NULL);
9029 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9030 xfered_len,
dc146f7c
VP
9031 &remote_protocol_packets[PACKET_qXfer_threads]);
9032
b3b9301e
PA
9033 case TARGET_OBJECT_TRACEFRAME_INFO:
9034 gdb_assert (annex == NULL);
9035 return remote_read_qxfer
9b409511 9036 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9037 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9038
9039 case TARGET_OBJECT_FDPIC:
9040 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9041 xfered_len,
78d85199 9042 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9043
9044 case TARGET_OBJECT_OPENVMS_UIB:
9045 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 9046 xfered_len,
169081d0
TG
9047 &remote_protocol_packets[PACKET_qXfer_uib]);
9048
9accd112
MM
9049 case TARGET_OBJECT_BTRACE:
9050 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 9051 xfered_len,
9accd112
MM
9052 &remote_protocol_packets[PACKET_qXfer_btrace]);
9053
f4abbc16
MM
9054 case TARGET_OBJECT_BTRACE_CONF:
9055 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9056 len, xfered_len,
9057 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9058
1e3ff5ad 9059 default:
2ed4b548 9060 return TARGET_XFER_E_IO;
c906108c
SS
9061 }
9062
0df8b418 9063 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 9064 large enough let the caller deal with it. */
ea9c271d 9065 if (len < get_remote_packet_size ())
2ed4b548 9066 return TARGET_XFER_E_IO;
ea9c271d 9067 len = get_remote_packet_size ();
1e3ff5ad 9068
23860348 9069 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 9070 if (!rs->remote_desc)
8a3fe4f8 9071 error (_("remote query is only available after target open"));
c906108c 9072
1e3ff5ad 9073 gdb_assert (annex != NULL);
4b8a223f 9074 gdb_assert (readbuf != NULL);
c906108c 9075
6d820c5c 9076 p2 = rs->buf;
c906108c
SS
9077 *p2++ = 'q';
9078 *p2++ = query_type;
9079
23860348
MS
9080 /* We used one buffer char for the remote protocol q command and
9081 another for the query type. As the remote protocol encapsulation
9082 uses 4 chars plus one extra in case we are debugging
9083 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9084 string. */
c906108c 9085 i = 0;
ea9c271d 9086 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 9087 {
1e3ff5ad
AC
9088 /* Bad caller may have sent forbidden characters. */
9089 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9090 *p2++ = annex[i];
c906108c
SS
9091 i++;
9092 }
1e3ff5ad
AC
9093 *p2 = '\0';
9094 gdb_assert (annex[i] == '\0');
c906108c 9095
6d820c5c 9096 i = putpkt (rs->buf);
c5aa993b 9097 if (i < 0)
2ed4b548 9098 return TARGET_XFER_E_IO;
c906108c 9099
6d820c5c
DJ
9100 getpkt (&rs->buf, &rs->buf_size, 0);
9101 strcpy ((char *) readbuf, rs->buf);
c906108c 9102
9b409511
YQ
9103 *xfered_len = strlen ((char *) readbuf);
9104 return TARGET_XFER_OK;
c906108c
SS
9105}
9106
08388c79
DE
9107static int
9108remote_search_memory (struct target_ops* ops,
9109 CORE_ADDR start_addr, ULONGEST search_space_len,
9110 const gdb_byte *pattern, ULONGEST pattern_len,
9111 CORE_ADDR *found_addrp)
9112{
f5656ead 9113 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
9114 struct remote_state *rs = get_remote_state ();
9115 int max_size = get_memory_write_packet_size ();
9116 struct packet_config *packet =
9117 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
9118 /* Number of packet bytes used to encode the pattern;
9119 this could be more than PATTERN_LEN due to escape characters. */
08388c79 9120 int escaped_pattern_len;
0df8b418 9121 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
9122 int used_pattern_len;
9123 int i;
9124 int found;
9125 ULONGEST found_addr;
9126
9127 /* Don't go to the target if we don't have to.
9128 This is done before checking packet->support to avoid the possibility that
9129 a success for this edge case means the facility works in general. */
9130 if (pattern_len > search_space_len)
9131 return 0;
9132 if (pattern_len == 0)
9133 {
9134 *found_addrp = start_addr;
9135 return 1;
9136 }
9137
9138 /* If we already know the packet isn't supported, fall back to the simple
9139 way of searching memory. */
9140
4082afcc 9141 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
9142 {
9143 /* Target doesn't provided special support, fall back and use the
9144 standard support (copy memory and do the search here). */
9145 return simple_search_memory (ops, start_addr, search_space_len,
9146 pattern, pattern_len, found_addrp);
9147 }
9148
28439a30
PA
9149 /* Make sure the remote is pointing at the right process. */
9150 set_general_process ();
9151
08388c79
DE
9152 /* Insert header. */
9153 i = snprintf (rs->buf, max_size,
9154 "qSearch:memory:%s;%s;",
5af949e3 9155 phex_nz (start_addr, addr_size),
08388c79
DE
9156 phex_nz (search_space_len, sizeof (search_space_len)));
9157 max_size -= (i + 1);
9158
9159 /* Escape as much data as fits into rs->buf. */
9160 escaped_pattern_len =
bc20a4af 9161 remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
08388c79
DE
9162 &used_pattern_len, max_size);
9163
9164 /* Bail if the pattern is too large. */
9165 if (used_pattern_len != pattern_len)
9b20d036 9166 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
9167
9168 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9169 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9170 || packet_ok (rs->buf, packet) != PACKET_OK)
9171 {
9172 /* The request may not have worked because the command is not
9173 supported. If so, fall back to the simple way. */
9174 if (packet->support == PACKET_DISABLE)
9175 {
9176 return simple_search_memory (ops, start_addr, search_space_len,
9177 pattern, pattern_len, found_addrp);
9178 }
9179 return -1;
9180 }
9181
9182 if (rs->buf[0] == '0')
9183 found = 0;
9184 else if (rs->buf[0] == '1')
9185 {
9186 found = 1;
9187 if (rs->buf[1] != ',')
10e0fa18 9188 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9189 unpack_varlen_hex (rs->buf + 2, &found_addr);
9190 *found_addrp = found_addr;
9191 }
9192 else
10e0fa18 9193 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9194
9195 return found;
9196}
9197
96baa820 9198static void
a30bf1f1 9199remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 9200 struct ui_file *outbuf)
96baa820 9201{
d01949b6 9202 struct remote_state *rs = get_remote_state ();
2e9f7625 9203 char *p = rs->buf;
96baa820 9204
5d93a237 9205 if (!rs->remote_desc)
8a3fe4f8 9206 error (_("remote rcmd is only available after target open"));
96baa820 9207
23860348 9208 /* Send a NULL command across as an empty command. */
7be570e7
JM
9209 if (command == NULL)
9210 command = "";
9211
23860348 9212 /* The query prefix. */
2e9f7625
DJ
9213 strcpy (rs->buf, "qRcmd,");
9214 p = strchr (rs->buf, '\0');
96baa820 9215
3e43a32a
MS
9216 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9217 > get_remote_packet_size ())
8a3fe4f8 9218 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9219
23860348 9220 /* Encode the actual command. */
a30bf1f1 9221 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 9222
6d820c5c 9223 if (putpkt (rs->buf) < 0)
8a3fe4f8 9224 error (_("Communication problem with target."));
96baa820
JM
9225
9226 /* get/display the response */
9227 while (1)
9228 {
2e9f7625
DJ
9229 char *buf;
9230
00bf0b85 9231 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9232 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9233 rs->buf[0] = '\0';
5b37825d
PW
9234 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9235 {
9236 /* Timeout. Continue to (try to) read responses.
9237 This is better than stopping with an error, assuming the stub
9238 is still executing the (long) monitor command.
9239 If needed, the user can interrupt gdb using C-c, obtaining
9240 an effect similar to stop on timeout. */
9241 continue;
9242 }
2e9f7625 9243 buf = rs->buf;
96baa820 9244 if (buf[0] == '\0')
8a3fe4f8 9245 error (_("Target does not support this command."));
96baa820
JM
9246 if (buf[0] == 'O' && buf[1] != 'K')
9247 {
23860348 9248 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9249 continue;
9250 }
9251 if (strcmp (buf, "OK") == 0)
9252 break;
7be570e7
JM
9253 if (strlen (buf) == 3 && buf[0] == 'E'
9254 && isdigit (buf[1]) && isdigit (buf[2]))
9255 {
8a3fe4f8 9256 error (_("Protocol error with Rcmd"));
7be570e7 9257 }
96baa820
JM
9258 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9259 {
9260 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9261
96baa820
JM
9262 fputc_unfiltered (c, outbuf);
9263 }
9264 break;
9265 }
9266}
9267
fd79ecee
DJ
9268static VEC(mem_region_s) *
9269remote_memory_map (struct target_ops *ops)
9270{
9271 VEC(mem_region_s) *result = NULL;
9272 char *text = target_read_stralloc (&current_target,
9273 TARGET_OBJECT_MEMORY_MAP, NULL);
9274
9275 if (text)
9276 {
9277 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9278
fd79ecee
DJ
9279 result = parse_memory_map (text);
9280 do_cleanups (back_to);
9281 }
9282
9283 return result;
9284}
9285
c906108c 9286static void
fba45db2 9287packet_command (char *args, int from_tty)
c906108c 9288{
d01949b6 9289 struct remote_state *rs = get_remote_state ();
c906108c 9290
5d93a237 9291 if (!rs->remote_desc)
8a3fe4f8 9292 error (_("command can only be used with remote target"));
c906108c 9293
c5aa993b 9294 if (!args)
8a3fe4f8 9295 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9296
9297 puts_filtered ("sending: ");
9298 print_packet (args);
9299 puts_filtered ("\n");
9300 putpkt (args);
9301
6d820c5c 9302 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9303 puts_filtered ("received: ");
6d820c5c 9304 print_packet (rs->buf);
c906108c
SS
9305 puts_filtered ("\n");
9306}
9307
9308#if 0
23860348 9309/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9310
a14ed312 9311static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9312
a14ed312 9313static void threadset_test_cmd (char *cmd, int tty);
c906108c 9314
a14ed312 9315static void threadalive_test (char *cmd, int tty);
c906108c 9316
a14ed312 9317static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9318
23860348 9319int get_and_display_threadinfo (threadref *ref);
c906108c 9320
a14ed312 9321static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9322
23860348 9323static int thread_display_step (threadref *ref, void *context);
c906108c 9324
a14ed312 9325static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9326
a14ed312 9327static void init_remote_threadtests (void);
c906108c 9328
23860348 9329#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9330
9331static void
fba45db2 9332threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9333{
9334 int sample_thread = SAMPLE_THREAD;
9335
a3f17187 9336 printf_filtered (_("Remote threadset test\n"));
79d7f229 9337 set_general_thread (sample_thread);
c906108c
SS
9338}
9339
9340
9341static void
fba45db2 9342threadalive_test (char *cmd, int tty)
c906108c
SS
9343{
9344 int sample_thread = SAMPLE_THREAD;
79d7f229 9345 int pid = ptid_get_pid (inferior_ptid);
ba348170 9346 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 9347
79d7f229 9348 if (remote_thread_alive (ptid))
c906108c
SS
9349 printf_filtered ("PASS: Thread alive test\n");
9350 else
9351 printf_filtered ("FAIL: Thread alive test\n");
9352}
9353
23860348 9354void output_threadid (char *title, threadref *ref);
c906108c
SS
9355
9356void
fba45db2 9357output_threadid (char *title, threadref *ref)
c906108c
SS
9358{
9359 char hexid[20];
9360
23860348 9361 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9362 hexid[16] = 0;
9363 printf_filtered ("%s %s\n", title, (&hexid[0]));
9364}
9365
9366static void
fba45db2 9367threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9368{
9369 int startflag = 1;
9370 threadref nextthread;
9371 int done, result_count;
9372 threadref threadlist[3];
9373
9374 printf_filtered ("Remote Threadlist test\n");
9375 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9376 &result_count, &threadlist[0]))
9377 printf_filtered ("FAIL: threadlist test\n");
9378 else
9379 {
9380 threadref *scan = threadlist;
9381 threadref *limit = scan + result_count;
9382
9383 while (scan < limit)
9384 output_threadid (" thread ", scan++);
9385 }
9386}
9387
9388void
fba45db2 9389display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9390{
9391 output_threadid ("Threadid: ", &info->threadid);
9392 printf_filtered ("Name: %s\n ", info->shortname);
9393 printf_filtered ("State: %s\n", info->display);
9394 printf_filtered ("other: %s\n\n", info->more_display);
9395}
9396
9397int
fba45db2 9398get_and_display_threadinfo (threadref *ref)
c906108c
SS
9399{
9400 int result;
9401 int set;
9402 struct gdb_ext_thread_info threadinfo;
9403
9404 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9405 | TAG_MOREDISPLAY | TAG_DISPLAY;
9406 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9407 display_thread_info (&threadinfo);
9408 return result;
9409}
9410
9411static void
fba45db2 9412threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9413{
9414 int athread = SAMPLE_THREAD;
9415 threadref thread;
9416 int set;
9417
9418 int_to_threadref (&thread, athread);
9419 printf_filtered ("Remote Threadinfo test\n");
9420 if (!get_and_display_threadinfo (&thread))
9421 printf_filtered ("FAIL cannot get thread info\n");
9422}
9423
9424static int
fba45db2 9425thread_display_step (threadref *ref, void *context)
c906108c
SS
9426{
9427 /* output_threadid(" threadstep ",ref); *//* simple test */
9428 return get_and_display_threadinfo (ref);
9429}
9430
9431static void
fba45db2 9432threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
9433{
9434 printf_filtered ("Remote Threadlist update test\n");
9435 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9436}
9437
9438static void
9439init_remote_threadtests (void)
9440{
3e43a32a
MS
9441 add_com ("tlist", class_obscure, threadlist_test_cmd,
9442 _("Fetch and print the remote list of "
9443 "thread identifiers, one pkt only"));
c906108c 9444 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 9445 _("Fetch and display info about one thread"));
c906108c 9446 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 9447 _("Test setting to a different thread"));
c906108c 9448 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 9449 _("Iterate through updating all remote thread info"));
c906108c 9450 add_com ("talive", class_obscure, threadalive_test,
1bedd215 9451 _(" Remote thread alive test "));
c906108c
SS
9452}
9453
9454#endif /* 0 */
9455
f3fb8c85
MS
9456/* Convert a thread ID to a string. Returns the string in a static
9457 buffer. */
9458
9459static char *
117de6a9 9460remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 9461{
79d7f229 9462 static char buf[64];
82f73884 9463 struct remote_state *rs = get_remote_state ();
f3fb8c85 9464
7cee1e54
PA
9465 if (ptid_equal (ptid, null_ptid))
9466 return normal_pid_to_str (ptid);
9467 else if (ptid_is_pid (ptid))
ecd0ada5
PA
9468 {
9469 /* Printing an inferior target id. */
9470
9471 /* When multi-process extensions are off, there's no way in the
9472 remote protocol to know the remote process id, if there's any
9473 at all. There's one exception --- when we're connected with
9474 target extended-remote, and we manually attached to a process
9475 with "attach PID". We don't record anywhere a flag that
9476 allows us to distinguish that case from the case of
9477 connecting with extended-remote and the stub already being
9478 attached to a process, and reporting yes to qAttached, hence
9479 no smart special casing here. */
9480 if (!remote_multi_process_p (rs))
9481 {
9482 xsnprintf (buf, sizeof buf, "Remote target");
9483 return buf;
9484 }
9485
9486 return normal_pid_to_str (ptid);
82f73884 9487 }
ecd0ada5 9488 else
79d7f229 9489 {
ecd0ada5
PA
9490 if (ptid_equal (magic_null_ptid, ptid))
9491 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 9492 else if (rs->extended && remote_multi_process_p (rs))
ecd0ada5 9493 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
ba348170 9494 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
9495 else
9496 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 9497 ptid_get_lwp (ptid));
79d7f229
PA
9498 return buf;
9499 }
f3fb8c85
MS
9500}
9501
38691318
KB
9502/* Get the address of the thread local variable in OBJFILE which is
9503 stored at OFFSET within the thread local storage for thread PTID. */
9504
9505static CORE_ADDR
117de6a9
PA
9506remote_get_thread_local_address (struct target_ops *ops,
9507 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 9508{
4082afcc 9509 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
9510 {
9511 struct remote_state *rs = get_remote_state ();
6d820c5c 9512 char *p = rs->buf;
82f73884 9513 char *endp = rs->buf + get_remote_packet_size ();
571dd617 9514 enum packet_result result;
38691318
KB
9515
9516 strcpy (p, "qGetTLSAddr:");
9517 p += strlen (p);
82f73884 9518 p = write_ptid (p, endp, ptid);
38691318
KB
9519 *p++ = ',';
9520 p += hexnumstr (p, offset);
9521 *p++ = ',';
9522 p += hexnumstr (p, lm);
9523 *p++ = '\0';
9524
6d820c5c
DJ
9525 putpkt (rs->buf);
9526 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
9527 result = packet_ok (rs->buf,
9528 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 9529 if (result == PACKET_OK)
38691318
KB
9530 {
9531 ULONGEST result;
9532
6d820c5c 9533 unpack_varlen_hex (rs->buf, &result);
38691318
KB
9534 return result;
9535 }
571dd617 9536 else if (result == PACKET_UNKNOWN)
109c3e39
AC
9537 throw_error (TLS_GENERIC_ERROR,
9538 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 9539 else
109c3e39
AC
9540 throw_error (TLS_GENERIC_ERROR,
9541 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
9542 }
9543 else
109c3e39
AC
9544 throw_error (TLS_GENERIC_ERROR,
9545 _("TLS not supported or disabled on this target"));
38691318
KB
9546 /* Not reached. */
9547 return 0;
9548}
9549
711e434b
PM
9550/* Provide thread local base, i.e. Thread Information Block address.
9551 Returns 1 if ptid is found and thread_local_base is non zero. */
9552
70221824 9553static int
bd7ae0f5 9554remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 9555{
4082afcc 9556 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
9557 {
9558 struct remote_state *rs = get_remote_state ();
9559 char *p = rs->buf;
9560 char *endp = rs->buf + get_remote_packet_size ();
9561 enum packet_result result;
9562
9563 strcpy (p, "qGetTIBAddr:");
9564 p += strlen (p);
9565 p = write_ptid (p, endp, ptid);
9566 *p++ = '\0';
9567
9568 putpkt (rs->buf);
9569 getpkt (&rs->buf, &rs->buf_size, 0);
9570 result = packet_ok (rs->buf,
9571 &remote_protocol_packets[PACKET_qGetTIBAddr]);
9572 if (result == PACKET_OK)
9573 {
9574 ULONGEST result;
9575
9576 unpack_varlen_hex (rs->buf, &result);
9577 if (addr)
9578 *addr = (CORE_ADDR) result;
9579 return 1;
9580 }
9581 else if (result == PACKET_UNKNOWN)
9582 error (_("Remote target doesn't support qGetTIBAddr packet"));
9583 else
9584 error (_("Remote target failed to process qGetTIBAddr request"));
9585 }
9586 else
9587 error (_("qGetTIBAddr not supported or disabled on this target"));
9588 /* Not reached. */
9589 return 0;
9590}
9591
29709017
DJ
9592/* Support for inferring a target description based on the current
9593 architecture and the size of a 'g' packet. While the 'g' packet
9594 can have any size (since optional registers can be left off the
9595 end), some sizes are easily recognizable given knowledge of the
9596 approximate architecture. */
9597
9598struct remote_g_packet_guess
9599{
9600 int bytes;
9601 const struct target_desc *tdesc;
9602};
9603typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9604DEF_VEC_O(remote_g_packet_guess_s);
9605
9606struct remote_g_packet_data
9607{
9608 VEC(remote_g_packet_guess_s) *guesses;
9609};
9610
9611static struct gdbarch_data *remote_g_packet_data_handle;
9612
9613static void *
9614remote_g_packet_data_init (struct obstack *obstack)
9615{
9616 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9617}
9618
9619void
9620register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9621 const struct target_desc *tdesc)
9622{
9623 struct remote_g_packet_data *data
9624 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9625 struct remote_g_packet_guess new_guess, *guess;
9626 int ix;
9627
9628 gdb_assert (tdesc != NULL);
9629
9630 for (ix = 0;
9631 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9632 ix++)
9633 if (guess->bytes == bytes)
9634 internal_error (__FILE__, __LINE__,
9b20d036 9635 _("Duplicate g packet description added for size %d"),
29709017
DJ
9636 bytes);
9637
9638 new_guess.bytes = bytes;
9639 new_guess.tdesc = tdesc;
9640 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9641}
9642
d962ef82
DJ
9643/* Return 1 if remote_read_description would do anything on this target
9644 and architecture, 0 otherwise. */
9645
9646static int
9647remote_read_description_p (struct target_ops *target)
9648{
9649 struct remote_g_packet_data *data
f5656ead 9650 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
9651
9652 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9653 return 1;
9654
9655 return 0;
9656}
9657
29709017
DJ
9658static const struct target_desc *
9659remote_read_description (struct target_ops *target)
9660{
9661 struct remote_g_packet_data *data
f5656ead 9662 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 9663
d962ef82
DJ
9664 /* Do not try this during initial connection, when we do not know
9665 whether there is a running but stopped thread. */
9666 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 9667 return target->beneath->to_read_description (target->beneath);
d962ef82 9668
29709017
DJ
9669 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9670 {
9671 struct remote_g_packet_guess *guess;
9672 int ix;
9673 int bytes = send_g_packet ();
9674
9675 for (ix = 0;
9676 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9677 ix++)
9678 if (guess->bytes == bytes)
9679 return guess->tdesc;
9680
9681 /* We discard the g packet. A minor optimization would be to
9682 hold on to it, and fill the register cache once we have selected
9683 an architecture, but it's too tricky to do safely. */
9684 }
9685
2117c711 9686 return target->beneath->to_read_description (target->beneath);
29709017
DJ
9687}
9688
a6b151f1
DJ
9689/* Remote file transfer support. This is host-initiated I/O, not
9690 target-initiated; for target-initiated, see remote-fileio.c. */
9691
9692/* If *LEFT is at least the length of STRING, copy STRING to
9693 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9694 decrease *LEFT. Otherwise raise an error. */
9695
9696static void
9697remote_buffer_add_string (char **buffer, int *left, char *string)
9698{
9699 int len = strlen (string);
9700
9701 if (len > *left)
9702 error (_("Packet too long for target."));
9703
9704 memcpy (*buffer, string, len);
9705 *buffer += len;
9706 *left -= len;
9707
9708 /* NUL-terminate the buffer as a convenience, if there is
9709 room. */
9710 if (*left)
9711 **buffer = '\0';
9712}
9713
9714/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9715 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9716 decrease *LEFT. Otherwise raise an error. */
9717
9718static void
9719remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9720 int len)
9721{
9722 if (2 * len > *left)
9723 error (_("Packet too long for target."));
9724
9725 bin2hex (bytes, *buffer, len);
9726 *buffer += 2 * len;
9727 *left -= 2 * len;
9728
9729 /* NUL-terminate the buffer as a convenience, if there is
9730 room. */
9731 if (*left)
9732 **buffer = '\0';
9733}
9734
9735/* If *LEFT is large enough, convert VALUE to hex and add it to
9736 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9737 decrease *LEFT. Otherwise raise an error. */
9738
9739static void
9740remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9741{
9742 int len = hexnumlen (value);
9743
9744 if (len > *left)
9745 error (_("Packet too long for target."));
9746
9747 hexnumstr (*buffer, value);
9748 *buffer += len;
9749 *left -= len;
9750
9751 /* NUL-terminate the buffer as a convenience, if there is
9752 room. */
9753 if (*left)
9754 **buffer = '\0';
9755}
9756
9757/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9758 value, *REMOTE_ERRNO to the remote error number or zero if none
9759 was included, and *ATTACHMENT to point to the start of the annex
9760 if any. The length of the packet isn't needed here; there may
9761 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9762
9763 Return 0 if the packet could be parsed, -1 if it could not. If
9764 -1 is returned, the other variables may not be initialized. */
9765
9766static int
9767remote_hostio_parse_result (char *buffer, int *retcode,
9768 int *remote_errno, char **attachment)
9769{
9770 char *p, *p2;
9771
9772 *remote_errno = 0;
9773 *attachment = NULL;
9774
9775 if (buffer[0] != 'F')
9776 return -1;
9777
9778 errno = 0;
9779 *retcode = strtol (&buffer[1], &p, 16);
9780 if (errno != 0 || p == &buffer[1])
9781 return -1;
9782
9783 /* Check for ",errno". */
9784 if (*p == ',')
9785 {
9786 errno = 0;
9787 *remote_errno = strtol (p + 1, &p2, 16);
9788 if (errno != 0 || p + 1 == p2)
9789 return -1;
9790 p = p2;
9791 }
9792
9793 /* Check for ";attachment". If there is no attachment, the
9794 packet should end here. */
9795 if (*p == ';')
9796 {
9797 *attachment = p + 1;
9798 return 0;
9799 }
9800 else if (*p == '\0')
9801 return 0;
9802 else
9803 return -1;
9804}
9805
9806/* Send a prepared I/O packet to the target and read its response.
9807 The prepared packet is in the global RS->BUF before this function
9808 is called, and the answer is there when we return.
9809
9810 COMMAND_BYTES is the length of the request to send, which may include
9811 binary data. WHICH_PACKET is the packet configuration to check
9812 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9813 is set to the error number and -1 is returned. Otherwise the value
9814 returned by the function is returned.
9815
9816 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9817 attachment is expected; an error will be reported if there's a
9818 mismatch. If one is found, *ATTACHMENT will be set to point into
9819 the packet buffer and *ATTACHMENT_LEN will be set to the
9820 attachment's length. */
9821
9822static int
9823remote_hostio_send_command (int command_bytes, int which_packet,
9824 int *remote_errno, char **attachment,
9825 int *attachment_len)
9826{
9827 struct remote_state *rs = get_remote_state ();
9828 int ret, bytes_read;
9829 char *attachment_tmp;
9830
5d93a237 9831 if (!rs->remote_desc
4082afcc 9832 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
9833 {
9834 *remote_errno = FILEIO_ENOSYS;
9835 return -1;
9836 }
9837
9838 putpkt_binary (rs->buf, command_bytes);
9839 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9840
9841 /* If it timed out, something is wrong. Don't try to parse the
9842 buffer. */
9843 if (bytes_read < 0)
9844 {
9845 *remote_errno = FILEIO_EINVAL;
9846 return -1;
9847 }
9848
9849 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9850 {
9851 case PACKET_ERROR:
9852 *remote_errno = FILEIO_EINVAL;
9853 return -1;
9854 case PACKET_UNKNOWN:
9855 *remote_errno = FILEIO_ENOSYS;
9856 return -1;
9857 case PACKET_OK:
9858 break;
9859 }
9860
9861 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9862 &attachment_tmp))
9863 {
9864 *remote_errno = FILEIO_EINVAL;
9865 return -1;
9866 }
9867
9868 /* Make sure we saw an attachment if and only if we expected one. */
9869 if ((attachment_tmp == NULL && attachment != NULL)
9870 || (attachment_tmp != NULL && attachment == NULL))
9871 {
9872 *remote_errno = FILEIO_EINVAL;
9873 return -1;
9874 }
9875
9876 /* If an attachment was found, it must point into the packet buffer;
9877 work out how many bytes there were. */
9878 if (attachment_tmp != NULL)
9879 {
9880 *attachment = attachment_tmp;
9881 *attachment_len = bytes_read - (*attachment - rs->buf);
9882 }
9883
9884 return ret;
9885}
9886
9887/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9888 remote file descriptor, or -1 if an error occurs (and set
9889 *REMOTE_ERRNO). */
9890
9891static int
cd897586
TT
9892remote_hostio_open (struct target_ops *self,
9893 const char *filename, int flags, int mode,
a6b151f1
DJ
9894 int *remote_errno)
9895{
9896 struct remote_state *rs = get_remote_state ();
9897 char *p = rs->buf;
9898 int left = get_remote_packet_size () - 1;
9899
9900 remote_buffer_add_string (&p, &left, "vFile:open:");
9901
9902 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9903 strlen (filename));
9904 remote_buffer_add_string (&p, &left, ",");
9905
9906 remote_buffer_add_int (&p, &left, flags);
9907 remote_buffer_add_string (&p, &left, ",");
9908
9909 remote_buffer_add_int (&p, &left, mode);
9910
9911 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9912 remote_errno, NULL, NULL);
9913}
9914
9915/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9916 Return the number of bytes written, or -1 if an error occurs (and
9917 set *REMOTE_ERRNO). */
9918
9919static int
0d866f62
TT
9920remote_hostio_pwrite (struct target_ops *self,
9921 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
9922 ULONGEST offset, int *remote_errno)
9923{
9924 struct remote_state *rs = get_remote_state ();
9925 char *p = rs->buf;
9926 int left = get_remote_packet_size ();
9927 int out_len;
9928
9929 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9930
9931 remote_buffer_add_int (&p, &left, fd);
9932 remote_buffer_add_string (&p, &left, ",");
9933
9934 remote_buffer_add_int (&p, &left, offset);
9935 remote_buffer_add_string (&p, &left, ",");
9936
bc20a4af 9937 p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
a6b151f1
DJ
9938 get_remote_packet_size () - (p - rs->buf));
9939
9940 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9941 remote_errno, NULL, NULL);
9942}
9943
9944/* Read up to LEN bytes FD on the remote target into READ_BUF
9945 Return the number of bytes read, or -1 if an error occurs (and
9946 set *REMOTE_ERRNO). */
9947
9948static int
a3be983c
TT
9949remote_hostio_pread (struct target_ops *self,
9950 int fd, gdb_byte *read_buf, int len,
a6b151f1
DJ
9951 ULONGEST offset, int *remote_errno)
9952{
9953 struct remote_state *rs = get_remote_state ();
9954 char *p = rs->buf;
9955 char *attachment;
9956 int left = get_remote_packet_size ();
9957 int ret, attachment_len;
9958 int read_len;
9959
9960 remote_buffer_add_string (&p, &left, "vFile:pread:");
9961
9962 remote_buffer_add_int (&p, &left, fd);
9963 remote_buffer_add_string (&p, &left, ",");
9964
9965 remote_buffer_add_int (&p, &left, len);
9966 remote_buffer_add_string (&p, &left, ",");
9967
9968 remote_buffer_add_int (&p, &left, offset);
9969
9970 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9971 remote_errno, &attachment,
9972 &attachment_len);
9973
9974 if (ret < 0)
9975 return ret;
9976
bc20a4af 9977 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
9978 read_buf, len);
9979 if (read_len != ret)
9980 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9981
9982 return ret;
9983}
9984
9985/* Close FD on the remote target. Return 0, or -1 if an error occurs
9986 (and set *REMOTE_ERRNO). */
9987
9988static int
df39ea25 9989remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
9990{
9991 struct remote_state *rs = get_remote_state ();
9992 char *p = rs->buf;
9993 int left = get_remote_packet_size () - 1;
9994
9995 remote_buffer_add_string (&p, &left, "vFile:close:");
9996
9997 remote_buffer_add_int (&p, &left, fd);
9998
9999 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10000 remote_errno, NULL, NULL);
10001}
10002
10003/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
10004 occurs (and set *REMOTE_ERRNO). */
10005
10006static int
dbbca37d
TT
10007remote_hostio_unlink (struct target_ops *self,
10008 const char *filename, int *remote_errno)
a6b151f1
DJ
10009{
10010 struct remote_state *rs = get_remote_state ();
10011 char *p = rs->buf;
10012 int left = get_remote_packet_size () - 1;
10013
10014 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10015
10016 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10017 strlen (filename));
10018
10019 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10020 remote_errno, NULL, NULL);
10021}
10022
b9e7b9c3
UW
10023/* Read value of symbolic link FILENAME on the remote target. Return
10024 a null-terminated string allocated via xmalloc, or NULL if an error
10025 occurs (and set *REMOTE_ERRNO). */
10026
10027static char *
fab5aa7c
TT
10028remote_hostio_readlink (struct target_ops *self,
10029 const char *filename, int *remote_errno)
b9e7b9c3
UW
10030{
10031 struct remote_state *rs = get_remote_state ();
10032 char *p = rs->buf;
10033 char *attachment;
10034 int left = get_remote_packet_size ();
10035 int len, attachment_len;
10036 int read_len;
10037 char *ret;
10038
10039 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10040
10041 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10042 strlen (filename));
10043
10044 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10045 remote_errno, &attachment,
10046 &attachment_len);
10047
10048 if (len < 0)
10049 return NULL;
10050
10051 ret = xmalloc (len + 1);
10052
bc20a4af
PA
10053 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10054 (gdb_byte *) ret, len);
b9e7b9c3
UW
10055 if (read_len != len)
10056 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10057
10058 ret[len] = '\0';
10059 return ret;
10060}
10061
0a93529c
GB
10062/* Read information about the open file FD on the remote target
10063 into ST. Return 0 on success, or -1 if an error occurs (and
10064 set *REMOTE_ERRNO). */
10065
10066static int
10067remote_hostio_fstat (struct target_ops *self,
10068 int fd, struct stat *st,
10069 int *remote_errno)
10070{
10071 struct remote_state *rs = get_remote_state ();
10072 char *p = rs->buf;
10073 int left = get_remote_packet_size ();
10074 int attachment_len, ret;
10075 char *attachment;
10076 struct fio_stat fst;
10077 int read_len;
10078
464b0089
GB
10079 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10080
10081 remote_buffer_add_int (&p, &left, fd);
10082
10083 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10084 remote_errno, &attachment,
10085 &attachment_len);
10086 if (ret < 0)
0a93529c 10087 {
464b0089
GB
10088 if (*remote_errno != FILEIO_ENOSYS)
10089 return ret;
10090
0a93529c
GB
10091 /* Strictly we should return -1, ENOSYS here, but when
10092 "set sysroot remote:" was implemented in August 2008
10093 BFD's need for a stat function was sidestepped with
10094 this hack. This was not remedied until March 2015
10095 so we retain the previous behavior to avoid breaking
10096 compatibility.
10097
10098 Note that the memset is a March 2015 addition; older
10099 GDBs set st_size *and nothing else* so the structure
10100 would have garbage in all other fields. This might
10101 break something but retaining the previous behavior
10102 here would be just too wrong. */
10103
10104 memset (st, 0, sizeof (struct stat));
10105 st->st_size = INT_MAX;
10106 return 0;
10107 }
10108
0a93529c
GB
10109 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10110 (gdb_byte *) &fst, sizeof (fst));
10111
10112 if (read_len != ret)
10113 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10114
10115 if (read_len != sizeof (fst))
10116 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10117 read_len, (int) sizeof (fst));
10118
10119 remote_fileio_to_host_stat (&fst, st);
10120
10121 return 0;
10122}
10123
a6b151f1
DJ
10124static int
10125remote_fileio_errno_to_host (int errnum)
10126{
10127 switch (errnum)
10128 {
10129 case FILEIO_EPERM:
10130 return EPERM;
10131 case FILEIO_ENOENT:
10132 return ENOENT;
10133 case FILEIO_EINTR:
10134 return EINTR;
10135 case FILEIO_EIO:
10136 return EIO;
10137 case FILEIO_EBADF:
10138 return EBADF;
10139 case FILEIO_EACCES:
10140 return EACCES;
10141 case FILEIO_EFAULT:
10142 return EFAULT;
10143 case FILEIO_EBUSY:
10144 return EBUSY;
10145 case FILEIO_EEXIST:
10146 return EEXIST;
10147 case FILEIO_ENODEV:
10148 return ENODEV;
10149 case FILEIO_ENOTDIR:
10150 return ENOTDIR;
10151 case FILEIO_EISDIR:
10152 return EISDIR;
10153 case FILEIO_EINVAL:
10154 return EINVAL;
10155 case FILEIO_ENFILE:
10156 return ENFILE;
10157 case FILEIO_EMFILE:
10158 return EMFILE;
10159 case FILEIO_EFBIG:
10160 return EFBIG;
10161 case FILEIO_ENOSPC:
10162 return ENOSPC;
10163 case FILEIO_ESPIPE:
10164 return ESPIPE;
10165 case FILEIO_EROFS:
10166 return EROFS;
10167 case FILEIO_ENOSYS:
10168 return ENOSYS;
10169 case FILEIO_ENAMETOOLONG:
10170 return ENAMETOOLONG;
10171 }
10172 return -1;
10173}
10174
10175static char *
10176remote_hostio_error (int errnum)
10177{
10178 int host_error = remote_fileio_errno_to_host (errnum);
10179
10180 if (host_error == -1)
10181 error (_("Unknown remote I/O error %d"), errnum);
10182 else
10183 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10184}
10185
a6b151f1
DJ
10186static void
10187remote_hostio_close_cleanup (void *opaque)
10188{
10189 int fd = *(int *) opaque;
10190 int remote_errno;
10191
df39ea25 10192 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
10193}
10194
f1838a98
UW
10195
10196static void *
10197remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
10198{
10199 const char *filename = bfd_get_filename (abfd);
10200 int fd, remote_errno;
10201 int *stream;
10202
10203 gdb_assert (remote_filename_p (filename));
10204
cd897586
TT
10205 fd = remote_hostio_open (find_target_at (process_stratum),
10206 filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
f1838a98
UW
10207 if (fd == -1)
10208 {
10209 errno = remote_fileio_errno_to_host (remote_errno);
10210 bfd_set_error (bfd_error_system_call);
10211 return NULL;
10212 }
10213
10214 stream = xmalloc (sizeof (int));
10215 *stream = fd;
10216 return stream;
10217}
10218
10219static int
10220remote_bfd_iovec_close (struct bfd *abfd, void *stream)
10221{
10222 int fd = *(int *)stream;
10223 int remote_errno;
10224
10225 xfree (stream);
10226
10227 /* Ignore errors on close; these may happen if the remote
10228 connection was already torn down. */
df39ea25 10229 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
f1838a98 10230
39ed5604
JK
10231 /* Zero means success. */
10232 return 0;
f1838a98
UW
10233}
10234
10235static file_ptr
10236remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
10237 file_ptr nbytes, file_ptr offset)
10238{
10239 int fd = *(int *)stream;
10240 int remote_errno;
10241 file_ptr pos, bytes;
10242
10243 pos = 0;
10244 while (nbytes > pos)
10245 {
a3be983c
TT
10246 bytes = remote_hostio_pread (find_target_at (process_stratum),
10247 fd, (gdb_byte *) buf + pos, nbytes - pos,
f1838a98
UW
10248 offset + pos, &remote_errno);
10249 if (bytes == 0)
10250 /* Success, but no bytes, means end-of-file. */
10251 break;
10252 if (bytes == -1)
10253 {
10254 errno = remote_fileio_errno_to_host (remote_errno);
10255 bfd_set_error (bfd_error_system_call);
10256 return -1;
10257 }
10258
10259 pos += bytes;
10260 }
10261
10262 return pos;
10263}
10264
10265static int
10266remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
10267{
0a93529c
GB
10268 int fd = *(int *) stream;
10269 int remote_errno;
10270 int result;
10271
10272 result = remote_hostio_fstat (find_target_at (process_stratum),
10273 fd, sb, &remote_errno);
10274
10275 if (result == -1)
10276 {
10277 errno = remote_fileio_errno_to_host (remote_errno);
10278 bfd_set_error (bfd_error_system_call);
10279 }
10280
10281 return result;
f1838a98
UW
10282}
10283
10284int
10285remote_filename_p (const char *filename)
10286{
61012eef 10287 return startswith (filename, REMOTE_SYSROOT_PREFIX);
f1838a98
UW
10288}
10289
10290bfd *
10291remote_bfd_open (const char *remote_file, const char *target)
10292{
64c31149
TT
10293 bfd *abfd = gdb_bfd_openr_iovec (remote_file, target,
10294 remote_bfd_iovec_open, NULL,
10295 remote_bfd_iovec_pread,
10296 remote_bfd_iovec_close,
10297 remote_bfd_iovec_stat);
10298
a4453b7e 10299 return abfd;
f1838a98
UW
10300}
10301
a6b151f1
DJ
10302void
10303remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10304{
10305 struct cleanup *back_to, *close_cleanup;
10306 int retcode, fd, remote_errno, bytes, io_size;
10307 FILE *file;
10308 gdb_byte *buffer;
10309 int bytes_in_buffer;
10310 int saw_eof;
10311 ULONGEST offset;
5d93a237 10312 struct remote_state *rs = get_remote_state ();
a6b151f1 10313
5d93a237 10314 if (!rs->remote_desc)
a6b151f1
DJ
10315 error (_("command can only be used with remote target"));
10316
614c279d 10317 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10318 if (file == NULL)
10319 perror_with_name (local_file);
7c8a8b04 10320 back_to = make_cleanup_fclose (file);
a6b151f1 10321
cd897586
TT
10322 fd = remote_hostio_open (find_target_at (process_stratum),
10323 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1
DJ
10324 | FILEIO_O_TRUNC),
10325 0700, &remote_errno);
10326 if (fd == -1)
10327 remote_hostio_error (remote_errno);
10328
10329 /* Send up to this many bytes at once. They won't all fit in the
10330 remote packet limit, so we'll transfer slightly fewer. */
10331 io_size = get_remote_packet_size ();
10332 buffer = xmalloc (io_size);
10333 make_cleanup (xfree, buffer);
10334
10335 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10336
10337 bytes_in_buffer = 0;
10338 saw_eof = 0;
10339 offset = 0;
10340 while (bytes_in_buffer || !saw_eof)
10341 {
10342 if (!saw_eof)
10343 {
3e43a32a
MS
10344 bytes = fread (buffer + bytes_in_buffer, 1,
10345 io_size - bytes_in_buffer,
a6b151f1
DJ
10346 file);
10347 if (bytes == 0)
10348 {
10349 if (ferror (file))
10350 error (_("Error reading %s."), local_file);
10351 else
10352 {
10353 /* EOF. Unless there is something still in the
10354 buffer from the last iteration, we are done. */
10355 saw_eof = 1;
10356 if (bytes_in_buffer == 0)
10357 break;
10358 }
10359 }
10360 }
10361 else
10362 bytes = 0;
10363
10364 bytes += bytes_in_buffer;
10365 bytes_in_buffer = 0;
10366
0d866f62
TT
10367 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10368 fd, buffer, bytes,
3e43a32a 10369 offset, &remote_errno);
a6b151f1
DJ
10370
10371 if (retcode < 0)
10372 remote_hostio_error (remote_errno);
10373 else if (retcode == 0)
10374 error (_("Remote write of %d bytes returned 0!"), bytes);
10375 else if (retcode < bytes)
10376 {
10377 /* Short write. Save the rest of the read data for the next
10378 write. */
10379 bytes_in_buffer = bytes - retcode;
10380 memmove (buffer, buffer + retcode, bytes_in_buffer);
10381 }
10382
10383 offset += retcode;
10384 }
10385
10386 discard_cleanups (close_cleanup);
df39ea25 10387 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10388 remote_hostio_error (remote_errno);
10389
10390 if (from_tty)
10391 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10392 do_cleanups (back_to);
10393}
10394
10395void
10396remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10397{
10398 struct cleanup *back_to, *close_cleanup;
cea39f65 10399 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
10400 FILE *file;
10401 gdb_byte *buffer;
10402 ULONGEST offset;
5d93a237 10403 struct remote_state *rs = get_remote_state ();
a6b151f1 10404
5d93a237 10405 if (!rs->remote_desc)
a6b151f1
DJ
10406 error (_("command can only be used with remote target"));
10407
cd897586
TT
10408 fd = remote_hostio_open (find_target_at (process_stratum),
10409 remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
a6b151f1
DJ
10410 if (fd == -1)
10411 remote_hostio_error (remote_errno);
10412
614c279d 10413 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
10414 if (file == NULL)
10415 perror_with_name (local_file);
7c8a8b04 10416 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
10417
10418 /* Send up to this many bytes at once. They won't all fit in the
10419 remote packet limit, so we'll transfer slightly fewer. */
10420 io_size = get_remote_packet_size ();
10421 buffer = xmalloc (io_size);
10422 make_cleanup (xfree, buffer);
10423
10424 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10425
10426 offset = 0;
10427 while (1)
10428 {
a3be983c
TT
10429 bytes = remote_hostio_pread (find_target_at (process_stratum),
10430 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
10431 if (bytes == 0)
10432 /* Success, but no bytes, means end-of-file. */
10433 break;
10434 if (bytes == -1)
10435 remote_hostio_error (remote_errno);
10436
10437 offset += bytes;
10438
10439 bytes = fwrite (buffer, 1, bytes, file);
10440 if (bytes == 0)
10441 perror_with_name (local_file);
10442 }
10443
10444 discard_cleanups (close_cleanup);
df39ea25 10445 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
10446 remote_hostio_error (remote_errno);
10447
10448 if (from_tty)
10449 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10450 do_cleanups (back_to);
10451}
10452
10453void
10454remote_file_delete (const char *remote_file, int from_tty)
10455{
10456 int retcode, remote_errno;
5d93a237 10457 struct remote_state *rs = get_remote_state ();
a6b151f1 10458
5d93a237 10459 if (!rs->remote_desc)
a6b151f1
DJ
10460 error (_("command can only be used with remote target"));
10461
dbbca37d
TT
10462 retcode = remote_hostio_unlink (find_target_at (process_stratum),
10463 remote_file, &remote_errno);
a6b151f1
DJ
10464 if (retcode == -1)
10465 remote_hostio_error (remote_errno);
10466
10467 if (from_tty)
10468 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10469}
10470
10471static void
10472remote_put_command (char *args, int from_tty)
10473{
10474 struct cleanup *back_to;
10475 char **argv;
10476
d1a41061
PP
10477 if (args == NULL)
10478 error_no_arg (_("file to put"));
10479
10480 argv = gdb_buildargv (args);
a6b151f1
DJ
10481 back_to = make_cleanup_freeargv (argv);
10482 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10483 error (_("Invalid parameters to remote put"));
10484
10485 remote_file_put (argv[0], argv[1], from_tty);
10486
10487 do_cleanups (back_to);
10488}
10489
10490static void
10491remote_get_command (char *args, int from_tty)
10492{
10493 struct cleanup *back_to;
10494 char **argv;
10495
d1a41061
PP
10496 if (args == NULL)
10497 error_no_arg (_("file to get"));
10498
10499 argv = gdb_buildargv (args);
a6b151f1
DJ
10500 back_to = make_cleanup_freeargv (argv);
10501 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10502 error (_("Invalid parameters to remote get"));
10503
10504 remote_file_get (argv[0], argv[1], from_tty);
10505
10506 do_cleanups (back_to);
10507}
10508
10509static void
10510remote_delete_command (char *args, int from_tty)
10511{
10512 struct cleanup *back_to;
10513 char **argv;
10514
d1a41061
PP
10515 if (args == NULL)
10516 error_no_arg (_("file to delete"));
10517
10518 argv = gdb_buildargv (args);
a6b151f1
DJ
10519 back_to = make_cleanup_freeargv (argv);
10520 if (argv[0] == NULL || argv[1] != NULL)
10521 error (_("Invalid parameters to remote delete"));
10522
10523 remote_file_delete (argv[0], from_tty);
10524
10525 do_cleanups (back_to);
10526}
10527
10528static void
10529remote_command (char *args, int from_tty)
10530{
635c7e8a 10531 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
10532}
10533
b2175913 10534static int
19db3e69 10535remote_can_execute_reverse (struct target_ops *self)
b2175913 10536{
4082afcc
PA
10537 if (packet_support (PACKET_bs) == PACKET_ENABLE
10538 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
10539 return 1;
10540 else
10541 return 0;
b2175913
MS
10542}
10543
74531fed 10544static int
2a9a2795 10545remote_supports_non_stop (struct target_ops *self)
74531fed
PA
10546{
10547 return 1;
10548}
10549
03583c20 10550static int
2bfc0540 10551remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
10552{
10553 /* Only supported in extended mode. */
10554 return 0;
10555}
10556
8a305172 10557static int
86ce2668 10558remote_supports_multi_process (struct target_ops *self)
8a305172
PA
10559{
10560 struct remote_state *rs = get_remote_state ();
a744cf53 10561
901f9912
UW
10562 /* Only extended-remote handles being attached to multiple
10563 processes, even though plain remote can use the multi-process
10564 thread id extensions, so that GDB knows the target process's
10565 PID. */
10566 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
10567}
10568
70221824 10569static int
782b2b07
SS
10570remote_supports_cond_tracepoints (void)
10571{
4082afcc 10572 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
10573}
10574
3788aec7 10575static int
efcc2da7 10576remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 10577{
4082afcc 10578 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
10579}
10580
70221824 10581static int
7a697b8d
SS
10582remote_supports_fast_tracepoints (void)
10583{
4082afcc 10584 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
10585}
10586
0fb4aa4b
PA
10587static int
10588remote_supports_static_tracepoints (void)
10589{
4082afcc 10590 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
10591}
10592
1e4d1764
YQ
10593static int
10594remote_supports_install_in_trace (void)
10595{
4082afcc 10596 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
10597}
10598
d248b706 10599static int
7d178d6a 10600remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 10601{
4082afcc
PA
10602 return (packet_support (PACKET_EnableDisableTracepoints_feature)
10603 == PACKET_ENABLE);
d248b706
KY
10604}
10605
3065dfb6 10606static int
6de37a3a 10607remote_supports_string_tracing (struct target_ops *self)
3065dfb6 10608{
4082afcc 10609 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
10610}
10611
d3ce09f5 10612static int
78eff0ec 10613remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 10614{
4082afcc 10615 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
10616}
10617
35b1e5cc 10618static void
ecae04e1 10619remote_trace_init (struct target_ops *self)
35b1e5cc
SS
10620{
10621 putpkt ("QTinit");
10622 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 10623 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10624 error (_("Target does not support this command."));
10625}
10626
10627static void free_actions_list (char **actions_list);
10628static void free_actions_list_cleanup_wrapper (void *);
10629static void
10630free_actions_list_cleanup_wrapper (void *al)
10631{
10632 free_actions_list (al);
10633}
10634
10635static void
10636free_actions_list (char **actions_list)
10637{
10638 int ndx;
10639
10640 if (actions_list == 0)
10641 return;
10642
10643 for (ndx = 0; actions_list[ndx]; ndx++)
10644 xfree (actions_list[ndx]);
10645
10646 xfree (actions_list);
10647}
10648
409873ef
SS
10649/* Recursive routine to walk through command list including loops, and
10650 download packets for each command. */
10651
10652static void
10653remote_download_command_source (int num, ULONGEST addr,
10654 struct command_line *cmds)
10655{
10656 struct remote_state *rs = get_remote_state ();
10657 struct command_line *cmd;
10658
10659 for (cmd = cmds; cmd; cmd = cmd->next)
10660 {
0df8b418 10661 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10662 strcpy (rs->buf, "QTDPsrc:");
10663 encode_source_string (num, addr, "cmd", cmd->line,
10664 rs->buf + strlen (rs->buf),
10665 rs->buf_size - strlen (rs->buf));
10666 putpkt (rs->buf);
10667 remote_get_noisy_reply (&target_buf, &target_buf_size);
10668 if (strcmp (target_buf, "OK"))
10669 warning (_("Target does not support source download."));
10670
10671 if (cmd->control_type == while_control
10672 || cmd->control_type == while_stepping_control)
10673 {
10674 remote_download_command_source (num, addr, *cmd->body_list);
10675
0df8b418 10676 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
10677 strcpy (rs->buf, "QTDPsrc:");
10678 encode_source_string (num, addr, "cmd", "end",
10679 rs->buf + strlen (rs->buf),
10680 rs->buf_size - strlen (rs->buf));
10681 putpkt (rs->buf);
10682 remote_get_noisy_reply (&target_buf, &target_buf_size);
10683 if (strcmp (target_buf, "OK"))
10684 warning (_("Target does not support source download."));
10685 }
10686 }
10687}
10688
35b1e5cc 10689static void
548f7808 10690remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 10691{
bba74b36 10692#define BUF_SIZE 2048
e8ba3115 10693
35b1e5cc 10694 CORE_ADDR tpaddr;
409873ef 10695 char addrbuf[40];
bba74b36 10696 char buf[BUF_SIZE];
35b1e5cc
SS
10697 char **tdp_actions;
10698 char **stepping_actions;
10699 int ndx;
10700 struct cleanup *old_chain = NULL;
10701 struct agent_expr *aexpr;
10702 struct cleanup *aexpr_chain = NULL;
10703 char *pkt;
e8ba3115 10704 struct breakpoint *b = loc->owner;
d9b3f62e 10705 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 10706
dc673c81 10707 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
10708 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10709 tdp_actions);
10710 (void) make_cleanup (free_actions_list_cleanup_wrapper,
10711 stepping_actions);
10712
10713 tpaddr = loc->address;
10714 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
10715 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10716 addrbuf, /* address */
10717 (b->enable_state == bp_enabled ? 'E' : 'D'),
10718 t->step_count, t->pass_count);
e8ba3115
YQ
10719 /* Fast tracepoints are mostly handled by the target, but we can
10720 tell the target how big of an instruction block should be moved
10721 around. */
10722 if (b->type == bp_fast_tracepoint)
10723 {
10724 /* Only test for support at download time; we may not know
10725 target capabilities at definition time. */
10726 if (remote_supports_fast_tracepoints ())
35b1e5cc 10727 {
e8ba3115 10728 int isize;
35b1e5cc 10729
f5656ead 10730 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
e8ba3115 10731 tpaddr, &isize, NULL))
bba74b36
YQ
10732 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10733 isize);
35b1e5cc 10734 else
e8ba3115
YQ
10735 /* If it passed validation at definition but fails now,
10736 something is very wrong. */
10737 internal_error (__FILE__, __LINE__,
10738 _("Fast tracepoint not "
10739 "valid during download"));
35b1e5cc 10740 }
e8ba3115
YQ
10741 else
10742 /* Fast tracepoints are functionally identical to regular
10743 tracepoints, so don't take lack of support as a reason to
10744 give up on the trace run. */
10745 warning (_("Target does not support fast tracepoints, "
10746 "downloading %d as regular tracepoint"), b->number);
10747 }
10748 else if (b->type == bp_static_tracepoint)
10749 {
10750 /* Only test for support at download time; we may not know
10751 target capabilities at definition time. */
10752 if (remote_supports_static_tracepoints ())
0fb4aa4b 10753 {
e8ba3115 10754 struct static_tracepoint_marker marker;
0fb4aa4b 10755
e8ba3115
YQ
10756 if (target_static_tracepoint_marker_at (tpaddr, &marker))
10757 strcat (buf, ":S");
0fb4aa4b 10758 else
e8ba3115 10759 error (_("Static tracepoint not valid during download"));
0fb4aa4b 10760 }
e8ba3115
YQ
10761 else
10762 /* Fast tracepoints are functionally identical to regular
10763 tracepoints, so don't take lack of support as a reason
10764 to give up on the trace run. */
10765 error (_("Target does not support static tracepoints"));
10766 }
10767 /* If the tracepoint has a conditional, make it into an agent
10768 expression and append to the definition. */
10769 if (loc->cond)
10770 {
10771 /* Only test support at download time, we may not know target
10772 capabilities at definition time. */
10773 if (remote_supports_cond_tracepoints ())
35b1e5cc 10774 {
e8ba3115
YQ
10775 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
10776 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
10777 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
10778 aexpr->len);
e8ba3115
YQ
10779 pkt = buf + strlen (buf);
10780 for (ndx = 0; ndx < aexpr->len; ++ndx)
10781 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
10782 *pkt = '\0';
10783 do_cleanups (aexpr_chain);
35b1e5cc 10784 }
e8ba3115
YQ
10785 else
10786 warning (_("Target does not support conditional tracepoints, "
10787 "ignoring tp %d cond"), b->number);
10788 }
35b1e5cc 10789
d9b3f62e 10790 if (b->commands || *default_collect)
e8ba3115
YQ
10791 strcat (buf, "-");
10792 putpkt (buf);
10793 remote_get_noisy_reply (&target_buf, &target_buf_size);
10794 if (strcmp (target_buf, "OK"))
10795 error (_("Target does not support tracepoints."));
35b1e5cc 10796
e8ba3115
YQ
10797 /* do_single_steps (t); */
10798 if (tdp_actions)
10799 {
10800 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 10801 {
e8ba3115 10802 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10803 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
10804 b->number, addrbuf, /* address */
10805 tdp_actions[ndx],
10806 ((tdp_actions[ndx + 1] || stepping_actions)
10807 ? '-' : 0));
e8ba3115
YQ
10808 putpkt (buf);
10809 remote_get_noisy_reply (&target_buf,
10810 &target_buf_size);
10811 if (strcmp (target_buf, "OK"))
10812 error (_("Error on target while setting tracepoints."));
35b1e5cc 10813 }
e8ba3115
YQ
10814 }
10815 if (stepping_actions)
10816 {
10817 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 10818 {
e8ba3115 10819 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
10820 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
10821 b->number, addrbuf, /* address */
10822 ((ndx == 0) ? "S" : ""),
10823 stepping_actions[ndx],
10824 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
10825 putpkt (buf);
10826 remote_get_noisy_reply (&target_buf,
10827 &target_buf_size);
10828 if (strcmp (target_buf, "OK"))
10829 error (_("Error on target while setting tracepoints."));
35b1e5cc 10830 }
e8ba3115 10831 }
409873ef 10832
4082afcc 10833 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115
YQ
10834 {
10835 if (b->addr_string)
409873ef 10836 {
e8ba3115
YQ
10837 strcpy (buf, "QTDPsrc:");
10838 encode_source_string (b->number, loc->address,
10839 "at", b->addr_string, buf + strlen (buf),
10840 2048 - strlen (buf));
409873ef 10841
e8ba3115
YQ
10842 putpkt (buf);
10843 remote_get_noisy_reply (&target_buf, &target_buf_size);
10844 if (strcmp (target_buf, "OK"))
10845 warning (_("Target does not support source download."));
409873ef 10846 }
e8ba3115
YQ
10847 if (b->cond_string)
10848 {
10849 strcpy (buf, "QTDPsrc:");
10850 encode_source_string (b->number, loc->address,
10851 "cond", b->cond_string, buf + strlen (buf),
10852 2048 - strlen (buf));
10853 putpkt (buf);
10854 remote_get_noisy_reply (&target_buf, &target_buf_size);
10855 if (strcmp (target_buf, "OK"))
10856 warning (_("Target does not support source download."));
10857 }
10858 remote_download_command_source (b->number, loc->address,
10859 breakpoint_commands (b));
35b1e5cc 10860 }
e8ba3115
YQ
10861
10862 do_cleanups (old_chain);
35b1e5cc
SS
10863}
10864
1e4d1764 10865static int
a52a8357 10866remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 10867{
1e51243a
PA
10868 struct remote_state *rs = get_remote_state ();
10869 struct trace_status *ts;
10870 int status;
10871
10872 /* Don't try to install tracepoints until we've relocated our
10873 symbols, and fetched and merged the target's tracepoint list with
10874 ours. */
10875 if (rs->starting_up)
10876 return 0;
10877
10878 ts = current_trace_status ();
8bd200f1 10879 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
10880
10881 if (status == -1 || !ts->running_known || !ts->running)
10882 return 0;
10883
10884 /* If we are in a tracing experiment, but remote stub doesn't support
10885 installing tracepoint in trace, we have to return. */
10886 if (!remote_supports_install_in_trace ())
10887 return 0;
10888
10889 return 1;
10890}
10891
10892
35b1e5cc 10893static void
559d2b81
TT
10894remote_download_trace_state_variable (struct target_ops *self,
10895 struct trace_state_variable *tsv)
35b1e5cc
SS
10896{
10897 struct remote_state *rs = get_remote_state ();
00bf0b85 10898 char *p;
35b1e5cc 10899
bba74b36
YQ
10900 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
10901 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
10902 tsv->builtin);
00bf0b85
SS
10903 p = rs->buf + strlen (rs->buf);
10904 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10905 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 10906 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 10907 *p++ = '\0';
35b1e5cc
SS
10908 putpkt (rs->buf);
10909 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10910 if (*target_buf == '\0')
10911 error (_("Target does not support this command."));
10912 if (strcmp (target_buf, "OK") != 0)
10913 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
10914}
10915
d248b706 10916static void
46670d57
TT
10917remote_enable_tracepoint (struct target_ops *self,
10918 struct bp_location *location)
d248b706
KY
10919{
10920 struct remote_state *rs = get_remote_state ();
10921 char addr_buf[40];
10922
10923 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10924 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
10925 location->owner->number, addr_buf);
d248b706
KY
10926 putpkt (rs->buf);
10927 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10928 if (*rs->buf == '\0')
10929 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10930 if (strcmp (rs->buf, "OK") != 0)
10931 error (_("Error on target while enabling tracepoint."));
10932}
10933
10934static void
780b049c
TT
10935remote_disable_tracepoint (struct target_ops *self,
10936 struct bp_location *location)
d248b706
KY
10937{
10938 struct remote_state *rs = get_remote_state ();
10939 char addr_buf[40];
10940
10941 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
10942 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
10943 location->owner->number, addr_buf);
d248b706
KY
10944 putpkt (rs->buf);
10945 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10946 if (*rs->buf == '\0')
10947 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10948 if (strcmp (rs->buf, "OK") != 0)
10949 error (_("Error on target while disabling tracepoint."));
10950}
10951
35b1e5cc 10952static void
583f9a86 10953remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
10954{
10955 asection *s;
81b9b86e 10956 bfd *abfd = NULL;
35b1e5cc 10957 bfd_size_type size;
608bcef2 10958 bfd_vma vma;
35b1e5cc 10959 int anysecs = 0;
c2fa21f1 10960 int offset = 0;
35b1e5cc
SS
10961
10962 if (!exec_bfd)
10963 return; /* No information to give. */
10964
10965 strcpy (target_buf, "QTro");
9779ab84 10966 offset = strlen (target_buf);
35b1e5cc
SS
10967 for (s = exec_bfd->sections; s; s = s->next)
10968 {
10969 char tmp1[40], tmp2[40];
c2fa21f1 10970 int sec_length;
35b1e5cc
SS
10971
10972 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 10973 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
10974 (s->flags & SEC_READONLY) == 0)
10975 continue;
10976
10977 anysecs = 1;
81b9b86e 10978 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 10979 size = bfd_get_section_size (s);
608bcef2
HZ
10980 sprintf_vma (tmp1, vma);
10981 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
10982 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10983 if (offset + sec_length + 1 > target_buf_size)
10984 {
4082afcc 10985 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 10986 warning (_("\
c2fa21f1
HZ
10987Too many sections for read-only sections definition packet."));
10988 break;
10989 }
bba74b36
YQ
10990 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
10991 tmp1, tmp2);
c2fa21f1 10992 offset += sec_length;
35b1e5cc
SS
10993 }
10994 if (anysecs)
10995 {
10996 putpkt (target_buf);
10997 getpkt (&target_buf, &target_buf_size, 0);
10998 }
10999}
11000
11001static void
e2d1aae3 11002remote_trace_start (struct target_ops *self)
35b1e5cc
SS
11003{
11004 putpkt ("QTStart");
11005 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11006 if (*target_buf == '\0')
11007 error (_("Target does not support this command."));
11008 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11009 error (_("Bogus reply from target: %s"), target_buf);
11010}
11011
11012static int
8bd200f1 11013remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 11014{
953b98d1 11015 /* Initialize it just to avoid a GCC false warning. */
f652de6f 11016 char *p = NULL;
0df8b418 11017 /* FIXME we need to get register block size some other way. */
00bf0b85 11018 extern int trace_regblock_size;
bd3eecc3
PA
11019 enum packet_result result;
11020
4082afcc 11021 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 11022 return -1;
a744cf53 11023
00bf0b85
SS
11024 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11025
049dc89b
JK
11026 putpkt ("qTStatus");
11027
492d29ea 11028 TRY
67f41397
JK
11029 {
11030 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11031 }
492d29ea 11032 CATCH (ex, RETURN_MASK_ERROR)
67f41397 11033 {
598d3636
JK
11034 if (ex.error != TARGET_CLOSE_ERROR)
11035 {
11036 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11037 return -1;
11038 }
11039 throw_exception (ex);
67f41397 11040 }
492d29ea 11041 END_CATCH
00bf0b85 11042
bd3eecc3
PA
11043 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11044
00bf0b85 11045 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 11046 if (result == PACKET_UNKNOWN)
00bf0b85 11047 return -1;
35b1e5cc 11048
00bf0b85 11049 /* We're working with a live target. */
f5911ea1 11050 ts->filename = NULL;
00bf0b85 11051
00bf0b85 11052 if (*p++ != 'T')
35b1e5cc
SS
11053 error (_("Bogus trace status reply from target: %s"), target_buf);
11054
84cebc4a
YQ
11055 /* Function 'parse_trace_status' sets default value of each field of
11056 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
11057 parse_trace_status (p, ts);
11058
11059 return ts->running;
35b1e5cc
SS
11060}
11061
70221824 11062static void
db90e85c 11063remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
11064 struct uploaded_tp *utp)
11065{
11066 struct remote_state *rs = get_remote_state ();
f196051f
SS
11067 char *reply;
11068 struct bp_location *loc;
11069 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 11070 size_t size = get_remote_packet_size ();
f196051f
SS
11071
11072 if (tp)
11073 {
11074 tp->base.hit_count = 0;
11075 tp->traceframe_usage = 0;
11076 for (loc = tp->base.loc; loc; loc = loc->next)
11077 {
11078 /* If the tracepoint was never downloaded, don't go asking for
11079 any status. */
11080 if (tp->number_on_target == 0)
11081 continue;
bba74b36
YQ
11082 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11083 phex_nz (loc->address, 0));
f196051f
SS
11084 putpkt (rs->buf);
11085 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11086 if (reply && *reply)
11087 {
11088 if (*reply == 'V')
11089 parse_tracepoint_status (reply + 1, bp, utp);
11090 }
11091 }
11092 }
11093 else if (utp)
11094 {
11095 utp->hit_count = 0;
11096 utp->traceframe_usage = 0;
bba74b36
YQ
11097 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11098 phex_nz (utp->addr, 0));
f196051f
SS
11099 putpkt (rs->buf);
11100 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11101 if (reply && *reply)
11102 {
11103 if (*reply == 'V')
11104 parse_tracepoint_status (reply + 1, bp, utp);
11105 }
11106 }
11107}
11108
35b1e5cc 11109static void
74499f1b 11110remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
11111{
11112 putpkt ("QTStop");
11113 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11114 if (*target_buf == '\0')
11115 error (_("Target does not support this command."));
11116 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11117 error (_("Bogus reply from target: %s"), target_buf);
11118}
11119
11120static int
bd4c6793
TT
11121remote_trace_find (struct target_ops *self,
11122 enum trace_find_type type, int num,
cc5925ad 11123 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
11124 int *tpp)
11125{
11126 struct remote_state *rs = get_remote_state ();
bba74b36 11127 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
11128 char *p, *reply;
11129 int target_frameno = -1, target_tracept = -1;
11130
e6e4e701
PA
11131 /* Lookups other than by absolute frame number depend on the current
11132 trace selected, so make sure it is correct on the remote end
11133 first. */
11134 if (type != tfind_number)
11135 set_remote_traceframe ();
11136
35b1e5cc
SS
11137 p = rs->buf;
11138 strcpy (p, "QTFrame:");
11139 p = strchr (p, '\0');
11140 switch (type)
11141 {
11142 case tfind_number:
bba74b36 11143 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
11144 break;
11145 case tfind_pc:
bba74b36 11146 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
11147 break;
11148 case tfind_tp:
bba74b36 11149 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
11150 break;
11151 case tfind_range:
bba74b36
YQ
11152 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11153 phex_nz (addr2, 0));
35b1e5cc
SS
11154 break;
11155 case tfind_outside:
bba74b36
YQ
11156 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11157 phex_nz (addr2, 0));
35b1e5cc
SS
11158 break;
11159 default:
9b20d036 11160 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
11161 }
11162
11163 putpkt (rs->buf);
2f65bcb7 11164 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
11165 if (*reply == '\0')
11166 error (_("Target does not support this command."));
35b1e5cc
SS
11167
11168 while (reply && *reply)
11169 switch (*reply)
11170 {
11171 case 'F':
f197e0f1
VP
11172 p = ++reply;
11173 target_frameno = (int) strtol (p, &reply, 16);
11174 if (reply == p)
11175 error (_("Unable to parse trace frame number"));
e6e4e701
PA
11176 /* Don't update our remote traceframe number cache on failure
11177 to select a remote traceframe. */
f197e0f1
VP
11178 if (target_frameno == -1)
11179 return -1;
35b1e5cc
SS
11180 break;
11181 case 'T':
f197e0f1
VP
11182 p = ++reply;
11183 target_tracept = (int) strtol (p, &reply, 16);
11184 if (reply == p)
11185 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
11186 break;
11187 case 'O': /* "OK"? */
11188 if (reply[1] == 'K' && reply[2] == '\0')
11189 reply += 2;
11190 else
11191 error (_("Bogus reply from target: %s"), reply);
11192 break;
11193 default:
11194 error (_("Bogus reply from target: %s"), reply);
11195 }
11196 if (tpp)
11197 *tpp = target_tracept;
e6e4e701 11198
262e1174 11199 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
11200 return target_frameno;
11201}
11202
11203static int
4011015b
TT
11204remote_get_trace_state_variable_value (struct target_ops *self,
11205 int tsvnum, LONGEST *val)
35b1e5cc
SS
11206{
11207 struct remote_state *rs = get_remote_state ();
11208 char *reply;
11209 ULONGEST uval;
11210
e6e4e701
PA
11211 set_remote_traceframe ();
11212
bba74b36 11213 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
11214 putpkt (rs->buf);
11215 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11216 if (reply && *reply)
11217 {
11218 if (*reply == 'V')
11219 {
11220 unpack_varlen_hex (reply + 1, &uval);
11221 *val = (LONGEST) uval;
11222 return 1;
11223 }
11224 }
11225 return 0;
11226}
11227
00bf0b85 11228static int
dc3decaf 11229remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
11230{
11231 struct remote_state *rs = get_remote_state ();
11232 char *p, *reply;
11233
11234 p = rs->buf;
11235 strcpy (p, "QTSave:");
11236 p += strlen (p);
11237 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11238 error (_("Remote file name too long for trace save packet"));
9f1b45b0 11239 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
11240 *p++ = '\0';
11241 putpkt (rs->buf);
ad91cd99 11242 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 11243 if (*reply == '\0')
ad91cd99
PA
11244 error (_("Target does not support this command."));
11245 if (strcmp (reply, "OK") != 0)
11246 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
11247 return 0;
11248}
11249
11250/* This is basically a memory transfer, but needs to be its own packet
11251 because we don't know how the target actually organizes its trace
11252 memory, plus we want to be able to ask for as much as possible, but
11253 not be unhappy if we don't get as much as we ask for. */
11254
11255static LONGEST
88ee6f45
TT
11256remote_get_raw_trace_data (struct target_ops *self,
11257 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
11258{
11259 struct remote_state *rs = get_remote_state ();
11260 char *reply;
11261 char *p;
11262 int rslt;
11263
11264 p = rs->buf;
11265 strcpy (p, "qTBuffer:");
11266 p += strlen (p);
11267 p += hexnumstr (p, offset);
11268 *p++ = ',';
11269 p += hexnumstr (p, len);
11270 *p++ = '\0';
11271
11272 putpkt (rs->buf);
11273 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11274 if (reply && *reply)
11275 {
11276 /* 'l' by itself means we're at the end of the buffer and
11277 there is nothing more to get. */
11278 if (*reply == 'l')
11279 return 0;
11280
11281 /* Convert the reply into binary. Limit the number of bytes to
11282 convert according to our passed-in buffer size, rather than
11283 what was returned in the packet; if the target is
11284 unexpectedly generous and gives us a bigger reply than we
11285 asked for, we don't want to crash. */
11286 rslt = hex2bin (target_buf, buf, len);
11287 return rslt;
11288 }
11289
11290 /* Something went wrong, flag as an error. */
11291 return -1;
11292}
11293
35b1e5cc 11294static void
37b25738 11295remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11296{
11297 struct remote_state *rs = get_remote_state ();
11298
4082afcc 11299 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 11300 {
ad91cd99
PA
11301 char *reply;
11302
bba74b36 11303 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11304 putpkt (rs->buf);
ad91cd99
PA
11305 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11306 if (*reply == '\0')
33da3f1c 11307 error (_("Target does not support this command."));
ad91cd99
PA
11308 if (strcmp (reply, "OK") != 0)
11309 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11310 }
11311 else if (val)
11312 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11313}
11314
dc146f7c
VP
11315static int
11316remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11317{
11318 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11319
fe978cb0
PA
11320 if (info && info->priv)
11321 return info->priv->core;
dc146f7c
VP
11322 return -1;
11323}
11324
4daf5ac0 11325static void
736d5b1f 11326remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11327{
11328 struct remote_state *rs = get_remote_state ();
ad91cd99 11329 char *reply;
4daf5ac0 11330
bba74b36 11331 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11332 putpkt (rs->buf);
ad91cd99
PA
11333 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11334 if (*reply == '\0')
4daf5ac0 11335 error (_("Target does not support this command."));
ad91cd99
PA
11336 if (strcmp (reply, "OK") != 0)
11337 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
11338}
11339
b3b9301e 11340static struct traceframe_info *
a893e81f 11341remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
11342{
11343 char *text;
11344
11345 text = target_read_stralloc (&current_target,
11346 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11347 if (text != NULL)
11348 {
11349 struct traceframe_info *info;
11350 struct cleanup *back_to = make_cleanup (xfree, text);
11351
11352 info = parse_traceframe_info (text);
11353 do_cleanups (back_to);
11354 return info;
11355 }
11356
11357 return NULL;
11358}
11359
405f8e94
SS
11360/* Handle the qTMinFTPILen packet. Returns the minimum length of
11361 instruction on which a fast tracepoint may be placed. Returns -1
11362 if the packet is not supported, and 0 if the minimum instruction
11363 length is unknown. */
11364
11365static int
0e67620a 11366remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
11367{
11368 struct remote_state *rs = get_remote_state ();
11369 char *reply;
11370
e886a173
PA
11371 /* If we're not debugging a process yet, the IPA can't be
11372 loaded. */
11373 if (!target_has_execution)
11374 return 0;
11375
11376 /* Make sure the remote is pointing at the right process. */
11377 set_general_process ();
11378
bba74b36 11379 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
11380 putpkt (rs->buf);
11381 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11382 if (*reply == '\0')
11383 return -1;
11384 else
11385 {
11386 ULONGEST min_insn_len;
11387
11388 unpack_varlen_hex (reply, &min_insn_len);
11389
11390 return (int) min_insn_len;
11391 }
11392}
11393
f6f899bf 11394static void
4da384be 11395remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 11396{
4082afcc 11397 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
11398 {
11399 struct remote_state *rs = get_remote_state ();
11400 char *buf = rs->buf;
11401 char *endbuf = rs->buf + get_remote_packet_size ();
11402 enum packet_result result;
11403
11404 gdb_assert (val >= 0 || val == -1);
11405 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11406 /* Send -1 as literal "-1" to avoid host size dependency. */
11407 if (val < 0)
11408 {
11409 *buf++ = '-';
11410 buf += hexnumstr (buf, (ULONGEST) -val);
11411 }
11412 else
11413 buf += hexnumstr (buf, (ULONGEST) val);
11414
11415 putpkt (rs->buf);
11416 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11417 result = packet_ok (rs->buf,
11418 &remote_protocol_packets[PACKET_QTBuffer_size]);
11419
11420 if (result != PACKET_OK)
11421 warning (_("Bogus reply from target: %s"), rs->buf);
11422 }
11423}
11424
f196051f 11425static int
d9e68a2c
TT
11426remote_set_trace_notes (struct target_ops *self,
11427 const char *user, const char *notes,
ca623f82 11428 const char *stop_notes)
f196051f
SS
11429{
11430 struct remote_state *rs = get_remote_state ();
11431 char *reply;
11432 char *buf = rs->buf;
11433 char *endbuf = rs->buf + get_remote_packet_size ();
11434 int nbytes;
11435
11436 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11437 if (user)
11438 {
11439 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 11440 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
11441 buf += 2 * nbytes;
11442 *buf++ = ';';
11443 }
11444 if (notes)
11445 {
11446 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 11447 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
11448 buf += 2 * nbytes;
11449 *buf++ = ';';
11450 }
11451 if (stop_notes)
11452 {
11453 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 11454 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
11455 buf += 2 * nbytes;
11456 *buf++ = ';';
11457 }
11458 /* Ensure the buffer is terminated. */
11459 *buf = '\0';
11460
11461 putpkt (rs->buf);
11462 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11463 if (*reply == '\0')
11464 return 0;
11465
11466 if (strcmp (reply, "OK") != 0)
11467 error (_("Bogus reply from target: %s"), reply);
11468
11469 return 1;
11470}
11471
d1feda86 11472static int
2c152180 11473remote_use_agent (struct target_ops *self, int use)
d1feda86 11474{
4082afcc 11475 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
11476 {
11477 struct remote_state *rs = get_remote_state ();
11478
11479 /* If the stub supports QAgent. */
bba74b36 11480 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
11481 putpkt (rs->buf);
11482 getpkt (&rs->buf, &rs->buf_size, 0);
11483
11484 if (strcmp (rs->buf, "OK") == 0)
11485 {
11486 use_agent = use;
11487 return 1;
11488 }
11489 }
11490
11491 return 0;
11492}
11493
11494static int
fe38f897 11495remote_can_use_agent (struct target_ops *self)
d1feda86 11496{
4082afcc 11497 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
11498}
11499
9accd112
MM
11500struct btrace_target_info
11501{
11502 /* The ptid of the traced thread. */
11503 ptid_t ptid;
f4abbc16
MM
11504
11505 /* The obtained branch trace configuration. */
11506 struct btrace_config conf;
9accd112
MM
11507};
11508
f4abbc16
MM
11509/* Reset our idea of our target's btrace configuration. */
11510
11511static void
11512remote_btrace_reset (void)
11513{
11514 struct remote_state *rs = get_remote_state ();
11515
11516 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11517}
11518
9accd112
MM
11519/* Check whether the target supports branch tracing. */
11520
11521static int
043c3577 11522remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 11523{
4082afcc 11524 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 11525 return 0;
4082afcc 11526 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
11527 return 0;
11528
043c3577
MM
11529 switch (format)
11530 {
11531 case BTRACE_FORMAT_NONE:
11532 return 0;
11533
11534 case BTRACE_FORMAT_BTS:
11535 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
11536 }
11537
11538 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
11539}
11540
f4abbc16
MM
11541/* Synchronize the configuration with the target. */
11542
11543static void
11544btrace_sync_conf (const struct btrace_config *conf)
11545{
d33501a5
MM
11546 struct packet_config *packet;
11547 struct remote_state *rs;
11548 char *buf, *pos, *endbuf;
11549
11550 rs = get_remote_state ();
11551 buf = rs->buf;
11552 endbuf = buf + get_remote_packet_size ();
11553
11554 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
11555 if (packet_config_support (packet) == PACKET_ENABLE
11556 && conf->bts.size != rs->btrace_config.bts.size)
11557 {
11558 pos = buf;
11559 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
11560 conf->bts.size);
11561
11562 putpkt (buf);
11563 getpkt (&buf, &rs->buf_size, 0);
11564
11565 if (packet_ok (buf, packet) == PACKET_ERROR)
11566 {
11567 if (buf[0] == 'E' && buf[1] == '.')
11568 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
11569 else
11570 error (_("Failed to configure the BTS buffer size."));
11571 }
11572
11573 rs->btrace_config.bts.size = conf->bts.size;
11574 }
f4abbc16
MM
11575}
11576
11577/* Read the current thread's btrace configuration from the target and
11578 store it into CONF. */
11579
11580static void
11581btrace_read_config (struct btrace_config *conf)
11582{
11583 char *xml;
11584
11585 xml = target_read_stralloc (&current_target,
11586 TARGET_OBJECT_BTRACE_CONF, "");
11587 if (xml != NULL)
11588 {
11589 struct cleanup *cleanup;
11590
11591 cleanup = make_cleanup (xfree, xml);
11592 parse_xml_btrace_conf (conf, xml);
11593 do_cleanups (cleanup);
11594 }
11595}
11596
9accd112
MM
11597/* Enable branch tracing. */
11598
11599static struct btrace_target_info *
f4abbc16
MM
11600remote_enable_btrace (struct target_ops *self, ptid_t ptid,
11601 const struct btrace_config *conf)
9accd112
MM
11602{
11603 struct btrace_target_info *tinfo = NULL;
11604 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11605 struct remote_state *rs = get_remote_state ();
11606 char *buf = rs->buf;
11607 char *endbuf = rs->buf + get_remote_packet_size ();
11608
4082afcc 11609 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11610 error (_("Target does not support branch tracing."));
11611
f4abbc16
MM
11612 btrace_sync_conf (conf);
11613
9accd112
MM
11614 set_general_thread (ptid);
11615
11616 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11617 putpkt (rs->buf);
11618 getpkt (&rs->buf, &rs->buf_size, 0);
11619
11620 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11621 {
11622 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11623 error (_("Could not enable branch tracing for %s: %s"),
11624 target_pid_to_str (ptid), rs->buf + 2);
11625 else
11626 error (_("Could not enable branch tracing for %s."),
11627 target_pid_to_str (ptid));
11628 }
11629
11630 tinfo = xzalloc (sizeof (*tinfo));
11631 tinfo->ptid = ptid;
11632
f4abbc16
MM
11633 /* If we fail to read the configuration, we lose some information, but the
11634 tracing itself is not impacted. */
492d29ea
PA
11635 TRY
11636 {
11637 btrace_read_config (&tinfo->conf);
11638 }
11639 CATCH (err, RETURN_MASK_ERROR)
11640 {
11641 if (err.message != NULL)
11642 warning ("%s", err.message);
11643 }
11644 END_CATCH
f4abbc16 11645
9accd112
MM
11646 return tinfo;
11647}
11648
11649/* Disable branch tracing. */
11650
11651static void
25e95349
TT
11652remote_disable_btrace (struct target_ops *self,
11653 struct btrace_target_info *tinfo)
9accd112
MM
11654{
11655 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11656 struct remote_state *rs = get_remote_state ();
11657 char *buf = rs->buf;
11658 char *endbuf = rs->buf + get_remote_packet_size ();
11659
4082afcc 11660 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11661 error (_("Target does not support branch tracing."));
11662
11663 set_general_thread (tinfo->ptid);
11664
11665 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11666 putpkt (rs->buf);
11667 getpkt (&rs->buf, &rs->buf_size, 0);
11668
11669 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11670 {
11671 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11672 error (_("Could not disable branch tracing for %s: %s"),
11673 target_pid_to_str (tinfo->ptid), rs->buf + 2);
11674 else
11675 error (_("Could not disable branch tracing for %s."),
11676 target_pid_to_str (tinfo->ptid));
11677 }
11678
11679 xfree (tinfo);
11680}
11681
11682/* Teardown branch tracing. */
11683
11684static void
1777056d
TT
11685remote_teardown_btrace (struct target_ops *self,
11686 struct btrace_target_info *tinfo)
9accd112
MM
11687{
11688 /* We must not talk to the target during teardown. */
11689 xfree (tinfo);
11690}
11691
11692/* Read the branch trace. */
11693
969c39fb 11694static enum btrace_error
39c49f83 11695remote_read_btrace (struct target_ops *self,
734b0e4b 11696 struct btrace_data *btrace,
969c39fb 11697 struct btrace_target_info *tinfo,
9accd112
MM
11698 enum btrace_read_type type)
11699{
11700 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11701 struct remote_state *rs = get_remote_state ();
969c39fb 11702 struct cleanup *cleanup;
9accd112
MM
11703 const char *annex;
11704 char *xml;
11705
4082afcc 11706 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
11707 error (_("Target does not support branch tracing."));
11708
11709#if !defined(HAVE_LIBEXPAT)
11710 error (_("Cannot process branch tracing result. XML parsing not supported."));
11711#endif
11712
11713 switch (type)
11714 {
864089d2 11715 case BTRACE_READ_ALL:
9accd112
MM
11716 annex = "all";
11717 break;
864089d2 11718 case BTRACE_READ_NEW:
9accd112
MM
11719 annex = "new";
11720 break;
969c39fb
MM
11721 case BTRACE_READ_DELTA:
11722 annex = "delta";
11723 break;
9accd112
MM
11724 default:
11725 internal_error (__FILE__, __LINE__,
11726 _("Bad branch tracing read type: %u."),
11727 (unsigned int) type);
11728 }
11729
11730 xml = target_read_stralloc (&current_target,
11731 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
11732 if (xml == NULL)
11733 return BTRACE_ERR_UNKNOWN;
9accd112 11734
969c39fb 11735 cleanup = make_cleanup (xfree, xml);
734b0e4b 11736 parse_xml_btrace (btrace, xml);
969c39fb 11737 do_cleanups (cleanup);
9accd112 11738
969c39fb 11739 return BTRACE_ERR_NONE;
9accd112
MM
11740}
11741
f4abbc16
MM
11742static const struct btrace_config *
11743remote_btrace_conf (struct target_ops *self,
11744 const struct btrace_target_info *tinfo)
11745{
11746 return &tinfo->conf;
11747}
11748
ced63ec0 11749static int
5436ff03 11750remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 11751{
4082afcc
PA
11752 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11753 == PACKET_ENABLE);
ced63ec0
GB
11754}
11755
9dd130a0
TT
11756/* Implementation of to_load. */
11757
11758static void
9cbe5fff 11759remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
11760{
11761 generic_load (name, from_tty);
11762}
11763
c906108c 11764static void
fba45db2 11765init_remote_ops (void)
c906108c 11766{
c5aa993b 11767 remote_ops.to_shortname = "remote";
c906108c 11768 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 11769 remote_ops.to_doc =
c906108c 11770 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
11771Specify the serial device it is connected to\n\
11772(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
11773 remote_ops.to_open = remote_open;
11774 remote_ops.to_close = remote_close;
c906108c 11775 remote_ops.to_detach = remote_detach;
6ad8ae5c 11776 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 11777 remote_ops.to_resume = remote_resume;
c906108c
SS
11778 remote_ops.to_wait = remote_wait;
11779 remote_ops.to_fetch_registers = remote_fetch_registers;
11780 remote_ops.to_store_registers = remote_store_registers;
11781 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 11782 remote_ops.to_files_info = remote_files_info;
c906108c
SS
11783 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
11784 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
11785 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
11786 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
11787 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
11788 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
11789 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
11790 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
11791 remote_ops.to_watchpoint_addr_within_range =
11792 remote_watchpoint_addr_within_range;
3c3bea1c
GS
11793 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
11794 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
11795 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
11796 remote_ops.to_region_ok_for_hw_watchpoint
11797 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
11798 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
11799 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 11800 remote_ops.to_kill = remote_kill;
9dd130a0 11801 remote_ops.to_load = remote_load;
c906108c 11802 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 11803 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 11804 remote_ops.to_program_signals = remote_program_signals;
c906108c 11805 remote_ops.to_thread_alive = remote_thread_alive;
e8032dde 11806 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 11807 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 11808 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 11809 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 11810 remote_ops.to_stop = remote_stop;
4b8a223f 11811 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 11812 remote_ops.to_rcmd = remote_rcmd;
49d03eab 11813 remote_ops.to_log_command = serial_log_command;
38691318 11814 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 11815 remote_ops.to_stratum = process_stratum;
c35b1492
PA
11816 remote_ops.to_has_all_memory = default_child_has_all_memory;
11817 remote_ops.to_has_memory = default_child_has_memory;
11818 remote_ops.to_has_stack = default_child_has_stack;
11819 remote_ops.to_has_registers = default_child_has_registers;
11820 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 11821 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 11822 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 11823 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 11824 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
11825 remote_ops.to_flash_erase = remote_flash_erase;
11826 remote_ops.to_flash_done = remote_flash_done;
29709017 11827 remote_ops.to_read_description = remote_read_description;
08388c79 11828 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
11829 remote_ops.to_can_async_p = remote_can_async_p;
11830 remote_ops.to_is_async_p = remote_is_async_p;
11831 remote_ops.to_async = remote_async;
75c99385
PA
11832 remote_ops.to_terminal_inferior = remote_terminal_inferior;
11833 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 11834 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 11835 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
11836 remote_ops.to_supports_disable_randomization
11837 = remote_supports_disable_randomization;
7313baad
UW
11838 remote_ops.to_fileio_open = remote_hostio_open;
11839 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
11840 remote_ops.to_fileio_pread = remote_hostio_pread;
11841 remote_ops.to_fileio_close = remote_hostio_close;
11842 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 11843 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 11844 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 11845 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 11846 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 11847 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
11848 remote_ops.to_trace_init = remote_trace_init;
11849 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 11850 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
11851 remote_ops.to_download_trace_state_variable
11852 = remote_download_trace_state_variable;
d248b706
KY
11853 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
11854 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
11855 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
11856 remote_ops.to_trace_start = remote_trace_start;
11857 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 11858 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
11859 remote_ops.to_trace_stop = remote_trace_stop;
11860 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
11861 remote_ops.to_get_trace_state_variable_value
11862 = remote_get_trace_state_variable_value;
00bf0b85
SS
11863 remote_ops.to_save_trace_data = remote_save_trace_data;
11864 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
11865 remote_ops.to_upload_trace_state_variables
11866 = remote_upload_trace_state_variables;
00bf0b85 11867 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 11868 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 11869 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 11870 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 11871 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 11872 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 11873 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 11874 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 11875 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 11876 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
11877 remote_ops.to_static_tracepoint_marker_at
11878 = remote_static_tracepoint_marker_at;
11879 remote_ops.to_static_tracepoint_markers_by_strid
11880 = remote_static_tracepoint_markers_by_strid;
b3b9301e 11881 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
11882 remote_ops.to_use_agent = remote_use_agent;
11883 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
11884 remote_ops.to_supports_btrace = remote_supports_btrace;
11885 remote_ops.to_enable_btrace = remote_enable_btrace;
11886 remote_ops.to_disable_btrace = remote_disable_btrace;
11887 remote_ops.to_teardown_btrace = remote_teardown_btrace;
11888 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 11889 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
11890 remote_ops.to_augmented_libraries_svr4_read =
11891 remote_augmented_libraries_svr4_read;
c906108c
SS
11892}
11893
11894/* Set up the extended remote vector by making a copy of the standard
11895 remote vector and adding to it. */
11896
11897static void
fba45db2 11898init_extended_remote_ops (void)
c906108c
SS
11899{
11900 extended_remote_ops = remote_ops;
11901
0f71a2f6 11902 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 11903 extended_remote_ops.to_longname =
c906108c 11904 "Extended remote serial target in gdb-specific protocol";
c5aa993b 11905 extended_remote_ops.to_doc =
c906108c 11906 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
11907Specify the serial device it is connected to (e.g. /dev/ttya).";
11908 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
11909 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
11910 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
11911 extended_remote_ops.to_detach = extended_remote_detach;
11912 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 11913 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 11914 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
11915 extended_remote_ops.to_supports_disable_randomization
11916 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
11917}
11918
6426a772 11919static int
6a109b6b 11920remote_can_async_p (struct target_ops *ops)
6426a772 11921{
5d93a237
TT
11922 struct remote_state *rs = get_remote_state ();
11923
c6ebd6cf 11924 if (!target_async_permitted)
75c99385
PA
11925 /* We only enable async when the user specifically asks for it. */
11926 return 0;
11927
23860348 11928 /* We're async whenever the serial device is. */
5d93a237 11929 return serial_can_async_p (rs->remote_desc);
6426a772
JM
11930}
11931
11932static int
6a109b6b 11933remote_is_async_p (struct target_ops *ops)
6426a772 11934{
5d93a237
TT
11935 struct remote_state *rs = get_remote_state ();
11936
c6ebd6cf 11937 if (!target_async_permitted)
75c99385
PA
11938 /* We only enable async when the user specifically asks for it. */
11939 return 0;
11940
23860348 11941 /* We're async whenever the serial device is. */
5d93a237 11942 return serial_is_async_p (rs->remote_desc);
6426a772
JM
11943}
11944
2acceee2
JM
11945/* Pass the SERIAL event on and up to the client. One day this code
11946 will be able to delay notifying the client of an event until the
23860348 11947 point where an entire packet has been received. */
2acceee2 11948
2acceee2
JM
11949static serial_event_ftype remote_async_serial_handler;
11950
6426a772 11951static void
819cc324 11952remote_async_serial_handler (struct serial *scb, void *context)
6426a772 11953{
88b496c3
TT
11954 struct remote_state *rs = context;
11955
2acceee2
JM
11956 /* Don't propogate error information up to the client. Instead let
11957 the client find out about the error by querying the target. */
6a3753b3 11958 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
11959}
11960
74531fed
PA
11961static void
11962remote_async_inferior_event_handler (gdb_client_data data)
11963{
11964 inferior_event_handler (INF_REG_EVENT, NULL);
11965}
11966
2acceee2 11967static void
6a3753b3 11968remote_async (struct target_ops *ops, int enable)
2acceee2 11969{
5d93a237
TT
11970 struct remote_state *rs = get_remote_state ();
11971
6a3753b3 11972 if (enable)
2acceee2 11973 {
88b496c3 11974 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
11975
11976 /* If there are pending events in the stop reply queue tell the
11977 event loop to process them. */
11978 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
11979 mark_async_event_handler (remote_async_inferior_event_token);
2acceee2
JM
11980 }
11981 else
b7d2e916
PA
11982 {
11983 serial_async (rs->remote_desc, NULL, NULL);
11984 clear_async_event_handler (remote_async_inferior_event_token);
11985 }
6426a772
JM
11986}
11987
5a2468f5 11988static void
c2d11a7d 11989set_remote_cmd (char *args, int from_tty)
5a2468f5 11990{
635c7e8a 11991 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
11992}
11993
d471ea57
AC
11994static void
11995show_remote_cmd (char *args, int from_tty)
11996{
37a105a1 11997 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 11998 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
11999 struct cleanup *showlist_chain;
12000 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 12001 struct ui_out *uiout = current_uiout;
37a105a1
DJ
12002
12003 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12004 for (; list != NULL; list = list->next)
12005 if (strcmp (list->name, "Z-packet") == 0)
12006 continue;
427c3a89
DJ
12007 else if (list->type == not_set_cmd)
12008 /* Alias commands are exactly like the original, except they
12009 don't have the normal type. */
12010 continue;
12011 else
37a105a1
DJ
12012 {
12013 struct cleanup *option_chain
12014 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 12015
37a105a1
DJ
12016 ui_out_field_string (uiout, "name", list->name);
12017 ui_out_text (uiout, ": ");
427c3a89 12018 if (list->type == show_cmd)
5b9afe8a 12019 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
12020 else
12021 cmd_func (list, NULL, from_tty);
37a105a1
DJ
12022 /* Close the tuple. */
12023 do_cleanups (option_chain);
12024 }
427c3a89
DJ
12025
12026 /* Close the tuple. */
12027 do_cleanups (showlist_chain);
d471ea57 12028}
5a2468f5 12029
0f71a2f6 12030
23860348 12031/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
12032static void
12033remote_new_objfile (struct objfile *objfile)
12034{
5d93a237
TT
12035 struct remote_state *rs = get_remote_state ();
12036
12037 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 12038 remote_check_symbols ();
dc8acb97
MS
12039}
12040
00bf0b85
SS
12041/* Pull all the tracepoints defined on the target and create local
12042 data structures representing them. We don't want to create real
12043 tracepoints yet, we don't want to mess up the user's existing
12044 collection. */
12045
12046static int
ab6617cc 12047remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 12048{
00bf0b85
SS
12049 struct remote_state *rs = get_remote_state ();
12050 char *p;
d5551862 12051
00bf0b85
SS
12052 /* Ask for a first packet of tracepoint definition. */
12053 putpkt ("qTfP");
12054 getpkt (&rs->buf, &rs->buf_size, 0);
12055 p = rs->buf;
12056 while (*p && *p != 'l')
d5551862 12057 {
00bf0b85
SS
12058 parse_tracepoint_definition (p, utpp);
12059 /* Ask for another packet of tracepoint definition. */
12060 putpkt ("qTsP");
12061 getpkt (&rs->buf, &rs->buf_size, 0);
12062 p = rs->buf;
d5551862 12063 }
00bf0b85 12064 return 0;
d5551862
SS
12065}
12066
00bf0b85 12067static int
181e3713
TT
12068remote_upload_trace_state_variables (struct target_ops *self,
12069 struct uploaded_tsv **utsvp)
d5551862 12070{
00bf0b85 12071 struct remote_state *rs = get_remote_state ();
d5551862 12072 char *p;
d5551862 12073
00bf0b85
SS
12074 /* Ask for a first packet of variable definition. */
12075 putpkt ("qTfV");
d5551862
SS
12076 getpkt (&rs->buf, &rs->buf_size, 0);
12077 p = rs->buf;
00bf0b85 12078 while (*p && *p != 'l')
d5551862 12079 {
00bf0b85
SS
12080 parse_tsv_definition (p, utsvp);
12081 /* Ask for another packet of variable definition. */
12082 putpkt ("qTsV");
d5551862
SS
12083 getpkt (&rs->buf, &rs->buf_size, 0);
12084 p = rs->buf;
12085 }
00bf0b85 12086 return 0;
d5551862
SS
12087}
12088
c1e36e3e
PA
12089/* The "set/show range-stepping" show hook. */
12090
12091static void
12092show_range_stepping (struct ui_file *file, int from_tty,
12093 struct cmd_list_element *c,
12094 const char *value)
12095{
12096 fprintf_filtered (file,
12097 _("Debugger's willingness to use range stepping "
12098 "is %s.\n"), value);
12099}
12100
12101/* The "set/show range-stepping" set hook. */
12102
12103static void
12104set_range_stepping (char *ignore_args, int from_tty,
12105 struct cmd_list_element *c)
12106{
5d93a237
TT
12107 struct remote_state *rs = get_remote_state ();
12108
c1e36e3e
PA
12109 /* Whene enabling, check whether range stepping is actually
12110 supported by the target, and warn if not. */
12111 if (use_range_stepping)
12112 {
5d93a237 12113 if (rs->remote_desc != NULL)
c1e36e3e 12114 {
4082afcc 12115 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
12116 remote_vcont_probe (rs);
12117
4082afcc 12118 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
12119 && rs->supports_vCont.r)
12120 return;
12121 }
12122
12123 warning (_("Range stepping is not supported by the current target"));
12124 }
12125}
12126
c906108c 12127void
fba45db2 12128_initialize_remote (void)
c906108c 12129{
ea9c271d 12130 struct remote_state *rs;
9a7071a8 12131 struct cmd_list_element *cmd;
6f937416 12132 const char *cmd_name;
ea9c271d 12133
0f71a2f6 12134 /* architecture specific data */
2bc416ba 12135 remote_gdbarch_data_handle =
23860348 12136 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
12137 remote_g_packet_data_handle =
12138 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 12139
ea9c271d
DJ
12140 /* Initialize the per-target state. At the moment there is only one
12141 of these, not one per target. Only one target is active at a
cf792862
TT
12142 time. */
12143 remote_state = new_remote_state ();
ea9c271d 12144
c906108c
SS
12145 init_remote_ops ();
12146 add_target (&remote_ops);
12147
12148 init_extended_remote_ops ();
12149 add_target (&extended_remote_ops);
cce74817 12150
dc8acb97 12151 /* Hook into new objfile notification. */
06d3b283 12152 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
12153 /* We're no longer interested in notification events of an inferior
12154 when it exits. */
12155 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 12156
b803fb0f 12157 /* Set up signal handlers. */
934b9bac 12158 async_sigint_remote_token =
b803fb0f 12159 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 12160 async_sigint_remote_twice_token =
6d549500 12161 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 12162
c906108c
SS
12163#if 0
12164 init_remote_threadtests ();
12165#endif
12166
722247f1 12167 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 12168 /* set/show remote ... */
d471ea57 12169
1bedd215 12170 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
12171Remote protocol specific variables\n\
12172Configure various remote-protocol specific variables such as\n\
1bedd215 12173the packets being used"),
cff3e48b 12174 &remote_set_cmdlist, "set remote ",
23860348 12175 0 /* allow-unknown */, &setlist);
1bedd215 12176 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
12177Remote protocol specific variables\n\
12178Configure various remote-protocol specific variables such as\n\
1bedd215 12179the packets being used"),
cff3e48b 12180 &remote_show_cmdlist, "show remote ",
23860348 12181 0 /* allow-unknown */, &showlist);
5a2468f5 12182
1a966eab
AC
12183 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12184Compare section data on target to the exec file.\n\
95cf3b38
DT
12185Argument is a single section name (default: all loaded sections).\n\
12186To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
12187 &cmdlist);
12188
1a966eab
AC
12189 add_cmd ("packet", class_maintenance, packet_command, _("\
12190Send an arbitrary packet to a remote target.\n\
c906108c
SS
12191 maintenance packet TEXT\n\
12192If GDB is talking to an inferior via the GDB serial protocol, then\n\
12193this command sends the string TEXT to the inferior, and displays the\n\
12194response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 12195terminating `#' character and checksum."),
c906108c
SS
12196 &maintenancelist);
12197
7915a72c
AC
12198 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12199Set whether to send break if interrupted."), _("\
12200Show whether to send break if interrupted."), _("\
12201If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 12202 set_remotebreak, show_remotebreak,
e707bbc2 12203 &setlist, &showlist);
9a7071a8
JB
12204 cmd_name = "remotebreak";
12205 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12206 deprecate_cmd (cmd, "set remote interrupt-sequence");
12207 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12208 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12209 deprecate_cmd (cmd, "show remote interrupt-sequence");
12210
12211 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
12212 interrupt_sequence_modes, &interrupt_sequence_mode,
12213 _("\
9a7071a8
JB
12214Set interrupt sequence to remote target."), _("\
12215Show interrupt sequence to remote target."), _("\
12216Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12217 NULL, show_interrupt_sequence,
12218 &remote_set_cmdlist,
12219 &remote_show_cmdlist);
12220
12221 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12222 &interrupt_on_connect, _("\
12223Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12224Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12225If set, interrupt sequence is sent to remote target."),
12226 NULL, NULL,
12227 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 12228
23860348 12229 /* Install commands for configuring memory read/write packets. */
11cf8741 12230
1a966eab
AC
12231 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12232Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 12233 &setlist);
1a966eab
AC
12234 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12235Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
12236 &showlist);
12237 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
12238 set_memory_write_packet_size, _("\
12239Set the maximum number of bytes per memory-write packet.\n\
12240Specify the number of bytes in a packet or 0 (zero) for the\n\
12241default packet size. The actual limit is further reduced\n\
12242dependent on the target. Specify ``fixed'' to disable the\n\
12243further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12244 &remote_set_cmdlist);
12245 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
12246 set_memory_read_packet_size, _("\
12247Set the maximum number of bytes per memory-read packet.\n\
12248Specify the number of bytes in a packet or 0 (zero) for the\n\
12249default packet size. The actual limit is further reduced\n\
12250dependent on the target. Specify ``fixed'' to disable the\n\
12251further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12252 &remote_set_cmdlist);
12253 add_cmd ("memory-write-packet-size", no_class,
12254 show_memory_write_packet_size,
1a966eab 12255 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
12256 &remote_show_cmdlist);
12257 add_cmd ("memory-read-packet-size", no_class,
12258 show_memory_read_packet_size,
1a966eab 12259 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 12260 &remote_show_cmdlist);
c906108c 12261
b3f42336 12262 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
12263 &remote_hw_watchpoint_limit, _("\
12264Set the maximum number of target hardware watchpoints."), _("\
12265Show the maximum number of target hardware watchpoints."), _("\
12266Specify a negative limit for unlimited."),
3e43a32a
MS
12267 NULL, NULL, /* FIXME: i18n: The maximum
12268 number of target hardware
12269 watchpoints is %s. */
b3f42336 12270 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
12271 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12272 &remote_hw_watchpoint_length_limit, _("\
12273Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12274Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12275Specify a negative limit for unlimited."),
12276 NULL, NULL, /* FIXME: i18n: The maximum
12277 length (in bytes) of a target
12278 hardware watchpoint is %s. */
12279 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 12280 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
12281 &remote_hw_breakpoint_limit, _("\
12282Set the maximum number of target hardware breakpoints."), _("\
12283Show the maximum number of target hardware breakpoints."), _("\
12284Specify a negative limit for unlimited."),
3e43a32a
MS
12285 NULL, NULL, /* FIXME: i18n: The maximum
12286 number of target hardware
12287 breakpoints is %s. */
b3f42336 12288 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 12289
1b493192
PA
12290 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12291 &remote_address_size, _("\
4d28ad1e
AC
12292Set the maximum size of the address (in bits) in a memory packet."), _("\
12293Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
12294 NULL,
12295 NULL, /* FIXME: i18n: */
12296 &setlist, &showlist);
c906108c 12297
ca4f7f8b
PA
12298 init_all_packet_configs ();
12299
444abaca 12300 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 12301 "X", "binary-download", 1);
0f71a2f6 12302
444abaca 12303 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 12304 "vCont", "verbose-resume", 0);
506fb367 12305
89be2091
DJ
12306 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12307 "QPassSignals", "pass-signals", 0);
12308
9b224c5e
PA
12309 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12310 "QProgramSignals", "program-signals", 0);
12311
444abaca 12312 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 12313 "qSymbol", "symbol-lookup", 0);
dc8acb97 12314
444abaca 12315 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 12316 "P", "set-register", 1);
d471ea57 12317
444abaca 12318 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 12319 "p", "fetch-register", 1);
b96ec7ac 12320
444abaca 12321 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 12322 "Z0", "software-breakpoint", 0);
d471ea57 12323
444abaca 12324 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 12325 "Z1", "hardware-breakpoint", 0);
d471ea57 12326
444abaca 12327 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 12328 "Z2", "write-watchpoint", 0);
d471ea57 12329
444abaca 12330 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 12331 "Z3", "read-watchpoint", 0);
d471ea57 12332
444abaca 12333 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 12334 "Z4", "access-watchpoint", 0);
d471ea57 12335
0876f84a
DJ
12336 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12337 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 12338
23181151
DJ
12339 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12340 "qXfer:features:read", "target-features", 0);
12341
cfa9d6d9
DJ
12342 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12343 "qXfer:libraries:read", "library-info", 0);
12344
2268b414
JK
12345 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12346 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12347
fd79ecee
DJ
12348 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12349 "qXfer:memory-map:read", "memory-map", 0);
12350
0e7f50da
UW
12351 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12352 "qXfer:spu:read", "read-spu-object", 0);
12353
12354 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12355 "qXfer:spu:write", "write-spu-object", 0);
12356
07e059b5
VP
12357 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12358 "qXfer:osdata:read", "osdata", 0);
12359
dc146f7c
VP
12360 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12361 "qXfer:threads:read", "threads", 0);
12362
4aa995e1
PA
12363 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12364 "qXfer:siginfo:read", "read-siginfo-object", 0);
12365
12366 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12367 "qXfer:siginfo:write", "write-siginfo-object", 0);
12368
b3b9301e
PA
12369 add_packet_config_cmd
12370 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 12371 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 12372
169081d0
TG
12373 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12374 "qXfer:uib:read", "unwind-info-block", 0);
12375
444abaca 12376 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 12377 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
12378 0);
12379
711e434b
PM
12380 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12381 "qGetTIBAddr", "get-thread-information-block-address",
12382 0);
12383
40ab02ce
MS
12384 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12385 "bc", "reverse-continue", 0);
12386
12387 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12388 "bs", "reverse-step", 0);
12389
be2a5f71
DJ
12390 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12391 "qSupported", "supported-packets", 0);
12392
08388c79
DE
12393 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12394 "qSearch:memory", "search-memory", 0);
12395
bd3eecc3
PA
12396 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12397 "qTStatus", "trace-status", 0);
12398
a6b151f1
DJ
12399 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12400 "vFile:open", "hostio-open", 0);
12401
12402 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12403 "vFile:pread", "hostio-pread", 0);
12404
12405 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12406 "vFile:pwrite", "hostio-pwrite", 0);
12407
12408 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12409 "vFile:close", "hostio-close", 0);
12410
12411 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12412 "vFile:unlink", "hostio-unlink", 0);
12413
b9e7b9c3
UW
12414 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12415 "vFile:readlink", "hostio-readlink", 0);
12416
0a93529c
GB
12417 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
12418 "vFile:fstat", "hostio-fstat", 0);
12419
2d717e4f
DJ
12420 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12421 "vAttach", "attach", 0);
12422
12423 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12424 "vRun", "run", 0);
12425
a6f3e723
SL
12426 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12427 "QStartNoAckMode", "noack", 0);
12428
82f73884
PA
12429 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12430 "vKill", "kill", 0);
12431
0b16c5cf
PA
12432 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12433 "qAttached", "query-attached", 0);
12434
782b2b07 12435 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
12436 "ConditionalTracepoints",
12437 "conditional-tracepoints", 0);
3788aec7
LM
12438
12439 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12440 "ConditionalBreakpoints",
12441 "conditional-breakpoints", 0);
12442
d3ce09f5
SS
12443 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12444 "BreakpointCommands",
12445 "breakpoint-commands", 0);
12446
7a697b8d
SS
12447 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12448 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 12449
409873ef
SS
12450 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12451 "TracepointSource", "TracepointSource", 0);
12452
d914c394
SS
12453 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12454 "QAllow", "allow", 0);
12455
0fb4aa4b
PA
12456 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12457 "StaticTracepoints", "static-tracepoints", 0);
12458
1e4d1764
YQ
12459 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12460 "InstallInTrace", "install-in-trace", 0);
12461
0fb4aa4b
PA
12462 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12463 "qXfer:statictrace:read", "read-sdata-object", 0);
12464
78d85199
YQ
12465 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12466 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12467
03583c20
UW
12468 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12469 "QDisableRandomization", "disable-randomization", 0);
12470
d1feda86
YQ
12471 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12472 "QAgent", "agent", 0);
12473
f6f899bf
HAQ
12474 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12475 "QTBuffer:size", "trace-buffer-size", 0);
12476
9accd112
MM
12477 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12478 "Qbtrace:off", "disable-btrace", 0);
12479
12480 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12481 "Qbtrace:bts", "enable-btrace", 0);
12482
12483 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12484 "qXfer:btrace", "read-btrace", 0);
12485
f4abbc16
MM
12486 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12487 "qXfer:btrace-conf", "read-btrace-conf", 0);
12488
d33501a5
MM
12489 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
12490 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
12491
f7e6eed5
PA
12492 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
12493 "swbreak-feature", "swbreak-feature", 0);
12494
12495 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
12496 "hwbreak-feature", "hwbreak-feature", 0);
12497
ca4f7f8b
PA
12498 /* Assert that we've registered commands for all packet configs. */
12499 {
12500 int i;
12501
12502 for (i = 0; i < PACKET_MAX; i++)
12503 {
12504 /* Ideally all configs would have a command associated. Some
12505 still don't though. */
12506 int excepted;
12507
12508 switch (i)
12509 {
12510 case PACKET_QNonStop:
12511 case PACKET_multiprocess_feature:
12512 case PACKET_EnableDisableTracepoints_feature:
12513 case PACKET_tracenz_feature:
12514 case PACKET_DisconnectedTracing_feature:
12515 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
12516 case PACKET_qCRC:
12517 /* Additions to this list need to be well justified:
12518 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
12519 excepted = 1;
12520 break;
12521 default:
12522 excepted = 0;
12523 break;
12524 }
12525
12526 /* This catches both forgetting to add a config command, and
12527 forgetting to remove a packet from the exception list. */
12528 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12529 }
12530 }
12531
37a105a1
DJ
12532 /* Keep the old ``set remote Z-packet ...'' working. Each individual
12533 Z sub-packet has its own set and show commands, but users may
12534 have sets to this variable in their .gdbinit files (or in their
12535 documentation). */
e9e68a56 12536 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
12537 &remote_Z_packet_detect, _("\
12538Set use of remote protocol `Z' packets"), _("\
12539Show use of remote protocol `Z' packets "), _("\
3b64bf98 12540When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 12541packets."),
e9e68a56 12542 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
12543 show_remote_protocol_Z_packet_cmd,
12544 /* FIXME: i18n: Use of remote protocol
12545 `Z' packets is %s. */
e9e68a56 12546 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 12547
a6b151f1
DJ
12548 add_prefix_cmd ("remote", class_files, remote_command, _("\
12549Manipulate files on the remote system\n\
12550Transfer files to and from the remote target system."),
12551 &remote_cmdlist, "remote ",
12552 0 /* allow-unknown */, &cmdlist);
12553
12554 add_cmd ("put", class_files, remote_put_command,
12555 _("Copy a local file to the remote system."),
12556 &remote_cmdlist);
12557
12558 add_cmd ("get", class_files, remote_get_command,
12559 _("Copy a remote file to the local system."),
12560 &remote_cmdlist);
12561
12562 add_cmd ("delete", class_files, remote_delete_command,
12563 _("Delete a remote file."),
12564 &remote_cmdlist);
12565
2d717e4f
DJ
12566 remote_exec_file = xstrdup ("");
12567 add_setshow_string_noescape_cmd ("exec-file", class_files,
12568 &remote_exec_file, _("\
12569Set the remote pathname for \"run\""), _("\
12570Show the remote pathname for \"run\""), NULL, NULL, NULL,
12571 &remote_set_cmdlist, &remote_show_cmdlist);
12572
c1e36e3e
PA
12573 add_setshow_boolean_cmd ("range-stepping", class_run,
12574 &use_range_stepping, _("\
12575Enable or disable range stepping."), _("\
12576Show whether target-assisted range stepping is enabled."), _("\
12577If on, and the target supports it, when stepping a source line, GDB\n\
12578tells the target to step the corresponding range of addresses itself instead\n\
12579of issuing multiple single-steps. This speeds up source level\n\
12580stepping. If off, GDB always issues single-steps, even if range\n\
12581stepping is supported by the target. The default is on."),
12582 set_range_stepping,
12583 show_range_stepping,
12584 &setlist,
12585 &showlist);
12586
449092f6
CV
12587 /* Eventually initialize fileio. See fileio.c */
12588 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 12589
ba348170 12590 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 12591 special ptids with it set to != 0. */
ba348170
PA
12592 magic_null_ptid = ptid_build (42000, -1, 1);
12593 not_sent_ptid = ptid_build (42000, -2, 1);
12594 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
12595
12596 target_buf_size = 2048;
12597 target_buf = xmalloc (target_buf_size);
c906108c 12598}
10760264 12599