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