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