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