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