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