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