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