2011-12-05 Tristan Gingold <gingold@adacore.com>
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
6aba47ca 3 Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
4c38e0a4 4 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
7b6bb8da 5 2010, 2011 Free Software Foundation, Inc.
c906108c 6
c5aa993b
JM
7 This file is part of GDB.
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
a9762ec7 11 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
a9762ec7 20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 21
23860348 22/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 23
c906108c
SS
24#include "defs.h"
25#include "gdb_string.h"
26#include <ctype.h>
27#include <fcntl.h>
c906108c
SS
28#include "inferior.h"
29#include "bfd.h"
30#include "symfile.h"
60250e8b 31#include "exceptions.h"
c906108c 32#include "target.h"
c5aa993b 33/*#include "terminal.h" */
c906108c
SS
34#include "gdbcmd.h"
35#include "objfiles.h"
36#include "gdb-stabs.h"
37#include "gdbthread.h"
c2c6d25f 38#include "remote.h"
4e052eda 39#include "regcache.h"
fd0407d6 40#include "value.h"
1ff9c3d6 41#include "gdb_assert.h"
6867ae3e 42#include "observer.h"
a77053c2 43#include "solib.h"
37a105a1
DJ
44#include "cli/cli-decode.h"
45#include "cli/cli-setshow.h"
424163ea 46#include "target-descriptions.h"
c906108c 47
7a292a7a 48#include <ctype.h>
9846de1b 49#include <sys/time.h>
c906108c 50
43ff13b4 51#include "event-loop.h"
c2c6d25f 52#include "event-top.h"
2acceee2 53#include "inf-loop.h"
43ff13b4 54
c906108c
SS
55#include <signal.h>
56#include "serial.h"
57
6240bebf
MS
58#include "gdbcore.h" /* for exec_bfd */
59
449092f6 60#include "remote-fileio.h"
a6b151f1 61#include "gdb/fileio.h"
3e88cf8d 62#include "gdb_stat.h"
dc146f7c 63#include "xml-support.h"
449092f6 64
fd79ecee
DJ
65#include "memory-map.h"
66
35b1e5cc
SS
67#include "tracepoint.h"
68#include "ax.h"
69#include "ax-gdb.h"
70
0df8b418 71/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
72static char *target_buf;
73static long target_buf_size;
74/*static*/ void
9355b391
SS
75encode_actions (struct breakpoint *t, struct bp_location *tloc,
76 char ***tdp_actions, char ***stepping_actions);
35b1e5cc 77
6765f3e5
DJ
78/* The size to align memory write packets, when practical. The protocol
79 does not guarantee any alignment, and gdb will generate short
80 writes and unaligned writes, but even as a best-effort attempt this
81 can improve bulk transfers. For instance, if a write is misaligned
82 relative to the target's data bus, the stub may need to make an extra
83 round trip fetching data from the target. This doesn't make a
84 huge difference, but it's easy to do, so we try to be helpful.
85
86 The alignment chosen is arbitrary; usually data bus width is
87 important here, not the possibly larger cache line size. */
88enum { REMOTE_ALIGN_WRITES = 16 };
89
23860348 90/* Prototypes for local functions. */
6426a772
JM
91static void cleanup_sigint_signal_handler (void *dummy);
92static void initialize_sigint_signal_handler (void);
6d820c5c 93static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed
PA
94static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
95 int forever);
6426a772 96
a14ed312
KB
97static void handle_remote_sigint (int);
98static void handle_remote_sigint_twice (int);
99static void async_remote_interrupt (gdb_client_data);
100void async_remote_interrupt_twice (gdb_client_data);
43ff13b4 101
a14ed312 102static void remote_files_info (struct target_ops *ignore);
c906108c 103
316f2060 104static void remote_prepare_to_store (struct regcache *regcache);
c906108c 105
a14ed312 106static void remote_open (char *name, int from_tty);
c906108c 107
a14ed312 108static void extended_remote_open (char *name, int from_tty);
c906108c 109
75c99385 110static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
c906108c 111
a14ed312 112static void remote_close (int quitting);
c906108c 113
136d6dae 114static void remote_mourn (struct target_ops *ops);
c906108c 115
a14ed312 116static void extended_remote_restart (void);
c906108c 117
136d6dae 118static void extended_remote_mourn (struct target_ops *);
c906108c 119
a14ed312 120static void remote_mourn_1 (struct target_ops *);
c906108c 121
6d820c5c 122static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 123
a14ed312 124static int readchar (int timeout);
c906108c 125
7d85a9c0 126static void remote_kill (struct target_ops *ops);
c906108c 127
a14ed312 128static int tohex (int nib);
c906108c 129
75c99385
PA
130static int remote_can_async_p (void);
131
132static int remote_is_async_p (void);
133
134static void remote_async (void (*callback) (enum inferior_event_type event_type,
135 void *context), void *context);
136
136d6dae 137static void remote_detach (struct target_ops *ops, char *args, int from_tty);
c906108c 138
a14ed312 139static void remote_interrupt (int signo);
c906108c 140
a14ed312 141static void remote_interrupt_twice (int signo);
7a292a7a 142
a14ed312 143static void interrupt_query (void);
c906108c 144
79d7f229
PA
145static void set_general_thread (struct ptid ptid);
146static void set_continue_thread (struct ptid ptid);
c906108c 147
a14ed312 148static void get_offsets (void);
c906108c 149
6d820c5c
DJ
150static void skip_frame (void);
151
152static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 153
a14ed312 154static int hexnumlen (ULONGEST num);
c906108c 155
a14ed312 156static void init_remote_ops (void);
c906108c 157
a14ed312 158static void init_extended_remote_ops (void);
c906108c 159
94cc34af 160static void remote_stop (ptid_t);
c906108c 161
a14ed312 162static int ishex (int ch, int *val);
c906108c 163
a14ed312 164static int stubhex (int ch);
c906108c 165
a14ed312 166static int hexnumstr (char *, ULONGEST);
c906108c 167
a14ed312 168static int hexnumnstr (char *, ULONGEST, int);
2df3850c 169
a14ed312 170static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 171
a14ed312 172static void print_packet (char *);
c906108c 173
a14ed312 174static void compare_sections_command (char *, int);
c906108c 175
a14ed312 176static void packet_command (char *, int);
c906108c 177
a14ed312 178static int stub_unpack_int (char *buff, int fieldlength);
c906108c 179
39f77062 180static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 181
a14ed312 182static void remote_find_new_threads (void);
c906108c 183
79d7f229 184static void record_currthread (ptid_t currthread);
c906108c 185
30559e10 186static int fromhex (int a);
c906108c 187
00bf0b85 188extern int hex2bin (const char *hex, gdb_byte *bin, int count);
c906108c 189
00bf0b85 190extern int bin2hex (const gdb_byte *bin, char *hex, int count);
234fa6d1 191
a14ed312 192static int putpkt_binary (char *buf, int cnt);
c906108c 193
a14ed312 194static void check_binary_download (CORE_ADDR addr);
c906108c 195
5a2468f5 196struct packet_config;
5a2468f5 197
a14ed312 198static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 199
d471ea57 200static void update_packet_config (struct packet_config *config);
5a2468f5 201
bb572ddd
DJ
202static void set_remote_protocol_packet_cmd (char *args, int from_tty,
203 struct cmd_list_element *c);
204
205static void show_remote_protocol_packet_cmd (struct ui_file *file,
206 int from_tty,
207 struct cmd_list_element *c,
208 const char *value);
209
82f73884
PA
210static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
211static ptid_t read_ptid (char *buf, char **obuf);
212
d914c394
SS
213static void remote_set_permissions (void);
214
d5551862 215struct remote_state;
00bf0b85 216static int remote_get_trace_status (struct trace_status *ts);
d5551862 217
00bf0b85
SS
218static int remote_upload_tracepoints (struct uploaded_tp **utpp);
219
220static int remote_upload_trace_state_variables (struct uploaded_tsv **utsvp);
221
c8d104ad
PA
222static void remote_query_supported (void);
223
224static void remote_check_symbols (struct objfile *objfile);
225
a14ed312 226void _initialize_remote (void);
c906108c 227
74531fed
PA
228struct stop_reply;
229static struct stop_reply *stop_reply_xmalloc (void);
230static void stop_reply_xfree (struct stop_reply *);
231static void do_stop_reply_xfree (void *arg);
232static void remote_parse_stop_reply (char *buf, struct stop_reply *);
233static void push_stop_reply (struct stop_reply *);
234static void remote_get_pending_stop_replies (void);
235static void discard_pending_stop_replies (int pid);
236static int peek_stop_reply (ptid_t ptid);
237
238static void remote_async_inferior_event_handler (gdb_client_data);
239static void remote_async_get_pending_events_handler (gdb_client_data);
240
d3fd5342
PA
241static void remote_terminal_ours (void);
242
d962ef82
DJ
243static int remote_read_description_p (struct target_ops *target);
244
176a6961 245static void remote_console_output (char *msg);
dde08ee1 246
74531fed
PA
247/* The non-stop remote protocol provisions for one pending stop reply.
248 This is where we keep it until it is acknowledged. */
249
250static struct stop_reply *pending_stop_reply = NULL;
251
a6b151f1
DJ
252/* For "remote". */
253
254static struct cmd_list_element *remote_cmdlist;
255
bb572ddd
DJ
256/* For "set remote" and "show remote". */
257
258static struct cmd_list_element *remote_set_cmdlist;
259static struct cmd_list_element *remote_show_cmdlist;
260
ea9c271d
DJ
261/* Description of the remote protocol state for the currently
262 connected target. This is per-target state, and independent of the
263 selected architecture. */
264
265struct remote_state
266{
267 /* A buffer to use for incoming packets, and its current size. The
268 buffer is grown dynamically for larger incoming packets.
269 Outgoing packets may also be constructed in this buffer.
270 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
271 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
272 packets. */
273 char *buf;
274 long buf_size;
be2a5f71
DJ
275
276 /* If we negotiated packet size explicitly (and thus can bypass
277 heuristics for the largest packet size that will not overflow
278 a buffer in the stub), this will be set to that packet size.
279 Otherwise zero, meaning to use the guessed size. */
280 long explicit_packet_size;
2d717e4f
DJ
281
282 /* remote_wait is normally called when the target is running and
283 waits for a stop reply packet. But sometimes we need to call it
284 when the target is already stopped. We can send a "?" packet
285 and have remote_wait read the response. Or, if we already have
286 the response, we can stash it in BUF and tell remote_wait to
287 skip calling getpkt. This flag is set when BUF contains a
288 stop reply packet and the target is not waiting. */
289 int cached_wait_status;
a6f3e723
SL
290
291 /* True, if in no ack mode. That is, neither GDB nor the stub will
292 expect acks from each other. The connection is assumed to be
293 reliable. */
294 int noack_mode;
82f73884
PA
295
296 /* True if we're connected in extended remote mode. */
297 int extended;
298
299 /* True if the stub reported support for multi-process
300 extensions. */
301 int multi_process_aware;
e24a49d8
PA
302
303 /* True if we resumed the target and we're waiting for the target to
304 stop. In the mean time, we can't start another command/query.
305 The remote server wouldn't be ready to process it, so we'd
306 timeout waiting for a reply that would never come and eventually
307 we'd close the connection. This can happen in asynchronous mode
308 because we allow GDB commands while the target is running. */
309 int waiting_for_stop_reply;
74531fed
PA
310
311 /* True if the stub reports support for non-stop mode. */
312 int non_stop_aware;
313
314 /* True if the stub reports support for vCont;t. */
315 int support_vCont_t;
782b2b07
SS
316
317 /* True if the stub reports support for conditional tracepoints. */
318 int cond_tracepoints;
3a29589a 319
7a697b8d
SS
320 /* True if the stub reports support for fast tracepoints. */
321 int fast_tracepoints;
322
0fb4aa4b
PA
323 /* True if the stub reports support for static tracepoints. */
324 int static_tracepoints;
325
1e4d1764
YQ
326 /* True if the stub reports support for installing tracepoint while
327 tracing. */
328 int install_in_trace;
329
d5551862
SS
330 /* True if the stub can continue running a trace while GDB is
331 disconnected. */
332 int disconnected_tracing;
333
d248b706
KY
334 /* True if the stub reports support for enabling and disabling
335 tracepoints while a trace experiment is running. */
336 int enable_disable_tracepoints;
337
3065dfb6
SS
338 /* True if the stub can collect strings using tracenz bytecode. */
339 int string_tracing;
340
3a29589a
DJ
341 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
342 responded to that. */
343 int ctrlc_pending_p;
ea9c271d
DJ
344};
345
dc146f7c
VP
346/* Private data that we'll store in (struct thread_info)->private. */
347struct private_thread_info
348{
349 char *extra;
350 int core;
351};
352
353static void
354free_private_thread_info (struct private_thread_info *info)
355{
356 xfree (info->extra);
357 xfree (info);
358}
359
82f73884
PA
360/* Returns true if the multi-process extensions are in effect. */
361static int
362remote_multi_process_p (struct remote_state *rs)
363{
364 return rs->extended && rs->multi_process_aware;
365}
366
ea9c271d
DJ
367/* This data could be associated with a target, but we do not always
368 have access to the current target when we need it, so for now it is
369 static. This will be fine for as long as only one target is in use
370 at a time. */
371static struct remote_state remote_state;
372
373static struct remote_state *
0b83947e 374get_remote_state_raw (void)
ea9c271d
DJ
375{
376 return &remote_state;
377}
378
379/* Description of the remote protocol for a given architecture. */
d01949b6 380
ad10f812
AC
381struct packet_reg
382{
383 long offset; /* Offset into G packet. */
384 long regnum; /* GDB's internal register number. */
385 LONGEST pnum; /* Remote protocol register number. */
b323314b 386 int in_g_packet; /* Always part of G packet. */
1cf3db46 387 /* long size in bytes; == register_size (target_gdbarch, regnum);
23860348 388 at present. */
1cf3db46 389 /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
c9f4d572 390 at present. */
ad10f812
AC
391};
392
ea9c271d 393struct remote_arch_state
d01949b6 394{
ad10f812
AC
395 /* Description of the remote protocol registers. */
396 long sizeof_g_packet;
b323314b
AC
397
398 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 399 (making an array gdbarch_num_regs in size). */
b323314b 400 struct packet_reg *regs;
ad10f812 401
d01949b6
AC
402 /* This is the size (in chars) of the first response to the ``g''
403 packet. It is used as a heuristic when determining the maximum
404 size of memory-read and memory-write packets. A target will
405 typically only reserve a buffer large enough to hold the ``g''
406 packet. The size does not include packet overhead (headers and
23860348 407 trailers). */
d01949b6
AC
408 long actual_register_packet_size;
409
410 /* This is the maximum size (in chars) of a non read/write packet.
23860348 411 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
412 long remote_packet_size;
413};
414
35b1e5cc
SS
415long sizeof_pkt = 2000;
416
417/* Utility: generate error from an incoming stub packet. */
418static void
419trace_error (char *buf)
420{
421 if (*buf++ != 'E')
422 return; /* not an error msg */
423 switch (*buf)
424 {
425 case '1': /* malformed packet error */
426 if (*++buf == '0') /* general case: */
427 error (_("remote.c: error in outgoing packet."));
428 else
429 error (_("remote.c: error in outgoing packet at field #%ld."),
430 strtol (buf, NULL, 16));
431 case '2':
432 error (_("trace API error 0x%s."), ++buf);
433 default:
434 error (_("Target returns error code '%s'."), buf);
435 }
436}
437
438/* Utility: wait for reply from stub, while accepting "O" packets. */
439static char *
440remote_get_noisy_reply (char **buf_p,
441 long *sizeof_buf)
442{
443 do /* Loop on reply from remote stub. */
444 {
445 char *buf;
a744cf53 446
0df8b418 447 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
448 getpkt (buf_p, sizeof_buf, 0);
449 buf = *buf_p;
ad91cd99 450 if (buf[0] == 'E')
35b1e5cc 451 trace_error (buf);
dde08ee1
PA
452 else if (strncmp (buf, "qRelocInsn:", strlen ("qRelocInsn:")) == 0)
453 {
454 ULONGEST ul;
455 CORE_ADDR from, to, org_to;
456 char *p, *pp;
457 int adjusted_size = 0;
458 volatile struct gdb_exception ex;
459
460 p = buf + strlen ("qRelocInsn:");
461 pp = unpack_varlen_hex (p, &ul);
462 if (*pp != ';')
cb91c06a 463 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
464 from = ul;
465
466 p = pp + 1;
a9cbf802 467 unpack_varlen_hex (p, &ul);
dde08ee1
PA
468 to = ul;
469
470 org_to = to;
471
472 TRY_CATCH (ex, RETURN_MASK_ALL)
473 {
474 gdbarch_relocate_instruction (target_gdbarch, &to, from);
475 }
476 if (ex.reason >= 0)
477 {
478 adjusted_size = to - org_to;
479
480 sprintf (buf, "qRelocInsn:%x", adjusted_size);
481 putpkt (buf);
482 }
483 else if (ex.reason < 0 && ex.error == MEMORY_ERROR)
484 {
485 /* Propagate memory errors silently back to the target.
486 The stub may have limited the range of addresses we
487 can write to, for example. */
488 putpkt ("E01");
489 }
490 else
491 {
492 /* Something unexpectedly bad happened. Be verbose so
493 we can tell what, and propagate the error back to the
494 stub, so it doesn't get stuck waiting for a
495 response. */
496 exception_fprintf (gdb_stderr, ex,
497 _("warning: relocating instruction: "));
498 putpkt ("E01");
499 }
500 }
ad91cd99 501 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
502 remote_console_output (buf + 1); /* 'O' message from stub */
503 else
0df8b418 504 return buf; /* Here's the actual reply. */
35b1e5cc
SS
505 }
506 while (1);
507}
3c3bea1c 508
d01949b6
AC
509/* Handle for retreving the remote protocol data from gdbarch. */
510static struct gdbarch_data *remote_gdbarch_data_handle;
511
ea9c271d
DJ
512static struct remote_arch_state *
513get_remote_arch_state (void)
d01949b6 514{
1cf3db46 515 return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
d01949b6
AC
516}
517
0b83947e
DJ
518/* Fetch the global remote target state. */
519
520static struct remote_state *
521get_remote_state (void)
522{
523 /* Make sure that the remote architecture state has been
524 initialized, because doing so might reallocate rs->buf. Any
525 function which calls getpkt also needs to be mindful of changes
526 to rs->buf, but this call limits the number of places which run
527 into trouble. */
528 get_remote_arch_state ();
529
530 return get_remote_state_raw ();
531}
532
74ca34ce
DJ
533static int
534compare_pnums (const void *lhs_, const void *rhs_)
535{
536 const struct packet_reg * const *lhs = lhs_;
537 const struct packet_reg * const *rhs = rhs_;
538
539 if ((*lhs)->pnum < (*rhs)->pnum)
540 return -1;
541 else if ((*lhs)->pnum == (*rhs)->pnum)
542 return 0;
543 else
544 return 1;
545}
546
c21236dc
PA
547static int
548map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 549{
74ca34ce 550 int regnum, num_remote_regs, offset;
74ca34ce 551 struct packet_reg **remote_regs;
ea9c271d 552
4a22f64d 553 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 554 {
c21236dc 555 struct packet_reg *r = &regs[regnum];
baef701f 556
4a22f64d 557 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
558 /* Do not try to fetch zero-sized (placeholder) registers. */
559 r->pnum = -1;
560 else
561 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
562
b323314b 563 r->regnum = regnum;
74ca34ce
DJ
564 }
565
566 /* Define the g/G packet format as the contents of each register
567 with a remote protocol number, in order of ascending protocol
568 number. */
569
4a22f64d 570 remote_regs = alloca (gdbarch_num_regs (gdbarch)
c21236dc 571 * sizeof (struct packet_reg *));
f57d151a 572 for (num_remote_regs = 0, regnum = 0;
4a22f64d 573 regnum < gdbarch_num_regs (gdbarch);
f57d151a 574 regnum++)
c21236dc
PA
575 if (regs[regnum].pnum != -1)
576 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 577
74ca34ce
DJ
578 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
579 compare_pnums);
580
581 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
582 {
583 remote_regs[regnum]->in_g_packet = 1;
584 remote_regs[regnum]->offset = offset;
4a22f64d 585 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
586 }
587
c21236dc
PA
588 return offset;
589}
590
591/* Given the architecture described by GDBARCH, return the remote
592 protocol register's number and the register's offset in the g/G
593 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
594 If the target does not have a mapping for REGNUM, return false,
595 otherwise, return true. */
596
597int
598remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
599 int *pnum, int *poffset)
600{
601 int sizeof_g_packet;
602 struct packet_reg *regs;
603 struct cleanup *old_chain;
604
605 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
606
607 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
608 old_chain = make_cleanup (xfree, regs);
609
610 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
611
612 *pnum = regs[regnum].pnum;
613 *poffset = regs[regnum].offset;
614
615 do_cleanups (old_chain);
616
617 return *pnum != -1;
618}
619
620static void *
621init_remote_state (struct gdbarch *gdbarch)
622{
623 struct remote_state *rs = get_remote_state_raw ();
624 struct remote_arch_state *rsa;
625
626 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
627
628 /* Use the architecture to build a regnum<->pnum table, which will be
629 1:1 unless a feature set specifies otherwise. */
630 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
631 gdbarch_num_regs (gdbarch),
632 struct packet_reg);
633
74ca34ce
DJ
634 /* Record the maximum possible size of the g packet - it may turn out
635 to be smaller. */
c21236dc 636 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 637
0df8b418 638 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
639 remote stubs have a hardwired buffer size of 400 bytes
640 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
641 as the maximum packet-size to ensure that the packet and an extra
642 NUL character can always fit in the buffer. This stops GDB
643 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
644 already a full buffer (As of 1999-12-04 that was most stubs). */
645 rsa->remote_packet_size = 400 - 1;
d01949b6 646
ea9c271d
DJ
647 /* This one is filled in when a ``g'' packet is received. */
648 rsa->actual_register_packet_size = 0;
649
650 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
651 default, adjust the size accordingly. Remember that each byte is
652 encoded as two characters. 32 is the overhead for the packet
653 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 654 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 655 little. */
ea9c271d
DJ
656 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
657 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 658
ea9c271d
DJ
659 /* Make sure that the packet buffer is plenty big enough for
660 this architecture. */
661 if (rs->buf_size < rsa->remote_packet_size)
662 {
663 rs->buf_size = 2 * rsa->remote_packet_size;
7fca722e 664 rs->buf = xrealloc (rs->buf, rs->buf_size);
ea9c271d 665 }
6d820c5c 666
ea9c271d
DJ
667 return rsa;
668}
669
670/* Return the current allowed size of a remote packet. This is
671 inferred from the current architecture, and should be used to
672 limit the length of outgoing packets. */
673static long
674get_remote_packet_size (void)
675{
be2a5f71 676 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
677 struct remote_arch_state *rsa = get_remote_arch_state ();
678
be2a5f71
DJ
679 if (rs->explicit_packet_size)
680 return rs->explicit_packet_size;
681
ea9c271d 682 return rsa->remote_packet_size;
d01949b6
AC
683}
684
ad10f812 685static struct packet_reg *
ea9c271d 686packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 687{
1cf3db46 688 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
b323314b
AC
689 return NULL;
690 else
ad10f812 691 {
ea9c271d 692 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 693
b323314b
AC
694 gdb_assert (r->regnum == regnum);
695 return r;
ad10f812 696 }
ad10f812
AC
697}
698
699static struct packet_reg *
ea9c271d 700packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 701{
b323314b 702 int i;
a744cf53 703
1cf3db46 704 for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
ad10f812 705 {
ea9c271d 706 struct packet_reg *r = &rsa->regs[i];
a744cf53 707
b323314b
AC
708 if (r->pnum == pnum)
709 return r;
ad10f812
AC
710 }
711 return NULL;
d01949b6
AC
712}
713
3c3bea1c
GS
714/* FIXME: graces/2002-08-08: These variables should eventually be
715 bound to an instance of the target object (as in gdbarch-tdep()),
716 when such a thing exists. */
717
718/* This is set to the data address of the access causing the target
719 to stop for a watchpoint. */
720static CORE_ADDR remote_watch_data_address;
721
94e08568 722/* This is non-zero if target stopped for a watchpoint. */
3c3bea1c
GS
723static int remote_stopped_by_watchpoint_p;
724
c906108c
SS
725static struct target_ops remote_ops;
726
727static struct target_ops extended_remote_ops;
728
6426a772
JM
729/* FIXME: cagney/1999-09-23: Even though getpkt was called with
730 ``forever'' still use the normal timeout mechanism. This is
731 currently used by the ASYNC code to guarentee that target reads
732 during the initial connect always time-out. Once getpkt has been
733 modified to return a timeout indication and, in turn
734 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 735 this can go away. */
6426a772
JM
736static int wait_forever_enabled_p = 1;
737
9a7071a8
JB
738/* Allow the user to specify what sequence to send to the remote
739 when he requests a program interruption: Although ^C is usually
740 what remote systems expect (this is the default, here), it is
741 sometimes preferable to send a break. On other systems such
742 as the Linux kernel, a break followed by g, which is Magic SysRq g
743 is required in order to interrupt the execution. */
744const char interrupt_sequence_control_c[] = "Ctrl-C";
745const char interrupt_sequence_break[] = "BREAK";
746const char interrupt_sequence_break_g[] = "BREAK-g";
747static const char *interrupt_sequence_modes[] =
748 {
749 interrupt_sequence_control_c,
750 interrupt_sequence_break,
751 interrupt_sequence_break_g,
752 NULL
753 };
754static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
755
756static void
757show_interrupt_sequence (struct ui_file *file, int from_tty,
758 struct cmd_list_element *c,
759 const char *value)
760{
761 if (interrupt_sequence_mode == interrupt_sequence_control_c)
762 fprintf_filtered (file,
763 _("Send the ASCII ETX character (Ctrl-c) "
764 "to the remote target to interrupt the "
765 "execution of the program.\n"));
766 else if (interrupt_sequence_mode == interrupt_sequence_break)
767 fprintf_filtered (file,
768 _("send a break signal to the remote target "
769 "to interrupt the execution of the program.\n"));
770 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
771 fprintf_filtered (file,
772 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
773 "the remote target to interrupt the execution "
774 "of Linux kernel.\n"));
775 else
776 internal_error (__FILE__, __LINE__,
777 _("Invalid value for interrupt_sequence_mode: %s."),
778 interrupt_sequence_mode);
779}
6426a772 780
9a7071a8
JB
781/* This boolean variable specifies whether interrupt_sequence is sent
782 to the remote target when gdb connects to it.
783 This is mostly needed when you debug the Linux kernel: The Linux kernel
784 expects BREAK g which is Magic SysRq g for connecting gdb. */
785static int interrupt_on_connect = 0;
c906108c 786
9a7071a8
JB
787/* This variable is used to implement the "set/show remotebreak" commands.
788 Since these commands are now deprecated in favor of "set/show remote
789 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
790static int remote_break;
791
9a7071a8
JB
792static void
793set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
794{
795 if (remote_break)
796 interrupt_sequence_mode = interrupt_sequence_break;
797 else
798 interrupt_sequence_mode = interrupt_sequence_control_c;
799}
800
801static void
802show_remotebreak (struct ui_file *file, int from_tty,
803 struct cmd_list_element *c,
804 const char *value)
805{
806}
807
c906108c
SS
808/* Descriptor for I/O to remote machine. Initialize it to NULL so that
809 remote_open knows that we don't have a file open when the program
810 starts. */
819cc324 811static struct serial *remote_desc = NULL;
c906108c 812
c906108c
SS
813/* This variable sets the number of bits in an address that are to be
814 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 815 leading zeros, the entire address would be sent. This variable
c906108c
SS
816 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
817 initial implementation of remote.c restricted the address sent in
818 memory packets to ``host::sizeof long'' bytes - (typically 32
819 bits). Consequently, for 64 bit targets, the upper 32 bits of an
820 address was never sent. Since fixing this bug may cause a break in
821 some remote targets this variable is principly provided to
23860348 822 facilitate backward compatibility. */
c906108c
SS
823
824static int remote_address_size;
825
75c99385
PA
826/* Temporary to track who currently owns the terminal. See
827 remote_terminal_* for more details. */
6426a772
JM
828
829static int remote_async_terminal_ours_p;
830
2d717e4f
DJ
831/* The executable file to use for "run" on the remote side. */
832
833static char *remote_exec_file = "";
834
11cf8741 835\f
11cf8741 836/* User configurable variables for the number of characters in a
ea9c271d
DJ
837 memory read/write packet. MIN (rsa->remote_packet_size,
838 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 839 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
840 (speed up transfers). The variables ``preferred_*'' (the user
841 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 842 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
843
844struct memory_packet_config
845{
846 char *name;
847 long size;
848 int fixed_p;
849};
850
851/* Compute the current size of a read/write packet. Since this makes
852 use of ``actual_register_packet_size'' the computation is dynamic. */
853
854static long
855get_memory_packet_size (struct memory_packet_config *config)
856{
d01949b6 857 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
858 struct remote_arch_state *rsa = get_remote_arch_state ();
859
11cf8741
JM
860 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
861 law?) that some hosts don't cope very well with large alloca()
862 calls. Eventually the alloca() code will be replaced by calls to
863 xmalloc() and make_cleanups() allowing this restriction to either
23860348 864 be lifted or removed. */
11cf8741
JM
865#ifndef MAX_REMOTE_PACKET_SIZE
866#define MAX_REMOTE_PACKET_SIZE 16384
867#endif
3de11b2e 868 /* NOTE: 20 ensures we can write at least one byte. */
11cf8741 869#ifndef MIN_REMOTE_PACKET_SIZE
3de11b2e 870#define MIN_REMOTE_PACKET_SIZE 20
11cf8741
JM
871#endif
872 long what_they_get;
873 if (config->fixed_p)
874 {
875 if (config->size <= 0)
876 what_they_get = MAX_REMOTE_PACKET_SIZE;
877 else
878 what_they_get = config->size;
879 }
880 else
881 {
ea9c271d 882 what_they_get = get_remote_packet_size ();
23860348 883 /* Limit the packet to the size specified by the user. */
11cf8741
JM
884 if (config->size > 0
885 && what_they_get > config->size)
886 what_they_get = config->size;
be2a5f71
DJ
887
888 /* Limit it to the size of the targets ``g'' response unless we have
889 permission from the stub to use a larger packet size. */
890 if (rs->explicit_packet_size == 0
891 && rsa->actual_register_packet_size > 0
892 && what_they_get > rsa->actual_register_packet_size)
893 what_they_get = rsa->actual_register_packet_size;
11cf8741
JM
894 }
895 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
896 what_they_get = MAX_REMOTE_PACKET_SIZE;
897 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
898 what_they_get = MIN_REMOTE_PACKET_SIZE;
6d820c5c
DJ
899
900 /* Make sure there is room in the global buffer for this packet
901 (including its trailing NUL byte). */
902 if (rs->buf_size < what_they_get + 1)
903 {
904 rs->buf_size = 2 * what_they_get;
905 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
906 }
907
11cf8741
JM
908 return what_they_get;
909}
910
0df8b418 911/* Update the size of a read/write packet. If they user wants
23860348 912 something really big then do a sanity check. */
11cf8741
JM
913
914static void
915set_memory_packet_size (char *args, struct memory_packet_config *config)
916{
917 int fixed_p = config->fixed_p;
918 long size = config->size;
a744cf53 919
11cf8741 920 if (args == NULL)
8a3fe4f8 921 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
922 else if (strcmp (args, "hard") == 0
923 || strcmp (args, "fixed") == 0)
924 fixed_p = 1;
925 else if (strcmp (args, "soft") == 0
926 || strcmp (args, "limit") == 0)
927 fixed_p = 0;
928 else
929 {
930 char *end;
a744cf53 931
11cf8741
JM
932 size = strtoul (args, &end, 0);
933 if (args == end)
8a3fe4f8 934 error (_("Invalid %s (bad syntax)."), config->name);
11cf8741
JM
935#if 0
936 /* Instead of explicitly capping the size of a packet to
937 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
938 instead allowed to set the size to something arbitrarily
23860348 939 large. */
11cf8741 940 if (size > MAX_REMOTE_PACKET_SIZE)
8a3fe4f8 941 error (_("Invalid %s (too large)."), config->name);
11cf8741
JM
942#endif
943 }
23860348 944 /* Extra checks? */
11cf8741
JM
945 if (fixed_p && !config->fixed_p)
946 {
e2e0b3e5
AC
947 if (! query (_("The target may not be able to correctly handle a %s\n"
948 "of %ld bytes. Change the packet size? "),
11cf8741 949 config->name, size))
8a3fe4f8 950 error (_("Packet size not changed."));
11cf8741 951 }
23860348 952 /* Update the config. */
11cf8741
JM
953 config->fixed_p = fixed_p;
954 config->size = size;
955}
956
957static void
958show_memory_packet_size (struct memory_packet_config *config)
959{
a3f17187 960 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 961 if (config->fixed_p)
a3f17187 962 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
963 get_memory_packet_size (config));
964 else
a3f17187 965 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
966 get_memory_packet_size (config));
967}
968
969static struct memory_packet_config memory_write_packet_config =
970{
971 "memory-write-packet-size",
972};
973
974static void
975set_memory_write_packet_size (char *args, int from_tty)
976{
977 set_memory_packet_size (args, &memory_write_packet_config);
978}
979
980static void
981show_memory_write_packet_size (char *args, int from_tty)
982{
983 show_memory_packet_size (&memory_write_packet_config);
984}
985
986static long
987get_memory_write_packet_size (void)
988{
989 return get_memory_packet_size (&memory_write_packet_config);
990}
991
992static struct memory_packet_config memory_read_packet_config =
993{
994 "memory-read-packet-size",
995};
996
997static void
998set_memory_read_packet_size (char *args, int from_tty)
999{
1000 set_memory_packet_size (args, &memory_read_packet_config);
1001}
1002
1003static void
1004show_memory_read_packet_size (char *args, int from_tty)
1005{
1006 show_memory_packet_size (&memory_read_packet_config);
1007}
1008
1009static long
1010get_memory_read_packet_size (void)
1011{
1012 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1013
11cf8741
JM
1014 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1015 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1016 increased beyond this. */
1017 if (size > get_remote_packet_size ())
1018 size = get_remote_packet_size ();
11cf8741
JM
1019 return size;
1020}
1021
11cf8741 1022\f
5a2468f5 1023/* Generic configuration support for packets the stub optionally
0df8b418 1024 supports. Allows the user to specify the use of the packet as well
23860348 1025 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1026
1027enum packet_support
1028 {
1029 PACKET_SUPPORT_UNKNOWN = 0,
1030 PACKET_ENABLE,
1031 PACKET_DISABLE
1032 };
1033
5a2468f5
JM
1034struct packet_config
1035 {
bb572ddd
DJ
1036 const char *name;
1037 const char *title;
7f19b9a2 1038 enum auto_boolean detect;
5a2468f5
JM
1039 enum packet_support support;
1040 };
1041
d471ea57 1042/* Analyze a packet's return value and update the packet config
23860348 1043 accordingly. */
d471ea57
AC
1044
1045enum packet_result
1046{
1047 PACKET_ERROR,
1048 PACKET_OK,
1049 PACKET_UNKNOWN
1050};
1051
5a2468f5 1052static void
d471ea57 1053update_packet_config (struct packet_config *config)
5a2468f5 1054{
d471ea57
AC
1055 switch (config->detect)
1056 {
7f19b9a2 1057 case AUTO_BOOLEAN_TRUE:
d471ea57
AC
1058 config->support = PACKET_ENABLE;
1059 break;
7f19b9a2 1060 case AUTO_BOOLEAN_FALSE:
d471ea57
AC
1061 config->support = PACKET_DISABLE;
1062 break;
7f19b9a2 1063 case AUTO_BOOLEAN_AUTO:
d471ea57
AC
1064 config->support = PACKET_SUPPORT_UNKNOWN;
1065 break;
1066 }
5a2468f5
JM
1067}
1068
1069static void
fba45db2 1070show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1071{
1072 char *support = "internal-error";
a744cf53 1073
5a2468f5
JM
1074 switch (config->support)
1075 {
1076 case PACKET_ENABLE:
1077 support = "enabled";
1078 break;
1079 case PACKET_DISABLE:
1080 support = "disabled";
1081 break;
1082 case PACKET_SUPPORT_UNKNOWN:
1083 support = "unknown";
1084 break;
1085 }
1086 switch (config->detect)
1087 {
7f19b9a2 1088 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1089 printf_filtered (_("Support for the `%s' packet "
1090 "is auto-detected, currently %s.\n"),
37a105a1 1091 config->name, support);
5a2468f5 1092 break;
7f19b9a2
AC
1093 case AUTO_BOOLEAN_TRUE:
1094 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1095 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1096 config->name, support);
8e248173 1097 break;
5a2468f5
JM
1098 }
1099}
1100
1101static void
bb572ddd
DJ
1102add_packet_config_cmd (struct packet_config *config, const char *name,
1103 const char *title, int legacy)
d471ea57 1104{
5a2468f5
JM
1105 char *set_doc;
1106 char *show_doc;
d471ea57 1107 char *cmd_name;
3ed07be4 1108
5a2468f5
JM
1109 config->name = name;
1110 config->title = title;
7f19b9a2 1111 config->detect = AUTO_BOOLEAN_AUTO;
8e248173 1112 config->support = PACKET_SUPPORT_UNKNOWN;
b435e160
AC
1113 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1114 name, title);
3e43a32a
MS
1115 show_doc = xstrprintf ("Show current use of remote "
1116 "protocol `%s' (%s) packet",
b435e160 1117 name, title);
d471ea57 1118 /* set/show TITLE-packet {auto,on,off} */
b435e160 1119 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1120 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1121 &config->detect, set_doc,
1122 show_doc, NULL, /* help_doc */
bb572ddd
DJ
1123 set_remote_protocol_packet_cmd,
1124 show_remote_protocol_packet_cmd,
1125 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1126 /* The command code copies the documentation strings. */
1127 xfree (set_doc);
1128 xfree (show_doc);
23860348 1129 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1130 if (legacy)
1131 {
1132 char *legacy_name;
a744cf53 1133
b435e160 1134 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1135 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1136 &remote_set_cmdlist);
d471ea57 1137 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1138 &remote_show_cmdlist);
d471ea57 1139 }
5a2468f5
JM
1140}
1141
d471ea57 1142static enum packet_result
a76d924d 1143packet_check_result (const char *buf)
5a2468f5 1144{
d471ea57 1145 if (buf[0] != '\0')
5a2468f5 1146 {
d471ea57 1147 /* The stub recognized the packet request. Check that the
23860348 1148 operation succeeded. */
a76d924d
DJ
1149 if (buf[0] == 'E'
1150 && isxdigit (buf[1]) && isxdigit (buf[2])
1151 && buf[3] == '\0')
1152 /* "Enn" - definitly an error. */
1153 return PACKET_ERROR;
1154
1155 /* Always treat "E." as an error. This will be used for
1156 more verbose error messages, such as E.memtypes. */
1157 if (buf[0] == 'E' && buf[1] == '.')
1158 return PACKET_ERROR;
1159
1160 /* The packet may or may not be OK. Just assume it is. */
1161 return PACKET_OK;
1162 }
1163 else
1164 /* The stub does not support the packet. */
1165 return PACKET_UNKNOWN;
1166}
1167
1168static enum packet_result
1169packet_ok (const char *buf, struct packet_config *config)
1170{
1171 enum packet_result result;
1172
1173 result = packet_check_result (buf);
1174 switch (result)
1175 {
1176 case PACKET_OK:
1177 case PACKET_ERROR:
1178 /* The stub recognized the packet request. */
d471ea57
AC
1179 switch (config->support)
1180 {
1181 case PACKET_SUPPORT_UNKNOWN:
1182 if (remote_debug)
1183 fprintf_unfiltered (gdb_stdlog,
1184 "Packet %s (%s) is supported\n",
1185 config->name, config->title);
1186 config->support = PACKET_ENABLE;
1187 break;
1188 case PACKET_DISABLE:
8e65ff28 1189 internal_error (__FILE__, __LINE__,
e2e0b3e5 1190 _("packet_ok: attempt to use a disabled packet"));
d471ea57
AC
1191 break;
1192 case PACKET_ENABLE:
1193 break;
1194 }
a76d924d
DJ
1195 break;
1196 case PACKET_UNKNOWN:
23860348 1197 /* The stub does not support the packet. */
d471ea57
AC
1198 switch (config->support)
1199 {
1200 case PACKET_ENABLE:
7f19b9a2 1201 if (config->detect == AUTO_BOOLEAN_AUTO)
d471ea57 1202 /* If the stub previously indicated that the packet was
23860348 1203 supported then there is a protocol error.. */
8a3fe4f8 1204 error (_("Protocol error: %s (%s) conflicting enabled responses."),
d471ea57
AC
1205 config->name, config->title);
1206 else
23860348 1207 /* The user set it wrong. */
8a3fe4f8 1208 error (_("Enabled packet %s (%s) not recognized by stub"),
d471ea57
AC
1209 config->name, config->title);
1210 break;
1211 case PACKET_SUPPORT_UNKNOWN:
1212 if (remote_debug)
1213 fprintf_unfiltered (gdb_stdlog,
1214 "Packet %s (%s) is NOT supported\n",
1215 config->name, config->title);
1216 config->support = PACKET_DISABLE;
1217 break;
1218 case PACKET_DISABLE:
1219 break;
1220 }
a76d924d 1221 break;
5a2468f5 1222 }
a76d924d
DJ
1223
1224 return result;
5a2468f5
JM
1225}
1226
444abaca
DJ
1227enum {
1228 PACKET_vCont = 0,
1229 PACKET_X,
1230 PACKET_qSymbol,
1231 PACKET_P,
1232 PACKET_p,
1233 PACKET_Z0,
1234 PACKET_Z1,
1235 PACKET_Z2,
1236 PACKET_Z3,
1237 PACKET_Z4,
a6b151f1
DJ
1238 PACKET_vFile_open,
1239 PACKET_vFile_pread,
1240 PACKET_vFile_pwrite,
1241 PACKET_vFile_close,
1242 PACKET_vFile_unlink,
0876f84a 1243 PACKET_qXfer_auxv,
23181151 1244 PACKET_qXfer_features,
cfa9d6d9 1245 PACKET_qXfer_libraries,
2268b414 1246 PACKET_qXfer_libraries_svr4,
fd79ecee 1247 PACKET_qXfer_memory_map,
0e7f50da
UW
1248 PACKET_qXfer_spu_read,
1249 PACKET_qXfer_spu_write,
07e059b5 1250 PACKET_qXfer_osdata,
dc146f7c 1251 PACKET_qXfer_threads,
0fb4aa4b 1252 PACKET_qXfer_statictrace_read,
b3b9301e 1253 PACKET_qXfer_traceframe_info,
711e434b 1254 PACKET_qGetTIBAddr,
444abaca 1255 PACKET_qGetTLSAddr,
be2a5f71 1256 PACKET_qSupported,
89be2091 1257 PACKET_QPassSignals,
08388c79 1258 PACKET_qSearch_memory,
2d717e4f
DJ
1259 PACKET_vAttach,
1260 PACKET_vRun,
a6f3e723 1261 PACKET_QStartNoAckMode,
82f73884 1262 PACKET_vKill,
4aa995e1
PA
1263 PACKET_qXfer_siginfo_read,
1264 PACKET_qXfer_siginfo_write,
0b16c5cf 1265 PACKET_qAttached,
782b2b07 1266 PACKET_ConditionalTracepoints,
7a697b8d 1267 PACKET_FastTracepoints,
0fb4aa4b 1268 PACKET_StaticTracepoints,
1e4d1764 1269 PACKET_InstallInTrace,
40ab02ce
MS
1270 PACKET_bc,
1271 PACKET_bs,
409873ef 1272 PACKET_TracepointSource,
d914c394 1273 PACKET_QAllow,
78d85199 1274 PACKET_qXfer_fdpic,
03583c20 1275 PACKET_QDisableRandomization,
444abaca
DJ
1276 PACKET_MAX
1277};
506fb367 1278
444abaca 1279static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97
MS
1280
1281static void
444abaca
DJ
1282set_remote_protocol_packet_cmd (char *args, int from_tty,
1283 struct cmd_list_element *c)
dc8acb97 1284{
444abaca 1285 struct packet_config *packet;
dc8acb97 1286
444abaca
DJ
1287 for (packet = remote_protocol_packets;
1288 packet < &remote_protocol_packets[PACKET_MAX];
1289 packet++)
1290 {
1291 if (&packet->detect == c->var)
1292 {
1293 update_packet_config (packet);
1294 return;
1295 }
1296 }
9b20d036 1297 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1298 c->name);
dc8acb97
MS
1299}
1300
5a2468f5 1301static void
444abaca
DJ
1302show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1303 struct cmd_list_element *c,
1304 const char *value)
5a2468f5 1305{
444abaca 1306 struct packet_config *packet;
5a2468f5 1307
444abaca
DJ
1308 for (packet = remote_protocol_packets;
1309 packet < &remote_protocol_packets[PACKET_MAX];
1310 packet++)
1311 {
1312 if (&packet->detect == c->var)
1313 {
1314 show_packet_config_cmd (packet);
1315 return;
1316 }
1317 }
9b20d036 1318 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1319 c->name);
5a2468f5
JM
1320}
1321
d471ea57
AC
1322/* Should we try one of the 'Z' requests? */
1323
1324enum Z_packet_type
1325{
1326 Z_PACKET_SOFTWARE_BP,
1327 Z_PACKET_HARDWARE_BP,
1328 Z_PACKET_WRITE_WP,
1329 Z_PACKET_READ_WP,
1330 Z_PACKET_ACCESS_WP,
1331 NR_Z_PACKET_TYPES
1332};
96baa820 1333
d471ea57 1334/* For compatibility with older distributions. Provide a ``set remote
23860348 1335 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1336
7f19b9a2 1337static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1338
1339static void
fba45db2
KB
1340set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1341 struct cmd_list_element *c)
96baa820 1342{
d471ea57 1343 int i;
a744cf53 1344
d471ea57
AC
1345 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1346 {
444abaca
DJ
1347 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1348 update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1349 }
96baa820
JM
1350}
1351
1352static void
08546159
AC
1353show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1354 struct cmd_list_element *c,
1355 const char *value)
96baa820 1356{
d471ea57 1357 int i;
a744cf53 1358
d471ea57
AC
1359 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1360 {
444abaca 1361 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1362 }
96baa820
JM
1363}
1364
9d1f7ab2
MS
1365/* Should we try the 'ThreadInfo' query packet?
1366
1367 This variable (NOT available to the user: auto-detect only!)
1368 determines whether GDB will use the new, simpler "ThreadInfo"
1369 query or the older, more complex syntax for thread queries.
802188a7 1370 This is an auto-detect variable (set to true at each connect,
9d1f7ab2
MS
1371 and set to false when the target fails to recognize it). */
1372
1373static int use_threadinfo_query;
1374static int use_threadextra_query;
1375
23860348 1376/* Tokens for use by the asynchronous signal handlers for SIGINT. */
d5d6fca5
DJ
1377static struct async_signal_handler *sigint_remote_twice_token;
1378static struct async_signal_handler *sigint_remote_token;
43ff13b4 1379
74531fed
PA
1380\f
1381/* Asynchronous signal handle registered as event loop source for
1382 when we have pending events ready to be passed to the core. */
1383
1384static struct async_event_handler *remote_async_inferior_event_token;
1385
1386/* Asynchronous signal handle registered as event loop source for when
1387 the remote sent us a %Stop notification. The registered callback
1388 will do a vStopped sequence to pull the rest of the events out of
1389 the remote side into our event queue. */
1390
1391static struct async_event_handler *remote_async_get_pending_events_token;
c906108c
SS
1392\f
1393
79d7f229
PA
1394static ptid_t magic_null_ptid;
1395static ptid_t not_sent_ptid;
1396static ptid_t any_thread_ptid;
1397
1398/* These are the threads which we last sent to the remote system. The
1399 TID member will be -1 for all or -2 for not sent yet. */
1400
1401static ptid_t general_thread;
1402static ptid_t continue_thread;
c5aa993b 1403
e6e4e701
PA
1404/* This the traceframe which we last selected on the remote system.
1405 It will be -1 if no traceframe is selected. */
1406static int remote_traceframe_number = -1;
1407
0b16c5cf
PA
1408/* Find out if the stub attached to PID (and hence GDB should offer to
1409 detach instead of killing it when bailing out). */
1410
1411static int
1412remote_query_attached (int pid)
1413{
1414 struct remote_state *rs = get_remote_state ();
1415
1416 if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1417 return 0;
1418
1419 if (remote_multi_process_p (rs))
1420 sprintf (rs->buf, "qAttached:%x", pid);
1421 else
1422 sprintf (rs->buf, "qAttached");
1423
1424 putpkt (rs->buf);
1425 getpkt (&rs->buf, &rs->buf_size, 0);
1426
1427 switch (packet_ok (rs->buf,
1554e9be 1428 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1429 {
1430 case PACKET_OK:
1431 if (strcmp (rs->buf, "1") == 0)
1432 return 1;
1433 break;
1434 case PACKET_ERROR:
1435 warning (_("Remote failure reply: %s"), rs->buf);
1436 break;
1437 case PACKET_UNKNOWN:
1438 break;
1439 }
1440
1441 return 0;
1442}
1443
1941c569
PA
1444/* Add PID to GDB's inferior table. Since we can be connected to a
1445 remote system before before knowing about any inferior, mark the
0b16c5cf
PA
1446 target with execution when we find the first inferior. If ATTACHED
1447 is 1, then we had just attached to this inferior. If it is 0, then
1448 we just created this inferior. If it is -1, then try querying the
1449 remote stub to find out if it had attached to the inferior or
1450 not. */
1941c569
PA
1451
1452static struct inferior *
0b16c5cf 1453remote_add_inferior (int pid, int attached)
1941c569 1454{
1941c569
PA
1455 struct inferior *inf;
1456
0b16c5cf
PA
1457 /* Check whether this process we're learning about is to be
1458 considered attached, or if is to be considered to have been
1459 spawned by the stub. */
1460 if (attached == -1)
1461 attached = remote_query_attached (pid);
1462
6c95b8df
PA
1463 if (gdbarch_has_global_solist (target_gdbarch))
1464 {
1465 /* If the target shares code across all inferiors, then every
1466 attach adds a new inferior. */
1467 inf = add_inferior (pid);
1468
1469 /* ... and every inferior is bound to the same program space.
1470 However, each inferior may still have its own address
1471 space. */
1472 inf->aspace = maybe_new_address_space ();
1473 inf->pspace = current_program_space;
1474 }
1475 else
1476 {
1477 /* In the traditional debugging scenario, there's a 1-1 match
1478 between program/address spaces. We simply bind the inferior
1479 to the program space's address space. */
1480 inf = current_inferior ();
1481 inferior_appeared (inf, pid);
1482 }
1941c569 1483
0b16c5cf
PA
1484 inf->attach_flag = attached;
1485
1941c569
PA
1486 return inf;
1487}
1488
1489/* Add thread PTID to GDB's thread list. Tag it as executing/running
1490 according to RUNNING. */
1491
c906108c 1492static void
1941c569 1493remote_add_thread (ptid_t ptid, int running)
c906108c 1494{
1941c569
PA
1495 add_thread (ptid);
1496
1497 set_executing (ptid, running);
1498 set_running (ptid, running);
1499}
1500
1501/* Come here when we learn about a thread id from the remote target.
1502 It may be the first time we hear about such thread, so take the
1503 opportunity to add it to GDB's thread list. In case this is the
1504 first time we're noticing its corresponding inferior, add it to
1505 GDB's inferior list as well. */
1506
1507static void
1508remote_notice_new_inferior (ptid_t currthread, int running)
1509{
c906108c
SS
1510 /* If this is a new thread, add it to GDB's thread list.
1511 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1512
1513 if (in_thread_list (currthread) && is_exited (currthread))
1514 {
1515 /* We're seeing an event on a thread id we knew had exited.
1516 This has to be a new thread reusing the old id. Add it. */
1941c569 1517 remote_add_thread (currthread, running);
82f73884
PA
1518 return;
1519 }
1520
79d7f229 1521 if (!in_thread_list (currthread))
c0a2216e 1522 {
1941c569 1523 struct inferior *inf = NULL;
bad34192 1524 int pid = ptid_get_pid (currthread);
1941c569 1525
bad34192
PA
1526 if (ptid_is_pid (inferior_ptid)
1527 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1528 {
1529 /* inferior_ptid has no thread member yet. This can happen
1530 with the vAttach -> remote_wait,"TAAthread:" path if the
1531 stub doesn't support qC. This is the first stop reported
1532 after an attach, so this is the main thread. Update the
1533 ptid in the thread list. */
bad34192
PA
1534 if (in_thread_list (pid_to_ptid (pid)))
1535 thread_change_ptid (inferior_ptid, currthread);
1536 else
1537 {
1538 remote_add_thread (currthread, running);
1539 inferior_ptid = currthread;
1540 }
dc146f7c 1541 return;
c0a2216e 1542 }
82f73884
PA
1543
1544 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1545 {
1546 /* inferior_ptid is not set yet. This can happen with the
1547 vRun -> remote_wait,"TAAthread:" path if the stub
1548 doesn't support qC. This is the first stop reported
1549 after an attach, so this is the main thread. Update the
1550 ptid in the thread list. */
dc146f7c 1551 thread_change_ptid (inferior_ptid, currthread);
82f73884 1552 return;
c0a2216e 1553 }
82f73884 1554
29c87f7f
PA
1555 /* When connecting to a target remote, or to a target
1556 extended-remote which already was debugging an inferior, we
1557 may not know about it yet. Add it before adding its child
1558 thread, so notifications are emitted in a sensible order. */
1559 if (!in_inferior_list (ptid_get_pid (currthread)))
0b16c5cf 1560 inf = remote_add_inferior (ptid_get_pid (currthread), -1);
29c87f7f 1561
82f73884 1562 /* This is really a new thread. Add it. */
1941c569
PA
1563 remote_add_thread (currthread, running);
1564
1565 /* If we found a new inferior, let the common code do whatever
1566 it needs to with it (e.g., read shared libraries, insert
1567 breakpoints). */
1568 if (inf != NULL)
1569 notice_new_inferior (currthread, running, 0);
c0a2216e 1570 }
c906108c
SS
1571}
1572
dc146f7c
VP
1573/* Return the private thread data, creating it if necessary. */
1574
1575struct private_thread_info *
1576demand_private_info (ptid_t ptid)
1577{
1578 struct thread_info *info = find_thread_ptid (ptid);
1579
1580 gdb_assert (info);
1581
1582 if (!info->private)
1583 {
1584 info->private = xmalloc (sizeof (*(info->private)));
1585 info->private_dtor = free_private_thread_info;
1586 info->private->core = -1;
1587 info->private->extra = 0;
1588 }
1589
1590 return info->private;
1591}
1592
74531fed
PA
1593/* Call this function as a result of
1594 1) A halt indication (T packet) containing a thread id
1595 2) A direct query of currthread
0df8b418 1596 3) Successful execution of set thread */
74531fed
PA
1597
1598static void
1599record_currthread (ptid_t currthread)
1600{
1601 general_thread = currthread;
74531fed
PA
1602}
1603
89be2091
DJ
1604static char *last_pass_packet;
1605
1606/* If 'QPassSignals' is supported, tell the remote stub what signals
1607 it can simply pass through to the inferior without reporting. */
1608
1609static void
2455069d 1610remote_pass_signals (int numsigs, unsigned char *pass_signals)
89be2091
DJ
1611{
1612 if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1613 {
1614 char *pass_packet, *p;
89be2091
DJ
1615 int count = 0, i;
1616
1617 gdb_assert (numsigs < 256);
1618 for (i = 0; i < numsigs; i++)
1619 {
2455069d 1620 if (pass_signals[i])
89be2091
DJ
1621 count++;
1622 }
1623 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1624 strcpy (pass_packet, "QPassSignals:");
1625 p = pass_packet + strlen (pass_packet);
1626 for (i = 0; i < numsigs; i++)
1627 {
2455069d 1628 if (pass_signals[i])
89be2091
DJ
1629 {
1630 if (i >= 16)
1631 *p++ = tohex (i >> 4);
1632 *p++ = tohex (i & 15);
1633 if (count)
1634 *p++ = ';';
1635 else
1636 break;
1637 count--;
1638 }
1639 }
1640 *p = 0;
1641 if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1642 {
1643 struct remote_state *rs = get_remote_state ();
1644 char *buf = rs->buf;
1645
1646 putpkt (pass_packet);
1647 getpkt (&rs->buf, &rs->buf_size, 0);
1648 packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1649 if (last_pass_packet)
1650 xfree (last_pass_packet);
1651 last_pass_packet = pass_packet;
1652 }
1653 else
1654 xfree (pass_packet);
1655 }
1656}
1657
79d7f229
PA
1658/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1659 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1660 thread. If GEN is set, set the general thread, if not, then set
1661 the step/continue thread. */
c906108c 1662static void
79d7f229 1663set_thread (struct ptid ptid, int gen)
c906108c 1664{
d01949b6 1665 struct remote_state *rs = get_remote_state ();
79d7f229 1666 ptid_t state = gen ? general_thread : continue_thread;
6d820c5c 1667 char *buf = rs->buf;
79d7f229 1668 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1669
79d7f229 1670 if (ptid_equal (state, ptid))
c906108c
SS
1671 return;
1672
79d7f229
PA
1673 *buf++ = 'H';
1674 *buf++ = gen ? 'g' : 'c';
1675 if (ptid_equal (ptid, magic_null_ptid))
1676 xsnprintf (buf, endbuf - buf, "0");
1677 else if (ptid_equal (ptid, any_thread_ptid))
1678 xsnprintf (buf, endbuf - buf, "0");
1679 else if (ptid_equal (ptid, minus_one_ptid))
1680 xsnprintf (buf, endbuf - buf, "-1");
1681 else
82f73884 1682 write_ptid (buf, endbuf, ptid);
79d7f229 1683 putpkt (rs->buf);
6d820c5c 1684 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1685 if (gen)
79d7f229 1686 general_thread = ptid;
c906108c 1687 else
79d7f229 1688 continue_thread = ptid;
c906108c 1689}
79d7f229
PA
1690
1691static void
1692set_general_thread (struct ptid ptid)
1693{
1694 set_thread (ptid, 1);
1695}
1696
1697static void
1698set_continue_thread (struct ptid ptid)
1699{
1700 set_thread (ptid, 0);
1701}
1702
3c9c4b83
PA
1703/* Change the remote current process. Which thread within the process
1704 ends up selected isn't important, as long as it is the same process
1705 as what INFERIOR_PTID points to.
1706
1707 This comes from that fact that there is no explicit notion of
1708 "selected process" in the protocol. The selected process for
1709 general operations is the process the selected general thread
1710 belongs to. */
1711
1712static void
1713set_general_process (void)
1714{
1715 struct remote_state *rs = get_remote_state ();
1716
1717 /* If the remote can't handle multiple processes, don't bother. */
1718 if (!remote_multi_process_p (rs))
1719 return;
1720
1721 /* We only need to change the remote current thread if it's pointing
1722 at some other process. */
1723 if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1724 set_general_thread (inferior_ptid);
1725}
1726
c906108c 1727\f
79d7f229
PA
1728/* Return nonzero if the thread PTID is still alive on the remote
1729 system. */
c906108c
SS
1730
1731static int
28439f5e 1732remote_thread_alive (struct target_ops *ops, ptid_t ptid)
c906108c 1733{
6d820c5c 1734 struct remote_state *rs = get_remote_state ();
82f73884 1735 char *p, *endp;
c906108c 1736
c0a2216e
PA
1737 if (ptid_equal (ptid, magic_null_ptid))
1738 /* The main thread is always alive. */
1739 return 1;
1740
1741 if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1742 /* The main thread is always alive. This can happen after a
1743 vAttach, if the remote side doesn't support
1744 multi-threading. */
1745 return 1;
1746
82f73884
PA
1747 p = rs->buf;
1748 endp = rs->buf + get_remote_packet_size ();
1749
1750 *p++ = 'T';
1751 write_ptid (p, endp, ptid);
1752
2e9f7625 1753 putpkt (rs->buf);
6d820c5c 1754 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 1755 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
1756}
1757
1758/* About these extended threadlist and threadinfo packets. They are
1759 variable length packets but, the fields within them are often fixed
1760 length. They are redundent enough to send over UDP as is the
1761 remote protocol in general. There is a matching unit test module
1762 in libstub. */
1763
cce74817
JM
1764#define OPAQUETHREADBYTES 8
1765
1766/* a 64 bit opaque identifier */
1767typedef unsigned char threadref[OPAQUETHREADBYTES];
1768
23860348 1769/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 1770 libstub protocol encoding, and remote.c. It is not particularly
23860348 1771 changable. */
cce74817
JM
1772
1773/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 1774 Plan to fix this. */
cce74817 1775
23860348 1776typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 1777
9d1f7ab2 1778/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 1779 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
1780
1781struct gdb_ext_thread_info
c5aa993b 1782 {
23860348 1783 threadref threadid; /* External form of thread reference. */
2bc416ba 1784 int active; /* Has state interesting to GDB?
23860348 1785 regs, stack. */
2bc416ba 1786 char display[256]; /* Brief state display, name,
cedea757 1787 blocked/suspended. */
23860348 1788 char shortname[32]; /* To be used to name threads. */
2bc416ba 1789 char more_display[256]; /* Long info, statistics, queue depth,
23860348 1790 whatever. */
c5aa993b 1791 };
cce74817
JM
1792
1793/* The volume of remote transfers can be limited by submitting
1794 a mask containing bits specifying the desired information.
1795 Use a union of these values as the 'selection' parameter to
0df8b418 1796 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
1797
1798#define TAG_THREADID 1
1799#define TAG_EXISTS 2
1800#define TAG_DISPLAY 4
1801#define TAG_THREADNAME 8
c5aa993b 1802#define TAG_MOREDISPLAY 16
cce74817 1803
23860348 1804#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 1805
b2dd6311 1806char *unpack_varlen_hex (char *buff, ULONGEST *result);
cce74817 1807
a14ed312 1808static char *unpack_nibble (char *buf, int *val);
cce74817 1809
a14ed312 1810static char *pack_nibble (char *buf, int nibble);
cce74817 1811
23860348 1812static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
cce74817 1813
a14ed312 1814static char *unpack_byte (char *buf, int *value);
cce74817 1815
a14ed312 1816static char *pack_int (char *buf, int value);
cce74817 1817
a14ed312 1818static char *unpack_int (char *buf, int *value);
cce74817 1819
a14ed312 1820static char *unpack_string (char *src, char *dest, int length);
cce74817 1821
23860348 1822static char *pack_threadid (char *pkt, threadref *id);
cce74817 1823
23860348 1824static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 1825
23860348 1826void int_to_threadref (threadref *id, int value);
cce74817 1827
23860348 1828static int threadref_to_int (threadref *ref);
cce74817 1829
23860348 1830static void copy_threadref (threadref *dest, threadref *src);
cce74817 1831
23860348 1832static int threadmatch (threadref *dest, threadref *src);
cce74817 1833
2bc416ba 1834static char *pack_threadinfo_request (char *pkt, int mode,
23860348 1835 threadref *id);
cce74817 1836
a14ed312 1837static int remote_unpack_thread_info_response (char *pkt,
23860348 1838 threadref *expectedref,
a14ed312
KB
1839 struct gdb_ext_thread_info
1840 *info);
cce74817
JM
1841
1842
2bc416ba 1843static int remote_get_threadinfo (threadref *threadid,
23860348 1844 int fieldset, /*TAG mask */
a14ed312 1845 struct gdb_ext_thread_info *info);
cce74817 1846
a14ed312
KB
1847static char *pack_threadlist_request (char *pkt, int startflag,
1848 int threadcount,
23860348 1849 threadref *nextthread);
cce74817 1850
a14ed312
KB
1851static int parse_threadlist_response (char *pkt,
1852 int result_limit,
23860348 1853 threadref *original_echo,
2bc416ba 1854 threadref *resultlist,
23860348 1855 int *doneflag);
cce74817 1856
a14ed312 1857static int remote_get_threadlist (int startflag,
23860348 1858 threadref *nextthread,
a14ed312
KB
1859 int result_limit,
1860 int *done,
2bc416ba 1861 int *result_count,
23860348 1862 threadref *threadlist);
cce74817 1863
23860348 1864typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 1865
a14ed312
KB
1866static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1867 void *context, int looplimit);
cce74817 1868
23860348 1869static int remote_newthread_step (threadref *ref, void *context);
cce74817 1870
82f73884
PA
1871
1872/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
1873 buffer we're allowed to write to. Returns
1874 BUF+CHARACTERS_WRITTEN. */
1875
1876static char *
1877write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1878{
1879 int pid, tid;
1880 struct remote_state *rs = get_remote_state ();
1881
1882 if (remote_multi_process_p (rs))
1883 {
1884 pid = ptid_get_pid (ptid);
1885 if (pid < 0)
1886 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1887 else
1888 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1889 }
1890 tid = ptid_get_tid (ptid);
1891 if (tid < 0)
1892 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1893 else
1894 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1895
1896 return buf;
1897}
1898
1899/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
1900 passed the last parsed char. Returns null_ptid on error. */
1901
1902static ptid_t
1903read_ptid (char *buf, char **obuf)
1904{
1905 char *p = buf;
1906 char *pp;
1907 ULONGEST pid = 0, tid = 0;
82f73884
PA
1908
1909 if (*p == 'p')
1910 {
1911 /* Multi-process ptid. */
1912 pp = unpack_varlen_hex (p + 1, &pid);
1913 if (*pp != '.')
b37520b6 1914 error (_("invalid remote ptid: %s"), p);
82f73884
PA
1915
1916 p = pp;
1917 pp = unpack_varlen_hex (p + 1, &tid);
1918 if (obuf)
1919 *obuf = pp;
1920 return ptid_build (pid, 0, tid);
1921 }
1922
1923 /* No multi-process. Just a tid. */
1924 pp = unpack_varlen_hex (p, &tid);
1925
1926 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
1927 what's in inferior_ptid, unless it's null at this point. If so,
1928 then since there's no way to know the pid of the reported
1929 threads, use the magic number. */
1930 if (ptid_equal (inferior_ptid, null_ptid))
1931 pid = ptid_get_pid (magic_null_ptid);
1932 else
1933 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
1934
1935 if (obuf)
1936 *obuf = pp;
1937 return ptid_build (pid, 0, tid);
1938}
1939
23860348 1940/* Encode 64 bits in 16 chars of hex. */
c906108c
SS
1941
1942static const char hexchars[] = "0123456789abcdef";
1943
1944static int
fba45db2 1945ishex (int ch, int *val)
c906108c
SS
1946{
1947 if ((ch >= 'a') && (ch <= 'f'))
1948 {
1949 *val = ch - 'a' + 10;
1950 return 1;
1951 }
1952 if ((ch >= 'A') && (ch <= 'F'))
1953 {
1954 *val = ch - 'A' + 10;
1955 return 1;
1956 }
1957 if ((ch >= '0') && (ch <= '9'))
1958 {
1959 *val = ch - '0';
1960 return 1;
1961 }
1962 return 0;
1963}
1964
1965static int
fba45db2 1966stubhex (int ch)
c906108c
SS
1967{
1968 if (ch >= 'a' && ch <= 'f')
1969 return ch - 'a' + 10;
1970 if (ch >= '0' && ch <= '9')
1971 return ch - '0';
1972 if (ch >= 'A' && ch <= 'F')
1973 return ch - 'A' + 10;
1974 return -1;
1975}
1976
1977static int
fba45db2 1978stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
1979{
1980 int nibble;
1981 int retval = 0;
1982
1983 while (fieldlength)
1984 {
1985 nibble = stubhex (*buff++);
1986 retval |= nibble;
1987 fieldlength--;
1988 if (fieldlength)
1989 retval = retval << 4;
1990 }
1991 return retval;
1992}
1993
1994char *
fba45db2 1995unpack_varlen_hex (char *buff, /* packet to parse */
b2dd6311 1996 ULONGEST *result)
c906108c
SS
1997{
1998 int nibble;
d49c44d5 1999 ULONGEST retval = 0;
c906108c
SS
2000
2001 while (ishex (*buff, &nibble))
2002 {
2003 buff++;
2004 retval = retval << 4;
2005 retval |= nibble & 0x0f;
2006 }
2007 *result = retval;
2008 return buff;
2009}
2010
2011static char *
fba45db2 2012unpack_nibble (char *buf, int *val)
c906108c 2013{
b7589f7d 2014 *val = fromhex (*buf++);
c906108c
SS
2015 return buf;
2016}
2017
2018static char *
fba45db2 2019pack_nibble (char *buf, int nibble)
c906108c
SS
2020{
2021 *buf++ = hexchars[(nibble & 0x0f)];
2022 return buf;
2023}
2024
2025static char *
fba45db2 2026pack_hex_byte (char *pkt, int byte)
c906108c
SS
2027{
2028 *pkt++ = hexchars[(byte >> 4) & 0xf];
2029 *pkt++ = hexchars[(byte & 0xf)];
2030 return pkt;
2031}
2032
2033static char *
fba45db2 2034unpack_byte (char *buf, int *value)
c906108c
SS
2035{
2036 *value = stub_unpack_int (buf, 2);
2037 return buf + 2;
2038}
2039
2040static char *
fba45db2 2041pack_int (char *buf, int value)
c906108c
SS
2042{
2043 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2044 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2045 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2046 buf = pack_hex_byte (buf, (value & 0xff));
2047 return buf;
2048}
2049
2050static char *
fba45db2 2051unpack_int (char *buf, int *value)
c906108c
SS
2052{
2053 *value = stub_unpack_int (buf, 8);
2054 return buf + 8;
2055}
2056
23860348 2057#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2058static char *pack_string (char *pkt, char *string);
c906108c
SS
2059
2060static char *
fba45db2 2061pack_string (char *pkt, char *string)
c906108c
SS
2062{
2063 char ch;
2064 int len;
2065
2066 len = strlen (string);
2067 if (len > 200)
23860348 2068 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2069 pkt = pack_hex_byte (pkt, len);
2070 while (len-- > 0)
2071 {
2072 ch = *string++;
2073 if ((ch == '\0') || (ch == '#'))
23860348 2074 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2075 *pkt++ = ch;
2076 }
2077 return pkt;
2078}
2079#endif /* 0 (unused) */
2080
2081static char *
fba45db2 2082unpack_string (char *src, char *dest, int length)
c906108c
SS
2083{
2084 while (length--)
2085 *dest++ = *src++;
2086 *dest = '\0';
2087 return src;
2088}
2089
2090static char *
fba45db2 2091pack_threadid (char *pkt, threadref *id)
c906108c
SS
2092{
2093 char *limit;
2094 unsigned char *altid;
2095
2096 altid = (unsigned char *) id;
2097 limit = pkt + BUF_THREAD_ID_SIZE;
2098 while (pkt < limit)
2099 pkt = pack_hex_byte (pkt, *altid++);
2100 return pkt;
2101}
2102
2103
2104static char *
fba45db2 2105unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2106{
2107 char *altref;
2108 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2109 int x, y;
2110
2111 altref = (char *) id;
2112
2113 while (inbuf < limit)
2114 {
2115 x = stubhex (*inbuf++);
2116 y = stubhex (*inbuf++);
2117 *altref++ = (x << 4) | y;
2118 }
2119 return inbuf;
2120}
2121
2122/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2123 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2124 to use 64bit thread references internally. This is an adapter
2125 function. */
2126
2127void
fba45db2 2128int_to_threadref (threadref *id, int value)
c906108c
SS
2129{
2130 unsigned char *scan;
2131
2132 scan = (unsigned char *) id;
2133 {
2134 int i = 4;
2135 while (i--)
2136 *scan++ = 0;
2137 }
2138 *scan++ = (value >> 24) & 0xff;
2139 *scan++ = (value >> 16) & 0xff;
2140 *scan++ = (value >> 8) & 0xff;
2141 *scan++ = (value & 0xff);
2142}
2143
2144static int
fba45db2 2145threadref_to_int (threadref *ref)
c906108c
SS
2146{
2147 int i, value = 0;
2148 unsigned char *scan;
2149
cfd77fa1 2150 scan = *ref;
c906108c
SS
2151 scan += 4;
2152 i = 4;
2153 while (i-- > 0)
2154 value = (value << 8) | ((*scan++) & 0xff);
2155 return value;
2156}
2157
2158static void
fba45db2 2159copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2160{
2161 int i;
2162 unsigned char *csrc, *cdest;
2163
2164 csrc = (unsigned char *) src;
2165 cdest = (unsigned char *) dest;
2166 i = 8;
2167 while (i--)
2168 *cdest++ = *csrc++;
2169}
2170
2171static int
fba45db2 2172threadmatch (threadref *dest, threadref *src)
c906108c 2173{
23860348 2174 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2175#if 0
2176 unsigned char *srcp, *destp;
2177 int i, result;
2178 srcp = (char *) src;
2179 destp = (char *) dest;
2180
2181 result = 1;
2182 while (i-- > 0)
2183 result &= (*srcp++ == *destp++) ? 1 : 0;
2184 return result;
2185#endif
2186 return 1;
2187}
2188
2189/*
c5aa993b
JM
2190 threadid:1, # always request threadid
2191 context_exists:2,
2192 display:4,
2193 unique_name:8,
2194 more_display:16
2195 */
c906108c
SS
2196
2197/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2198
2199static char *
fba45db2 2200pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2201{
23860348
MS
2202 *pkt++ = 'q'; /* Info Query */
2203 *pkt++ = 'P'; /* process or thread info */
2204 pkt = pack_int (pkt, mode); /* mode */
c906108c 2205 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2206 *pkt = '\0'; /* terminate */
c906108c
SS
2207 return pkt;
2208}
2209
23860348 2210/* These values tag the fields in a thread info response packet. */
c906108c 2211/* Tagging the fields allows us to request specific fields and to
23860348 2212 add more fields as time goes by. */
c906108c 2213
23860348 2214#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2215#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2216 fetch registers and its stack? */
c5aa993b 2217#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2218#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2219#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2220 the process. */
c906108c
SS
2221
2222static int
fba45db2
KB
2223remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2224 struct gdb_ext_thread_info *info)
c906108c 2225{
d01949b6 2226 struct remote_state *rs = get_remote_state ();
c906108c 2227 int mask, length;
cfd77fa1 2228 int tag;
c906108c 2229 threadref ref;
6d820c5c 2230 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2231 int retval = 1;
2232
23860348 2233 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2234 info->active = 0;
2235 info->display[0] = '\0';
2236 info->shortname[0] = '\0';
2237 info->more_display[0] = '\0';
2238
23860348
MS
2239 /* Assume the characters indicating the packet type have been
2240 stripped. */
c906108c
SS
2241 pkt = unpack_int (pkt, &mask); /* arg mask */
2242 pkt = unpack_threadid (pkt, &ref);
2243
2244 if (mask == 0)
8a3fe4f8 2245 warning (_("Incomplete response to threadinfo request."));
c906108c 2246 if (!threadmatch (&ref, expectedref))
23860348 2247 { /* This is an answer to a different request. */
8a3fe4f8 2248 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2249 return 0;
2250 }
2251 copy_threadref (&info->threadid, &ref);
2252
23860348 2253 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2254
23860348
MS
2255 /* Packets are terminated with nulls. */
2256 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2257 {
2258 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2259 pkt = unpack_byte (pkt, &length); /* length */
2260 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2261 {
8a3fe4f8 2262 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2263 retval = 0;
2264 break;
2265 }
2266 if (tag == TAG_THREADID)
2267 {
2268 if (length != 16)
2269 {
8a3fe4f8 2270 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2271 retval = 0;
2272 break;
2273 }
2274 pkt = unpack_threadid (pkt, &ref);
2275 mask = mask & ~TAG_THREADID;
2276 continue;
2277 }
2278 if (tag == TAG_EXISTS)
2279 {
2280 info->active = stub_unpack_int (pkt, length);
2281 pkt += length;
2282 mask = mask & ~(TAG_EXISTS);
2283 if (length > 8)
2284 {
8a3fe4f8 2285 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2286 retval = 0;
2287 break;
2288 }
2289 continue;
2290 }
2291 if (tag == TAG_THREADNAME)
2292 {
2293 pkt = unpack_string (pkt, &info->shortname[0], length);
2294 mask = mask & ~TAG_THREADNAME;
2295 continue;
2296 }
2297 if (tag == TAG_DISPLAY)
2298 {
2299 pkt = unpack_string (pkt, &info->display[0], length);
2300 mask = mask & ~TAG_DISPLAY;
2301 continue;
2302 }
2303 if (tag == TAG_MOREDISPLAY)
2304 {
2305 pkt = unpack_string (pkt, &info->more_display[0], length);
2306 mask = mask & ~TAG_MOREDISPLAY;
2307 continue;
2308 }
8a3fe4f8 2309 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2310 break; /* Not a tag we know about. */
c906108c
SS
2311 }
2312 return retval;
2313}
2314
2315static int
fba45db2
KB
2316remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2317 struct gdb_ext_thread_info *info)
c906108c 2318{
d01949b6 2319 struct remote_state *rs = get_remote_state ();
c906108c 2320 int result;
c906108c 2321
2e9f7625
DJ
2322 pack_threadinfo_request (rs->buf, fieldset, threadid);
2323 putpkt (rs->buf);
6d820c5c 2324 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2325
2326 if (rs->buf[0] == '\0')
2327 return 0;
2328
2e9f7625 2329 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2330 threadid, info);
c906108c
SS
2331 return result;
2332}
2333
c906108c
SS
2334/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2335
2336static char *
fba45db2
KB
2337pack_threadlist_request (char *pkt, int startflag, int threadcount,
2338 threadref *nextthread)
c906108c
SS
2339{
2340 *pkt++ = 'q'; /* info query packet */
2341 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2342 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2343 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2344 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2345 *pkt = '\0';
2346 return pkt;
2347}
2348
2349/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2350
2351static int
fba45db2
KB
2352parse_threadlist_response (char *pkt, int result_limit,
2353 threadref *original_echo, threadref *resultlist,
2354 int *doneflag)
c906108c 2355{
d01949b6 2356 struct remote_state *rs = get_remote_state ();
c906108c
SS
2357 char *limit;
2358 int count, resultcount, done;
2359
2360 resultcount = 0;
2361 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2362 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2363 /* done parse past here */
c906108c
SS
2364 pkt = unpack_byte (pkt, &count); /* count field */
2365 pkt = unpack_nibble (pkt, &done);
2366 /* The first threadid is the argument threadid. */
2367 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2368 while ((count-- > 0) && (pkt < limit))
2369 {
2370 pkt = unpack_threadid (pkt, resultlist++);
2371 if (resultcount++ >= result_limit)
2372 break;
2373 }
2374 if (doneflag)
2375 *doneflag = done;
2376 return resultcount;
2377}
2378
2379static int
fba45db2
KB
2380remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2381 int *done, int *result_count, threadref *threadlist)
c906108c 2382{
d01949b6 2383 struct remote_state *rs = get_remote_state ();
c906108c 2384 static threadref echo_nextthread;
c906108c
SS
2385 int result = 1;
2386
23860348 2387 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2388 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2389 >= get_remote_packet_size ())
ea9c271d 2390 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2391
6d820c5c
DJ
2392 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2393 putpkt (rs->buf);
2394 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2395
d8f2712d 2396 if (*rs->buf == '\0')
21bce120 2397 return 0;
d8f2712d
VP
2398 else
2399 *result_count =
2400 parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2401 threadlist, done);
c906108c
SS
2402
2403 if (!threadmatch (&echo_nextthread, nextthread))
2404 {
23860348
MS
2405 /* FIXME: This is a good reason to drop the packet. */
2406 /* Possably, there is a duplicate response. */
c906108c
SS
2407 /* Possabilities :
2408 retransmit immediatly - race conditions
2409 retransmit after timeout - yes
2410 exit
2411 wait for packet, then exit
2412 */
8a3fe4f8 2413 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2414 return 0; /* I choose simply exiting. */
c906108c
SS
2415 }
2416 if (*result_count <= 0)
2417 {
2418 if (*done != 1)
2419 {
8a3fe4f8 2420 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2421 result = 0;
2422 }
2423 return result; /* break; */
2424 }
2425 if (*result_count > result_limit)
2426 {
2427 *result_count = 0;
8a3fe4f8 2428 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2429 return 0;
2430 }
2431 return result;
2432}
2433
23860348
MS
2434/* This is the interface between remote and threads, remotes upper
2435 interface. */
c906108c
SS
2436
2437/* remote_find_new_threads retrieves the thread list and for each
2438 thread in the list, looks up the thread in GDB's internal list,
79d7f229 2439 adding the thread if it does not already exist. This involves
c906108c
SS
2440 getting partial thread lists from the remote target so, polling the
2441 quit_flag is required. */
2442
2443
23860348 2444/* About this many threadisds fit in a packet. */
c906108c
SS
2445
2446#define MAXTHREADLISTRESULTS 32
2447
2448static int
fba45db2
KB
2449remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2450 int looplimit)
c906108c
SS
2451{
2452 int done, i, result_count;
2453 int startflag = 1;
2454 int result = 1;
2455 int loopcount = 0;
2456 static threadref nextthread;
2457 static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2458
2459 done = 0;
2460 while (!done)
2461 {
2462 if (loopcount++ > looplimit)
2463 {
2464 result = 0;
8a3fe4f8 2465 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2466 break;
2467 }
2468 if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2469 &done, &result_count, resultthreadlist))
2470 {
2471 result = 0;
2472 break;
2473 }
23860348 2474 /* Clear for later iterations. */
c906108c
SS
2475 startflag = 0;
2476 /* Setup to resume next batch of thread references, set nextthread. */
2477 if (result_count >= 1)
2478 copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2479 i = 0;
2480 while (result_count--)
2481 if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2482 break;
2483 }
2484 return result;
2485}
2486
2487static int
fba45db2 2488remote_newthread_step (threadref *ref, void *context)
c906108c 2489{
79d7f229
PA
2490 int pid = ptid_get_pid (inferior_ptid);
2491 ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
39f77062
KB
2492
2493 if (!in_thread_list (ptid))
2494 add_thread (ptid);
c906108c
SS
2495 return 1; /* continue iterator */
2496}
2497
2498#define CRAZY_MAX_THREADS 1000
2499
39f77062
KB
2500static ptid_t
2501remote_current_thread (ptid_t oldpid)
c906108c 2502{
d01949b6 2503 struct remote_state *rs = get_remote_state ();
c906108c
SS
2504
2505 putpkt ("qC");
6d820c5c 2506 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2507 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
82f73884 2508 return read_ptid (&rs->buf[2], NULL);
c906108c
SS
2509 else
2510 return oldpid;
2511}
2512
802188a7
RM
2513/* Find new threads for info threads command.
2514 * Original version, using John Metzler's thread protocol.
9d1f7ab2 2515 */
cce74817
JM
2516
2517static void
fba45db2 2518remote_find_new_threads (void)
c906108c 2519{
c5aa993b
JM
2520 remote_threadlist_iterator (remote_newthread_step, 0,
2521 CRAZY_MAX_THREADS);
c906108c
SS
2522}
2523
dc146f7c
VP
2524#if defined(HAVE_LIBEXPAT)
2525
2526typedef struct thread_item
2527{
2528 ptid_t ptid;
2529 char *extra;
2530 int core;
2531} thread_item_t;
2532DEF_VEC_O(thread_item_t);
2533
2534struct threads_parsing_context
2535{
2536 VEC (thread_item_t) *items;
2537};
2538
2539static void
2540start_thread (struct gdb_xml_parser *parser,
2541 const struct gdb_xml_element *element,
2542 void *user_data, VEC(gdb_xml_value_s) *attributes)
2543{
2544 struct threads_parsing_context *data = user_data;
2545
2546 struct thread_item item;
2547 char *id;
3d2c1d41 2548 struct gdb_xml_value *attr;
dc146f7c 2549
3d2c1d41 2550 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2551 item.ptid = read_ptid (id, NULL);
2552
3d2c1d41
PA
2553 attr = xml_find_attribute (attributes, "core");
2554 if (attr != NULL)
2555 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2556 else
2557 item.core = -1;
2558
2559 item.extra = 0;
2560
2561 VEC_safe_push (thread_item_t, data->items, &item);
2562}
2563
2564static void
2565end_thread (struct gdb_xml_parser *parser,
2566 const struct gdb_xml_element *element,
2567 void *user_data, const char *body_text)
2568{
2569 struct threads_parsing_context *data = user_data;
2570
2571 if (body_text && *body_text)
2ae2a0b7 2572 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2573}
2574
2575const struct gdb_xml_attribute thread_attributes[] = {
2576 { "id", GDB_XML_AF_NONE, NULL, NULL },
2577 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2578 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2579};
2580
2581const struct gdb_xml_element thread_children[] = {
2582 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2583};
2584
2585const struct gdb_xml_element threads_children[] = {
2586 { "thread", thread_attributes, thread_children,
2587 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2588 start_thread, end_thread },
2589 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2590};
2591
2592const struct gdb_xml_element threads_elements[] = {
2593 { "threads", NULL, threads_children,
2594 GDB_XML_EF_NONE, NULL, NULL },
2595 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2596};
2597
02357a4a
PA
2598/* Discard the contents of the constructed thread info context. */
2599
2600static void
2601clear_threads_parsing_context (void *p)
2602{
2603 struct threads_parsing_context *context = p;
2604 int i;
2605 struct thread_item *item;
2606
2607 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2608 xfree (item->extra);
2609
2610 VEC_free (thread_item_t, context->items);
2611}
2612
dc146f7c
VP
2613#endif
2614
9d1f7ab2
MS
2615/*
2616 * Find all threads for info threads command.
2617 * Uses new thread protocol contributed by Cisco.
2618 * Falls back and attempts to use the older method (above)
2619 * if the target doesn't respond to the new method.
2620 */
2621
0f71a2f6 2622static void
28439f5e 2623remote_threads_info (struct target_ops *ops)
0f71a2f6 2624{
d01949b6 2625 struct remote_state *rs = get_remote_state ();
085dd6e6 2626 char *bufp;
79d7f229 2627 ptid_t new_thread;
0f71a2f6
JM
2628
2629 if (remote_desc == 0) /* paranoia */
8a3fe4f8 2630 error (_("Command can only be used when connected to the remote target."));
0f71a2f6 2631
dc146f7c
VP
2632#if defined(HAVE_LIBEXPAT)
2633 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2634 {
2635 char *xml = target_read_stralloc (&current_target,
2636 TARGET_OBJECT_THREADS, NULL);
2637
2638 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2639
dc146f7c
VP
2640 if (xml && *xml)
2641 {
dc146f7c 2642 struct threads_parsing_context context;
dc146f7c 2643
efc0eabd
PA
2644 context.items = NULL;
2645 make_cleanup (clear_threads_parsing_context, &context);
dc146f7c 2646
efc0eabd
PA
2647 if (gdb_xml_parse_quick (_("threads"), "threads.dtd",
2648 threads_elements, xml, &context) == 0)
dc146f7c
VP
2649 {
2650 int i;
2651 struct thread_item *item;
2652
3e43a32a
MS
2653 for (i = 0;
2654 VEC_iterate (thread_item_t, context.items, i, item);
2655 ++i)
dc146f7c
VP
2656 {
2657 if (!ptid_equal (item->ptid, null_ptid))
2658 {
2659 struct private_thread_info *info;
2660 /* In non-stop mode, we assume new found threads
2661 are running until proven otherwise with a
2662 stop reply. In all-stop, we can only get
2663 here if all threads are stopped. */
2664 int running = non_stop ? 1 : 0;
2665
2666 remote_notice_new_inferior (item->ptid, running);
2667
2668 info = demand_private_info (item->ptid);
2669 info->core = item->core;
2670 info->extra = item->extra;
02357a4a 2671 item->extra = NULL;
dc146f7c 2672 }
dc146f7c
VP
2673 }
2674 }
dc146f7c
VP
2675 }
2676
2677 do_cleanups (back_to);
2678 return;
2679 }
2680#endif
2681
9d1f7ab2
MS
2682 if (use_threadinfo_query)
2683 {
2684 putpkt ("qfThreadInfo");
6d820c5c 2685 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2686 bufp = rs->buf;
9d1f7ab2 2687 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2688 {
9d1f7ab2
MS
2689 while (*bufp++ == 'm') /* reply contains one or more TID */
2690 {
2691 do
2692 {
82f73884 2693 new_thread = read_ptid (bufp, &bufp);
1941c569 2694 if (!ptid_equal (new_thread, null_ptid))
82f73884 2695 {
74531fed 2696 /* In non-stop mode, we assume new found threads
1941c569 2697 are running until proven otherwise with a
74531fed
PA
2698 stop reply. In all-stop, we can only get
2699 here if all threads are stopped. */
1941c569
PA
2700 int running = non_stop ? 1 : 0;
2701
2702 remote_notice_new_inferior (new_thread, running);
82f73884 2703 }
9d1f7ab2
MS
2704 }
2705 while (*bufp++ == ','); /* comma-separated list */
2706 putpkt ("qsThreadInfo");
6d820c5c 2707 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2708 bufp = rs->buf;
9d1f7ab2
MS
2709 }
2710 return; /* done */
2711 }
2712 }
2713
74531fed
PA
2714 /* Only qfThreadInfo is supported in non-stop mode. */
2715 if (non_stop)
2716 return;
2717
23860348 2718 /* Else fall back to old method based on jmetzler protocol. */
9d1f7ab2
MS
2719 use_threadinfo_query = 0;
2720 remote_find_new_threads ();
2721 return;
2722}
2723
802188a7 2724/*
9d1f7ab2
MS
2725 * Collect a descriptive string about the given thread.
2726 * The target may say anything it wants to about the thread
2727 * (typically info about its blocked / runnable state, name, etc.).
2728 * This string will appear in the info threads display.
802188a7 2729 *
9d1f7ab2
MS
2730 * Optional: targets are not required to implement this function.
2731 */
2732
2733static char *
2734remote_threads_extra_info (struct thread_info *tp)
2735{
d01949b6 2736 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
2737 int result;
2738 int set;
2739 threadref id;
2740 struct gdb_ext_thread_info threadinfo;
23860348 2741 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
2742 int n = 0; /* position in display_buf */
2743
2744 if (remote_desc == 0) /* paranoia */
8e65ff28 2745 internal_error (__FILE__, __LINE__,
e2e0b3e5 2746 _("remote_threads_extra_info"));
9d1f7ab2 2747
60e569b9
PA
2748 if (ptid_equal (tp->ptid, magic_null_ptid)
2749 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2750 /* This is the main thread which was added by GDB. The remote
2751 server doesn't know about it. */
2752 return NULL;
2753
dc146f7c
VP
2754 if (remote_protocol_packets[PACKET_qXfer_threads].support == PACKET_ENABLE)
2755 {
2756 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 2757
dc146f7c
VP
2758 if (info && info->private)
2759 return info->private->extra;
2760 else
2761 return NULL;
2762 }
2763
9d1f7ab2
MS
2764 if (use_threadextra_query)
2765 {
82f73884
PA
2766 char *b = rs->buf;
2767 char *endb = rs->buf + get_remote_packet_size ();
2768
2769 xsnprintf (b, endb - b, "qThreadExtraInfo,");
2770 b += strlen (b);
2771 write_ptid (b, endb, tp->ptid);
2772
2e9f7625 2773 putpkt (rs->buf);
6d820c5c 2774 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2775 if (rs->buf[0] != 0)
9d1f7ab2 2776 {
2e9f7625
DJ
2777 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2778 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 2779 display_buf [result] = '\0';
9d1f7ab2
MS
2780 return display_buf;
2781 }
0f71a2f6 2782 }
9d1f7ab2
MS
2783
2784 /* If the above query fails, fall back to the old method. */
2785 use_threadextra_query = 0;
2786 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2787 | TAG_MOREDISPLAY | TAG_DISPLAY;
79d7f229 2788 int_to_threadref (&id, ptid_get_tid (tp->ptid));
9d1f7ab2
MS
2789 if (remote_get_threadinfo (&id, set, &threadinfo))
2790 if (threadinfo.active)
0f71a2f6 2791 {
9d1f7ab2 2792 if (*threadinfo.shortname)
2bc416ba 2793 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 2794 " Name: %s,", threadinfo.shortname);
9d1f7ab2 2795 if (*threadinfo.display)
2bc416ba 2796 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2797 " State: %s,", threadinfo.display);
9d1f7ab2 2798 if (*threadinfo.more_display)
2bc416ba 2799 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 2800 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
2801
2802 if (n > 0)
c5aa993b 2803 {
23860348 2804 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
2805 if (',' == display_buf[n-1])
2806 display_buf[n-1] = ' ';
2807 return display_buf;
c5aa993b 2808 }
0f71a2f6 2809 }
9d1f7ab2 2810 return NULL;
0f71a2f6 2811}
c906108c 2812\f
c5aa993b 2813
0fb4aa4b
PA
2814static int
2815remote_static_tracepoint_marker_at (CORE_ADDR addr,
2816 struct static_tracepoint_marker *marker)
2817{
2818 struct remote_state *rs = get_remote_state ();
2819 char *p = rs->buf;
2820
2821 sprintf (p, "qTSTMat:");
2822 p += strlen (p);
2823 p += hexnumstr (p, addr);
2824 putpkt (rs->buf);
2825 getpkt (&rs->buf, &rs->buf_size, 0);
2826 p = rs->buf;
2827
2828 if (*p == 'E')
2829 error (_("Remote failure reply: %s"), p);
2830
2831 if (*p++ == 'm')
2832 {
2833 parse_static_tracepoint_marker_definition (p, &p, marker);
2834 return 1;
2835 }
2836
2837 return 0;
2838}
2839
2840static void
2841free_current_marker (void *arg)
2842{
2843 struct static_tracepoint_marker **marker_p = arg;
2844
2845 if (*marker_p != NULL)
2846 {
2847 release_static_tracepoint_marker (*marker_p);
2848 xfree (*marker_p);
2849 }
2850 else
2851 *marker_p = NULL;
2852}
2853
2854static VEC(static_tracepoint_marker_p) *
2855remote_static_tracepoint_markers_by_strid (const char *strid)
2856{
2857 struct remote_state *rs = get_remote_state ();
2858 VEC(static_tracepoint_marker_p) *markers = NULL;
2859 struct static_tracepoint_marker *marker = NULL;
2860 struct cleanup *old_chain;
2861 char *p;
2862
2863 /* Ask for a first packet of static tracepoint marker
2864 definition. */
2865 putpkt ("qTfSTM");
2866 getpkt (&rs->buf, &rs->buf_size, 0);
2867 p = rs->buf;
2868 if (*p == 'E')
2869 error (_("Remote failure reply: %s"), p);
2870
2871 old_chain = make_cleanup (free_current_marker, &marker);
2872
2873 while (*p++ == 'm')
2874 {
2875 if (marker == NULL)
2876 marker = XCNEW (struct static_tracepoint_marker);
2877
2878 do
2879 {
2880 parse_static_tracepoint_marker_definition (p, &p, marker);
2881
2882 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
2883 {
2884 VEC_safe_push (static_tracepoint_marker_p,
2885 markers, marker);
2886 marker = NULL;
2887 }
2888 else
2889 {
2890 release_static_tracepoint_marker (marker);
2891 memset (marker, 0, sizeof (*marker));
2892 }
2893 }
2894 while (*p++ == ','); /* comma-separated list */
2895 /* Ask for another packet of static tracepoint definition. */
2896 putpkt ("qTsSTM");
2897 getpkt (&rs->buf, &rs->buf_size, 0);
2898 p = rs->buf;
2899 }
2900
2901 do_cleanups (old_chain);
2902 return markers;
2903}
2904
2905\f
10760264
JB
2906/* Implement the to_get_ada_task_ptid function for the remote targets. */
2907
2908static ptid_t
2909remote_get_ada_task_ptid (long lwp, long thread)
2910{
2911 return ptid_build (ptid_get_pid (inferior_ptid), 0, lwp);
2912}
2913\f
2914
24b06219 2915/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
2916
2917static void
fba45db2 2918extended_remote_restart (void)
c906108c 2919{
d01949b6 2920 struct remote_state *rs = get_remote_state ();
c906108c
SS
2921
2922 /* Send the restart command; for reasons I don't understand the
2923 remote side really expects a number after the "R". */
ea9c271d 2924 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 2925 putpkt (rs->buf);
c906108c 2926
ad9a8f3f 2927 remote_fileio_reset ();
c906108c
SS
2928}
2929\f
2930/* Clean up connection to a remote debugger. */
2931
c906108c 2932static void
fba45db2 2933remote_close (int quitting)
c906108c 2934{
d3fd5342
PA
2935 if (remote_desc == NULL)
2936 return; /* already closed */
2937
2938 /* Make sure we leave stdin registered in the event loop, and we
2939 don't leave the async SIGINT signal handler installed. */
2940 remote_terminal_ours ();
ce5ce7ed 2941
d3fd5342
PA
2942 serial_close (remote_desc);
2943 remote_desc = NULL;
ce5ce7ed
PA
2944
2945 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
2946 of all the inferiors and their threads we were controlling.
2947 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
2948 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 2949 inferior_ptid = null_ptid;
f67fd822 2950 discard_all_inferiors ();
ce5ce7ed 2951
74531fed
PA
2952 /* We're no longer interested in any of these events. */
2953 discard_pending_stop_replies (-1);
2954
2955 if (remote_async_inferior_event_token)
2956 delete_async_event_handler (&remote_async_inferior_event_token);
2957 if (remote_async_get_pending_events_token)
2958 delete_async_event_handler (&remote_async_get_pending_events_token);
c906108c
SS
2959}
2960
23860348 2961/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
2962
2963static void
fba45db2 2964get_offsets (void)
c906108c 2965{
d01949b6 2966 struct remote_state *rs = get_remote_state ();
2e9f7625 2967 char *buf;
085dd6e6 2968 char *ptr;
31d99776
DJ
2969 int lose, num_segments = 0, do_sections, do_segments;
2970 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 2971 struct section_offsets *offs;
31d99776
DJ
2972 struct symfile_segment_data *data;
2973
2974 if (symfile_objfile == NULL)
2975 return;
c906108c
SS
2976
2977 putpkt ("qOffsets");
6d820c5c 2978 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2979 buf = rs->buf;
c906108c
SS
2980
2981 if (buf[0] == '\000')
2982 return; /* Return silently. Stub doesn't support
23860348 2983 this command. */
c906108c
SS
2984 if (buf[0] == 'E')
2985 {
8a3fe4f8 2986 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
2987 return;
2988 }
2989
2990 /* Pick up each field in turn. This used to be done with scanf, but
2991 scanf will make trouble if CORE_ADDR size doesn't match
2992 conversion directives correctly. The following code will work
2993 with any size of CORE_ADDR. */
2994 text_addr = data_addr = bss_addr = 0;
2995 ptr = buf;
2996 lose = 0;
2997
2998 if (strncmp (ptr, "Text=", 5) == 0)
2999 {
3000 ptr += 5;
3001 /* Don't use strtol, could lose on big values. */
3002 while (*ptr && *ptr != ';')
3003 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3004
31d99776
DJ
3005 if (strncmp (ptr, ";Data=", 6) == 0)
3006 {
3007 ptr += 6;
3008 while (*ptr && *ptr != ';')
3009 data_addr = (data_addr << 4) + fromhex (*ptr++);
3010 }
3011 else
3012 lose = 1;
3013
3014 if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
3015 {
3016 ptr += 5;
3017 while (*ptr && *ptr != ';')
3018 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3019
31d99776
DJ
3020 if (bss_addr != data_addr)
3021 warning (_("Target reported unsupported offsets: %s"), buf);
3022 }
3023 else
3024 lose = 1;
3025 }
3026 else if (strncmp (ptr, "TextSeg=", 8) == 0)
c906108c 3027 {
31d99776
DJ
3028 ptr += 8;
3029 /* Don't use strtol, could lose on big values. */
c906108c 3030 while (*ptr && *ptr != ';')
31d99776
DJ
3031 text_addr = (text_addr << 4) + fromhex (*ptr++);
3032 num_segments = 1;
3033
3034 if (strncmp (ptr, ";DataSeg=", 9) == 0)
3035 {
3036 ptr += 9;
3037 while (*ptr && *ptr != ';')
3038 data_addr = (data_addr << 4) + fromhex (*ptr++);
3039 num_segments++;
3040 }
c906108c
SS
3041 }
3042 else
3043 lose = 1;
3044
3045 if (lose)
8a3fe4f8 3046 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3047 else if (*ptr != '\0')
3048 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3049
802188a7 3050 offs = ((struct section_offsets *)
a39a16c4 3051 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3052 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3053 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3054
31d99776
DJ
3055 data = get_symfile_segment_data (symfile_objfile->obfd);
3056 do_segments = (data != NULL);
3057 do_sections = num_segments == 0;
c906108c 3058
28c32713 3059 if (num_segments > 0)
31d99776 3060 {
31d99776
DJ
3061 segments[0] = text_addr;
3062 segments[1] = data_addr;
3063 }
28c32713
JB
3064 /* If we have two segments, we can still try to relocate everything
3065 by assuming that the .text and .data offsets apply to the whole
3066 text and data segments. Convert the offsets given in the packet
3067 to base addresses for symfile_map_offsets_to_segments. */
3068 else if (data && data->num_segments == 2)
3069 {
3070 segments[0] = data->segment_bases[0] + text_addr;
3071 segments[1] = data->segment_bases[1] + data_addr;
3072 num_segments = 2;
3073 }
8d385431
DJ
3074 /* If the object file has only one segment, assume that it is text
3075 rather than data; main programs with no writable data are rare,
3076 but programs with no code are useless. Of course the code might
3077 have ended up in the data segment... to detect that we would need
3078 the permissions here. */
3079 else if (data && data->num_segments == 1)
3080 {
3081 segments[0] = data->segment_bases[0] + text_addr;
3082 num_segments = 1;
3083 }
28c32713
JB
3084 /* There's no way to relocate by segment. */
3085 else
3086 do_segments = 0;
31d99776
DJ
3087
3088 if (do_segments)
3089 {
3090 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3091 offs, num_segments, segments);
3092
3093 if (ret == 0 && !do_sections)
3e43a32a
MS
3094 error (_("Can not handle qOffsets TextSeg "
3095 "response with this symbol file"));
31d99776
DJ
3096
3097 if (ret > 0)
3098 do_sections = 0;
3099 }
c906108c 3100
9ef895d6
DJ
3101 if (data)
3102 free_symfile_segment_data (data);
31d99776
DJ
3103
3104 if (do_sections)
3105 {
3106 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3107
3e43a32a
MS
3108 /* This is a temporary kludge to force data and bss to use the
3109 same offsets because that's what nlmconv does now. The real
3110 solution requires changes to the stub and remote.c that I
3111 don't have time to do right now. */
31d99776
DJ
3112
3113 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3114 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3115 }
c906108c
SS
3116
3117 objfile_relocate (symfile_objfile, offs);
3118}
3119
74531fed
PA
3120/* Callback for iterate_over_threads. Set the STOP_REQUESTED flags in
3121 threads we know are stopped already. This is used during the
3122 initial remote connection in non-stop mode --- threads that are
3123 reported as already being stopped are left stopped. */
3124
3125static int
3126set_stop_requested_callback (struct thread_info *thread, void *data)
3127{
3128 /* If we have a stop reply for this thread, it must be stopped. */
3129 if (peek_stop_reply (thread->ptid))
3130 set_stop_requested (thread->ptid, 1);
3131
3132 return 0;
3133}
3134
9a7071a8
JB
3135/* Send interrupt_sequence to remote target. */
3136static void
eeae04df 3137send_interrupt_sequence (void)
9a7071a8
JB
3138{
3139 if (interrupt_sequence_mode == interrupt_sequence_control_c)
3140 serial_write (remote_desc, "\x03", 1);
3141 else if (interrupt_sequence_mode == interrupt_sequence_break)
3142 serial_send_break (remote_desc);
3143 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3144 {
3145 serial_send_break (remote_desc);
3146 serial_write (remote_desc, "g", 1);
3147 }
3148 else
3149 internal_error (__FILE__, __LINE__,
3150 _("Invalid value for interrupt_sequence_mode: %s."),
3151 interrupt_sequence_mode);
3152}
3153
9cbc821d 3154static void
04bd08de 3155remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3156{
c8d104ad
PA
3157 struct remote_state *rs = get_remote_state ();
3158 struct packet_config *noack_config;
2d717e4f 3159 char *wait_status = NULL;
8621d6a9 3160
23860348 3161 immediate_quit++; /* Allow user to interrupt it. */
c906108c 3162
9a7071a8
JB
3163 if (interrupt_on_connect)
3164 send_interrupt_sequence ();
3165
57e12211
TT
3166 /* Ack any packet which the remote side has already sent. */
3167 serial_write (remote_desc, "+", 1);
3168
c8d104ad
PA
3169 /* The first packet we send to the target is the optional "supported
3170 packets" request. If the target can answer this, it will tell us
3171 which later probes to skip. */
3172 remote_query_supported ();
3173
d914c394
SS
3174 /* If the stub wants to get a QAllow, compose one and send it. */
3175 if (remote_protocol_packets[PACKET_QAllow].support != PACKET_DISABLE)
3176 remote_set_permissions ();
3177
c8d104ad
PA
3178 /* Next, we possibly activate noack mode.
3179
3180 If the QStartNoAckMode packet configuration is set to AUTO,
3181 enable noack mode if the stub reported a wish for it with
3182 qSupported.
3183
3184 If set to TRUE, then enable noack mode even if the stub didn't
3185 report it in qSupported. If the stub doesn't reply OK, the
3186 session ends with an error.
3187
3188 If FALSE, then don't activate noack mode, regardless of what the
3189 stub claimed should be the default with qSupported. */
3190
3191 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3192
3193 if (noack_config->detect == AUTO_BOOLEAN_TRUE
3194 || (noack_config->detect == AUTO_BOOLEAN_AUTO
3195 && noack_config->support == PACKET_ENABLE))
3196 {
3197 putpkt ("QStartNoAckMode");
3198 getpkt (&rs->buf, &rs->buf_size, 0);
3199 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3200 rs->noack_mode = 1;
3201 }
3202
04bd08de 3203 if (extended_p)
5fe04517
PA
3204 {
3205 /* Tell the remote that we are using the extended protocol. */
3206 putpkt ("!");
3207 getpkt (&rs->buf, &rs->buf_size, 0);
3208 }
3209
d962ef82
DJ
3210 /* Next, if the target can specify a description, read it. We do
3211 this before anything involving memory or registers. */
3212 target_find_description ();
3213
6c95b8df
PA
3214 /* Next, now that we know something about the target, update the
3215 address spaces in the program spaces. */
3216 update_address_spaces ();
3217
50c71eaf
PA
3218 /* On OSs where the list of libraries is global to all
3219 processes, we fetch them early. */
3220 if (gdbarch_has_global_solist (target_gdbarch))
04bd08de 3221 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3222
74531fed
PA
3223 if (non_stop)
3224 {
3225 if (!rs->non_stop_aware)
3e43a32a
MS
3226 error (_("Non-stop mode requested, but remote "
3227 "does not support non-stop"));
74531fed
PA
3228
3229 putpkt ("QNonStop:1");
3230 getpkt (&rs->buf, &rs->buf_size, 0);
3231
3232 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3233 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3234
3235 /* Find about threads and processes the stub is already
3236 controlling. We default to adding them in the running state.
3237 The '?' query below will then tell us about which threads are
3238 stopped. */
04bd08de 3239 remote_threads_info (target);
74531fed
PA
3240 }
3241 else if (rs->non_stop_aware)
3242 {
3243 /* Don't assume that the stub can operate in all-stop mode.
3244 Request it explicitely. */
3245 putpkt ("QNonStop:0");
3246 getpkt (&rs->buf, &rs->buf_size, 0);
3247
3248 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3249 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3250 }
3251
2d717e4f
DJ
3252 /* Check whether the target is running now. */
3253 putpkt ("?");
3254 getpkt (&rs->buf, &rs->buf_size, 0);
3255
74531fed 3256 if (!non_stop)
2d717e4f 3257 {
74531fed 3258 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3259 {
04bd08de 3260 if (!extended_p)
74531fed 3261 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3262
3263 /* We're connected, but not running. Drop out before we
3264 call start_remote. */
3265 return;
2d717e4f
DJ
3266 }
3267 else
74531fed 3268 {
74531fed
PA
3269 /* Save the reply for later. */
3270 wait_status = alloca (strlen (rs->buf) + 1);
3271 strcpy (wait_status, rs->buf);
3272 }
3273
3274 /* Let the stub know that we want it to return the thread. */
3275 set_continue_thread (minus_one_ptid);
3276
3277 /* Without this, some commands which require an active target
3278 (such as kill) won't work. This variable serves (at least)
3279 double duty as both the pid of the target process (if it has
3280 such), and as a flag indicating that a target is active.
3281 These functions should be split out into seperate variables,
3282 especially since GDB will someday have a notion of debugging
3283 several processes. */
3284 inferior_ptid = magic_null_ptid;
3285
3286 /* Now, if we have thread information, update inferior_ptid. */
3287 inferior_ptid = remote_current_thread (inferior_ptid);
3288
0b16c5cf 3289 remote_add_inferior (ptid_get_pid (inferior_ptid), -1);
74531fed
PA
3290
3291 /* Always add the main thread. */
3292 add_thread_silent (inferior_ptid);
3293
6e586cc5
YQ
3294 /* init_wait_for_inferior should be called before get_offsets in order
3295 to manage `inserted' flag in bp loc in a correct state.
3296 breakpoint_init_inferior, called from init_wait_for_inferior, set
3297 `inserted' flag to 0, while before breakpoint_re_set, called from
3298 start_remote, set `inserted' flag to 1. In the initialization of
3299 inferior, breakpoint_init_inferior should be called first, and then
3300 breakpoint_re_set can be called. If this order is broken, state of
3301 `inserted' flag is wrong, and cause some problems on breakpoint
3302 manipulation. */
3303 init_wait_for_inferior ();
3304
74531fed
PA
3305 get_offsets (); /* Get text, data & bss offsets. */
3306
d962ef82
DJ
3307 /* If we could not find a description using qXfer, and we know
3308 how to do it some other way, try again. This is not
3309 supported for non-stop; it could be, but it is tricky if
3310 there are no stopped threads when we connect. */
04bd08de 3311 if (remote_read_description_p (target)
d962ef82
DJ
3312 && gdbarch_target_desc (target_gdbarch) == NULL)
3313 {
3314 target_clear_description ();
3315 target_find_description ();
3316 }
3317
74531fed
PA
3318 /* Use the previously fetched status. */
3319 gdb_assert (wait_status != NULL);
3320 strcpy (rs->buf, wait_status);
3321 rs->cached_wait_status = 1;
3322
3323 immediate_quit--;
04bd08de 3324 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3325 }
3326 else
3327 {
68c97600
PA
3328 /* Clear WFI global state. Do this before finding about new
3329 threads and inferiors, and setting the current inferior.
3330 Otherwise we would clear the proceed status of the current
3331 inferior when we want its stop_soon state to be preserved
3332 (see notice_new_inferior). */
3333 init_wait_for_inferior ();
3334
74531fed
PA
3335 /* In non-stop, we will either get an "OK", meaning that there
3336 are no stopped threads at this time; or, a regular stop
3337 reply. In the latter case, there may be more than one thread
3338 stopped --- we pull them all out using the vStopped
3339 mechanism. */
3340 if (strcmp (rs->buf, "OK") != 0)
3341 {
3342 struct stop_reply *stop_reply;
3343 struct cleanup *old_chain;
2d717e4f 3344
74531fed
PA
3345 stop_reply = stop_reply_xmalloc ();
3346 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
2d717e4f 3347
74531fed
PA
3348 remote_parse_stop_reply (rs->buf, stop_reply);
3349 discard_cleanups (old_chain);
c0a2216e 3350
74531fed
PA
3351 /* get_pending_stop_replies acks this one, and gets the rest
3352 out. */
3353 pending_stop_reply = stop_reply;
3354 remote_get_pending_stop_replies ();
c906108c 3355
74531fed
PA
3356 /* Make sure that threads that were stopped remain
3357 stopped. */
3358 iterate_over_threads (set_stop_requested_callback, NULL);
3359 }
2d717e4f 3360
74531fed
PA
3361 if (target_can_async_p ())
3362 target_async (inferior_event_handler, 0);
c906108c 3363
74531fed
PA
3364 if (thread_count () == 0)
3365 {
04bd08de 3366 if (!extended_p)
74531fed 3367 error (_("The target is not running (try extended-remote?)"));
82f73884 3368
c35b1492
PA
3369 /* We're connected, but not running. Drop out before we
3370 call start_remote. */
3371 return;
3372 }
74531fed
PA
3373
3374 /* Let the stub know that we want it to return the thread. */
c0a2216e 3375
74531fed
PA
3376 /* Force the stub to choose a thread. */
3377 set_general_thread (null_ptid);
c906108c 3378
74531fed
PA
3379 /* Query it. */
3380 inferior_ptid = remote_current_thread (minus_one_ptid);
3381 if (ptid_equal (inferior_ptid, minus_one_ptid))
3382 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3383
74531fed
PA
3384 get_offsets (); /* Get text, data & bss offsets. */
3385
3386 /* In non-stop mode, any cached wait status will be stored in
3387 the stop reply queue. */
3388 gdb_assert (wait_status == NULL);
f0223081 3389
2455069d
UW
3390 /* Report all signals during attach/startup. */
3391 remote_pass_signals (0, NULL);
74531fed 3392 }
c8d104ad 3393
c8d104ad
PA
3394 /* If we connected to a live target, do some additional setup. */
3395 if (target_has_execution)
3396 {
3397 if (exec_bfd) /* No use without an exec file. */
3398 remote_check_symbols (symfile_objfile);
3399 }
50c71eaf 3400
d5551862
SS
3401 /* Possibly the target has been engaged in a trace run started
3402 previously; find out where things are at. */
26afc0d7 3403 if (remote_get_trace_status (current_trace_status ()) != -1)
d5551862 3404 {
00bf0b85
SS
3405 struct uploaded_tp *uploaded_tps = NULL;
3406 struct uploaded_tsv *uploaded_tsvs = NULL;
3407
00bf0b85
SS
3408 if (current_trace_status ()->running)
3409 printf_filtered (_("Trace is already running on the target.\n"));
3410
3411 /* Get trace state variables first, they may be checked when
3412 parsing uploaded commands. */
3413
3414 remote_upload_trace_state_variables (&uploaded_tsvs);
3415
3416 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3417
3418 remote_upload_tracepoints (&uploaded_tps);
3419
3420 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3421 }
3422
2567c7d9
PA
3423 /* If breakpoints are global, insert them now. */
3424 if (gdbarch_has_global_breakpoints (target_gdbarch)
50c71eaf
PA
3425 && breakpoints_always_inserted_mode ())
3426 insert_breakpoints ();
c906108c
SS
3427}
3428
3429/* Open a connection to a remote debugger.
3430 NAME is the filename used for communication. */
3431
3432static void
fba45db2 3433remote_open (char *name, int from_tty)
c906108c 3434{
75c99385 3435 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3436}
3437
c906108c
SS
3438/* Open a connection to a remote debugger using the extended
3439 remote gdb protocol. NAME is the filename used for communication. */
3440
3441static void
fba45db2 3442extended_remote_open (char *name, int from_tty)
c906108c 3443{
75c99385 3444 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3445}
3446
c906108c
SS
3447/* Generic code for opening a connection to a remote target. */
3448
d471ea57
AC
3449static void
3450init_all_packet_configs (void)
3451{
3452 int i;
a744cf53 3453
444abaca
DJ
3454 for (i = 0; i < PACKET_MAX; i++)
3455 update_packet_config (&remote_protocol_packets[i]);
d471ea57
AC
3456}
3457
23860348 3458/* Symbol look-up. */
dc8acb97
MS
3459
3460static void
3461remote_check_symbols (struct objfile *objfile)
3462{
d01949b6 3463 struct remote_state *rs = get_remote_state ();
dc8acb97
MS
3464 char *msg, *reply, *tmp;
3465 struct minimal_symbol *sym;
3466 int end;
3467
63154eca
PA
3468 /* The remote side has no concept of inferiors that aren't running
3469 yet, it only knows about running processes. If we're connected
3470 but our current inferior is not running, we should not invite the
3471 remote target to request symbol lookups related to its
3472 (unrelated) current process. */
3473 if (!target_has_execution)
3474 return;
3475
444abaca 3476 if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
dc8acb97
MS
3477 return;
3478
63154eca
PA
3479 /* Make sure the remote is pointing at the right process. Note
3480 there's no way to select "no process". */
3c9c4b83
PA
3481 set_general_process ();
3482
6d820c5c
DJ
3483 /* Allocate a message buffer. We can't reuse the input buffer in RS,
3484 because we need both at the same time. */
ea9c271d 3485 msg = alloca (get_remote_packet_size ());
6d820c5c 3486
23860348 3487 /* Invite target to request symbol lookups. */
dc8acb97
MS
3488
3489 putpkt ("qSymbol::");
6d820c5c
DJ
3490 getpkt (&rs->buf, &rs->buf_size, 0);
3491 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 3492 reply = rs->buf;
dc8acb97
MS
3493
3494 while (strncmp (reply, "qSymbol:", 8) == 0)
3495 {
3496 tmp = &reply[8];
cfd77fa1 3497 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
3498 msg[end] = '\0';
3499 sym = lookup_minimal_symbol (msg, NULL, NULL);
3500 if (sym == NULL)
ea9c271d 3501 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 3502 else
2bbe3cc1 3503 {
5af949e3 3504 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
2bbe3cc1
DJ
3505 CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
3506
3507 /* If this is a function address, return the start of code
3508 instead of any data function descriptor. */
1cf3db46 3509 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
2bbe3cc1
DJ
3510 sym_addr,
3511 &current_target);
3512
3513 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 3514 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
3515 }
3516
dc8acb97 3517 putpkt (msg);
6d820c5c 3518 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3519 reply = rs->buf;
dc8acb97
MS
3520 }
3521}
3522
9db8d71f
DJ
3523static struct serial *
3524remote_serial_open (char *name)
3525{
3526 static int udp_warning = 0;
3527
3528 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
3529 of in ser-tcp.c, because it is the remote protocol assuming that the
3530 serial connection is reliable and not the serial connection promising
3531 to be. */
3532 if (!udp_warning && strncmp (name, "udp:", 4) == 0)
3533 {
3e43a32a
MS
3534 warning (_("The remote protocol may be unreliable over UDP.\n"
3535 "Some events may be lost, rendering further debugging "
3536 "impossible."));
9db8d71f
DJ
3537 udp_warning = 1;
3538 }
3539
3540 return serial_open (name);
3541}
3542
d914c394
SS
3543/* Inform the target of our permission settings. The permission flags
3544 work without this, but if the target knows the settings, it can do
3545 a couple things. First, it can add its own check, to catch cases
3546 that somehow manage to get by the permissions checks in target
3547 methods. Second, if the target is wired to disallow particular
3548 settings (for instance, a system in the field that is not set up to
3549 be able to stop at a breakpoint), it can object to any unavailable
3550 permissions. */
3551
3552void
3553remote_set_permissions (void)
3554{
3555 struct remote_state *rs = get_remote_state ();
3556
3557 sprintf (rs->buf, "QAllow:"
3558 "WriteReg:%x;WriteMem:%x;"
3559 "InsertBreak:%x;InsertTrace:%x;"
3560 "InsertFastTrace:%x;Stop:%x",
3561 may_write_registers, may_write_memory,
3562 may_insert_breakpoints, may_insert_tracepoints,
3563 may_insert_fast_tracepoints, may_stop);
3564 putpkt (rs->buf);
3565 getpkt (&rs->buf, &rs->buf_size, 0);
3566
3567 /* If the target didn't like the packet, warn the user. Do not try
3568 to undo the user's settings, that would just be maddening. */
3569 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 3570 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
3571}
3572
be2a5f71
DJ
3573/* This type describes each known response to the qSupported
3574 packet. */
3575struct protocol_feature
3576{
3577 /* The name of this protocol feature. */
3578 const char *name;
3579
3580 /* The default for this protocol feature. */
3581 enum packet_support default_support;
3582
3583 /* The function to call when this feature is reported, or after
3584 qSupported processing if the feature is not supported.
3585 The first argument points to this structure. The second
3586 argument indicates whether the packet requested support be
3587 enabled, disabled, or probed (or the default, if this function
3588 is being called at the end of processing and this feature was
3589 not reported). The third argument may be NULL; if not NULL, it
3590 is a NUL-terminated string taken from the packet following
3591 this feature's name and an equals sign. */
3592 void (*func) (const struct protocol_feature *, enum packet_support,
3593 const char *);
3594
3595 /* The corresponding packet for this feature. Only used if
3596 FUNC is remote_supported_packet. */
3597 int packet;
3598};
3599
be2a5f71
DJ
3600static void
3601remote_supported_packet (const struct protocol_feature *feature,
3602 enum packet_support support,
3603 const char *argument)
3604{
3605 if (argument)
3606 {
3607 warning (_("Remote qSupported response supplied an unexpected value for"
3608 " \"%s\"."), feature->name);
3609 return;
3610 }
3611
3612 if (remote_protocol_packets[feature->packet].support
3613 == PACKET_SUPPORT_UNKNOWN)
3614 remote_protocol_packets[feature->packet].support = support;
3615}
be2a5f71
DJ
3616
3617static void
3618remote_packet_size (const struct protocol_feature *feature,
3619 enum packet_support support, const char *value)
3620{
3621 struct remote_state *rs = get_remote_state ();
3622
3623 int packet_size;
3624 char *value_end;
3625
3626 if (support != PACKET_ENABLE)
3627 return;
3628
3629 if (value == NULL || *value == '\0')
3630 {
3631 warning (_("Remote target reported \"%s\" without a size."),
3632 feature->name);
3633 return;
3634 }
3635
3636 errno = 0;
3637 packet_size = strtol (value, &value_end, 16);
3638 if (errno != 0 || *value_end != '\0' || packet_size < 0)
3639 {
3640 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
3641 feature->name, value);
3642 return;
3643 }
3644
3645 if (packet_size > MAX_REMOTE_PACKET_SIZE)
3646 {
3647 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
3648 packet_size, MAX_REMOTE_PACKET_SIZE);
3649 packet_size = MAX_REMOTE_PACKET_SIZE;
3650 }
3651
3652 /* Record the new maximum packet size. */
3653 rs->explicit_packet_size = packet_size;
3654}
3655
82f73884
PA
3656static void
3657remote_multi_process_feature (const struct protocol_feature *feature,
3658 enum packet_support support, const char *value)
3659{
3660 struct remote_state *rs = get_remote_state ();
a744cf53 3661
82f73884
PA
3662 rs->multi_process_aware = (support == PACKET_ENABLE);
3663}
3664
74531fed
PA
3665static void
3666remote_non_stop_feature (const struct protocol_feature *feature,
3667 enum packet_support support, const char *value)
3668{
3669 struct remote_state *rs = get_remote_state ();
a744cf53 3670
74531fed
PA
3671 rs->non_stop_aware = (support == PACKET_ENABLE);
3672}
3673
782b2b07
SS
3674static void
3675remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3676 enum packet_support support,
3677 const char *value)
3678{
3679 struct remote_state *rs = get_remote_state ();
a744cf53 3680
782b2b07
SS
3681 rs->cond_tracepoints = (support == PACKET_ENABLE);
3682}
3683
7a697b8d
SS
3684static void
3685remote_fast_tracepoint_feature (const struct protocol_feature *feature,
3686 enum packet_support support,
3687 const char *value)
3688{
3689 struct remote_state *rs = get_remote_state ();
a744cf53 3690
7a697b8d
SS
3691 rs->fast_tracepoints = (support == PACKET_ENABLE);
3692}
3693
0fb4aa4b
PA
3694static void
3695remote_static_tracepoint_feature (const struct protocol_feature *feature,
3696 enum packet_support support,
3697 const char *value)
3698{
3699 struct remote_state *rs = get_remote_state ();
3700
3701 rs->static_tracepoints = (support == PACKET_ENABLE);
3702}
3703
1e4d1764
YQ
3704static void
3705remote_install_in_trace_feature (const struct protocol_feature *feature,
3706 enum packet_support support,
3707 const char *value)
3708{
3709 struct remote_state *rs = get_remote_state ();
3710
3711 rs->install_in_trace = (support == PACKET_ENABLE);
3712}
3713
d5551862
SS
3714static void
3715remote_disconnected_tracing_feature (const struct protocol_feature *feature,
3716 enum packet_support support,
3717 const char *value)
3718{
3719 struct remote_state *rs = get_remote_state ();
a744cf53 3720
d5551862
SS
3721 rs->disconnected_tracing = (support == PACKET_ENABLE);
3722}
3723
d248b706
KY
3724static void
3725remote_enable_disable_tracepoint_feature (const struct protocol_feature *feature,
3726 enum packet_support support,
3727 const char *value)
3728{
3729 struct remote_state *rs = get_remote_state ();
3730
3731 rs->enable_disable_tracepoints = (support == PACKET_ENABLE);
3732}
3733
3065dfb6
SS
3734static void
3735remote_string_tracing_feature (const struct protocol_feature *feature,
3736 enum packet_support support,
3737 const char *value)
3738{
3739 struct remote_state *rs = get_remote_state ();
3740
3741 rs->string_tracing = (support == PACKET_ENABLE);
3742}
3743
be2a5f71 3744static struct protocol_feature remote_protocol_features[] = {
0876f84a 3745 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 3746 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 3747 PACKET_qXfer_auxv },
23181151
DJ
3748 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3749 PACKET_qXfer_features },
cfa9d6d9
DJ
3750 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3751 PACKET_qXfer_libraries },
2268b414
JK
3752 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
3753 PACKET_qXfer_libraries_svr4 },
fd79ecee 3754 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 3755 PACKET_qXfer_memory_map },
4de6483e
UW
3756 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3757 PACKET_qXfer_spu_read },
3758 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3759 PACKET_qXfer_spu_write },
07e059b5
VP
3760 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3761 PACKET_qXfer_osdata },
dc146f7c
VP
3762 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
3763 PACKET_qXfer_threads },
b3b9301e
PA
3764 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
3765 PACKET_qXfer_traceframe_info },
89be2091
DJ
3766 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3767 PACKET_QPassSignals },
a6f3e723
SL
3768 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3769 PACKET_QStartNoAckMode },
82f73884 3770 { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
74531fed 3771 { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
4aa995e1
PA
3772 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3773 PACKET_qXfer_siginfo_read },
3774 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3775 PACKET_qXfer_siginfo_write },
782b2b07
SS
3776 { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
3777 PACKET_ConditionalTracepoints },
7a697b8d
SS
3778 { "FastTracepoints", PACKET_DISABLE, remote_fast_tracepoint_feature,
3779 PACKET_FastTracepoints },
0fb4aa4b
PA
3780 { "StaticTracepoints", PACKET_DISABLE, remote_static_tracepoint_feature,
3781 PACKET_StaticTracepoints },
1e4d1764
YQ
3782 {"InstallInTrace", PACKET_DISABLE, remote_install_in_trace_feature,
3783 PACKET_InstallInTrace},
d5551862
SS
3784 { "DisconnectedTracing", PACKET_DISABLE, remote_disconnected_tracing_feature,
3785 -1 },
40ab02ce
MS
3786 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
3787 PACKET_bc },
3788 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
3789 PACKET_bs },
409873ef
SS
3790 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
3791 PACKET_TracepointSource },
d914c394
SS
3792 { "QAllow", PACKET_DISABLE, remote_supported_packet,
3793 PACKET_QAllow },
d248b706
KY
3794 { "EnableDisableTracepoints", PACKET_DISABLE,
3795 remote_enable_disable_tracepoint_feature, -1 },
78d85199
YQ
3796 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
3797 PACKET_qXfer_fdpic },
03583c20
UW
3798 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
3799 PACKET_QDisableRandomization },
3065dfb6
SS
3800 { "tracenz", PACKET_DISABLE,
3801 remote_string_tracing_feature, -1 },
be2a5f71
DJ
3802};
3803
c8d5aac9
L
3804static char *remote_support_xml;
3805
3806/* Register string appended to "xmlRegisters=" in qSupported query. */
3807
3808void
6e39997a 3809register_remote_support_xml (const char *xml)
c8d5aac9
L
3810{
3811#if defined(HAVE_LIBEXPAT)
3812 if (remote_support_xml == NULL)
c4f7c687 3813 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
3814 else
3815 {
3816 char *copy = xstrdup (remote_support_xml + 13);
3817 char *p = strtok (copy, ",");
3818
3819 do
3820 {
3821 if (strcmp (p, xml) == 0)
3822 {
3823 /* already there */
3824 xfree (copy);
3825 return;
3826 }
3827 }
3828 while ((p = strtok (NULL, ",")) != NULL);
3829 xfree (copy);
3830
94b0dee1
PA
3831 remote_support_xml = reconcat (remote_support_xml,
3832 remote_support_xml, ",", xml,
3833 (char *) NULL);
c8d5aac9
L
3834 }
3835#endif
3836}
3837
3838static char *
3839remote_query_supported_append (char *msg, const char *append)
3840{
3841 if (msg)
94b0dee1 3842 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
3843 else
3844 return xstrdup (append);
3845}
3846
be2a5f71
DJ
3847static void
3848remote_query_supported (void)
3849{
3850 struct remote_state *rs = get_remote_state ();
3851 char *next;
3852 int i;
3853 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
3854
3855 /* The packet support flags are handled differently for this packet
3856 than for most others. We treat an error, a disabled packet, and
3857 an empty response identically: any features which must be reported
3858 to be used will be automatically disabled. An empty buffer
3859 accomplishes this, since that is also the representation for a list
3860 containing no features. */
3861
3862 rs->buf[0] = 0;
3863 if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
3864 {
c8d5aac9 3865 char *q = NULL;
94b0dee1 3866 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9
L
3867
3868 if (rs->extended)
3869 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9
L
3870
3871 if (remote_support_xml)
3872 q = remote_query_supported_append (q, remote_support_xml);
3873
dde08ee1
PA
3874 q = remote_query_supported_append (q, "qRelocInsn+");
3875
3876 q = reconcat (q, "qSupported:", q, (char *) NULL);
3877 putpkt (q);
82f73884 3878
94b0dee1
PA
3879 do_cleanups (old_chain);
3880
be2a5f71
DJ
3881 getpkt (&rs->buf, &rs->buf_size, 0);
3882
3883 /* If an error occured, warn, but do not return - just reset the
3884 buffer to empty and go on to disable features. */
3885 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
3886 == PACKET_ERROR)
3887 {
3888 warning (_("Remote failure reply: %s"), rs->buf);
3889 rs->buf[0] = 0;
3890 }
3891 }
3892
3893 memset (seen, 0, sizeof (seen));
3894
3895 next = rs->buf;
3896 while (*next)
3897 {
3898 enum packet_support is_supported;
3899 char *p, *end, *name_end, *value;
3900
3901 /* First separate out this item from the rest of the packet. If
3902 there's another item after this, we overwrite the separator
3903 (terminated strings are much easier to work with). */
3904 p = next;
3905 end = strchr (p, ';');
3906 if (end == NULL)
3907 {
3908 end = p + strlen (p);
3909 next = end;
3910 }
3911 else
3912 {
89be2091
DJ
3913 *end = '\0';
3914 next = end + 1;
3915
be2a5f71
DJ
3916 if (end == p)
3917 {
3918 warning (_("empty item in \"qSupported\" response"));
3919 continue;
3920 }
be2a5f71
DJ
3921 }
3922
3923 name_end = strchr (p, '=');
3924 if (name_end)
3925 {
3926 /* This is a name=value entry. */
3927 is_supported = PACKET_ENABLE;
3928 value = name_end + 1;
3929 *name_end = '\0';
3930 }
3931 else
3932 {
3933 value = NULL;
3934 switch (end[-1])
3935 {
3936 case '+':
3937 is_supported = PACKET_ENABLE;
3938 break;
3939
3940 case '-':
3941 is_supported = PACKET_DISABLE;
3942 break;
3943
3944 case '?':
3945 is_supported = PACKET_SUPPORT_UNKNOWN;
3946 break;
3947
3948 default:
3e43a32a
MS
3949 warning (_("unrecognized item \"%s\" "
3950 "in \"qSupported\" response"), p);
be2a5f71
DJ
3951 continue;
3952 }
3953 end[-1] = '\0';
3954 }
3955
3956 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3957 if (strcmp (remote_protocol_features[i].name, p) == 0)
3958 {
3959 const struct protocol_feature *feature;
3960
3961 seen[i] = 1;
3962 feature = &remote_protocol_features[i];
3963 feature->func (feature, is_supported, value);
3964 break;
3965 }
3966 }
3967
3968 /* If we increased the packet size, make sure to increase the global
3969 buffer size also. We delay this until after parsing the entire
3970 qSupported packet, because this is the same buffer we were
3971 parsing. */
3972 if (rs->buf_size < rs->explicit_packet_size)
3973 {
3974 rs->buf_size = rs->explicit_packet_size;
3975 rs->buf = xrealloc (rs->buf, rs->buf_size);
3976 }
3977
3978 /* Handle the defaults for unmentioned features. */
3979 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3980 if (!seen[i])
3981 {
3982 const struct protocol_feature *feature;
3983
3984 feature = &remote_protocol_features[i];
3985 feature->func (feature, feature->default_support, NULL);
3986 }
3987}
3988
3989
c906108c 3990static void
3e43a32a
MS
3991remote_open_1 (char *name, int from_tty,
3992 struct target_ops *target, int extended_p)
c906108c 3993{
d01949b6 3994 struct remote_state *rs = get_remote_state ();
a6f3e723 3995
c906108c 3996 if (name == 0)
8a3fe4f8 3997 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 3998 "serial device is attached to the remote system\n"
8a3fe4f8 3999 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4000
23860348 4001 /* See FIXME above. */
c6ebd6cf 4002 if (!target_async_permitted)
92d1e331 4003 wait_forever_enabled_p = 1;
6426a772 4004
2d717e4f
DJ
4005 /* If we're connected to a running target, target_preopen will kill it.
4006 But if we're connected to a target system with no running process,
4007 then we will still be connected when it returns. Ask this question
4008 first, before target_preopen has a chance to kill anything. */
c35b1492 4009 if (remote_desc != NULL && !have_inferiors ())
2d717e4f
DJ
4010 {
4011 if (!from_tty
4012 || query (_("Already connected to a remote target. Disconnect? ")))
4013 pop_target ();
4014 else
4015 error (_("Still connected."));
4016 }
4017
c906108c
SS
4018 target_preopen (from_tty);
4019
4020 unpush_target (target);
4021
2d717e4f
DJ
4022 /* This time without a query. If we were connected to an
4023 extended-remote target and target_preopen killed the running
4024 process, we may still be connected. If we are starting "target
4025 remote" now, the extended-remote target will not have been
4026 removed by unpush_target. */
c35b1492 4027 if (remote_desc != NULL && !have_inferiors ())
2d717e4f
DJ
4028 pop_target ();
4029
89be2091
DJ
4030 /* Make sure we send the passed signals list the next time we resume. */
4031 xfree (last_pass_packet);
4032 last_pass_packet = NULL;
4033
ad9a8f3f 4034 remote_fileio_reset ();
1dd41f16
NS
4035 reopen_exec_file ();
4036 reread_symbols ();
4037
9db8d71f 4038 remote_desc = remote_serial_open (name);
c906108c
SS
4039 if (!remote_desc)
4040 perror_with_name (name);
4041
4042 if (baud_rate != -1)
4043 {
2cd58942 4044 if (serial_setbaudrate (remote_desc, baud_rate))
c906108c 4045 {
9b74d5d3
KB
4046 /* The requested speed could not be set. Error out to
4047 top level after closing remote_desc. Take care to
4048 set remote_desc to NULL to avoid closing remote_desc
4049 more than once. */
2cd58942 4050 serial_close (remote_desc);
9b74d5d3 4051 remote_desc = NULL;
c906108c
SS
4052 perror_with_name (name);
4053 }
4054 }
4055
2cd58942 4056 serial_raw (remote_desc);
c906108c
SS
4057
4058 /* If there is something sitting in the buffer we might take it as a
4059 response to a command, which would be bad. */
2cd58942 4060 serial_flush_input (remote_desc);
c906108c
SS
4061
4062 if (from_tty)
4063 {
4064 puts_filtered ("Remote debugging using ");
4065 puts_filtered (name);
4066 puts_filtered ("\n");
4067 }
23860348 4068 push_target (target); /* Switch to using remote target now. */
c906108c 4069
74531fed
PA
4070 /* Register extra event sources in the event loop. */
4071 remote_async_inferior_event_token
4072 = create_async_event_handler (remote_async_inferior_event_handler,
4073 NULL);
4074 remote_async_get_pending_events_token
4075 = create_async_event_handler (remote_async_get_pending_events_handler,
4076 NULL);
4077
be2a5f71
DJ
4078 /* Reset the target state; these things will be queried either by
4079 remote_query_supported or as they are needed. */
d471ea57 4080 init_all_packet_configs ();
74531fed 4081 rs->cached_wait_status = 0;
be2a5f71 4082 rs->explicit_packet_size = 0;
a6f3e723 4083 rs->noack_mode = 0;
82f73884
PA
4084 rs->multi_process_aware = 0;
4085 rs->extended = extended_p;
74531fed 4086 rs->non_stop_aware = 0;
e24a49d8 4087 rs->waiting_for_stop_reply = 0;
3a29589a 4088 rs->ctrlc_pending_p = 0;
802188a7 4089
79d7f229
PA
4090 general_thread = not_sent_ptid;
4091 continue_thread = not_sent_ptid;
e6e4e701 4092 remote_traceframe_number = -1;
c906108c 4093
9d1f7ab2
MS
4094 /* Probe for ability to use "ThreadInfo" query, as required. */
4095 use_threadinfo_query = 1;
4096 use_threadextra_query = 1;
4097
c6ebd6cf 4098 if (target_async_permitted)
92d1e331 4099 {
23860348 4100 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4101 remote_async_terminal_ours_p = 1;
4102
4103 /* FIXME: cagney/1999-09-23: During the initial connection it is
4104 assumed that the target is already ready and able to respond to
0df8b418 4105 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4106 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4107 around this. Eventually a mechanism that allows
92d1e331 4108 wait_for_inferior() to expect/get timeouts will be
23860348 4109 implemented. */
92d1e331
DJ
4110 wait_forever_enabled_p = 0;
4111 }
4112
23860348 4113 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4114 no_shared_libraries (NULL, 0);
f78f6cf1 4115
74531fed
PA
4116 /* Start afresh. */
4117 init_thread_list ();
4118
36918e70 4119 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4120 target (we'd otherwise be in an inconsistent state) and then
4121 propogate the error on up the exception chain. This ensures that
4122 the caller doesn't stumble along blindly assuming that the
4123 function succeeded. The CLI doesn't have this problem but other
4124 UI's, such as MI do.
36918e70
AC
4125
4126 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4127 this function should return an error indication letting the
ce2826aa 4128 caller restore the previous state. Unfortunately the command
36918e70
AC
4129 ``target remote'' is directly wired to this function making that
4130 impossible. On a positive note, the CLI side of this problem has
4131 been fixed - the function set_cmd_context() makes it possible for
4132 all the ``target ....'' commands to share a common callback
4133 function. See cli-dump.c. */
109c3e39 4134 {
04bd08de 4135 volatile struct gdb_exception ex;
2d717e4f 4136
04bd08de
TT
4137 TRY_CATCH (ex, RETURN_MASK_ALL)
4138 {
4139 remote_start_remote (from_tty, target, extended_p);
4140 }
109c3e39
AC
4141 if (ex.reason < 0)
4142 {
c8d104ad
PA
4143 /* Pop the partially set up target - unless something else did
4144 already before throwing the exception. */
4145 if (remote_desc != NULL)
4146 pop_target ();
c6ebd6cf 4147 if (target_async_permitted)
109c3e39
AC
4148 wait_forever_enabled_p = 1;
4149 throw_exception (ex);
4150 }
4151 }
c906108c 4152
c6ebd6cf 4153 if (target_async_permitted)
92d1e331 4154 wait_forever_enabled_p = 1;
43ff13b4
JM
4155}
4156
c906108c
SS
4157/* This takes a program previously attached to and detaches it. After
4158 this is done, GDB can be used to debug some other program. We
4159 better not have left any breakpoints in the target program or it'll
4160 die when it hits one. */
4161
4162static void
2d717e4f 4163remote_detach_1 (char *args, int from_tty, int extended)
c906108c 4164{
82f73884 4165 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4166 struct remote_state *rs = get_remote_state ();
c906108c
SS
4167
4168 if (args)
8a3fe4f8 4169 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4170
2d717e4f
DJ
4171 if (!target_has_execution)
4172 error (_("No process to detach from."));
4173
c906108c 4174 /* Tell the remote target to detach. */
82f73884
PA
4175 if (remote_multi_process_p (rs))
4176 sprintf (rs->buf, "D;%x", pid);
4177 else
4178 strcpy (rs->buf, "D");
4179
4ddda9b5
PA
4180 putpkt (rs->buf);
4181 getpkt (&rs->buf, &rs->buf_size, 0);
4182
82f73884
PA
4183 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4184 ;
4185 else if (rs->buf[0] == '\0')
4186 error (_("Remote doesn't know how to detach"));
4187 else
4ddda9b5 4188 error (_("Can't detach process."));
c906108c 4189
c906108c 4190 if (from_tty)
2d717e4f 4191 {
82f73884
PA
4192 if (remote_multi_process_p (rs))
4193 printf_filtered (_("Detached from remote %s.\n"),
4194 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4195 else
82f73884
PA
4196 {
4197 if (extended)
4198 puts_filtered (_("Detached from remote process.\n"));
4199 else
4200 puts_filtered (_("Ending remote debugging.\n"));
4201 }
2d717e4f 4202 }
82f73884 4203
74531fed 4204 discard_pending_stop_replies (pid);
82f73884 4205 target_mourn_inferior ();
2d717e4f
DJ
4206}
4207
4208static void
136d6dae 4209remote_detach (struct target_ops *ops, char *args, int from_tty)
2d717e4f
DJ
4210{
4211 remote_detach_1 (args, from_tty, 0);
4212}
4213
4214static void
136d6dae 4215extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
2d717e4f
DJ
4216{
4217 remote_detach_1 (args, from_tty, 1);
c906108c
SS
4218}
4219
6ad8ae5c
DJ
4220/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4221
43ff13b4 4222static void
597320e7 4223remote_disconnect (struct target_ops *target, char *args, int from_tty)
43ff13b4 4224{
43ff13b4 4225 if (args)
2d717e4f 4226 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4227
2d717e4f
DJ
4228 /* Make sure we unpush even the extended remote targets; mourn
4229 won't do it. So call remote_mourn_1 directly instead of
4230 target_mourn_inferior. */
4231 remote_mourn_1 (target);
4232
43ff13b4
JM
4233 if (from_tty)
4234 puts_filtered ("Ending remote debugging.\n");
4235}
4236
2d717e4f
DJ
4237/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4238 be chatty about it. */
4239
4240static void
4241extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
4242{
4243 struct remote_state *rs = get_remote_state ();
be86555c 4244 int pid;
96ef3384 4245 char *wait_status = NULL;
2d717e4f 4246
74164c56 4247 pid = parse_pid_to_attach (args);
2d717e4f 4248
74164c56
JK
4249 /* Remote PID can be freely equal to getpid, do not check it here the same
4250 way as in other targets. */
2d717e4f
DJ
4251
4252 if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4253 error (_("This target does not support attaching to a process"));
4254
4255 sprintf (rs->buf, "vAttach;%x", pid);
4256 putpkt (rs->buf);
4257 getpkt (&rs->buf, &rs->buf_size, 0);
4258
3e43a32a
MS
4259 if (packet_ok (rs->buf,
4260 &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
2d717e4f
DJ
4261 {
4262 if (from_tty)
4263 printf_unfiltered (_("Attached to %s\n"),
4264 target_pid_to_str (pid_to_ptid (pid)));
4265
74531fed
PA
4266 if (!non_stop)
4267 {
4268 /* Save the reply for later. */
4269 wait_status = alloca (strlen (rs->buf) + 1);
4270 strcpy (wait_status, rs->buf);
4271 }
4272 else if (strcmp (rs->buf, "OK") != 0)
4273 error (_("Attaching to %s failed with: %s"),
4274 target_pid_to_str (pid_to_ptid (pid)),
4275 rs->buf);
2d717e4f
DJ
4276 }
4277 else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
4278 error (_("This target does not support attaching to a process"));
4279 else
4280 error (_("Attaching to %s failed"),
4281 target_pid_to_str (pid_to_ptid (pid)));
4282
6c95b8df 4283 set_current_inferior (remote_add_inferior (pid, 1));
bad34192 4284
2d717e4f 4285 inferior_ptid = pid_to_ptid (pid);
79d7f229 4286
bad34192
PA
4287 if (non_stop)
4288 {
4289 struct thread_info *thread;
79d7f229 4290
bad34192
PA
4291 /* Get list of threads. */
4292 remote_threads_info (target);
82f73884 4293
bad34192
PA
4294 thread = first_thread_of_process (pid);
4295 if (thread)
4296 inferior_ptid = thread->ptid;
4297 else
4298 inferior_ptid = pid_to_ptid (pid);
4299
4300 /* Invalidate our notion of the remote current thread. */
4301 record_currthread (minus_one_ptid);
4302 }
74531fed 4303 else
bad34192
PA
4304 {
4305 /* Now, if we have thread information, update inferior_ptid. */
4306 inferior_ptid = remote_current_thread (inferior_ptid);
4307
4308 /* Add the main thread to the thread list. */
4309 add_thread_silent (inferior_ptid);
4310 }
c0a2216e 4311
96ef3384
UW
4312 /* Next, if the target can specify a description, read it. We do
4313 this before anything involving memory or registers. */
4314 target_find_description ();
4315
74531fed
PA
4316 if (!non_stop)
4317 {
4318 /* Use the previously fetched status. */
4319 gdb_assert (wait_status != NULL);
4320
4321 if (target_can_async_p ())
4322 {
4323 struct stop_reply *stop_reply;
4324 struct cleanup *old_chain;
4325
4326 stop_reply = stop_reply_xmalloc ();
4327 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4328 remote_parse_stop_reply (wait_status, stop_reply);
4329 discard_cleanups (old_chain);
4330 push_stop_reply (stop_reply);
4331
4332 target_async (inferior_event_handler, 0);
4333 }
4334 else
4335 {
4336 gdb_assert (wait_status != NULL);
4337 strcpy (rs->buf, wait_status);
4338 rs->cached_wait_status = 1;
4339 }
4340 }
4341 else
4342 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4343}
4344
4345static void
136d6dae 4346extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
2d717e4f 4347{
136d6dae 4348 extended_remote_attach_1 (ops, args, from_tty);
2d717e4f
DJ
4349}
4350
c906108c
SS
4351/* Convert hex digit A to a number. */
4352
30559e10 4353static int
fba45db2 4354fromhex (int a)
c906108c
SS
4355{
4356 if (a >= '0' && a <= '9')
4357 return a - '0';
4358 else if (a >= 'a' && a <= 'f')
4359 return a - 'a' + 10;
4360 else if (a >= 'A' && a <= 'F')
4361 return a - 'A' + 10;
c5aa993b 4362 else
8a3fe4f8 4363 error (_("Reply contains invalid hex digit %d"), a);
c906108c
SS
4364}
4365
00bf0b85 4366int
cfd77fa1 4367hex2bin (const char *hex, gdb_byte *bin, int count)
30559e10
MS
4368{
4369 int i;
4370
30559e10
MS
4371 for (i = 0; i < count; i++)
4372 {
4373 if (hex[0] == 0 || hex[1] == 0)
4374 {
4375 /* Hex string is short, or of uneven length.
23860348 4376 Return the count that has been converted so far. */
30559e10
MS
4377 return i;
4378 }
4379 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
4380 hex += 2;
4381 }
4382 return i;
4383}
4384
c906108c
SS
4385/* Convert number NIB to a hex digit. */
4386
4387static int
fba45db2 4388tohex (int nib)
c906108c
SS
4389{
4390 if (nib < 10)
c5aa993b 4391 return '0' + nib;
c906108c 4392 else
c5aa993b 4393 return 'a' + nib - 10;
c906108c 4394}
30559e10 4395
00bf0b85 4396int
cfd77fa1 4397bin2hex (const gdb_byte *bin, char *hex, int count)
30559e10
MS
4398{
4399 int i;
a744cf53 4400
23860348 4401 /* May use a length, or a nul-terminated string as input. */
30559e10 4402 if (count == 0)
cfd77fa1 4403 count = strlen ((char *) bin);
30559e10
MS
4404
4405 for (i = 0; i < count; i++)
4406 {
4407 *hex++ = tohex ((*bin >> 4) & 0xf);
4408 *hex++ = tohex (*bin++ & 0xf);
4409 }
4410 *hex = 0;
4411 return i;
4412}
c906108c 4413\f
506fb367
DJ
4414/* Check for the availability of vCont. This function should also check
4415 the response. */
c906108c
SS
4416
4417static void
6d820c5c 4418remote_vcont_probe (struct remote_state *rs)
c906108c 4419{
2e9f7625 4420 char *buf;
6d820c5c 4421
2e9f7625
DJ
4422 strcpy (rs->buf, "vCont?");
4423 putpkt (rs->buf);
6d820c5c 4424 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4425 buf = rs->buf;
c906108c 4426
506fb367
DJ
4427 /* Make sure that the features we assume are supported. */
4428 if (strncmp (buf, "vCont", 5) == 0)
4429 {
4430 char *p = &buf[5];
4431 int support_s, support_S, support_c, support_C;
4432
4433 support_s = 0;
4434 support_S = 0;
4435 support_c = 0;
4436 support_C = 0;
74531fed 4437 rs->support_vCont_t = 0;
506fb367
DJ
4438 while (p && *p == ';')
4439 {
4440 p++;
4441 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4442 support_s = 1;
4443 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4444 support_S = 1;
4445 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4446 support_c = 1;
4447 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4448 support_C = 1;
74531fed
PA
4449 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4450 rs->support_vCont_t = 1;
506fb367
DJ
4451
4452 p = strchr (p, ';');
4453 }
c906108c 4454
506fb367
DJ
4455 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4456 BUF will make packet_ok disable the packet. */
4457 if (!support_s || !support_S || !support_c || !support_C)
4458 buf[0] = 0;
4459 }
c906108c 4460
444abaca 4461 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4462}
c906108c 4463
0d8f58ca
PA
4464/* Helper function for building "vCont" resumptions. Write a
4465 resumption to P. ENDP points to one-passed-the-end of the buffer
4466 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4467 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4468 resumed thread should be single-stepped and/or signalled. If PTID
4469 equals minus_one_ptid, then all threads are resumed; if PTID
4470 represents a process, then all threads of the process are resumed;
4471 the thread to be stepped and/or signalled is given in the global
4472 INFERIOR_PTID. */
4473
4474static char *
4475append_resumption (char *p, char *endp,
4476 ptid_t ptid, int step, enum target_signal siggnal)
4477{
4478 struct remote_state *rs = get_remote_state ();
4479
4480 if (step && siggnal != TARGET_SIGNAL_0)
4481 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4482 else if (step)
4483 p += xsnprintf (p, endp - p, ";s");
4484 else if (siggnal != TARGET_SIGNAL_0)
4485 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4486 else
4487 p += xsnprintf (p, endp - p, ";c");
4488
4489 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4490 {
4491 ptid_t nptid;
4492
4493 /* All (-1) threads of process. */
4494 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4495
4496 p += xsnprintf (p, endp - p, ":");
4497 p = write_ptid (p, endp, nptid);
4498 }
4499 else if (!ptid_equal (ptid, minus_one_ptid))
4500 {
4501 p += xsnprintf (p, endp - p, ":");
4502 p = write_ptid (p, endp, ptid);
4503 }
4504
4505 return p;
4506}
4507
506fb367
DJ
4508/* Resume the remote inferior by using a "vCont" packet. The thread
4509 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
4510 resumed thread should be single-stepped and/or signalled. If PTID
4511 equals minus_one_ptid, then all threads are resumed; the thread to
4512 be stepped and/or signalled is given in the global INFERIOR_PTID.
4513 This function returns non-zero iff it resumes the inferior.
44eaed12 4514
506fb367
DJ
4515 This function issues a strict subset of all possible vCont commands at the
4516 moment. */
44eaed12 4517
506fb367
DJ
4518static int
4519remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
4520{
4521 struct remote_state *rs = get_remote_state ();
82f73884
PA
4522 char *p;
4523 char *endp;
44eaed12 4524
444abaca 4525 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
6d820c5c 4526 remote_vcont_probe (rs);
44eaed12 4527
444abaca 4528 if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
6d820c5c 4529 return 0;
44eaed12 4530
82f73884
PA
4531 p = rs->buf;
4532 endp = rs->buf + get_remote_packet_size ();
4533
506fb367
DJ
4534 /* If we could generate a wider range of packets, we'd have to worry
4535 about overflowing BUF. Should there be a generic
4536 "multi-part-packet" packet? */
4537
0d8f58ca
PA
4538 p += xsnprintf (p, endp - p, "vCont");
4539
79d7f229 4540 if (ptid_equal (ptid, magic_null_ptid))
c906108c 4541 {
79d7f229
PA
4542 /* MAGIC_NULL_PTID means that we don't have any active threads,
4543 so we don't have any TID numbers the inferior will
4544 understand. Make sure to only send forms that do not specify
4545 a TID. */
a9cbf802 4546 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 4547 }
0d8f58ca 4548 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 4549 {
0d8f58ca
PA
4550 /* Resume all threads (of all processes, or of a single
4551 process), with preference for INFERIOR_PTID. This assumes
4552 inferior_ptid belongs to the set of all threads we are about
4553 to resume. */
4554 if (step || siggnal != TARGET_SIGNAL_0)
82f73884 4555 {
0d8f58ca
PA
4556 /* Step inferior_ptid, with or without signal. */
4557 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 4558 }
0d8f58ca
PA
4559
4560 /* And continue others without a signal. */
a9cbf802 4561 append_resumption (p, endp, ptid, /*step=*/ 0, TARGET_SIGNAL_0);
c906108c
SS
4562 }
4563 else
506fb367
DJ
4564 {
4565 /* Scheduler locking; resume only PTID. */
a9cbf802 4566 append_resumption (p, endp, ptid, step, siggnal);
506fb367 4567 }
c906108c 4568
82f73884
PA
4569 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
4570 putpkt (rs->buf);
506fb367 4571
74531fed
PA
4572 if (non_stop)
4573 {
4574 /* In non-stop, the stub replies to vCont with "OK". The stop
4575 reply will be reported asynchronously by means of a `%Stop'
4576 notification. */
4577 getpkt (&rs->buf, &rs->buf_size, 0);
4578 if (strcmp (rs->buf, "OK") != 0)
4579 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
4580 }
4581
506fb367 4582 return 1;
c906108c 4583}
43ff13b4 4584
506fb367
DJ
4585/* Tell the remote machine to resume. */
4586
4587static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
4588
4589static int last_sent_step;
4590
43ff13b4 4591static void
28439f5e
PA
4592remote_resume (struct target_ops *ops,
4593 ptid_t ptid, int step, enum target_signal siggnal)
43ff13b4 4594{
d01949b6 4595 struct remote_state *rs = get_remote_state ();
2e9f7625 4596 char *buf;
43ff13b4 4597
43ff13b4
JM
4598 last_sent_signal = siggnal;
4599 last_sent_step = step;
4600
506fb367 4601 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
4602 /* No reverse support (yet) for vCont. */
4603 if (execution_direction != EXEC_REVERSE)
4604 if (remote_vcont_resume (ptid, step, siggnal))
4605 goto done;
506fb367 4606
79d7f229
PA
4607 /* All other supported resume packets do use Hc, so set the continue
4608 thread. */
4609 if (ptid_equal (ptid, minus_one_ptid))
4610 set_continue_thread (any_thread_ptid);
506fb367 4611 else
79d7f229 4612 set_continue_thread (ptid);
506fb367 4613
2e9f7625 4614 buf = rs->buf;
b2175913
MS
4615 if (execution_direction == EXEC_REVERSE)
4616 {
4617 /* We don't pass signals to the target in reverse exec mode. */
4618 if (info_verbose && siggnal != TARGET_SIGNAL_0)
7ea6d463 4619 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 4620 siggnal);
40ab02ce
MS
4621
4622 if (step
4623 && remote_protocol_packets[PACKET_bs].support == PACKET_DISABLE)
4624 error (_("Remote reverse-step not supported."));
4625 if (!step
4626 && remote_protocol_packets[PACKET_bc].support == PACKET_DISABLE)
08c93ed9 4627 error (_("Remote reverse-continue not supported."));
40ab02ce 4628
b2175913
MS
4629 strcpy (buf, step ? "bs" : "bc");
4630 }
4631 else if (siggnal != TARGET_SIGNAL_0)
43ff13b4
JM
4632 {
4633 buf[0] = step ? 'S' : 'C';
c5aa993b 4634 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 4635 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
4636 buf[3] = '\0';
4637 }
4638 else
c5aa993b 4639 strcpy (buf, step ? "s" : "c");
506fb367 4640
44eaed12 4641 putpkt (buf);
43ff13b4 4642
75c99385 4643 done:
2acceee2 4644 /* We are about to start executing the inferior, let's register it
0df8b418
MS
4645 with the event loop. NOTE: this is the one place where all the
4646 execution commands end up. We could alternatively do this in each
23860348 4647 of the execution commands in infcmd.c. */
2acceee2
JM
4648 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
4649 into infcmd.c in order to allow inferior function calls to work
23860348 4650 NOT asynchronously. */
362646f5 4651 if (target_can_async_p ())
2acceee2 4652 target_async (inferior_event_handler, 0);
e24a49d8
PA
4653
4654 /* We've just told the target to resume. The remote server will
4655 wait for the inferior to stop, and then send a stop reply. In
4656 the mean time, we can't start another command/query ourselves
74531fed
PA
4657 because the stub wouldn't be ready to process it. This applies
4658 only to the base all-stop protocol, however. In non-stop (which
4659 only supports vCont), the stub replies with an "OK", and is
4660 immediate able to process further serial input. */
4661 if (!non_stop)
4662 rs->waiting_for_stop_reply = 1;
43ff13b4 4663}
c906108c 4664\f
43ff13b4
JM
4665
4666/* Set up the signal handler for SIGINT, while the target is
23860348 4667 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 4668static void
fba45db2 4669initialize_sigint_signal_handler (void)
43ff13b4 4670{
43ff13b4
JM
4671 signal (SIGINT, handle_remote_sigint);
4672}
4673
23860348 4674/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 4675static void
fba45db2 4676handle_remote_sigint (int sig)
43ff13b4
JM
4677{
4678 signal (sig, handle_remote_sigint_twice);
43ff13b4
JM
4679 mark_async_signal_handler_wrapper (sigint_remote_token);
4680}
4681
4682/* Signal handler for SIGINT, installed after SIGINT has already been
4683 sent once. It will take effect the second time that the user sends
23860348 4684 a ^C. */
43ff13b4 4685static void
fba45db2 4686handle_remote_sigint_twice (int sig)
43ff13b4 4687{
b803fb0f 4688 signal (sig, handle_remote_sigint);
43ff13b4
JM
4689 mark_async_signal_handler_wrapper (sigint_remote_twice_token);
4690}
4691
6426a772 4692/* Perform the real interruption of the target execution, in response
23860348 4693 to a ^C. */
c5aa993b 4694static void
fba45db2 4695async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
4696{
4697 if (remote_debug)
4698 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
4699
94cc34af 4700 target_stop (inferior_ptid);
43ff13b4
JM
4701}
4702
0df8b418 4703/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 4704 up on the target alltogether. */
2df3850c 4705void
fba45db2 4706async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 4707{
2df3850c
JM
4708 if (remote_debug)
4709 fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
b803fb0f
DJ
4710
4711 interrupt_query ();
43ff13b4
JM
4712}
4713
4714/* Reinstall the usual SIGINT handlers, after the target has
23860348 4715 stopped. */
6426a772
JM
4716static void
4717cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
4718{
4719 signal (SIGINT, handle_sigint);
43ff13b4
JM
4720}
4721
c906108c
SS
4722/* Send ^C to target to halt it. Target will respond, and send us a
4723 packet. */
507f3c78 4724static void (*ofunc) (int);
c906108c 4725
0df8b418
MS
4726/* The command line interface's stop routine. This function is installed
4727 as a signal handler for SIGINT. The first time a user requests a
4728 stop, we call remote_stop to send a break or ^C. If there is no
7a292a7a 4729 response from the target (it didn't stop when the user requested it),
23860348 4730 we ask the user if he'd like to detach from the target. */
c906108c 4731static void
fba45db2 4732remote_interrupt (int signo)
c906108c 4733{
23860348 4734 /* If this doesn't work, try more severe steps. */
7a292a7a
SS
4735 signal (signo, remote_interrupt_twice);
4736
b803fb0f 4737 gdb_call_async_signal_handler (sigint_remote_token, 1);
7a292a7a
SS
4738}
4739
4740/* The user typed ^C twice. */
4741
4742static void
fba45db2 4743remote_interrupt_twice (int signo)
7a292a7a
SS
4744{
4745 signal (signo, ofunc);
b803fb0f 4746 gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
c906108c
SS
4747 signal (signo, remote_interrupt);
4748}
7a292a7a 4749
74531fed
PA
4750/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
4751 thread, all threads of a remote process, or all threads of all
4752 processes. */
4753
4754static void
4755remote_stop_ns (ptid_t ptid)
4756{
4757 struct remote_state *rs = get_remote_state ();
4758 char *p = rs->buf;
4759 char *endp = rs->buf + get_remote_packet_size ();
74531fed
PA
4760
4761 if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
4762 remote_vcont_probe (rs);
4763
4764 if (!rs->support_vCont_t)
4765 error (_("Remote server does not support stopping threads"));
4766
f91d3df5
PA
4767 if (ptid_equal (ptid, minus_one_ptid)
4768 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
4769 p += xsnprintf (p, endp - p, "vCont;t");
4770 else
4771 {
4772 ptid_t nptid;
4773
74531fed
PA
4774 p += xsnprintf (p, endp - p, "vCont;t:");
4775
4776 if (ptid_is_pid (ptid))
4777 /* All (-1) threads of process. */
4778 nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
4779 else
4780 {
4781 /* Small optimization: if we already have a stop reply for
4782 this thread, no use in telling the stub we want this
4783 stopped. */
4784 if (peek_stop_reply (ptid))
4785 return;
4786
4787 nptid = ptid;
4788 }
4789
a9cbf802 4790 write_ptid (p, endp, nptid);
74531fed
PA
4791 }
4792
4793 /* In non-stop, we get an immediate OK reply. The stop reply will
4794 come in asynchronously by notification. */
4795 putpkt (rs->buf);
4796 getpkt (&rs->buf, &rs->buf_size, 0);
4797 if (strcmp (rs->buf, "OK") != 0)
4798 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
4799}
4800
4801/* All-stop version of target_stop. Sends a break or a ^C to stop the
4802 remote target. It is undefined which thread of which process
4803 reports the stop. */
4804
4805static void
4806remote_stop_as (ptid_t ptid)
4807{
4808 struct remote_state *rs = get_remote_state ();
4809
3a29589a
DJ
4810 rs->ctrlc_pending_p = 1;
4811
74531fed
PA
4812 /* If the inferior is stopped already, but the core didn't know
4813 about it yet, just ignore the request. The cached wait status
4814 will be collected in remote_wait. */
4815 if (rs->cached_wait_status)
4816 return;
4817
9a7071a8
JB
4818 /* Send interrupt_sequence to remote target. */
4819 send_interrupt_sequence ();
74531fed
PA
4820}
4821
0df8b418 4822/* This is the generic stop called via the target vector. When a target
7a292a7a 4823 interrupt is requested, either by the command line or the GUI, we
23860348 4824 will eventually end up here. */
74531fed 4825
c906108c 4826static void
94cc34af 4827remote_stop (ptid_t ptid)
c906108c 4828{
7a292a7a 4829 if (remote_debug)
0f71a2f6 4830 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 4831
74531fed
PA
4832 if (non_stop)
4833 remote_stop_ns (ptid);
c906108c 4834 else
74531fed 4835 remote_stop_as (ptid);
c906108c
SS
4836}
4837
4838/* Ask the user what to do when an interrupt is received. */
4839
4840static void
fba45db2 4841interrupt_query (void)
c906108c
SS
4842{
4843 target_terminal_ours ();
4844
74531fed 4845 if (target_can_async_p ())
c906108c 4846 {
74531fed 4847 signal (SIGINT, handle_sigint);
315a522e 4848 deprecated_throw_reason (RETURN_QUIT);
c906108c 4849 }
74531fed
PA
4850 else
4851 {
9e2f0ad4
HZ
4852 if (query (_("Interrupted while waiting for the program.\n\
4853Give up (and stop debugging it)? ")))
74531fed
PA
4854 {
4855 pop_target ();
4856 deprecated_throw_reason (RETURN_QUIT);
4857 }
4858 }
c906108c
SS
4859
4860 target_terminal_inferior ();
4861}
4862
6426a772
JM
4863/* Enable/disable target terminal ownership. Most targets can use
4864 terminal groups to control terminal ownership. Remote targets are
4865 different in that explicit transfer of ownership to/from GDB/target
23860348 4866 is required. */
6426a772
JM
4867
4868static void
75c99385 4869remote_terminal_inferior (void)
6426a772 4870{
c6ebd6cf 4871 if (!target_async_permitted)
75c99385
PA
4872 /* Nothing to do. */
4873 return;
4874
d9d2d8b6
PA
4875 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
4876 idempotent. The event-loop GDB talking to an asynchronous target
4877 with a synchronous command calls this function from both
4878 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
4879 transfer the terminal to the target when it shouldn't this guard
4880 can go away. */
6426a772
JM
4881 if (!remote_async_terminal_ours_p)
4882 return;
4883 delete_file_handler (input_fd);
4884 remote_async_terminal_ours_p = 0;
4885 initialize_sigint_signal_handler ();
4886 /* NOTE: At this point we could also register our selves as the
4887 recipient of all input. Any characters typed could then be
23860348 4888 passed on down to the target. */
6426a772
JM
4889}
4890
4891static void
75c99385 4892remote_terminal_ours (void)
6426a772 4893{
c6ebd6cf 4894 if (!target_async_permitted)
75c99385
PA
4895 /* Nothing to do. */
4896 return;
4897
4898 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
4899 if (remote_async_terminal_ours_p)
4900 return;
4901 cleanup_sigint_signal_handler (NULL);
4902 add_file_handler (input_fd, stdin_event_handler, 0);
4903 remote_async_terminal_ours_p = 1;
4904}
4905
176a6961 4906static void
917317f4 4907remote_console_output (char *msg)
c906108c
SS
4908{
4909 char *p;
4910
c5aa993b 4911 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
4912 {
4913 char tb[2];
4914 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 4915
c906108c
SS
4916 tb[0] = c;
4917 tb[1] = 0;
43ff13b4 4918 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 4919 }
00db5b94
PA
4920 gdb_flush (gdb_stdtarg);
4921}
74531fed
PA
4922
4923typedef struct cached_reg
4924{
4925 int num;
4926 gdb_byte data[MAX_REGISTER_SIZE];
4927} cached_reg_t;
4928
4929DEF_VEC_O(cached_reg_t);
4930
4931struct stop_reply
4932{
4933 struct stop_reply *next;
4934
4935 ptid_t ptid;
4936
4937 struct target_waitstatus ws;
4938
15148d6a
PA
4939 /* Expedited registers. This makes remote debugging a bit more
4940 efficient for those targets that provide critical registers as
4941 part of their normal status mechanism (as another roundtrip to
4942 fetch them is avoided). */
74531fed
PA
4943 VEC(cached_reg_t) *regcache;
4944
4945 int stopped_by_watchpoint_p;
4946 CORE_ADDR watch_data_address;
4947
4948 int solibs_changed;
4949 int replay_event;
dc146f7c
VP
4950
4951 int core;
74531fed
PA
4952};
4953
4954/* The list of already fetched and acknowledged stop events. */
4955static struct stop_reply *stop_reply_queue;
4956
4957static struct stop_reply *
4958stop_reply_xmalloc (void)
4959{
4960 struct stop_reply *r = XMALLOC (struct stop_reply);
a744cf53 4961
74531fed
PA
4962 r->next = NULL;
4963 return r;
4964}
4965
4966static void
4967stop_reply_xfree (struct stop_reply *r)
4968{
4969 if (r != NULL)
4970 {
4971 VEC_free (cached_reg_t, r->regcache);
4972 xfree (r);
4973 }
c906108c
SS
4974}
4975
74531fed
PA
4976/* Discard all pending stop replies of inferior PID. If PID is -1,
4977 discard everything. */
c906108c 4978
74531fed
PA
4979static void
4980discard_pending_stop_replies (int pid)
c906108c 4981{
74531fed 4982 struct stop_reply *prev = NULL, *reply, *next;
c906108c 4983
74531fed
PA
4984 /* Discard the in-flight notification. */
4985 if (pending_stop_reply != NULL
4986 && (pid == -1
4987 || ptid_get_pid (pending_stop_reply->ptid) == pid))
4988 {
4989 stop_reply_xfree (pending_stop_reply);
4990 pending_stop_reply = NULL;
4991 }
c906108c 4992
74531fed
PA
4993 /* Discard the stop replies we have already pulled with
4994 vStopped. */
4995 for (reply = stop_reply_queue; reply; reply = next)
43ff13b4 4996 {
74531fed
PA
4997 next = reply->next;
4998 if (pid == -1
4999 || ptid_get_pid (reply->ptid) == pid)
9fa2223d 5000 {
74531fed
PA
5001 if (reply == stop_reply_queue)
5002 stop_reply_queue = reply->next;
5003 else
5004 prev->next = reply->next;
5005
5006 stop_reply_xfree (reply);
9fa2223d 5007 }
74531fed
PA
5008 else
5009 prev = reply;
c8e38a49 5010 }
74531fed 5011}
43ff13b4 5012
74531fed 5013/* Cleanup wrapper. */
2e9f7625 5014
74531fed
PA
5015static void
5016do_stop_reply_xfree (void *arg)
5017{
5018 struct stop_reply *r = arg;
a744cf53 5019
74531fed
PA
5020 stop_reply_xfree (r);
5021}
75c99385 5022
74531fed
PA
5023/* Look for a queued stop reply belonging to PTID. If one is found,
5024 remove it from the queue, and return it. Returns NULL if none is
5025 found. If there are still queued events left to process, tell the
5026 event loop to get back to target_wait soon. */
e24a49d8 5027
74531fed
PA
5028static struct stop_reply *
5029queued_stop_reply (ptid_t ptid)
5030{
0723dbf5
PA
5031 struct stop_reply *it;
5032 struct stop_reply **it_link;
74531fed 5033
0723dbf5
PA
5034 it = stop_reply_queue;
5035 it_link = &stop_reply_queue;
5036 while (it)
c8e38a49 5037 {
0723dbf5
PA
5038 if (ptid_match (it->ptid, ptid))
5039 {
5040 *it_link = it->next;
5041 it->next = NULL;
5042 break;
5043 }
e24a49d8 5044
0723dbf5
PA
5045 it_link = &it->next;
5046 it = *it_link;
5047 }
74531fed
PA
5048
5049 if (stop_reply_queue)
5050 /* There's still at least an event left. */
5051 mark_async_event_handler (remote_async_inferior_event_token);
5052
5053 return it;
5054}
5055
5056/* Push a fully parsed stop reply in the stop reply queue. Since we
5057 know that we now have at least one queued event left to pass to the
5058 core side, tell the event loop to get back to target_wait soon. */
5059
5060static void
5061push_stop_reply (struct stop_reply *new_event)
5062{
5063 struct stop_reply *event;
5064
5065 if (stop_reply_queue)
5066 {
5067 for (event = stop_reply_queue;
5068 event && event->next;
5069 event = event->next)
5070 ;
5071
5072 event->next = new_event;
5073 }
5074 else
5075 stop_reply_queue = new_event;
5076
5077 mark_async_event_handler (remote_async_inferior_event_token);
5078}
5079
5080/* Returns true if we have a stop reply for PTID. */
5081
5082static int
5083peek_stop_reply (ptid_t ptid)
5084{
5085 struct stop_reply *it;
5086
5087 for (it = stop_reply_queue; it; it = it->next)
5088 if (ptid_equal (ptid, it->ptid))
5089 {
5090 if (it->ws.kind == TARGET_WAITKIND_STOPPED)
5091 return 1;
5092 }
5093
5094 return 0;
5095}
5096
5097/* Parse the stop reply in BUF. Either the function succeeds, and the
5098 result is stored in EVENT, or throws an error. */
5099
5100static void
5101remote_parse_stop_reply (char *buf, struct stop_reply *event)
5102{
5103 struct remote_arch_state *rsa = get_remote_arch_state ();
5104 ULONGEST addr;
5105 char *p;
5106
5107 event->ptid = null_ptid;
5108 event->ws.kind = TARGET_WAITKIND_IGNORE;
5109 event->ws.value.integer = 0;
5110 event->solibs_changed = 0;
5111 event->replay_event = 0;
5112 event->stopped_by_watchpoint_p = 0;
5113 event->regcache = NULL;
dc146f7c 5114 event->core = -1;
74531fed
PA
5115
5116 switch (buf[0])
5117 {
5118 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5119 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5120 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5121 ss = signal number
5122 n... = register number
5123 r... = register contents
5124 */
5125
5126 p = &buf[3]; /* after Txx */
5127 while (*p)
5128 {
5129 char *p1;
5130 char *p_temp;
5131 int fieldsize;
5132 LONGEST pnum = 0;
43ff13b4 5133
cea39f65
MS
5134 /* If the packet contains a register number, save it in
5135 pnum and set p1 to point to the character following it.
5136 Otherwise p1 points to p. */
3c3bea1c 5137
cea39f65
MS
5138 /* If this packet is an awatch packet, don't parse the 'a'
5139 as a register number. */
c8e38a49 5140
dc146f7c
VP
5141 if (strncmp (p, "awatch", strlen("awatch")) != 0
5142 && strncmp (p, "core", strlen ("core") != 0))
cea39f65
MS
5143 {
5144 /* Read the ``P'' register number. */
5145 pnum = strtol (p, &p_temp, 16);
5146 p1 = p_temp;
5147 }
5148 else
5149 p1 = p;
802188a7 5150
cea39f65
MS
5151 if (p1 == p) /* No register number present here. */
5152 {
5153 p1 = strchr (p, ':');
5154 if (p1 == NULL)
5155 error (_("Malformed packet(a) (missing colon): %s\n\
c8e38a49 5156Packet: '%s'\n"),
cea39f65
MS
5157 p, buf);
5158 if (strncmp (p, "thread", p1 - p) == 0)
5159 event->ptid = read_ptid (++p1, &p);
5160 else if ((strncmp (p, "watch", p1 - p) == 0)
5161 || (strncmp (p, "rwatch", p1 - p) == 0)
5162 || (strncmp (p, "awatch", p1 - p) == 0))
5163 {
5164 event->stopped_by_watchpoint_p = 1;
5165 p = unpack_varlen_hex (++p1, &addr);
5166 event->watch_data_address = (CORE_ADDR) addr;
5167 }
5168 else if (strncmp (p, "library", p1 - p) == 0)
5169 {
5170 p1++;
5171 p_temp = p1;
5172 while (*p_temp && *p_temp != ';')
5173 p_temp++;
c8e38a49 5174
cea39f65
MS
5175 event->solibs_changed = 1;
5176 p = p_temp;
5177 }
5178 else if (strncmp (p, "replaylog", p1 - p) == 0)
5179 {
5180 /* NO_HISTORY event.
5181 p1 will indicate "begin" or "end", but
5182 it makes no difference for now, so ignore it. */
5183 event->replay_event = 1;
5184 p_temp = strchr (p1 + 1, ';');
5185 if (p_temp)
c8e38a49 5186 p = p_temp;
cea39f65 5187 }
dc146f7c
VP
5188 else if (strncmp (p, "core", p1 - p) == 0)
5189 {
5190 ULONGEST c;
a744cf53 5191
dc146f7c
VP
5192 p = unpack_varlen_hex (++p1, &c);
5193 event->core = c;
5194 }
cea39f65
MS
5195 else
5196 {
5197 /* Silently skip unknown optional info. */
5198 p_temp = strchr (p1 + 1, ';');
5199 if (p_temp)
5200 p = p_temp;
5201 }
5202 }
5203 else
5204 {
5205 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5206 cached_reg_t cached_reg;
74531fed 5207
cea39f65 5208 p = p1;
75c99385 5209
cea39f65
MS
5210 if (*p != ':')
5211 error (_("Malformed packet(b) (missing colon): %s\n\
8a3fe4f8 5212Packet: '%s'\n"),
cea39f65
MS
5213 p, buf);
5214 ++p;
43ff13b4 5215
cea39f65
MS
5216 if (reg == NULL)
5217 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 5218Packet: '%s'\n"),
7c47795c 5219 hex_string (pnum), p, buf);
c8e38a49 5220
cea39f65 5221 cached_reg.num = reg->regnum;
4100683b 5222
cea39f65
MS
5223 fieldsize = hex2bin (p, cached_reg.data,
5224 register_size (target_gdbarch,
5225 reg->regnum));
5226 p += 2 * fieldsize;
5227 if (fieldsize < register_size (target_gdbarch,
5228 reg->regnum))
5229 warning (_("Remote reply is too short: %s"), buf);
74531fed 5230
cea39f65
MS
5231 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5232 }
c8e38a49 5233
cea39f65
MS
5234 if (*p != ';')
5235 error (_("Remote register badly formatted: %s\nhere: %s"),
5236 buf, p);
5237 ++p;
5238 }
c8e38a49
PA
5239 /* fall through */
5240 case 'S': /* Old style status, just signal only. */
74531fed
PA
5241 if (event->solibs_changed)
5242 event->ws.kind = TARGET_WAITKIND_LOADED;
5243 else if (event->replay_event)
5244 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
c8e38a49
PA
5245 else
5246 {
74531fed
PA
5247 event->ws.kind = TARGET_WAITKIND_STOPPED;
5248 event->ws.value.sig = (enum target_signal)
c8e38a49
PA
5249 (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
5250 }
5251 break;
5252 case 'W': /* Target exited. */
5253 case 'X':
5254 {
5255 char *p;
5256 int pid;
5257 ULONGEST value;
82f73884 5258
c8e38a49
PA
5259 /* GDB used to accept only 2 hex chars here. Stubs should
5260 only send more if they detect GDB supports multi-process
5261 support. */
5262 p = unpack_varlen_hex (&buf[1], &value);
82f73884 5263
c8e38a49
PA
5264 if (buf[0] == 'W')
5265 {
5266 /* The remote process exited. */
74531fed
PA
5267 event->ws.kind = TARGET_WAITKIND_EXITED;
5268 event->ws.value.integer = value;
c8e38a49
PA
5269 }
5270 else
5271 {
5272 /* The remote process exited with a signal. */
74531fed
PA
5273 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5274 event->ws.value.sig = (enum target_signal) value;
c8e38a49 5275 }
82f73884 5276
c8e38a49
PA
5277 /* If no process is specified, assume inferior_ptid. */
5278 pid = ptid_get_pid (inferior_ptid);
5279 if (*p == '\0')
5280 ;
5281 else if (*p == ';')
5282 {
5283 p++;
5284
5285 if (p == '\0')
82f73884 5286 ;
c8e38a49
PA
5287 else if (strncmp (p,
5288 "process:", sizeof ("process:") - 1) == 0)
82f73884 5289 {
c8e38a49 5290 ULONGEST upid;
a744cf53 5291
c8e38a49
PA
5292 p += sizeof ("process:") - 1;
5293 unpack_varlen_hex (p, &upid);
5294 pid = upid;
82f73884
PA
5295 }
5296 else
5297 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 5298 }
c8e38a49
PA
5299 else
5300 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
5301 event->ptid = pid_to_ptid (pid);
5302 }
5303 break;
5304 }
5305
5306 if (non_stop && ptid_equal (event->ptid, null_ptid))
5307 error (_("No process or thread specified in stop reply: %s"), buf);
5308}
5309
5310/* When the stub wants to tell GDB about a new stop reply, it sends a
5311 stop notification (%Stop). Those can come it at any time, hence,
5312 we have to make sure that any pending putpkt/getpkt sequence we're
5313 making is finished, before querying the stub for more events with
5314 vStopped. E.g., if we started a vStopped sequence immediatelly
5315 upon receiving the %Stop notification, something like this could
5316 happen:
5317
5318 1.1) --> Hg 1
5319 1.2) <-- OK
5320 1.3) --> g
5321 1.4) <-- %Stop
5322 1.5) --> vStopped
5323 1.6) <-- (registers reply to step #1.3)
5324
5325 Obviously, the reply in step #1.6 would be unexpected to a vStopped
5326 query.
5327
5328 To solve this, whenever we parse a %Stop notification sucessfully,
5329 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
5330 doing whatever we were doing:
5331
5332 2.1) --> Hg 1
5333 2.2) <-- OK
5334 2.3) --> g
5335 2.4) <-- %Stop
5336 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
5337 2.5) <-- (registers reply to step #2.3)
5338
5339 Eventualy after step #2.5, we return to the event loop, which
5340 notices there's an event on the
5341 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
5342 associated callback --- the function below. At this point, we're
5343 always safe to start a vStopped sequence. :
5344
5345 2.6) --> vStopped
5346 2.7) <-- T05 thread:2
5347 2.8) --> vStopped
5348 2.9) --> OK
5349*/
5350
5351static void
5352remote_get_pending_stop_replies (void)
5353{
5354 struct remote_state *rs = get_remote_state ();
74531fed
PA
5355
5356 if (pending_stop_reply)
5357 {
5358 /* acknowledge */
5359 putpkt ("vStopped");
5360
5361 /* Now we can rely on it. */
5362 push_stop_reply (pending_stop_reply);
5363 pending_stop_reply = NULL;
5364
5365 while (1)
5366 {
5367 getpkt (&rs->buf, &rs->buf_size, 0);
5368 if (strcmp (rs->buf, "OK") == 0)
5369 break;
5370 else
5371 {
5372 struct cleanup *old_chain;
5373 struct stop_reply *stop_reply = stop_reply_xmalloc ();
5374
5375 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5376 remote_parse_stop_reply (rs->buf, stop_reply);
5377
5378 /* acknowledge */
5379 putpkt ("vStopped");
5380
5381 if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
5382 {
5383 /* Now we can rely on it. */
5384 discard_cleanups (old_chain);
5385 push_stop_reply (stop_reply);
5386 }
5387 else
5388 /* We got an unknown stop reply. */
5389 do_cleanups (old_chain);
5390 }
5391 }
5392 }
5393}
5394
5395
5396/* Called when it is decided that STOP_REPLY holds the info of the
5397 event that is to be returned to the core. This function always
5398 destroys STOP_REPLY. */
5399
5400static ptid_t
5401process_stop_reply (struct stop_reply *stop_reply,
5402 struct target_waitstatus *status)
5403{
5404 ptid_t ptid;
5405
5406 *status = stop_reply->ws;
5407 ptid = stop_reply->ptid;
5408
5409 /* If no thread/process was reported by the stub, assume the current
5410 inferior. */
5411 if (ptid_equal (ptid, null_ptid))
5412 ptid = inferior_ptid;
5413
5f3563ea
PA
5414 if (status->kind != TARGET_WAITKIND_EXITED
5415 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 5416 {
5f3563ea
PA
5417 /* Expedited registers. */
5418 if (stop_reply->regcache)
5419 {
217f1f79
UW
5420 struct regcache *regcache
5421 = get_thread_arch_regcache (ptid, target_gdbarch);
5f3563ea
PA
5422 cached_reg_t *reg;
5423 int ix;
5424
5425 for (ix = 0;
5426 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
5427 ix++)
217f1f79 5428 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
5429 VEC_free (cached_reg_t, stop_reply->regcache);
5430 }
74531fed 5431
5f3563ea
PA
5432 remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
5433 remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
5434
5435 remote_notice_new_inferior (ptid, 0);
dc146f7c 5436 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
5437 }
5438
74531fed
PA
5439 stop_reply_xfree (stop_reply);
5440 return ptid;
5441}
5442
5443/* The non-stop mode version of target_wait. */
5444
5445static ptid_t
47608cb1 5446remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5447{
5448 struct remote_state *rs = get_remote_state ();
74531fed
PA
5449 struct stop_reply *stop_reply;
5450 int ret;
5451
5452 /* If in non-stop mode, get out of getpkt even if a
5453 notification is received. */
5454
5455 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5456 0 /* forever */);
5457 while (1)
5458 {
5459 if (ret != -1)
5460 switch (rs->buf[0])
5461 {
5462 case 'E': /* Error of some sort. */
5463 /* We're out of sync with the target now. Did it continue
5464 or not? We can't tell which thread it was in non-stop,
5465 so just ignore this. */
5466 warning (_("Remote failure reply: %s"), rs->buf);
5467 break;
5468 case 'O': /* Console output. */
5469 remote_console_output (rs->buf + 1);
5470 break;
5471 default:
5472 warning (_("Invalid remote reply: %s"), rs->buf);
5473 break;
5474 }
5475
5476 /* Acknowledge a pending stop reply that may have arrived in the
5477 mean time. */
5478 if (pending_stop_reply != NULL)
5479 remote_get_pending_stop_replies ();
5480
5481 /* If indeed we noticed a stop reply, we're done. */
5482 stop_reply = queued_stop_reply (ptid);
5483 if (stop_reply != NULL)
5484 return process_stop_reply (stop_reply, status);
5485
47608cb1 5486 /* Still no event. If we're just polling for an event, then
74531fed 5487 return to the event loop. */
47608cb1 5488 if (options & TARGET_WNOHANG)
74531fed
PA
5489 {
5490 status->kind = TARGET_WAITKIND_IGNORE;
5491 return minus_one_ptid;
5492 }
5493
47608cb1 5494 /* Otherwise do a blocking wait. */
74531fed
PA
5495 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
5496 1 /* forever */);
5497 }
5498}
5499
5500/* Wait until the remote machine stops, then return, storing status in
5501 STATUS just as `wait' would. */
5502
5503static ptid_t
47608cb1 5504remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
5505{
5506 struct remote_state *rs = get_remote_state ();
74531fed 5507 ptid_t event_ptid = null_ptid;
cea39f65 5508 char *buf;
74531fed
PA
5509 struct stop_reply *stop_reply;
5510
47608cb1
PA
5511 again:
5512
74531fed
PA
5513 status->kind = TARGET_WAITKIND_IGNORE;
5514 status->value.integer = 0;
5515
5516 stop_reply = queued_stop_reply (ptid);
5517 if (stop_reply != NULL)
5518 return process_stop_reply (stop_reply, status);
5519
5520 if (rs->cached_wait_status)
5521 /* Use the cached wait status, but only once. */
5522 rs->cached_wait_status = 0;
5523 else
5524 {
5525 int ret;
5526
5527 if (!target_is_async_p ())
5528 {
5529 ofunc = signal (SIGINT, remote_interrupt);
5530 /* If the user hit C-c before this packet, or between packets,
5531 pretend that it was hit right here. */
5532 if (quit_flag)
5533 {
5534 quit_flag = 0;
5535 remote_interrupt (SIGINT);
5536 }
5537 }
5538
5539 /* FIXME: cagney/1999-09-27: If we're in async mode we should
5540 _never_ wait for ever -> test on target_is_async_p().
5541 However, before we do that we need to ensure that the caller
5542 knows how to take the target into/out of async mode. */
5543 ret = getpkt_sane (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
5544 if (!target_is_async_p ())
5545 signal (SIGINT, ofunc);
5546 }
5547
5548 buf = rs->buf;
5549
5550 remote_stopped_by_watchpoint_p = 0;
5551
5552 /* We got something. */
5553 rs->waiting_for_stop_reply = 0;
5554
3a29589a
DJ
5555 /* Assume that the target has acknowledged Ctrl-C unless we receive
5556 an 'F' or 'O' packet. */
5557 if (buf[0] != 'F' && buf[0] != 'O')
5558 rs->ctrlc_pending_p = 0;
5559
74531fed
PA
5560 switch (buf[0])
5561 {
5562 case 'E': /* Error of some sort. */
5563 /* We're out of sync with the target now. Did it continue or
5564 not? Not is more likely, so report a stop. */
5565 warning (_("Remote failure reply: %s"), buf);
5566 status->kind = TARGET_WAITKIND_STOPPED;
5567 status->value.sig = TARGET_SIGNAL_0;
5568 break;
5569 case 'F': /* File-I/O request. */
3a29589a
DJ
5570 remote_fileio_request (buf, rs->ctrlc_pending_p);
5571 rs->ctrlc_pending_p = 0;
74531fed
PA
5572 break;
5573 case 'T': case 'S': case 'X': case 'W':
5574 {
5575 struct stop_reply *stop_reply;
5576 struct cleanup *old_chain;
5577
5578 stop_reply = stop_reply_xmalloc ();
5579 old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
5580 remote_parse_stop_reply (buf, stop_reply);
5581 discard_cleanups (old_chain);
5582 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
5583 break;
5584 }
5585 case 'O': /* Console output. */
5586 remote_console_output (buf + 1);
e24a49d8 5587
c8e38a49
PA
5588 /* The target didn't really stop; keep waiting. */
5589 rs->waiting_for_stop_reply = 1;
e24a49d8 5590
c8e38a49
PA
5591 break;
5592 case '\0':
5593 if (last_sent_signal != TARGET_SIGNAL_0)
5594 {
5595 /* Zero length reply means that we tried 'S' or 'C' and the
5596 remote system doesn't support it. */
5597 target_terminal_ours_for_output ();
5598 printf_filtered
5599 ("Can't send signals to this remote system. %s not sent.\n",
5600 target_signal_to_name (last_sent_signal));
5601 last_sent_signal = TARGET_SIGNAL_0;
5602 target_terminal_inferior ();
5603
5604 strcpy ((char *) buf, last_sent_step ? "s" : "c");
5605 putpkt ((char *) buf);
5606
5607 /* We just told the target to resume, so a stop reply is in
5608 order. */
e24a49d8 5609 rs->waiting_for_stop_reply = 1;
c8e38a49 5610 break;
43ff13b4 5611 }
c8e38a49
PA
5612 /* else fallthrough */
5613 default:
5614 warning (_("Invalid remote reply: %s"), buf);
5615 /* Keep waiting. */
5616 rs->waiting_for_stop_reply = 1;
5617 break;
43ff13b4 5618 }
c8e38a49 5619
c8e38a49 5620 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
5621 {
5622 /* Nothing interesting happened. If we're doing a non-blocking
5623 poll, we're done. Otherwise, go back to waiting. */
5624 if (options & TARGET_WNOHANG)
5625 return minus_one_ptid;
5626 else
5627 goto again;
5628 }
74531fed
PA
5629 else if (status->kind != TARGET_WAITKIND_EXITED
5630 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
5631 {
5632 if (!ptid_equal (event_ptid, null_ptid))
5633 record_currthread (event_ptid);
5634 else
5635 event_ptid = inferior_ptid;
43ff13b4 5636 }
74531fed
PA
5637 else
5638 /* A process exit. Invalidate our notion of current thread. */
5639 record_currthread (minus_one_ptid);
79d7f229 5640
82f73884 5641 return event_ptid;
43ff13b4
JM
5642}
5643
74531fed
PA
5644/* Wait until the remote machine stops, then return, storing status in
5645 STATUS just as `wait' would. */
5646
c8e38a49 5647static ptid_t
117de6a9 5648remote_wait (struct target_ops *ops,
47608cb1 5649 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
5650{
5651 ptid_t event_ptid;
5652
74531fed 5653 if (non_stop)
47608cb1 5654 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 5655 else
47608cb1 5656 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 5657
74531fed 5658 if (target_can_async_p ())
c8e38a49 5659 {
74531fed
PA
5660 /* If there are are events left in the queue tell the event loop
5661 to return here. */
5662 if (stop_reply_queue)
5663 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 5664 }
c8e38a49
PA
5665
5666 return event_ptid;
5667}
5668
74ca34ce 5669/* Fetch a single register using a 'p' packet. */
c906108c 5670
b96ec7ac 5671static int
56be3814 5672fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
5673{
5674 struct remote_state *rs = get_remote_state ();
2e9f7625 5675 char *buf, *p;
b96ec7ac
AC
5676 char regp[MAX_REGISTER_SIZE];
5677 int i;
5678
74ca34ce
DJ
5679 if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
5680 return 0;
5681
5682 if (reg->pnum == -1)
5683 return 0;
5684
2e9f7625 5685 p = rs->buf;
fcad0fa4 5686 *p++ = 'p';
74ca34ce 5687 p += hexnumstr (p, reg->pnum);
fcad0fa4 5688 *p++ = '\0';
1f4437a4
MS
5689 putpkt (rs->buf);
5690 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 5691
2e9f7625
DJ
5692 buf = rs->buf;
5693
74ca34ce
DJ
5694 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
5695 {
5696 case PACKET_OK:
5697 break;
5698 case PACKET_UNKNOWN:
5699 return 0;
5700 case PACKET_ERROR:
27a9c0bf
MS
5701 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
5702 gdbarch_register_name (get_regcache_arch (regcache),
5703 reg->regnum),
5704 buf);
74ca34ce 5705 }
3f9a994c
JB
5706
5707 /* If this register is unfetchable, tell the regcache. */
5708 if (buf[0] == 'x')
8480adf2 5709 {
56be3814 5710 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 5711 return 1;
b96ec7ac 5712 }
b96ec7ac 5713
3f9a994c
JB
5714 /* Otherwise, parse and supply the value. */
5715 p = buf;
5716 i = 0;
5717 while (p[0] != 0)
5718 {
5719 if (p[1] == 0)
74ca34ce 5720 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
5721
5722 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
5723 p += 2;
5724 }
56be3814 5725 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 5726 return 1;
b96ec7ac
AC
5727}
5728
74ca34ce
DJ
5729/* Fetch the registers included in the target's 'g' packet. */
5730
29709017
DJ
5731static int
5732send_g_packet (void)
c906108c 5733{
d01949b6 5734 struct remote_state *rs = get_remote_state ();
cea39f65 5735 int buf_len;
c906108c 5736
74ca34ce
DJ
5737 sprintf (rs->buf, "g");
5738 remote_send (&rs->buf, &rs->buf_size);
c906108c 5739
29709017
DJ
5740 /* We can get out of synch in various cases. If the first character
5741 in the buffer is not a hex character, assume that has happened
5742 and try to fetch another packet to read. */
5743 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
5744 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
5745 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
5746 && rs->buf[0] != 'x') /* New: unavailable register value. */
5747 {
5748 if (remote_debug)
5749 fprintf_unfiltered (gdb_stdlog,
5750 "Bad register packet; fetching a new packet\n");
5751 getpkt (&rs->buf, &rs->buf_size, 0);
5752 }
5753
74ca34ce
DJ
5754 buf_len = strlen (rs->buf);
5755
5756 /* Sanity check the received packet. */
5757 if (buf_len % 2 != 0)
5758 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
5759
5760 return buf_len / 2;
5761}
5762
5763static void
56be3814 5764process_g_packet (struct regcache *regcache)
29709017 5765{
4a22f64d 5766 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
5767 struct remote_state *rs = get_remote_state ();
5768 struct remote_arch_state *rsa = get_remote_arch_state ();
5769 int i, buf_len;
5770 char *p;
5771 char *regs;
5772
5773 buf_len = strlen (rs->buf);
5774
5775 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
5776 if (buf_len > 2 * rsa->sizeof_g_packet)
5777 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
5778
5779 /* Save the size of the packet sent to us by the target. It is used
5780 as a heuristic when determining the max size of packets that the
5781 target can safely receive. */
5782 if (rsa->actual_register_packet_size == 0)
5783 rsa->actual_register_packet_size = buf_len;
5784
5785 /* If this is smaller than we guessed the 'g' packet would be,
5786 update our records. A 'g' reply that doesn't include a register's
5787 value implies either that the register is not available, or that
5788 the 'p' packet must be used. */
5789 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 5790 {
74ca34ce
DJ
5791 rsa->sizeof_g_packet = buf_len / 2;
5792
4a22f64d 5793 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 5794 {
74ca34ce
DJ
5795 if (rsa->regs[i].pnum == -1)
5796 continue;
5797
5798 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
5799 rsa->regs[i].in_g_packet = 0;
b96ec7ac 5800 else
74ca34ce 5801 rsa->regs[i].in_g_packet = 1;
b96ec7ac 5802 }
74ca34ce 5803 }
b323314b 5804
74ca34ce 5805 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
5806
5807 /* Unimplemented registers read as all bits zero. */
ea9c271d 5808 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 5809
c906108c
SS
5810 /* Reply describes registers byte by byte, each byte encoded as two
5811 hex characters. Suck them all up, then supply them to the
5812 register cacheing/storage mechanism. */
5813
74ca34ce 5814 p = rs->buf;
ea9c271d 5815 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 5816 {
74ca34ce
DJ
5817 if (p[0] == 0 || p[1] == 0)
5818 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
5819 internal_error (__FILE__, __LINE__,
9b20d036 5820 _("unexpected end of 'g' packet reply"));
74ca34ce 5821
c906108c 5822 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 5823 regs[i] = 0; /* 'x' */
c906108c
SS
5824 else
5825 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
5826 p += 2;
5827 }
5828
a744cf53
MS
5829 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5830 {
5831 struct packet_reg *r = &rsa->regs[i];
5832
5833 if (r->in_g_packet)
5834 {
5835 if (r->offset * 2 >= strlen (rs->buf))
5836 /* This shouldn't happen - we adjusted in_g_packet above. */
5837 internal_error (__FILE__, __LINE__,
9b20d036 5838 _("unexpected end of 'g' packet reply"));
a744cf53
MS
5839 else if (rs->buf[r->offset * 2] == 'x')
5840 {
5841 gdb_assert (r->offset * 2 < strlen (rs->buf));
5842 /* The register isn't available, mark it as such (at
5843 the same time setting the value to zero). */
5844 regcache_raw_supply (regcache, r->regnum, NULL);
5845 }
5846 else
5847 regcache_raw_supply (regcache, r->regnum,
5848 regs + r->offset);
5849 }
5850 }
c906108c
SS
5851}
5852
29709017 5853static void
56be3814 5854fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
5855{
5856 send_g_packet ();
56be3814 5857 process_g_packet (regcache);
29709017
DJ
5858}
5859
e6e4e701
PA
5860/* Make the remote selected traceframe match GDB's selected
5861 traceframe. */
5862
5863static void
5864set_remote_traceframe (void)
5865{
5866 int newnum;
5867
5868 if (remote_traceframe_number == get_traceframe_number ())
5869 return;
5870
5871 /* Avoid recursion, remote_trace_find calls us again. */
5872 remote_traceframe_number = get_traceframe_number ();
5873
5874 newnum = target_trace_find (tfind_number,
5875 get_traceframe_number (), 0, 0, NULL);
5876
5877 /* Should not happen. If it does, all bets are off. */
5878 if (newnum != get_traceframe_number ())
5879 warning (_("could not set remote traceframe"));
5880}
5881
74ca34ce 5882static void
28439f5e
PA
5883remote_fetch_registers (struct target_ops *ops,
5884 struct regcache *regcache, int regnum)
74ca34ce 5885{
74ca34ce
DJ
5886 struct remote_arch_state *rsa = get_remote_arch_state ();
5887 int i;
5888
e6e4e701 5889 set_remote_traceframe ();
79d7f229 5890 set_general_thread (inferior_ptid);
74ca34ce
DJ
5891
5892 if (regnum >= 0)
5893 {
5894 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 5895
74ca34ce
DJ
5896 gdb_assert (reg != NULL);
5897
5898 /* If this register might be in the 'g' packet, try that first -
5899 we are likely to read more than one register. If this is the
5900 first 'g' packet, we might be overly optimistic about its
5901 contents, so fall back to 'p'. */
5902 if (reg->in_g_packet)
5903 {
56be3814 5904 fetch_registers_using_g (regcache);
74ca34ce
DJ
5905 if (reg->in_g_packet)
5906 return;
5907 }
5908
56be3814 5909 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
5910 return;
5911
5912 /* This register is not available. */
56be3814 5913 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
5914
5915 return;
5916 }
5917
56be3814 5918 fetch_registers_using_g (regcache);
74ca34ce 5919
4a22f64d 5920 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 5921 if (!rsa->regs[i].in_g_packet)
56be3814 5922 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
5923 {
5924 /* This register is not available. */
56be3814 5925 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
5926 }
5927}
5928
c906108c
SS
5929/* Prepare to store registers. Since we may send them all (using a
5930 'G' request), we have to read out the ones we don't want to change
5931 first. */
5932
c5aa993b 5933static void
316f2060 5934remote_prepare_to_store (struct regcache *regcache)
c906108c 5935{
ea9c271d 5936 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 5937 int i;
cfd77fa1 5938 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 5939
c906108c 5940 /* Make sure the entire registers array is valid. */
444abaca 5941 switch (remote_protocol_packets[PACKET_P].support)
5a2468f5
JM
5942 {
5943 case PACKET_DISABLE:
5944 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 5945 /* Make sure all the necessary registers are cached. */
4a22f64d 5946 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 5947 if (rsa->regs[i].in_g_packet)
316f2060 5948 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
5949 break;
5950 case PACKET_ENABLE:
5951 break;
5952 }
5953}
5954
ad10f812 5955/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 5956 packet was not recognized. */
5a2468f5
JM
5957
5958static int
1f4437a4
MS
5959store_register_using_P (const struct regcache *regcache,
5960 struct packet_reg *reg)
5a2468f5 5961{
4a22f64d 5962 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 5963 struct remote_state *rs = get_remote_state ();
5a2468f5 5964 /* Try storing a single register. */
6d820c5c 5965 char *buf = rs->buf;
cfd77fa1 5966 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 5967 char *p;
5a2468f5 5968
74ca34ce
DJ
5969 if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
5970 return 0;
5971
5972 if (reg->pnum == -1)
5973 return 0;
5974
ea9c271d 5975 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 5976 p = buf + strlen (buf);
56be3814 5977 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 5978 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
5979 putpkt (rs->buf);
5980 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 5981
74ca34ce
DJ
5982 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
5983 {
5984 case PACKET_OK:
5985 return 1;
5986 case PACKET_ERROR:
27a9c0bf
MS
5987 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
5988 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
5989 case PACKET_UNKNOWN:
5990 return 0;
5991 default:
5992 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
5993 }
c906108c
SS
5994}
5995
23860348
MS
5996/* Store register REGNUM, or all registers if REGNUM == -1, from the
5997 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
5998
5999static void
56be3814 6000store_registers_using_G (const struct regcache *regcache)
c906108c 6001{
d01949b6 6002 struct remote_state *rs = get_remote_state ();
ea9c271d 6003 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6004 gdb_byte *regs;
c906108c
SS
6005 char *p;
6006
193cb69f
AC
6007 /* Extract all the registers in the regcache copying them into a
6008 local buffer. */
6009 {
b323314b 6010 int i;
a744cf53 6011
ea9c271d
DJ
6012 regs = alloca (rsa->sizeof_g_packet);
6013 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6014 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6015 {
ea9c271d 6016 struct packet_reg *r = &rsa->regs[i];
a744cf53 6017
b323314b 6018 if (r->in_g_packet)
56be3814 6019 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6020 }
6021 }
c906108c
SS
6022
6023 /* Command describes registers byte by byte,
6024 each byte encoded as two hex characters. */
6d820c5c 6025 p = rs->buf;
193cb69f 6026 *p++ = 'G';
74ca34ce
DJ
6027 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6028 updated. */
6029 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6030 putpkt (rs->buf);
6031 getpkt (&rs->buf, &rs->buf_size, 0);
6032 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6033 error (_("Could not write registers; remote failure reply '%s'"),
6034 rs->buf);
c906108c 6035}
74ca34ce
DJ
6036
6037/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6038 of the register cache buffer. FIXME: ignores errors. */
6039
6040static void
28439f5e
PA
6041remote_store_registers (struct target_ops *ops,
6042 struct regcache *regcache, int regnum)
74ca34ce 6043{
74ca34ce
DJ
6044 struct remote_arch_state *rsa = get_remote_arch_state ();
6045 int i;
6046
e6e4e701 6047 set_remote_traceframe ();
79d7f229 6048 set_general_thread (inferior_ptid);
74ca34ce
DJ
6049
6050 if (regnum >= 0)
6051 {
6052 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6053
74ca34ce
DJ
6054 gdb_assert (reg != NULL);
6055
6056 /* Always prefer to store registers using the 'P' packet if
6057 possible; we often change only a small number of registers.
6058 Sometimes we change a larger number; we'd need help from a
6059 higher layer to know to use 'G'. */
56be3814 6060 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6061 return;
6062
6063 /* For now, don't complain if we have no way to write the
6064 register. GDB loses track of unavailable registers too
6065 easily. Some day, this may be an error. We don't have
0df8b418 6066 any way to read the register, either... */
74ca34ce
DJ
6067 if (!reg->in_g_packet)
6068 return;
6069
56be3814 6070 store_registers_using_G (regcache);
74ca34ce
DJ
6071 return;
6072 }
6073
56be3814 6074 store_registers_using_G (regcache);
74ca34ce 6075
4a22f64d 6076 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6077 if (!rsa->regs[i].in_g_packet)
56be3814 6078 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6079 /* See above for why we do not issue an error here. */
6080 continue;
6081}
c906108c
SS
6082\f
6083
6084/* Return the number of hex digits in num. */
6085
6086static int
fba45db2 6087hexnumlen (ULONGEST num)
c906108c
SS
6088{
6089 int i;
6090
6091 for (i = 0; num != 0; i++)
6092 num >>= 4;
6093
6094 return max (i, 1);
6095}
6096
2df3850c 6097/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
6098
6099static int
fba45db2 6100hexnumstr (char *buf, ULONGEST num)
c906108c 6101{
c906108c 6102 int len = hexnumlen (num);
a744cf53 6103
2df3850c
JM
6104 return hexnumnstr (buf, num, len);
6105}
6106
c906108c 6107
2df3850c 6108/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 6109
2df3850c 6110static int
fba45db2 6111hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
6112{
6113 int i;
6114
6115 buf[width] = '\0';
6116
6117 for (i = width - 1; i >= 0; i--)
c906108c 6118 {
c5aa993b 6119 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
6120 num >>= 4;
6121 }
6122
2df3850c 6123 return width;
c906108c
SS
6124}
6125
23860348 6126/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
6127
6128static CORE_ADDR
fba45db2 6129remote_address_masked (CORE_ADDR addr)
c906108c 6130{
911c95a5 6131 int address_size = remote_address_size;
a744cf53 6132
911c95a5
UW
6133 /* If "remoteaddresssize" was not set, default to target address size. */
6134 if (!address_size)
1cf3db46 6135 address_size = gdbarch_addr_bit (target_gdbarch);
911c95a5
UW
6136
6137 if (address_size > 0
6138 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
6139 {
6140 /* Only create a mask when that mask can safely be constructed
23860348 6141 in a ULONGEST variable. */
c906108c 6142 ULONGEST mask = 1;
a744cf53 6143
911c95a5 6144 mask = (mask << address_size) - 1;
c906108c
SS
6145 addr &= mask;
6146 }
6147 return addr;
6148}
6149
a31ea83d
DJ
6150/* Convert BUFFER, binary data at least LEN bytes long, into escaped
6151 binary data in OUT_BUF. Set *OUT_LEN to the length of the data
6152 encoded in OUT_BUF, and return the number of bytes in OUT_BUF
6153 (which may be more than *OUT_LEN due to escape characters). The
6154 total number of bytes in the output buffer will be at most
6155 OUT_MAXLEN. */
6156
6157static int
6158remote_escape_output (const gdb_byte *buffer, int len,
6159 gdb_byte *out_buf, int *out_len,
6160 int out_maxlen)
6161{
6162 int input_index, output_index;
6163
6164 output_index = 0;
6165 for (input_index = 0; input_index < len; input_index++)
6166 {
6167 gdb_byte b = buffer[input_index];
6168
6169 if (b == '$' || b == '#' || b == '}')
6170 {
6171 /* These must be escaped. */
6172 if (output_index + 2 > out_maxlen)
6173 break;
6174 out_buf[output_index++] = '}';
6175 out_buf[output_index++] = b ^ 0x20;
6176 }
6177 else
6178 {
6179 if (output_index + 1 > out_maxlen)
6180 break;
6181 out_buf[output_index++] = b;
6182 }
6183 }
6184
6185 *out_len = input_index;
6186 return output_index;
6187}
6188
0876f84a
DJ
6189/* Convert BUFFER, escaped data LEN bytes long, into binary data
6190 in OUT_BUF. Return the number of bytes written to OUT_BUF.
6191 Raise an error if the total number of bytes exceeds OUT_MAXLEN.
6192
6193 This function reverses remote_escape_output. It allows more
6194 escaped characters than that function does, in particular because
6195 '*' must be escaped to avoid the run-length encoding processing
6196 in reading packets. */
6197
6198static int
6199remote_unescape_input (const gdb_byte *buffer, int len,
6200 gdb_byte *out_buf, int out_maxlen)
6201{
6202 int input_index, output_index;
6203 int escaped;
6204
6205 output_index = 0;
6206 escaped = 0;
6207 for (input_index = 0; input_index < len; input_index++)
6208 {
6209 gdb_byte b = buffer[input_index];
6210
6211 if (output_index + 1 > out_maxlen)
6212 {
6213 warning (_("Received too much data from remote target;"
6214 " ignoring overflow."));
6215 return output_index;
6216 }
6217
6218 if (escaped)
6219 {
6220 out_buf[output_index++] = b ^ 0x20;
6221 escaped = 0;
6222 }
6223 else if (b == '}')
6224 escaped = 1;
6225 else
6226 out_buf[output_index++] = b;
6227 }
6228
6229 if (escaped)
6230 error (_("Unmatched escape character in target response."));
6231
6232 return output_index;
6233}
6234
c906108c
SS
6235/* Determine whether the remote target supports binary downloading.
6236 This is accomplished by sending a no-op memory write of zero length
6237 to the target at the specified address. It does not suffice to send
23860348
MS
6238 the whole packet, since many stubs strip the eighth bit and
6239 subsequently compute a wrong checksum, which causes real havoc with
6240 remote_write_bytes.
7a292a7a 6241
96baa820 6242 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 6243 clean. In cases like this, the user should clear "remote
23860348 6244 X-packet". */
96baa820 6245
c906108c 6246static void
fba45db2 6247check_binary_download (CORE_ADDR addr)
c906108c 6248{
d01949b6 6249 struct remote_state *rs = get_remote_state ();
24b06219 6250
444abaca 6251 switch (remote_protocol_packets[PACKET_X].support)
c906108c 6252 {
96baa820
JM
6253 case PACKET_DISABLE:
6254 break;
6255 case PACKET_ENABLE:
6256 break;
6257 case PACKET_SUPPORT_UNKNOWN:
6258 {
96baa820 6259 char *p;
802188a7 6260
2e9f7625 6261 p = rs->buf;
96baa820
JM
6262 *p++ = 'X';
6263 p += hexnumstr (p, (ULONGEST) addr);
6264 *p++ = ',';
6265 p += hexnumstr (p, (ULONGEST) 0);
6266 *p++ = ':';
6267 *p = '\0';
802188a7 6268
2e9f7625 6269 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6270 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 6271
2e9f7625 6272 if (rs->buf[0] == '\0')
96baa820
JM
6273 {
6274 if (remote_debug)
6275 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
6276 "binary downloading NOT "
6277 "supported by target\n");
444abaca 6278 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
6279 }
6280 else
6281 {
6282 if (remote_debug)
6283 fprintf_unfiltered (gdb_stdlog,
64b9b334 6284 "binary downloading supported by target\n");
444abaca 6285 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
6286 }
6287 break;
6288 }
c906108c
SS
6289 }
6290}
6291
6292/* Write memory data directly to the remote machine.
6293 This does not inform the data cache; the data cache uses this.
a76d924d 6294 HEADER is the starting part of the packet.
c906108c
SS
6295 MEMADDR is the address in the remote memory space.
6296 MYADDR is the address of the buffer in our space.
6297 LEN is the number of bytes.
a76d924d
DJ
6298 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6299 should send data as binary ('X'), or hex-encoded ('M').
6300
6301 The function creates packet of the form
6302 <HEADER><ADDRESS>,<LENGTH>:<DATA>
6303
6304 where encoding of <DATA> is termined by PACKET_FORMAT.
6305
6306 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6307 are omitted.
6308
6309 Returns the number of bytes transferred, or 0 (setting errno) for
23860348 6310 error. Only transfer a single packet. */
c906108c 6311
a76d924d
DJ
6312static int
6313remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6314 const gdb_byte *myaddr, int len,
6315 char packet_format, int use_length)
c906108c 6316{
6d820c5c 6317 struct remote_state *rs = get_remote_state ();
cfd77fa1 6318 char *p;
a76d924d
DJ
6319 char *plen = NULL;
6320 int plenlen = 0;
917317f4
JM
6321 int todo;
6322 int nr_bytes;
a257b5bb 6323 int payload_size;
6765f3e5 6324 int payload_length;
a76d924d
DJ
6325 int header_length;
6326
6327 if (packet_format != 'X' && packet_format != 'M')
6328 internal_error (__FILE__, __LINE__,
9b20d036 6329 _("remote_write_bytes_aux: bad packet format"));
c906108c 6330
b2182ed2
DJ
6331 if (len <= 0)
6332 return 0;
6333
3de11b2e 6334 payload_size = get_memory_write_packet_size ();
2bc416ba 6335
6d820c5c
DJ
6336 /* The packet buffer will be large enough for the payload;
6337 get_memory_packet_size ensures this. */
a76d924d 6338 rs->buf[0] = '\0';
c906108c 6339
a257b5bb 6340 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
6341 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
6342
a76d924d
DJ
6343 payload_size -= strlen ("$,:#NN");
6344 if (!use_length)
0df8b418 6345 /* The comma won't be used. */
a76d924d
DJ
6346 payload_size += 1;
6347 header_length = strlen (header);
6348 payload_size -= header_length;
3de11b2e 6349 payload_size -= hexnumlen (memaddr);
c906108c 6350
a76d924d 6351 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 6352
a76d924d
DJ
6353 strcat (rs->buf, header);
6354 p = rs->buf + strlen (header);
6355
6356 /* Compute a best guess of the number of bytes actually transfered. */
6357 if (packet_format == 'X')
c906108c 6358 {
23860348 6359 /* Best guess at number of bytes that will fit. */
a257b5bb 6360 todo = min (len, payload_size);
a76d924d
DJ
6361 if (use_length)
6362 payload_size -= hexnumlen (todo);
3de11b2e 6363 todo = min (todo, payload_size);
a76d924d
DJ
6364 }
6365 else
6366 {
23860348 6367 /* Num bytes that will fit. */
a257b5bb 6368 todo = min (len, payload_size / 2);
a76d924d
DJ
6369 if (use_length)
6370 payload_size -= hexnumlen (todo);
3de11b2e 6371 todo = min (todo, payload_size / 2);
917317f4 6372 }
a76d924d 6373
3de11b2e
NS
6374 if (todo <= 0)
6375 internal_error (__FILE__, __LINE__,
405f8e94 6376 _("minimum packet size too small to write data"));
802188a7 6377
6765f3e5
DJ
6378 /* If we already need another packet, then try to align the end
6379 of this packet to a useful boundary. */
6380 if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
6381 todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
6382
a257b5bb 6383 /* Append "<memaddr>". */
917317f4
JM
6384 memaddr = remote_address_masked (memaddr);
6385 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 6386
a76d924d
DJ
6387 if (use_length)
6388 {
6389 /* Append ",". */
6390 *p++ = ',';
802188a7 6391
a76d924d
DJ
6392 /* Append <len>. Retain the location/size of <len>. It may need to
6393 be adjusted once the packet body has been created. */
6394 plen = p;
6395 plenlen = hexnumstr (p, (ULONGEST) todo);
6396 p += plenlen;
6397 }
a257b5bb
AC
6398
6399 /* Append ":". */
917317f4
JM
6400 *p++ = ':';
6401 *p = '\0';
802188a7 6402
a257b5bb 6403 /* Append the packet body. */
a76d924d 6404 if (packet_format == 'X')
917317f4 6405 {
917317f4
JM
6406 /* Binary mode. Send target system values byte by byte, in
6407 increasing byte addresses. Only escape certain critical
6408 characters. */
6765f3e5
DJ
6409 payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
6410 payload_size);
6411
6412 /* If not all TODO bytes fit, then we'll need another packet. Make
9b7194bc
DJ
6413 a second try to keep the end of the packet aligned. Don't do
6414 this if the packet is tiny. */
6415 if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
6765f3e5
DJ
6416 {
6417 int new_nr_bytes;
6418
6419 new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
6420 - memaddr);
6421 if (new_nr_bytes != nr_bytes)
6422 payload_length = remote_escape_output (myaddr, new_nr_bytes,
6423 p, &nr_bytes,
6424 payload_size);
6425 }
6426
6427 p += payload_length;
a76d924d 6428 if (use_length && nr_bytes < todo)
c906108c 6429 {
802188a7 6430 /* Escape chars have filled up the buffer prematurely,
917317f4
JM
6431 and we have actually sent fewer bytes than planned.
6432 Fix-up the length field of the packet. Use the same
6433 number of characters as before. */
917317f4
JM
6434 plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
6435 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 6436 }
a76d924d
DJ
6437 }
6438 else
6439 {
917317f4
JM
6440 /* Normal mode: Send target system values byte by byte, in
6441 increasing byte addresses. Each byte is encoded as a two hex
6442 value. */
2644f393 6443 nr_bytes = bin2hex (myaddr, p, todo);
aa6c0017 6444 p += 2 * nr_bytes;
c906108c 6445 }
802188a7 6446
2e9f7625 6447 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 6448 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 6449
2e9f7625 6450 if (rs->buf[0] == 'E')
917317f4
JM
6451 {
6452 /* There is no correspondance between what the remote protocol
6453 uses for errors and errno codes. We would like a cleaner way
6454 of representing errors (big enough to include errno codes,
6455 bfd_error codes, and others). But for now just return EIO. */
6456 errno = EIO;
6457 return 0;
6458 }
802188a7 6459
23860348
MS
6460 /* Return NR_BYTES, not TODO, in case escape chars caused us to send
6461 fewer bytes than we'd planned. */
917317f4 6462 return nr_bytes;
c906108c
SS
6463}
6464
a76d924d
DJ
6465/* Write memory data directly to the remote machine.
6466 This does not inform the data cache; the data cache uses this.
6467 MEMADDR is the address in the remote memory space.
6468 MYADDR is the address of the buffer in our space.
6469 LEN is the number of bytes.
6470
6471 Returns number of bytes transferred, or 0 (setting errno) for
6472 error. Only transfer a single packet. */
6473
f7605bc2 6474static int
a76d924d
DJ
6475remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
6476{
6477 char *packet_format = 0;
6478
6479 /* Check whether the target supports binary download. */
6480 check_binary_download (memaddr);
6481
6482 switch (remote_protocol_packets[PACKET_X].support)
6483 {
6484 case PACKET_ENABLE:
6485 packet_format = "X";
6486 break;
6487 case PACKET_DISABLE:
6488 packet_format = "M";
6489 break;
6490 case PACKET_SUPPORT_UNKNOWN:
6491 internal_error (__FILE__, __LINE__,
6492 _("remote_write_bytes: bad internal state"));
6493 default:
6494 internal_error (__FILE__, __LINE__, _("bad switch"));
6495 }
6496
6497 return remote_write_bytes_aux (packet_format,
6498 memaddr, myaddr, len, packet_format[0], 1);
6499}
6500
c906108c
SS
6501/* Read memory data directly from the remote machine.
6502 This does not use the data cache; the data cache uses this.
6503 MEMADDR is the address in the remote memory space.
6504 MYADDR is the address of the buffer in our space.
6505 LEN is the number of bytes.
6506
6507 Returns number of bytes transferred, or 0 for error. */
6508
f7605bc2 6509static int
cfd77fa1 6510remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
c906108c 6511{
6d820c5c 6512 struct remote_state *rs = get_remote_state ();
23860348 6513 int max_buf_size; /* Max size of packet output buffer. */
f7605bc2
PA
6514 char *p;
6515 int todo;
6516 int i;
c906108c 6517
b2182ed2
DJ
6518 if (len <= 0)
6519 return 0;
6520
11cf8741 6521 max_buf_size = get_memory_read_packet_size ();
6d820c5c
DJ
6522 /* The packet buffer will be large enough for the payload;
6523 get_memory_packet_size ensures this. */
c906108c 6524
f7605bc2
PA
6525 /* Number if bytes that will fit. */
6526 todo = min (len, max_buf_size / 2);
c906108c 6527
f7605bc2
PA
6528 /* Construct "m"<memaddr>","<len>". */
6529 memaddr = remote_address_masked (memaddr);
6530 p = rs->buf;
6531 *p++ = 'm';
6532 p += hexnumstr (p, (ULONGEST) memaddr);
6533 *p++ = ',';
6534 p += hexnumstr (p, (ULONGEST) todo);
6535 *p = '\0';
6536 putpkt (rs->buf);
6537 getpkt (&rs->buf, &rs->buf_size, 0);
6538 if (rs->buf[0] == 'E'
6539 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
6540 && rs->buf[3] == '\0')
6541 {
6542 /* There is no correspondance between what the remote protocol
6543 uses for errors and errno codes. We would like a cleaner way
6544 of representing errors (big enough to include errno codes,
6545 bfd_error codes, and others). But for now just return
6546 EIO. */
6547 errno = EIO;
6548 return 0;
c906108c 6549 }
f7605bc2
PA
6550 /* Reply describes memory byte by byte, each byte encoded as two hex
6551 characters. */
6552 p = rs->buf;
6553 i = hex2bin (p, myaddr, todo);
6554 /* Return what we have. Let higher layers handle partial reads. */
6555 return i;
c906108c 6556}
74531fed
PA
6557\f
6558
6559/* Remote notification handler. */
6560
6561static void
6562handle_notification (char *buf, size_t length)
6563{
6564 if (strncmp (buf, "Stop:", 5) == 0)
6565 {
6566 if (pending_stop_reply)
0723dbf5
PA
6567 {
6568 /* We've already parsed the in-flight stop-reply, but the
6569 stub for some reason thought we didn't, possibly due to
6570 timeout on its side. Just ignore it. */
6571 if (remote_debug)
6572 fprintf_unfiltered (gdb_stdlog, "ignoring resent notification\n");
6573 }
74531fed
PA
6574 else
6575 {
6576 struct cleanup *old_chain;
6577 struct stop_reply *reply = stop_reply_xmalloc ();
a744cf53 6578
74531fed
PA
6579 old_chain = make_cleanup (do_stop_reply_xfree, reply);
6580
6581 remote_parse_stop_reply (buf + 5, reply);
6582
6583 discard_cleanups (old_chain);
6584
6585 /* Be careful to only set it after parsing, since an error
6586 may be thrown then. */
6587 pending_stop_reply = reply;
6588
6589 /* Notify the event loop there's a stop reply to acknowledge
6590 and that there may be more events to fetch. */
6591 mark_async_event_handler (remote_async_get_pending_events_token);
0723dbf5
PA
6592
6593 if (remote_debug)
6594 fprintf_unfiltered (gdb_stdlog, "stop notification captured\n");
74531fed
PA
6595 }
6596 }
6597 else
6598 /* We ignore notifications we don't recognize, for compatibility
6599 with newer stubs. */
6600 ;
6601}
6602
c906108c
SS
6603\f
6604/* Read or write LEN bytes from inferior memory at MEMADDR,
23860348
MS
6605 transferring to or from debugger address BUFFER. Write to inferior
6606 if SHOULD_WRITE is nonzero. Returns length of data written or
6607 read; 0 for error. TARGET is unused. */
392a587b 6608
c906108c 6609static int
961cb7b5 6610remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
0a65a603 6611 int should_write, struct mem_attrib *attrib,
29e57380 6612 struct target_ops *target)
c906108c 6613{
4930751a
C
6614 int res;
6615
e6e4e701 6616 set_remote_traceframe ();
82f73884
PA
6617 set_general_thread (inferior_ptid);
6618
4930751a 6619 if (should_write)
b2182ed2 6620 res = remote_write_bytes (mem_addr, buffer, mem_len);
4930751a 6621 else
b2182ed2 6622 res = remote_read_bytes (mem_addr, buffer, mem_len);
4930751a
C
6623
6624 return res;
c906108c
SS
6625}
6626
a76d924d
DJ
6627/* Sends a packet with content determined by the printf format string
6628 FORMAT and the remaining arguments, then gets the reply. Returns
6629 whether the packet was a success, a failure, or unknown. */
6630
2c0b251b 6631static enum packet_result
a76d924d
DJ
6632remote_send_printf (const char *format, ...)
6633{
6634 struct remote_state *rs = get_remote_state ();
6635 int max_size = get_remote_packet_size ();
a76d924d 6636 va_list ap;
a744cf53 6637
a76d924d
DJ
6638 va_start (ap, format);
6639
6640 rs->buf[0] = '\0';
6641 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 6642 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
6643
6644 if (putpkt (rs->buf) < 0)
6645 error (_("Communication problem with target."));
6646
6647 rs->buf[0] = '\0';
6648 getpkt (&rs->buf, &rs->buf_size, 0);
6649
6650 return packet_check_result (rs->buf);
6651}
6652
6653static void
6654restore_remote_timeout (void *p)
6655{
6656 int value = *(int *)p;
a744cf53 6657
a76d924d
DJ
6658 remote_timeout = value;
6659}
6660
6661/* Flash writing can take quite some time. We'll set
6662 effectively infinite timeout for flash operations.
6663 In future, we'll need to decide on a better approach. */
6664static const int remote_flash_timeout = 1000;
6665
6666static void
6667remote_flash_erase (struct target_ops *ops,
6668 ULONGEST address, LONGEST length)
6669{
5af949e3 6670 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
a76d924d
DJ
6671 int saved_remote_timeout = remote_timeout;
6672 enum packet_result ret;
a76d924d
DJ
6673 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6674 &saved_remote_timeout);
a744cf53 6675
a76d924d
DJ
6676 remote_timeout = remote_flash_timeout;
6677
6678 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 6679 phex (address, addr_size),
a76d924d
DJ
6680 phex (length, 4));
6681 switch (ret)
6682 {
6683 case PACKET_UNKNOWN:
6684 error (_("Remote target does not support flash erase"));
6685 case PACKET_ERROR:
6686 error (_("Error erasing flash with vFlashErase packet"));
6687 default:
6688 break;
6689 }
6690
6691 do_cleanups (back_to);
6692}
6693
6694static LONGEST
6695remote_flash_write (struct target_ops *ops,
6696 ULONGEST address, LONGEST length,
6697 const gdb_byte *data)
6698{
6699 int saved_remote_timeout = remote_timeout;
6700 int ret;
6701 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6702 &saved_remote_timeout);
6703
6704 remote_timeout = remote_flash_timeout;
6705 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
6706 do_cleanups (back_to);
6707
6708 return ret;
6709}
6710
6711static void
6712remote_flash_done (struct target_ops *ops)
6713{
6714 int saved_remote_timeout = remote_timeout;
6715 int ret;
6716 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
6717 &saved_remote_timeout);
6718
6719 remote_timeout = remote_flash_timeout;
6720 ret = remote_send_printf ("vFlashDone");
6721 do_cleanups (back_to);
6722
6723 switch (ret)
6724 {
6725 case PACKET_UNKNOWN:
6726 error (_("Remote target does not support vFlashDone"));
6727 case PACKET_ERROR:
6728 error (_("Error finishing flash operation"));
6729 default:
6730 break;
6731 }
6732}
6733
c906108c 6734static void
fba45db2 6735remote_files_info (struct target_ops *ignore)
c906108c
SS
6736{
6737 puts_filtered ("Debugging a target over a serial line.\n");
6738}
6739\f
6740/* Stuff for dealing with the packets which are part of this protocol.
6741 See comment at top of file for details. */
6742
0876f84a 6743/* Read a single character from the remote end. */
c906108c
SS
6744
6745static int
fba45db2 6746readchar (int timeout)
c906108c
SS
6747{
6748 int ch;
6749
2cd58942 6750 ch = serial_readchar (remote_desc, timeout);
c906108c 6751
2acceee2 6752 if (ch >= 0)
0876f84a 6753 return ch;
2acceee2
JM
6754
6755 switch ((enum serial_rc) ch)
c906108c
SS
6756 {
6757 case SERIAL_EOF:
ce5ce7ed 6758 pop_target ();
8a3fe4f8 6759 error (_("Remote connection closed"));
2acceee2 6760 /* no return */
c906108c 6761 case SERIAL_ERROR:
4ac8c4da 6762 pop_target ();
3e43a32a
MS
6763 perror_with_name (_("Remote communication error. "
6764 "Target disconnected."));
2acceee2 6765 /* no return */
c906108c 6766 case SERIAL_TIMEOUT:
2acceee2 6767 break;
c906108c 6768 }
2acceee2 6769 return ch;
c906108c
SS
6770}
6771
6d820c5c
DJ
6772/* Send the command in *BUF to the remote machine, and read the reply
6773 into *BUF. Report an error if we get an error reply. Resize
6774 *BUF using xrealloc if necessary to hold the result, and update
6775 *SIZEOF_BUF. */
c906108c
SS
6776
6777static void
6d820c5c
DJ
6778remote_send (char **buf,
6779 long *sizeof_buf)
c906108c 6780{
6d820c5c 6781 putpkt (*buf);
c2d11a7d 6782 getpkt (buf, sizeof_buf, 0);
c906108c 6783
6d820c5c
DJ
6784 if ((*buf)[0] == 'E')
6785 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
6786}
6787
6e5abd65
PA
6788/* Return a pointer to an xmalloc'ed string representing an escaped
6789 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
6790 etc. The caller is responsible for releasing the returned
6791 memory. */
6792
6793static char *
6794escape_buffer (const char *buf, int n)
6795{
6796 struct cleanup *old_chain;
6797 struct ui_file *stb;
6798 char *str;
6e5abd65
PA
6799
6800 stb = mem_fileopen ();
6801 old_chain = make_cleanup_ui_file_delete (stb);
6802
6803 fputstrn_unfiltered (buf, n, 0, stb);
759ef836 6804 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
6805 do_cleanups (old_chain);
6806 return str;
6807}
6808
c906108c
SS
6809/* Display a null-terminated packet on stdout, for debugging, using C
6810 string notation. */
6811
6812static void
fba45db2 6813print_packet (char *buf)
c906108c
SS
6814{
6815 puts_filtered ("\"");
43e526b9 6816 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
6817 puts_filtered ("\"");
6818}
6819
6820int
fba45db2 6821putpkt (char *buf)
c906108c
SS
6822{
6823 return putpkt_binary (buf, strlen (buf));
6824}
6825
6826/* Send a packet to the remote machine, with error checking. The data
23860348 6827 of the packet is in BUF. The string in BUF can be at most
ea9c271d 6828 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
6829 and for a possible /0 if we are debugging (remote_debug) and want
6830 to print the sent packet as a string. */
c906108c
SS
6831
6832static int
fba45db2 6833putpkt_binary (char *buf, int cnt)
c906108c 6834{
2d717e4f 6835 struct remote_state *rs = get_remote_state ();
c906108c
SS
6836 int i;
6837 unsigned char csum = 0;
11cf8741 6838 char *buf2 = alloca (cnt + 6);
085dd6e6 6839
c906108c
SS
6840 int ch;
6841 int tcount = 0;
6842 char *p;
6843
e24a49d8
PA
6844 /* Catch cases like trying to read memory or listing threads while
6845 we're waiting for a stop reply. The remote server wouldn't be
6846 ready to handle this request, so we'd hang and timeout. We don't
6847 have to worry about this in synchronous mode, because in that
6848 case it's not possible to issue a command while the target is
74531fed
PA
6849 running. This is not a problem in non-stop mode, because in that
6850 case, the stub is always ready to process serial input. */
6851 if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
e24a49d8
PA
6852 error (_("Cannot execute this command while the target is running."));
6853
2d717e4f
DJ
6854 /* We're sending out a new packet. Make sure we don't look at a
6855 stale cached response. */
6856 rs->cached_wait_status = 0;
6857
c906108c
SS
6858 /* Copy the packet into buffer BUF2, encapsulating it
6859 and giving it a checksum. */
6860
c906108c
SS
6861 p = buf2;
6862 *p++ = '$';
6863
6864 for (i = 0; i < cnt; i++)
6865 {
6866 csum += buf[i];
6867 *p++ = buf[i];
6868 }
6869 *p++ = '#';
6870 *p++ = tohex ((csum >> 4) & 0xf);
6871 *p++ = tohex (csum & 0xf);
6872
6873 /* Send it over and over until we get a positive ack. */
6874
6875 while (1)
6876 {
6877 int started_error_output = 0;
6878
6879 if (remote_debug)
6880 {
6e5abd65
PA
6881 struct cleanup *old_chain;
6882 char *str;
6883
c906108c 6884 *p = '\0';
6e5abd65
PA
6885 str = escape_buffer (buf2, p - buf2);
6886 old_chain = make_cleanup (xfree, str);
6887 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 6888 gdb_flush (gdb_stdlog);
6e5abd65 6889 do_cleanups (old_chain);
c906108c 6890 }
2cd58942 6891 if (serial_write (remote_desc, buf2, p - buf2))
e2e0b3e5 6892 perror_with_name (_("putpkt: write failed"));
c906108c 6893
a6f3e723
SL
6894 /* If this is a no acks version of the remote protocol, send the
6895 packet and move on. */
6896 if (rs->noack_mode)
6897 break;
6898
74531fed
PA
6899 /* Read until either a timeout occurs (-2) or '+' is read.
6900 Handle any notification that arrives in the mean time. */
c906108c
SS
6901 while (1)
6902 {
6903 ch = readchar (remote_timeout);
6904
c5aa993b 6905 if (remote_debug)
c906108c
SS
6906 {
6907 switch (ch)
6908 {
6909 case '+':
1216fa2c 6910 case '-':
c906108c
SS
6911 case SERIAL_TIMEOUT:
6912 case '$':
74531fed 6913 case '%':
c906108c
SS
6914 if (started_error_output)
6915 {
6916 putchar_unfiltered ('\n');
6917 started_error_output = 0;
6918 }
6919 }
6920 }
6921
6922 switch (ch)
6923 {
6924 case '+':
6925 if (remote_debug)
0f71a2f6 6926 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 6927 return 1;
1216fa2c
AC
6928 case '-':
6929 if (remote_debug)
6930 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 6931 /* FALLTHROUGH */
c906108c 6932 case SERIAL_TIMEOUT:
c5aa993b 6933 tcount++;
c906108c
SS
6934 if (tcount > 3)
6935 return 0;
23860348 6936 break; /* Retransmit buffer. */
c906108c
SS
6937 case '$':
6938 {
40e3f985 6939 if (remote_debug)
2bc416ba 6940 fprintf_unfiltered (gdb_stdlog,
23860348 6941 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
6942 /* It's probably an old response sent because an ACK
6943 was lost. Gobble up the packet and ack it so it
6944 doesn't get retransmitted when we resend this
6945 packet. */
6d820c5c 6946 skip_frame ();
d6f7abdf 6947 serial_write (remote_desc, "+", 1);
23860348 6948 continue; /* Now, go look for +. */
c906108c 6949 }
74531fed
PA
6950
6951 case '%':
6952 {
6953 int val;
6954
6955 /* If we got a notification, handle it, and go back to looking
6956 for an ack. */
6957 /* We've found the start of a notification. Now
6958 collect the data. */
6959 val = read_frame (&rs->buf, &rs->buf_size);
6960 if (val >= 0)
6961 {
6962 if (remote_debug)
6963 {
6e5abd65
PA
6964 struct cleanup *old_chain;
6965 char *str;
6966
6967 str = escape_buffer (rs->buf, val);
6968 old_chain = make_cleanup (xfree, str);
6969 fprintf_unfiltered (gdb_stdlog,
6970 " Notification received: %s\n",
6971 str);
6972 do_cleanups (old_chain);
74531fed
PA
6973 }
6974 handle_notification (rs->buf, val);
6975 /* We're in sync now, rewait for the ack. */
6976 tcount = 0;
6977 }
6978 else
6979 {
6980 if (remote_debug)
6981 {
6982 if (!started_error_output)
6983 {
6984 started_error_output = 1;
6985 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6986 }
6987 fputc_unfiltered (ch & 0177, gdb_stdlog);
6988 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
6989 }
6990 }
6991 continue;
6992 }
6993 /* fall-through */
c906108c
SS
6994 default:
6995 if (remote_debug)
6996 {
6997 if (!started_error_output)
6998 {
6999 started_error_output = 1;
0f71a2f6 7000 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7001 }
0f71a2f6 7002 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7003 }
7004 continue;
7005 }
23860348 7006 break; /* Here to retransmit. */
c906108c
SS
7007 }
7008
7009#if 0
7010 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7011 able to get out next time we call QUIT, without anything as
7012 violent as interrupt_query. If we want to provide a way out of
7013 here without getting to the next QUIT, it should be based on
7014 hitting ^C twice as in remote_wait. */
c906108c
SS
7015 if (quit_flag)
7016 {
7017 quit_flag = 0;
7018 interrupt_query ();
7019 }
7020#endif
7021 }
a6f3e723 7022 return 0;
c906108c
SS
7023}
7024
6d820c5c
DJ
7025/* Come here after finding the start of a frame when we expected an
7026 ack. Do our best to discard the rest of this packet. */
7027
7028static void
7029skip_frame (void)
7030{
7031 int c;
7032
7033 while (1)
7034 {
7035 c = readchar (remote_timeout);
7036 switch (c)
7037 {
7038 case SERIAL_TIMEOUT:
7039 /* Nothing we can do. */
7040 return;
7041 case '#':
7042 /* Discard the two bytes of checksum and stop. */
7043 c = readchar (remote_timeout);
7044 if (c >= 0)
7045 c = readchar (remote_timeout);
7046
7047 return;
7048 case '*': /* Run length encoding. */
7049 /* Discard the repeat count. */
7050 c = readchar (remote_timeout);
7051 if (c < 0)
7052 return;
7053 break;
7054 default:
7055 /* A regular character. */
7056 break;
7057 }
7058 }
7059}
7060
c906108c 7061/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
7062 into *BUF, verifying the checksum, length, and handling run-length
7063 compression. NUL terminate the buffer. If there is not enough room,
7064 expand *BUF using xrealloc.
c906108c 7065
c2d11a7d
JM
7066 Returns -1 on error, number of characters in buffer (ignoring the
7067 trailing NULL) on success. (could be extended to return one of the
23860348 7068 SERIAL status indications). */
c2d11a7d
JM
7069
7070static long
6d820c5c
DJ
7071read_frame (char **buf_p,
7072 long *sizeof_buf)
c906108c
SS
7073{
7074 unsigned char csum;
c2d11a7d 7075 long bc;
c906108c 7076 int c;
6d820c5c 7077 char *buf = *buf_p;
a6f3e723 7078 struct remote_state *rs = get_remote_state ();
c906108c
SS
7079
7080 csum = 0;
c2d11a7d 7081 bc = 0;
c906108c
SS
7082
7083 while (1)
7084 {
7085 c = readchar (remote_timeout);
c906108c
SS
7086 switch (c)
7087 {
7088 case SERIAL_TIMEOUT:
7089 if (remote_debug)
0f71a2f6 7090 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 7091 return -1;
c906108c
SS
7092 case '$':
7093 if (remote_debug)
0f71a2f6
JM
7094 fputs_filtered ("Saw new packet start in middle of old one\n",
7095 gdb_stdlog);
23860348 7096 return -1; /* Start a new packet, count retries. */
c906108c
SS
7097 case '#':
7098 {
7099 unsigned char pktcsum;
e1b09194
AC
7100 int check_0 = 0;
7101 int check_1 = 0;
c906108c 7102
c2d11a7d 7103 buf[bc] = '\0';
c906108c 7104
e1b09194
AC
7105 check_0 = readchar (remote_timeout);
7106 if (check_0 >= 0)
7107 check_1 = readchar (remote_timeout);
802188a7 7108
e1b09194
AC
7109 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7110 {
7111 if (remote_debug)
2bc416ba 7112 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 7113 gdb_stdlog);
e1b09194
AC
7114 return -1;
7115 }
7116 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
7117 {
7118 if (remote_debug)
2bc416ba 7119 fputs_filtered ("Communication error in checksum\n",
23860348 7120 gdb_stdlog);
40e3f985
FN
7121 return -1;
7122 }
c906108c 7123
a6f3e723
SL
7124 /* Don't recompute the checksum; with no ack packets we
7125 don't have any way to indicate a packet retransmission
7126 is necessary. */
7127 if (rs->noack_mode)
7128 return bc;
7129
e1b09194 7130 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 7131 if (csum == pktcsum)
c2d11a7d 7132 return bc;
c906108c 7133
c5aa993b 7134 if (remote_debug)
c906108c 7135 {
6e5abd65
PA
7136 struct cleanup *old_chain;
7137 char *str;
7138
7139 str = escape_buffer (buf, bc);
7140 old_chain = make_cleanup (xfree, str);
7141 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7142 "Bad checksum, sentsum=0x%x, "
7143 "csum=0x%x, buf=%s\n",
6e5abd65
PA
7144 pktcsum, csum, str);
7145 do_cleanups (old_chain);
c906108c 7146 }
c2d11a7d 7147 /* Number of characters in buffer ignoring trailing
23860348 7148 NULL. */
c2d11a7d 7149 return -1;
c906108c 7150 }
23860348 7151 case '*': /* Run length encoding. */
c2c6d25f
JM
7152 {
7153 int repeat;
c906108c 7154
a744cf53 7155 csum += c;
b4501125
AC
7156 c = readchar (remote_timeout);
7157 csum += c;
23860348 7158 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 7159
23860348 7160 /* The character before ``*'' is repeated. */
c2d11a7d 7161
6d820c5c 7162 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 7163 {
6d820c5c
DJ
7164 if (bc + repeat - 1 >= *sizeof_buf - 1)
7165 {
7166 /* Make some more room in the buffer. */
7167 *sizeof_buf += repeat;
7168 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7169 buf = *buf_p;
7170 }
7171
c2d11a7d
JM
7172 memset (&buf[bc], buf[bc - 1], repeat);
7173 bc += repeat;
c2c6d25f
JM
7174 continue;
7175 }
7176
c2d11a7d 7177 buf[bc] = '\0';
6d820c5c 7178 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 7179 return -1;
c2c6d25f 7180 }
c906108c 7181 default:
6d820c5c 7182 if (bc >= *sizeof_buf - 1)
c906108c 7183 {
6d820c5c
DJ
7184 /* Make some more room in the buffer. */
7185 *sizeof_buf *= 2;
7186 *buf_p = xrealloc (*buf_p, *sizeof_buf);
7187 buf = *buf_p;
c906108c
SS
7188 }
7189
6d820c5c
DJ
7190 buf[bc++] = c;
7191 csum += c;
7192 continue;
c906108c
SS
7193 }
7194 }
7195}
7196
7197/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7198 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7199 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7200 rather than timing out; this is used (in synchronous mode) to wait
7201 for a target that is is executing user code to stop. */
d9fcf2fb
JM
7202/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7203 don't have to change all the calls to getpkt to deal with the
7204 return value, because at the moment I don't know what the right
23860348 7205 thing to do it for those. */
c906108c 7206void
6d820c5c
DJ
7207getpkt (char **buf,
7208 long *sizeof_buf,
c2d11a7d 7209 int forever)
d9fcf2fb
JM
7210{
7211 int timed_out;
7212
7213 timed_out = getpkt_sane (buf, sizeof_buf, forever);
7214}
7215
7216
7217/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
7218 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
7219 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
7220 rather than timing out; this is used (in synchronous mode) to wait
7221 for a target that is is executing user code to stop. If FOREVER ==
7222 0, this function is allowed to time out gracefully and return an
74531fed
PA
7223 indication of this to the caller. Otherwise return the number of
7224 bytes read. If EXPECTING_NOTIF, consider receiving a notification
7225 enough reason to return to the caller. */
7226
3172dc30 7227static int
74531fed
PA
7228getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7229 int expecting_notif)
c906108c 7230{
2d717e4f 7231 struct remote_state *rs = get_remote_state ();
c906108c
SS
7232 int c;
7233 int tries;
7234 int timeout;
df4b58fe 7235 int val = -1;
c906108c 7236
2d717e4f
DJ
7237 /* We're reading a new response. Make sure we don't look at a
7238 previously cached response. */
7239 rs->cached_wait_status = 0;
7240
6d820c5c 7241 strcpy (*buf, "timeout");
c906108c
SS
7242
7243 if (forever)
74531fed
PA
7244 timeout = watchdog > 0 ? watchdog : -1;
7245 else if (expecting_notif)
7246 timeout = 0; /* There should already be a char in the buffer. If
7247 not, bail out. */
c906108c
SS
7248 else
7249 timeout = remote_timeout;
7250
7251#define MAX_TRIES 3
7252
74531fed
PA
7253 /* Process any number of notifications, and then return when
7254 we get a packet. */
7255 for (;;)
c906108c 7256 {
74531fed
PA
7257 /* If we get a timeout or bad checksm, retry up to MAX_TRIES
7258 times. */
7259 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 7260 {
74531fed
PA
7261 /* This can loop forever if the remote side sends us
7262 characters continuously, but if it pauses, we'll get
7263 SERIAL_TIMEOUT from readchar because of timeout. Then
7264 we'll count that as a retry.
7265
7266 Note that even when forever is set, we will only wait
7267 forever prior to the start of a packet. After that, we
7268 expect characters to arrive at a brisk pace. They should
7269 show up within remote_timeout intervals. */
7270 do
7271 c = readchar (timeout);
7272 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
7273
7274 if (c == SERIAL_TIMEOUT)
7275 {
74531fed
PA
7276 if (expecting_notif)
7277 return -1; /* Don't complain, it's normal to not get
7278 anything in this case. */
7279
23860348 7280 if (forever) /* Watchdog went off? Kill the target. */
c906108c 7281 {
2acceee2 7282 QUIT;
ce5ce7ed 7283 pop_target ();
489eaeba 7284 error (_("Watchdog timeout has expired. Target detached."));
c906108c 7285 }
c906108c 7286 if (remote_debug)
0f71a2f6 7287 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 7288 }
74531fed
PA
7289 else
7290 {
7291 /* We've found the start of a packet or notification.
7292 Now collect the data. */
7293 val = read_frame (buf, sizeof_buf);
7294 if (val >= 0)
7295 break;
7296 }
7297
7298 serial_write (remote_desc, "-", 1);
c906108c 7299 }
c906108c 7300
74531fed
PA
7301 if (tries > MAX_TRIES)
7302 {
7303 /* We have tried hard enough, and just can't receive the
7304 packet/notification. Give up. */
7305 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 7306
74531fed
PA
7307 /* Skip the ack char if we're in no-ack mode. */
7308 if (!rs->noack_mode)
7309 serial_write (remote_desc, "+", 1);
7310 return -1;
7311 }
c906108c 7312
74531fed
PA
7313 /* If we got an ordinary packet, return that to our caller. */
7314 if (c == '$')
c906108c
SS
7315 {
7316 if (remote_debug)
43e526b9 7317 {
6e5abd65
PA
7318 struct cleanup *old_chain;
7319 char *str;
7320
7321 str = escape_buffer (*buf, val);
7322 old_chain = make_cleanup (xfree, str);
7323 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
7324 do_cleanups (old_chain);
43e526b9 7325 }
a6f3e723
SL
7326
7327 /* Skip the ack char if we're in no-ack mode. */
7328 if (!rs->noack_mode)
7329 serial_write (remote_desc, "+", 1);
0876f84a 7330 return val;
c906108c
SS
7331 }
7332
74531fed
PA
7333 /* If we got a notification, handle it, and go back to looking
7334 for a packet. */
7335 else
7336 {
7337 gdb_assert (c == '%');
7338
7339 if (remote_debug)
7340 {
6e5abd65
PA
7341 struct cleanup *old_chain;
7342 char *str;
7343
7344 str = escape_buffer (*buf, val);
7345 old_chain = make_cleanup (xfree, str);
7346 fprintf_unfiltered (gdb_stdlog,
7347 " Notification received: %s\n",
7348 str);
7349 do_cleanups (old_chain);
74531fed 7350 }
c906108c 7351
74531fed 7352 handle_notification (*buf, val);
c906108c 7353
74531fed 7354 /* Notifications require no acknowledgement. */
a6f3e723 7355
74531fed
PA
7356 if (expecting_notif)
7357 return -1;
7358 }
7359 }
7360}
7361
7362static int
7363getpkt_sane (char **buf, long *sizeof_buf, int forever)
7364{
7365 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
7366}
7367
7368static int
7369getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
7370{
7371 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
c906108c 7372}
74531fed 7373
c906108c 7374\f
732f3f12
TT
7375/* A helper function that just calls putpkt; for type correctness. */
7376
7377static int
7378putpkt_for_catch_errors (void *arg)
7379{
7380 return putpkt (arg);
7381}
7382
c906108c 7383static void
7d85a9c0 7384remote_kill (struct target_ops *ops)
43ff13b4 7385{
23860348
MS
7386 /* Use catch_errors so the user can quit from gdb even when we
7387 aren't on speaking terms with the remote system. */
732f3f12 7388 catch_errors (putpkt_for_catch_errors, "k", "", RETURN_MASK_ERROR);
43ff13b4
JM
7389
7390 /* Don't wait for it to die. I'm not really sure it matters whether
7391 we do or not. For the existing stubs, kill is a noop. */
7392 target_mourn_inferior ();
7393}
7394
82f73884
PA
7395static int
7396remote_vkill (int pid, struct remote_state *rs)
7397{
7398 if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7399 return -1;
7400
7401 /* Tell the remote target to detach. */
7402 sprintf (rs->buf, "vKill;%x", pid);
7403 putpkt (rs->buf);
7404 getpkt (&rs->buf, &rs->buf_size, 0);
7405
7406 if (packet_ok (rs->buf,
7407 &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
7408 return 0;
7409 else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
7410 return -1;
7411 else
7412 return 1;
7413}
7414
7415static void
7d85a9c0 7416extended_remote_kill (struct target_ops *ops)
82f73884
PA
7417{
7418 int res;
7419 int pid = ptid_get_pid (inferior_ptid);
7420 struct remote_state *rs = get_remote_state ();
7421
7422 res = remote_vkill (pid, rs);
7423 if (res == -1 && !remote_multi_process_p (rs))
7424 {
7425 /* Don't try 'k' on a multi-process aware stub -- it has no way
7426 to specify the pid. */
7427
7428 putpkt ("k");
7429#if 0
7430 getpkt (&rs->buf, &rs->buf_size, 0);
7431 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
7432 res = 1;
7433#else
7434 /* Don't wait for it to die. I'm not really sure it matters whether
7435 we do or not. For the existing stubs, kill is a noop. */
7436 res = 0;
7437#endif
7438 }
7439
7440 if (res != 0)
7441 error (_("Can't kill process"));
7442
82f73884
PA
7443 target_mourn_inferior ();
7444}
7445
c906108c 7446static void
136d6dae 7447remote_mourn (struct target_ops *ops)
c906108c 7448{
136d6dae 7449 remote_mourn_1 (ops);
c906108c
SS
7450}
7451
c906108c
SS
7452/* Worker function for remote_mourn. */
7453static void
fba45db2 7454remote_mourn_1 (struct target_ops *target)
c906108c
SS
7455{
7456 unpush_target (target);
ce5ce7ed 7457
8a2492ee
PA
7458 /* remote_close takes care of doing most of the clean up. */
7459 generic_mourn_inferior ();
c906108c
SS
7460}
7461
2d717e4f
DJ
7462static void
7463extended_remote_mourn_1 (struct target_ops *target)
7464{
7465 struct remote_state *rs = get_remote_state ();
c906108c 7466
e24a49d8
PA
7467 /* In case we got here due to an error, but we're going to stay
7468 connected. */
7469 rs->waiting_for_stop_reply = 0;
7470
74531fed
PA
7471 /* We're no longer interested in these events. */
7472 discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
7473
dc1981d7
PA
7474 /* If the current general thread belonged to the process we just
7475 detached from or has exited, the remote side current general
7476 thread becomes undefined. Considering a case like this:
7477
7478 - We just got here due to a detach.
7479 - The process that we're detaching from happens to immediately
7480 report a global breakpoint being hit in non-stop mode, in the
7481 same thread we had selected before.
7482 - GDB attaches to this process again.
7483 - This event happens to be the next event we handle.
7484
7485 GDB would consider that the current general thread didn't need to
7486 be set on the stub side (with Hg), since for all it knew,
7487 GENERAL_THREAD hadn't changed.
7488
7489 Notice that although in all-stop mode, the remote server always
7490 sets the current thread to the thread reporting the stop event,
7491 that doesn't happen in non-stop mode; in non-stop, the stub *must
7492 not* change the current thread when reporting a breakpoint hit,
7493 due to the decoupling of event reporting and event handling.
7494
7495 To keep things simple, we always invalidate our notion of the
7496 current thread. */
7497 record_currthread (minus_one_ptid);
7498
2d717e4f
DJ
7499 /* Unlike "target remote", we do not want to unpush the target; then
7500 the next time the user says "run", we won't be connected. */
7501
48aa3c27
PA
7502 /* Call common code to mark the inferior as not running. */
7503 generic_mourn_inferior ();
7504
d729566a 7505 if (!have_inferiors ())
2d717e4f 7506 {
82f73884
PA
7507 if (!remote_multi_process_p (rs))
7508 {
7509 /* Check whether the target is running now - some remote stubs
7510 automatically restart after kill. */
7511 putpkt ("?");
7512 getpkt (&rs->buf, &rs->buf_size, 0);
7513
7514 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
7515 {
3e43a32a
MS
7516 /* Assume that the target has been restarted. Set
7517 inferior_ptid so that bits of core GDB realizes
7518 there's something here, e.g., so that the user can
7519 say "kill" again. */
82f73884
PA
7520 inferior_ptid = magic_null_ptid;
7521 }
82f73884 7522 }
2d717e4f
DJ
7523 }
7524}
c906108c
SS
7525
7526static void
136d6dae 7527extended_remote_mourn (struct target_ops *ops)
c906108c 7528{
136d6dae 7529 extended_remote_mourn_1 (ops);
2d717e4f 7530}
c906108c 7531
03583c20
UW
7532static int
7533extended_remote_supports_disable_randomization (void)
7534{
7535 return (remote_protocol_packets[PACKET_QDisableRandomization].support
7536 == PACKET_ENABLE);
7537}
7538
7539static void
7540extended_remote_disable_randomization (int val)
7541{
7542 struct remote_state *rs = get_remote_state ();
7543 char *reply;
7544
7545 sprintf (rs->buf, "QDisableRandomization:%x", val);
7546 putpkt (rs->buf);
7547 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
7548 if (*reply == '\0')
7549 error (_("Target does not support QDisableRandomization."));
7550 if (strcmp (reply, "OK") != 0)
7551 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
7552}
7553
2d717e4f
DJ
7554static int
7555extended_remote_run (char *args)
7556{
7557 struct remote_state *rs = get_remote_state ();
2d717e4f 7558 int len;
c906108c 7559
2d717e4f
DJ
7560 /* If the user has disabled vRun support, or we have detected that
7561 support is not available, do not try it. */
7562 if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7563 return -1;
424163ea 7564
2d717e4f
DJ
7565 strcpy (rs->buf, "vRun;");
7566 len = strlen (rs->buf);
c906108c 7567
2d717e4f
DJ
7568 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
7569 error (_("Remote file name too long for run packet"));
7570 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
7571
d1a41061 7572 gdb_assert (args != NULL);
2d717e4f
DJ
7573 if (*args)
7574 {
7575 struct cleanup *back_to;
7576 int i;
7577 char **argv;
7578
d1a41061 7579 argv = gdb_buildargv (args);
2d717e4f
DJ
7580 back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
7581 for (i = 0; argv[i] != NULL; i++)
7582 {
7583 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
7584 error (_("Argument list too long for run packet"));
7585 rs->buf[len++] = ';';
7586 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
7587 }
7588 do_cleanups (back_to);
7589 }
7590
7591 rs->buf[len++] = '\0';
7592
7593 putpkt (rs->buf);
7594 getpkt (&rs->buf, &rs->buf_size, 0);
7595
7596 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
7597 {
7598 /* We have a wait response; we don't need it, though. All is well. */
7599 return 0;
7600 }
7601 else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
7602 /* It wasn't disabled before, but it is now. */
7603 return -1;
7604 else
7605 {
7606 if (remote_exec_file[0] == '\0')
7607 error (_("Running the default executable on the remote target failed; "
7608 "try \"set remote exec-file\"?"));
7609 else
7610 error (_("Running \"%s\" on the remote target failed"),
7611 remote_exec_file);
7612 }
c906108c
SS
7613}
7614
2d717e4f
DJ
7615/* In the extended protocol we want to be able to do things like
7616 "run" and have them basically work as expected. So we need
7617 a special create_inferior function. We support changing the
7618 executable file and the command line arguments, but not the
7619 environment. */
7620
43ff13b4 7621static void
2d717e4f 7622extended_remote_create_inferior_1 (char *exec_file, char *args,
75c99385 7623 char **env, int from_tty)
43ff13b4 7624{
43ff13b4 7625 /* If running asynchronously, register the target file descriptor
23860348 7626 with the event loop. */
75c99385 7627 if (target_can_async_p ())
2acceee2 7628 target_async (inferior_event_handler, 0);
43ff13b4 7629
03583c20
UW
7630 /* Disable address space randomization if requested (and supported). */
7631 if (extended_remote_supports_disable_randomization ())
7632 extended_remote_disable_randomization (disable_randomization);
7633
43ff13b4 7634 /* Now restart the remote server. */
2d717e4f
DJ
7635 if (extended_remote_run (args) == -1)
7636 {
7637 /* vRun was not supported. Fail if we need it to do what the
7638 user requested. */
7639 if (remote_exec_file[0])
7640 error (_("Remote target does not support \"set remote exec-file\""));
7641 if (args[0])
7642 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 7643
2d717e4f
DJ
7644 /* Fall back to "R". */
7645 extended_remote_restart ();
7646 }
424163ea 7647
6c95b8df
PA
7648 if (!have_inferiors ())
7649 {
7650 /* Clean up from the last time we ran, before we mark the target
7651 running again. This will mark breakpoints uninserted, and
7652 get_offsets may insert breakpoints. */
7653 init_thread_list ();
7654 init_wait_for_inferior ();
7655 }
45280a52 7656
2d717e4f 7657 /* Now mark the inferior as running before we do anything else. */
79d7f229 7658 inferior_ptid = magic_null_ptid;
c0a2216e 7659
74531fed
PA
7660 /* Now, if we have thread information, update inferior_ptid. */
7661 inferior_ptid = remote_current_thread (inferior_ptid);
7662
0b16c5cf 7663 remote_add_inferior (ptid_get_pid (inferior_ptid), 0);
c0a2216e
PA
7664 add_thread_silent (inferior_ptid);
7665
2d717e4f
DJ
7666 /* Get updated offsets, if the stub uses qOffsets. */
7667 get_offsets ();
2d717e4f
DJ
7668}
7669
7670static void
136d6dae
VP
7671extended_remote_create_inferior (struct target_ops *ops,
7672 char *exec_file, char *args,
2d717e4f
DJ
7673 char **env, int from_tty)
7674{
75c99385 7675 extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
43ff13b4 7676}
c906108c 7677\f
c5aa993b 7678
8181d85f
DJ
7679/* Insert a breakpoint. On targets that have software breakpoint
7680 support, we ask the remote target to do the work; on targets
7681 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
7682
7683static int
a6d9a66e
UW
7684remote_insert_breakpoint (struct gdbarch *gdbarch,
7685 struct bp_target_info *bp_tgt)
c906108c 7686{
d471ea57
AC
7687 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
7688 If it succeeds, then set the support to PACKET_ENABLE. If it
7689 fails, and the user has explicitly requested the Z support then
23860348 7690 report an error, otherwise, mark it disabled and go on. */
802188a7 7691
444abaca 7692 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 7693 {
7c0f6dcc 7694 CORE_ADDR addr = bp_tgt->placed_address;
4fff2411
JZ
7695 struct remote_state *rs;
7696 char *p;
7c0f6dcc 7697 int bpsize;
4fff2411 7698
a1dcb23a 7699 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
7700
7701 rs = get_remote_state ();
7702 p = rs->buf;
802188a7 7703
96baa820
JM
7704 *(p++) = 'Z';
7705 *(p++) = '0';
7706 *(p++) = ',';
7c0f6dcc 7707 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 7708 p += hexnumstr (p, addr);
7c0f6dcc 7709 sprintf (p, ",%d", bpsize);
802188a7 7710
6d820c5c
DJ
7711 putpkt (rs->buf);
7712 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 7713
6d820c5c 7714 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 7715 {
d471ea57
AC
7716 case PACKET_ERROR:
7717 return -1;
7718 case PACKET_OK:
7c0f6dcc
JL
7719 bp_tgt->placed_address = addr;
7720 bp_tgt->placed_size = bpsize;
d471ea57
AC
7721 return 0;
7722 case PACKET_UNKNOWN:
7723 break;
96baa820
JM
7724 }
7725 }
c906108c 7726
a6d9a66e 7727 return memory_insert_breakpoint (gdbarch, bp_tgt);
c906108c
SS
7728}
7729
7730static int
a6d9a66e
UW
7731remote_remove_breakpoint (struct gdbarch *gdbarch,
7732 struct bp_target_info *bp_tgt)
c906108c 7733{
8181d85f 7734 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 7735 struct remote_state *rs = get_remote_state ();
96baa820 7736
444abaca 7737 if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
96baa820 7738 {
6d820c5c 7739 char *p = rs->buf;
802188a7 7740
96baa820
JM
7741 *(p++) = 'z';
7742 *(p++) = '0';
7743 *(p++) = ',';
7744
8181d85f
DJ
7745 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
7746 p += hexnumstr (p, addr);
7747 sprintf (p, ",%d", bp_tgt->placed_size);
802188a7 7748
6d820c5c
DJ
7749 putpkt (rs->buf);
7750 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 7751
6d820c5c 7752 return (rs->buf[0] == 'E');
96baa820
JM
7753 }
7754
a6d9a66e 7755 return memory_remove_breakpoint (gdbarch, bp_tgt);
c906108c
SS
7756}
7757
d471ea57
AC
7758static int
7759watchpoint_to_Z_packet (int type)
7760{
7761 switch (type)
7762 {
7763 case hw_write:
bb858e6a 7764 return Z_PACKET_WRITE_WP;
d471ea57
AC
7765 break;
7766 case hw_read:
bb858e6a 7767 return Z_PACKET_READ_WP;
d471ea57
AC
7768 break;
7769 case hw_access:
bb858e6a 7770 return Z_PACKET_ACCESS_WP;
d471ea57
AC
7771 break;
7772 default:
8e65ff28 7773 internal_error (__FILE__, __LINE__,
e2e0b3e5 7774 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
7775 }
7776}
7777
3c3bea1c 7778static int
0cf6dd15
TJB
7779remote_insert_watchpoint (CORE_ADDR addr, int len, int type,
7780 struct expression *cond)
96baa820 7781{
d01949b6 7782 struct remote_state *rs = get_remote_state ();
e514a9d6 7783 char *p;
d471ea57 7784 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 7785
444abaca 7786 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
85d721b8 7787 return 1;
802188a7 7788
6d820c5c
DJ
7789 sprintf (rs->buf, "Z%x,", packet);
7790 p = strchr (rs->buf, '\0');
96baa820
JM
7791 addr = remote_address_masked (addr);
7792 p += hexnumstr (p, (ULONGEST) addr);
d4f3574e 7793 sprintf (p, ",%x", len);
802188a7 7794
6d820c5c
DJ
7795 putpkt (rs->buf);
7796 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 7797
6d820c5c 7798 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
7799 {
7800 case PACKET_ERROR:
d471ea57 7801 return -1;
85d721b8
PA
7802 case PACKET_UNKNOWN:
7803 return 1;
d471ea57
AC
7804 case PACKET_OK:
7805 return 0;
7806 }
8e65ff28 7807 internal_error (__FILE__, __LINE__,
e2e0b3e5 7808 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
7809}
7810
d471ea57 7811
3c3bea1c 7812static int
0cf6dd15
TJB
7813remote_remove_watchpoint (CORE_ADDR addr, int len, int type,
7814 struct expression *cond)
96baa820 7815{
d01949b6 7816 struct remote_state *rs = get_remote_state ();
e514a9d6 7817 char *p;
d471ea57
AC
7818 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
7819
444abaca 7820 if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
5cffb350 7821 return -1;
802188a7 7822
6d820c5c
DJ
7823 sprintf (rs->buf, "z%x,", packet);
7824 p = strchr (rs->buf, '\0');
96baa820
JM
7825 addr = remote_address_masked (addr);
7826 p += hexnumstr (p, (ULONGEST) addr);
d4f3574e 7827 sprintf (p, ",%x", len);
6d820c5c
DJ
7828 putpkt (rs->buf);
7829 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 7830
6d820c5c 7831 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
7832 {
7833 case PACKET_ERROR:
7834 case PACKET_UNKNOWN:
7835 return -1;
7836 case PACKET_OK:
7837 return 0;
7838 }
8e65ff28 7839 internal_error (__FILE__, __LINE__,
e2e0b3e5 7840 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
7841}
7842
3c3bea1c 7843
501eef12 7844int remote_hw_watchpoint_limit = -1;
480a3f21 7845int remote_hw_watchpoint_length_limit = -1;
501eef12 7846int remote_hw_breakpoint_limit = -1;
d471ea57 7847
480a3f21
PW
7848static int
7849remote_region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
7850{
7851 if (remote_hw_watchpoint_length_limit == 0)
7852 return 0;
7853 else if (remote_hw_watchpoint_length_limit < 0)
7854 return 1;
7855 else if (len <= remote_hw_watchpoint_length_limit)
7856 return 1;
7857 else
7858 return 0;
7859}
7860
b9362cc7 7861static int
3c3bea1c 7862remote_check_watch_resources (int type, int cnt, int ot)
96baa820 7863{
3c3bea1c
GS
7864 if (type == bp_hardware_breakpoint)
7865 {
7866 if (remote_hw_breakpoint_limit == 0)
7867 return 0;
501eef12
AC
7868 else if (remote_hw_breakpoint_limit < 0)
7869 return 1;
3c3bea1c
GS
7870 else if (cnt <= remote_hw_breakpoint_limit)
7871 return 1;
7872 }
7873 else
7874 {
7875 if (remote_hw_watchpoint_limit == 0)
7876 return 0;
501eef12
AC
7877 else if (remote_hw_watchpoint_limit < 0)
7878 return 1;
3c3bea1c
GS
7879 else if (ot)
7880 return -1;
7881 else if (cnt <= remote_hw_watchpoint_limit)
7882 return 1;
7883 }
7884 return -1;
7885}
7886
b9362cc7 7887static int
3c3bea1c
GS
7888remote_stopped_by_watchpoint (void)
7889{
82f73884 7890 return remote_stopped_by_watchpoint_p;
3c3bea1c
GS
7891}
7892
4aa7a7f5
JJ
7893static int
7894remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 7895{
4aa7a7f5 7896 int rc = 0;
a744cf53 7897
d983da9c 7898 if (remote_stopped_by_watchpoint ())
4aa7a7f5
JJ
7899 {
7900 *addr_p = remote_watch_data_address;
7901 rc = 1;
7902 }
7903
7904 return rc;
3c3bea1c
GS
7905}
7906
7907
7908static int
a6d9a66e
UW
7909remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
7910 struct bp_target_info *bp_tgt)
3c3bea1c 7911{
8181d85f 7912 CORE_ADDR addr;
4fff2411
JZ
7913 struct remote_state *rs;
7914 char *p;
802188a7 7915
c8189ed1 7916 /* The length field should be set to the size of a breakpoint
8181d85f 7917 instruction, even though we aren't inserting one ourselves. */
c8189ed1 7918
a1dcb23a 7919 gdbarch_remote_breakpoint_from_pc
a6d9a66e 7920 (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
3c3bea1c 7921
444abaca 7922 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 7923 return -1;
2bc416ba 7924
4fff2411
JZ
7925 rs = get_remote_state ();
7926 p = rs->buf;
7927
96baa820
JM
7928 *(p++) = 'Z';
7929 *(p++) = '1';
7930 *(p++) = ',';
802188a7 7931
8181d85f 7932 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 7933 p += hexnumstr (p, (ULONGEST) addr);
8181d85f 7934 sprintf (p, ",%x", bp_tgt->placed_size);
96baa820 7935
6d820c5c
DJ
7936 putpkt (rs->buf);
7937 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 7938
6d820c5c 7939 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
7940 {
7941 case PACKET_ERROR:
7942 case PACKET_UNKNOWN:
7943 return -1;
7944 case PACKET_OK:
7945 return 0;
7946 }
8e65ff28 7947 internal_error (__FILE__, __LINE__,
e2e0b3e5 7948 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
7949}
7950
d471ea57 7951
802188a7 7952static int
a6d9a66e
UW
7953remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
7954 struct bp_target_info *bp_tgt)
96baa820 7955{
8181d85f 7956 CORE_ADDR addr;
d01949b6 7957 struct remote_state *rs = get_remote_state ();
6d820c5c 7958 char *p = rs->buf;
c8189ed1 7959
444abaca 7960 if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
5cffb350 7961 return -1;
802188a7 7962
96baa820
JM
7963 *(p++) = 'z';
7964 *(p++) = '1';
7965 *(p++) = ',';
802188a7 7966
8181d85f 7967 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 7968 p += hexnumstr (p, (ULONGEST) addr);
8181d85f 7969 sprintf (p, ",%x", bp_tgt->placed_size);
96baa820 7970
6d820c5c
DJ
7971 putpkt (rs->buf);
7972 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7973
6d820c5c 7974 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
7975 {
7976 case PACKET_ERROR:
7977 case PACKET_UNKNOWN:
7978 return -1;
7979 case PACKET_OK:
7980 return 0;
7981 }
8e65ff28 7982 internal_error (__FILE__, __LINE__,
e2e0b3e5 7983 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 7984}
96baa820 7985
23860348 7986/* Table used by the crc32 function to calcuate the checksum. */
c906108c 7987
c5aa993b
JM
7988static unsigned long crc32_table[256] =
7989{0, 0};
c906108c
SS
7990
7991static unsigned long
4a5e7a5b 7992crc32 (const unsigned char *buf, int len, unsigned int crc)
c906108c 7993{
c5aa993b 7994 if (!crc32_table[1])
c906108c 7995 {
23860348 7996 /* Initialize the CRC table and the decoding table. */
c906108c
SS
7997 int i, j;
7998 unsigned int c;
7999
8000 for (i = 0; i < 256; i++)
c5aa993b
JM
8001 {
8002 for (c = i << 24, j = 8; j > 0; --j)
8003 c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
8004 crc32_table[i] = c;
8005 }
c906108c
SS
8006 }
8007
8008 while (len--)
8009 {
8010 crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
8011 buf++;
8012 }
8013 return crc;
8014}
8015
4a5e7a5b
PA
8016/* Verify memory using the "qCRC:" request. */
8017
8018static int
8019remote_verify_memory (struct target_ops *ops,
8020 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8021{
8022 struct remote_state *rs = get_remote_state ();
8023 unsigned long host_crc, target_crc;
8024 char *tmp;
8025
8026 /* FIXME: assumes lma can fit into long. */
8027 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8028 (long) lma, (long) size);
8029 putpkt (rs->buf);
8030
8031 /* Be clever; compute the host_crc before waiting for target
8032 reply. */
8033 host_crc = crc32 (data, size, 0xffffffff);
8034
8035 getpkt (&rs->buf, &rs->buf_size, 0);
8036 if (rs->buf[0] == 'E')
8037 return -1;
8038
8039 if (rs->buf[0] != 'C')
8040 error (_("remote target does not support this operation"));
8041
8042 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
8043 target_crc = target_crc * 16 + fromhex (*tmp);
8044
8045 return (host_crc == target_crc);
8046}
8047
c906108c
SS
8048/* compare-sections command
8049
8050 With no arguments, compares each loadable section in the exec bfd
8051 with the same memory range on the target, and reports mismatches.
4a5e7a5b 8052 Useful for verifying the image on the target against the exec file. */
e514a9d6 8053
c906108c 8054static void
fba45db2 8055compare_sections_command (char *args, int from_tty)
c906108c
SS
8056{
8057 asection *s;
c906108c 8058 struct cleanup *old_chain;
085dd6e6 8059 char *sectdata;
ce359b09 8060 const char *sectname;
c906108c
SS
8061 bfd_size_type size;
8062 bfd_vma lma;
8063 int matched = 0;
8064 int mismatched = 0;
4a5e7a5b 8065 int res;
c906108c
SS
8066
8067 if (!exec_bfd)
8a3fe4f8 8068 error (_("command cannot be used without an exec file"));
c906108c 8069
c5aa993b 8070 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
8071 {
8072 if (!(s->flags & SEC_LOAD))
0df8b418 8073 continue; /* Skip non-loadable section. */
c906108c 8074
2c500098 8075 size = bfd_get_section_size (s);
c906108c 8076 if (size == 0)
0df8b418 8077 continue; /* Skip zero-length section. */
c906108c 8078
ce359b09 8079 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 8080 if (args && strcmp (args, sectname) != 0)
0df8b418 8081 continue; /* Not the section selected by user. */
c906108c 8082
0df8b418 8083 matched = 1; /* Do this section. */
c906108c 8084 lma = s->lma;
c906108c 8085
c906108c 8086 sectdata = xmalloc (size);
b8c9b27d 8087 old_chain = make_cleanup (xfree, sectdata);
c906108c 8088 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 8089
4a5e7a5b
PA
8090 res = target_verify_memory (sectdata, lma, size);
8091
8092 if (res == -1)
5af949e3
UW
8093 error (_("target memory fault, section %s, range %s -- %s"), sectname,
8094 paddress (target_gdbarch, lma),
8095 paddress (target_gdbarch, lma + size));
c906108c 8096
5af949e3
UW
8097 printf_filtered ("Section %s, range %s -- %s: ", sectname,
8098 paddress (target_gdbarch, lma),
8099 paddress (target_gdbarch, lma + size));
4a5e7a5b 8100 if (res)
c906108c
SS
8101 printf_filtered ("matched.\n");
8102 else
c5aa993b
JM
8103 {
8104 printf_filtered ("MIS-MATCHED!\n");
8105 mismatched++;
8106 }
c906108c
SS
8107
8108 do_cleanups (old_chain);
8109 }
8110 if (mismatched > 0)
8a3fe4f8
AC
8111 warning (_("One or more sections of the remote executable does not match\n\
8112the loaded file\n"));
c906108c 8113 if (args && !matched)
a3f17187 8114 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
8115}
8116
0e7f50da
UW
8117/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
8118 into remote target. The number of bytes written to the remote
8119 target is returned, or -1 for error. */
8120
8121static LONGEST
8122remote_write_qxfer (struct target_ops *ops, const char *object_name,
8123 const char *annex, const gdb_byte *writebuf,
8124 ULONGEST offset, LONGEST len,
8125 struct packet_config *packet)
8126{
8127 int i, buf_len;
8128 ULONGEST n;
0e7f50da
UW
8129 struct remote_state *rs = get_remote_state ();
8130 int max_size = get_memory_write_packet_size ();
8131
8132 if (packet->support == PACKET_DISABLE)
8133 return -1;
8134
8135 /* Insert header. */
8136 i = snprintf (rs->buf, max_size,
8137 "qXfer:%s:write:%s:%s:",
8138 object_name, annex ? annex : "",
8139 phex_nz (offset, sizeof offset));
8140 max_size -= (i + 1);
8141
8142 /* Escape as much data as fits into rs->buf. */
8143 buf_len = remote_escape_output
8144 (writebuf, len, (rs->buf + i), &max_size, max_size);
8145
8146 if (putpkt_binary (rs->buf, i + buf_len) < 0
8147 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8148 || packet_ok (rs->buf, packet) != PACKET_OK)
8149 return -1;
8150
8151 unpack_varlen_hex (rs->buf, &n);
8152 return n;
8153}
8154
0876f84a
DJ
8155/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
8156 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
8157 number of bytes read is returned, or 0 for EOF, or -1 for error.
8158 The number of bytes read may be less than LEN without indicating an
8159 EOF. PACKET is checked and updated to indicate whether the remote
8160 target supports this object. */
8161
8162static LONGEST
8163remote_read_qxfer (struct target_ops *ops, const char *object_name,
8164 const char *annex,
8165 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
8166 struct packet_config *packet)
8167{
8168 static char *finished_object;
8169 static char *finished_annex;
8170 static ULONGEST finished_offset;
8171
8172 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
8173 LONGEST i, n, packet_len;
8174
8175 if (packet->support == PACKET_DISABLE)
8176 return -1;
8177
8178 /* Check whether we've cached an end-of-object packet that matches
8179 this request. */
8180 if (finished_object)
8181 {
8182 if (strcmp (object_name, finished_object) == 0
8183 && strcmp (annex ? annex : "", finished_annex) == 0
8184 && offset == finished_offset)
8185 return 0;
8186
8187 /* Otherwise, we're now reading something different. Discard
8188 the cache. */
8189 xfree (finished_object);
8190 xfree (finished_annex);
8191 finished_object = NULL;
8192 finished_annex = NULL;
8193 }
8194
8195 /* Request only enough to fit in a single packet. The actual data
8196 may not, since we don't know how much of it will need to be escaped;
8197 the target is free to respond with slightly less data. We subtract
8198 five to account for the response type and the protocol frame. */
8199 n = min (get_remote_packet_size () - 5, len);
8200 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
8201 object_name, annex ? annex : "",
8202 phex_nz (offset, sizeof offset),
8203 phex_nz (n, sizeof n));
8204 i = putpkt (rs->buf);
8205 if (i < 0)
8206 return -1;
8207
8208 rs->buf[0] = '\0';
8209 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8210 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
8211 return -1;
8212
8213 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
8214 error (_("Unknown remote qXfer reply: %s"), rs->buf);
8215
8216 /* 'm' means there is (or at least might be) more data after this
8217 batch. That does not make sense unless there's at least one byte
8218 of data in this reply. */
8219 if (rs->buf[0] == 'm' && packet_len == 1)
8220 error (_("Remote qXfer reply contained no data."));
8221
8222 /* Got some data. */
8223 i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
8224
8225 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
8226 or possibly empty. If we have the final block of a non-empty
8227 object, record this fact to bypass a subsequent partial read. */
8228 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a
DJ
8229 {
8230 finished_object = xstrdup (object_name);
8231 finished_annex = xstrdup (annex ? annex : "");
8232 finished_offset = offset + i;
8233 }
8234
8235 return i;
8236}
8237
1e3ff5ad 8238static LONGEST
4b8a223f 8239remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5
MK
8240 const char *annex, gdb_byte *readbuf,
8241 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
c906108c 8242{
82f73884 8243 struct remote_state *rs;
c906108c 8244 int i;
6d820c5c 8245 char *p2;
1e3ff5ad 8246 char query_type;
c906108c 8247
e6e4e701 8248 set_remote_traceframe ();
82f73884
PA
8249 set_general_thread (inferior_ptid);
8250
8251 rs = get_remote_state ();
8252
b2182ed2 8253 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
8254 if (object == TARGET_OBJECT_MEMORY)
8255 {
8256 int xfered;
a744cf53 8257
21e3b9b9
DJ
8258 errno = 0;
8259
2d717e4f
DJ
8260 /* If the remote target is connected but not running, we should
8261 pass this request down to a lower stratum (e.g. the executable
8262 file). */
8263 if (!target_has_execution)
8264 return 0;
8265
21e3b9b9 8266 if (writebuf != NULL)
b2182ed2 8267 xfered = remote_write_bytes (offset, writebuf, len);
21e3b9b9 8268 else
b2182ed2 8269 xfered = remote_read_bytes (offset, readbuf, len);
21e3b9b9
DJ
8270
8271 if (xfered > 0)
8272 return xfered;
8273 else if (xfered == 0 && errno == 0)
8274 return 0;
8275 else
8276 return -1;
8277 }
8278
0df8b418 8279 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
8280 if (object == TARGET_OBJECT_SPU)
8281 {
8282 if (readbuf)
8283 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
8284 &remote_protocol_packets
8285 [PACKET_qXfer_spu_read]);
8286 else
8287 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
8288 &remote_protocol_packets
8289 [PACKET_qXfer_spu_write]);
8290 }
8291
4aa995e1
PA
8292 /* Handle extra signal info using qxfer packets. */
8293 if (object == TARGET_OBJECT_SIGNAL_INFO)
8294 {
8295 if (readbuf)
8296 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
8297 &remote_protocol_packets
8298 [PACKET_qXfer_siginfo_read]);
8299 else
3e43a32a
MS
8300 return remote_write_qxfer (ops, "siginfo", annex,
8301 writebuf, offset, len,
4aa995e1
PA
8302 &remote_protocol_packets
8303 [PACKET_qXfer_siginfo_write]);
8304 }
8305
0fb4aa4b
PA
8306 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
8307 {
8308 if (readbuf)
3e43a32a
MS
8309 return remote_read_qxfer (ops, "statictrace", annex,
8310 readbuf, offset, len,
0fb4aa4b
PA
8311 &remote_protocol_packets
8312 [PACKET_qXfer_statictrace_read]);
8313 else
8314 return -1;
8315 }
8316
a76d924d
DJ
8317 /* Only handle flash writes. */
8318 if (writebuf != NULL)
8319 {
8320 LONGEST xfered;
8321
8322 switch (object)
8323 {
8324 case TARGET_OBJECT_FLASH:
8325 xfered = remote_flash_write (ops, offset, len, writebuf);
8326
8327 if (xfered > 0)
8328 return xfered;
8329 else if (xfered == 0 && errno == 0)
8330 return 0;
8331 else
8332 return -1;
8333
8334 default:
8335 return -1;
8336 }
8337 }
4b8a223f 8338
1e3ff5ad
AC
8339 /* Map pre-existing objects onto letters. DO NOT do this for new
8340 objects!!! Instead specify new query packets. */
8341 switch (object)
c906108c 8342 {
1e3ff5ad
AC
8343 case TARGET_OBJECT_AVR:
8344 query_type = 'R';
8345 break;
802188a7
RM
8346
8347 case TARGET_OBJECT_AUXV:
0876f84a
DJ
8348 gdb_assert (annex == NULL);
8349 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
8350 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 8351
23181151
DJ
8352 case TARGET_OBJECT_AVAILABLE_FEATURES:
8353 return remote_read_qxfer
8354 (ops, "features", annex, readbuf, offset, len,
8355 &remote_protocol_packets[PACKET_qXfer_features]);
8356
cfa9d6d9
DJ
8357 case TARGET_OBJECT_LIBRARIES:
8358 return remote_read_qxfer
8359 (ops, "libraries", annex, readbuf, offset, len,
8360 &remote_protocol_packets[PACKET_qXfer_libraries]);
8361
2268b414
JK
8362 case TARGET_OBJECT_LIBRARIES_SVR4:
8363 return remote_read_qxfer
8364 (ops, "libraries-svr4", annex, readbuf, offset, len,
8365 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
8366
fd79ecee
DJ
8367 case TARGET_OBJECT_MEMORY_MAP:
8368 gdb_assert (annex == NULL);
8369 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
8370 &remote_protocol_packets[PACKET_qXfer_memory_map]);
8371
07e059b5
VP
8372 case TARGET_OBJECT_OSDATA:
8373 /* Should only get here if we're connected. */
8374 gdb_assert (remote_desc);
8375 return remote_read_qxfer
8376 (ops, "osdata", annex, readbuf, offset, len,
8377 &remote_protocol_packets[PACKET_qXfer_osdata]);
8378
dc146f7c
VP
8379 case TARGET_OBJECT_THREADS:
8380 gdb_assert (annex == NULL);
8381 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
8382 &remote_protocol_packets[PACKET_qXfer_threads]);
8383
b3b9301e
PA
8384 case TARGET_OBJECT_TRACEFRAME_INFO:
8385 gdb_assert (annex == NULL);
8386 return remote_read_qxfer
8387 (ops, "traceframe-info", annex, readbuf, offset, len,
8388 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
8389
8390 case TARGET_OBJECT_FDPIC:
8391 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
8392 &remote_protocol_packets[PACKET_qXfer_fdpic]);
1e3ff5ad 8393 default:
c906108c
SS
8394 return -1;
8395 }
8396
4b8a223f 8397 /* Note: a zero OFFSET and LEN can be used to query the minimum
1e3ff5ad 8398 buffer size. */
4b8a223f 8399 if (offset == 0 && len == 0)
ea9c271d 8400 return (get_remote_packet_size ());
0df8b418 8401 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 8402 large enough let the caller deal with it. */
ea9c271d 8403 if (len < get_remote_packet_size ())
1e3ff5ad 8404 return -1;
ea9c271d 8405 len = get_remote_packet_size ();
1e3ff5ad 8406
23860348 8407 /* Except for querying the minimum buffer size, target must be open. */
c5aa993b 8408 if (!remote_desc)
8a3fe4f8 8409 error (_("remote query is only available after target open"));
c906108c 8410
1e3ff5ad 8411 gdb_assert (annex != NULL);
4b8a223f 8412 gdb_assert (readbuf != NULL);
c906108c 8413
6d820c5c 8414 p2 = rs->buf;
c906108c
SS
8415 *p2++ = 'q';
8416 *p2++ = query_type;
8417
23860348
MS
8418 /* We used one buffer char for the remote protocol q command and
8419 another for the query type. As the remote protocol encapsulation
8420 uses 4 chars plus one extra in case we are debugging
8421 (remote_debug), we have PBUFZIZ - 7 left to pack the query
8422 string. */
c906108c 8423 i = 0;
ea9c271d 8424 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 8425 {
1e3ff5ad
AC
8426 /* Bad caller may have sent forbidden characters. */
8427 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
8428 *p2++ = annex[i];
c906108c
SS
8429 i++;
8430 }
1e3ff5ad
AC
8431 *p2 = '\0';
8432 gdb_assert (annex[i] == '\0');
c906108c 8433
6d820c5c 8434 i = putpkt (rs->buf);
c5aa993b
JM
8435 if (i < 0)
8436 return i;
c906108c 8437
6d820c5c
DJ
8438 getpkt (&rs->buf, &rs->buf_size, 0);
8439 strcpy ((char *) readbuf, rs->buf);
c906108c 8440
cfd77fa1 8441 return strlen ((char *) readbuf);
c906108c
SS
8442}
8443
08388c79
DE
8444static int
8445remote_search_memory (struct target_ops* ops,
8446 CORE_ADDR start_addr, ULONGEST search_space_len,
8447 const gdb_byte *pattern, ULONGEST pattern_len,
8448 CORE_ADDR *found_addrp)
8449{
5af949e3 8450 int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
08388c79
DE
8451 struct remote_state *rs = get_remote_state ();
8452 int max_size = get_memory_write_packet_size ();
8453 struct packet_config *packet =
8454 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
8455 /* Number of packet bytes used to encode the pattern;
8456 this could be more than PATTERN_LEN due to escape characters. */
08388c79 8457 int escaped_pattern_len;
0df8b418 8458 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
8459 int used_pattern_len;
8460 int i;
8461 int found;
8462 ULONGEST found_addr;
8463
8464 /* Don't go to the target if we don't have to.
8465 This is done before checking packet->support to avoid the possibility that
8466 a success for this edge case means the facility works in general. */
8467 if (pattern_len > search_space_len)
8468 return 0;
8469 if (pattern_len == 0)
8470 {
8471 *found_addrp = start_addr;
8472 return 1;
8473 }
8474
8475 /* If we already know the packet isn't supported, fall back to the simple
8476 way of searching memory. */
8477
8478 if (packet->support == PACKET_DISABLE)
8479 {
8480 /* Target doesn't provided special support, fall back and use the
8481 standard support (copy memory and do the search here). */
8482 return simple_search_memory (ops, start_addr, search_space_len,
8483 pattern, pattern_len, found_addrp);
8484 }
8485
8486 /* Insert header. */
8487 i = snprintf (rs->buf, max_size,
8488 "qSearch:memory:%s;%s;",
5af949e3 8489 phex_nz (start_addr, addr_size),
08388c79
DE
8490 phex_nz (search_space_len, sizeof (search_space_len)));
8491 max_size -= (i + 1);
8492
8493 /* Escape as much data as fits into rs->buf. */
8494 escaped_pattern_len =
8495 remote_escape_output (pattern, pattern_len, (rs->buf + i),
8496 &used_pattern_len, max_size);
8497
8498 /* Bail if the pattern is too large. */
8499 if (used_pattern_len != pattern_len)
9b20d036 8500 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
8501
8502 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
8503 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
8504 || packet_ok (rs->buf, packet) != PACKET_OK)
8505 {
8506 /* The request may not have worked because the command is not
8507 supported. If so, fall back to the simple way. */
8508 if (packet->support == PACKET_DISABLE)
8509 {
8510 return simple_search_memory (ops, start_addr, search_space_len,
8511 pattern, pattern_len, found_addrp);
8512 }
8513 return -1;
8514 }
8515
8516 if (rs->buf[0] == '0')
8517 found = 0;
8518 else if (rs->buf[0] == '1')
8519 {
8520 found = 1;
8521 if (rs->buf[1] != ',')
10e0fa18 8522 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
8523 unpack_varlen_hex (rs->buf + 2, &found_addr);
8524 *found_addrp = found_addr;
8525 }
8526 else
10e0fa18 8527 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
8528
8529 return found;
8530}
8531
96baa820
JM
8532static void
8533remote_rcmd (char *command,
d9fcf2fb 8534 struct ui_file *outbuf)
96baa820 8535{
d01949b6 8536 struct remote_state *rs = get_remote_state ();
2e9f7625 8537 char *p = rs->buf;
96baa820
JM
8538
8539 if (!remote_desc)
8a3fe4f8 8540 error (_("remote rcmd is only available after target open"));
96baa820 8541
23860348 8542 /* Send a NULL command across as an empty command. */
7be570e7
JM
8543 if (command == NULL)
8544 command = "";
8545
23860348 8546 /* The query prefix. */
2e9f7625
DJ
8547 strcpy (rs->buf, "qRcmd,");
8548 p = strchr (rs->buf, '\0');
96baa820 8549
3e43a32a
MS
8550 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
8551 > get_remote_packet_size ())
8a3fe4f8 8552 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 8553
23860348 8554 /* Encode the actual command. */
cfd77fa1 8555 bin2hex ((gdb_byte *) command, p, 0);
96baa820 8556
6d820c5c 8557 if (putpkt (rs->buf) < 0)
8a3fe4f8 8558 error (_("Communication problem with target."));
96baa820
JM
8559
8560 /* get/display the response */
8561 while (1)
8562 {
2e9f7625
DJ
8563 char *buf;
8564
00bf0b85 8565 /* XXX - see also remote_get_noisy_reply(). */
2e9f7625 8566 rs->buf[0] = '\0';
6d820c5c 8567 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 8568 buf = rs->buf;
96baa820 8569 if (buf[0] == '\0')
8a3fe4f8 8570 error (_("Target does not support this command."));
96baa820
JM
8571 if (buf[0] == 'O' && buf[1] != 'K')
8572 {
23860348 8573 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
8574 continue;
8575 }
8576 if (strcmp (buf, "OK") == 0)
8577 break;
7be570e7
JM
8578 if (strlen (buf) == 3 && buf[0] == 'E'
8579 && isdigit (buf[1]) && isdigit (buf[2]))
8580 {
8a3fe4f8 8581 error (_("Protocol error with Rcmd"));
7be570e7 8582 }
96baa820
JM
8583 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
8584 {
8585 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 8586
96baa820
JM
8587 fputc_unfiltered (c, outbuf);
8588 }
8589 break;
8590 }
8591}
8592
fd79ecee
DJ
8593static VEC(mem_region_s) *
8594remote_memory_map (struct target_ops *ops)
8595{
8596 VEC(mem_region_s) *result = NULL;
8597 char *text = target_read_stralloc (&current_target,
8598 TARGET_OBJECT_MEMORY_MAP, NULL);
8599
8600 if (text)
8601 {
8602 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 8603
fd79ecee
DJ
8604 result = parse_memory_map (text);
8605 do_cleanups (back_to);
8606 }
8607
8608 return result;
8609}
8610
c906108c 8611static void
fba45db2 8612packet_command (char *args, int from_tty)
c906108c 8613{
d01949b6 8614 struct remote_state *rs = get_remote_state ();
c906108c 8615
c5aa993b 8616 if (!remote_desc)
8a3fe4f8 8617 error (_("command can only be used with remote target"));
c906108c 8618
c5aa993b 8619 if (!args)
8a3fe4f8 8620 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
8621
8622 puts_filtered ("sending: ");
8623 print_packet (args);
8624 puts_filtered ("\n");
8625 putpkt (args);
8626
6d820c5c 8627 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8628 puts_filtered ("received: ");
6d820c5c 8629 print_packet (rs->buf);
c906108c
SS
8630 puts_filtered ("\n");
8631}
8632
8633#if 0
23860348 8634/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 8635
a14ed312 8636static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 8637
a14ed312 8638static void threadset_test_cmd (char *cmd, int tty);
c906108c 8639
a14ed312 8640static void threadalive_test (char *cmd, int tty);
c906108c 8641
a14ed312 8642static void threadlist_test_cmd (char *cmd, int tty);
c906108c 8643
23860348 8644int get_and_display_threadinfo (threadref *ref);
c906108c 8645
a14ed312 8646static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 8647
23860348 8648static int thread_display_step (threadref *ref, void *context);
c906108c 8649
a14ed312 8650static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 8651
a14ed312 8652static void init_remote_threadtests (void);
c906108c 8653
23860348 8654#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
8655
8656static void
fba45db2 8657threadset_test_cmd (char *cmd, int tty)
c906108c
SS
8658{
8659 int sample_thread = SAMPLE_THREAD;
8660
a3f17187 8661 printf_filtered (_("Remote threadset test\n"));
79d7f229 8662 set_general_thread (sample_thread);
c906108c
SS
8663}
8664
8665
8666static void
fba45db2 8667threadalive_test (char *cmd, int tty)
c906108c
SS
8668{
8669 int sample_thread = SAMPLE_THREAD;
79d7f229
PA
8670 int pid = ptid_get_pid (inferior_ptid);
8671 ptid_t ptid = ptid_build (pid, 0, sample_thread);
c906108c 8672
79d7f229 8673 if (remote_thread_alive (ptid))
c906108c
SS
8674 printf_filtered ("PASS: Thread alive test\n");
8675 else
8676 printf_filtered ("FAIL: Thread alive test\n");
8677}
8678
23860348 8679void output_threadid (char *title, threadref *ref);
c906108c
SS
8680
8681void
fba45db2 8682output_threadid (char *title, threadref *ref)
c906108c
SS
8683{
8684 char hexid[20];
8685
23860348 8686 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
8687 hexid[16] = 0;
8688 printf_filtered ("%s %s\n", title, (&hexid[0]));
8689}
8690
8691static void
fba45db2 8692threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
8693{
8694 int startflag = 1;
8695 threadref nextthread;
8696 int done, result_count;
8697 threadref threadlist[3];
8698
8699 printf_filtered ("Remote Threadlist test\n");
8700 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
8701 &result_count, &threadlist[0]))
8702 printf_filtered ("FAIL: threadlist test\n");
8703 else
8704 {
8705 threadref *scan = threadlist;
8706 threadref *limit = scan + result_count;
8707
8708 while (scan < limit)
8709 output_threadid (" thread ", scan++);
8710 }
8711}
8712
8713void
fba45db2 8714display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
8715{
8716 output_threadid ("Threadid: ", &info->threadid);
8717 printf_filtered ("Name: %s\n ", info->shortname);
8718 printf_filtered ("State: %s\n", info->display);
8719 printf_filtered ("other: %s\n\n", info->more_display);
8720}
8721
8722int
fba45db2 8723get_and_display_threadinfo (threadref *ref)
c906108c
SS
8724{
8725 int result;
8726 int set;
8727 struct gdb_ext_thread_info threadinfo;
8728
8729 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
8730 | TAG_MOREDISPLAY | TAG_DISPLAY;
8731 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
8732 display_thread_info (&threadinfo);
8733 return result;
8734}
8735
8736static void
fba45db2 8737threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
8738{
8739 int athread = SAMPLE_THREAD;
8740 threadref thread;
8741 int set;
8742
8743 int_to_threadref (&thread, athread);
8744 printf_filtered ("Remote Threadinfo test\n");
8745 if (!get_and_display_threadinfo (&thread))
8746 printf_filtered ("FAIL cannot get thread info\n");
8747}
8748
8749static int
fba45db2 8750thread_display_step (threadref *ref, void *context)
c906108c
SS
8751{
8752 /* output_threadid(" threadstep ",ref); *//* simple test */
8753 return get_and_display_threadinfo (ref);
8754}
8755
8756static void
fba45db2 8757threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
8758{
8759 printf_filtered ("Remote Threadlist update test\n");
8760 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
8761}
8762
8763static void
8764init_remote_threadtests (void)
8765{
3e43a32a
MS
8766 add_com ("tlist", class_obscure, threadlist_test_cmd,
8767 _("Fetch and print the remote list of "
8768 "thread identifiers, one pkt only"));
c906108c 8769 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 8770 _("Fetch and display info about one thread"));
c906108c 8771 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 8772 _("Test setting to a different thread"));
c906108c 8773 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 8774 _("Iterate through updating all remote thread info"));
c906108c 8775 add_com ("talive", class_obscure, threadalive_test,
1bedd215 8776 _(" Remote thread alive test "));
c906108c
SS
8777}
8778
8779#endif /* 0 */
8780
f3fb8c85
MS
8781/* Convert a thread ID to a string. Returns the string in a static
8782 buffer. */
8783
8784static char *
117de6a9 8785remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 8786{
79d7f229 8787 static char buf[64];
82f73884 8788 struct remote_state *rs = get_remote_state ();
f3fb8c85 8789
ecd0ada5
PA
8790 if (ptid_is_pid (ptid))
8791 {
8792 /* Printing an inferior target id. */
8793
8794 /* When multi-process extensions are off, there's no way in the
8795 remote protocol to know the remote process id, if there's any
8796 at all. There's one exception --- when we're connected with
8797 target extended-remote, and we manually attached to a process
8798 with "attach PID". We don't record anywhere a flag that
8799 allows us to distinguish that case from the case of
8800 connecting with extended-remote and the stub already being
8801 attached to a process, and reporting yes to qAttached, hence
8802 no smart special casing here. */
8803 if (!remote_multi_process_p (rs))
8804 {
8805 xsnprintf (buf, sizeof buf, "Remote target");
8806 return buf;
8807 }
8808
8809 return normal_pid_to_str (ptid);
82f73884 8810 }
ecd0ada5 8811 else
79d7f229 8812 {
ecd0ada5
PA
8813 if (ptid_equal (magic_null_ptid, ptid))
8814 xsnprintf (buf, sizeof buf, "Thread <main>");
8815 else if (remote_multi_process_p (rs))
8816 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
8817 ptid_get_pid (ptid), ptid_get_tid (ptid));
8818 else
8819 xsnprintf (buf, sizeof buf, "Thread %ld",
8820 ptid_get_tid (ptid));
79d7f229
PA
8821 return buf;
8822 }
f3fb8c85
MS
8823}
8824
38691318
KB
8825/* Get the address of the thread local variable in OBJFILE which is
8826 stored at OFFSET within the thread local storage for thread PTID. */
8827
8828static CORE_ADDR
117de6a9
PA
8829remote_get_thread_local_address (struct target_ops *ops,
8830 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 8831{
444abaca 8832 if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
38691318
KB
8833 {
8834 struct remote_state *rs = get_remote_state ();
6d820c5c 8835 char *p = rs->buf;
82f73884 8836 char *endp = rs->buf + get_remote_packet_size ();
571dd617 8837 enum packet_result result;
38691318
KB
8838
8839 strcpy (p, "qGetTLSAddr:");
8840 p += strlen (p);
82f73884 8841 p = write_ptid (p, endp, ptid);
38691318
KB
8842 *p++ = ',';
8843 p += hexnumstr (p, offset);
8844 *p++ = ',';
8845 p += hexnumstr (p, lm);
8846 *p++ = '\0';
8847
6d820c5c
DJ
8848 putpkt (rs->buf);
8849 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
8850 result = packet_ok (rs->buf,
8851 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 8852 if (result == PACKET_OK)
38691318
KB
8853 {
8854 ULONGEST result;
8855
6d820c5c 8856 unpack_varlen_hex (rs->buf, &result);
38691318
KB
8857 return result;
8858 }
571dd617 8859 else if (result == PACKET_UNKNOWN)
109c3e39
AC
8860 throw_error (TLS_GENERIC_ERROR,
8861 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 8862 else
109c3e39
AC
8863 throw_error (TLS_GENERIC_ERROR,
8864 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
8865 }
8866 else
109c3e39
AC
8867 throw_error (TLS_GENERIC_ERROR,
8868 _("TLS not supported or disabled on this target"));
38691318
KB
8869 /* Not reached. */
8870 return 0;
8871}
8872
711e434b
PM
8873/* Provide thread local base, i.e. Thread Information Block address.
8874 Returns 1 if ptid is found and thread_local_base is non zero. */
8875
8876int
8877remote_get_tib_address (ptid_t ptid, CORE_ADDR *addr)
8878{
8879 if (remote_protocol_packets[PACKET_qGetTIBAddr].support != PACKET_DISABLE)
8880 {
8881 struct remote_state *rs = get_remote_state ();
8882 char *p = rs->buf;
8883 char *endp = rs->buf + get_remote_packet_size ();
8884 enum packet_result result;
8885
8886 strcpy (p, "qGetTIBAddr:");
8887 p += strlen (p);
8888 p = write_ptid (p, endp, ptid);
8889 *p++ = '\0';
8890
8891 putpkt (rs->buf);
8892 getpkt (&rs->buf, &rs->buf_size, 0);
8893 result = packet_ok (rs->buf,
8894 &remote_protocol_packets[PACKET_qGetTIBAddr]);
8895 if (result == PACKET_OK)
8896 {
8897 ULONGEST result;
8898
8899 unpack_varlen_hex (rs->buf, &result);
8900 if (addr)
8901 *addr = (CORE_ADDR) result;
8902 return 1;
8903 }
8904 else if (result == PACKET_UNKNOWN)
8905 error (_("Remote target doesn't support qGetTIBAddr packet"));
8906 else
8907 error (_("Remote target failed to process qGetTIBAddr request"));
8908 }
8909 else
8910 error (_("qGetTIBAddr not supported or disabled on this target"));
8911 /* Not reached. */
8912 return 0;
8913}
8914
29709017
DJ
8915/* Support for inferring a target description based on the current
8916 architecture and the size of a 'g' packet. While the 'g' packet
8917 can have any size (since optional registers can be left off the
8918 end), some sizes are easily recognizable given knowledge of the
8919 approximate architecture. */
8920
8921struct remote_g_packet_guess
8922{
8923 int bytes;
8924 const struct target_desc *tdesc;
8925};
8926typedef struct remote_g_packet_guess remote_g_packet_guess_s;
8927DEF_VEC_O(remote_g_packet_guess_s);
8928
8929struct remote_g_packet_data
8930{
8931 VEC(remote_g_packet_guess_s) *guesses;
8932};
8933
8934static struct gdbarch_data *remote_g_packet_data_handle;
8935
8936static void *
8937remote_g_packet_data_init (struct obstack *obstack)
8938{
8939 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
8940}
8941
8942void
8943register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
8944 const struct target_desc *tdesc)
8945{
8946 struct remote_g_packet_data *data
8947 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
8948 struct remote_g_packet_guess new_guess, *guess;
8949 int ix;
8950
8951 gdb_assert (tdesc != NULL);
8952
8953 for (ix = 0;
8954 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8955 ix++)
8956 if (guess->bytes == bytes)
8957 internal_error (__FILE__, __LINE__,
9b20d036 8958 _("Duplicate g packet description added for size %d"),
29709017
DJ
8959 bytes);
8960
8961 new_guess.bytes = bytes;
8962 new_guess.tdesc = tdesc;
8963 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
8964}
8965
d962ef82
DJ
8966/* Return 1 if remote_read_description would do anything on this target
8967 and architecture, 0 otherwise. */
8968
8969static int
8970remote_read_description_p (struct target_ops *target)
8971{
8972 struct remote_g_packet_data *data
8973 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
8974
8975 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8976 return 1;
8977
8978 return 0;
8979}
8980
29709017
DJ
8981static const struct target_desc *
8982remote_read_description (struct target_ops *target)
8983{
8984 struct remote_g_packet_data *data
1cf3db46 8985 = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
29709017 8986
d962ef82
DJ
8987 /* Do not try this during initial connection, when we do not know
8988 whether there is a running but stopped thread. */
8989 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
8990 return NULL;
8991
29709017
DJ
8992 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8993 {
8994 struct remote_g_packet_guess *guess;
8995 int ix;
8996 int bytes = send_g_packet ();
8997
8998 for (ix = 0;
8999 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9000 ix++)
9001 if (guess->bytes == bytes)
9002 return guess->tdesc;
9003
9004 /* We discard the g packet. A minor optimization would be to
9005 hold on to it, and fill the register cache once we have selected
9006 an architecture, but it's too tricky to do safely. */
9007 }
9008
9009 return NULL;
9010}
9011
a6b151f1
DJ
9012/* Remote file transfer support. This is host-initiated I/O, not
9013 target-initiated; for target-initiated, see remote-fileio.c. */
9014
9015/* If *LEFT is at least the length of STRING, copy STRING to
9016 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9017 decrease *LEFT. Otherwise raise an error. */
9018
9019static void
9020remote_buffer_add_string (char **buffer, int *left, char *string)
9021{
9022 int len = strlen (string);
9023
9024 if (len > *left)
9025 error (_("Packet too long for target."));
9026
9027 memcpy (*buffer, string, len);
9028 *buffer += len;
9029 *left -= len;
9030
9031 /* NUL-terminate the buffer as a convenience, if there is
9032 room. */
9033 if (*left)
9034 **buffer = '\0';
9035}
9036
9037/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
9038 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9039 decrease *LEFT. Otherwise raise an error. */
9040
9041static void
9042remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
9043 int len)
9044{
9045 if (2 * len > *left)
9046 error (_("Packet too long for target."));
9047
9048 bin2hex (bytes, *buffer, len);
9049 *buffer += 2 * len;
9050 *left -= 2 * len;
9051
9052 /* NUL-terminate the buffer as a convenience, if there is
9053 room. */
9054 if (*left)
9055 **buffer = '\0';
9056}
9057
9058/* If *LEFT is large enough, convert VALUE to hex and add it to
9059 *BUFFER, update *BUFFER to point to the new end of the buffer, and
9060 decrease *LEFT. Otherwise raise an error. */
9061
9062static void
9063remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
9064{
9065 int len = hexnumlen (value);
9066
9067 if (len > *left)
9068 error (_("Packet too long for target."));
9069
9070 hexnumstr (*buffer, value);
9071 *buffer += len;
9072 *left -= len;
9073
9074 /* NUL-terminate the buffer as a convenience, if there is
9075 room. */
9076 if (*left)
9077 **buffer = '\0';
9078}
9079
9080/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
9081 value, *REMOTE_ERRNO to the remote error number or zero if none
9082 was included, and *ATTACHMENT to point to the start of the annex
9083 if any. The length of the packet isn't needed here; there may
9084 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
9085
9086 Return 0 if the packet could be parsed, -1 if it could not. If
9087 -1 is returned, the other variables may not be initialized. */
9088
9089static int
9090remote_hostio_parse_result (char *buffer, int *retcode,
9091 int *remote_errno, char **attachment)
9092{
9093 char *p, *p2;
9094
9095 *remote_errno = 0;
9096 *attachment = NULL;
9097
9098 if (buffer[0] != 'F')
9099 return -1;
9100
9101 errno = 0;
9102 *retcode = strtol (&buffer[1], &p, 16);
9103 if (errno != 0 || p == &buffer[1])
9104 return -1;
9105
9106 /* Check for ",errno". */
9107 if (*p == ',')
9108 {
9109 errno = 0;
9110 *remote_errno = strtol (p + 1, &p2, 16);
9111 if (errno != 0 || p + 1 == p2)
9112 return -1;
9113 p = p2;
9114 }
9115
9116 /* Check for ";attachment". If there is no attachment, the
9117 packet should end here. */
9118 if (*p == ';')
9119 {
9120 *attachment = p + 1;
9121 return 0;
9122 }
9123 else if (*p == '\0')
9124 return 0;
9125 else
9126 return -1;
9127}
9128
9129/* Send a prepared I/O packet to the target and read its response.
9130 The prepared packet is in the global RS->BUF before this function
9131 is called, and the answer is there when we return.
9132
9133 COMMAND_BYTES is the length of the request to send, which may include
9134 binary data. WHICH_PACKET is the packet configuration to check
9135 before attempting a packet. If an error occurs, *REMOTE_ERRNO
9136 is set to the error number and -1 is returned. Otherwise the value
9137 returned by the function is returned.
9138
9139 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
9140 attachment is expected; an error will be reported if there's a
9141 mismatch. If one is found, *ATTACHMENT will be set to point into
9142 the packet buffer and *ATTACHMENT_LEN will be set to the
9143 attachment's length. */
9144
9145static int
9146remote_hostio_send_command (int command_bytes, int which_packet,
9147 int *remote_errno, char **attachment,
9148 int *attachment_len)
9149{
9150 struct remote_state *rs = get_remote_state ();
9151 int ret, bytes_read;
9152 char *attachment_tmp;
9153
f1838a98
UW
9154 if (!remote_desc
9155 || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
a6b151f1
DJ
9156 {
9157 *remote_errno = FILEIO_ENOSYS;
9158 return -1;
9159 }
9160
9161 putpkt_binary (rs->buf, command_bytes);
9162 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9163
9164 /* If it timed out, something is wrong. Don't try to parse the
9165 buffer. */
9166 if (bytes_read < 0)
9167 {
9168 *remote_errno = FILEIO_EINVAL;
9169 return -1;
9170 }
9171
9172 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
9173 {
9174 case PACKET_ERROR:
9175 *remote_errno = FILEIO_EINVAL;
9176 return -1;
9177 case PACKET_UNKNOWN:
9178 *remote_errno = FILEIO_ENOSYS;
9179 return -1;
9180 case PACKET_OK:
9181 break;
9182 }
9183
9184 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
9185 &attachment_tmp))
9186 {
9187 *remote_errno = FILEIO_EINVAL;
9188 return -1;
9189 }
9190
9191 /* Make sure we saw an attachment if and only if we expected one. */
9192 if ((attachment_tmp == NULL && attachment != NULL)
9193 || (attachment_tmp != NULL && attachment == NULL))
9194 {
9195 *remote_errno = FILEIO_EINVAL;
9196 return -1;
9197 }
9198
9199 /* If an attachment was found, it must point into the packet buffer;
9200 work out how many bytes there were. */
9201 if (attachment_tmp != NULL)
9202 {
9203 *attachment = attachment_tmp;
9204 *attachment_len = bytes_read - (*attachment - rs->buf);
9205 }
9206
9207 return ret;
9208}
9209
9210/* Open FILENAME on the remote target, using FLAGS and MODE. Return a
9211 remote file descriptor, or -1 if an error occurs (and set
9212 *REMOTE_ERRNO). */
9213
9214static int
9215remote_hostio_open (const char *filename, int flags, int mode,
9216 int *remote_errno)
9217{
9218 struct remote_state *rs = get_remote_state ();
9219 char *p = rs->buf;
9220 int left = get_remote_packet_size () - 1;
9221
9222 remote_buffer_add_string (&p, &left, "vFile:open:");
9223
9224 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9225 strlen (filename));
9226 remote_buffer_add_string (&p, &left, ",");
9227
9228 remote_buffer_add_int (&p, &left, flags);
9229 remote_buffer_add_string (&p, &left, ",");
9230
9231 remote_buffer_add_int (&p, &left, mode);
9232
9233 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
9234 remote_errno, NULL, NULL);
9235}
9236
9237/* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
9238 Return the number of bytes written, or -1 if an error occurs (and
9239 set *REMOTE_ERRNO). */
9240
9241static int
9242remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
9243 ULONGEST offset, int *remote_errno)
9244{
9245 struct remote_state *rs = get_remote_state ();
9246 char *p = rs->buf;
9247 int left = get_remote_packet_size ();
9248 int out_len;
9249
9250 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
9251
9252 remote_buffer_add_int (&p, &left, fd);
9253 remote_buffer_add_string (&p, &left, ",");
9254
9255 remote_buffer_add_int (&p, &left, offset);
9256 remote_buffer_add_string (&p, &left, ",");
9257
9258 p += remote_escape_output (write_buf, len, p, &out_len,
9259 get_remote_packet_size () - (p - rs->buf));
9260
9261 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
9262 remote_errno, NULL, NULL);
9263}
9264
9265/* Read up to LEN bytes FD on the remote target into READ_BUF
9266 Return the number of bytes read, or -1 if an error occurs (and
9267 set *REMOTE_ERRNO). */
9268
9269static int
9270remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
9271 ULONGEST offset, int *remote_errno)
9272{
9273 struct remote_state *rs = get_remote_state ();
9274 char *p = rs->buf;
9275 char *attachment;
9276 int left = get_remote_packet_size ();
9277 int ret, attachment_len;
9278 int read_len;
9279
9280 remote_buffer_add_string (&p, &left, "vFile:pread:");
9281
9282 remote_buffer_add_int (&p, &left, fd);
9283 remote_buffer_add_string (&p, &left, ",");
9284
9285 remote_buffer_add_int (&p, &left, len);
9286 remote_buffer_add_string (&p, &left, ",");
9287
9288 remote_buffer_add_int (&p, &left, offset);
9289
9290 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
9291 remote_errno, &attachment,
9292 &attachment_len);
9293
9294 if (ret < 0)
9295 return ret;
9296
9297 read_len = remote_unescape_input (attachment, attachment_len,
9298 read_buf, len);
9299 if (read_len != ret)
9300 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
9301
9302 return ret;
9303}
9304
9305/* Close FD on the remote target. Return 0, or -1 if an error occurs
9306 (and set *REMOTE_ERRNO). */
9307
9308static int
9309remote_hostio_close (int fd, int *remote_errno)
9310{
9311 struct remote_state *rs = get_remote_state ();
9312 char *p = rs->buf;
9313 int left = get_remote_packet_size () - 1;
9314
9315 remote_buffer_add_string (&p, &left, "vFile:close:");
9316
9317 remote_buffer_add_int (&p, &left, fd);
9318
9319 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
9320 remote_errno, NULL, NULL);
9321}
9322
9323/* Unlink FILENAME on the remote target. Return 0, or -1 if an error
9324 occurs (and set *REMOTE_ERRNO). */
9325
9326static int
9327remote_hostio_unlink (const char *filename, int *remote_errno)
9328{
9329 struct remote_state *rs = get_remote_state ();
9330 char *p = rs->buf;
9331 int left = get_remote_packet_size () - 1;
9332
9333 remote_buffer_add_string (&p, &left, "vFile:unlink:");
9334
9335 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
9336 strlen (filename));
9337
9338 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
9339 remote_errno, NULL, NULL);
9340}
9341
9342static int
9343remote_fileio_errno_to_host (int errnum)
9344{
9345 switch (errnum)
9346 {
9347 case FILEIO_EPERM:
9348 return EPERM;
9349 case FILEIO_ENOENT:
9350 return ENOENT;
9351 case FILEIO_EINTR:
9352 return EINTR;
9353 case FILEIO_EIO:
9354 return EIO;
9355 case FILEIO_EBADF:
9356 return EBADF;
9357 case FILEIO_EACCES:
9358 return EACCES;
9359 case FILEIO_EFAULT:
9360 return EFAULT;
9361 case FILEIO_EBUSY:
9362 return EBUSY;
9363 case FILEIO_EEXIST:
9364 return EEXIST;
9365 case FILEIO_ENODEV:
9366 return ENODEV;
9367 case FILEIO_ENOTDIR:
9368 return ENOTDIR;
9369 case FILEIO_EISDIR:
9370 return EISDIR;
9371 case FILEIO_EINVAL:
9372 return EINVAL;
9373 case FILEIO_ENFILE:
9374 return ENFILE;
9375 case FILEIO_EMFILE:
9376 return EMFILE;
9377 case FILEIO_EFBIG:
9378 return EFBIG;
9379 case FILEIO_ENOSPC:
9380 return ENOSPC;
9381 case FILEIO_ESPIPE:
9382 return ESPIPE;
9383 case FILEIO_EROFS:
9384 return EROFS;
9385 case FILEIO_ENOSYS:
9386 return ENOSYS;
9387 case FILEIO_ENAMETOOLONG:
9388 return ENAMETOOLONG;
9389 }
9390 return -1;
9391}
9392
9393static char *
9394remote_hostio_error (int errnum)
9395{
9396 int host_error = remote_fileio_errno_to_host (errnum);
9397
9398 if (host_error == -1)
9399 error (_("Unknown remote I/O error %d"), errnum);
9400 else
9401 error (_("Remote I/O error: %s"), safe_strerror (host_error));
9402}
9403
a6b151f1
DJ
9404static void
9405remote_hostio_close_cleanup (void *opaque)
9406{
9407 int fd = *(int *) opaque;
9408 int remote_errno;
9409
9410 remote_hostio_close (fd, &remote_errno);
9411}
9412
f1838a98
UW
9413
9414static void *
9415remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
9416{
9417 const char *filename = bfd_get_filename (abfd);
9418 int fd, remote_errno;
9419 int *stream;
9420
9421 gdb_assert (remote_filename_p (filename));
9422
9423 fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
9424 if (fd == -1)
9425 {
9426 errno = remote_fileio_errno_to_host (remote_errno);
9427 bfd_set_error (bfd_error_system_call);
9428 return NULL;
9429 }
9430
9431 stream = xmalloc (sizeof (int));
9432 *stream = fd;
9433 return stream;
9434}
9435
9436static int
9437remote_bfd_iovec_close (struct bfd *abfd, void *stream)
9438{
9439 int fd = *(int *)stream;
9440 int remote_errno;
9441
9442 xfree (stream);
9443
9444 /* Ignore errors on close; these may happen if the remote
9445 connection was already torn down. */
9446 remote_hostio_close (fd, &remote_errno);
9447
9448 return 1;
9449}
9450
9451static file_ptr
9452remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
9453 file_ptr nbytes, file_ptr offset)
9454{
9455 int fd = *(int *)stream;
9456 int remote_errno;
9457 file_ptr pos, bytes;
9458
9459 pos = 0;
9460 while (nbytes > pos)
9461 {
9462 bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
9463 offset + pos, &remote_errno);
9464 if (bytes == 0)
9465 /* Success, but no bytes, means end-of-file. */
9466 break;
9467 if (bytes == -1)
9468 {
9469 errno = remote_fileio_errno_to_host (remote_errno);
9470 bfd_set_error (bfd_error_system_call);
9471 return -1;
9472 }
9473
9474 pos += bytes;
9475 }
9476
9477 return pos;
9478}
9479
9480static int
9481remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
9482{
9483 /* FIXME: We should probably implement remote_hostio_stat. */
9484 sb->st_size = INT_MAX;
9485 return 0;
9486}
9487
9488int
9489remote_filename_p (const char *filename)
9490{
9491 return strncmp (filename, "remote:", 7) == 0;
9492}
9493
9494bfd *
9495remote_bfd_open (const char *remote_file, const char *target)
9496{
9497 return bfd_openr_iovec (remote_file, target,
9498 remote_bfd_iovec_open, NULL,
9499 remote_bfd_iovec_pread,
9500 remote_bfd_iovec_close,
9501 remote_bfd_iovec_stat);
9502}
9503
a6b151f1
DJ
9504void
9505remote_file_put (const char *local_file, const char *remote_file, int from_tty)
9506{
9507 struct cleanup *back_to, *close_cleanup;
9508 int retcode, fd, remote_errno, bytes, io_size;
9509 FILE *file;
9510 gdb_byte *buffer;
9511 int bytes_in_buffer;
9512 int saw_eof;
9513 ULONGEST offset;
9514
9515 if (!remote_desc)
9516 error (_("command can only be used with remote target"));
9517
9518 file = fopen (local_file, "rb");
9519 if (file == NULL)
9520 perror_with_name (local_file);
7c8a8b04 9521 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
9522
9523 fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
9524 | FILEIO_O_TRUNC),
9525 0700, &remote_errno);
9526 if (fd == -1)
9527 remote_hostio_error (remote_errno);
9528
9529 /* Send up to this many bytes at once. They won't all fit in the
9530 remote packet limit, so we'll transfer slightly fewer. */
9531 io_size = get_remote_packet_size ();
9532 buffer = xmalloc (io_size);
9533 make_cleanup (xfree, buffer);
9534
9535 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9536
9537 bytes_in_buffer = 0;
9538 saw_eof = 0;
9539 offset = 0;
9540 while (bytes_in_buffer || !saw_eof)
9541 {
9542 if (!saw_eof)
9543 {
3e43a32a
MS
9544 bytes = fread (buffer + bytes_in_buffer, 1,
9545 io_size - bytes_in_buffer,
a6b151f1
DJ
9546 file);
9547 if (bytes == 0)
9548 {
9549 if (ferror (file))
9550 error (_("Error reading %s."), local_file);
9551 else
9552 {
9553 /* EOF. Unless there is something still in the
9554 buffer from the last iteration, we are done. */
9555 saw_eof = 1;
9556 if (bytes_in_buffer == 0)
9557 break;
9558 }
9559 }
9560 }
9561 else
9562 bytes = 0;
9563
9564 bytes += bytes_in_buffer;
9565 bytes_in_buffer = 0;
9566
3e43a32a
MS
9567 retcode = remote_hostio_pwrite (fd, buffer, bytes,
9568 offset, &remote_errno);
a6b151f1
DJ
9569
9570 if (retcode < 0)
9571 remote_hostio_error (remote_errno);
9572 else if (retcode == 0)
9573 error (_("Remote write of %d bytes returned 0!"), bytes);
9574 else if (retcode < bytes)
9575 {
9576 /* Short write. Save the rest of the read data for the next
9577 write. */
9578 bytes_in_buffer = bytes - retcode;
9579 memmove (buffer, buffer + retcode, bytes_in_buffer);
9580 }
9581
9582 offset += retcode;
9583 }
9584
9585 discard_cleanups (close_cleanup);
9586 if (remote_hostio_close (fd, &remote_errno))
9587 remote_hostio_error (remote_errno);
9588
9589 if (from_tty)
9590 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
9591 do_cleanups (back_to);
9592}
9593
9594void
9595remote_file_get (const char *remote_file, const char *local_file, int from_tty)
9596{
9597 struct cleanup *back_to, *close_cleanup;
cea39f65 9598 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
9599 FILE *file;
9600 gdb_byte *buffer;
9601 ULONGEST offset;
9602
9603 if (!remote_desc)
9604 error (_("command can only be used with remote target"));
9605
9606 fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
9607 if (fd == -1)
9608 remote_hostio_error (remote_errno);
9609
9610 file = fopen (local_file, "wb");
9611 if (file == NULL)
9612 perror_with_name (local_file);
7c8a8b04 9613 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
9614
9615 /* Send up to this many bytes at once. They won't all fit in the
9616 remote packet limit, so we'll transfer slightly fewer. */
9617 io_size = get_remote_packet_size ();
9618 buffer = xmalloc (io_size);
9619 make_cleanup (xfree, buffer);
9620
9621 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
9622
9623 offset = 0;
9624 while (1)
9625 {
9626 bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
9627 if (bytes == 0)
9628 /* Success, but no bytes, means end-of-file. */
9629 break;
9630 if (bytes == -1)
9631 remote_hostio_error (remote_errno);
9632
9633 offset += bytes;
9634
9635 bytes = fwrite (buffer, 1, bytes, file);
9636 if (bytes == 0)
9637 perror_with_name (local_file);
9638 }
9639
9640 discard_cleanups (close_cleanup);
9641 if (remote_hostio_close (fd, &remote_errno))
9642 remote_hostio_error (remote_errno);
9643
9644 if (from_tty)
9645 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
9646 do_cleanups (back_to);
9647}
9648
9649void
9650remote_file_delete (const char *remote_file, int from_tty)
9651{
9652 int retcode, remote_errno;
9653
9654 if (!remote_desc)
9655 error (_("command can only be used with remote target"));
9656
9657 retcode = remote_hostio_unlink (remote_file, &remote_errno);
9658 if (retcode == -1)
9659 remote_hostio_error (remote_errno);
9660
9661 if (from_tty)
9662 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
9663}
9664
9665static void
9666remote_put_command (char *args, int from_tty)
9667{
9668 struct cleanup *back_to;
9669 char **argv;
9670
d1a41061
PP
9671 if (args == NULL)
9672 error_no_arg (_("file to put"));
9673
9674 argv = gdb_buildargv (args);
a6b151f1
DJ
9675 back_to = make_cleanup_freeargv (argv);
9676 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9677 error (_("Invalid parameters to remote put"));
9678
9679 remote_file_put (argv[0], argv[1], from_tty);
9680
9681 do_cleanups (back_to);
9682}
9683
9684static void
9685remote_get_command (char *args, int from_tty)
9686{
9687 struct cleanup *back_to;
9688 char **argv;
9689
d1a41061
PP
9690 if (args == NULL)
9691 error_no_arg (_("file to get"));
9692
9693 argv = gdb_buildargv (args);
a6b151f1
DJ
9694 back_to = make_cleanup_freeargv (argv);
9695 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
9696 error (_("Invalid parameters to remote get"));
9697
9698 remote_file_get (argv[0], argv[1], from_tty);
9699
9700 do_cleanups (back_to);
9701}
9702
9703static void
9704remote_delete_command (char *args, int from_tty)
9705{
9706 struct cleanup *back_to;
9707 char **argv;
9708
d1a41061
PP
9709 if (args == NULL)
9710 error_no_arg (_("file to delete"));
9711
9712 argv = gdb_buildargv (args);
a6b151f1
DJ
9713 back_to = make_cleanup_freeargv (argv);
9714 if (argv[0] == NULL || argv[1] != NULL)
9715 error (_("Invalid parameters to remote delete"));
9716
9717 remote_file_delete (argv[0], from_tty);
9718
9719 do_cleanups (back_to);
9720}
9721
9722static void
9723remote_command (char *args, int from_tty)
9724{
9725 help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
9726}
9727
b2175913
MS
9728static int
9729remote_can_execute_reverse (void)
9730{
40ab02ce
MS
9731 if (remote_protocol_packets[PACKET_bs].support == PACKET_ENABLE
9732 || remote_protocol_packets[PACKET_bc].support == PACKET_ENABLE)
9733 return 1;
9734 else
9735 return 0;
b2175913
MS
9736}
9737
74531fed
PA
9738static int
9739remote_supports_non_stop (void)
9740{
9741 return 1;
9742}
9743
03583c20
UW
9744static int
9745remote_supports_disable_randomization (void)
9746{
9747 /* Only supported in extended mode. */
9748 return 0;
9749}
9750
8a305172
PA
9751static int
9752remote_supports_multi_process (void)
9753{
9754 struct remote_state *rs = get_remote_state ();
a744cf53 9755
8a305172
PA
9756 return remote_multi_process_p (rs);
9757}
9758
782b2b07
SS
9759int
9760remote_supports_cond_tracepoints (void)
9761{
9762 struct remote_state *rs = get_remote_state ();
a744cf53 9763
782b2b07
SS
9764 return rs->cond_tracepoints;
9765}
9766
7a697b8d
SS
9767int
9768remote_supports_fast_tracepoints (void)
9769{
9770 struct remote_state *rs = get_remote_state ();
a744cf53 9771
7a697b8d
SS
9772 return rs->fast_tracepoints;
9773}
9774
0fb4aa4b
PA
9775static int
9776remote_supports_static_tracepoints (void)
9777{
9778 struct remote_state *rs = get_remote_state ();
9779
9780 return rs->static_tracepoints;
9781}
9782
1e4d1764
YQ
9783static int
9784remote_supports_install_in_trace (void)
9785{
9786 struct remote_state *rs = get_remote_state ();
9787
9788 return rs->install_in_trace;
9789}
9790
d248b706
KY
9791static int
9792remote_supports_enable_disable_tracepoint (void)
9793{
9794 struct remote_state *rs = get_remote_state ();
9795
9796 return rs->enable_disable_tracepoints;
9797}
9798
3065dfb6
SS
9799static int
9800remote_supports_string_tracing (void)
9801{
9802 struct remote_state *rs = get_remote_state ();
9803
9804 return rs->string_tracing;
9805}
9806
35b1e5cc 9807static void
ad91cd99 9808remote_trace_init (void)
35b1e5cc
SS
9809{
9810 putpkt ("QTinit");
9811 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 9812 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
9813 error (_("Target does not support this command."));
9814}
9815
9816static void free_actions_list (char **actions_list);
9817static void free_actions_list_cleanup_wrapper (void *);
9818static void
9819free_actions_list_cleanup_wrapper (void *al)
9820{
9821 free_actions_list (al);
9822}
9823
9824static void
9825free_actions_list (char **actions_list)
9826{
9827 int ndx;
9828
9829 if (actions_list == 0)
9830 return;
9831
9832 for (ndx = 0; actions_list[ndx]; ndx++)
9833 xfree (actions_list[ndx]);
9834
9835 xfree (actions_list);
9836}
9837
409873ef
SS
9838/* Recursive routine to walk through command list including loops, and
9839 download packets for each command. */
9840
9841static void
9842remote_download_command_source (int num, ULONGEST addr,
9843 struct command_line *cmds)
9844{
9845 struct remote_state *rs = get_remote_state ();
9846 struct command_line *cmd;
9847
9848 for (cmd = cmds; cmd; cmd = cmd->next)
9849 {
0df8b418 9850 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
9851 strcpy (rs->buf, "QTDPsrc:");
9852 encode_source_string (num, addr, "cmd", cmd->line,
9853 rs->buf + strlen (rs->buf),
9854 rs->buf_size - strlen (rs->buf));
9855 putpkt (rs->buf);
9856 remote_get_noisy_reply (&target_buf, &target_buf_size);
9857 if (strcmp (target_buf, "OK"))
9858 warning (_("Target does not support source download."));
9859
9860 if (cmd->control_type == while_control
9861 || cmd->control_type == while_stepping_control)
9862 {
9863 remote_download_command_source (num, addr, *cmd->body_list);
9864
0df8b418 9865 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
9866 strcpy (rs->buf, "QTDPsrc:");
9867 encode_source_string (num, addr, "cmd", "end",
9868 rs->buf + strlen (rs->buf),
9869 rs->buf_size - strlen (rs->buf));
9870 putpkt (rs->buf);
9871 remote_get_noisy_reply (&target_buf, &target_buf_size);
9872 if (strcmp (target_buf, "OK"))
9873 warning (_("Target does not support source download."));
9874 }
9875 }
9876}
9877
35b1e5cc 9878static void
e8ba3115 9879remote_download_tracepoint (struct bp_location *loc)
35b1e5cc 9880{
e8ba3115 9881
35b1e5cc 9882 CORE_ADDR tpaddr;
409873ef 9883 char addrbuf[40];
35b1e5cc
SS
9884 char buf[2048];
9885 char **tdp_actions;
9886 char **stepping_actions;
9887 int ndx;
9888 struct cleanup *old_chain = NULL;
9889 struct agent_expr *aexpr;
9890 struct cleanup *aexpr_chain = NULL;
9891 char *pkt;
e8ba3115 9892 struct breakpoint *b = loc->owner;
d9b3f62e 9893 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 9894
e8ba3115
YQ
9895 encode_actions (loc->owner, loc, &tdp_actions, &stepping_actions);
9896 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
9897 tdp_actions);
9898 (void) make_cleanup (free_actions_list_cleanup_wrapper,
9899 stepping_actions);
9900
9901 tpaddr = loc->address;
9902 sprintf_vma (addrbuf, tpaddr);
9903 sprintf (buf, "QTDP:%x:%s:%c:%lx:%x", b->number,
9904 addrbuf, /* address */
9905 (b->enable_state == bp_enabled ? 'E' : 'D'),
9906 t->step_count, t->pass_count);
9907 /* Fast tracepoints are mostly handled by the target, but we can
9908 tell the target how big of an instruction block should be moved
9909 around. */
9910 if (b->type == bp_fast_tracepoint)
9911 {
9912 /* Only test for support at download time; we may not know
9913 target capabilities at definition time. */
9914 if (remote_supports_fast_tracepoints ())
35b1e5cc 9915 {
e8ba3115 9916 int isize;
35b1e5cc 9917
e8ba3115
YQ
9918 if (gdbarch_fast_tracepoint_valid_at (target_gdbarch,
9919 tpaddr, &isize, NULL))
9920 sprintf (buf + strlen (buf), ":F%x", isize);
35b1e5cc 9921 else
e8ba3115
YQ
9922 /* If it passed validation at definition but fails now,
9923 something is very wrong. */
9924 internal_error (__FILE__, __LINE__,
9925 _("Fast tracepoint not "
9926 "valid during download"));
35b1e5cc 9927 }
e8ba3115
YQ
9928 else
9929 /* Fast tracepoints are functionally identical to regular
9930 tracepoints, so don't take lack of support as a reason to
9931 give up on the trace run. */
9932 warning (_("Target does not support fast tracepoints, "
9933 "downloading %d as regular tracepoint"), b->number);
9934 }
9935 else if (b->type == bp_static_tracepoint)
9936 {
9937 /* Only test for support at download time; we may not know
9938 target capabilities at definition time. */
9939 if (remote_supports_static_tracepoints ())
0fb4aa4b 9940 {
e8ba3115 9941 struct static_tracepoint_marker marker;
0fb4aa4b 9942
e8ba3115
YQ
9943 if (target_static_tracepoint_marker_at (tpaddr, &marker))
9944 strcat (buf, ":S");
0fb4aa4b 9945 else
e8ba3115 9946 error (_("Static tracepoint not valid during download"));
0fb4aa4b 9947 }
e8ba3115
YQ
9948 else
9949 /* Fast tracepoints are functionally identical to regular
9950 tracepoints, so don't take lack of support as a reason
9951 to give up on the trace run. */
9952 error (_("Target does not support static tracepoints"));
9953 }
9954 /* If the tracepoint has a conditional, make it into an agent
9955 expression and append to the definition. */
9956 if (loc->cond)
9957 {
9958 /* Only test support at download time, we may not know target
9959 capabilities at definition time. */
9960 if (remote_supports_cond_tracepoints ())
35b1e5cc 9961 {
e8ba3115
YQ
9962 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
9963 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
9964 sprintf (buf + strlen (buf), ":X%x,", aexpr->len);
9965 pkt = buf + strlen (buf);
9966 for (ndx = 0; ndx < aexpr->len; ++ndx)
9967 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
9968 *pkt = '\0';
9969 do_cleanups (aexpr_chain);
35b1e5cc 9970 }
e8ba3115
YQ
9971 else
9972 warning (_("Target does not support conditional tracepoints, "
9973 "ignoring tp %d cond"), b->number);
9974 }
35b1e5cc 9975
d9b3f62e 9976 if (b->commands || *default_collect)
e8ba3115
YQ
9977 strcat (buf, "-");
9978 putpkt (buf);
9979 remote_get_noisy_reply (&target_buf, &target_buf_size);
9980 if (strcmp (target_buf, "OK"))
9981 error (_("Target does not support tracepoints."));
35b1e5cc 9982
e8ba3115
YQ
9983 /* do_single_steps (t); */
9984 if (tdp_actions)
9985 {
9986 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 9987 {
e8ba3115
YQ
9988 QUIT; /* Allow user to bail out with ^C. */
9989 sprintf (buf, "QTDP:-%x:%s:%s%c",
9990 b->number, addrbuf, /* address */
9991 tdp_actions[ndx],
9992 ((tdp_actions[ndx + 1] || stepping_actions)
9993 ? '-' : 0));
9994 putpkt (buf);
9995 remote_get_noisy_reply (&target_buf,
9996 &target_buf_size);
9997 if (strcmp (target_buf, "OK"))
9998 error (_("Error on target while setting tracepoints."));
35b1e5cc 9999 }
e8ba3115
YQ
10000 }
10001 if (stepping_actions)
10002 {
10003 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 10004 {
e8ba3115
YQ
10005 QUIT; /* Allow user to bail out with ^C. */
10006 sprintf (buf, "QTDP:-%x:%s:%s%s%s",
10007 b->number, addrbuf, /* address */
10008 ((ndx == 0) ? "S" : ""),
10009 stepping_actions[ndx],
10010 (stepping_actions[ndx + 1] ? "-" : ""));
10011 putpkt (buf);
10012 remote_get_noisy_reply (&target_buf,
10013 &target_buf_size);
10014 if (strcmp (target_buf, "OK"))
10015 error (_("Error on target while setting tracepoints."));
35b1e5cc 10016 }
e8ba3115 10017 }
409873ef 10018
e8ba3115
YQ
10019 if (remote_protocol_packets[PACKET_TracepointSource].support
10020 == PACKET_ENABLE)
10021 {
10022 if (b->addr_string)
409873ef 10023 {
e8ba3115
YQ
10024 strcpy (buf, "QTDPsrc:");
10025 encode_source_string (b->number, loc->address,
10026 "at", b->addr_string, buf + strlen (buf),
10027 2048 - strlen (buf));
409873ef 10028
e8ba3115
YQ
10029 putpkt (buf);
10030 remote_get_noisy_reply (&target_buf, &target_buf_size);
10031 if (strcmp (target_buf, "OK"))
10032 warning (_("Target does not support source download."));
409873ef 10033 }
e8ba3115
YQ
10034 if (b->cond_string)
10035 {
10036 strcpy (buf, "QTDPsrc:");
10037 encode_source_string (b->number, loc->address,
10038 "cond", b->cond_string, buf + strlen (buf),
10039 2048 - strlen (buf));
10040 putpkt (buf);
10041 remote_get_noisy_reply (&target_buf, &target_buf_size);
10042 if (strcmp (target_buf, "OK"))
10043 warning (_("Target does not support source download."));
10044 }
10045 remote_download_command_source (b->number, loc->address,
10046 breakpoint_commands (b));
35b1e5cc 10047 }
e8ba3115
YQ
10048
10049 do_cleanups (old_chain);
35b1e5cc
SS
10050}
10051
1e4d1764
YQ
10052static int
10053remote_can_download_tracepoint (void)
10054{
10055 struct trace_status *ts = current_trace_status ();
10056 int status = remote_get_trace_status (ts);
10057
10058 if (status == -1 || !ts->running_known || !ts->running)
10059 return 0;
10060
10061 /* If we are in a tracing experiment, but remote stub doesn't support
10062 installing tracepoint in trace, we have to return. */
10063 if (!remote_supports_install_in_trace ())
10064 return 0;
10065
10066 return 1;
10067}
10068
10069
35b1e5cc
SS
10070static void
10071remote_download_trace_state_variable (struct trace_state_variable *tsv)
10072{
10073 struct remote_state *rs = get_remote_state ();
00bf0b85 10074 char *p;
35b1e5cc 10075
00bf0b85
SS
10076 sprintf (rs->buf, "QTDV:%x:%s:%x:",
10077 tsv->number, phex ((ULONGEST) tsv->initial_value, 8), tsv->builtin);
10078 p = rs->buf + strlen (rs->buf);
10079 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
10080 error (_("Trace state variable name too long for tsv definition packet"));
10081 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, 0);
10082 *p++ = '\0';
35b1e5cc
SS
10083 putpkt (rs->buf);
10084 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10085 if (*target_buf == '\0')
10086 error (_("Target does not support this command."));
10087 if (strcmp (target_buf, "OK") != 0)
10088 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
10089}
10090
d248b706
KY
10091static void
10092remote_enable_tracepoint (struct bp_location *location)
10093{
10094 struct remote_state *rs = get_remote_state ();
10095 char addr_buf[40];
10096
10097 sprintf_vma (addr_buf, location->address);
10098 sprintf (rs->buf, "QTEnable:%x:%s", location->owner->number, addr_buf);
10099 putpkt (rs->buf);
10100 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10101 if (*rs->buf == '\0')
10102 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
10103 if (strcmp (rs->buf, "OK") != 0)
10104 error (_("Error on target while enabling tracepoint."));
10105}
10106
10107static void
10108remote_disable_tracepoint (struct bp_location *location)
10109{
10110 struct remote_state *rs = get_remote_state ();
10111 char addr_buf[40];
10112
10113 sprintf_vma (addr_buf, location->address);
10114 sprintf (rs->buf, "QTDisable:%x:%s", location->owner->number, addr_buf);
10115 putpkt (rs->buf);
10116 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
10117 if (*rs->buf == '\0')
10118 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
10119 if (strcmp (rs->buf, "OK") != 0)
10120 error (_("Error on target while disabling tracepoint."));
10121}
10122
35b1e5cc 10123static void
ad91cd99 10124remote_trace_set_readonly_regions (void)
35b1e5cc
SS
10125{
10126 asection *s;
10127 bfd_size_type size;
608bcef2 10128 bfd_vma vma;
35b1e5cc 10129 int anysecs = 0;
c2fa21f1 10130 int offset = 0;
35b1e5cc
SS
10131
10132 if (!exec_bfd)
10133 return; /* No information to give. */
10134
10135 strcpy (target_buf, "QTro");
10136 for (s = exec_bfd->sections; s; s = s->next)
10137 {
10138 char tmp1[40], tmp2[40];
c2fa21f1 10139 int sec_length;
35b1e5cc
SS
10140
10141 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 10142 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
10143 (s->flags & SEC_READONLY) == 0)
10144 continue;
10145
10146 anysecs = 1;
608bcef2 10147 vma = bfd_get_section_vma (,s);
35b1e5cc 10148 size = bfd_get_section_size (s);
608bcef2
HZ
10149 sprintf_vma (tmp1, vma);
10150 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
10151 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
10152 if (offset + sec_length + 1 > target_buf_size)
10153 {
864ac8a7
HZ
10154 if (remote_protocol_packets[PACKET_qXfer_traceframe_info].support
10155 != PACKET_ENABLE)
10156 warning (_("\
c2fa21f1
HZ
10157Too many sections for read-only sections definition packet."));
10158 break;
10159 }
10160 sprintf (target_buf + offset, ":%s,%s", tmp1, tmp2);
10161 offset += sec_length;
35b1e5cc
SS
10162 }
10163 if (anysecs)
10164 {
10165 putpkt (target_buf);
10166 getpkt (&target_buf, &target_buf_size, 0);
10167 }
10168}
10169
10170static void
ad91cd99 10171remote_trace_start (void)
35b1e5cc
SS
10172{
10173 putpkt ("QTStart");
10174 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10175 if (*target_buf == '\0')
10176 error (_("Target does not support this command."));
10177 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10178 error (_("Bogus reply from target: %s"), target_buf);
10179}
10180
10181static int
00bf0b85 10182remote_get_trace_status (struct trace_status *ts)
35b1e5cc 10183{
953b98d1 10184 /* Initialize it just to avoid a GCC false warning. */
f652de6f 10185 char *p = NULL;
0df8b418 10186 /* FIXME we need to get register block size some other way. */
00bf0b85 10187 extern int trace_regblock_size;
67f41397 10188 volatile struct gdb_exception ex;
a744cf53 10189
00bf0b85
SS
10190 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
10191
35b1e5cc 10192 putpkt ("qTStatus");
67f41397
JK
10193
10194 TRY_CATCH (ex, RETURN_MASK_ERROR)
10195 {
10196 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
10197 }
10198 if (ex.reason < 0)
10199 {
10200 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
10201 return -1;
10202 }
00bf0b85
SS
10203
10204 /* If the remote target doesn't do tracing, flag it. */
10205 if (*p == '\0')
10206 return -1;
35b1e5cc 10207
00bf0b85
SS
10208 /* We're working with a live target. */
10209 ts->from_file = 0;
10210
10211 /* Set some defaults. */
10212 ts->running_known = 0;
10213 ts->stop_reason = trace_stop_reason_unknown;
10214 ts->traceframe_count = -1;
10215 ts->buffer_free = 0;
10216
10217 if (*p++ != 'T')
35b1e5cc
SS
10218 error (_("Bogus trace status reply from target: %s"), target_buf);
10219
00bf0b85
SS
10220 parse_trace_status (p, ts);
10221
10222 return ts->running;
35b1e5cc
SS
10223}
10224
f196051f
SS
10225void
10226remote_get_tracepoint_status (struct breakpoint *bp,
10227 struct uploaded_tp *utp)
10228{
10229 struct remote_state *rs = get_remote_state ();
f196051f
SS
10230 char *reply;
10231 struct bp_location *loc;
10232 struct tracepoint *tp = (struct tracepoint *) bp;
10233
10234 if (tp)
10235 {
10236 tp->base.hit_count = 0;
10237 tp->traceframe_usage = 0;
10238 for (loc = tp->base.loc; loc; loc = loc->next)
10239 {
10240 /* If the tracepoint was never downloaded, don't go asking for
10241 any status. */
10242 if (tp->number_on_target == 0)
10243 continue;
2bf50f6f
JB
10244 sprintf (rs->buf, "qTP:%x:%s", tp->number_on_target,
10245 phex_nz (loc->address, 0));
f196051f
SS
10246 putpkt (rs->buf);
10247 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10248 if (reply && *reply)
10249 {
10250 if (*reply == 'V')
10251 parse_tracepoint_status (reply + 1, bp, utp);
10252 }
10253 }
10254 }
10255 else if (utp)
10256 {
10257 utp->hit_count = 0;
10258 utp->traceframe_usage = 0;
2bf50f6f 10259 sprintf (rs->buf, "qTP:%x:%s", utp->number, phex_nz (utp->addr, 0));
f196051f
SS
10260 putpkt (rs->buf);
10261 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10262 if (reply && *reply)
10263 {
10264 if (*reply == 'V')
10265 parse_tracepoint_status (reply + 1, bp, utp);
10266 }
10267 }
10268}
10269
35b1e5cc 10270static void
ad91cd99 10271remote_trace_stop (void)
35b1e5cc
SS
10272{
10273 putpkt ("QTStop");
10274 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
10275 if (*target_buf == '\0')
10276 error (_("Target does not support this command."));
10277 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
10278 error (_("Bogus reply from target: %s"), target_buf);
10279}
10280
10281static int
10282remote_trace_find (enum trace_find_type type, int num,
10283 ULONGEST addr1, ULONGEST addr2,
10284 int *tpp)
10285{
10286 struct remote_state *rs = get_remote_state ();
10287 char *p, *reply;
10288 int target_frameno = -1, target_tracept = -1;
10289
e6e4e701
PA
10290 /* Lookups other than by absolute frame number depend on the current
10291 trace selected, so make sure it is correct on the remote end
10292 first. */
10293 if (type != tfind_number)
10294 set_remote_traceframe ();
10295
35b1e5cc
SS
10296 p = rs->buf;
10297 strcpy (p, "QTFrame:");
10298 p = strchr (p, '\0');
10299 switch (type)
10300 {
10301 case tfind_number:
10302 sprintf (p, "%x", num);
10303 break;
10304 case tfind_pc:
00bf0b85 10305 sprintf (p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
10306 break;
10307 case tfind_tp:
10308 sprintf (p, "tdp:%x", num);
10309 break;
10310 case tfind_range:
00bf0b85 10311 sprintf (p, "range:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
35b1e5cc
SS
10312 break;
10313 case tfind_outside:
00bf0b85 10314 sprintf (p, "outside:%s:%s", phex_nz (addr1, 0), phex_nz (addr2, 0));
35b1e5cc
SS
10315 break;
10316 default:
9b20d036 10317 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
10318 }
10319
10320 putpkt (rs->buf);
10321 reply = remote_get_noisy_reply (&(rs->buf), &sizeof_pkt);
ad91cd99
PA
10322 if (*reply == '\0')
10323 error (_("Target does not support this command."));
35b1e5cc
SS
10324
10325 while (reply && *reply)
10326 switch (*reply)
10327 {
10328 case 'F':
f197e0f1
VP
10329 p = ++reply;
10330 target_frameno = (int) strtol (p, &reply, 16);
10331 if (reply == p)
10332 error (_("Unable to parse trace frame number"));
e6e4e701
PA
10333 /* Don't update our remote traceframe number cache on failure
10334 to select a remote traceframe. */
f197e0f1
VP
10335 if (target_frameno == -1)
10336 return -1;
35b1e5cc
SS
10337 break;
10338 case 'T':
f197e0f1
VP
10339 p = ++reply;
10340 target_tracept = (int) strtol (p, &reply, 16);
10341 if (reply == p)
10342 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
10343 break;
10344 case 'O': /* "OK"? */
10345 if (reply[1] == 'K' && reply[2] == '\0')
10346 reply += 2;
10347 else
10348 error (_("Bogus reply from target: %s"), reply);
10349 break;
10350 default:
10351 error (_("Bogus reply from target: %s"), reply);
10352 }
10353 if (tpp)
10354 *tpp = target_tracept;
e6e4e701
PA
10355
10356 remote_traceframe_number = target_frameno;
35b1e5cc
SS
10357 return target_frameno;
10358}
10359
10360static int
10361remote_get_trace_state_variable_value (int tsvnum, LONGEST *val)
10362{
10363 struct remote_state *rs = get_remote_state ();
10364 char *reply;
10365 ULONGEST uval;
10366
e6e4e701
PA
10367 set_remote_traceframe ();
10368
35b1e5cc
SS
10369 sprintf (rs->buf, "qTV:%x", tsvnum);
10370 putpkt (rs->buf);
10371 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10372 if (reply && *reply)
10373 {
10374 if (*reply == 'V')
10375 {
10376 unpack_varlen_hex (reply + 1, &uval);
10377 *val = (LONGEST) uval;
10378 return 1;
10379 }
10380 }
10381 return 0;
10382}
10383
00bf0b85 10384static int
011aacb0 10385remote_save_trace_data (const char *filename)
00bf0b85
SS
10386{
10387 struct remote_state *rs = get_remote_state ();
10388 char *p, *reply;
10389
10390 p = rs->buf;
10391 strcpy (p, "QTSave:");
10392 p += strlen (p);
10393 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
10394 error (_("Remote file name too long for trace save packet"));
10395 p += 2 * bin2hex ((gdb_byte *) filename, p, 0);
10396 *p++ = '\0';
10397 putpkt (rs->buf);
ad91cd99 10398 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 10399 if (*reply == '\0')
ad91cd99
PA
10400 error (_("Target does not support this command."));
10401 if (strcmp (reply, "OK") != 0)
10402 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
10403 return 0;
10404}
10405
10406/* This is basically a memory transfer, but needs to be its own packet
10407 because we don't know how the target actually organizes its trace
10408 memory, plus we want to be able to ask for as much as possible, but
10409 not be unhappy if we don't get as much as we ask for. */
10410
10411static LONGEST
10412remote_get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
10413{
10414 struct remote_state *rs = get_remote_state ();
10415 char *reply;
10416 char *p;
10417 int rslt;
10418
10419 p = rs->buf;
10420 strcpy (p, "qTBuffer:");
10421 p += strlen (p);
10422 p += hexnumstr (p, offset);
10423 *p++ = ',';
10424 p += hexnumstr (p, len);
10425 *p++ = '\0';
10426
10427 putpkt (rs->buf);
10428 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10429 if (reply && *reply)
10430 {
10431 /* 'l' by itself means we're at the end of the buffer and
10432 there is nothing more to get. */
10433 if (*reply == 'l')
10434 return 0;
10435
10436 /* Convert the reply into binary. Limit the number of bytes to
10437 convert according to our passed-in buffer size, rather than
10438 what was returned in the packet; if the target is
10439 unexpectedly generous and gives us a bigger reply than we
10440 asked for, we don't want to crash. */
10441 rslt = hex2bin (target_buf, buf, len);
10442 return rslt;
10443 }
10444
10445 /* Something went wrong, flag as an error. */
10446 return -1;
10447}
10448
35b1e5cc
SS
10449static void
10450remote_set_disconnected_tracing (int val)
10451{
10452 struct remote_state *rs = get_remote_state ();
10453
33da3f1c
SS
10454 if (rs->disconnected_tracing)
10455 {
ad91cd99
PA
10456 char *reply;
10457
33da3f1c
SS
10458 sprintf (rs->buf, "QTDisconnected:%x", val);
10459 putpkt (rs->buf);
ad91cd99
PA
10460 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10461 if (*reply == '\0')
33da3f1c 10462 error (_("Target does not support this command."));
ad91cd99
PA
10463 if (strcmp (reply, "OK") != 0)
10464 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
10465 }
10466 else if (val)
10467 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
10468}
10469
dc146f7c
VP
10470static int
10471remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
10472{
10473 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 10474
dc146f7c
VP
10475 if (info && info->private)
10476 return info->private->core;
10477 return -1;
10478}
10479
4daf5ac0
SS
10480static void
10481remote_set_circular_trace_buffer (int val)
10482{
10483 struct remote_state *rs = get_remote_state ();
ad91cd99 10484 char *reply;
4daf5ac0
SS
10485
10486 sprintf (rs->buf, "QTBuffer:circular:%x", val);
10487 putpkt (rs->buf);
ad91cd99
PA
10488 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10489 if (*reply == '\0')
4daf5ac0 10490 error (_("Target does not support this command."));
ad91cd99
PA
10491 if (strcmp (reply, "OK") != 0)
10492 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
10493}
10494
b3b9301e
PA
10495static struct traceframe_info *
10496remote_traceframe_info (void)
10497{
10498 char *text;
10499
10500 text = target_read_stralloc (&current_target,
10501 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
10502 if (text != NULL)
10503 {
10504 struct traceframe_info *info;
10505 struct cleanup *back_to = make_cleanup (xfree, text);
10506
10507 info = parse_traceframe_info (text);
10508 do_cleanups (back_to);
10509 return info;
10510 }
10511
10512 return NULL;
10513}
10514
405f8e94
SS
10515/* Handle the qTMinFTPILen packet. Returns the minimum length of
10516 instruction on which a fast tracepoint may be placed. Returns -1
10517 if the packet is not supported, and 0 if the minimum instruction
10518 length is unknown. */
10519
10520static int
10521remote_get_min_fast_tracepoint_insn_len (void)
10522{
10523 struct remote_state *rs = get_remote_state ();
10524 char *reply;
10525
10526 sprintf (rs->buf, "qTMinFTPILen");
10527 putpkt (rs->buf);
10528 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10529 if (*reply == '\0')
10530 return -1;
10531 else
10532 {
10533 ULONGEST min_insn_len;
10534
10535 unpack_varlen_hex (reply, &min_insn_len);
10536
10537 return (int) min_insn_len;
10538 }
10539}
10540
f196051f
SS
10541static int
10542remote_set_trace_notes (char *user, char *notes, char *stop_notes)
10543{
10544 struct remote_state *rs = get_remote_state ();
10545 char *reply;
10546 char *buf = rs->buf;
10547 char *endbuf = rs->buf + get_remote_packet_size ();
10548 int nbytes;
10549
10550 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
10551 if (user)
10552 {
10553 buf += xsnprintf (buf, endbuf - buf, "user:");
10554 nbytes = bin2hex (user, buf, 0);
10555 buf += 2 * nbytes;
10556 *buf++ = ';';
10557 }
10558 if (notes)
10559 {
10560 buf += xsnprintf (buf, endbuf - buf, "notes:");
10561 nbytes = bin2hex (notes, buf, 0);
10562 buf += 2 * nbytes;
10563 *buf++ = ';';
10564 }
10565 if (stop_notes)
10566 {
10567 buf += xsnprintf (buf, endbuf - buf, "tstop:");
10568 nbytes = bin2hex (stop_notes, buf, 0);
10569 buf += 2 * nbytes;
10570 *buf++ = ';';
10571 }
10572 /* Ensure the buffer is terminated. */
10573 *buf = '\0';
10574
10575 putpkt (rs->buf);
10576 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
10577 if (*reply == '\0')
10578 return 0;
10579
10580 if (strcmp (reply, "OK") != 0)
10581 error (_("Bogus reply from target: %s"), reply);
10582
10583 return 1;
10584}
10585
c906108c 10586static void
fba45db2 10587init_remote_ops (void)
c906108c 10588{
c5aa993b 10589 remote_ops.to_shortname = "remote";
c906108c 10590 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 10591 remote_ops.to_doc =
c906108c 10592 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
10593Specify the serial device it is connected to\n\
10594(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
10595 remote_ops.to_open = remote_open;
10596 remote_ops.to_close = remote_close;
c906108c 10597 remote_ops.to_detach = remote_detach;
6ad8ae5c 10598 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 10599 remote_ops.to_resume = remote_resume;
c906108c
SS
10600 remote_ops.to_wait = remote_wait;
10601 remote_ops.to_fetch_registers = remote_fetch_registers;
10602 remote_ops.to_store_registers = remote_store_registers;
10603 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c8e73a31 10604 remote_ops.deprecated_xfer_memory = remote_xfer_memory;
c5aa993b 10605 remote_ops.to_files_info = remote_files_info;
c906108c
SS
10606 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
10607 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
3c3bea1c
GS
10608 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
10609 remote_ops.to_stopped_data_address = remote_stopped_data_address;
10610 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
10611 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
10612 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
10613 remote_ops.to_region_ok_for_hw_watchpoint
10614 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
10615 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
10616 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b
JM
10617 remote_ops.to_kill = remote_kill;
10618 remote_ops.to_load = generic_load;
c906108c 10619 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 10620 remote_ops.to_pass_signals = remote_pass_signals;
c906108c 10621 remote_ops.to_thread_alive = remote_thread_alive;
0f71a2f6 10622 remote_ops.to_find_new_threads = remote_threads_info;
0caabb7e 10623 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 10624 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 10625 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 10626 remote_ops.to_stop = remote_stop;
4b8a223f 10627 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 10628 remote_ops.to_rcmd = remote_rcmd;
49d03eab 10629 remote_ops.to_log_command = serial_log_command;
38691318 10630 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 10631 remote_ops.to_stratum = process_stratum;
c35b1492
PA
10632 remote_ops.to_has_all_memory = default_child_has_all_memory;
10633 remote_ops.to_has_memory = default_child_has_memory;
10634 remote_ops.to_has_stack = default_child_has_stack;
10635 remote_ops.to_has_registers = default_child_has_registers;
10636 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 10637 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 10638 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 10639 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 10640 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
10641 remote_ops.to_flash_erase = remote_flash_erase;
10642 remote_ops.to_flash_done = remote_flash_done;
29709017 10643 remote_ops.to_read_description = remote_read_description;
08388c79 10644 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
10645 remote_ops.to_can_async_p = remote_can_async_p;
10646 remote_ops.to_is_async_p = remote_is_async_p;
10647 remote_ops.to_async = remote_async;
75c99385
PA
10648 remote_ops.to_terminal_inferior = remote_terminal_inferior;
10649 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 10650 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 10651 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
10652 remote_ops.to_supports_disable_randomization
10653 = remote_supports_disable_randomization;
d248b706 10654 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 10655 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
35b1e5cc
SS
10656 remote_ops.to_trace_init = remote_trace_init;
10657 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 10658 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
10659 remote_ops.to_download_trace_state_variable
10660 = remote_download_trace_state_variable;
d248b706
KY
10661 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
10662 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
10663 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
10664 remote_ops.to_trace_start = remote_trace_start;
10665 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 10666 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
10667 remote_ops.to_trace_stop = remote_trace_stop;
10668 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
10669 remote_ops.to_get_trace_state_variable_value
10670 = remote_get_trace_state_variable_value;
00bf0b85
SS
10671 remote_ops.to_save_trace_data = remote_save_trace_data;
10672 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
10673 remote_ops.to_upload_trace_state_variables
10674 = remote_upload_trace_state_variables;
00bf0b85 10675 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 10676 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 10677 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 10678 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f196051f 10679 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 10680 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 10681 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 10682 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 10683 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
10684 remote_ops.to_static_tracepoint_marker_at
10685 = remote_static_tracepoint_marker_at;
10686 remote_ops.to_static_tracepoint_markers_by_strid
10687 = remote_static_tracepoint_markers_by_strid;
b3b9301e 10688 remote_ops.to_traceframe_info = remote_traceframe_info;
c906108c
SS
10689}
10690
10691/* Set up the extended remote vector by making a copy of the standard
10692 remote vector and adding to it. */
10693
10694static void
fba45db2 10695init_extended_remote_ops (void)
c906108c
SS
10696{
10697 extended_remote_ops = remote_ops;
10698
0f71a2f6 10699 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 10700 extended_remote_ops.to_longname =
c906108c 10701 "Extended remote serial target in gdb-specific protocol";
c5aa993b 10702 extended_remote_ops.to_doc =
c906108c 10703 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
10704Specify the serial device it is connected to (e.g. /dev/ttya).";
10705 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
10706 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
10707 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
10708 extended_remote_ops.to_detach = extended_remote_detach;
10709 extended_remote_ops.to_attach = extended_remote_attach;
82f73884 10710 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
10711 extended_remote_ops.to_supports_disable_randomization
10712 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
10713}
10714
6426a772
JM
10715static int
10716remote_can_async_p (void)
10717{
c6ebd6cf 10718 if (!target_async_permitted)
75c99385
PA
10719 /* We only enable async when the user specifically asks for it. */
10720 return 0;
10721
23860348 10722 /* We're async whenever the serial device is. */
3dd5b83d 10723 return serial_can_async_p (remote_desc);
6426a772
JM
10724}
10725
10726static int
10727remote_is_async_p (void)
10728{
c6ebd6cf 10729 if (!target_async_permitted)
75c99385
PA
10730 /* We only enable async when the user specifically asks for it. */
10731 return 0;
10732
23860348 10733 /* We're async whenever the serial device is. */
3dd5b83d 10734 return serial_is_async_p (remote_desc);
6426a772
JM
10735}
10736
2acceee2
JM
10737/* Pass the SERIAL event on and up to the client. One day this code
10738 will be able to delay notifying the client of an event until the
23860348 10739 point where an entire packet has been received. */
2acceee2 10740
2bc416ba 10741static void (*async_client_callback) (enum inferior_event_type event_type,
23860348 10742 void *context);
2acceee2
JM
10743static void *async_client_context;
10744static serial_event_ftype remote_async_serial_handler;
10745
6426a772 10746static void
819cc324 10747remote_async_serial_handler (struct serial *scb, void *context)
6426a772 10748{
2acceee2
JM
10749 /* Don't propogate error information up to the client. Instead let
10750 the client find out about the error by querying the target. */
10751 async_client_callback (INF_REG_EVENT, async_client_context);
10752}
10753
74531fed
PA
10754static void
10755remote_async_inferior_event_handler (gdb_client_data data)
10756{
10757 inferior_event_handler (INF_REG_EVENT, NULL);
10758}
10759
10760static void
10761remote_async_get_pending_events_handler (gdb_client_data data)
10762{
10763 remote_get_pending_stop_replies ();
10764}
10765
2acceee2 10766static void
2bc416ba 10767remote_async (void (*callback) (enum inferior_event_type event_type,
23860348 10768 void *context), void *context)
2acceee2
JM
10769{
10770 if (callback != NULL)
10771 {
2cd58942 10772 serial_async (remote_desc, remote_async_serial_handler, NULL);
2acceee2
JM
10773 async_client_callback = callback;
10774 async_client_context = context;
10775 }
10776 else
2cd58942 10777 serial_async (remote_desc, NULL, NULL);
6426a772
JM
10778}
10779
5a2468f5 10780static void
c2d11a7d 10781set_remote_cmd (char *args, int from_tty)
5a2468f5 10782{
427c3a89 10783 help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
5a2468f5
JM
10784}
10785
d471ea57
AC
10786static void
10787show_remote_cmd (char *args, int from_tty)
10788{
37a105a1 10789 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 10790 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
10791 struct cleanup *showlist_chain;
10792 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 10793 struct ui_out *uiout = current_uiout;
37a105a1
DJ
10794
10795 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
10796 for (; list != NULL; list = list->next)
10797 if (strcmp (list->name, "Z-packet") == 0)
10798 continue;
427c3a89
DJ
10799 else if (list->type == not_set_cmd)
10800 /* Alias commands are exactly like the original, except they
10801 don't have the normal type. */
10802 continue;
10803 else
37a105a1
DJ
10804 {
10805 struct cleanup *option_chain
10806 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 10807
37a105a1
DJ
10808 ui_out_field_string (uiout, "name", list->name);
10809 ui_out_text (uiout, ": ");
427c3a89
DJ
10810 if (list->type == show_cmd)
10811 do_setshow_command ((char *) NULL, from_tty, list);
10812 else
10813 cmd_func (list, NULL, from_tty);
37a105a1
DJ
10814 /* Close the tuple. */
10815 do_cleanups (option_chain);
10816 }
427c3a89
DJ
10817
10818 /* Close the tuple. */
10819 do_cleanups (showlist_chain);
d471ea57 10820}
5a2468f5 10821
0f71a2f6 10822
23860348 10823/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
10824static void
10825remote_new_objfile (struct objfile *objfile)
10826{
23860348 10827 if (remote_desc != 0) /* Have a remote connection. */
06d3b283 10828 remote_check_symbols (objfile);
dc8acb97
MS
10829}
10830
00bf0b85
SS
10831/* Pull all the tracepoints defined on the target and create local
10832 data structures representing them. We don't want to create real
10833 tracepoints yet, we don't want to mess up the user's existing
10834 collection. */
10835
10836static int
10837remote_upload_tracepoints (struct uploaded_tp **utpp)
d5551862 10838{
00bf0b85
SS
10839 struct remote_state *rs = get_remote_state ();
10840 char *p;
d5551862 10841
00bf0b85
SS
10842 /* Ask for a first packet of tracepoint definition. */
10843 putpkt ("qTfP");
10844 getpkt (&rs->buf, &rs->buf_size, 0);
10845 p = rs->buf;
10846 while (*p && *p != 'l')
d5551862 10847 {
00bf0b85
SS
10848 parse_tracepoint_definition (p, utpp);
10849 /* Ask for another packet of tracepoint definition. */
10850 putpkt ("qTsP");
10851 getpkt (&rs->buf, &rs->buf_size, 0);
10852 p = rs->buf;
d5551862 10853 }
00bf0b85 10854 return 0;
d5551862
SS
10855}
10856
00bf0b85
SS
10857static int
10858remote_upload_trace_state_variables (struct uploaded_tsv **utsvp)
d5551862 10859{
00bf0b85 10860 struct remote_state *rs = get_remote_state ();
d5551862 10861 char *p;
d5551862 10862
00bf0b85
SS
10863 /* Ask for a first packet of variable definition. */
10864 putpkt ("qTfV");
d5551862
SS
10865 getpkt (&rs->buf, &rs->buf_size, 0);
10866 p = rs->buf;
00bf0b85 10867 while (*p && *p != 'l')
d5551862 10868 {
00bf0b85
SS
10869 parse_tsv_definition (p, utsvp);
10870 /* Ask for another packet of variable definition. */
10871 putpkt ("qTsV");
d5551862
SS
10872 getpkt (&rs->buf, &rs->buf_size, 0);
10873 p = rs->buf;
10874 }
00bf0b85 10875 return 0;
d5551862
SS
10876}
10877
c906108c 10878void
fba45db2 10879_initialize_remote (void)
c906108c 10880{
ea9c271d 10881 struct remote_state *rs;
9a7071a8
JB
10882 struct cmd_list_element *cmd;
10883 char *cmd_name;
ea9c271d 10884
0f71a2f6 10885 /* architecture specific data */
2bc416ba 10886 remote_gdbarch_data_handle =
23860348 10887 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
10888 remote_g_packet_data_handle =
10889 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 10890
ea9c271d
DJ
10891 /* Initialize the per-target state. At the moment there is only one
10892 of these, not one per target. Only one target is active at a
10893 time. The default buffer size is unimportant; it will be expanded
10894 whenever a larger buffer is needed. */
0b83947e 10895 rs = get_remote_state_raw ();
ea9c271d
DJ
10896 rs->buf_size = 400;
10897 rs->buf = xmalloc (rs->buf_size);
10898
c906108c
SS
10899 init_remote_ops ();
10900 add_target (&remote_ops);
10901
10902 init_extended_remote_ops ();
10903 add_target (&extended_remote_ops);
cce74817 10904
dc8acb97 10905 /* Hook into new objfile notification. */
06d3b283 10906 observer_attach_new_objfile (remote_new_objfile);
dc8acb97 10907
b803fb0f
DJ
10908 /* Set up signal handlers. */
10909 sigint_remote_token =
10910 create_async_signal_handler (async_remote_interrupt, NULL);
10911 sigint_remote_twice_token =
6d549500 10912 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 10913
c906108c
SS
10914#if 0
10915 init_remote_threadtests ();
10916#endif
10917
23860348 10918 /* set/show remote ... */
d471ea57 10919
1bedd215 10920 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
10921Remote protocol specific variables\n\
10922Configure various remote-protocol specific variables such as\n\
1bedd215 10923the packets being used"),
cff3e48b 10924 &remote_set_cmdlist, "set remote ",
23860348 10925 0 /* allow-unknown */, &setlist);
1bedd215 10926 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
10927Remote protocol specific variables\n\
10928Configure various remote-protocol specific variables such as\n\
1bedd215 10929the packets being used"),
cff3e48b 10930 &remote_show_cmdlist, "show remote ",
23860348 10931 0 /* allow-unknown */, &showlist);
5a2468f5 10932
1a966eab
AC
10933 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
10934Compare section data on target to the exec file.\n\
10935Argument is a single section name (default: all loaded sections)."),
c906108c
SS
10936 &cmdlist);
10937
1a966eab
AC
10938 add_cmd ("packet", class_maintenance, packet_command, _("\
10939Send an arbitrary packet to a remote target.\n\
c906108c
SS
10940 maintenance packet TEXT\n\
10941If GDB is talking to an inferior via the GDB serial protocol, then\n\
10942this command sends the string TEXT to the inferior, and displays the\n\
10943response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 10944terminating `#' character and checksum."),
c906108c
SS
10945 &maintenancelist);
10946
7915a72c
AC
10947 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
10948Set whether to send break if interrupted."), _("\
10949Show whether to send break if interrupted."), _("\
10950If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 10951 set_remotebreak, show_remotebreak,
e707bbc2 10952 &setlist, &showlist);
9a7071a8
JB
10953 cmd_name = "remotebreak";
10954 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
10955 deprecate_cmd (cmd, "set remote interrupt-sequence");
10956 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
10957 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
10958 deprecate_cmd (cmd, "show remote interrupt-sequence");
10959
10960 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
10961 interrupt_sequence_modes, &interrupt_sequence_mode,
10962 _("\
9a7071a8
JB
10963Set interrupt sequence to remote target."), _("\
10964Show interrupt sequence to remote target."), _("\
10965Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
10966 NULL, show_interrupt_sequence,
10967 &remote_set_cmdlist,
10968 &remote_show_cmdlist);
10969
10970 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
10971 &interrupt_on_connect, _("\
10972Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10973Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
10974If set, interrupt sequence is sent to remote target."),
10975 NULL, NULL,
10976 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 10977
23860348 10978 /* Install commands for configuring memory read/write packets. */
11cf8741 10979
1a966eab
AC
10980 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
10981Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 10982 &setlist);
1a966eab
AC
10983 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
10984Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
10985 &showlist);
10986 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
10987 set_memory_write_packet_size, _("\
10988Set the maximum number of bytes per memory-write packet.\n\
10989Specify the number of bytes in a packet or 0 (zero) for the\n\
10990default packet size. The actual limit is further reduced\n\
10991dependent on the target. Specify ``fixed'' to disable the\n\
10992further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
10993 &remote_set_cmdlist);
10994 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
10995 set_memory_read_packet_size, _("\
10996Set the maximum number of bytes per memory-read packet.\n\
10997Specify the number of bytes in a packet or 0 (zero) for the\n\
10998default packet size. The actual limit is further reduced\n\
10999dependent on the target. Specify ``fixed'' to disable the\n\
11000further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
11001 &remote_set_cmdlist);
11002 add_cmd ("memory-write-packet-size", no_class,
11003 show_memory_write_packet_size,
1a966eab 11004 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
11005 &remote_show_cmdlist);
11006 add_cmd ("memory-read-packet-size", no_class,
11007 show_memory_read_packet_size,
1a966eab 11008 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 11009 &remote_show_cmdlist);
c906108c 11010
b3f42336 11011 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
11012 &remote_hw_watchpoint_limit, _("\
11013Set the maximum number of target hardware watchpoints."), _("\
11014Show the maximum number of target hardware watchpoints."), _("\
11015Specify a negative limit for unlimited."),
3e43a32a
MS
11016 NULL, NULL, /* FIXME: i18n: The maximum
11017 number of target hardware
11018 watchpoints is %s. */
b3f42336 11019 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
11020 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
11021 &remote_hw_watchpoint_length_limit, _("\
11022Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
11023Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
11024Specify a negative limit for unlimited."),
11025 NULL, NULL, /* FIXME: i18n: The maximum
11026 length (in bytes) of a target
11027 hardware watchpoint is %s. */
11028 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 11029 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
11030 &remote_hw_breakpoint_limit, _("\
11031Set the maximum number of target hardware breakpoints."), _("\
11032Show the maximum number of target hardware breakpoints."), _("\
11033Specify a negative limit for unlimited."),
3e43a32a
MS
11034 NULL, NULL, /* FIXME: i18n: The maximum
11035 number of target hardware
11036 breakpoints is %s. */
b3f42336 11037 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 11038
4d28ad1e
AC
11039 add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
11040 &remote_address_size, _("\
11041Set the maximum size of the address (in bits) in a memory packet."), _("\
11042Show the maximum size of the address (in bits) in a memory packet."), NULL,
11043 NULL,
11044 NULL, /* FIXME: i18n: */
11045 &setlist, &showlist);
c906108c 11046
444abaca 11047 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 11048 "X", "binary-download", 1);
0f71a2f6 11049
444abaca 11050 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 11051 "vCont", "verbose-resume", 0);
506fb367 11052
89be2091
DJ
11053 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
11054 "QPassSignals", "pass-signals", 0);
11055
444abaca 11056 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 11057 "qSymbol", "symbol-lookup", 0);
dc8acb97 11058
444abaca 11059 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 11060 "P", "set-register", 1);
d471ea57 11061
444abaca 11062 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 11063 "p", "fetch-register", 1);
b96ec7ac 11064
444abaca 11065 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 11066 "Z0", "software-breakpoint", 0);
d471ea57 11067
444abaca 11068 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 11069 "Z1", "hardware-breakpoint", 0);
d471ea57 11070
444abaca 11071 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 11072 "Z2", "write-watchpoint", 0);
d471ea57 11073
444abaca 11074 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 11075 "Z3", "read-watchpoint", 0);
d471ea57 11076
444abaca 11077 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 11078 "Z4", "access-watchpoint", 0);
d471ea57 11079
0876f84a
DJ
11080 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
11081 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 11082
23181151
DJ
11083 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
11084 "qXfer:features:read", "target-features", 0);
11085
cfa9d6d9
DJ
11086 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
11087 "qXfer:libraries:read", "library-info", 0);
11088
2268b414
JK
11089 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
11090 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
11091
fd79ecee
DJ
11092 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
11093 "qXfer:memory-map:read", "memory-map", 0);
11094
0e7f50da
UW
11095 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
11096 "qXfer:spu:read", "read-spu-object", 0);
11097
11098 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
11099 "qXfer:spu:write", "write-spu-object", 0);
11100
07e059b5
VP
11101 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
11102 "qXfer:osdata:read", "osdata", 0);
11103
dc146f7c
VP
11104 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
11105 "qXfer:threads:read", "threads", 0);
11106
4aa995e1
PA
11107 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
11108 "qXfer:siginfo:read", "read-siginfo-object", 0);
11109
11110 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
11111 "qXfer:siginfo:write", "write-siginfo-object", 0);
11112
b3b9301e
PA
11113 add_packet_config_cmd
11114 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
11115 "qXfer:trace-frame-info:read", "traceframe-info", 0);
11116
444abaca 11117 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 11118 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
11119 0);
11120
711e434b
PM
11121 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
11122 "qGetTIBAddr", "get-thread-information-block-address",
11123 0);
11124
40ab02ce
MS
11125 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
11126 "bc", "reverse-continue", 0);
11127
11128 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
11129 "bs", "reverse-step", 0);
11130
be2a5f71
DJ
11131 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
11132 "qSupported", "supported-packets", 0);
11133
08388c79
DE
11134 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
11135 "qSearch:memory", "search-memory", 0);
11136
a6b151f1
DJ
11137 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
11138 "vFile:open", "hostio-open", 0);
11139
11140 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
11141 "vFile:pread", "hostio-pread", 0);
11142
11143 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
11144 "vFile:pwrite", "hostio-pwrite", 0);
11145
11146 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
11147 "vFile:close", "hostio-close", 0);
11148
11149 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
11150 "vFile:unlink", "hostio-unlink", 0);
11151
2d717e4f
DJ
11152 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
11153 "vAttach", "attach", 0);
11154
11155 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
11156 "vRun", "run", 0);
11157
a6f3e723
SL
11158 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
11159 "QStartNoAckMode", "noack", 0);
11160
82f73884
PA
11161 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
11162 "vKill", "kill", 0);
11163
0b16c5cf
PA
11164 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
11165 "qAttached", "query-attached", 0);
11166
782b2b07 11167 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
11168 "ConditionalTracepoints",
11169 "conditional-tracepoints", 0);
7a697b8d
SS
11170 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
11171 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 11172
409873ef
SS
11173 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
11174 "TracepointSource", "TracepointSource", 0);
11175
d914c394
SS
11176 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
11177 "QAllow", "allow", 0);
11178
0fb4aa4b
PA
11179 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
11180 "StaticTracepoints", "static-tracepoints", 0);
11181
1e4d1764
YQ
11182 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
11183 "InstallInTrace", "install-in-trace", 0);
11184
0fb4aa4b
PA
11185 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
11186 "qXfer:statictrace:read", "read-sdata-object", 0);
11187
78d85199
YQ
11188 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
11189 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
11190
03583c20
UW
11191 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
11192 "QDisableRandomization", "disable-randomization", 0);
11193
37a105a1
DJ
11194 /* Keep the old ``set remote Z-packet ...'' working. Each individual
11195 Z sub-packet has its own set and show commands, but users may
11196 have sets to this variable in their .gdbinit files (or in their
11197 documentation). */
e9e68a56 11198 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
11199 &remote_Z_packet_detect, _("\
11200Set use of remote protocol `Z' packets"), _("\
11201Show use of remote protocol `Z' packets "), _("\
3b64bf98 11202When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 11203packets."),
e9e68a56 11204 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
11205 show_remote_protocol_Z_packet_cmd,
11206 /* FIXME: i18n: Use of remote protocol
11207 `Z' packets is %s. */
e9e68a56 11208 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 11209
a6b151f1
DJ
11210 add_prefix_cmd ("remote", class_files, remote_command, _("\
11211Manipulate files on the remote system\n\
11212Transfer files to and from the remote target system."),
11213 &remote_cmdlist, "remote ",
11214 0 /* allow-unknown */, &cmdlist);
11215
11216 add_cmd ("put", class_files, remote_put_command,
11217 _("Copy a local file to the remote system."),
11218 &remote_cmdlist);
11219
11220 add_cmd ("get", class_files, remote_get_command,
11221 _("Copy a remote file to the local system."),
11222 &remote_cmdlist);
11223
11224 add_cmd ("delete", class_files, remote_delete_command,
11225 _("Delete a remote file."),
11226 &remote_cmdlist);
11227
2d717e4f
DJ
11228 remote_exec_file = xstrdup ("");
11229 add_setshow_string_noescape_cmd ("exec-file", class_files,
11230 &remote_exec_file, _("\
11231Set the remote pathname for \"run\""), _("\
11232Show the remote pathname for \"run\""), NULL, NULL, NULL,
11233 &remote_set_cmdlist, &remote_show_cmdlist);
11234
449092f6
CV
11235 /* Eventually initialize fileio. See fileio.c */
11236 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229
PA
11237
11238 /* Take advantage of the fact that the LWP field is not used, to tag
11239 special ptids with it set to != 0. */
82f73884
PA
11240 magic_null_ptid = ptid_build (42000, 1, -1);
11241 not_sent_ptid = ptid_build (42000, 1, -2);
11242 any_thread_ptid = ptid_build (42000, 1, 0);
35b1e5cc
SS
11243
11244 target_buf_size = 2048;
11245 target_buf = xmalloc (target_buf_size);
c906108c 11246}
10760264 11247
This page took 2.00015 seconds and 4 git commands to generate.