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