]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
Introduce string_appendf/string_vappendf
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
61baf725 3 Copyright (C) 1988-2017 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"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
c0272db5 73#include "record-btrace.h"
325fac50 74#include <algorithm>
2ec845e7 75#include "common/scoped_restore.h"
0a2dde4a 76#include "environ.h"
f6327dcb 77#include "common/byte-vector.h"
35b1e5cc 78
94585166
DB
79/* Per-program-space data key. */
80static const struct program_space_data *remote_pspace_data;
81
82/* The variable registered as the control variable used by the
83 remote exec-file commands. While the remote exec-file setting is
84 per-program-space, the set/show machinery uses this as the
85 location of the remote exec-file value. */
86static char *remote_exec_file_var;
87
6765f3e5
DJ
88/* The size to align memory write packets, when practical. The protocol
89 does not guarantee any alignment, and gdb will generate short
90 writes and unaligned writes, but even as a best-effort attempt this
91 can improve bulk transfers. For instance, if a write is misaligned
92 relative to the target's data bus, the stub may need to make an extra
93 round trip fetching data from the target. This doesn't make a
94 huge difference, but it's easy to do, so we try to be helpful.
95
96 The alignment chosen is arbitrary; usually data bus width is
97 important here, not the possibly larger cache line size. */
98enum { REMOTE_ALIGN_WRITES = 16 };
99
23860348 100/* Prototypes for local functions. */
6d820c5c 101static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 102static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 103 int forever, int *is_notif);
6426a772 104
a14ed312 105static void remote_files_info (struct target_ops *ignore);
c906108c 106
f32dbf8c
MM
107static void remote_prepare_to_store (struct target_ops *self,
108 struct regcache *regcache);
c906108c 109
014f9477
TT
110static void remote_open_1 (const char *, int, struct target_ops *,
111 int extended_p);
c906108c 112
de90e03d 113static void remote_close (struct target_ops *self);
c906108c 114
cbb8991c
DB
115struct remote_state;
116
117static int remote_vkill (int pid, struct remote_state *rs);
118
8020350c
DB
119static void remote_kill_k (void);
120
136d6dae 121static void remote_mourn (struct target_ops *ops);
c906108c 122
a14ed312 123static void extended_remote_restart (void);
c906108c 124
6d820c5c 125static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 126
a14ed312 127static int readchar (int timeout);
c906108c 128
c33e31fd
PA
129static void remote_serial_write (const char *str, int len);
130
7d85a9c0 131static void remote_kill (struct target_ops *ops);
c906108c 132
6a109b6b 133static int remote_can_async_p (struct target_ops *);
75c99385 134
6a109b6b 135static int remote_is_async_p (struct target_ops *);
75c99385 136
6a3753b3 137static void remote_async (struct target_ops *ops, int enable);
75c99385 138
65706a29
PA
139static void remote_thread_events (struct target_ops *ops, int enable);
140
a14ed312 141static void interrupt_query (void);
c906108c 142
d62a8ae2
SM
143static void set_general_thread (ptid_t ptid);
144static void set_continue_thread (ptid_t ptid);
c906108c 145
a14ed312 146static void get_offsets (void);
c906108c 147
6d820c5c
DJ
148static void skip_frame (void);
149
150static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 151
a14ed312 152static int hexnumlen (ULONGEST num);
c906108c 153
a14ed312 154static void init_remote_ops (void);
c906108c 155
a14ed312 156static void init_extended_remote_ops (void);
c906108c 157
1eab8a48 158static void remote_stop (struct target_ops *self, ptid_t);
c906108c 159
a14ed312 160static int stubhex (int ch);
c906108c 161
a14ed312 162static int hexnumstr (char *, ULONGEST);
c906108c 163
a14ed312 164static int hexnumnstr (char *, ULONGEST, int);
2df3850c 165
a14ed312 166static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 167
baa336ce 168static void print_packet (const char *);
c906108c 169
a14ed312 170static int stub_unpack_int (char *buff, int fieldlength);
c906108c 171
39f77062 172static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 173
baa336ce 174static int putpkt_binary (const char *buf, int cnt);
c906108c 175
a14ed312 176static void check_binary_download (CORE_ADDR addr);
c906108c 177
5a2468f5 178struct packet_config;
5a2468f5 179
a14ed312 180static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 181
bb572ddd
DJ
182static void show_remote_protocol_packet_cmd (struct ui_file *file,
183 int from_tty,
184 struct cmd_list_element *c,
185 const char *value);
186
82f73884 187static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
256642e8 188static ptid_t read_ptid (const char *buf, const char **obuf);
82f73884 189
c378d69d 190static void remote_set_permissions (struct target_ops *self);
d914c394 191
8bd200f1
TT
192static int remote_get_trace_status (struct target_ops *self,
193 struct trace_status *ts);
d5551862 194
ab6617cc
TT
195static int remote_upload_tracepoints (struct target_ops *self,
196 struct uploaded_tp **utpp);
00bf0b85 197
181e3713
TT
198static int remote_upload_trace_state_variables (struct target_ops *self,
199 struct uploaded_tsv **utsvp);
00bf0b85 200
c8d104ad
PA
201static void remote_query_supported (void);
202
36d25514 203static void remote_check_symbols (void);
c8d104ad 204
74531fed 205struct stop_reply;
74531fed 206static void stop_reply_xfree (struct stop_reply *);
722247f1 207static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 208static void push_stop_reply (struct stop_reply *);
bcc75809 209static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
210static int peek_stop_reply (ptid_t ptid);
211
cbb8991c
DB
212struct threads_listing_context;
213static void remove_new_fork_children (struct threads_listing_context *);
214
74531fed 215static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 216
e3594fd1 217static void remote_terminal_ours (struct target_ops *self);
d3fd5342 218
d962ef82
DJ
219static int remote_read_description_p (struct target_ops *target);
220
176a6961 221static void remote_console_output (char *msg);
dde08ee1 222
efcc2da7 223static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 224
78eff0ec 225static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 226
f4abbc16
MM
227static void remote_btrace_reset (void);
228
c0272db5
TW
229static void remote_btrace_maybe_reopen (void);
230
221e1a37
PA
231static int stop_reply_queue_length (void);
232
80152258
PA
233static void readahead_cache_invalidate (void);
234
048094ac
PA
235static void remote_unpush_and_throw (void);
236
b6bb3468
PA
237static struct remote_state *get_remote_state (void);
238
a6b151f1
DJ
239/* For "remote". */
240
241static struct cmd_list_element *remote_cmdlist;
242
bb572ddd
DJ
243/* For "set remote" and "show remote". */
244
245static struct cmd_list_element *remote_set_cmdlist;
246static struct cmd_list_element *remote_show_cmdlist;
247
d458bd84
PA
248/* Stub vCont actions support.
249
250 Each field is a boolean flag indicating whether the stub reports
251 support for the corresponding action. */
252
253struct vCont_action_support
254{
255 /* vCont;t */
256 int t;
c1e36e3e
PA
257
258 /* vCont;r */
259 int r;
750ce8d1
YQ
260
261 /* vCont;s */
262 int s;
263
264 /* vCont;S */
265 int S;
d458bd84
PA
266};
267
c1e36e3e
PA
268/* Controls whether GDB is willing to use range stepping. */
269
270static int use_range_stepping = 1;
271
0d031856
TT
272#define OPAQUETHREADBYTES 8
273
274/* a 64 bit opaque identifier */
275typedef unsigned char threadref[OPAQUETHREADBYTES];
276
277/* About this many threadisds fit in a packet. */
278
279#define MAXTHREADLISTRESULTS 32
280
6f8976bf
YQ
281/* The max number of chars in debug output. The rest of chars are
282 omitted. */
283
284#define REMOTE_DEBUG_MAX_CHAR 512
285
80152258
PA
286/* Data for the vFile:pread readahead cache. */
287
288struct readahead_cache
289{
290 /* The file descriptor for the file that is being cached. -1 if the
291 cache is invalid. */
292 int fd;
293
294 /* The offset into the file that the cache buffer corresponds
295 to. */
296 ULONGEST offset;
297
298 /* The buffer holding the cache contents. */
299 gdb_byte *buf;
300 /* The buffer's size. We try to read as much as fits into a packet
301 at a time. */
302 size_t bufsize;
303
304 /* Cache hit and miss counters. */
305 ULONGEST hit_count;
306 ULONGEST miss_count;
307};
308
ea9c271d
DJ
309/* Description of the remote protocol state for the currently
310 connected target. This is per-target state, and independent of the
311 selected architecture. */
312
313struct remote_state
314{
315 /* A buffer to use for incoming packets, and its current size. The
316 buffer is grown dynamically for larger incoming packets.
317 Outgoing packets may also be constructed in this buffer.
318 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
320 packets. */
321 char *buf;
322 long buf_size;
be2a5f71 323
1e51243a
PA
324 /* True if we're going through initial connection setup (finding out
325 about the remote side's threads, relocating symbols, etc.). */
326 int starting_up;
327
be2a5f71
DJ
328 /* If we negotiated packet size explicitly (and thus can bypass
329 heuristics for the largest packet size that will not overflow
330 a buffer in the stub), this will be set to that packet size.
331 Otherwise zero, meaning to use the guessed size. */
332 long explicit_packet_size;
2d717e4f
DJ
333
334 /* remote_wait is normally called when the target is running and
335 waits for a stop reply packet. But sometimes we need to call it
336 when the target is already stopped. We can send a "?" packet
337 and have remote_wait read the response. Or, if we already have
338 the response, we can stash it in BUF and tell remote_wait to
339 skip calling getpkt. This flag is set when BUF contains a
340 stop reply packet and the target is not waiting. */
341 int cached_wait_status;
a6f3e723
SL
342
343 /* True, if in no ack mode. That is, neither GDB nor the stub will
344 expect acks from each other. The connection is assumed to be
345 reliable. */
346 int noack_mode;
82f73884
PA
347
348 /* True if we're connected in extended remote mode. */
349 int extended;
350
e24a49d8
PA
351 /* True if we resumed the target and we're waiting for the target to
352 stop. In the mean time, we can't start another command/query.
353 The remote server wouldn't be ready to process it, so we'd
354 timeout waiting for a reply that would never come and eventually
355 we'd close the connection. This can happen in asynchronous mode
356 because we allow GDB commands while the target is running. */
357 int waiting_for_stop_reply;
74531fed 358
d458bd84
PA
359 /* The status of the stub support for the various vCont actions. */
360 struct vCont_action_support supports_vCont;
782b2b07 361
3a29589a
DJ
362 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363 responded to that. */
364 int ctrlc_pending_p;
5d93a237 365
048094ac
PA
366 /* True if we saw a Ctrl-C while reading or writing from/to the
367 remote descriptor. At that point it is not safe to send a remote
368 interrupt packet, so we instead remember we saw the Ctrl-C and
369 process it once we're done with sending/receiving the current
370 packet, which should be shortly. If however that takes too long,
371 and the user presses Ctrl-C again, we offer to disconnect. */
372 int got_ctrlc_during_io;
373
5d93a237
TT
374 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
375 remote_open knows that we don't have a file open when the program
376 starts. */
377 struct serial *remote_desc;
47f8a51d
TT
378
379 /* These are the threads which we last sent to the remote system. The
380 TID member will be -1 for all or -2 for not sent yet. */
381 ptid_t general_thread;
382 ptid_t continue_thread;
262e1174
TT
383
384 /* This is the traceframe which we last selected on the remote system.
385 It will be -1 if no traceframe is selected. */
386 int remote_traceframe_number;
747dc59d
TT
387
388 char *last_pass_packet;
5e4a05c4
TT
389
390 /* The last QProgramSignals packet sent to the target. We bypass
391 sending a new program signals list down to the target if the new
392 packet is exactly the same as the last we sent. IOW, we only let
393 the target know about program signals list changes. */
394 char *last_program_signals_packet;
b73be471
TT
395
396 enum gdb_signal last_sent_signal;
280ceea3
TT
397
398 int last_sent_step;
8e88304f 399
3a00c802
PA
400 /* The execution direction of the last resume we got. */
401 enum exec_direction_kind last_resume_exec_dir;
402
8e88304f
TT
403 char *finished_object;
404 char *finished_annex;
405 ULONGEST finished_offset;
b80fafe3
TT
406
407 /* Should we try the 'ThreadInfo' query packet?
408
409 This variable (NOT available to the user: auto-detect only!)
410 determines whether GDB will use the new, simpler "ThreadInfo"
411 query or the older, more complex syntax for thread queries.
412 This is an auto-detect variable (set to true at each connect,
413 and set to false when the target fails to recognize it). */
414 int use_threadinfo_query;
415 int use_threadextra_query;
88b496c3 416
0d031856
TT
417 threadref echo_nextthread;
418 threadref nextthread;
419 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
420
421 /* The state of remote notification. */
422 struct remote_notif_state *notif_state;
f4abbc16
MM
423
424 /* The branch trace configuration. */
425 struct btrace_config btrace_config;
15a201c8
GB
426
427 /* The argument to the last "vFile:setfs:" packet we sent, used
428 to avoid sending repeated unnecessary "vFile:setfs:" packets.
429 Initialized to -1 to indicate that no "vFile:setfs:" packet
430 has yet been sent. */
431 int fs_pid;
80152258
PA
432
433 /* A readahead cache for vFile:pread. Often, reading a binary
434 involves a sequence of small reads. E.g., when parsing an ELF
435 file. A readahead cache helps mostly the case of remote
436 debugging on a connection with higher latency, due to the
437 request/reply nature of the RSP. We only cache data for a single
438 file descriptor at a time. */
439 struct readahead_cache readahead_cache;
ea9c271d
DJ
440};
441
dc146f7c
VP
442/* Private data that we'll store in (struct thread_info)->private. */
443struct private_thread_info
444{
445 char *extra;
79efa585 446 char *name;
dc146f7c 447 int core;
799a2abe 448
f6327dcb
KB
449 /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
450 sequence of bytes. */
451 gdb::byte_vector *thread_handle;
452
799a2abe
PA
453 /* Whether the target stopped for a breakpoint/watchpoint. */
454 enum target_stop_reason stop_reason;
455
456 /* This is set to the data address of the access causing the target
457 to stop for a watchpoint. */
458 CORE_ADDR watch_data_address;
85ad3aaf
PA
459
460 /* Fields used by the vCont action coalescing implemented in
461 remote_resume / remote_commit_resume. remote_resume stores each
462 thread's last resume request in these fields, so that a later
463 remote_commit_resume knows which is the proper action for this
464 thread to include in the vCont packet. */
465
466 /* True if the last target_resume call for this thread was a step
467 request, false if a continue request. */
468 int last_resume_step;
469
470 /* The signal specified in the last target_resume call for this
471 thread. */
472 enum gdb_signal last_resume_sig;
473
474 /* Whether this thread was already vCont-resumed on the remote
475 side. */
476 int vcont_resumed;
dc146f7c
VP
477};
478
479static void
480free_private_thread_info (struct private_thread_info *info)
481{
482 xfree (info->extra);
79efa585 483 xfree (info->name);
f6327dcb 484 delete info->thread_handle;
dc146f7c
VP
485 xfree (info);
486}
487
ea9c271d
DJ
488/* This data could be associated with a target, but we do not always
489 have access to the current target when we need it, so for now it is
490 static. This will be fine for as long as only one target is in use
491 at a time. */
cf792862 492static struct remote_state *remote_state;
ea9c271d
DJ
493
494static struct remote_state *
0b83947e 495get_remote_state_raw (void)
ea9c271d 496{
cf792862
TT
497 return remote_state;
498}
499
500/* Allocate a new struct remote_state with xmalloc, initialize it, and
501 return it. */
502
503static struct remote_state *
504new_remote_state (void)
505{
506 struct remote_state *result = XCNEW (struct remote_state);
507
508 /* The default buffer size is unimportant; it will be expanded
509 whenever a larger buffer is needed. */
510 result->buf_size = 400;
224c3ddb 511 result->buf = (char *) xmalloc (result->buf_size);
262e1174 512 result->remote_traceframe_number = -1;
b73be471 513 result->last_sent_signal = GDB_SIGNAL_0;
3a00c802 514 result->last_resume_exec_dir = EXEC_FORWARD;
15a201c8 515 result->fs_pid = -1;
cf792862
TT
516
517 return result;
ea9c271d
DJ
518}
519
520/* Description of the remote protocol for a given architecture. */
d01949b6 521
ad10f812
AC
522struct packet_reg
523{
524 long offset; /* Offset into G packet. */
525 long regnum; /* GDB's internal register number. */
526 LONGEST pnum; /* Remote protocol register number. */
b323314b 527 int in_g_packet; /* Always part of G packet. */
f5656ead 528 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 529 at present. */
f5656ead 530 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 531 at present. */
ad10f812
AC
532};
533
ea9c271d 534struct remote_arch_state
d01949b6 535{
ad10f812
AC
536 /* Description of the remote protocol registers. */
537 long sizeof_g_packet;
b323314b
AC
538
539 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 540 (making an array gdbarch_num_regs in size). */
b323314b 541 struct packet_reg *regs;
ad10f812 542
d01949b6
AC
543 /* This is the size (in chars) of the first response to the ``g''
544 packet. It is used as a heuristic when determining the maximum
545 size of memory-read and memory-write packets. A target will
546 typically only reserve a buffer large enough to hold the ``g''
547 packet. The size does not include packet overhead (headers and
23860348 548 trailers). */
d01949b6
AC
549 long actual_register_packet_size;
550
551 /* This is the maximum size (in chars) of a non read/write packet.
23860348 552 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
553 long remote_packet_size;
554};
555
35b1e5cc
SS
556/* Utility: generate error from an incoming stub packet. */
557static void
558trace_error (char *buf)
559{
560 if (*buf++ != 'E')
561 return; /* not an error msg */
562 switch (*buf)
563 {
564 case '1': /* malformed packet error */
565 if (*++buf == '0') /* general case: */
566 error (_("remote.c: error in outgoing packet."));
567 else
568 error (_("remote.c: error in outgoing packet at field #%ld."),
569 strtol (buf, NULL, 16));
35b1e5cc
SS
570 default:
571 error (_("Target returns error code '%s'."), buf);
572 }
573}
574
575/* Utility: wait for reply from stub, while accepting "O" packets. */
b6bb3468 576
35b1e5cc 577static char *
b6bb3468 578remote_get_noisy_reply ()
35b1e5cc 579{
b6bb3468
PA
580 struct remote_state *rs = get_remote_state ();
581
35b1e5cc
SS
582 do /* Loop on reply from remote stub. */
583 {
584 char *buf;
a744cf53 585
0df8b418 586 QUIT; /* Allow user to bail out with ^C. */
b6bb3468
PA
587 getpkt (&rs->buf, &rs->buf_size, 0);
588 buf = rs->buf;
ad91cd99 589 if (buf[0] == 'E')
35b1e5cc 590 trace_error (buf);
61012eef 591 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
592 {
593 ULONGEST ul;
594 CORE_ADDR from, to, org_to;
256642e8 595 const char *p, *pp;
dde08ee1 596 int adjusted_size = 0;
7556d4a4 597 int relocated = 0;
dde08ee1
PA
598
599 p = buf + strlen ("qRelocInsn:");
600 pp = unpack_varlen_hex (p, &ul);
601 if (*pp != ';')
cb91c06a 602 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
603 from = ul;
604
605 p = pp + 1;
a9cbf802 606 unpack_varlen_hex (p, &ul);
dde08ee1
PA
607 to = ul;
608
609 org_to = to;
610
492d29ea 611 TRY
dde08ee1 612 {
f5656ead 613 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 614 relocated = 1;
dde08ee1 615 }
492d29ea 616 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
617 {
618 if (ex.error == MEMORY_ERROR)
619 {
620 /* Propagate memory errors silently back to the
621 target. The stub may have limited the range of
622 addresses we can write to, for example. */
623 }
624 else
625 {
626 /* Something unexpectedly bad happened. Be verbose
627 so we can tell what, and propagate the error back
628 to the stub, so it doesn't get stuck waiting for
629 a response. */
630 exception_fprintf (gdb_stderr, ex,
631 _("warning: relocating instruction: "));
632 }
633 putpkt ("E01");
634 }
492d29ea 635 END_CATCH
7556d4a4
PA
636
637 if (relocated)
dde08ee1
PA
638 {
639 adjusted_size = to - org_to;
640
b6bb3468 641 xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
642 putpkt (buf);
643 }
dde08ee1 644 }
ad91cd99 645 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
646 remote_console_output (buf + 1); /* 'O' message from stub */
647 else
0df8b418 648 return buf; /* Here's the actual reply. */
35b1e5cc
SS
649 }
650 while (1);
651}
3c3bea1c 652
d01949b6
AC
653/* Handle for retreving the remote protocol data from gdbarch. */
654static struct gdbarch_data *remote_gdbarch_data_handle;
655
ea9c271d 656static struct remote_arch_state *
5cd63fda 657get_remote_arch_state (struct gdbarch *gdbarch)
d01949b6 658{
5cd63fda 659 gdb_assert (gdbarch != NULL);
19ba03f4 660 return ((struct remote_arch_state *)
5cd63fda 661 gdbarch_data (gdbarch, remote_gdbarch_data_handle));
d01949b6
AC
662}
663
0b83947e
DJ
664/* Fetch the global remote target state. */
665
666static struct remote_state *
667get_remote_state (void)
668{
669 /* Make sure that the remote architecture state has been
670 initialized, because doing so might reallocate rs->buf. Any
671 function which calls getpkt also needs to be mindful of changes
672 to rs->buf, but this call limits the number of places which run
673 into trouble. */
5cd63fda 674 get_remote_arch_state (target_gdbarch ());
0b83947e
DJ
675
676 return get_remote_state_raw ();
677}
678
94585166
DB
679/* Cleanup routine for the remote module's pspace data. */
680
681static void
682remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
683{
19ba03f4 684 char *remote_exec_file = (char *) arg;
94585166
DB
685
686 xfree (remote_exec_file);
687}
688
689/* Fetch the remote exec-file from the current program space. */
690
691static const char *
692get_remote_exec_file (void)
693{
694 char *remote_exec_file;
695
19ba03f4
SM
696 remote_exec_file
697 = (char *) program_space_data (current_program_space,
698 remote_pspace_data);
94585166
DB
699 if (remote_exec_file == NULL)
700 return "";
701
702 return remote_exec_file;
703}
704
705/* Set the remote exec file for PSPACE. */
706
707static void
708set_pspace_remote_exec_file (struct program_space *pspace,
709 char *remote_exec_file)
710{
19ba03f4 711 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
712
713 xfree (old_file);
714 set_program_space_data (pspace, remote_pspace_data,
715 xstrdup (remote_exec_file));
716}
717
718/* The "set/show remote exec-file" set command hook. */
719
720static void
721set_remote_exec_file (char *ignored, int from_tty,
722 struct cmd_list_element *c)
723{
724 gdb_assert (remote_exec_file_var != NULL);
725 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
726}
727
728/* The "set/show remote exec-file" show command hook. */
729
730static void
731show_remote_exec_file (struct ui_file *file, int from_tty,
732 struct cmd_list_element *cmd, const char *value)
733{
734 fprintf_filtered (file, "%s\n", remote_exec_file_var);
735}
736
74ca34ce
DJ
737static int
738compare_pnums (const void *lhs_, const void *rhs_)
739{
19ba03f4
SM
740 const struct packet_reg * const *lhs
741 = (const struct packet_reg * const *) lhs_;
742 const struct packet_reg * const *rhs
743 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
744
745 if ((*lhs)->pnum < (*rhs)->pnum)
746 return -1;
747 else if ((*lhs)->pnum == (*rhs)->pnum)
748 return 0;
749 else
750 return 1;
751}
752
c21236dc
PA
753static int
754map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 755{
74ca34ce 756 int regnum, num_remote_regs, offset;
74ca34ce 757 struct packet_reg **remote_regs;
ea9c271d 758
4a22f64d 759 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 760 {
c21236dc 761 struct packet_reg *r = &regs[regnum];
baef701f 762
4a22f64d 763 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
764 /* Do not try to fetch zero-sized (placeholder) registers. */
765 r->pnum = -1;
766 else
767 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
768
b323314b 769 r->regnum = regnum;
74ca34ce
DJ
770 }
771
772 /* Define the g/G packet format as the contents of each register
773 with a remote protocol number, in order of ascending protocol
774 number. */
775
224c3ddb 776 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 777 for (num_remote_regs = 0, regnum = 0;
4a22f64d 778 regnum < gdbarch_num_regs (gdbarch);
f57d151a 779 regnum++)
c21236dc
PA
780 if (regs[regnum].pnum != -1)
781 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 782
74ca34ce
DJ
783 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
784 compare_pnums);
785
786 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
787 {
788 remote_regs[regnum]->in_g_packet = 1;
789 remote_regs[regnum]->offset = offset;
4a22f64d 790 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
791 }
792
c21236dc
PA
793 return offset;
794}
795
796/* Given the architecture described by GDBARCH, return the remote
797 protocol register's number and the register's offset in the g/G
798 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
799 If the target does not have a mapping for REGNUM, return false,
800 otherwise, return true. */
801
802int
803remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
804 int *pnum, int *poffset)
805{
c21236dc
PA
806 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
807
b80406ac 808 std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
c21236dc 809
b80406ac 810 map_regcache_remote_table (gdbarch, regs.data ());
c21236dc
PA
811
812 *pnum = regs[regnum].pnum;
813 *poffset = regs[regnum].offset;
814
c21236dc
PA
815 return *pnum != -1;
816}
817
818static void *
819init_remote_state (struct gdbarch *gdbarch)
820{
821 struct remote_state *rs = get_remote_state_raw ();
822 struct remote_arch_state *rsa;
823
824 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
825
826 /* Use the architecture to build a regnum<->pnum table, which will be
827 1:1 unless a feature set specifies otherwise. */
828 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
829 gdbarch_num_regs (gdbarch),
830 struct packet_reg);
831
74ca34ce
DJ
832 /* Record the maximum possible size of the g packet - it may turn out
833 to be smaller. */
c21236dc 834 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 835
0df8b418 836 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
837 remote stubs have a hardwired buffer size of 400 bytes
838 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
839 as the maximum packet-size to ensure that the packet and an extra
840 NUL character can always fit in the buffer. This stops GDB
841 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
842 already a full buffer (As of 1999-12-04 that was most stubs). */
843 rsa->remote_packet_size = 400 - 1;
d01949b6 844
ea9c271d
DJ
845 /* This one is filled in when a ``g'' packet is received. */
846 rsa->actual_register_packet_size = 0;
847
848 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
849 default, adjust the size accordingly. Remember that each byte is
850 encoded as two characters. 32 is the overhead for the packet
851 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 852 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 853 little. */
ea9c271d
DJ
854 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
855 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 856
ea9c271d
DJ
857 /* Make sure that the packet buffer is plenty big enough for
858 this architecture. */
859 if (rs->buf_size < rsa->remote_packet_size)
860 {
861 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 862 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 863 }
6d820c5c 864
ea9c271d
DJ
865 return rsa;
866}
867
868/* Return the current allowed size of a remote packet. This is
869 inferred from the current architecture, and should be used to
870 limit the length of outgoing packets. */
871static long
872get_remote_packet_size (void)
873{
be2a5f71 874 struct remote_state *rs = get_remote_state ();
5cd63fda 875 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
ea9c271d 876
be2a5f71
DJ
877 if (rs->explicit_packet_size)
878 return rs->explicit_packet_size;
879
ea9c271d 880 return rsa->remote_packet_size;
d01949b6
AC
881}
882
ad10f812 883static struct packet_reg *
5cd63fda
PA
884packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
885 long regnum)
ad10f812 886{
5cd63fda 887 if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
b323314b
AC
888 return NULL;
889 else
ad10f812 890 {
ea9c271d 891 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 892
b323314b
AC
893 gdb_assert (r->regnum == regnum);
894 return r;
ad10f812 895 }
ad10f812
AC
896}
897
898static struct packet_reg *
5cd63fda
PA
899packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
900 LONGEST pnum)
ad10f812 901{
b323314b 902 int i;
a744cf53 903
5cd63fda 904 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
ad10f812 905 {
ea9c271d 906 struct packet_reg *r = &rsa->regs[i];
a744cf53 907
b323314b
AC
908 if (r->pnum == pnum)
909 return r;
ad10f812
AC
910 }
911 return NULL;
d01949b6
AC
912}
913
c906108c
SS
914static struct target_ops remote_ops;
915
916static struct target_ops extended_remote_ops;
917
6426a772
JM
918/* FIXME: cagney/1999-09-23: Even though getpkt was called with
919 ``forever'' still use the normal timeout mechanism. This is
920 currently used by the ASYNC code to guarentee that target reads
921 during the initial connect always time-out. Once getpkt has been
922 modified to return a timeout indication and, in turn
923 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 924 this can go away. */
6426a772
JM
925static int wait_forever_enabled_p = 1;
926
9a7071a8
JB
927/* Allow the user to specify what sequence to send to the remote
928 when he requests a program interruption: Although ^C is usually
929 what remote systems expect (this is the default, here), it is
930 sometimes preferable to send a break. On other systems such
931 as the Linux kernel, a break followed by g, which is Magic SysRq g
932 is required in order to interrupt the execution. */
933const char interrupt_sequence_control_c[] = "Ctrl-C";
934const char interrupt_sequence_break[] = "BREAK";
935const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 936static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
937 {
938 interrupt_sequence_control_c,
939 interrupt_sequence_break,
940 interrupt_sequence_break_g,
941 NULL
942 };
943static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
944
945static void
946show_interrupt_sequence (struct ui_file *file, int from_tty,
947 struct cmd_list_element *c,
948 const char *value)
949{
950 if (interrupt_sequence_mode == interrupt_sequence_control_c)
951 fprintf_filtered (file,
952 _("Send the ASCII ETX character (Ctrl-c) "
953 "to the remote target to interrupt the "
954 "execution of the program.\n"));
955 else if (interrupt_sequence_mode == interrupt_sequence_break)
956 fprintf_filtered (file,
957 _("send a break signal to the remote target "
958 "to interrupt the execution of the program.\n"));
959 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
960 fprintf_filtered (file,
961 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
962 "the remote target to interrupt the execution "
963 "of Linux kernel.\n"));
964 else
965 internal_error (__FILE__, __LINE__,
966 _("Invalid value for interrupt_sequence_mode: %s."),
967 interrupt_sequence_mode);
968}
6426a772 969
9a7071a8
JB
970/* This boolean variable specifies whether interrupt_sequence is sent
971 to the remote target when gdb connects to it.
972 This is mostly needed when you debug the Linux kernel: The Linux kernel
973 expects BREAK g which is Magic SysRq g for connecting gdb. */
974static int interrupt_on_connect = 0;
c906108c 975
9a7071a8
JB
976/* This variable is used to implement the "set/show remotebreak" commands.
977 Since these commands are now deprecated in favor of "set/show remote
978 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
979static int remote_break;
980
9a7071a8
JB
981static void
982set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
983{
984 if (remote_break)
985 interrupt_sequence_mode = interrupt_sequence_break;
986 else
987 interrupt_sequence_mode = interrupt_sequence_control_c;
988}
989
990static void
991show_remotebreak (struct ui_file *file, int from_tty,
992 struct cmd_list_element *c,
993 const char *value)
994{
995}
996
c906108c
SS
997/* This variable sets the number of bits in an address that are to be
998 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 999 leading zeros, the entire address would be sent. This variable
c906108c
SS
1000 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1001 initial implementation of remote.c restricted the address sent in
1002 memory packets to ``host::sizeof long'' bytes - (typically 32
1003 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1004 address was never sent. Since fixing this bug may cause a break in
1005 some remote targets this variable is principly provided to
23860348 1006 facilitate backward compatibility. */
c906108c 1007
883b9c6c 1008static unsigned int remote_address_size;
c906108c 1009
11cf8741 1010\f
11cf8741 1011/* User configurable variables for the number of characters in a
ea9c271d
DJ
1012 memory read/write packet. MIN (rsa->remote_packet_size,
1013 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1014 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1015 (speed up transfers). The variables ``preferred_*'' (the user
1016 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1017 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1018
1019struct memory_packet_config
1020{
a121b7c1 1021 const char *name;
11cf8741
JM
1022 long size;
1023 int fixed_p;
1024};
1025
a5c0808e
PA
1026/* The default max memory-write-packet-size. The 16k is historical.
1027 (It came from older GDB's using alloca for buffers and the
1028 knowledge (folklore?) that some hosts don't cope very well with
1029 large alloca calls.) */
1030#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1031
1032/* The minimum remote packet size for memory transfers. Ensures we
1033 can write at least one byte. */
1034#define MIN_MEMORY_PACKET_SIZE 20
1035
11cf8741
JM
1036/* Compute the current size of a read/write packet. Since this makes
1037 use of ``actual_register_packet_size'' the computation is dynamic. */
1038
1039static long
1040get_memory_packet_size (struct memory_packet_config *config)
1041{
d01949b6 1042 struct remote_state *rs = get_remote_state ();
5cd63fda 1043 remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
ea9c271d 1044
11cf8741
JM
1045 long what_they_get;
1046 if (config->fixed_p)
1047 {
1048 if (config->size <= 0)
a5c0808e 1049 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1050 else
1051 what_they_get = config->size;
1052 }
1053 else
1054 {
ea9c271d 1055 what_they_get = get_remote_packet_size ();
23860348 1056 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1057 if (config->size > 0
1058 && what_they_get > config->size)
1059 what_they_get = config->size;
be2a5f71
DJ
1060
1061 /* Limit it to the size of the targets ``g'' response unless we have
1062 permission from the stub to use a larger packet size. */
1063 if (rs->explicit_packet_size == 0
1064 && rsa->actual_register_packet_size > 0
1065 && what_they_get > rsa->actual_register_packet_size)
1066 what_they_get = rsa->actual_register_packet_size;
11cf8741 1067 }
a5c0808e
PA
1068 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1069 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1070
1071 /* Make sure there is room in the global buffer for this packet
1072 (including its trailing NUL byte). */
1073 if (rs->buf_size < what_they_get + 1)
1074 {
1075 rs->buf_size = 2 * what_they_get;
224c3ddb 1076 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1077 }
1078
11cf8741
JM
1079 return what_they_get;
1080}
1081
0df8b418 1082/* Update the size of a read/write packet. If they user wants
23860348 1083 something really big then do a sanity check. */
11cf8741
JM
1084
1085static void
ac88e2de 1086set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1087{
1088 int fixed_p = config->fixed_p;
1089 long size = config->size;
a744cf53 1090
11cf8741 1091 if (args == NULL)
8a3fe4f8 1092 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1093 else if (strcmp (args, "hard") == 0
1094 || strcmp (args, "fixed") == 0)
1095 fixed_p = 1;
1096 else if (strcmp (args, "soft") == 0
1097 || strcmp (args, "limit") == 0)
1098 fixed_p = 0;
1099 else
1100 {
1101 char *end;
a744cf53 1102
11cf8741
JM
1103 size = strtoul (args, &end, 0);
1104 if (args == end)
8a3fe4f8 1105 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1106
1107 /* Instead of explicitly capping the size of a packet to or
1108 disallowing it, the user is allowed to set the size to
1109 something arbitrarily large. */
11cf8741 1110 }
a5c0808e
PA
1111
1112 /* So that the query shows the correct value. */
1113 if (size <= 0)
1114 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1115
23860348 1116 /* Extra checks? */
11cf8741
JM
1117 if (fixed_p && !config->fixed_p)
1118 {
e2e0b3e5
AC
1119 if (! query (_("The target may not be able to correctly handle a %s\n"
1120 "of %ld bytes. Change the packet size? "),
11cf8741 1121 config->name, size))
8a3fe4f8 1122 error (_("Packet size not changed."));
11cf8741 1123 }
23860348 1124 /* Update the config. */
11cf8741
JM
1125 config->fixed_p = fixed_p;
1126 config->size = size;
1127}
1128
1129static void
1130show_memory_packet_size (struct memory_packet_config *config)
1131{
a3f17187 1132 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1133 if (config->fixed_p)
a3f17187 1134 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1135 get_memory_packet_size (config));
1136 else
a3f17187 1137 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1138 get_memory_packet_size (config));
1139}
1140
1141static struct memory_packet_config memory_write_packet_config =
1142{
1143 "memory-write-packet-size",
1144};
1145
1146static void
ac88e2de 1147set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1148{
1149 set_memory_packet_size (args, &memory_write_packet_config);
1150}
1151
1152static void
ac88e2de 1153show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1154{
1155 show_memory_packet_size (&memory_write_packet_config);
1156}
1157
1158static long
1159get_memory_write_packet_size (void)
1160{
1161 return get_memory_packet_size (&memory_write_packet_config);
1162}
1163
1164static struct memory_packet_config memory_read_packet_config =
1165{
1166 "memory-read-packet-size",
1167};
1168
1169static void
ac88e2de 1170set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1171{
1172 set_memory_packet_size (args, &memory_read_packet_config);
1173}
1174
1175static void
ac88e2de 1176show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1177{
1178 show_memory_packet_size (&memory_read_packet_config);
1179}
1180
1181static long
1182get_memory_read_packet_size (void)
1183{
1184 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1185
11cf8741
JM
1186 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1187 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1188 increased beyond this. */
1189 if (size > get_remote_packet_size ())
1190 size = get_remote_packet_size ();
11cf8741
JM
1191 return size;
1192}
1193
11cf8741 1194\f
5a2468f5 1195/* Generic configuration support for packets the stub optionally
0df8b418 1196 supports. Allows the user to specify the use of the packet as well
23860348 1197 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1198
1199enum packet_support
1200 {
1201 PACKET_SUPPORT_UNKNOWN = 0,
1202 PACKET_ENABLE,
1203 PACKET_DISABLE
1204 };
1205
5a2468f5
JM
1206struct packet_config
1207 {
bb572ddd
DJ
1208 const char *name;
1209 const char *title;
4082afcc
PA
1210
1211 /* If auto, GDB auto-detects support for this packet or feature,
1212 either through qSupported, or by trying the packet and looking
1213 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1214 packet. If false, the packet is disabled. Configs that don't
1215 have an associated command always have this set to auto. */
7f19b9a2 1216 enum auto_boolean detect;
4082afcc
PA
1217
1218 /* Does the target support this packet? */
5a2468f5
JM
1219 enum packet_support support;
1220 };
1221
d471ea57 1222/* Analyze a packet's return value and update the packet config
23860348 1223 accordingly. */
d471ea57
AC
1224
1225enum packet_result
1226{
1227 PACKET_ERROR,
1228 PACKET_OK,
1229 PACKET_UNKNOWN
1230};
1231
4082afcc
PA
1232static enum packet_support packet_config_support (struct packet_config *config);
1233static enum packet_support packet_support (int packet);
5a2468f5
JM
1234
1235static void
fba45db2 1236show_packet_config_cmd (struct packet_config *config)
5a2468f5 1237{
a121b7c1 1238 const char *support = "internal-error";
a744cf53 1239
4082afcc 1240 switch (packet_config_support (config))
5a2468f5
JM
1241 {
1242 case PACKET_ENABLE:
1243 support = "enabled";
1244 break;
1245 case PACKET_DISABLE:
1246 support = "disabled";
1247 break;
1248 case PACKET_SUPPORT_UNKNOWN:
1249 support = "unknown";
1250 break;
1251 }
1252 switch (config->detect)
1253 {
7f19b9a2 1254 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1255 printf_filtered (_("Support for the `%s' packet "
1256 "is auto-detected, currently %s.\n"),
37a105a1 1257 config->name, support);
5a2468f5 1258 break;
7f19b9a2
AC
1259 case AUTO_BOOLEAN_TRUE:
1260 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1261 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1262 config->name, support);
8e248173 1263 break;
5a2468f5
JM
1264 }
1265}
1266
1267static void
bb572ddd
DJ
1268add_packet_config_cmd (struct packet_config *config, const char *name,
1269 const char *title, int legacy)
d471ea57 1270{
5a2468f5
JM
1271 char *set_doc;
1272 char *show_doc;
d471ea57 1273 char *cmd_name;
3ed07be4 1274
5a2468f5
JM
1275 config->name = name;
1276 config->title = title;
b435e160
AC
1277 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1278 name, title);
3e43a32a
MS
1279 show_doc = xstrprintf ("Show current use of remote "
1280 "protocol `%s' (%s) packet",
b435e160 1281 name, title);
d471ea57 1282 /* set/show TITLE-packet {auto,on,off} */
b435e160 1283 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1284 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1285 &config->detect, set_doc,
1286 show_doc, NULL, /* help_doc */
4082afcc 1287 NULL,
bb572ddd
DJ
1288 show_remote_protocol_packet_cmd,
1289 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1290 /* The command code copies the documentation strings. */
1291 xfree (set_doc);
1292 xfree (show_doc);
23860348 1293 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1294 if (legacy)
1295 {
1296 char *legacy_name;
a744cf53 1297
b435e160 1298 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1299 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1300 &remote_set_cmdlist);
d471ea57 1301 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1302 &remote_show_cmdlist);
d471ea57 1303 }
5a2468f5
JM
1304}
1305
d471ea57 1306static enum packet_result
a76d924d 1307packet_check_result (const char *buf)
5a2468f5 1308{
d471ea57 1309 if (buf[0] != '\0')
5a2468f5 1310 {
d471ea57 1311 /* The stub recognized the packet request. Check that the
23860348 1312 operation succeeded. */
a76d924d
DJ
1313 if (buf[0] == 'E'
1314 && isxdigit (buf[1]) && isxdigit (buf[2])
1315 && buf[3] == '\0')
1316 /* "Enn" - definitly an error. */
1317 return PACKET_ERROR;
1318
1319 /* Always treat "E." as an error. This will be used for
1320 more verbose error messages, such as E.memtypes. */
1321 if (buf[0] == 'E' && buf[1] == '.')
1322 return PACKET_ERROR;
1323
1324 /* The packet may or may not be OK. Just assume it is. */
1325 return PACKET_OK;
1326 }
1327 else
1328 /* The stub does not support the packet. */
1329 return PACKET_UNKNOWN;
1330}
1331
1332static enum packet_result
1333packet_ok (const char *buf, struct packet_config *config)
1334{
1335 enum packet_result result;
1336
4082afcc
PA
1337 if (config->detect != AUTO_BOOLEAN_TRUE
1338 && config->support == PACKET_DISABLE)
1339 internal_error (__FILE__, __LINE__,
1340 _("packet_ok: attempt to use a disabled packet"));
1341
a76d924d
DJ
1342 result = packet_check_result (buf);
1343 switch (result)
1344 {
1345 case PACKET_OK:
1346 case PACKET_ERROR:
1347 /* The stub recognized the packet request. */
4082afcc 1348 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1349 {
d471ea57
AC
1350 if (remote_debug)
1351 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1352 "Packet %s (%s) is supported\n",
1353 config->name, config->title);
d471ea57 1354 config->support = PACKET_ENABLE;
d471ea57 1355 }
a76d924d
DJ
1356 break;
1357 case PACKET_UNKNOWN:
23860348 1358 /* The stub does not support the packet. */
4082afcc
PA
1359 if (config->detect == AUTO_BOOLEAN_AUTO
1360 && config->support == PACKET_ENABLE)
d471ea57 1361 {
4082afcc
PA
1362 /* If the stub previously indicated that the packet was
1363 supported then there is a protocol error. */
1364 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1365 config->name, config->title);
1366 }
1367 else if (config->detect == AUTO_BOOLEAN_TRUE)
1368 {
1369 /* The user set it wrong. */
1370 error (_("Enabled packet %s (%s) not recognized by stub"),
1371 config->name, config->title);
d471ea57 1372 }
4082afcc
PA
1373
1374 if (remote_debug)
1375 fprintf_unfiltered (gdb_stdlog,
1376 "Packet %s (%s) is NOT supported\n",
1377 config->name, config->title);
1378 config->support = PACKET_DISABLE;
a76d924d 1379 break;
5a2468f5 1380 }
a76d924d
DJ
1381
1382 return result;
5a2468f5
JM
1383}
1384
444abaca
DJ
1385enum {
1386 PACKET_vCont = 0,
1387 PACKET_X,
1388 PACKET_qSymbol,
1389 PACKET_P,
1390 PACKET_p,
1391 PACKET_Z0,
1392 PACKET_Z1,
1393 PACKET_Z2,
1394 PACKET_Z3,
1395 PACKET_Z4,
15a201c8 1396 PACKET_vFile_setfs,
a6b151f1
DJ
1397 PACKET_vFile_open,
1398 PACKET_vFile_pread,
1399 PACKET_vFile_pwrite,
1400 PACKET_vFile_close,
1401 PACKET_vFile_unlink,
b9e7b9c3 1402 PACKET_vFile_readlink,
0a93529c 1403 PACKET_vFile_fstat,
0876f84a 1404 PACKET_qXfer_auxv,
23181151 1405 PACKET_qXfer_features,
c78fa86a 1406 PACKET_qXfer_exec_file,
cfa9d6d9 1407 PACKET_qXfer_libraries,
2268b414 1408 PACKET_qXfer_libraries_svr4,
fd79ecee 1409 PACKET_qXfer_memory_map,
0e7f50da
UW
1410 PACKET_qXfer_spu_read,
1411 PACKET_qXfer_spu_write,
07e059b5 1412 PACKET_qXfer_osdata,
dc146f7c 1413 PACKET_qXfer_threads,
0fb4aa4b 1414 PACKET_qXfer_statictrace_read,
b3b9301e 1415 PACKET_qXfer_traceframe_info,
169081d0 1416 PACKET_qXfer_uib,
711e434b 1417 PACKET_qGetTIBAddr,
444abaca 1418 PACKET_qGetTLSAddr,
be2a5f71 1419 PACKET_qSupported,
bd3eecc3 1420 PACKET_qTStatus,
89be2091 1421 PACKET_QPassSignals,
82075af2 1422 PACKET_QCatchSyscalls,
9b224c5e 1423 PACKET_QProgramSignals,
bc3b087d 1424 PACKET_QSetWorkingDir,
aefd8b33 1425 PACKET_QStartupWithShell,
0a2dde4a
SDJ
1426 PACKET_QEnvironmentHexEncoded,
1427 PACKET_QEnvironmentReset,
1428 PACKET_QEnvironmentUnset,
936d2992 1429 PACKET_qCRC,
08388c79 1430 PACKET_qSearch_memory,
2d717e4f
DJ
1431 PACKET_vAttach,
1432 PACKET_vRun,
a6f3e723 1433 PACKET_QStartNoAckMode,
82f73884 1434 PACKET_vKill,
4aa995e1
PA
1435 PACKET_qXfer_siginfo_read,
1436 PACKET_qXfer_siginfo_write,
0b16c5cf 1437 PACKET_qAttached,
4082afcc
PA
1438
1439 /* Support for conditional tracepoints. */
782b2b07 1440 PACKET_ConditionalTracepoints,
4082afcc
PA
1441
1442 /* Support for target-side breakpoint conditions. */
3788aec7 1443 PACKET_ConditionalBreakpoints,
4082afcc
PA
1444
1445 /* Support for target-side breakpoint commands. */
d3ce09f5 1446 PACKET_BreakpointCommands,
4082afcc
PA
1447
1448 /* Support for fast tracepoints. */
7a697b8d 1449 PACKET_FastTracepoints,
4082afcc
PA
1450
1451 /* Support for static tracepoints. */
0fb4aa4b 1452 PACKET_StaticTracepoints,
4082afcc
PA
1453
1454 /* Support for installing tracepoints while a trace experiment is
1455 running. */
1e4d1764 1456 PACKET_InstallInTrace,
4082afcc 1457
40ab02ce
MS
1458 PACKET_bc,
1459 PACKET_bs,
409873ef 1460 PACKET_TracepointSource,
d914c394 1461 PACKET_QAllow,
78d85199 1462 PACKET_qXfer_fdpic,
03583c20 1463 PACKET_QDisableRandomization,
d1feda86 1464 PACKET_QAgent,
f6f899bf 1465 PACKET_QTBuffer_size,
9accd112
MM
1466 PACKET_Qbtrace_off,
1467 PACKET_Qbtrace_bts,
b20a6524 1468 PACKET_Qbtrace_pt,
9accd112 1469 PACKET_qXfer_btrace,
4082afcc
PA
1470
1471 /* Support for the QNonStop packet. */
1472 PACKET_QNonStop,
1473
65706a29
PA
1474 /* Support for the QThreadEvents packet. */
1475 PACKET_QThreadEvents,
1476
4082afcc
PA
1477 /* Support for multi-process extensions. */
1478 PACKET_multiprocess_feature,
1479
1480 /* Support for enabling and disabling tracepoints while a trace
1481 experiment is running. */
1482 PACKET_EnableDisableTracepoints_feature,
1483
1484 /* Support for collecting strings using the tracenz bytecode. */
1485 PACKET_tracenz_feature,
1486
1487 /* Support for continuing to run a trace experiment while GDB is
1488 disconnected. */
1489 PACKET_DisconnectedTracing_feature,
1490
1491 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1492 PACKET_augmented_libraries_svr4_read_feature,
1493
f4abbc16
MM
1494 /* Support for the qXfer:btrace-conf:read packet. */
1495 PACKET_qXfer_btrace_conf,
1496
d33501a5
MM
1497 /* Support for the Qbtrace-conf:bts:size packet. */
1498 PACKET_Qbtrace_conf_bts_size,
1499
f7e6eed5
PA
1500 /* Support for swbreak+ feature. */
1501 PACKET_swbreak_feature,
1502
1503 /* Support for hwbreak+ feature. */
1504 PACKET_hwbreak_feature,
1505
89245bc0
DB
1506 /* Support for fork events. */
1507 PACKET_fork_event_feature,
1508
1509 /* Support for vfork events. */
1510 PACKET_vfork_event_feature,
1511
b20a6524
MM
1512 /* Support for the Qbtrace-conf:pt:size packet. */
1513 PACKET_Qbtrace_conf_pt_size,
1514
94585166
DB
1515 /* Support for exec events. */
1516 PACKET_exec_event_feature,
1517
750ce8d1
YQ
1518 /* Support for query supported vCont actions. */
1519 PACKET_vContSupported,
1520
de979965
PA
1521 /* Support remote CTRL-C. */
1522 PACKET_vCtrlC,
1523
f2faf941
PA
1524 /* Support TARGET_WAITKIND_NO_RESUMED. */
1525 PACKET_no_resumed,
1526
444abaca
DJ
1527 PACKET_MAX
1528};
506fb367 1529
444abaca 1530static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1531
f7e6eed5
PA
1532/* Returns the packet's corresponding "set remote foo-packet" command
1533 state. See struct packet_config for more details. */
1534
1535static enum auto_boolean
1536packet_set_cmd_state (int packet)
1537{
1538 return remote_protocol_packets[packet].detect;
1539}
1540
4082afcc
PA
1541/* Returns whether a given packet or feature is supported. This takes
1542 into account the state of the corresponding "set remote foo-packet"
1543 command, which may be used to bypass auto-detection. */
dc8acb97 1544
4082afcc
PA
1545static enum packet_support
1546packet_config_support (struct packet_config *config)
1547{
1548 switch (config->detect)
444abaca 1549 {
4082afcc
PA
1550 case AUTO_BOOLEAN_TRUE:
1551 return PACKET_ENABLE;
1552 case AUTO_BOOLEAN_FALSE:
1553 return PACKET_DISABLE;
1554 case AUTO_BOOLEAN_AUTO:
1555 return config->support;
1556 default:
1557 gdb_assert_not_reached (_("bad switch"));
444abaca 1558 }
4082afcc
PA
1559}
1560
1561/* Same as packet_config_support, but takes the packet's enum value as
1562 argument. */
1563
1564static enum packet_support
1565packet_support (int packet)
1566{
1567 struct packet_config *config = &remote_protocol_packets[packet];
1568
1569 return packet_config_support (config);
dc8acb97
MS
1570}
1571
5a2468f5 1572static void
444abaca
DJ
1573show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1574 struct cmd_list_element *c,
1575 const char *value)
5a2468f5 1576{
444abaca 1577 struct packet_config *packet;
5a2468f5 1578
444abaca
DJ
1579 for (packet = remote_protocol_packets;
1580 packet < &remote_protocol_packets[PACKET_MAX];
1581 packet++)
1582 {
1583 if (&packet->detect == c->var)
1584 {
1585 show_packet_config_cmd (packet);
1586 return;
1587 }
1588 }
9b20d036 1589 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1590 c->name);
5a2468f5
JM
1591}
1592
d471ea57
AC
1593/* Should we try one of the 'Z' requests? */
1594
1595enum Z_packet_type
1596{
1597 Z_PACKET_SOFTWARE_BP,
1598 Z_PACKET_HARDWARE_BP,
1599 Z_PACKET_WRITE_WP,
1600 Z_PACKET_READ_WP,
1601 Z_PACKET_ACCESS_WP,
1602 NR_Z_PACKET_TYPES
1603};
96baa820 1604
d471ea57 1605/* For compatibility with older distributions. Provide a ``set remote
23860348 1606 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1607
7f19b9a2 1608static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1609
1610static void
fba45db2
KB
1611set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1612 struct cmd_list_element *c)
96baa820 1613{
d471ea57 1614 int i;
a744cf53 1615
d471ea57 1616 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1617 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1618}
1619
1620static void
08546159
AC
1621show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1622 struct cmd_list_element *c,
1623 const char *value)
96baa820 1624{
d471ea57 1625 int i;
a744cf53 1626
d471ea57
AC
1627 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1628 {
444abaca 1629 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1630 }
96baa820
JM
1631}
1632
4082afcc
PA
1633/* Returns true if the multi-process extensions are in effect. */
1634
1635static int
1636remote_multi_process_p (struct remote_state *rs)
1637{
1638 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1639}
1640
de0d863e
DB
1641/* Returns true if fork events are supported. */
1642
1643static int
1644remote_fork_event_p (struct remote_state *rs)
1645{
1646 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1647}
1648
c269dbdb
DB
1649/* Returns true if vfork events are supported. */
1650
1651static int
1652remote_vfork_event_p (struct remote_state *rs)
1653{
1654 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1655}
1656
d46addbb
DB
1657/* Returns true if exec events are supported. */
1658
1659static int
1660remote_exec_event_p (struct remote_state *rs)
1661{
1662 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1663}
1664
cbb8991c
DB
1665/* Insert fork catchpoint target routine. If fork events are enabled
1666 then return success, nothing more to do. */
1667
1668static int
1669remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1670{
1671 struct remote_state *rs = get_remote_state ();
1672
1673 return !remote_fork_event_p (rs);
1674}
1675
1676/* Remove fork catchpoint target routine. Nothing to do, just
1677 return success. */
1678
1679static int
1680remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1681{
1682 return 0;
1683}
1684
1685/* Insert vfork catchpoint target routine. If vfork events are enabled
1686 then return success, nothing more to do. */
1687
1688static int
1689remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1690{
1691 struct remote_state *rs = get_remote_state ();
1692
1693 return !remote_vfork_event_p (rs);
1694}
1695
1696/* Remove vfork catchpoint target routine. Nothing to do, just
1697 return success. */
1698
1699static int
1700remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1701{
1702 return 0;
1703}
1704
d46addbb
DB
1705/* Insert exec catchpoint target routine. If exec events are
1706 enabled, just return success. */
1707
1708static int
1709remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1710{
1711 struct remote_state *rs = get_remote_state ();
1712
1713 return !remote_exec_event_p (rs);
1714}
1715
1716/* Remove exec catchpoint target routine. Nothing to do, just
1717 return success. */
1718
1719static int
1720remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1721{
1722 return 0;
1723}
1724
74531fed
PA
1725\f
1726/* Asynchronous signal handle registered as event loop source for
1727 when we have pending events ready to be passed to the core. */
1728
1729static struct async_event_handler *remote_async_inferior_event_token;
1730
c906108c
SS
1731\f
1732
79d7f229
PA
1733static ptid_t magic_null_ptid;
1734static ptid_t not_sent_ptid;
1735static ptid_t any_thread_ptid;
1736
0b16c5cf
PA
1737/* Find out if the stub attached to PID (and hence GDB should offer to
1738 detach instead of killing it when bailing out). */
1739
1740static int
1741remote_query_attached (int pid)
1742{
1743 struct remote_state *rs = get_remote_state ();
bba74b36 1744 size_t size = get_remote_packet_size ();
0b16c5cf 1745
4082afcc 1746 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1747 return 0;
1748
1749 if (remote_multi_process_p (rs))
bba74b36 1750 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1751 else
bba74b36 1752 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1753
1754 putpkt (rs->buf);
1755 getpkt (&rs->buf, &rs->buf_size, 0);
1756
1757 switch (packet_ok (rs->buf,
1554e9be 1758 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1759 {
1760 case PACKET_OK:
1761 if (strcmp (rs->buf, "1") == 0)
1762 return 1;
1763 break;
1764 case PACKET_ERROR:
1765 warning (_("Remote failure reply: %s"), rs->buf);
1766 break;
1767 case PACKET_UNKNOWN:
1768 break;
1769 }
1770
1771 return 0;
1772}
1773
49c62f2e
PA
1774/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1775 has been invented by GDB, instead of reported by the target. Since
1776 we can be connected to a remote system before before knowing about
1777 any inferior, mark the target with execution when we find the first
1778 inferior. If ATTACHED is 1, then we had just attached to this
1779 inferior. If it is 0, then we just created this inferior. If it
1780 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1781 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1782 attempt to open this inferior's executable as the main executable
1783 if no main executable is open already. */
1941c569
PA
1784
1785static struct inferior *
1b6e6f5c
GB
1786remote_add_inferior (int fake_pid_p, int pid, int attached,
1787 int try_open_exec)
1941c569 1788{
1941c569
PA
1789 struct inferior *inf;
1790
0b16c5cf
PA
1791 /* Check whether this process we're learning about is to be
1792 considered attached, or if is to be considered to have been
1793 spawned by the stub. */
1794 if (attached == -1)
1795 attached = remote_query_attached (pid);
1796
f5656ead 1797 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1798 {
1799 /* If the target shares code across all inferiors, then every
1800 attach adds a new inferior. */
1801 inf = add_inferior (pid);
1802
1803 /* ... and every inferior is bound to the same program space.
1804 However, each inferior may still have its own address
1805 space. */
1806 inf->aspace = maybe_new_address_space ();
1807 inf->pspace = current_program_space;
1808 }
1809 else
1810 {
1811 /* In the traditional debugging scenario, there's a 1-1 match
1812 between program/address spaces. We simply bind the inferior
1813 to the program space's address space. */
1814 inf = current_inferior ();
1815 inferior_appeared (inf, pid);
1816 }
1941c569 1817
0b16c5cf 1818 inf->attach_flag = attached;
49c62f2e 1819 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1820
1b6e6f5c
GB
1821 /* If no main executable is currently open then attempt to
1822 open the file that was executed to create this inferior. */
835205d0 1823 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 1824 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 1825
1941c569
PA
1826 return inf;
1827}
1828
85ad3aaf
PA
1829static struct private_thread_info *
1830 get_private_info_thread (struct thread_info *info);
1831
1941c569
PA
1832/* Add thread PTID to GDB's thread list. Tag it as executing/running
1833 according to RUNNING. */
1834
c906108c 1835static void
0d5b594f 1836remote_add_thread (ptid_t ptid, int running, int executing)
c906108c 1837{
b7ea362b 1838 struct remote_state *rs = get_remote_state ();
85ad3aaf 1839 struct thread_info *thread;
b7ea362b
PA
1840
1841 /* GDB historically didn't pull threads in the initial connection
1842 setup. If the remote target doesn't even have a concept of
1843 threads (e.g., a bare-metal target), even if internally we
1844 consider that a single-threaded target, mentioning a new thread
1845 might be confusing to the user. Be silent then, preserving the
1846 age old behavior. */
1847 if (rs->starting_up)
85ad3aaf 1848 thread = add_thread_silent (ptid);
b7ea362b 1849 else
85ad3aaf 1850 thread = add_thread (ptid);
1941c569 1851
85ad3aaf 1852 get_private_info_thread (thread)->vcont_resumed = executing;
0d5b594f 1853 set_executing (ptid, executing);
1941c569
PA
1854 set_running (ptid, running);
1855}
1856
1857/* Come here when we learn about a thread id from the remote target.
1858 It may be the first time we hear about such thread, so take the
1859 opportunity to add it to GDB's thread list. In case this is the
1860 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
1861 GDB's inferior list as well. EXECUTING indicates whether the
1862 thread is (internally) executing or stopped. */
1941c569
PA
1863
1864static void
0d5b594f 1865remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 1866{
0d5b594f
PA
1867 /* In non-stop mode, we assume new found threads are (externally)
1868 running until proven otherwise with a stop reply. In all-stop,
1869 we can only get here if all threads are stopped. */
1870 int running = target_is_non_stop_p () ? 1 : 0;
1871
c906108c
SS
1872 /* If this is a new thread, add it to GDB's thread list.
1873 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1874
1875 if (in_thread_list (currthread) && is_exited (currthread))
1876 {
1877 /* We're seeing an event on a thread id we knew had exited.
1878 This has to be a new thread reusing the old id. Add it. */
0d5b594f 1879 remote_add_thread (currthread, running, executing);
82f73884
PA
1880 return;
1881 }
1882
79d7f229 1883 if (!in_thread_list (currthread))
c0a2216e 1884 {
1941c569 1885 struct inferior *inf = NULL;
bad34192 1886 int pid = ptid_get_pid (currthread);
1941c569 1887
bad34192
PA
1888 if (ptid_is_pid (inferior_ptid)
1889 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1890 {
1891 /* inferior_ptid has no thread member yet. This can happen
1892 with the vAttach -> remote_wait,"TAAthread:" path if the
1893 stub doesn't support qC. This is the first stop reported
1894 after an attach, so this is the main thread. Update the
1895 ptid in the thread list. */
bad34192
PA
1896 if (in_thread_list (pid_to_ptid (pid)))
1897 thread_change_ptid (inferior_ptid, currthread);
1898 else
1899 {
0d5b594f 1900 remote_add_thread (currthread, running, executing);
bad34192
PA
1901 inferior_ptid = currthread;
1902 }
dc146f7c 1903 return;
c0a2216e 1904 }
82f73884
PA
1905
1906 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1907 {
1908 /* inferior_ptid is not set yet. This can happen with the
1909 vRun -> remote_wait,"TAAthread:" path if the stub
1910 doesn't support qC. This is the first stop reported
1911 after an attach, so this is the main thread. Update the
1912 ptid in the thread list. */
dc146f7c 1913 thread_change_ptid (inferior_ptid, currthread);
82f73884 1914 return;
c0a2216e 1915 }
82f73884 1916
29c87f7f
PA
1917 /* When connecting to a target remote, or to a target
1918 extended-remote which already was debugging an inferior, we
1919 may not know about it yet. Add it before adding its child
1920 thread, so notifications are emitted in a sensible order. */
1921 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1922 {
1923 struct remote_state *rs = get_remote_state ();
1924 int fake_pid_p = !remote_multi_process_p (rs);
1925
1926 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1927 ptid_get_pid (currthread), -1, 1);
49c62f2e 1928 }
29c87f7f 1929
82f73884 1930 /* This is really a new thread. Add it. */
0d5b594f 1931 remote_add_thread (currthread, running, executing);
1941c569
PA
1932
1933 /* If we found a new inferior, let the common code do whatever
1934 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1935 breakpoints), unless we're just setting up an all-stop
1936 connection. */
1941c569 1937 if (inf != NULL)
b7ea362b
PA
1938 {
1939 struct remote_state *rs = get_remote_state ();
1940
6efcd9a8 1941 if (!rs->starting_up)
0d5b594f 1942 notice_new_inferior (currthread, executing, 0);
b7ea362b 1943 }
c0a2216e 1944 }
c906108c
SS
1945}
1946
85ad3aaf 1947/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 1948
70221824 1949static struct private_thread_info *
85ad3aaf 1950get_private_info_thread (struct thread_info *thread)
dc146f7c 1951{
85ad3aaf 1952 gdb_assert (thread != NULL);
dc146f7c 1953
85ad3aaf 1954 if (thread->priv == NULL)
dc146f7c 1955 {
85ad3aaf
PA
1956 struct private_thread_info *priv = XNEW (struct private_thread_info);
1957
1958 thread->private_dtor = free_private_thread_info;
1959 thread->priv = priv;
1960
1961 priv->core = -1;
1962 priv->extra = NULL;
1963 priv->name = NULL;
1964 priv->name = NULL;
1965 priv->last_resume_step = 0;
1966 priv->last_resume_sig = GDB_SIGNAL_0;
1967 priv->vcont_resumed = 0;
f6327dcb 1968 priv->thread_handle = nullptr;
dc146f7c
VP
1969 }
1970
85ad3aaf
PA
1971 return thread->priv;
1972}
1973
1974/* Return PTID's private thread data, creating it if necessary. */
1975
1976static struct private_thread_info *
1977get_private_info_ptid (ptid_t ptid)
1978{
1979 struct thread_info *info = find_thread_ptid (ptid);
1980
1981 return get_private_info_thread (info);
dc146f7c
VP
1982}
1983
74531fed
PA
1984/* Call this function as a result of
1985 1) A halt indication (T packet) containing a thread id
1986 2) A direct query of currthread
0df8b418 1987 3) Successful execution of set thread */
74531fed
PA
1988
1989static void
47f8a51d 1990record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1991{
47f8a51d 1992 rs->general_thread = currthread;
74531fed
PA
1993}
1994
89be2091
DJ
1995/* If 'QPassSignals' is supported, tell the remote stub what signals
1996 it can simply pass through to the inferior without reporting. */
1997
1998static void
94bedb42
TT
1999remote_pass_signals (struct target_ops *self,
2000 int numsigs, unsigned char *pass_signals)
89be2091 2001{
4082afcc 2002 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2003 {
2004 char *pass_packet, *p;
89be2091 2005 int count = 0, i;
747dc59d 2006 struct remote_state *rs = get_remote_state ();
89be2091
DJ
2007
2008 gdb_assert (numsigs < 256);
2009 for (i = 0; i < numsigs; i++)
2010 {
2455069d 2011 if (pass_signals[i])
89be2091
DJ
2012 count++;
2013 }
224c3ddb 2014 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2015 strcpy (pass_packet, "QPassSignals:");
2016 p = pass_packet + strlen (pass_packet);
2017 for (i = 0; i < numsigs; i++)
2018 {
2455069d 2019 if (pass_signals[i])
89be2091
DJ
2020 {
2021 if (i >= 16)
2022 *p++ = tohex (i >> 4);
2023 *p++ = tohex (i & 15);
2024 if (count)
2025 *p++ = ';';
2026 else
2027 break;
2028 count--;
2029 }
2030 }
2031 *p = 0;
747dc59d 2032 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2033 {
89be2091
DJ
2034 putpkt (pass_packet);
2035 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2036 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2037 if (rs->last_pass_packet)
2038 xfree (rs->last_pass_packet);
2039 rs->last_pass_packet = pass_packet;
89be2091
DJ
2040 }
2041 else
2042 xfree (pass_packet);
2043 }
2044}
2045
82075af2
JS
2046/* If 'QCatchSyscalls' is supported, tell the remote stub
2047 to report syscalls to GDB. */
2048
2049static int
2050remote_set_syscall_catchpoint (struct target_ops *self,
2051 int pid, int needed, int any_count,
2052 int table_size, int *table)
2053{
b80406ac 2054 const char *catch_packet;
82075af2
JS
2055 enum packet_result result;
2056 int n_sysno = 0;
2057
2058 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2059 {
2060 /* Not supported. */
2061 return 1;
2062 }
2063
2064 if (needed && !any_count)
2065 {
2066 int i;
2067
2068 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2069 for (i = 0; i < table_size; i++)
2070 {
2071 if (table[i] != 0)
2072 n_sysno++;
2073 }
2074 }
2075
2076 if (remote_debug)
2077 {
2078 fprintf_unfiltered (gdb_stdlog,
2079 "remote_set_syscall_catchpoint "
2080 "pid %d needed %d any_count %d n_sysno %d\n",
2081 pid, needed, any_count, n_sysno);
2082 }
2083
b80406ac 2084 gdb::unique_xmalloc_ptr<char> built_packet;
82075af2
JS
2085 if (needed)
2086 {
2087 /* Prepare a packet with the sysno list, assuming max 8+1
2088 characters for a sysno. If the resulting packet size is too
2089 big, fallback on the non-selective packet. */
2090 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2091
b80406ac
TT
2092 built_packet.reset ((char *) xmalloc (maxpktsz));
2093 strcpy (built_packet.get (), "QCatchSyscalls:1");
82075af2
JS
2094 if (!any_count)
2095 {
2096 int i;
2097 char *p;
2098
b80406ac 2099 p = built_packet.get ();
82075af2
JS
2100 p += strlen (p);
2101
2102 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2103 for (i = 0; i < table_size; i++)
2104 {
2105 if (table[i] != 0)
b80406ac
TT
2106 p += xsnprintf (p, built_packet.get () + maxpktsz - p,
2107 ";%x", i);
82075af2
JS
2108 }
2109 }
b80406ac 2110 if (strlen (built_packet.get ()) > get_remote_packet_size ())
82075af2
JS
2111 {
2112 /* catch_packet too big. Fallback to less efficient
2113 non selective mode, with GDB doing the filtering. */
b80406ac 2114 catch_packet = "QCatchSyscalls:1";
82075af2 2115 }
b80406ac
TT
2116 else
2117 catch_packet = built_packet.get ();
82075af2
JS
2118 }
2119 else
b80406ac 2120 catch_packet = "QCatchSyscalls:0";
82075af2 2121
b80406ac 2122 struct remote_state *rs = get_remote_state ();
82075af2 2123
b80406ac
TT
2124 putpkt (catch_packet);
2125 getpkt (&rs->buf, &rs->buf_size, 0);
2126 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2127 if (result == PACKET_OK)
2128 return 0;
2129 else
2130 return -1;
82075af2
JS
2131}
2132
9b224c5e
PA
2133/* If 'QProgramSignals' is supported, tell the remote stub what
2134 signals it should pass through to the inferior when detaching. */
2135
2136static void
daf5e9b6
TT
2137remote_program_signals (struct target_ops *self,
2138 int numsigs, unsigned char *signals)
9b224c5e 2139{
4082afcc 2140 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2141 {
2142 char *packet, *p;
2143 int count = 0, i;
5e4a05c4 2144 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2145
2146 gdb_assert (numsigs < 256);
2147 for (i = 0; i < numsigs; i++)
2148 {
2149 if (signals[i])
2150 count++;
2151 }
224c3ddb 2152 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2153 strcpy (packet, "QProgramSignals:");
2154 p = packet + strlen (packet);
2155 for (i = 0; i < numsigs; i++)
2156 {
2157 if (signal_pass_state (i))
2158 {
2159 if (i >= 16)
2160 *p++ = tohex (i >> 4);
2161 *p++ = tohex (i & 15);
2162 if (count)
2163 *p++ = ';';
2164 else
2165 break;
2166 count--;
2167 }
2168 }
2169 *p = 0;
5e4a05c4
TT
2170 if (!rs->last_program_signals_packet
2171 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2172 {
9b224c5e
PA
2173 putpkt (packet);
2174 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2175 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2176 xfree (rs->last_program_signals_packet);
2177 rs->last_program_signals_packet = packet;
9b224c5e
PA
2178 }
2179 else
2180 xfree (packet);
2181 }
2182}
2183
79d7f229
PA
2184/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2185 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2186 thread. If GEN is set, set the general thread, if not, then set
2187 the step/continue thread. */
c906108c 2188static void
d62a8ae2 2189set_thread (ptid_t ptid, int gen)
c906108c 2190{
d01949b6 2191 struct remote_state *rs = get_remote_state ();
47f8a51d 2192 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2193 char *buf = rs->buf;
79d7f229 2194 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2195
79d7f229 2196 if (ptid_equal (state, ptid))
c906108c
SS
2197 return;
2198
79d7f229
PA
2199 *buf++ = 'H';
2200 *buf++ = gen ? 'g' : 'c';
2201 if (ptid_equal (ptid, magic_null_ptid))
2202 xsnprintf (buf, endbuf - buf, "0");
2203 else if (ptid_equal (ptid, any_thread_ptid))
2204 xsnprintf (buf, endbuf - buf, "0");
2205 else if (ptid_equal (ptid, minus_one_ptid))
2206 xsnprintf (buf, endbuf - buf, "-1");
2207 else
82f73884 2208 write_ptid (buf, endbuf, ptid);
79d7f229 2209 putpkt (rs->buf);
6d820c5c 2210 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2211 if (gen)
47f8a51d 2212 rs->general_thread = ptid;
c906108c 2213 else
47f8a51d 2214 rs->continue_thread = ptid;
c906108c 2215}
79d7f229
PA
2216
2217static void
d62a8ae2 2218set_general_thread (ptid_t ptid)
79d7f229
PA
2219{
2220 set_thread (ptid, 1);
2221}
2222
2223static void
d62a8ae2 2224set_continue_thread (ptid_t ptid)
79d7f229
PA
2225{
2226 set_thread (ptid, 0);
2227}
2228
3c9c4b83
PA
2229/* Change the remote current process. Which thread within the process
2230 ends up selected isn't important, as long as it is the same process
2231 as what INFERIOR_PTID points to.
2232
2233 This comes from that fact that there is no explicit notion of
2234 "selected process" in the protocol. The selected process for
2235 general operations is the process the selected general thread
2236 belongs to. */
2237
2238static void
2239set_general_process (void)
2240{
2241 struct remote_state *rs = get_remote_state ();
2242
2243 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2244 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2245 return;
2246
2247 /* We only need to change the remote current thread if it's pointing
2248 at some other process. */
47f8a51d 2249 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2250 set_general_thread (inferior_ptid);
2251}
2252
c906108c 2253\f
7d1a114c
PA
2254/* Return nonzero if this is the main thread that we made up ourselves
2255 to model non-threaded targets as single-threaded. */
c906108c
SS
2256
2257static int
7d1a114c 2258remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2259{
c0a2216e
PA
2260 if (ptid_equal (ptid, magic_null_ptid))
2261 /* The main thread is always alive. */
2262 return 1;
2263
ba348170 2264 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2265 /* The main thread is always alive. This can happen after a
2266 vAttach, if the remote side doesn't support
2267 multi-threading. */
2268 return 1;
2269
7d1a114c
PA
2270 return 0;
2271}
2272
2273/* Return nonzero if the thread PTID is still alive on the remote
2274 system. */
2275
2276static int
2277remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2278{
2279 struct remote_state *rs = get_remote_state ();
2280 char *p, *endp;
2281
2282 /* Check if this is a thread that we made up ourselves to model
2283 non-threaded targets as single-threaded. */
2284 if (remote_thread_always_alive (ops, ptid))
2285 return 1;
2286
82f73884
PA
2287 p = rs->buf;
2288 endp = rs->buf + get_remote_packet_size ();
2289
2290 *p++ = 'T';
2291 write_ptid (p, endp, ptid);
2292
2e9f7625 2293 putpkt (rs->buf);
6d820c5c 2294 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2295 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2296}
2297
79efa585
SM
2298/* Return a pointer to a thread name if we know it and NULL otherwise.
2299 The thread_info object owns the memory for the name. */
2300
2301static const char *
2302remote_thread_name (struct target_ops *ops, struct thread_info *info)
2303{
2304 if (info->priv != NULL)
2305 return info->priv->name;
2306
2307 return NULL;
2308}
2309
c906108c
SS
2310/* About these extended threadlist and threadinfo packets. They are
2311 variable length packets but, the fields within them are often fixed
2312 length. They are redundent enough to send over UDP as is the
2313 remote protocol in general. There is a matching unit test module
2314 in libstub. */
2315
23860348 2316/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2317 libstub protocol encoding, and remote.c. It is not particularly
23860348 2318 changable. */
cce74817
JM
2319
2320/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2321 Plan to fix this. */
cce74817 2322
23860348 2323typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2324
9d1f7ab2 2325/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2326 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2327
2328struct gdb_ext_thread_info
c5aa993b 2329 {
23860348 2330 threadref threadid; /* External form of thread reference. */
2bc416ba 2331 int active; /* Has state interesting to GDB?
23860348 2332 regs, stack. */
2bc416ba 2333 char display[256]; /* Brief state display, name,
cedea757 2334 blocked/suspended. */
23860348 2335 char shortname[32]; /* To be used to name threads. */
2bc416ba 2336 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2337 whatever. */
c5aa993b 2338 };
cce74817
JM
2339
2340/* The volume of remote transfers can be limited by submitting
2341 a mask containing bits specifying the desired information.
2342 Use a union of these values as the 'selection' parameter to
0df8b418 2343 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2344
2345#define TAG_THREADID 1
2346#define TAG_EXISTS 2
2347#define TAG_DISPLAY 4
2348#define TAG_THREADNAME 8
c5aa993b 2349#define TAG_MOREDISPLAY 16
cce74817 2350
23860348 2351#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2352
a14ed312 2353static char *unpack_nibble (char *buf, int *val);
cce74817 2354
a14ed312 2355static char *unpack_byte (char *buf, int *value);
cce74817 2356
a14ed312 2357static char *pack_int (char *buf, int value);
cce74817 2358
a14ed312 2359static char *unpack_int (char *buf, int *value);
cce74817 2360
a14ed312 2361static char *unpack_string (char *src, char *dest, int length);
cce74817 2362
23860348 2363static char *pack_threadid (char *pkt, threadref *id);
cce74817 2364
23860348 2365static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2366
23860348 2367void int_to_threadref (threadref *id, int value);
cce74817 2368
23860348 2369static int threadref_to_int (threadref *ref);
cce74817 2370
23860348 2371static void copy_threadref (threadref *dest, threadref *src);
cce74817 2372
23860348 2373static int threadmatch (threadref *dest, threadref *src);
cce74817 2374
2bc416ba 2375static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2376 threadref *id);
cce74817 2377
a14ed312 2378static int remote_unpack_thread_info_response (char *pkt,
23860348 2379 threadref *expectedref,
a14ed312
KB
2380 struct gdb_ext_thread_info
2381 *info);
cce74817
JM
2382
2383
2bc416ba 2384static int remote_get_threadinfo (threadref *threadid,
23860348 2385 int fieldset, /*TAG mask */
a14ed312 2386 struct gdb_ext_thread_info *info);
cce74817 2387
a14ed312
KB
2388static char *pack_threadlist_request (char *pkt, int startflag,
2389 int threadcount,
23860348 2390 threadref *nextthread);
cce74817 2391
a14ed312
KB
2392static int parse_threadlist_response (char *pkt,
2393 int result_limit,
23860348 2394 threadref *original_echo,
2bc416ba 2395 threadref *resultlist,
23860348 2396 int *doneflag);
cce74817 2397
a14ed312 2398static int remote_get_threadlist (int startflag,
23860348 2399 threadref *nextthread,
a14ed312
KB
2400 int result_limit,
2401 int *done,
2bc416ba 2402 int *result_count,
23860348 2403 threadref *threadlist);
cce74817 2404
23860348 2405typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2406
a14ed312
KB
2407static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2408 void *context, int looplimit);
cce74817 2409
23860348 2410static int remote_newthread_step (threadref *ref, void *context);
cce74817 2411
82f73884
PA
2412
2413/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2414 buffer we're allowed to write to. Returns
2415 BUF+CHARACTERS_WRITTEN. */
2416
2417static char *
2418write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2419{
2420 int pid, tid;
2421 struct remote_state *rs = get_remote_state ();
2422
2423 if (remote_multi_process_p (rs))
2424 {
2425 pid = ptid_get_pid (ptid);
2426 if (pid < 0)
2427 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2428 else
2429 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2430 }
ba348170 2431 tid = ptid_get_lwp (ptid);
82f73884
PA
2432 if (tid < 0)
2433 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2434 else
2435 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2436
2437 return buf;
2438}
2439
256642e8
PA
2440/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2441 last parsed char. Returns null_ptid if no thread id is found, and
2442 throws an error if the thread id has an invalid format. */
82f73884
PA
2443
2444static ptid_t
256642e8 2445read_ptid (const char *buf, const char **obuf)
82f73884 2446{
256642e8
PA
2447 const char *p = buf;
2448 const char *pp;
82f73884 2449 ULONGEST pid = 0, tid = 0;
82f73884
PA
2450
2451 if (*p == 'p')
2452 {
2453 /* Multi-process ptid. */
2454 pp = unpack_varlen_hex (p + 1, &pid);
2455 if (*pp != '.')
b37520b6 2456 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2457
2458 p = pp;
2459 pp = unpack_varlen_hex (p + 1, &tid);
2460 if (obuf)
2461 *obuf = pp;
ba348170 2462 return ptid_build (pid, tid, 0);
82f73884
PA
2463 }
2464
2465 /* No multi-process. Just a tid. */
2466 pp = unpack_varlen_hex (p, &tid);
2467
c9f35b34
KB
2468 /* Return null_ptid when no thread id is found. */
2469 if (p == pp)
2470 {
2471 if (obuf)
2472 *obuf = pp;
2473 return null_ptid;
2474 }
2475
82f73884 2476 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2477 what's in inferior_ptid, unless it's null at this point. If so,
2478 then since there's no way to know the pid of the reported
2479 threads, use the magic number. */
2480 if (ptid_equal (inferior_ptid, null_ptid))
2481 pid = ptid_get_pid (magic_null_ptid);
2482 else
2483 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2484
2485 if (obuf)
2486 *obuf = pp;
ba348170 2487 return ptid_build (pid, tid, 0);
82f73884
PA
2488}
2489
c906108c 2490static int
fba45db2 2491stubhex (int ch)
c906108c
SS
2492{
2493 if (ch >= 'a' && ch <= 'f')
2494 return ch - 'a' + 10;
2495 if (ch >= '0' && ch <= '9')
2496 return ch - '0';
2497 if (ch >= 'A' && ch <= 'F')
2498 return ch - 'A' + 10;
2499 return -1;
2500}
2501
2502static int
fba45db2 2503stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2504{
2505 int nibble;
2506 int retval = 0;
2507
2508 while (fieldlength)
2509 {
2510 nibble = stubhex (*buff++);
2511 retval |= nibble;
2512 fieldlength--;
2513 if (fieldlength)
2514 retval = retval << 4;
2515 }
2516 return retval;
2517}
2518
c906108c 2519static char *
fba45db2 2520unpack_nibble (char *buf, int *val)
c906108c 2521{
b7589f7d 2522 *val = fromhex (*buf++);
c906108c
SS
2523 return buf;
2524}
2525
c906108c 2526static char *
fba45db2 2527unpack_byte (char *buf, int *value)
c906108c
SS
2528{
2529 *value = stub_unpack_int (buf, 2);
2530 return buf + 2;
2531}
2532
2533static char *
fba45db2 2534pack_int (char *buf, int value)
c906108c
SS
2535{
2536 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2537 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2538 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2539 buf = pack_hex_byte (buf, (value & 0xff));
2540 return buf;
2541}
2542
2543static char *
fba45db2 2544unpack_int (char *buf, int *value)
c906108c
SS
2545{
2546 *value = stub_unpack_int (buf, 8);
2547 return buf + 8;
2548}
2549
23860348 2550#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2551static char *pack_string (char *pkt, char *string);
c906108c
SS
2552
2553static char *
fba45db2 2554pack_string (char *pkt, char *string)
c906108c
SS
2555{
2556 char ch;
2557 int len;
2558
2559 len = strlen (string);
2560 if (len > 200)
23860348 2561 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2562 pkt = pack_hex_byte (pkt, len);
2563 while (len-- > 0)
2564 {
2565 ch = *string++;
2566 if ((ch == '\0') || (ch == '#'))
23860348 2567 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2568 *pkt++ = ch;
2569 }
2570 return pkt;
2571}
2572#endif /* 0 (unused) */
2573
2574static char *
fba45db2 2575unpack_string (char *src, char *dest, int length)
c906108c
SS
2576{
2577 while (length--)
2578 *dest++ = *src++;
2579 *dest = '\0';
2580 return src;
2581}
2582
2583static char *
fba45db2 2584pack_threadid (char *pkt, threadref *id)
c906108c
SS
2585{
2586 char *limit;
2587 unsigned char *altid;
2588
2589 altid = (unsigned char *) id;
2590 limit = pkt + BUF_THREAD_ID_SIZE;
2591 while (pkt < limit)
2592 pkt = pack_hex_byte (pkt, *altid++);
2593 return pkt;
2594}
2595
2596
2597static char *
fba45db2 2598unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2599{
2600 char *altref;
2601 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2602 int x, y;
2603
2604 altref = (char *) id;
2605
2606 while (inbuf < limit)
2607 {
2608 x = stubhex (*inbuf++);
2609 y = stubhex (*inbuf++);
2610 *altref++ = (x << 4) | y;
2611 }
2612 return inbuf;
2613}
2614
2615/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2616 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2617 to use 64bit thread references internally. This is an adapter
2618 function. */
2619
2620void
fba45db2 2621int_to_threadref (threadref *id, int value)
c906108c
SS
2622{
2623 unsigned char *scan;
2624
2625 scan = (unsigned char *) id;
2626 {
2627 int i = 4;
2628 while (i--)
2629 *scan++ = 0;
2630 }
2631 *scan++ = (value >> 24) & 0xff;
2632 *scan++ = (value >> 16) & 0xff;
2633 *scan++ = (value >> 8) & 0xff;
2634 *scan++ = (value & 0xff);
2635}
2636
2637static int
fba45db2 2638threadref_to_int (threadref *ref)
c906108c
SS
2639{
2640 int i, value = 0;
2641 unsigned char *scan;
2642
cfd77fa1 2643 scan = *ref;
c906108c
SS
2644 scan += 4;
2645 i = 4;
2646 while (i-- > 0)
2647 value = (value << 8) | ((*scan++) & 0xff);
2648 return value;
2649}
2650
2651static void
fba45db2 2652copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2653{
2654 int i;
2655 unsigned char *csrc, *cdest;
2656
2657 csrc = (unsigned char *) src;
2658 cdest = (unsigned char *) dest;
2659 i = 8;
2660 while (i--)
2661 *cdest++ = *csrc++;
2662}
2663
2664static int
fba45db2 2665threadmatch (threadref *dest, threadref *src)
c906108c 2666{
23860348 2667 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2668#if 0
2669 unsigned char *srcp, *destp;
2670 int i, result;
2671 srcp = (char *) src;
2672 destp = (char *) dest;
2673
2674 result = 1;
2675 while (i-- > 0)
2676 result &= (*srcp++ == *destp++) ? 1 : 0;
2677 return result;
2678#endif
2679 return 1;
2680}
2681
2682/*
c5aa993b
JM
2683 threadid:1, # always request threadid
2684 context_exists:2,
2685 display:4,
2686 unique_name:8,
2687 more_display:16
2688 */
c906108c
SS
2689
2690/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2691
2692static char *
fba45db2 2693pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2694{
23860348
MS
2695 *pkt++ = 'q'; /* Info Query */
2696 *pkt++ = 'P'; /* process or thread info */
2697 pkt = pack_int (pkt, mode); /* mode */
c906108c 2698 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2699 *pkt = '\0'; /* terminate */
c906108c
SS
2700 return pkt;
2701}
2702
23860348 2703/* These values tag the fields in a thread info response packet. */
c906108c 2704/* Tagging the fields allows us to request specific fields and to
23860348 2705 add more fields as time goes by. */
c906108c 2706
23860348 2707#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2708#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2709 fetch registers and its stack? */
c5aa993b 2710#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2711#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2712#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2713 the process. */
c906108c
SS
2714
2715static int
fba45db2
KB
2716remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2717 struct gdb_ext_thread_info *info)
c906108c 2718{
d01949b6 2719 struct remote_state *rs = get_remote_state ();
c906108c 2720 int mask, length;
cfd77fa1 2721 int tag;
c906108c 2722 threadref ref;
6d820c5c 2723 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2724 int retval = 1;
2725
23860348 2726 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2727 info->active = 0;
2728 info->display[0] = '\0';
2729 info->shortname[0] = '\0';
2730 info->more_display[0] = '\0';
2731
23860348
MS
2732 /* Assume the characters indicating the packet type have been
2733 stripped. */
c906108c
SS
2734 pkt = unpack_int (pkt, &mask); /* arg mask */
2735 pkt = unpack_threadid (pkt, &ref);
2736
2737 if (mask == 0)
8a3fe4f8 2738 warning (_("Incomplete response to threadinfo request."));
c906108c 2739 if (!threadmatch (&ref, expectedref))
23860348 2740 { /* This is an answer to a different request. */
8a3fe4f8 2741 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2742 return 0;
2743 }
2744 copy_threadref (&info->threadid, &ref);
2745
23860348 2746 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2747
23860348
MS
2748 /* Packets are terminated with nulls. */
2749 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2750 {
2751 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2752 pkt = unpack_byte (pkt, &length); /* length */
2753 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2754 {
8a3fe4f8 2755 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2756 retval = 0;
2757 break;
2758 }
2759 if (tag == TAG_THREADID)
2760 {
2761 if (length != 16)
2762 {
8a3fe4f8 2763 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2764 retval = 0;
2765 break;
2766 }
2767 pkt = unpack_threadid (pkt, &ref);
2768 mask = mask & ~TAG_THREADID;
2769 continue;
2770 }
2771 if (tag == TAG_EXISTS)
2772 {
2773 info->active = stub_unpack_int (pkt, length);
2774 pkt += length;
2775 mask = mask & ~(TAG_EXISTS);
2776 if (length > 8)
2777 {
8a3fe4f8 2778 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2779 retval = 0;
2780 break;
2781 }
2782 continue;
2783 }
2784 if (tag == TAG_THREADNAME)
2785 {
2786 pkt = unpack_string (pkt, &info->shortname[0], length);
2787 mask = mask & ~TAG_THREADNAME;
2788 continue;
2789 }
2790 if (tag == TAG_DISPLAY)
2791 {
2792 pkt = unpack_string (pkt, &info->display[0], length);
2793 mask = mask & ~TAG_DISPLAY;
2794 continue;
2795 }
2796 if (tag == TAG_MOREDISPLAY)
2797 {
2798 pkt = unpack_string (pkt, &info->more_display[0], length);
2799 mask = mask & ~TAG_MOREDISPLAY;
2800 continue;
2801 }
8a3fe4f8 2802 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2803 break; /* Not a tag we know about. */
c906108c
SS
2804 }
2805 return retval;
2806}
2807
2808static int
fba45db2
KB
2809remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2810 struct gdb_ext_thread_info *info)
c906108c 2811{
d01949b6 2812 struct remote_state *rs = get_remote_state ();
c906108c 2813 int result;
c906108c 2814
2e9f7625
DJ
2815 pack_threadinfo_request (rs->buf, fieldset, threadid);
2816 putpkt (rs->buf);
6d820c5c 2817 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2818
2819 if (rs->buf[0] == '\0')
2820 return 0;
2821
2e9f7625 2822 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2823 threadid, info);
c906108c
SS
2824 return result;
2825}
2826
c906108c
SS
2827/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2828
2829static char *
fba45db2
KB
2830pack_threadlist_request (char *pkt, int startflag, int threadcount,
2831 threadref *nextthread)
c906108c
SS
2832{
2833 *pkt++ = 'q'; /* info query packet */
2834 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2835 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2836 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2837 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2838 *pkt = '\0';
2839 return pkt;
2840}
2841
2842/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2843
2844static int
fba45db2
KB
2845parse_threadlist_response (char *pkt, int result_limit,
2846 threadref *original_echo, threadref *resultlist,
2847 int *doneflag)
c906108c 2848{
d01949b6 2849 struct remote_state *rs = get_remote_state ();
c906108c
SS
2850 char *limit;
2851 int count, resultcount, done;
2852
2853 resultcount = 0;
2854 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2855 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2856 /* done parse past here */
c906108c
SS
2857 pkt = unpack_byte (pkt, &count); /* count field */
2858 pkt = unpack_nibble (pkt, &done);
2859 /* The first threadid is the argument threadid. */
2860 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2861 while ((count-- > 0) && (pkt < limit))
2862 {
2863 pkt = unpack_threadid (pkt, resultlist++);
2864 if (resultcount++ >= result_limit)
2865 break;
2866 }
2867 if (doneflag)
2868 *doneflag = done;
2869 return resultcount;
2870}
2871
6dc54d91
PA
2872/* Fetch the next batch of threads from the remote. Returns -1 if the
2873 qL packet is not supported, 0 on error and 1 on success. */
2874
c906108c 2875static int
fba45db2
KB
2876remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2877 int *done, int *result_count, threadref *threadlist)
c906108c 2878{
d01949b6 2879 struct remote_state *rs = get_remote_state ();
c906108c
SS
2880 int result = 1;
2881
23860348 2882 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2883 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2884 >= get_remote_packet_size ())
ea9c271d 2885 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2886
6d820c5c
DJ
2887 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2888 putpkt (rs->buf);
2889 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2890 if (*rs->buf == '\0')
6dc54d91
PA
2891 {
2892 /* Packet not supported. */
2893 return -1;
2894 }
2895
2896 *result_count =
2897 parse_threadlist_response (rs->buf + 2, result_limit,
2898 &rs->echo_nextthread, threadlist, done);
c906108c 2899
0d031856 2900 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2901 {
23860348
MS
2902 /* FIXME: This is a good reason to drop the packet. */
2903 /* Possably, there is a duplicate response. */
c906108c
SS
2904 /* Possabilities :
2905 retransmit immediatly - race conditions
2906 retransmit after timeout - yes
2907 exit
2908 wait for packet, then exit
2909 */
8a3fe4f8 2910 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2911 return 0; /* I choose simply exiting. */
c906108c
SS
2912 }
2913 if (*result_count <= 0)
2914 {
2915 if (*done != 1)
2916 {
8a3fe4f8 2917 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2918 result = 0;
2919 }
2920 return result; /* break; */
2921 }
2922 if (*result_count > result_limit)
2923 {
2924 *result_count = 0;
8a3fe4f8 2925 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2926 return 0;
2927 }
2928 return result;
2929}
2930
6dc54d91
PA
2931/* Fetch the list of remote threads, with the qL packet, and call
2932 STEPFUNCTION for each thread found. Stops iterating and returns 1
2933 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2934 STEPFUNCTION returns false. If the packet is not supported,
2935 returns -1. */
c906108c 2936
c906108c 2937static int
fba45db2
KB
2938remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2939 int looplimit)
c906108c 2940{
0d031856 2941 struct remote_state *rs = get_remote_state ();
c906108c
SS
2942 int done, i, result_count;
2943 int startflag = 1;
2944 int result = 1;
2945 int loopcount = 0;
c906108c
SS
2946
2947 done = 0;
2948 while (!done)
2949 {
2950 if (loopcount++ > looplimit)
2951 {
2952 result = 0;
8a3fe4f8 2953 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2954 break;
2955 }
6dc54d91
PA
2956 result = remote_get_threadlist (startflag, &rs->nextthread,
2957 MAXTHREADLISTRESULTS,
2958 &done, &result_count,
2959 rs->resultthreadlist);
2960 if (result <= 0)
2961 break;
23860348 2962 /* Clear for later iterations. */
c906108c
SS
2963 startflag = 0;
2964 /* Setup to resume next batch of thread references, set nextthread. */
2965 if (result_count >= 1)
0d031856
TT
2966 copy_threadref (&rs->nextthread,
2967 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2968 i = 0;
2969 while (result_count--)
6dc54d91
PA
2970 {
2971 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2972 {
2973 result = 0;
2974 break;
2975 }
2976 }
c906108c
SS
2977 }
2978 return result;
2979}
2980
6dc54d91
PA
2981/* A thread found on the remote target. */
2982
2983typedef struct thread_item
2984{
2985 /* The thread's PTID. */
2986 ptid_t ptid;
2987
2988 /* The thread's extra info. May be NULL. */
2989 char *extra;
2990
79efa585
SM
2991 /* The thread's name. May be NULL. */
2992 char *name;
2993
6dc54d91
PA
2994 /* The core the thread was running on. -1 if not known. */
2995 int core;
f6327dcb
KB
2996
2997 /* The thread handle associated with the thread. */
2998 gdb::byte_vector *thread_handle;
2999
6dc54d91
PA
3000} thread_item_t;
3001DEF_VEC_O(thread_item_t);
3002
3003/* Context passed around to the various methods listing remote
3004 threads. As new threads are found, they're added to the ITEMS
3005 vector. */
3006
3007struct threads_listing_context
3008{
3009 /* The threads found on the remote target. */
3010 VEC (thread_item_t) *items;
3011};
3012
80134cf5
PA
3013/* Discard the contents of the constructed thread listing context. */
3014
3015static void
3016clear_threads_listing_context (void *p)
3017{
19ba03f4
SM
3018 struct threads_listing_context *context
3019 = (struct threads_listing_context *) p;
80134cf5
PA
3020 int i;
3021 struct thread_item *item;
3022
3023 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
3024 {
3025 xfree (item->extra);
3026 xfree (item->name);
f6327dcb 3027 delete item->thread_handle;
79efa585 3028 }
80134cf5
PA
3029
3030 VEC_free (thread_item_t, context->items);
3031}
3032
cbb8991c
DB
3033/* Remove the thread specified as the related_pid field of WS
3034 from the CONTEXT list. */
3035
3036static void
3037threads_listing_context_remove (struct target_waitstatus *ws,
3038 struct threads_listing_context *context)
3039{
3040 struct thread_item *item;
3041 int i;
3042 ptid_t child_ptid = ws->value.related_pid;
3043
3044 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3045 {
3046 if (ptid_equal (item->ptid, child_ptid))
3047 {
3048 VEC_ordered_remove (thread_item_t, context->items, i);
3049 break;
3050 }
3051 }
3052}
3053
c906108c 3054static int
6dc54d91 3055remote_newthread_step (threadref *ref, void *data)
c906108c 3056{
19ba03f4
SM
3057 struct threads_listing_context *context
3058 = (struct threads_listing_context *) data;
6dc54d91 3059 struct thread_item item;
79d7f229 3060 int pid = ptid_get_pid (inferior_ptid);
39f77062 3061
6dc54d91
PA
3062 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3063 item.core = -1;
2e3b657e 3064 item.name = NULL;
6dc54d91 3065 item.extra = NULL;
f6327dcb 3066 item.thread_handle = nullptr;
6dc54d91
PA
3067
3068 VEC_safe_push (thread_item_t, context->items, &item);
3069
c906108c
SS
3070 return 1; /* continue iterator */
3071}
3072
3073#define CRAZY_MAX_THREADS 1000
3074
39f77062
KB
3075static ptid_t
3076remote_current_thread (ptid_t oldpid)
c906108c 3077{
d01949b6 3078 struct remote_state *rs = get_remote_state ();
c906108c
SS
3079
3080 putpkt ("qC");
6d820c5c 3081 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3082 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3083 {
256642e8 3084 const char *obuf;
c9f35b34
KB
3085 ptid_t result;
3086
3087 result = read_ptid (&rs->buf[2], &obuf);
3088 if (*obuf != '\0' && remote_debug)
3089 fprintf_unfiltered (gdb_stdlog,
3090 "warning: garbage in qC reply\n");
3091
3092 return result;
3093 }
c906108c
SS
3094 else
3095 return oldpid;
3096}
3097
6dc54d91 3098/* List remote threads using the deprecated qL packet. */
cce74817 3099
6dc54d91
PA
3100static int
3101remote_get_threads_with_ql (struct target_ops *ops,
3102 struct threads_listing_context *context)
c906108c 3103{
6dc54d91
PA
3104 if (remote_threadlist_iterator (remote_newthread_step, context,
3105 CRAZY_MAX_THREADS) >= 0)
3106 return 1;
3107
3108 return 0;
c906108c
SS
3109}
3110
dc146f7c
VP
3111#if defined(HAVE_LIBEXPAT)
3112
dc146f7c
VP
3113static void
3114start_thread (struct gdb_xml_parser *parser,
3115 const struct gdb_xml_element *element,
3116 void *user_data, VEC(gdb_xml_value_s) *attributes)
3117{
19ba03f4
SM
3118 struct threads_listing_context *data
3119 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3120
3121 struct thread_item item;
3122 char *id;
3d2c1d41 3123 struct gdb_xml_value *attr;
dc146f7c 3124
19ba03f4 3125 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
3126 item.ptid = read_ptid (id, NULL);
3127
3d2c1d41
PA
3128 attr = xml_find_attribute (attributes, "core");
3129 if (attr != NULL)
3130 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
3131 else
3132 item.core = -1;
3133
79efa585 3134 attr = xml_find_attribute (attributes, "name");
e1961661 3135 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 3136
f6327dcb
KB
3137 attr = xml_find_attribute (attributes, "handle");
3138 if (attr != NULL)
3139 {
3140 item.thread_handle = new gdb::byte_vector
3141 (strlen ((const char *) attr->value) / 2);
3142 hex2bin ((const char *) attr->value, item.thread_handle->data (),
3143 item.thread_handle->size ());
3144 }
3145 else
3146 item.thread_handle = nullptr;
3147
dc146f7c
VP
3148 item.extra = 0;
3149
3150 VEC_safe_push (thread_item_t, data->items, &item);
3151}
3152
3153static void
3154end_thread (struct gdb_xml_parser *parser,
3155 const struct gdb_xml_element *element,
3156 void *user_data, const char *body_text)
3157{
19ba03f4
SM
3158 struct threads_listing_context *data
3159 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3160
3161 if (body_text && *body_text)
2ae2a0b7 3162 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3163}
3164
3165const struct gdb_xml_attribute thread_attributes[] = {
3166 { "id", GDB_XML_AF_NONE, NULL, NULL },
3167 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3168 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3169 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3170 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3171};
3172
3173const struct gdb_xml_element thread_children[] = {
3174 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3175};
3176
3177const struct gdb_xml_element threads_children[] = {
3178 { "thread", thread_attributes, thread_children,
3179 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3180 start_thread, end_thread },
3181 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3182};
3183
3184const struct gdb_xml_element threads_elements[] = {
3185 { "threads", NULL, threads_children,
3186 GDB_XML_EF_NONE, NULL, NULL },
3187 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3188};
3189
3190#endif
3191
6dc54d91 3192/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3193
6dc54d91
PA
3194static int
3195remote_get_threads_with_qxfer (struct target_ops *ops,
3196 struct threads_listing_context *context)
0f71a2f6 3197{
dc146f7c 3198#if defined(HAVE_LIBEXPAT)
4082afcc 3199 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3200 {
b7b030ad
TT
3201 gdb::unique_xmalloc_ptr<char> xml
3202 = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
efc0eabd 3203
6dc54d91 3204 if (xml != NULL && *xml != '\0')
dc146f7c 3205 {
6dc54d91 3206 gdb_xml_parse_quick (_("threads"), "threads.dtd",
b7b030ad 3207 threads_elements, xml.get (), context);
dc146f7c
VP
3208 }
3209
6dc54d91 3210 return 1;
dc146f7c
VP
3211 }
3212#endif
3213
6dc54d91
PA
3214 return 0;
3215}
3216
3217/* List remote threads using qfThreadInfo/qsThreadInfo. */
3218
3219static int
3220remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3221 struct threads_listing_context *context)
3222{
3223 struct remote_state *rs = get_remote_state ();
3224
b80fafe3 3225 if (rs->use_threadinfo_query)
9d1f7ab2 3226 {
256642e8 3227 const char *bufp;
6dc54d91 3228
9d1f7ab2 3229 putpkt ("qfThreadInfo");
6d820c5c 3230 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3231 bufp = rs->buf;
9d1f7ab2 3232 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3233 {
9d1f7ab2
MS
3234 while (*bufp++ == 'm') /* reply contains one or more TID */
3235 {
3236 do
3237 {
6dc54d91
PA
3238 struct thread_item item;
3239
3240 item.ptid = read_ptid (bufp, &bufp);
3241 item.core = -1;
2e3b657e 3242 item.name = NULL;
6dc54d91 3243 item.extra = NULL;
f6327dcb 3244 item.thread_handle = nullptr;
6dc54d91
PA
3245
3246 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3247 }
3248 while (*bufp++ == ','); /* comma-separated list */
3249 putpkt ("qsThreadInfo");
6d820c5c 3250 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3251 bufp = rs->buf;
9d1f7ab2 3252 }
6dc54d91
PA
3253 return 1;
3254 }
3255 else
3256 {
3257 /* Packet not recognized. */
3258 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3259 }
3260 }
3261
6dc54d91
PA
3262 return 0;
3263}
3264
e8032dde 3265/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3266 targets. */
3267
3268static void
e8032dde 3269remote_update_thread_list (struct target_ops *ops)
6dc54d91 3270{
6dc54d91
PA
3271 struct threads_listing_context context;
3272 struct cleanup *old_chain;
ab970af1 3273 int got_list = 0;
e8032dde 3274
6dc54d91
PA
3275 context.items = NULL;
3276 old_chain = make_cleanup (clear_threads_listing_context, &context);
3277
3278 /* We have a few different mechanisms to fetch the thread list. Try
3279 them all, starting with the most preferred one first, falling
3280 back to older methods. */
3281 if (remote_get_threads_with_qxfer (ops, &context)
3282 || remote_get_threads_with_qthreadinfo (ops, &context)
3283 || remote_get_threads_with_ql (ops, &context))
3284 {
3285 int i;
3286 struct thread_item *item;
ab970af1
PA
3287 struct thread_info *tp, *tmp;
3288
3289 got_list = 1;
3290
7d1a114c
PA
3291 if (VEC_empty (thread_item_t, context.items)
3292 && remote_thread_always_alive (ops, inferior_ptid))
3293 {
3294 /* Some targets don't really support threads, but still
3295 reply an (empty) thread list in response to the thread
3296 listing packets, instead of replying "packet not
3297 supported". Exit early so we don't delete the main
3298 thread. */
3299 do_cleanups (old_chain);
3300 return;
3301 }
3302
ab970af1
PA
3303 /* CONTEXT now holds the current thread list on the remote
3304 target end. Delete GDB-side threads no longer found on the
3305 target. */
8a06aea7 3306 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3307 {
ab970af1
PA
3308 for (i = 0;
3309 VEC_iterate (thread_item_t, context.items, i, item);
3310 ++i)
3311 {
3312 if (ptid_equal (item->ptid, tp->ptid))
3313 break;
3314 }
3315
3316 if (i == VEC_length (thread_item_t, context.items))
3317 {
3318 /* Not found. */
3319 delete_thread (tp->ptid);
3320 }
cbb8991c
DB
3321 }
3322
3323 /* Remove any unreported fork child threads from CONTEXT so
3324 that we don't interfere with follow fork, which is where
3325 creation of such threads is handled. */
3326 remove_new_fork_children (&context);
74531fed 3327
ab970af1 3328 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3329 for (i = 0;
3330 VEC_iterate (thread_item_t, context.items, i, item);
3331 ++i)
3332 {
3333 if (!ptid_equal (item->ptid, null_ptid))
3334 {
3335 struct private_thread_info *info;
3336 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3337 executing until proven otherwise with a stop reply.
3338 In all-stop, we can only get here if all threads are
6dc54d91 3339 stopped. */
0d5b594f 3340 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3341
0d5b594f 3342 remote_notice_new_inferior (item->ptid, executing);
6dc54d91 3343
85ad3aaf 3344 info = get_private_info_ptid (item->ptid);
6dc54d91
PA
3345 info->core = item->core;
3346 info->extra = item->extra;
3347 item->extra = NULL;
79efa585
SM
3348 info->name = item->name;
3349 item->name = NULL;
f6327dcb
KB
3350 info->thread_handle = item->thread_handle;
3351 item->thread_handle = nullptr;
6dc54d91
PA
3352 }
3353 }
3354 }
3355
ab970af1
PA
3356 if (!got_list)
3357 {
3358 /* If no thread listing method is supported, then query whether
3359 each known thread is alive, one by one, with the T packet.
3360 If the target doesn't support threads at all, then this is a
3361 no-op. See remote_thread_alive. */
3362 prune_threads ();
3363 }
3364
6dc54d91 3365 do_cleanups (old_chain);
9d1f7ab2
MS
3366}
3367
802188a7 3368/*
9d1f7ab2
MS
3369 * Collect a descriptive string about the given thread.
3370 * The target may say anything it wants to about the thread
3371 * (typically info about its blocked / runnable state, name, etc.).
3372 * This string will appear in the info threads display.
802188a7 3373 *
9d1f7ab2
MS
3374 * Optional: targets are not required to implement this function.
3375 */
3376
7a114964 3377static const char *
c15906d8 3378remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3379{
d01949b6 3380 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3381 int result;
3382 int set;
3383 threadref id;
3384 struct gdb_ext_thread_info threadinfo;
23860348 3385 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3386 int n = 0; /* position in display_buf */
3387
5d93a237 3388 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3389 internal_error (__FILE__, __LINE__,
e2e0b3e5 3390 _("remote_threads_extra_info"));
9d1f7ab2 3391
60e569b9 3392 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3393 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3394 /* This is the main thread which was added by GDB. The remote
3395 server doesn't know about it. */
3396 return NULL;
3397
4082afcc 3398 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3399 {
3400 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3401
fe978cb0
PA
3402 if (info && info->priv)
3403 return info->priv->extra;
dc146f7c
VP
3404 else
3405 return NULL;
3406 }
3407
b80fafe3 3408 if (rs->use_threadextra_query)
9d1f7ab2 3409 {
82f73884
PA
3410 char *b = rs->buf;
3411 char *endb = rs->buf + get_remote_packet_size ();
3412
3413 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3414 b += strlen (b);
3415 write_ptid (b, endb, tp->ptid);
3416
2e9f7625 3417 putpkt (rs->buf);
6d820c5c 3418 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3419 if (rs->buf[0] != 0)
9d1f7ab2 3420 {
325fac50 3421 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
2e9f7625 3422 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3423 display_buf [result] = '\0';
9d1f7ab2
MS
3424 return display_buf;
3425 }
0f71a2f6 3426 }
9d1f7ab2
MS
3427
3428 /* If the above query fails, fall back to the old method. */
b80fafe3 3429 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3430 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3431 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3432 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3433 if (remote_get_threadinfo (&id, set, &threadinfo))
3434 if (threadinfo.active)
0f71a2f6 3435 {
9d1f7ab2 3436 if (*threadinfo.shortname)
2bc416ba 3437 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3438 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3439 if (*threadinfo.display)
2bc416ba 3440 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3441 " State: %s,", threadinfo.display);
9d1f7ab2 3442 if (*threadinfo.more_display)
2bc416ba 3443 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3444 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3445
3446 if (n > 0)
c5aa993b 3447 {
23860348 3448 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3449 if (',' == display_buf[n-1])
3450 display_buf[n-1] = ' ';
3451 return display_buf;
c5aa993b 3452 }
0f71a2f6 3453 }
9d1f7ab2 3454 return NULL;
0f71a2f6 3455}
c906108c 3456\f
c5aa993b 3457
0fb4aa4b 3458static int
61fc905d 3459remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3460 struct static_tracepoint_marker *marker)
3461{
3462 struct remote_state *rs = get_remote_state ();
3463 char *p = rs->buf;
3464
bba74b36 3465 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3466 p += strlen (p);
3467 p += hexnumstr (p, addr);
3468 putpkt (rs->buf);
3469 getpkt (&rs->buf, &rs->buf_size, 0);
3470 p = rs->buf;
3471
3472 if (*p == 'E')
3473 error (_("Remote failure reply: %s"), p);
3474
3475 if (*p++ == 'm')
3476 {
256642e8 3477 parse_static_tracepoint_marker_definition (p, NULL, marker);
0fb4aa4b
PA
3478 return 1;
3479 }
3480
3481 return 0;
3482}
3483
0fb4aa4b 3484static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3485remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3486 const char *strid)
0fb4aa4b
PA
3487{
3488 struct remote_state *rs = get_remote_state ();
3489 VEC(static_tracepoint_marker_p) *markers = NULL;
3490 struct static_tracepoint_marker *marker = NULL;
3491 struct cleanup *old_chain;
256642e8 3492 const char *p;
0fb4aa4b
PA
3493
3494 /* Ask for a first packet of static tracepoint marker
3495 definition. */
3496 putpkt ("qTfSTM");
3497 getpkt (&rs->buf, &rs->buf_size, 0);
3498 p = rs->buf;
3499 if (*p == 'E')
3500 error (_("Remote failure reply: %s"), p);
3501
3502 old_chain = make_cleanup (free_current_marker, &marker);
3503
3504 while (*p++ == 'm')
3505 {
3506 if (marker == NULL)
3507 marker = XCNEW (struct static_tracepoint_marker);
3508
3509 do
3510 {
3511 parse_static_tracepoint_marker_definition (p, &p, marker);
3512
3513 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3514 {
3515 VEC_safe_push (static_tracepoint_marker_p,
3516 markers, marker);
3517 marker = NULL;
3518 }
3519 else
3520 {
3521 release_static_tracepoint_marker (marker);
3522 memset (marker, 0, sizeof (*marker));
3523 }
3524 }
3525 while (*p++ == ','); /* comma-separated list */
3526 /* Ask for another packet of static tracepoint definition. */
3527 putpkt ("qTsSTM");
3528 getpkt (&rs->buf, &rs->buf_size, 0);
3529 p = rs->buf;
3530 }
3531
3532 do_cleanups (old_chain);
3533 return markers;
3534}
3535
3536\f
10760264
JB
3537/* Implement the to_get_ada_task_ptid function for the remote targets. */
3538
3539static ptid_t
1e6b91a4 3540remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3541{
ba348170 3542 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3543}
3544\f
3545
24b06219 3546/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3547
3548static void
fba45db2 3549extended_remote_restart (void)
c906108c 3550{
d01949b6 3551 struct remote_state *rs = get_remote_state ();
c906108c
SS
3552
3553 /* Send the restart command; for reasons I don't understand the
3554 remote side really expects a number after the "R". */
ea9c271d 3555 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3556 putpkt (rs->buf);
c906108c 3557
ad9a8f3f 3558 remote_fileio_reset ();
c906108c
SS
3559}
3560\f
3561/* Clean up connection to a remote debugger. */
3562
c906108c 3563static void
de90e03d 3564remote_close (struct target_ops *self)
c906108c 3565{
5d93a237
TT
3566 struct remote_state *rs = get_remote_state ();
3567
3568 if (rs->remote_desc == NULL)
d3fd5342
PA
3569 return; /* already closed */
3570
048094ac 3571 /* Make sure we leave stdin registered in the event loop. */
e3594fd1 3572 remote_terminal_ours (self);
ce5ce7ed 3573
5d93a237
TT
3574 serial_close (rs->remote_desc);
3575 rs->remote_desc = NULL;
ce5ce7ed
PA
3576
3577 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3578 of all the inferiors and their threads we were controlling.
3579 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3580 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3581 inferior_ptid = null_ptid;
f67fd822 3582 discard_all_inferiors ();
ce5ce7ed 3583
f48ff2a7
YQ
3584 /* We are closing the remote target, so we should discard
3585 everything of this target. */
bcc75809 3586 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3587
3588 if (remote_async_inferior_event_token)
3589 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3590
5965e028 3591 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3592
3593 trace_reset_local_state ();
c906108c
SS
3594}
3595
23860348 3596/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3597
3598static void
fba45db2 3599get_offsets (void)
c906108c 3600{
d01949b6 3601 struct remote_state *rs = get_remote_state ();
2e9f7625 3602 char *buf;
085dd6e6 3603 char *ptr;
31d99776
DJ
3604 int lose, num_segments = 0, do_sections, do_segments;
3605 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3606 struct section_offsets *offs;
31d99776
DJ
3607 struct symfile_segment_data *data;
3608
3609 if (symfile_objfile == NULL)
3610 return;
c906108c
SS
3611
3612 putpkt ("qOffsets");
6d820c5c 3613 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3614 buf = rs->buf;
c906108c
SS
3615
3616 if (buf[0] == '\000')
3617 return; /* Return silently. Stub doesn't support
23860348 3618 this command. */
c906108c
SS
3619 if (buf[0] == 'E')
3620 {
8a3fe4f8 3621 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3622 return;
3623 }
3624
3625 /* Pick up each field in turn. This used to be done with scanf, but
3626 scanf will make trouble if CORE_ADDR size doesn't match
3627 conversion directives correctly. The following code will work
3628 with any size of CORE_ADDR. */
3629 text_addr = data_addr = bss_addr = 0;
3630 ptr = buf;
3631 lose = 0;
3632
61012eef 3633 if (startswith (ptr, "Text="))
c906108c
SS
3634 {
3635 ptr += 5;
3636 /* Don't use strtol, could lose on big values. */
3637 while (*ptr && *ptr != ';')
3638 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3639
61012eef 3640 if (startswith (ptr, ";Data="))
31d99776
DJ
3641 {
3642 ptr += 6;
3643 while (*ptr && *ptr != ';')
3644 data_addr = (data_addr << 4) + fromhex (*ptr++);
3645 }
3646 else
3647 lose = 1;
3648
61012eef 3649 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3650 {
3651 ptr += 5;
3652 while (*ptr && *ptr != ';')
3653 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3654
31d99776
DJ
3655 if (bss_addr != data_addr)
3656 warning (_("Target reported unsupported offsets: %s"), buf);
3657 }
3658 else
3659 lose = 1;
3660 }
61012eef 3661 else if (startswith (ptr, "TextSeg="))
c906108c 3662 {
31d99776
DJ
3663 ptr += 8;
3664 /* Don't use strtol, could lose on big values. */
c906108c 3665 while (*ptr && *ptr != ';')
31d99776
DJ
3666 text_addr = (text_addr << 4) + fromhex (*ptr++);
3667 num_segments = 1;
3668
61012eef 3669 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3670 {
3671 ptr += 9;
3672 while (*ptr && *ptr != ';')
3673 data_addr = (data_addr << 4) + fromhex (*ptr++);
3674 num_segments++;
3675 }
c906108c
SS
3676 }
3677 else
3678 lose = 1;
3679
3680 if (lose)
8a3fe4f8 3681 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3682 else if (*ptr != '\0')
3683 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3684
802188a7 3685 offs = ((struct section_offsets *)
a39a16c4 3686 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3687 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3688 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3689
31d99776
DJ
3690 data = get_symfile_segment_data (symfile_objfile->obfd);
3691 do_segments = (data != NULL);
3692 do_sections = num_segments == 0;
c906108c 3693
28c32713 3694 if (num_segments > 0)
31d99776 3695 {
31d99776
DJ
3696 segments[0] = text_addr;
3697 segments[1] = data_addr;
3698 }
28c32713
JB
3699 /* If we have two segments, we can still try to relocate everything
3700 by assuming that the .text and .data offsets apply to the whole
3701 text and data segments. Convert the offsets given in the packet
3702 to base addresses for symfile_map_offsets_to_segments. */
3703 else if (data && data->num_segments == 2)
3704 {
3705 segments[0] = data->segment_bases[0] + text_addr;
3706 segments[1] = data->segment_bases[1] + data_addr;
3707 num_segments = 2;
3708 }
8d385431
DJ
3709 /* If the object file has only one segment, assume that it is text
3710 rather than data; main programs with no writable data are rare,
3711 but programs with no code are useless. Of course the code might
3712 have ended up in the data segment... to detect that we would need
3713 the permissions here. */
3714 else if (data && data->num_segments == 1)
3715 {
3716 segments[0] = data->segment_bases[0] + text_addr;
3717 num_segments = 1;
3718 }
28c32713
JB
3719 /* There's no way to relocate by segment. */
3720 else
3721 do_segments = 0;
31d99776
DJ
3722
3723 if (do_segments)
3724 {
3725 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3726 offs, num_segments, segments);
3727
3728 if (ret == 0 && !do_sections)
3e43a32a
MS
3729 error (_("Can not handle qOffsets TextSeg "
3730 "response with this symbol file"));
31d99776
DJ
3731
3732 if (ret > 0)
3733 do_sections = 0;
3734 }
c906108c 3735
9ef895d6
DJ
3736 if (data)
3737 free_symfile_segment_data (data);
31d99776
DJ
3738
3739 if (do_sections)
3740 {
3741 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3742
3e43a32a
MS
3743 /* This is a temporary kludge to force data and bss to use the
3744 same offsets because that's what nlmconv does now. The real
3745 solution requires changes to the stub and remote.c that I
3746 don't have time to do right now. */
31d99776
DJ
3747
3748 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3749 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3750 }
c906108c
SS
3751
3752 objfile_relocate (symfile_objfile, offs);
3753}
3754
9a7071a8
JB
3755/* Send interrupt_sequence to remote target. */
3756static void
eeae04df 3757send_interrupt_sequence (void)
9a7071a8 3758{
5d93a237
TT
3759 struct remote_state *rs = get_remote_state ();
3760
9a7071a8 3761 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3762 remote_serial_write ("\x03", 1);
9a7071a8 3763 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3764 serial_send_break (rs->remote_desc);
9a7071a8
JB
3765 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3766 {
5d93a237 3767 serial_send_break (rs->remote_desc);
c33e31fd 3768 remote_serial_write ("g", 1);
9a7071a8
JB
3769 }
3770 else
3771 internal_error (__FILE__, __LINE__,
3772 _("Invalid value for interrupt_sequence_mode: %s."),
3773 interrupt_sequence_mode);
3774}
3775
3405876a
PA
3776
3777/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3778 and extract the PTID. Returns NULL_PTID if not found. */
3779
3780static ptid_t
3781stop_reply_extract_thread (char *stop_reply)
3782{
3783 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3784 {
256642e8 3785 const char *p;
3405876a
PA
3786
3787 /* Txx r:val ; r:val (...) */
3788 p = &stop_reply[3];
3789
3790 /* Look for "register" named "thread". */
3791 while (*p != '\0')
3792 {
256642e8 3793 const char *p1;
3405876a
PA
3794
3795 p1 = strchr (p, ':');
3796 if (p1 == NULL)
3797 return null_ptid;
3798
3799 if (strncmp (p, "thread", p1 - p) == 0)
3800 return read_ptid (++p1, &p);
3801
3802 p1 = strchr (p, ';');
3803 if (p1 == NULL)
3804 return null_ptid;
3805 p1++;
3806
3807 p = p1;
3808 }
3809 }
3810
3811 return null_ptid;
3812}
3813
b7ea362b
PA
3814/* Determine the remote side's current thread. If we have a stop
3815 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3816 "thread" register we can extract the current thread from. If not,
3817 ask the remote which is the current thread with qC. The former
3818 method avoids a roundtrip. */
3819
3820static ptid_t
3821get_current_thread (char *wait_status)
3822{
6a49a997 3823 ptid_t ptid = null_ptid;
b7ea362b
PA
3824
3825 /* Note we don't use remote_parse_stop_reply as that makes use of
3826 the target architecture, which we haven't yet fully determined at
3827 this point. */
3828 if (wait_status != NULL)
3829 ptid = stop_reply_extract_thread (wait_status);
3830 if (ptid_equal (ptid, null_ptid))
3831 ptid = remote_current_thread (inferior_ptid);
3832
3833 return ptid;
3834}
3835
49c62f2e
PA
3836/* Query the remote target for which is the current thread/process,
3837 add it to our tables, and update INFERIOR_PTID. The caller is
3838 responsible for setting the state such that the remote end is ready
3405876a
PA
3839 to return the current thread.
3840
3841 This function is called after handling the '?' or 'vRun' packets,
3842 whose response is a stop reply from which we can also try
3843 extracting the thread. If the target doesn't support the explicit
3844 qC query, we infer the current thread from that stop reply, passed
3845 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3846
3847static void
3405876a 3848add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3849{
3850 struct remote_state *rs = get_remote_state ();
3851 int fake_pid_p = 0;
49c62f2e
PA
3852
3853 inferior_ptid = null_ptid;
3854
b7ea362b 3855 /* Now, if we have thread information, update inferior_ptid. */
87215ad1 3856 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 3857
87215ad1 3858 if (curr_ptid != null_ptid)
49c62f2e
PA
3859 {
3860 if (!remote_multi_process_p (rs))
3861 fake_pid_p = 1;
49c62f2e
PA
3862 }
3863 else
3864 {
3865 /* Without this, some commands which require an active target
3866 (such as kill) won't work. This variable serves (at least)
3867 double duty as both the pid of the target process (if it has
3868 such), and as a flag indicating that a target is active. */
87215ad1 3869 curr_ptid = magic_null_ptid;
49c62f2e
PA
3870 fake_pid_p = 1;
3871 }
3872
87215ad1 3873 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
49c62f2e 3874
87215ad1
SDJ
3875 /* Add the main thread and switch to it. Don't try reading
3876 registers yet, since we haven't fetched the target description
3877 yet. */
3878 thread_info *tp = add_thread_silent (curr_ptid);
3879 switch_to_thread_no_regs (tp);
49c62f2e
PA
3880}
3881
6efcd9a8
PA
3882/* Print info about a thread that was found already stopped on
3883 connection. */
3884
3885static void
3886print_one_stopped_thread (struct thread_info *thread)
3887{
3888 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3889
3890 switch_to_thread (thread->ptid);
3891 stop_pc = get_frame_pc (get_current_frame ());
3892 set_current_sal_from_frame (get_current_frame ());
3893
3894 thread->suspend.waitstatus_pending_p = 0;
3895
3896 if (ws->kind == TARGET_WAITKIND_STOPPED)
3897 {
3898 enum gdb_signal sig = ws->value.sig;
3899
3900 if (signal_print_state (sig))
3901 observer_notify_signal_received (sig);
3902 }
3903 observer_notify_normal_stop (NULL, 1);
3904}
3905
221e1a37
PA
3906/* Process all initial stop replies the remote side sent in response
3907 to the ? packet. These indicate threads that were already stopped
3908 on initial connection. We mark these threads as stopped and print
3909 their current frame before giving the user the prompt. */
3910
3911static void
6efcd9a8 3912process_initial_stop_replies (int from_tty)
221e1a37
PA
3913{
3914 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3915 struct inferior *inf;
3916 struct thread_info *thread;
3917 struct thread_info *selected = NULL;
3918 struct thread_info *lowest_stopped = NULL;
3919 struct thread_info *first = NULL;
221e1a37
PA
3920
3921 /* Consume the initial pending events. */
3922 while (pending_stop_replies-- > 0)
3923 {
3924 ptid_t waiton_ptid = minus_one_ptid;
3925 ptid_t event_ptid;
3926 struct target_waitstatus ws;
3927 int ignore_event = 0;
6efcd9a8 3928 struct thread_info *thread;
221e1a37
PA
3929
3930 memset (&ws, 0, sizeof (ws));
3931 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3932 if (remote_debug)
3933 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3934
3935 switch (ws.kind)
3936 {
3937 case TARGET_WAITKIND_IGNORE:
3938 case TARGET_WAITKIND_NO_RESUMED:
3939 case TARGET_WAITKIND_SIGNALLED:
3940 case TARGET_WAITKIND_EXITED:
3941 /* We shouldn't see these, but if we do, just ignore. */
3942 if (remote_debug)
3943 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3944 ignore_event = 1;
3945 break;
3946
3947 case TARGET_WAITKIND_EXECD:
3948 xfree (ws.value.execd_pathname);
3949 break;
3950 default:
3951 break;
3952 }
3953
3954 if (ignore_event)
3955 continue;
3956
6efcd9a8 3957 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3958
3959 if (ws.kind == TARGET_WAITKIND_STOPPED)
3960 {
3961 enum gdb_signal sig = ws.value.sig;
3962
3963 /* Stubs traditionally report SIGTRAP as initial signal,
3964 instead of signal 0. Suppress it. */
3965 if (sig == GDB_SIGNAL_TRAP)
3966 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3967 thread->suspend.stop_signal = sig;
3968 ws.value.sig = sig;
3969 }
221e1a37 3970
6efcd9a8
PA
3971 thread->suspend.waitstatus = ws;
3972
3973 if (ws.kind != TARGET_WAITKIND_STOPPED
3974 || ws.value.sig != GDB_SIGNAL_0)
3975 thread->suspend.waitstatus_pending_p = 1;
3976
3977 set_executing (event_ptid, 0);
3978 set_running (event_ptid, 0);
85ad3aaf 3979 thread->priv->vcont_resumed = 0;
6efcd9a8
PA
3980 }
3981
3982 /* "Notice" the new inferiors before anything related to
3983 registers/memory. */
3984 ALL_INFERIORS (inf)
3985 {
3986 if (inf->pid == 0)
3987 continue;
3988
3989 inf->needs_setup = 1;
3990
3991 if (non_stop)
3992 {
3993 thread = any_live_thread_of_process (inf->pid);
3994 notice_new_inferior (thread->ptid,
3995 thread->state == THREAD_RUNNING,
3996 from_tty);
3997 }
3998 }
3999
4000 /* If all-stop on top of non-stop, pause all threads. Note this
4001 records the threads' stop pc, so must be done after "noticing"
4002 the inferiors. */
4003 if (!non_stop)
4004 {
4005 stop_all_threads ();
4006
4007 /* If all threads of an inferior were already stopped, we
4008 haven't setup the inferior yet. */
4009 ALL_INFERIORS (inf)
4010 {
4011 if (inf->pid == 0)
4012 continue;
221e1a37 4013
6efcd9a8
PA
4014 if (inf->needs_setup)
4015 {
4016 thread = any_live_thread_of_process (inf->pid);
4017 switch_to_thread_no_regs (thread);
4018 setup_inferior (0);
4019 }
4020 }
221e1a37 4021 }
6efcd9a8
PA
4022
4023 /* Now go over all threads that are stopped, and print their current
4024 frame. If all-stop, then if there's a signalled thread, pick
4025 that as current. */
4026 ALL_NON_EXITED_THREADS (thread)
4027 {
6efcd9a8
PA
4028 if (first == NULL)
4029 first = thread;
4030
4031 if (!non_stop)
4032 set_running (thread->ptid, 0);
4033 else if (thread->state != THREAD_STOPPED)
4034 continue;
4035
6efcd9a8
PA
4036 if (selected == NULL
4037 && thread->suspend.waitstatus_pending_p)
4038 selected = thread;
4039
5d5658a1
PA
4040 if (lowest_stopped == NULL
4041 || thread->inf->num < lowest_stopped->inf->num
4042 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4043 lowest_stopped = thread;
4044
4045 if (non_stop)
4046 print_one_stopped_thread (thread);
4047 }
4048
4049 /* In all-stop, we only print the status of one thread, and leave
4050 others with their status pending. */
4051 if (!non_stop)
4052 {
4053 thread = selected;
4054 if (thread == NULL)
4055 thread = lowest_stopped;
4056 if (thread == NULL)
4057 thread = first;
4058
4059 print_one_stopped_thread (thread);
4060 }
4061
4062 /* For "info program". */
4063 thread = inferior_thread ();
4064 if (thread->state == THREAD_STOPPED)
4065 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4066}
4067
048094ac
PA
4068/* Start the remote connection and sync state. */
4069
9cbc821d 4070static void
04bd08de 4071remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 4072{
c8d104ad
PA
4073 struct remote_state *rs = get_remote_state ();
4074 struct packet_config *noack_config;
2d717e4f 4075 char *wait_status = NULL;
8621d6a9 4076
048094ac
PA
4077 /* Signal other parts that we're going through the initial setup,
4078 and so things may not be stable yet. E.g., we don't try to
4079 install tracepoints until we've relocated symbols. Also, a
4080 Ctrl-C before we're connected and synced up can't interrupt the
4081 target. Instead, it offers to drop the (potentially wedged)
4082 connection. */
4083 rs->starting_up = 1;
4084
522002f9 4085 QUIT;
c906108c 4086
9a7071a8
JB
4087 if (interrupt_on_connect)
4088 send_interrupt_sequence ();
4089
57e12211 4090 /* Ack any packet which the remote side has already sent. */
048094ac 4091 remote_serial_write ("+", 1);
1e51243a 4092
c8d104ad
PA
4093 /* The first packet we send to the target is the optional "supported
4094 packets" request. If the target can answer this, it will tell us
4095 which later probes to skip. */
4096 remote_query_supported ();
4097
d914c394 4098 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4099 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 4100 remote_set_permissions (target);
d914c394 4101
57809e5e
JK
4102 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4103 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4104 as a reply to known packet. For packet "vFile:setfs:" it is an
4105 invalid reply and GDB would return error in
4106 remote_hostio_set_filesystem, making remote files access impossible.
4107 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4108 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4109 {
4110 const char v_mustreplyempty[] = "vMustReplyEmpty";
4111
4112 putpkt (v_mustreplyempty);
4113 getpkt (&rs->buf, &rs->buf_size, 0);
4114 if (strcmp (rs->buf, "OK") == 0)
4115 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4116 else if (strcmp (rs->buf, "") != 0)
4117 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4118 rs->buf);
4119 }
4120
c8d104ad
PA
4121 /* Next, we possibly activate noack mode.
4122
4123 If the QStartNoAckMode packet configuration is set to AUTO,
4124 enable noack mode if the stub reported a wish for it with
4125 qSupported.
4126
4127 If set to TRUE, then enable noack mode even if the stub didn't
4128 report it in qSupported. If the stub doesn't reply OK, the
4129 session ends with an error.
4130
4131 If FALSE, then don't activate noack mode, regardless of what the
4132 stub claimed should be the default with qSupported. */
4133
4134 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4135 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4136 {
4137 putpkt ("QStartNoAckMode");
4138 getpkt (&rs->buf, &rs->buf_size, 0);
4139 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4140 rs->noack_mode = 1;
4141 }
4142
04bd08de 4143 if (extended_p)
5fe04517
PA
4144 {
4145 /* Tell the remote that we are using the extended protocol. */
4146 putpkt ("!");
4147 getpkt (&rs->buf, &rs->buf_size, 0);
4148 }
4149
9b224c5e
PA
4150 /* Let the target know which signals it is allowed to pass down to
4151 the program. */
4152 update_signals_program_target ();
4153
d962ef82
DJ
4154 /* Next, if the target can specify a description, read it. We do
4155 this before anything involving memory or registers. */
4156 target_find_description ();
4157
6c95b8df
PA
4158 /* Next, now that we know something about the target, update the
4159 address spaces in the program spaces. */
4160 update_address_spaces ();
4161
50c71eaf
PA
4162 /* On OSs where the list of libraries is global to all
4163 processes, we fetch them early. */
f5656ead 4164 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4165 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4166
6efcd9a8 4167 if (target_is_non_stop_p ())
74531fed 4168 {
4082afcc 4169 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4170 error (_("Non-stop mode requested, but remote "
4171 "does not support non-stop"));
74531fed
PA
4172
4173 putpkt ("QNonStop:1");
4174 getpkt (&rs->buf, &rs->buf_size, 0);
4175
4176 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4177 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4178
4179 /* Find about threads and processes the stub is already
4180 controlling. We default to adding them in the running state.
4181 The '?' query below will then tell us about which threads are
4182 stopped. */
e8032dde 4183 remote_update_thread_list (target);
74531fed 4184 }
4082afcc 4185 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4186 {
4187 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4188 Request it explicitly. */
74531fed
PA
4189 putpkt ("QNonStop:0");
4190 getpkt (&rs->buf, &rs->buf_size, 0);
4191
4192 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4193 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4194 }
4195
a0743c90
YQ
4196 /* Upload TSVs regardless of whether the target is running or not. The
4197 remote stub, such as GDBserver, may have some predefined or builtin
4198 TSVs, even if the target is not running. */
8bd200f1 4199 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4200 {
4201 struct uploaded_tsv *uploaded_tsvs = NULL;
4202
181e3713 4203 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4204 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4205 }
4206
2d717e4f
DJ
4207 /* Check whether the target is running now. */
4208 putpkt ("?");
4209 getpkt (&rs->buf, &rs->buf_size, 0);
4210
6efcd9a8 4211 if (!target_is_non_stop_p ())
2d717e4f 4212 {
74531fed 4213 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4214 {
04bd08de 4215 if (!extended_p)
74531fed 4216 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4217
4218 /* We're connected, but not running. Drop out before we
4219 call start_remote. */
e278ad5b 4220 rs->starting_up = 0;
c35b1492 4221 return;
2d717e4f
DJ
4222 }
4223 else
74531fed 4224 {
74531fed 4225 /* Save the reply for later. */
224c3ddb 4226 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4227 strcpy (wait_status, rs->buf);
4228 }
4229
b7ea362b 4230 /* Fetch thread list. */
e8032dde 4231 target_update_thread_list ();
b7ea362b 4232
74531fed
PA
4233 /* Let the stub know that we want it to return the thread. */
4234 set_continue_thread (minus_one_ptid);
4235
b7ea362b
PA
4236 if (thread_count () == 0)
4237 {
4238 /* Target has no concept of threads at all. GDB treats
4239 non-threaded target as single-threaded; add a main
4240 thread. */
4241 add_current_inferior_and_thread (wait_status);
4242 }
4243 else
4244 {
4245 /* We have thread information; select the thread the target
4246 says should be current. If we're reconnecting to a
4247 multi-threaded program, this will ideally be the thread
4248 that last reported an event before GDB disconnected. */
4249 inferior_ptid = get_current_thread (wait_status);
4250 if (ptid_equal (inferior_ptid, null_ptid))
4251 {
4252 /* Odd... The target was able to list threads, but not
4253 tell us which thread was current (no "thread"
4254 register in T stop reply?). Just pick the first
4255 thread in the thread list then. */
c9f35b34
KB
4256
4257 if (remote_debug)
4258 fprintf_unfiltered (gdb_stdlog,
4259 "warning: couldn't determine remote "
4260 "current thread; picking first in list.\n");
4261
b7ea362b
PA
4262 inferior_ptid = thread_list->ptid;
4263 }
4264 }
74531fed 4265
6e586cc5
YQ
4266 /* init_wait_for_inferior should be called before get_offsets in order
4267 to manage `inserted' flag in bp loc in a correct state.
4268 breakpoint_init_inferior, called from init_wait_for_inferior, set
4269 `inserted' flag to 0, while before breakpoint_re_set, called from
4270 start_remote, set `inserted' flag to 1. In the initialization of
4271 inferior, breakpoint_init_inferior should be called first, and then
4272 breakpoint_re_set can be called. If this order is broken, state of
4273 `inserted' flag is wrong, and cause some problems on breakpoint
4274 manipulation. */
4275 init_wait_for_inferior ();
4276
74531fed
PA
4277 get_offsets (); /* Get text, data & bss offsets. */
4278
d962ef82
DJ
4279 /* If we could not find a description using qXfer, and we know
4280 how to do it some other way, try again. This is not
4281 supported for non-stop; it could be, but it is tricky if
4282 there are no stopped threads when we connect. */
04bd08de 4283 if (remote_read_description_p (target)
f5656ead 4284 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4285 {
4286 target_clear_description ();
4287 target_find_description ();
4288 }
4289
74531fed
PA
4290 /* Use the previously fetched status. */
4291 gdb_assert (wait_status != NULL);
4292 strcpy (rs->buf, wait_status);
4293 rs->cached_wait_status = 1;
4294
04bd08de 4295 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4296 }
4297 else
4298 {
68c97600
PA
4299 /* Clear WFI global state. Do this before finding about new
4300 threads and inferiors, and setting the current inferior.
4301 Otherwise we would clear the proceed status of the current
4302 inferior when we want its stop_soon state to be preserved
4303 (see notice_new_inferior). */
4304 init_wait_for_inferior ();
4305
74531fed
PA
4306 /* In non-stop, we will either get an "OK", meaning that there
4307 are no stopped threads at this time; or, a regular stop
4308 reply. In the latter case, there may be more than one thread
4309 stopped --- we pull them all out using the vStopped
4310 mechanism. */
4311 if (strcmp (rs->buf, "OK") != 0)
4312 {
722247f1 4313 struct notif_client *notif = &notif_client_stop;
2d717e4f 4314
722247f1
YQ
4315 /* remote_notif_get_pending_replies acks this one, and gets
4316 the rest out. */
f48ff2a7 4317 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4318 = remote_notif_parse (notif, rs->buf);
4319 remote_notif_get_pending_events (notif);
74531fed 4320 }
2d717e4f 4321
74531fed
PA
4322 if (thread_count () == 0)
4323 {
04bd08de 4324 if (!extended_p)
74531fed 4325 error (_("The target is not running (try extended-remote?)"));
82f73884 4326
c35b1492
PA
4327 /* We're connected, but not running. Drop out before we
4328 call start_remote. */
e278ad5b 4329 rs->starting_up = 0;
c35b1492
PA
4330 return;
4331 }
74531fed 4332
74531fed
PA
4333 /* In non-stop mode, any cached wait status will be stored in
4334 the stop reply queue. */
4335 gdb_assert (wait_status == NULL);
f0223081 4336
2455069d 4337 /* Report all signals during attach/startup. */
94bedb42 4338 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4339
4340 /* If there are already stopped threads, mark them stopped and
4341 report their stops before giving the prompt to the user. */
6efcd9a8 4342 process_initial_stop_replies (from_tty);
221e1a37
PA
4343
4344 if (target_can_async_p ())
4345 target_async (1);
74531fed 4346 }
c8d104ad 4347
c8d104ad
PA
4348 /* If we connected to a live target, do some additional setup. */
4349 if (target_has_execution)
4350 {
f4ccffad 4351 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4352 remote_check_symbols ();
c8d104ad 4353 }
50c71eaf 4354
d5551862
SS
4355 /* Possibly the target has been engaged in a trace run started
4356 previously; find out where things are at. */
8bd200f1 4357 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4358 {
00bf0b85 4359 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4360
00bf0b85
SS
4361 if (current_trace_status ()->running)
4362 printf_filtered (_("Trace is already running on the target.\n"));
4363
ab6617cc 4364 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4365
4366 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4367 }
4368
c0272db5
TW
4369 /* Possibly the target has been engaged in a btrace record started
4370 previously; find out where things are at. */
4371 remote_btrace_maybe_reopen ();
4372
1e51243a
PA
4373 /* The thread and inferior lists are now synchronized with the
4374 target, our symbols have been relocated, and we're merged the
4375 target's tracepoints with ours. We're done with basic start
4376 up. */
4377 rs->starting_up = 0;
4378
a25a5a45
PA
4379 /* Maybe breakpoints are global and need to be inserted now. */
4380 if (breakpoints_should_be_inserted_now ())
50c71eaf 4381 insert_breakpoints ();
c906108c
SS
4382}
4383
4384/* Open a connection to a remote debugger.
4385 NAME is the filename used for communication. */
4386
4387static void
014f9477 4388remote_open (const char *name, int from_tty)
c906108c 4389{
75c99385 4390 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4391}
4392
c906108c
SS
4393/* Open a connection to a remote debugger using the extended
4394 remote gdb protocol. NAME is the filename used for communication. */
4395
4396static void
014f9477 4397extended_remote_open (const char *name, int from_tty)
c906108c 4398{
75c99385 4399 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4400}
4401
ca4f7f8b
PA
4402/* Reset all packets back to "unknown support". Called when opening a
4403 new connection to a remote target. */
c906108c 4404
d471ea57 4405static void
ca4f7f8b 4406reset_all_packet_configs_support (void)
d471ea57
AC
4407{
4408 int i;
a744cf53 4409
444abaca 4410 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4411 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4412}
4413
ca4f7f8b
PA
4414/* Initialize all packet configs. */
4415
4416static void
4417init_all_packet_configs (void)
4418{
4419 int i;
4420
4421 for (i = 0; i < PACKET_MAX; i++)
4422 {
4423 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4424 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4425 }
4426}
4427
23860348 4428/* Symbol look-up. */
dc8acb97
MS
4429
4430static void
36d25514 4431remote_check_symbols (void)
dc8acb97 4432{
d01949b6 4433 struct remote_state *rs = get_remote_state ();
dc8acb97 4434 char *msg, *reply, *tmp;
dc8acb97 4435 int end;
28170b88 4436 long reply_size;
a5c0808e 4437 struct cleanup *old_chain;
dc8acb97 4438
63154eca
PA
4439 /* The remote side has no concept of inferiors that aren't running
4440 yet, it only knows about running processes. If we're connected
4441 but our current inferior is not running, we should not invite the
4442 remote target to request symbol lookups related to its
4443 (unrelated) current process. */
4444 if (!target_has_execution)
4445 return;
4446
4082afcc 4447 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4448 return;
4449
63154eca
PA
4450 /* Make sure the remote is pointing at the right process. Note
4451 there's no way to select "no process". */
3c9c4b83
PA
4452 set_general_process ();
4453
6d820c5c
DJ
4454 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4455 because we need both at the same time. */
224c3ddb 4456 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4457 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4458 reply = (char *) xmalloc (get_remote_packet_size ());
4459 make_cleanup (free_current_contents, &reply);
4460 reply_size = get_remote_packet_size ();
6d820c5c 4461
23860348 4462 /* Invite target to request symbol lookups. */
dc8acb97
MS
4463
4464 putpkt ("qSymbol::");
28170b88
MK
4465 getpkt (&reply, &reply_size, 0);
4466 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4467
61012eef 4468 while (startswith (reply, "qSymbol:"))
dc8acb97 4469 {
77e371c0
TT
4470 struct bound_minimal_symbol sym;
4471
dc8acb97 4472 tmp = &reply[8];
cfd77fa1 4473 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4474 msg[end] = '\0';
4475 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4476 if (sym.minsym == NULL)
ea9c271d 4477 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4478 else
2bbe3cc1 4479 {
f5656ead 4480 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4481 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4482
4483 /* If this is a function address, return the start of code
4484 instead of any data function descriptor. */
f5656ead 4485 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4486 sym_addr,
4487 &current_target);
4488
4489 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4490 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4491 }
4492
dc8acb97 4493 putpkt (msg);
28170b88 4494 getpkt (&reply, &reply_size, 0);
dc8acb97 4495 }
a5c0808e
PA
4496
4497 do_cleanups (old_chain);
dc8acb97
MS
4498}
4499
9db8d71f 4500static struct serial *
baa336ce 4501remote_serial_open (const char *name)
9db8d71f
DJ
4502{
4503 static int udp_warning = 0;
4504
4505 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4506 of in ser-tcp.c, because it is the remote protocol assuming that the
4507 serial connection is reliable and not the serial connection promising
4508 to be. */
61012eef 4509 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4510 {
3e43a32a
MS
4511 warning (_("The remote protocol may be unreliable over UDP.\n"
4512 "Some events may be lost, rendering further debugging "
4513 "impossible."));
9db8d71f
DJ
4514 udp_warning = 1;
4515 }
4516
4517 return serial_open (name);
4518}
4519
d914c394
SS
4520/* Inform the target of our permission settings. The permission flags
4521 work without this, but if the target knows the settings, it can do
4522 a couple things. First, it can add its own check, to catch cases
4523 that somehow manage to get by the permissions checks in target
4524 methods. Second, if the target is wired to disallow particular
4525 settings (for instance, a system in the field that is not set up to
4526 be able to stop at a breakpoint), it can object to any unavailable
4527 permissions. */
4528
4529void
c378d69d 4530remote_set_permissions (struct target_ops *self)
d914c394
SS
4531{
4532 struct remote_state *rs = get_remote_state ();
4533
bba74b36
YQ
4534 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4535 "WriteReg:%x;WriteMem:%x;"
4536 "InsertBreak:%x;InsertTrace:%x;"
4537 "InsertFastTrace:%x;Stop:%x",
4538 may_write_registers, may_write_memory,
4539 may_insert_breakpoints, may_insert_tracepoints,
4540 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4541 putpkt (rs->buf);
4542 getpkt (&rs->buf, &rs->buf_size, 0);
4543
4544 /* If the target didn't like the packet, warn the user. Do not try
4545 to undo the user's settings, that would just be maddening. */
4546 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4547 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4548}
4549
be2a5f71
DJ
4550/* This type describes each known response to the qSupported
4551 packet. */
4552struct protocol_feature
4553{
4554 /* The name of this protocol feature. */
4555 const char *name;
4556
4557 /* The default for this protocol feature. */
4558 enum packet_support default_support;
4559
4560 /* The function to call when this feature is reported, or after
4561 qSupported processing if the feature is not supported.
4562 The first argument points to this structure. The second
4563 argument indicates whether the packet requested support be
4564 enabled, disabled, or probed (or the default, if this function
4565 is being called at the end of processing and this feature was
4566 not reported). The third argument may be NULL; if not NULL, it
4567 is a NUL-terminated string taken from the packet following
4568 this feature's name and an equals sign. */
4569 void (*func) (const struct protocol_feature *, enum packet_support,
4570 const char *);
4571
4572 /* The corresponding packet for this feature. Only used if
4573 FUNC is remote_supported_packet. */
4574 int packet;
4575};
4576
be2a5f71
DJ
4577static void
4578remote_supported_packet (const struct protocol_feature *feature,
4579 enum packet_support support,
4580 const char *argument)
4581{
4582 if (argument)
4583 {
4584 warning (_("Remote qSupported response supplied an unexpected value for"
4585 " \"%s\"."), feature->name);
4586 return;
4587 }
4588
4082afcc 4589 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4590}
be2a5f71
DJ
4591
4592static void
4593remote_packet_size (const struct protocol_feature *feature,
4594 enum packet_support support, const char *value)
4595{
4596 struct remote_state *rs = get_remote_state ();
4597
4598 int packet_size;
4599 char *value_end;
4600
4601 if (support != PACKET_ENABLE)
4602 return;
4603
4604 if (value == NULL || *value == '\0')
4605 {
4606 warning (_("Remote target reported \"%s\" without a size."),
4607 feature->name);
4608 return;
4609 }
4610
4611 errno = 0;
4612 packet_size = strtol (value, &value_end, 16);
4613 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4614 {
4615 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4616 feature->name, value);
4617 return;
4618 }
4619
be2a5f71
DJ
4620 /* Record the new maximum packet size. */
4621 rs->explicit_packet_size = packet_size;
4622}
4623
dc473cfb 4624static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4625 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4626 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4627 PACKET_qXfer_auxv },
c78fa86a
GB
4628 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4629 PACKET_qXfer_exec_file },
23181151
DJ
4630 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4631 PACKET_qXfer_features },
cfa9d6d9
DJ
4632 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4633 PACKET_qXfer_libraries },
2268b414
JK
4634 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4635 PACKET_qXfer_libraries_svr4 },
ced63ec0 4636 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4637 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4638 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4639 PACKET_qXfer_memory_map },
4de6483e
UW
4640 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4641 PACKET_qXfer_spu_read },
4642 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4643 PACKET_qXfer_spu_write },
07e059b5
VP
4644 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4645 PACKET_qXfer_osdata },
dc146f7c
VP
4646 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4647 PACKET_qXfer_threads },
b3b9301e
PA
4648 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4649 PACKET_qXfer_traceframe_info },
89be2091
DJ
4650 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4651 PACKET_QPassSignals },
82075af2
JS
4652 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4653 PACKET_QCatchSyscalls },
9b224c5e
PA
4654 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4655 PACKET_QProgramSignals },
bc3b087d
SDJ
4656 { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4657 PACKET_QSetWorkingDir },
aefd8b33
SDJ
4658 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4659 PACKET_QStartupWithShell },
0a2dde4a
SDJ
4660 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4661 PACKET_QEnvironmentHexEncoded },
4662 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4663 PACKET_QEnvironmentReset },
4664 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4665 PACKET_QEnvironmentUnset },
a6f3e723
SL
4666 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4667 PACKET_QStartNoAckMode },
4082afcc
PA
4668 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4669 PACKET_multiprocess_feature },
4670 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4671 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4672 PACKET_qXfer_siginfo_read },
4673 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4674 PACKET_qXfer_siginfo_write },
4082afcc 4675 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4676 PACKET_ConditionalTracepoints },
4082afcc 4677 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4678 PACKET_ConditionalBreakpoints },
4082afcc 4679 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4680 PACKET_BreakpointCommands },
4082afcc 4681 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4682 PACKET_FastTracepoints },
4082afcc 4683 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4684 PACKET_StaticTracepoints },
4082afcc 4685 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4686 PACKET_InstallInTrace},
4082afcc
PA
4687 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4688 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4689 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4690 PACKET_bc },
4691 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4692 PACKET_bs },
409873ef
SS
4693 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4694 PACKET_TracepointSource },
d914c394
SS
4695 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4696 PACKET_QAllow },
4082afcc
PA
4697 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4698 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4699 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4700 PACKET_qXfer_fdpic },
169081d0
TG
4701 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4702 PACKET_qXfer_uib },
03583c20
UW
4703 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4704 PACKET_QDisableRandomization },
d1feda86 4705 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4706 { "QTBuffer:size", PACKET_DISABLE,
4707 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4708 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4709 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4710 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4711 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4712 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4713 PACKET_qXfer_btrace },
4714 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4715 PACKET_qXfer_btrace_conf },
4716 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4717 PACKET_Qbtrace_conf_bts_size },
4718 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4719 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4720 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4721 PACKET_fork_event_feature },
4722 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4723 PACKET_vfork_event_feature },
94585166
DB
4724 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4725 PACKET_exec_event_feature },
b20a6524 4726 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4727 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4728 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4729 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4730 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4731};
4732
c8d5aac9
L
4733static char *remote_support_xml;
4734
4735/* Register string appended to "xmlRegisters=" in qSupported query. */
4736
4737void
6e39997a 4738register_remote_support_xml (const char *xml)
c8d5aac9
L
4739{
4740#if defined(HAVE_LIBEXPAT)
4741 if (remote_support_xml == NULL)
c4f7c687 4742 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4743 else
4744 {
4745 char *copy = xstrdup (remote_support_xml + 13);
4746 char *p = strtok (copy, ",");
4747
4748 do
4749 {
4750 if (strcmp (p, xml) == 0)
4751 {
4752 /* already there */
4753 xfree (copy);
4754 return;
4755 }
4756 }
4757 while ((p = strtok (NULL, ",")) != NULL);
4758 xfree (copy);
4759
94b0dee1
PA
4760 remote_support_xml = reconcat (remote_support_xml,
4761 remote_support_xml, ",", xml,
4762 (char *) NULL);
c8d5aac9
L
4763 }
4764#endif
4765}
4766
4767static char *
4768remote_query_supported_append (char *msg, const char *append)
4769{
4770 if (msg)
94b0dee1 4771 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4772 else
4773 return xstrdup (append);
4774}
4775
be2a5f71
DJ
4776static void
4777remote_query_supported (void)
4778{
4779 struct remote_state *rs = get_remote_state ();
4780 char *next;
4781 int i;
4782 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4783
4784 /* The packet support flags are handled differently for this packet
4785 than for most others. We treat an error, a disabled packet, and
4786 an empty response identically: any features which must be reported
4787 to be used will be automatically disabled. An empty buffer
4788 accomplishes this, since that is also the representation for a list
4789 containing no features. */
4790
4791 rs->buf[0] = 0;
4082afcc 4792 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4793 {
c8d5aac9 4794 char *q = NULL;
94b0dee1 4795 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4796
73b8c1fd
PA
4797 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4798 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4799
f7e6eed5
PA
4800 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4801 q = remote_query_supported_append (q, "swbreak+");
4802 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4803 q = remote_query_supported_append (q, "hwbreak+");
4804
dde08ee1
PA
4805 q = remote_query_supported_append (q, "qRelocInsn+");
4806
8020350c
DB
4807 if (packet_set_cmd_state (PACKET_fork_event_feature)
4808 != AUTO_BOOLEAN_FALSE)
4809 q = remote_query_supported_append (q, "fork-events+");
4810 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4811 != AUTO_BOOLEAN_FALSE)
4812 q = remote_query_supported_append (q, "vfork-events+");
4813 if (packet_set_cmd_state (PACKET_exec_event_feature)
4814 != AUTO_BOOLEAN_FALSE)
4815 q = remote_query_supported_append (q, "exec-events+");
89245bc0 4816
750ce8d1
YQ
4817 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4818 q = remote_query_supported_append (q, "vContSupported+");
4819
65706a29
PA
4820 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4821 q = remote_query_supported_append (q, "QThreadEvents+");
4822
f2faf941
PA
4823 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4824 q = remote_query_supported_append (q, "no-resumed+");
4825
b35d5edb
PA
4826 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4827 the qSupported:xmlRegisters=i386 handling. */
4828 if (remote_support_xml != NULL)
4829 q = remote_query_supported_append (q, remote_support_xml);
4830
dde08ee1
PA
4831 q = reconcat (q, "qSupported:", q, (char *) NULL);
4832 putpkt (q);
82f73884 4833
94b0dee1
PA
4834 do_cleanups (old_chain);
4835
be2a5f71
DJ
4836 getpkt (&rs->buf, &rs->buf_size, 0);
4837
4838 /* If an error occured, warn, but do not return - just reset the
4839 buffer to empty and go on to disable features. */
4840 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4841 == PACKET_ERROR)
4842 {
4843 warning (_("Remote failure reply: %s"), rs->buf);
4844 rs->buf[0] = 0;
4845 }
4846 }
4847
4848 memset (seen, 0, sizeof (seen));
4849
4850 next = rs->buf;
4851 while (*next)
4852 {
4853 enum packet_support is_supported;
4854 char *p, *end, *name_end, *value;
4855
4856 /* First separate out this item from the rest of the packet. If
4857 there's another item after this, we overwrite the separator
4858 (terminated strings are much easier to work with). */
4859 p = next;
4860 end = strchr (p, ';');
4861 if (end == NULL)
4862 {
4863 end = p + strlen (p);
4864 next = end;
4865 }
4866 else
4867 {
89be2091
DJ
4868 *end = '\0';
4869 next = end + 1;
4870
be2a5f71
DJ
4871 if (end == p)
4872 {
4873 warning (_("empty item in \"qSupported\" response"));
4874 continue;
4875 }
be2a5f71
DJ
4876 }
4877
4878 name_end = strchr (p, '=');
4879 if (name_end)
4880 {
4881 /* This is a name=value entry. */
4882 is_supported = PACKET_ENABLE;
4883 value = name_end + 1;
4884 *name_end = '\0';
4885 }
4886 else
4887 {
4888 value = NULL;
4889 switch (end[-1])
4890 {
4891 case '+':
4892 is_supported = PACKET_ENABLE;
4893 break;
4894
4895 case '-':
4896 is_supported = PACKET_DISABLE;
4897 break;
4898
4899 case '?':
4900 is_supported = PACKET_SUPPORT_UNKNOWN;
4901 break;
4902
4903 default:
3e43a32a
MS
4904 warning (_("unrecognized item \"%s\" "
4905 "in \"qSupported\" response"), p);
be2a5f71
DJ
4906 continue;
4907 }
4908 end[-1] = '\0';
4909 }
4910
4911 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4912 if (strcmp (remote_protocol_features[i].name, p) == 0)
4913 {
4914 const struct protocol_feature *feature;
4915
4916 seen[i] = 1;
4917 feature = &remote_protocol_features[i];
4918 feature->func (feature, is_supported, value);
4919 break;
4920 }
4921 }
4922
4923 /* If we increased the packet size, make sure to increase the global
4924 buffer size also. We delay this until after parsing the entire
4925 qSupported packet, because this is the same buffer we were
4926 parsing. */
4927 if (rs->buf_size < rs->explicit_packet_size)
4928 {
4929 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4930 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4931 }
4932
4933 /* Handle the defaults for unmentioned features. */
4934 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4935 if (!seen[i])
4936 {
4937 const struct protocol_feature *feature;
4938
4939 feature = &remote_protocol_features[i];
4940 feature->func (feature, feature->default_support, NULL);
4941 }
4942}
4943
048094ac
PA
4944/* Serial QUIT handler for the remote serial descriptor.
4945
4946 Defers handling a Ctrl-C until we're done with the current
4947 command/response packet sequence, unless:
4948
4949 - We're setting up the connection. Don't send a remote interrupt
4950 request, as we're not fully synced yet. Quit immediately
4951 instead.
4952
4953 - The target has been resumed in the foreground
223ffa71 4954 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
4955 packet, and we're blocked waiting for the stop reply, thus a
4956 Ctrl-C should be immediately sent to the target.
4957
4958 - We get a second Ctrl-C while still within the same serial read or
4959 write. In that case the serial is seemingly wedged --- offer to
4960 quit/disconnect.
4961
4962 - We see a second Ctrl-C without target response, after having
4963 previously interrupted the target. In that case the target/stub
4964 is probably wedged --- offer to quit/disconnect.
4965*/
4966
4967static void
4968remote_serial_quit_handler (void)
4969{
4970 struct remote_state *rs = get_remote_state ();
4971
4972 if (check_quit_flag ())
4973 {
4974 /* If we're starting up, we're not fully synced yet. Quit
4975 immediately. */
4976 if (rs->starting_up)
4977 quit ();
4978 else if (rs->got_ctrlc_during_io)
4979 {
4980 if (query (_("The target is not responding to GDB commands.\n"
4981 "Stop debugging it? ")))
4982 remote_unpush_and_throw ();
4983 }
4984 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 4985 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
4986 interrupt_query ();
4987 /* All-stop protocol, and blocked waiting for stop reply. Send
4988 an interrupt request. */
223ffa71 4989 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
048094ac
PA
4990 target_interrupt (inferior_ptid);
4991 else
4992 rs->got_ctrlc_during_io = 1;
4993 }
4994}
4995
78a095c3
JK
4996/* Remove any of the remote.c targets from target stack. Upper targets depend
4997 on it so remove them first. */
4998
4999static void
5000remote_unpush_target (void)
5001{
915ef8b1 5002 pop_all_targets_at_and_above (process_stratum);
78a095c3 5003}
be2a5f71 5004
048094ac
PA
5005static void
5006remote_unpush_and_throw (void)
5007{
5008 remote_unpush_target ();
5009 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5010}
5011
c906108c 5012static void
014f9477 5013remote_open_1 (const char *name, int from_tty,
3e43a32a 5014 struct target_ops *target, int extended_p)
c906108c 5015{
d01949b6 5016 struct remote_state *rs = get_remote_state ();
a6f3e723 5017
c906108c 5018 if (name == 0)
8a3fe4f8 5019 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5020 "serial device is attached to the remote system\n"
8a3fe4f8 5021 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5022
23860348 5023 /* See FIXME above. */
c6ebd6cf 5024 if (!target_async_permitted)
92d1e331 5025 wait_forever_enabled_p = 1;
6426a772 5026
2d717e4f 5027 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5028 Ask this question first, before target_preopen has a chance to kill
5029 anything. */
5d93a237 5030 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 5031 {
78a095c3
JK
5032 if (from_tty
5033 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5034 error (_("Still connected."));
5035 }
5036
78a095c3 5037 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5038 target_preopen (from_tty);
5039
89be2091 5040 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
5041 xfree (rs->last_pass_packet);
5042 rs->last_pass_packet = NULL;
89be2091 5043
9b224c5e
PA
5044 /* Make sure we send the program signals list the next time we
5045 resume. */
5e4a05c4
TT
5046 xfree (rs->last_program_signals_packet);
5047 rs->last_program_signals_packet = NULL;
9b224c5e 5048
ad9a8f3f 5049 remote_fileio_reset ();
1dd41f16
NS
5050 reopen_exec_file ();
5051 reread_symbols ();
5052
5d93a237
TT
5053 rs->remote_desc = remote_serial_open (name);
5054 if (!rs->remote_desc)
c906108c
SS
5055 perror_with_name (name);
5056
5057 if (baud_rate != -1)
5058 {
5d93a237 5059 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5060 {
9b74d5d3
KB
5061 /* The requested speed could not be set. Error out to
5062 top level after closing remote_desc. Take care to
5063 set remote_desc to NULL to avoid closing remote_desc
5064 more than once. */
5d93a237
TT
5065 serial_close (rs->remote_desc);
5066 rs->remote_desc = NULL;
c906108c
SS
5067 perror_with_name (name);
5068 }
5069 }
5070
236af5e3 5071 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5072 serial_raw (rs->remote_desc);
c906108c
SS
5073
5074 /* If there is something sitting in the buffer we might take it as a
5075 response to a command, which would be bad. */
5d93a237 5076 serial_flush_input (rs->remote_desc);
c906108c
SS
5077
5078 if (from_tty)
5079 {
5080 puts_filtered ("Remote debugging using ");
5081 puts_filtered (name);
5082 puts_filtered ("\n");
5083 }
23860348 5084 push_target (target); /* Switch to using remote target now. */
c906108c 5085
74531fed
PA
5086 /* Register extra event sources in the event loop. */
5087 remote_async_inferior_event_token
5088 = create_async_event_handler (remote_async_inferior_event_handler,
5089 NULL);
5965e028 5090 rs->notif_state = remote_notif_state_allocate ();
74531fed 5091
be2a5f71
DJ
5092 /* Reset the target state; these things will be queried either by
5093 remote_query_supported or as they are needed. */
ca4f7f8b 5094 reset_all_packet_configs_support ();
74531fed 5095 rs->cached_wait_status = 0;
be2a5f71 5096 rs->explicit_packet_size = 0;
a6f3e723 5097 rs->noack_mode = 0;
82f73884 5098 rs->extended = extended_p;
e24a49d8 5099 rs->waiting_for_stop_reply = 0;
3a29589a 5100 rs->ctrlc_pending_p = 0;
048094ac 5101 rs->got_ctrlc_during_io = 0;
802188a7 5102
47f8a51d
TT
5103 rs->general_thread = not_sent_ptid;
5104 rs->continue_thread = not_sent_ptid;
262e1174 5105 rs->remote_traceframe_number = -1;
c906108c 5106
3a00c802
PA
5107 rs->last_resume_exec_dir = EXEC_FORWARD;
5108
9d1f7ab2 5109 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5110 rs->use_threadinfo_query = 1;
5111 rs->use_threadextra_query = 1;
9d1f7ab2 5112
80152258
PA
5113 readahead_cache_invalidate ();
5114
c6ebd6cf 5115 if (target_async_permitted)
92d1e331 5116 {
92d1e331
DJ
5117 /* FIXME: cagney/1999-09-23: During the initial connection it is
5118 assumed that the target is already ready and able to respond to
0df8b418 5119 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5120 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5121 around this. Eventually a mechanism that allows
92d1e331 5122 wait_for_inferior() to expect/get timeouts will be
23860348 5123 implemented. */
92d1e331
DJ
5124 wait_forever_enabled_p = 0;
5125 }
5126
23860348 5127 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5128 no_shared_libraries (NULL, 0);
f78f6cf1 5129
74531fed
PA
5130 /* Start afresh. */
5131 init_thread_list ();
5132
36918e70 5133 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5134 target (we'd otherwise be in an inconsistent state) and then
5135 propogate the error on up the exception chain. This ensures that
5136 the caller doesn't stumble along blindly assuming that the
5137 function succeeded. The CLI doesn't have this problem but other
5138 UI's, such as MI do.
36918e70
AC
5139
5140 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5141 this function should return an error indication letting the
ce2826aa 5142 caller restore the previous state. Unfortunately the command
36918e70
AC
5143 ``target remote'' is directly wired to this function making that
5144 impossible. On a positive note, the CLI side of this problem has
5145 been fixed - the function set_cmd_context() makes it possible for
5146 all the ``target ....'' commands to share a common callback
5147 function. See cli-dump.c. */
109c3e39 5148 {
2d717e4f 5149
492d29ea 5150 TRY
04bd08de
TT
5151 {
5152 remote_start_remote (from_tty, target, extended_p);
5153 }
492d29ea 5154 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5155 {
c8d104ad
PA
5156 /* Pop the partially set up target - unless something else did
5157 already before throwing the exception. */
5d93a237 5158 if (rs->remote_desc != NULL)
78a095c3 5159 remote_unpush_target ();
c6ebd6cf 5160 if (target_async_permitted)
109c3e39
AC
5161 wait_forever_enabled_p = 1;
5162 throw_exception (ex);
5163 }
492d29ea 5164 END_CATCH
109c3e39 5165 }
c906108c 5166
f4abbc16
MM
5167 remote_btrace_reset ();
5168
c6ebd6cf 5169 if (target_async_permitted)
92d1e331 5170 wait_forever_enabled_p = 1;
43ff13b4
JM
5171}
5172
de0d863e
DB
5173/* Detach the specified process. */
5174
5175static void
5176remote_detach_pid (int pid)
5177{
5178 struct remote_state *rs = get_remote_state ();
5179
5180 if (remote_multi_process_p (rs))
5181 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5182 else
5183 strcpy (rs->buf, "D");
5184
5185 putpkt (rs->buf);
5186 getpkt (&rs->buf, &rs->buf_size, 0);
5187
5188 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5189 ;
5190 else if (rs->buf[0] == '\0')
5191 error (_("Remote doesn't know how to detach"));
5192 else
5193 error (_("Can't detach process."));
5194}
5195
5196/* This detaches a program to which we previously attached, using
5197 inferior_ptid to identify the process. After this is done, GDB
5198 can be used to debug some other program. We better not have left
5199 any breakpoints in the target program or it'll die when it hits
5200 one. */
c906108c
SS
5201
5202static void
de0d863e 5203remote_detach_1 (const char *args, int from_tty)
c906108c 5204{
82f73884 5205 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5206 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5207 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5208 int is_fork_parent;
c906108c
SS
5209
5210 if (args)
8a3fe4f8 5211 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 5212
2d717e4f
DJ
5213 if (!target_has_execution)
5214 error (_("No process to detach from."));
5215
0f48b757 5216 target_announce_detach (from_tty);
7cee1e54 5217
c906108c 5218 /* Tell the remote target to detach. */
de0d863e 5219 remote_detach_pid (pid);
82f73884 5220
8020350c
DB
5221 /* Exit only if this is the only active inferior. */
5222 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5223 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5224
de0d863e
DB
5225 /* Check to see if we are detaching a fork parent. Note that if we
5226 are detaching a fork child, tp == NULL. */
5227 is_fork_parent = (tp != NULL
5228 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5229
5230 /* If doing detach-on-fork, we don't mourn, because that will delete
5231 breakpoints that should be available for the followed inferior. */
5232 if (!is_fork_parent)
bc1e6c81 5233 target_mourn_inferior (inferior_ptid);
de0d863e
DB
5234 else
5235 {
5236 inferior_ptid = null_ptid;
5237 detach_inferior (pid);
5238 }
2d717e4f
DJ
5239}
5240
5241static void
52554a0e 5242remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5243{
de0d863e 5244 remote_detach_1 (args, from_tty);
2d717e4f
DJ
5245}
5246
5247static void
52554a0e 5248extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5249{
de0d863e
DB
5250 remote_detach_1 (args, from_tty);
5251}
5252
5253/* Target follow-fork function for remote targets. On entry, and
5254 at return, the current inferior is the fork parent.
5255
5256 Note that although this is currently only used for extended-remote,
5257 it is named remote_follow_fork in anticipation of using it for the
5258 remote target as well. */
5259
5260static int
5261remote_follow_fork (struct target_ops *ops, int follow_child,
5262 int detach_fork)
5263{
5264 struct remote_state *rs = get_remote_state ();
c269dbdb 5265 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5266
c269dbdb
DB
5267 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5268 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5269 {
5270 /* When following the parent and detaching the child, we detach
5271 the child here. For the case of following the child and
5272 detaching the parent, the detach is done in the target-
5273 independent follow fork code in infrun.c. We can't use
5274 target_detach when detaching an unfollowed child because
5275 the client side doesn't know anything about the child. */
5276 if (detach_fork && !follow_child)
5277 {
5278 /* Detach the fork child. */
5279 ptid_t child_ptid;
5280 pid_t child_pid;
5281
5282 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5283 child_pid = ptid_get_pid (child_ptid);
5284
5285 remote_detach_pid (child_pid);
5286 detach_inferior (child_pid);
5287 }
5288 }
5289 return 0;
c906108c
SS
5290}
5291
94585166
DB
5292/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5293 in the program space of the new inferior. On entry and at return the
5294 current inferior is the exec'ing inferior. INF is the new exec'd
5295 inferior, which may be the same as the exec'ing inferior unless
5296 follow-exec-mode is "new". */
5297
5298static void
5299remote_follow_exec (struct target_ops *ops,
5300 struct inferior *inf, char *execd_pathname)
5301{
5302 /* We know that this is a target file name, so if it has the "target:"
5303 prefix we strip it off before saving it in the program space. */
5304 if (is_target_filename (execd_pathname))
5305 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5306
5307 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5308}
5309
6ad8ae5c
DJ
5310/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5311
43ff13b4 5312static void
fee354ee 5313remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5314{
43ff13b4 5315 if (args)
2d717e4f 5316 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5317
8020350c
DB
5318 /* Make sure we unpush even the extended remote targets. Calling
5319 target_mourn_inferior won't unpush, and remote_mourn won't
5320 unpush if there is more than one inferior left. */
5321 unpush_target (target);
5322 generic_mourn_inferior ();
2d717e4f 5323
43ff13b4
JM
5324 if (from_tty)
5325 puts_filtered ("Ending remote debugging.\n");
5326}
5327
2d717e4f
DJ
5328/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5329 be chatty about it. */
5330
5331static void
20f796c9
GB
5332extended_remote_attach (struct target_ops *target, const char *args,
5333 int from_tty)
2d717e4f
DJ
5334{
5335 struct remote_state *rs = get_remote_state ();
be86555c 5336 int pid;
96ef3384 5337 char *wait_status = NULL;
2d717e4f 5338
74164c56 5339 pid = parse_pid_to_attach (args);
2d717e4f 5340
74164c56
JK
5341 /* Remote PID can be freely equal to getpid, do not check it here the same
5342 way as in other targets. */
2d717e4f 5343
4082afcc 5344 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5345 error (_("This target does not support attaching to a process"));
5346
7cee1e54
PA
5347 if (from_tty)
5348 {
5349 char *exec_file = get_exec_file (0);
5350
5351 if (exec_file)
5352 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5353 target_pid_to_str (pid_to_ptid (pid)));
5354 else
5355 printf_unfiltered (_("Attaching to %s\n"),
5356 target_pid_to_str (pid_to_ptid (pid)));
5357
5358 gdb_flush (gdb_stdout);
5359 }
5360
bba74b36 5361 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5362 putpkt (rs->buf);
5363 getpkt (&rs->buf, &rs->buf_size, 0);
5364
4082afcc
PA
5365 switch (packet_ok (rs->buf,
5366 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5367 {
4082afcc 5368 case PACKET_OK:
6efcd9a8 5369 if (!target_is_non_stop_p ())
74531fed
PA
5370 {
5371 /* Save the reply for later. */
224c3ddb 5372 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5373 strcpy (wait_status, rs->buf);
5374 }
5375 else if (strcmp (rs->buf, "OK") != 0)
5376 error (_("Attaching to %s failed with: %s"),
5377 target_pid_to_str (pid_to_ptid (pid)),
5378 rs->buf);
4082afcc
PA
5379 break;
5380 case PACKET_UNKNOWN:
5381 error (_("This target does not support attaching to a process"));
5382 default:
5383 error (_("Attaching to %s failed"),
5384 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5385 }
2d717e4f 5386
1b6e6f5c 5387 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5388
2d717e4f 5389 inferior_ptid = pid_to_ptid (pid);
79d7f229 5390
6efcd9a8 5391 if (target_is_non_stop_p ())
bad34192
PA
5392 {
5393 struct thread_info *thread;
79d7f229 5394
bad34192 5395 /* Get list of threads. */
e8032dde 5396 remote_update_thread_list (target);
82f73884 5397
bad34192
PA
5398 thread = first_thread_of_process (pid);
5399 if (thread)
5400 inferior_ptid = thread->ptid;
5401 else
5402 inferior_ptid = pid_to_ptid (pid);
5403
5404 /* Invalidate our notion of the remote current thread. */
47f8a51d 5405 record_currthread (rs, minus_one_ptid);
bad34192 5406 }
74531fed 5407 else
bad34192
PA
5408 {
5409 /* Now, if we have thread information, update inferior_ptid. */
5410 inferior_ptid = remote_current_thread (inferior_ptid);
5411
5412 /* Add the main thread to the thread list. */
5413 add_thread_silent (inferior_ptid);
5414 }
c0a2216e 5415
96ef3384
UW
5416 /* Next, if the target can specify a description, read it. We do
5417 this before anything involving memory or registers. */
5418 target_find_description ();
5419
6efcd9a8 5420 if (!target_is_non_stop_p ())
74531fed
PA
5421 {
5422 /* Use the previously fetched status. */
5423 gdb_assert (wait_status != NULL);
5424
5425 if (target_can_async_p ())
5426 {
722247f1
YQ
5427 struct notif_event *reply
5428 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5429
722247f1 5430 push_stop_reply ((struct stop_reply *) reply);
74531fed 5431
6a3753b3 5432 target_async (1);
74531fed
PA
5433 }
5434 else
5435 {
5436 gdb_assert (wait_status != NULL);
5437 strcpy (rs->buf, wait_status);
5438 rs->cached_wait_status = 1;
5439 }
5440 }
5441 else
5442 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5443}
5444
b9c1d481
AS
5445/* Implementation of the to_post_attach method. */
5446
5447static void
5448extended_remote_post_attach (struct target_ops *ops, int pid)
5449{
6efcd9a8
PA
5450 /* Get text, data & bss offsets. */
5451 get_offsets ();
5452
b9c1d481
AS
5453 /* In certain cases GDB might not have had the chance to start
5454 symbol lookup up until now. This could happen if the debugged
5455 binary is not using shared libraries, the vsyscall page is not
5456 present (on Linux) and the binary itself hadn't changed since the
5457 debugging process was started. */
5458 if (symfile_objfile != NULL)
5459 remote_check_symbols();
5460}
5461
c906108c 5462\f
506fb367
DJ
5463/* Check for the availability of vCont. This function should also check
5464 the response. */
c906108c
SS
5465
5466static void
6d820c5c 5467remote_vcont_probe (struct remote_state *rs)
c906108c 5468{
2e9f7625 5469 char *buf;
6d820c5c 5470
2e9f7625
DJ
5471 strcpy (rs->buf, "vCont?");
5472 putpkt (rs->buf);
6d820c5c 5473 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5474 buf = rs->buf;
c906108c 5475
506fb367 5476 /* Make sure that the features we assume are supported. */
61012eef 5477 if (startswith (buf, "vCont"))
506fb367
DJ
5478 {
5479 char *p = &buf[5];
750ce8d1 5480 int support_c, support_C;
506fb367 5481
750ce8d1
YQ
5482 rs->supports_vCont.s = 0;
5483 rs->supports_vCont.S = 0;
506fb367
DJ
5484 support_c = 0;
5485 support_C = 0;
d458bd84 5486 rs->supports_vCont.t = 0;
c1e36e3e 5487 rs->supports_vCont.r = 0;
506fb367
DJ
5488 while (p && *p == ';')
5489 {
5490 p++;
5491 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5492 rs->supports_vCont.s = 1;
506fb367 5493 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5494 rs->supports_vCont.S = 1;
506fb367
DJ
5495 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5496 support_c = 1;
5497 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5498 support_C = 1;
74531fed 5499 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5500 rs->supports_vCont.t = 1;
c1e36e3e
PA
5501 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5502 rs->supports_vCont.r = 1;
506fb367
DJ
5503
5504 p = strchr (p, ';');
5505 }
c906108c 5506
750ce8d1
YQ
5507 /* If c, and C are not all supported, we can't use vCont. Clearing
5508 BUF will make packet_ok disable the packet. */
5509 if (!support_c || !support_C)
506fb367
DJ
5510 buf[0] = 0;
5511 }
c906108c 5512
444abaca 5513 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5514}
c906108c 5515
0d8f58ca
PA
5516/* Helper function for building "vCont" resumptions. Write a
5517 resumption to P. ENDP points to one-passed-the-end of the buffer
5518 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5519 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5520 resumed thread should be single-stepped and/or signalled. If PTID
5521 equals minus_one_ptid, then all threads are resumed; if PTID
5522 represents a process, then all threads of the process are resumed;
5523 the thread to be stepped and/or signalled is given in the global
5524 INFERIOR_PTID. */
5525
5526static char *
5527append_resumption (char *p, char *endp,
2ea28649 5528 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5529{
5530 struct remote_state *rs = get_remote_state ();
5531
a493e3e2 5532 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5533 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5534 else if (step
5535 /* GDB is willing to range step. */
5536 && use_range_stepping
5537 /* Target supports range stepping. */
5538 && rs->supports_vCont.r
5539 /* We don't currently support range stepping multiple
5540 threads with a wildcard (though the protocol allows it,
5541 so stubs shouldn't make an active effort to forbid
5542 it). */
5543 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5544 {
5545 struct thread_info *tp;
5546
5547 if (ptid_equal (ptid, minus_one_ptid))
5548 {
5549 /* If we don't know about the target thread's tid, then
5550 we're resuming magic_null_ptid (see caller). */
5551 tp = find_thread_ptid (magic_null_ptid);
5552 }
5553 else
5554 tp = find_thread_ptid (ptid);
5555 gdb_assert (tp != NULL);
5556
5557 if (tp->control.may_range_step)
5558 {
5559 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5560
5561 p += xsnprintf (p, endp - p, ";r%s,%s",
5562 phex_nz (tp->control.step_range_start,
5563 addr_size),
5564 phex_nz (tp->control.step_range_end,
5565 addr_size));
5566 }
5567 else
5568 p += xsnprintf (p, endp - p, ";s");
5569 }
0d8f58ca
PA
5570 else if (step)
5571 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5572 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5573 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5574 else
5575 p += xsnprintf (p, endp - p, ";c");
5576
5577 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5578 {
5579 ptid_t nptid;
5580
5581 /* All (-1) threads of process. */
ba348170 5582 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5583
5584 p += xsnprintf (p, endp - p, ":");
5585 p = write_ptid (p, endp, nptid);
5586 }
5587 else if (!ptid_equal (ptid, minus_one_ptid))
5588 {
5589 p += xsnprintf (p, endp - p, ":");
5590 p = write_ptid (p, endp, ptid);
5591 }
5592
5593 return p;
5594}
5595
799a2abe
PA
5596/* Clear the thread's private info on resume. */
5597
5598static void
5599resume_clear_thread_private_info (struct thread_info *thread)
5600{
5601 if (thread->priv != NULL)
5602 {
5603 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5604 thread->priv->watch_data_address = 0;
5605 }
5606}
5607
e5ef252a
PA
5608/* Append a vCont continue-with-signal action for threads that have a
5609 non-zero stop signal. */
5610
5611static char *
5612append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5613{
5614 struct thread_info *thread;
5615
034f788c 5616 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5617 if (ptid_match (thread->ptid, ptid)
5618 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5619 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5620 {
5621 p = append_resumption (p, endp, thread->ptid,
5622 0, thread->suspend.stop_signal);
5623 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5624 resume_clear_thread_private_info (thread);
e5ef252a
PA
5625 }
5626
5627 return p;
5628}
5629
7b68ffbb
PA
5630/* Set the target running, using the packets that use Hc
5631 (c/s/C/S). */
5632
5633static void
5634remote_resume_with_hc (struct target_ops *ops,
5635 ptid_t ptid, int step, enum gdb_signal siggnal)
5636{
5637 struct remote_state *rs = get_remote_state ();
5638 struct thread_info *thread;
5639 char *buf;
5640
5641 rs->last_sent_signal = siggnal;
5642 rs->last_sent_step = step;
5643
5644 /* The c/s/C/S resume packets use Hc, so set the continue
5645 thread. */
5646 if (ptid_equal (ptid, minus_one_ptid))
5647 set_continue_thread (any_thread_ptid);
5648 else
5649 set_continue_thread (ptid);
5650
5651 ALL_NON_EXITED_THREADS (thread)
5652 resume_clear_thread_private_info (thread);
5653
5654 buf = rs->buf;
5655 if (execution_direction == EXEC_REVERSE)
5656 {
5657 /* We don't pass signals to the target in reverse exec mode. */
5658 if (info_verbose && siggnal != GDB_SIGNAL_0)
5659 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5660 siggnal);
5661
5662 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5663 error (_("Remote reverse-step not supported."));
5664 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5665 error (_("Remote reverse-continue not supported."));
5666
5667 strcpy (buf, step ? "bs" : "bc");
5668 }
5669 else if (siggnal != GDB_SIGNAL_0)
5670 {
5671 buf[0] = step ? 'S' : 'C';
5672 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5673 buf[2] = tohex (((int) siggnal) & 0xf);
5674 buf[3] = '\0';
5675 }
5676 else
5677 strcpy (buf, step ? "s" : "c");
5678
5679 putpkt (buf);
5680}
5681
506fb367
DJ
5682/* Resume the remote inferior by using a "vCont" packet. The thread
5683 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5684 resumed thread should be single-stepped and/or signalled. If PTID
5685 equals minus_one_ptid, then all threads are resumed; the thread to
5686 be stepped and/or signalled is given in the global INFERIOR_PTID.
5687 This function returns non-zero iff it resumes the inferior.
44eaed12 5688
7b68ffbb
PA
5689 This function issues a strict subset of all possible vCont commands
5690 at the moment. */
44eaed12 5691
506fb367 5692static int
7b68ffbb 5693remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5694{
5695 struct remote_state *rs = get_remote_state ();
82f73884
PA
5696 char *p;
5697 char *endp;
44eaed12 5698
7b68ffbb
PA
5699 /* No reverse execution actions defined for vCont. */
5700 if (execution_direction == EXEC_REVERSE)
5701 return 0;
5702
4082afcc 5703 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5704 remote_vcont_probe (rs);
44eaed12 5705
4082afcc 5706 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5707 return 0;
44eaed12 5708
82f73884
PA
5709 p = rs->buf;
5710 endp = rs->buf + get_remote_packet_size ();
5711
506fb367
DJ
5712 /* If we could generate a wider range of packets, we'd have to worry
5713 about overflowing BUF. Should there be a generic
5714 "multi-part-packet" packet? */
5715
0d8f58ca
PA
5716 p += xsnprintf (p, endp - p, "vCont");
5717
79d7f229 5718 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5719 {
79d7f229
PA
5720 /* MAGIC_NULL_PTID means that we don't have any active threads,
5721 so we don't have any TID numbers the inferior will
5722 understand. Make sure to only send forms that do not specify
5723 a TID. */
a9cbf802 5724 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5725 }
0d8f58ca 5726 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5727 {
0d8f58ca
PA
5728 /* Resume all threads (of all processes, or of a single
5729 process), with preference for INFERIOR_PTID. This assumes
5730 inferior_ptid belongs to the set of all threads we are about
5731 to resume. */
a493e3e2 5732 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5733 {
0d8f58ca
PA
5734 /* Step inferior_ptid, with or without signal. */
5735 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5736 }
0d8f58ca 5737
e5ef252a
PA
5738 /* Also pass down any pending signaled resumption for other
5739 threads not the current. */
5740 p = append_pending_thread_resumptions (p, endp, ptid);
5741
0d8f58ca 5742 /* And continue others without a signal. */
a493e3e2 5743 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5744 }
5745 else
506fb367
DJ
5746 {
5747 /* Scheduler locking; resume only PTID. */
a9cbf802 5748 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5749 }
c906108c 5750
82f73884
PA
5751 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5752 putpkt (rs->buf);
506fb367 5753
6efcd9a8 5754 if (target_is_non_stop_p ())
74531fed
PA
5755 {
5756 /* In non-stop, the stub replies to vCont with "OK". The stop
5757 reply will be reported asynchronously by means of a `%Stop'
5758 notification. */
5759 getpkt (&rs->buf, &rs->buf_size, 0);
5760 if (strcmp (rs->buf, "OK") != 0)
5761 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5762 }
5763
506fb367 5764 return 1;
c906108c 5765}
43ff13b4 5766
506fb367
DJ
5767/* Tell the remote machine to resume. */
5768
43ff13b4 5769static void
28439f5e 5770remote_resume (struct target_ops *ops,
2ea28649 5771 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5772{
d01949b6 5773 struct remote_state *rs = get_remote_state ();
43ff13b4 5774
85ad3aaf
PA
5775 /* When connected in non-stop mode, the core resumes threads
5776 individually. Resuming remote threads directly in target_resume
5777 would thus result in sending one packet per thread. Instead, to
5778 minimize roundtrip latency, here we just store the resume
5779 request; the actual remote resumption will be done in
5780 target_commit_resume / remote_commit_resume, where we'll be able
5781 to do vCont action coalescing. */
5782 if (target_is_non_stop_p () && execution_direction != EXEC_REVERSE)
5783 {
5784 struct private_thread_info *remote_thr;
5785
5786 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5787 remote_thr = get_private_info_ptid (inferior_ptid);
5788 else
5789 remote_thr = get_private_info_ptid (ptid);
5790 remote_thr->last_resume_step = step;
5791 remote_thr->last_resume_sig = siggnal;
5792 return;
5793 }
5794
722247f1
YQ
5795 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5796 (explained in remote-notif.c:handle_notification) so
5797 remote_notif_process is not called. We need find a place where
5798 it is safe to start a 'vNotif' sequence. It is good to do it
5799 before resuming inferior, because inferior was stopped and no RSP
5800 traffic at that moment. */
6efcd9a8 5801 if (!target_is_non_stop_p ())
5965e028 5802 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5803
3a00c802
PA
5804 rs->last_resume_exec_dir = execution_direction;
5805
7b68ffbb
PA
5806 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
5807 if (!remote_resume_with_vcont (ptid, step, siggnal))
5808 remote_resume_with_hc (ops, ptid, step, siggnal);
43ff13b4 5809
2acceee2 5810 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5811 with the event loop. NOTE: this is the one place where all the
5812 execution commands end up. We could alternatively do this in each
23860348 5813 of the execution commands in infcmd.c. */
2acceee2
JM
5814 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5815 into infcmd.c in order to allow inferior function calls to work
23860348 5816 NOT asynchronously. */
362646f5 5817 if (target_can_async_p ())
6a3753b3 5818 target_async (1);
e24a49d8
PA
5819
5820 /* We've just told the target to resume. The remote server will
5821 wait for the inferior to stop, and then send a stop reply. In
5822 the mean time, we can't start another command/query ourselves
74531fed
PA
5823 because the stub wouldn't be ready to process it. This applies
5824 only to the base all-stop protocol, however. In non-stop (which
5825 only supports vCont), the stub replies with an "OK", and is
5826 immediate able to process further serial input. */
6efcd9a8 5827 if (!target_is_non_stop_p ())
74531fed 5828 rs->waiting_for_stop_reply = 1;
43ff13b4 5829}
85ad3aaf
PA
5830
5831static void check_pending_events_prevent_wildcard_vcont
5832 (int *may_global_wildcard_vcont);
5833static int is_pending_fork_parent_thread (struct thread_info *thread);
5834
5835/* Private per-inferior info for target remote processes. */
5836
5837struct private_inferior
5838{
5839 /* Whether we can send a wildcard vCont for this process. */
5840 int may_wildcard_vcont;
5841};
5842
5843/* Structure used to track the construction of a vCont packet in the
5844 outgoing packet buffer. This is used to send multiple vCont
5845 packets if we have more actions than would fit a single packet. */
5846
5847struct vcont_builder
5848{
5849 /* Pointer to the first action. P points here if no action has been
5850 appended yet. */
5851 char *first_action;
5852
5853 /* Where the next action will be appended. */
5854 char *p;
5855
5856 /* The end of the buffer. Must never write past this. */
5857 char *endp;
5858};
5859
5860/* Prepare the outgoing buffer for a new vCont packet. */
5861
5862static void
5863vcont_builder_restart (struct vcont_builder *builder)
5864{
5865 struct remote_state *rs = get_remote_state ();
5866
5867 builder->p = rs->buf;
5868 builder->endp = rs->buf + get_remote_packet_size ();
5869 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
5870 builder->first_action = builder->p;
5871}
5872
5873/* If the vCont packet being built has any action, send it to the
5874 remote end. */
5875
5876static void
5877vcont_builder_flush (struct vcont_builder *builder)
5878{
5879 struct remote_state *rs;
5880
5881 if (builder->p == builder->first_action)
5882 return;
5883
5884 rs = get_remote_state ();
5885 putpkt (rs->buf);
5886 getpkt (&rs->buf, &rs->buf_size, 0);
5887 if (strcmp (rs->buf, "OK") != 0)
5888 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5889}
5890
5891/* The largest action is range-stepping, with its two addresses. This
5892 is more than sufficient. If a new, bigger action is created, it'll
5893 quickly trigger a failed assertion in append_resumption (and we'll
5894 just bump this). */
5895#define MAX_ACTION_SIZE 200
5896
5897/* Append a new vCont action in the outgoing packet being built. If
5898 the action doesn't fit the packet along with previous actions, push
5899 what we've got so far to the remote end and start over a new vCont
5900 packet (with the new action). */
5901
5902static void
5903vcont_builder_push_action (struct vcont_builder *builder,
5904 ptid_t ptid, int step, enum gdb_signal siggnal)
5905{
5906 char buf[MAX_ACTION_SIZE + 1];
5907 char *endp;
5908 size_t rsize;
5909
5910 endp = append_resumption (buf, buf + sizeof (buf),
5911 ptid, step, siggnal);
5912
5913 /* Check whether this new action would fit in the vCont packet along
5914 with previous actions. If not, send what we've got so far and
5915 start a new vCont packet. */
5916 rsize = endp - buf;
5917 if (rsize > builder->endp - builder->p)
5918 {
5919 vcont_builder_flush (builder);
5920 vcont_builder_restart (builder);
5921
5922 /* Should now fit. */
5923 gdb_assert (rsize <= builder->endp - builder->p);
5924 }
5925
5926 memcpy (builder->p, buf, rsize);
5927 builder->p += rsize;
5928 *builder->p = '\0';
5929}
5930
5931/* to_commit_resume implementation. */
5932
5933static void
5934remote_commit_resume (struct target_ops *ops)
5935{
5936 struct remote_state *rs = get_remote_state ();
5937 struct inferior *inf;
5938 struct thread_info *tp;
5939 int any_process_wildcard;
5940 int may_global_wildcard_vcont;
5941 struct vcont_builder vcont_builder;
5942
5943 /* If connected in all-stop mode, we'd send the remote resume
5944 request directly from remote_resume. Likewise if
5945 reverse-debugging, as there are no defined vCont actions for
5946 reverse execution. */
5947 if (!target_is_non_stop_p () || execution_direction == EXEC_REVERSE)
5948 return;
5949
5950 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
5951 instead of resuming all threads of each process individually.
5952 However, if any thread of a process must remain halted, we can't
5953 send wildcard resumes and must send one action per thread.
5954
5955 Care must be taken to not resume threads/processes the server
5956 side already told us are stopped, but the core doesn't know about
5957 yet, because the events are still in the vStopped notification
5958 queue. For example:
5959
5960 #1 => vCont s:p1.1;c
5961 #2 <= OK
5962 #3 <= %Stopped T05 p1.1
5963 #4 => vStopped
5964 #5 <= T05 p1.2
5965 #6 => vStopped
5966 #7 <= OK
5967 #8 (infrun handles the stop for p1.1 and continues stepping)
5968 #9 => vCont s:p1.1;c
5969
5970 The last vCont above would resume thread p1.2 by mistake, because
5971 the server has no idea that the event for p1.2 had not been
5972 handled yet.
5973
5974 The server side must similarly ignore resume actions for the
5975 thread that has a pending %Stopped notification (and any other
5976 threads with events pending), until GDB acks the notification
5977 with vStopped. Otherwise, e.g., the following case is
5978 mishandled:
5979
5980 #1 => g (or any other packet)
5981 #2 <= [registers]
5982 #3 <= %Stopped T05 p1.2
5983 #4 => vCont s:p1.1;c
5984 #5 <= OK
5985
5986 Above, the server must not resume thread p1.2. GDB can't know
5987 that p1.2 stopped until it acks the %Stopped notification, and
5988 since from GDB's perspective all threads should be running, it
5989 sends a "c" action.
5990
5991 Finally, special care must also be given to handling fork/vfork
5992 events. A (v)fork event actually tells us that two processes
5993 stopped -- the parent and the child. Until we follow the fork,
5994 we must not resume the child. Therefore, if we have a pending
5995 fork follow, we must not send a global wildcard resume action
5996 (vCont;c). We can still send process-wide wildcards though. */
5997
5998 /* Start by assuming a global wildcard (vCont;c) is possible. */
5999 may_global_wildcard_vcont = 1;
6000
6001 /* And assume every process is individually wildcard-able too. */
6002 ALL_NON_EXITED_INFERIORS (inf)
6003 {
6004 if (inf->priv == NULL)
6005 inf->priv = XNEW (struct private_inferior);
6006 inf->priv->may_wildcard_vcont = 1;
6007 }
6008
6009 /* Check for any pending events (not reported or processed yet) and
6010 disable process and global wildcard resumes appropriately. */
6011 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6012
6013 ALL_NON_EXITED_THREADS (tp)
6014 {
6015 /* If a thread of a process is not meant to be resumed, then we
6016 can't wildcard that process. */
6017 if (!tp->executing)
6018 {
6019 tp->inf->priv->may_wildcard_vcont = 0;
6020
6021 /* And if we can't wildcard a process, we can't wildcard
6022 everything either. */
6023 may_global_wildcard_vcont = 0;
6024 continue;
6025 }
6026
6027 /* If a thread is the parent of an unfollowed fork, then we
6028 can't do a global wildcard, as that would resume the fork
6029 child. */
6030 if (is_pending_fork_parent_thread (tp))
6031 may_global_wildcard_vcont = 0;
6032 }
6033
6034 /* Now let's build the vCont packet(s). Actions must be appended
6035 from narrower to wider scopes (thread -> process -> global). If
6036 we end up with too many actions for a single packet vcont_builder
6037 flushes the current vCont packet to the remote side and starts a
6038 new one. */
6039 vcont_builder_restart (&vcont_builder);
6040
6041 /* Threads first. */
6042 ALL_NON_EXITED_THREADS (tp)
6043 {
6044 struct private_thread_info *remote_thr = tp->priv;
6045
6046 if (!tp->executing || remote_thr->vcont_resumed)
6047 continue;
6048
6049 gdb_assert (!thread_is_in_step_over_chain (tp));
6050
6051 if (!remote_thr->last_resume_step
6052 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6053 && tp->inf->priv->may_wildcard_vcont)
6054 {
6055 /* We'll send a wildcard resume instead. */
6056 remote_thr->vcont_resumed = 1;
6057 continue;
6058 }
6059
6060 vcont_builder_push_action (&vcont_builder, tp->ptid,
6061 remote_thr->last_resume_step,
6062 remote_thr->last_resume_sig);
6063 remote_thr->vcont_resumed = 1;
6064 }
6065
6066 /* Now check whether we can send any process-wide wildcard. This is
6067 to avoid sending a global wildcard in the case nothing is
6068 supposed to be resumed. */
6069 any_process_wildcard = 0;
6070
6071 ALL_NON_EXITED_INFERIORS (inf)
6072 {
6073 if (inf->priv->may_wildcard_vcont)
6074 {
6075 any_process_wildcard = 1;
6076 break;
6077 }
6078 }
6079
6080 if (any_process_wildcard)
6081 {
6082 /* If all processes are wildcard-able, then send a single "c"
6083 action, otherwise, send an "all (-1) threads of process"
6084 continue action for each running process, if any. */
6085 if (may_global_wildcard_vcont)
6086 {
6087 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6088 0, GDB_SIGNAL_0);
6089 }
6090 else
6091 {
6092 ALL_NON_EXITED_INFERIORS (inf)
6093 {
6094 if (inf->priv->may_wildcard_vcont)
6095 {
6096 vcont_builder_push_action (&vcont_builder,
6097 pid_to_ptid (inf->pid),
6098 0, GDB_SIGNAL_0);
6099 }
6100 }
6101 }
6102 }
6103
6104 vcont_builder_flush (&vcont_builder);
6105}
6106
c906108c 6107\f
43ff13b4 6108
74531fed
PA
6109/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6110 thread, all threads of a remote process, or all threads of all
6111 processes. */
6112
6113static void
6114remote_stop_ns (ptid_t ptid)
6115{
6116 struct remote_state *rs = get_remote_state ();
6117 char *p = rs->buf;
6118 char *endp = rs->buf + get_remote_packet_size ();
74531fed 6119
4082afcc 6120 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
6121 remote_vcont_probe (rs);
6122
d458bd84 6123 if (!rs->supports_vCont.t)
74531fed
PA
6124 error (_("Remote server does not support stopping threads"));
6125
f91d3df5
PA
6126 if (ptid_equal (ptid, minus_one_ptid)
6127 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
6128 p += xsnprintf (p, endp - p, "vCont;t");
6129 else
6130 {
6131 ptid_t nptid;
6132
74531fed
PA
6133 p += xsnprintf (p, endp - p, "vCont;t:");
6134
6135 if (ptid_is_pid (ptid))
6136 /* All (-1) threads of process. */
ba348170 6137 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
6138 else
6139 {
6140 /* Small optimization: if we already have a stop reply for
6141 this thread, no use in telling the stub we want this
6142 stopped. */
6143 if (peek_stop_reply (ptid))
6144 return;
6145
6146 nptid = ptid;
6147 }
6148
a9cbf802 6149 write_ptid (p, endp, nptid);
74531fed
PA
6150 }
6151
6152 /* In non-stop, we get an immediate OK reply. The stop reply will
6153 come in asynchronously by notification. */
6154 putpkt (rs->buf);
6155 getpkt (&rs->buf, &rs->buf_size, 0);
6156 if (strcmp (rs->buf, "OK") != 0)
6157 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6158}
6159
bfedc46a
PA
6160/* All-stop version of target_interrupt. Sends a break or a ^C to
6161 interrupt the remote target. It is undefined which thread of which
6162 process reports the interrupt. */
74531fed
PA
6163
6164static void
de979965 6165remote_interrupt_as (void)
74531fed
PA
6166{
6167 struct remote_state *rs = get_remote_state ();
6168
3a29589a
DJ
6169 rs->ctrlc_pending_p = 1;
6170
74531fed
PA
6171 /* If the inferior is stopped already, but the core didn't know
6172 about it yet, just ignore the request. The cached wait status
6173 will be collected in remote_wait. */
6174 if (rs->cached_wait_status)
6175 return;
6176
9a7071a8
JB
6177 /* Send interrupt_sequence to remote target. */
6178 send_interrupt_sequence ();
74531fed
PA
6179}
6180
de979965
PA
6181/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6182 the remote target. It is undefined which thread of which process
e42de8c7
PA
6183 reports the interrupt. Throws an error if the packet is not
6184 supported by the server. */
de979965 6185
e42de8c7 6186static void
de979965
PA
6187remote_interrupt_ns (void)
6188{
6189 struct remote_state *rs = get_remote_state ();
6190 char *p = rs->buf;
6191 char *endp = rs->buf + get_remote_packet_size ();
6192
6193 xsnprintf (p, endp - p, "vCtrlC");
6194
6195 /* In non-stop, we get an immediate OK reply. The stop reply will
6196 come in asynchronously by notification. */
6197 putpkt (rs->buf);
6198 getpkt (&rs->buf, &rs->buf_size, 0);
6199
6200 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6201 {
6202 case PACKET_OK:
6203 break;
6204 case PACKET_UNKNOWN:
e42de8c7 6205 error (_("No support for interrupting the remote target."));
de979965
PA
6206 case PACKET_ERROR:
6207 error (_("Interrupting target failed: %s"), rs->buf);
6208 }
de979965
PA
6209}
6210
bfedc46a 6211/* Implement the to_stop function for the remote targets. */
74531fed 6212
c906108c 6213static void
1eab8a48 6214remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 6215{
7a292a7a 6216 if (remote_debug)
0f71a2f6 6217 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6218
6efcd9a8 6219 if (target_is_non_stop_p ())
74531fed 6220 remote_stop_ns (ptid);
c906108c 6221 else
bfedc46a
PA
6222 {
6223 /* We don't currently have a way to transparently pause the
6224 remote target in all-stop mode. Interrupt it instead. */
de979965 6225 remote_interrupt_as ();
bfedc46a
PA
6226 }
6227}
6228
6229/* Implement the to_interrupt function for the remote targets. */
6230
6231static void
6232remote_interrupt (struct target_ops *self, ptid_t ptid)
6233{
e42de8c7
PA
6234 struct remote_state *rs = get_remote_state ();
6235
bfedc46a
PA
6236 if (remote_debug)
6237 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6238
e42de8c7
PA
6239 if (target_is_non_stop_p ())
6240 remote_interrupt_ns ();
bfedc46a 6241 else
e42de8c7 6242 remote_interrupt_as ();
c906108c
SS
6243}
6244
93692b58
PA
6245/* Implement the to_pass_ctrlc function for the remote targets. */
6246
6247static void
6248remote_pass_ctrlc (struct target_ops *self)
6249{
6250 struct remote_state *rs = get_remote_state ();
6251
6252 if (remote_debug)
6253 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6254
6255 /* If we're starting up, we're not fully synced yet. Quit
6256 immediately. */
6257 if (rs->starting_up)
6258 quit ();
6259 /* If ^C has already been sent once, offer to disconnect. */
6260 else if (rs->ctrlc_pending_p)
6261 interrupt_query ();
6262 else
6263 target_interrupt (inferior_ptid);
6264}
6265
c906108c
SS
6266/* Ask the user what to do when an interrupt is received. */
6267
6268static void
fba45db2 6269interrupt_query (void)
c906108c 6270{
abc56d60 6271 struct remote_state *rs = get_remote_state ();
c906108c 6272
abc56d60 6273 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6274 {
abc56d60
PA
6275 if (query (_("The target is not responding to interrupt requests.\n"
6276 "Stop debugging it? ")))
74531fed 6277 {
78a095c3 6278 remote_unpush_target ();
abc56d60 6279 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6280 }
6281 }
abc56d60
PA
6282 else
6283 {
6284 if (query (_("Interrupted while waiting for the program.\n"
6285 "Give up waiting? ")))
6286 quit ();
6287 }
c906108c
SS
6288}
6289
6426a772
JM
6290/* Enable/disable target terminal ownership. Most targets can use
6291 terminal groups to control terminal ownership. Remote targets are
6292 different in that explicit transfer of ownership to/from GDB/target
23860348 6293 is required. */
6426a772
JM
6294
6295static void
d2f640d4 6296remote_terminal_inferior (struct target_ops *self)
6426a772 6297{
6426a772
JM
6298 /* NOTE: At this point we could also register our selves as the
6299 recipient of all input. Any characters typed could then be
23860348 6300 passed on down to the target. */
6426a772
JM
6301}
6302
6303static void
e3594fd1 6304remote_terminal_ours (struct target_ops *self)
6426a772 6305{
6426a772
JM
6306}
6307
176a6961 6308static void
917317f4 6309remote_console_output (char *msg)
c906108c
SS
6310{
6311 char *p;
6312
c5aa993b 6313 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6314 {
6315 char tb[2];
6316 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6317
c906108c
SS
6318 tb[0] = c;
6319 tb[1] = 0;
43ff13b4 6320 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6321 }
00db5b94
PA
6322 gdb_flush (gdb_stdtarg);
6323}
74531fed 6324
74531fed
PA
6325DEF_VEC_O(cached_reg_t);
6326
722247f1 6327typedef struct stop_reply
74531fed 6328{
722247f1 6329 struct notif_event base;
74531fed 6330
722247f1 6331 /* The identifier of the thread about this event */
74531fed
PA
6332 ptid_t ptid;
6333
340e3c99 6334 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6335 connection, represented by a remote_state object, is closed,
6336 all the associated stop_reply events should be released. */
6337 struct remote_state *rs;
6338
74531fed
PA
6339 struct target_waitstatus ws;
6340
5cd63fda
PA
6341 /* The architecture associated with the expedited registers. */
6342 gdbarch *arch;
6343
15148d6a
PA
6344 /* Expedited registers. This makes remote debugging a bit more
6345 efficient for those targets that provide critical registers as
6346 part of their normal status mechanism (as another roundtrip to
6347 fetch them is avoided). */
74531fed
PA
6348 VEC(cached_reg_t) *regcache;
6349
f7e6eed5
PA
6350 enum target_stop_reason stop_reason;
6351
74531fed
PA
6352 CORE_ADDR watch_data_address;
6353
dc146f7c 6354 int core;
722247f1 6355} *stop_reply_p;
a744cf53 6356
722247f1
YQ
6357DECLARE_QUEUE_P (stop_reply_p);
6358DEFINE_QUEUE_P (stop_reply_p);
6359/* The list of already fetched and acknowledged stop events. This
6360 queue is used for notification Stop, and other notifications
6361 don't need queue for their events, because the notification events
6362 of Stop can't be consumed immediately, so that events should be
6363 queued first, and be consumed by remote_wait_{ns,as} one per
6364 time. Other notifications can consume their events immediately,
6365 so queue is not needed for them. */
6366static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
6367
6368static void
6369stop_reply_xfree (struct stop_reply *r)
6370{
f48ff2a7 6371 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6372}
6373
221e1a37
PA
6374/* Return the length of the stop reply queue. */
6375
6376static int
6377stop_reply_queue_length (void)
6378{
6379 return QUEUE_length (stop_reply_p, stop_reply_queue);
6380}
6381
722247f1
YQ
6382static void
6383remote_notif_stop_parse (struct notif_client *self, char *buf,
6384 struct notif_event *event)
6385{
6386 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6387}
6388
6389static void
6390remote_notif_stop_ack (struct notif_client *self, char *buf,
6391 struct notif_event *event)
6392{
6393 struct stop_reply *stop_reply = (struct stop_reply *) event;
6394
6395 /* acknowledge */
f5c4fcd9 6396 putpkt (self->ack_command);
722247f1
YQ
6397
6398 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6399 /* We got an unknown stop reply. */
6400 error (_("Unknown stop reply"));
6401
6402 push_stop_reply (stop_reply);
6403}
6404
6405static int
6406remote_notif_stop_can_get_pending_events (struct notif_client *self)
6407{
6408 /* We can't get pending events in remote_notif_process for
6409 notification stop, and we have to do this in remote_wait_ns
6410 instead. If we fetch all queued events from stub, remote stub
6411 may exit and we have no chance to process them back in
6412 remote_wait_ns. */
6413 mark_async_event_handler (remote_async_inferior_event_token);
6414 return 0;
6415}
6416
6417static void
6418stop_reply_dtr (struct notif_event *event)
6419{
6420 struct stop_reply *r = (struct stop_reply *) event;
d1dff226
AH
6421 cached_reg_t *reg;
6422 int ix;
6423
6424 for (ix = 0;
6425 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6426 ix++)
6427 xfree (reg->data);
722247f1
YQ
6428
6429 VEC_free (cached_reg_t, r->regcache);
6430}
6431
6432static struct notif_event *
6433remote_notif_stop_alloc_reply (void)
6434{
8d749320
SM
6435 /* We cast to a pointer to the "base class". */
6436 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6437
6438 r->dtr = stop_reply_dtr;
6439
6440 return r;
6441}
6442
6443/* A client of notification Stop. */
6444
6445struct notif_client notif_client_stop =
6446{
6447 "Stop",
6448 "vStopped",
6449 remote_notif_stop_parse,
6450 remote_notif_stop_ack,
6451 remote_notif_stop_can_get_pending_events,
6452 remote_notif_stop_alloc_reply,
f48ff2a7 6453 REMOTE_NOTIF_STOP,
722247f1
YQ
6454};
6455
6456/* A parameter to pass data in and out. */
6457
6458struct queue_iter_param
6459{
6460 void *input;
6461 struct stop_reply *output;
6462};
6463
85ad3aaf 6464/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6465 the pid of the process that owns the threads we want to check, or
6466 -1 if we want to check all threads. */
6467
6468static int
6469is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6470 ptid_t thread_ptid)
6471{
6472 if (ws->kind == TARGET_WAITKIND_FORKED
6473 || ws->kind == TARGET_WAITKIND_VFORKED)
6474 {
6475 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6476 return 1;
6477 }
6478
6479 return 0;
6480}
6481
85ad3aaf
PA
6482/* Return the thread's pending status used to determine whether the
6483 thread is a fork parent stopped at a fork event. */
6484
6485static struct target_waitstatus *
6486thread_pending_fork_status (struct thread_info *thread)
6487{
6488 if (thread->suspend.waitstatus_pending_p)
6489 return &thread->suspend.waitstatus;
6490 else
6491 return &thread->pending_follow;
6492}
6493
6494/* Determine if THREAD is a pending fork parent thread. */
6495
6496static int
6497is_pending_fork_parent_thread (struct thread_info *thread)
6498{
6499 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6500 int pid = -1;
6501
6502 return is_pending_fork_parent (ws, pid, thread->ptid);
6503}
6504
cbb8991c
DB
6505/* Check whether EVENT is a fork event, and if it is, remove the
6506 fork child from the context list passed in DATA. */
6507
6508static int
6509remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6510 QUEUE_ITER (stop_reply_p) *iter,
6511 stop_reply_p event,
6512 void *data)
6513{
19ba03f4
SM
6514 struct queue_iter_param *param = (struct queue_iter_param *) data;
6515 struct threads_listing_context *context
6516 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6517
6518 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6519 || event->ws.kind == TARGET_WAITKIND_VFORKED
6520 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6521 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6522
6523 return 1;
6524}
6525
6526/* If CONTEXT contains any fork child threads that have not been
6527 reported yet, remove them from the CONTEXT list. If such a
6528 thread exists it is because we are stopped at a fork catchpoint
6529 and have not yet called follow_fork, which will set up the
6530 host-side data structures for the new process. */
6531
6532static void
6533remove_new_fork_children (struct threads_listing_context *context)
6534{
6535 struct thread_info * thread;
6536 int pid = -1;
6537 struct notif_client *notif = &notif_client_stop;
6538 struct queue_iter_param param;
6539
6540 /* For any threads stopped at a fork event, remove the corresponding
6541 fork child threads from the CONTEXT list. */
6542 ALL_NON_EXITED_THREADS (thread)
6543 {
85ad3aaf 6544 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
6545
6546 if (is_pending_fork_parent (ws, pid, thread->ptid))
6547 {
6548 threads_listing_context_remove (ws, context);
6549 }
6550 }
6551
6552 /* Check for any pending fork events (not reported or processed yet)
6553 in process PID and remove those fork child threads from the
6554 CONTEXT list as well. */
6555 remote_notif_get_pending_events (notif);
6556 param.input = context;
6557 param.output = NULL;
6558 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6559 remove_child_of_pending_fork, &param);
6560}
6561
85ad3aaf
PA
6562/* Check whether EVENT would prevent a global or process wildcard
6563 vCont action. */
6564
6565static int
6566check_pending_event_prevents_wildcard_vcont_callback
6567 (QUEUE (stop_reply_p) *q,
6568 QUEUE_ITER (stop_reply_p) *iter,
6569 stop_reply_p event,
6570 void *data)
6571{
6572 struct inferior *inf;
6573 int *may_global_wildcard_vcont = (int *) data;
6574
6575 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6576 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6577 return 1;
6578
6579 if (event->ws.kind == TARGET_WAITKIND_FORKED
6580 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6581 *may_global_wildcard_vcont = 0;
6582
6583 inf = find_inferior_ptid (event->ptid);
6584
6585 /* This may be the first time we heard about this process.
6586 Regardless, we must not do a global wildcard resume, otherwise
6587 we'd resume this process too. */
6588 *may_global_wildcard_vcont = 0;
6589 if (inf != NULL)
6590 inf->priv->may_wildcard_vcont = 0;
6591
6592 return 1;
6593}
6594
6595/* Check whether any event pending in the vStopped queue would prevent
6596 a global or process wildcard vCont action. Clear
6597 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6598 and clear the event inferior's may_wildcard_vcont flag if we can't
6599 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6600
6601static void
6602check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6603{
6604 struct notif_client *notif = &notif_client_stop;
6605
6606 remote_notif_get_pending_events (notif);
6607 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6608 check_pending_event_prevents_wildcard_vcont_callback,
6609 may_global_wildcard);
6610}
6611
f48ff2a7
YQ
6612/* Remove stop replies in the queue if its pid is equal to the given
6613 inferior's pid. */
722247f1
YQ
6614
6615static int
f48ff2a7
YQ
6616remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6617 QUEUE_ITER (stop_reply_p) *iter,
6618 stop_reply_p event,
6619 void *data)
722247f1 6620{
19ba03f4
SM
6621 struct queue_iter_param *param = (struct queue_iter_param *) data;
6622 struct inferior *inf = (struct inferior *) param->input;
722247f1 6623
f48ff2a7 6624 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6625 {
6626 stop_reply_xfree (event);
6627 QUEUE_remove_elem (stop_reply_p, q, iter);
6628 }
6629
6630 return 1;
6631}
6632
f48ff2a7 6633/* Discard all pending stop replies of inferior INF. */
c906108c 6634
74531fed 6635static void
5f4cf0bb 6636discard_pending_stop_replies (struct inferior *inf)
c906108c 6637{
722247f1 6638 struct queue_iter_param param;
f48ff2a7
YQ
6639 struct stop_reply *reply;
6640 struct remote_state *rs = get_remote_state ();
6641 struct remote_notif_state *rns = rs->notif_state;
6642
6643 /* This function can be notified when an inferior exists. When the
6644 target is not remote, the notification state is NULL. */
6645 if (rs->remote_desc == NULL)
6646 return;
6647
6648 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6649
74531fed 6650 /* Discard the in-flight notification. */
f48ff2a7 6651 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6652 {
722247f1 6653 stop_reply_xfree (reply);
f48ff2a7 6654 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6655 }
c906108c 6656
722247f1
YQ
6657 param.input = inf;
6658 param.output = NULL;
74531fed
PA
6659 /* Discard the stop replies we have already pulled with
6660 vStopped. */
722247f1 6661 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6662 remove_stop_reply_for_inferior, &param);
6663}
6664
bcc75809
YQ
6665/* If its remote state is equal to the given remote state,
6666 remove EVENT from the stop reply queue. */
6667
6668static int
6669remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6670 QUEUE_ITER (stop_reply_p) *iter,
6671 stop_reply_p event,
6672 void *data)
6673{
19ba03f4
SM
6674 struct queue_iter_param *param = (struct queue_iter_param *) data;
6675 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6676
6677 if (event->rs == rs)
6678 {
6679 stop_reply_xfree (event);
6680 QUEUE_remove_elem (stop_reply_p, q, iter);
6681 }
6682
6683 return 1;
6684}
6685
6686/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6687
6688static void
bcc75809 6689discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6690{
6691 struct queue_iter_param param;
6692
bcc75809 6693 param.input = rs;
f48ff2a7
YQ
6694 param.output = NULL;
6695 /* Discard the stop replies we have already pulled with
6696 vStopped. */
6697 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6698 remove_stop_reply_of_remote_state, &param);
722247f1 6699}
74531fed 6700
722247f1
YQ
6701/* A parameter to pass data in and out. */
6702
6703static int
6704remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6705 QUEUE_ITER (stop_reply_p) *iter,
6706 stop_reply_p event,
6707 void *data)
6708{
19ba03f4
SM
6709 struct queue_iter_param *param = (struct queue_iter_param *) data;
6710 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6711
6712 if (ptid_match (event->ptid, *ptid))
6713 {
6714 param->output = event;
6715 QUEUE_remove_elem (stop_reply_p, q, iter);
6716 return 0;
c8e38a49 6717 }
722247f1
YQ
6718
6719 return 1;
74531fed 6720}
43ff13b4 6721
722247f1
YQ
6722/* Remove the first reply in 'stop_reply_queue' which matches
6723 PTID. */
2e9f7625 6724
722247f1
YQ
6725static struct stop_reply *
6726remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6727{
722247f1
YQ
6728 struct queue_iter_param param;
6729
6730 param.input = &ptid;
6731 param.output = NULL;
6732
6733 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6734 remote_notif_remove_once_on_match, &param);
6735 if (notif_debug)
6736 fprintf_unfiltered (gdb_stdlog,
6737 "notif: discard queued event: 'Stop' in %s\n",
6738 target_pid_to_str (ptid));
a744cf53 6739
722247f1 6740 return param.output;
74531fed 6741}
75c99385 6742
74531fed
PA
6743/* Look for a queued stop reply belonging to PTID. If one is found,
6744 remove it from the queue, and return it. Returns NULL if none is
6745 found. If there are still queued events left to process, tell the
6746 event loop to get back to target_wait soon. */
e24a49d8 6747
74531fed
PA
6748static struct stop_reply *
6749queued_stop_reply (ptid_t ptid)
6750{
722247f1 6751 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6752
722247f1 6753 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6754 /* There's still at least an event left. */
6755 mark_async_event_handler (remote_async_inferior_event_token);
6756
722247f1 6757 return r;
74531fed
PA
6758}
6759
6760/* Push a fully parsed stop reply in the stop reply queue. Since we
6761 know that we now have at least one queued event left to pass to the
6762 core side, tell the event loop to get back to target_wait soon. */
6763
6764static void
6765push_stop_reply (struct stop_reply *new_event)
6766{
722247f1 6767 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6768
722247f1
YQ
6769 if (notif_debug)
6770 fprintf_unfiltered (gdb_stdlog,
6771 "notif: push 'Stop' %s to queue %d\n",
6772 target_pid_to_str (new_event->ptid),
6773 QUEUE_length (stop_reply_p,
6774 stop_reply_queue));
74531fed
PA
6775
6776 mark_async_event_handler (remote_async_inferior_event_token);
6777}
6778
722247f1
YQ
6779static int
6780stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6781 QUEUE_ITER (stop_reply_p) *iter,
6782 struct stop_reply *event,
6783 void *data)
6784{
19ba03f4 6785 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6786
6787 return !(ptid_equal (*ptid, event->ptid)
6788 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6789}
6790
74531fed
PA
6791/* Returns true if we have a stop reply for PTID. */
6792
6793static int
6794peek_stop_reply (ptid_t ptid)
6795{
722247f1
YQ
6796 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6797 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6798}
6799
26d56a93
SL
6800/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6801 starting with P and ending with PEND matches PREFIX. */
6802
6803static int
6804strprefix (const char *p, const char *pend, const char *prefix)
6805{
6806 for ( ; p < pend; p++, prefix++)
6807 if (*p != *prefix)
6808 return 0;
6809 return *prefix == '\0';
6810}
6811
74531fed
PA
6812/* Parse the stop reply in BUF. Either the function succeeds, and the
6813 result is stored in EVENT, or throws an error. */
6814
6815static void
6816remote_parse_stop_reply (char *buf, struct stop_reply *event)
6817{
5cd63fda 6818 remote_arch_state *rsa = NULL;
74531fed 6819 ULONGEST addr;
256642e8 6820 const char *p;
94585166 6821 int skipregs = 0;
74531fed
PA
6822
6823 event->ptid = null_ptid;
bcc75809 6824 event->rs = get_remote_state ();
74531fed
PA
6825 event->ws.kind = TARGET_WAITKIND_IGNORE;
6826 event->ws.value.integer = 0;
f7e6eed5 6827 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6828 event->regcache = NULL;
dc146f7c 6829 event->core = -1;
74531fed
PA
6830
6831 switch (buf[0])
6832 {
6833 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6834 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6835 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6836 ss = signal number
6837 n... = register number
6838 r... = register contents
6839 */
6840
6841 p = &buf[3]; /* after Txx */
6842 while (*p)
6843 {
256642e8 6844 const char *p1;
cea39f65 6845 int fieldsize;
43ff13b4 6846
1f10ba14
PA
6847 p1 = strchr (p, ':');
6848 if (p1 == NULL)
6849 error (_("Malformed packet(a) (missing colon): %s\n\
6850Packet: '%s'\n"),
6851 p, buf);
6852 if (p == p1)
6853 error (_("Malformed packet(a) (missing register number): %s\n\
6854Packet: '%s'\n"),
6855 p, buf);
3c3bea1c 6856
1f10ba14
PA
6857 /* Some "registers" are actually extended stop information.
6858 Note if you're adding a new entry here: GDB 7.9 and
6859 earlier assume that all register "numbers" that start
6860 with an hex digit are real register numbers. Make sure
6861 the server only sends such a packet if it knows the
6862 client understands it. */
c8e38a49 6863
26d56a93 6864 if (strprefix (p, p1, "thread"))
1f10ba14 6865 event->ptid = read_ptid (++p1, &p);
82075af2
JS
6866 else if (strprefix (p, p1, "syscall_entry"))
6867 {
6868 ULONGEST sysno;
6869
6870 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6871 p = unpack_varlen_hex (++p1, &sysno);
6872 event->ws.value.syscall_number = (int) sysno;
6873 }
6874 else if (strprefix (p, p1, "syscall_return"))
6875 {
6876 ULONGEST sysno;
6877
6878 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6879 p = unpack_varlen_hex (++p1, &sysno);
6880 event->ws.value.syscall_number = (int) sysno;
6881 }
26d56a93
SL
6882 else if (strprefix (p, p1, "watch")
6883 || strprefix (p, p1, "rwatch")
6884 || strprefix (p, p1, "awatch"))
cea39f65 6885 {
f7e6eed5 6886 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6887 p = unpack_varlen_hex (++p1, &addr);
6888 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6889 }
26d56a93 6890 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6891 {
6892 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6893
6894 /* Make sure the stub doesn't forget to indicate support
6895 with qSupported. */
6896 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6897 error (_("Unexpected swbreak stop reason"));
6898
6899 /* The value part is documented as "must be empty",
6900 though we ignore it, in case we ever decide to make
6901 use of it in a backward compatible way. */
8424cc97 6902 p = strchrnul (p1 + 1, ';');
f7e6eed5 6903 }
26d56a93 6904 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6905 {
6906 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6907
6908 /* Make sure the stub doesn't forget to indicate support
6909 with qSupported. */
6910 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6911 error (_("Unexpected hwbreak stop reason"));
6912
6913 /* See above. */
8424cc97 6914 p = strchrnul (p1 + 1, ';');
f7e6eed5 6915 }
26d56a93 6916 else if (strprefix (p, p1, "library"))
cea39f65 6917 {
1f10ba14 6918 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 6919 p = strchrnul (p1 + 1, ';');
1f10ba14 6920 }
26d56a93 6921 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6922 {
6923 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6924 /* p1 will indicate "begin" or "end", but it makes
6925 no difference for now, so ignore it. */
8424cc97 6926 p = strchrnul (p1 + 1, ';');
1f10ba14 6927 }
26d56a93 6928 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6929 {
6930 ULONGEST c;
a744cf53 6931
1f10ba14
PA
6932 p = unpack_varlen_hex (++p1, &c);
6933 event->core = c;
cea39f65 6934 }
26d56a93 6935 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6936 {
6937 event->ws.value.related_pid = read_ptid (++p1, &p);
6938 event->ws.kind = TARGET_WAITKIND_FORKED;
6939 }
26d56a93 6940 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6941 {
6942 event->ws.value.related_pid = read_ptid (++p1, &p);
6943 event->ws.kind = TARGET_WAITKIND_VFORKED;
6944 }
26d56a93 6945 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6946 {
6947 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 6948 p = strchrnul (p1 + 1, ';');
c269dbdb 6949 }
6ab24463 6950 else if (strprefix (p, p1, "exec"))
94585166
DB
6951 {
6952 ULONGEST ignored;
6953 char pathname[PATH_MAX];
6954 int pathlen;
6955
6956 /* Determine the length of the execd pathname. */
6957 p = unpack_varlen_hex (++p1, &ignored);
6958 pathlen = (p - p1) / 2;
6959
6960 /* Save the pathname for event reporting and for
6961 the next run command. */
6962 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6963 pathname[pathlen] = '\0';
6964
6965 /* This is freed during event handling. */
6966 event->ws.value.execd_pathname = xstrdup (pathname);
6967 event->ws.kind = TARGET_WAITKIND_EXECD;
6968
6969 /* Skip the registers included in this packet, since
6970 they may be for an architecture different from the
6971 one used by the original program. */
6972 skipregs = 1;
6973 }
65706a29
PA
6974 else if (strprefix (p, p1, "create"))
6975 {
6976 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 6977 p = strchrnul (p1 + 1, ';');
65706a29 6978 }
cea39f65
MS
6979 else
6980 {
1f10ba14 6981 ULONGEST pnum;
256642e8 6982 const char *p_temp;
1f10ba14 6983
94585166
DB
6984 if (skipregs)
6985 {
8424cc97 6986 p = strchrnul (p1 + 1, ';');
94585166
DB
6987 p++;
6988 continue;
6989 }
6990
1f10ba14
PA
6991 /* Maybe a real ``P'' register number. */
6992 p_temp = unpack_varlen_hex (p, &pnum);
6993 /* If the first invalid character is the colon, we got a
6994 register number. Otherwise, it's an unknown stop
6995 reason. */
6996 if (p_temp == p1)
6997 {
5cd63fda
PA
6998 /* If we haven't parsed the event's thread yet, find
6999 it now, in order to find the architecture of the
7000 reported expedited registers. */
7001 if (event->ptid == null_ptid)
7002 {
7003 const char *thr = strstr (p1 + 1, ";thread:");
7004 if (thr != NULL)
7005 event->ptid = read_ptid (thr + strlen (";thread:"),
7006 NULL);
7007 else
7008 event->ptid = magic_null_ptid;
7009 }
7010
7011 if (rsa == NULL)
7012 {
7013 inferior *inf = (event->ptid == null_ptid
7014 ? NULL
7015 : find_inferior_ptid (event->ptid));
7016 /* If this is the first time we learn anything
7017 about this process, skip the registers
7018 included in this packet, since we don't yet
7019 know which architecture to use to parse them.
7020 We'll determine the architecture later when
7021 we process the stop reply and retrieve the
7022 target description, via
7023 remote_notice_new_inferior ->
7024 post_create_inferior. */
7025 if (inf == NULL)
7026 {
7027 p = strchrnul (p1 + 1, ';');
7028 p++;
7029 continue;
7030 }
7031
7032 event->arch = inf->gdbarch;
7033 rsa = get_remote_arch_state (event->arch);
7034 }
7035
7036 packet_reg *reg
7037 = packet_reg_from_pnum (event->arch, rsa, pnum);
1f10ba14 7038 cached_reg_t cached_reg;
43ff13b4 7039
1f10ba14
PA
7040 if (reg == NULL)
7041 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7042Packet: '%s'\n"),
1f10ba14 7043 hex_string (pnum), p, buf);
c8e38a49 7044
1f10ba14 7045 cached_reg.num = reg->regnum;
d1dff226 7046 cached_reg.data = (gdb_byte *)
5cd63fda 7047 xmalloc (register_size (event->arch, reg->regnum));
4100683b 7048
1f10ba14
PA
7049 p = p1 + 1;
7050 fieldsize = hex2bin (p, cached_reg.data,
5cd63fda 7051 register_size (event->arch, reg->regnum));
1f10ba14 7052 p += 2 * fieldsize;
5cd63fda 7053 if (fieldsize < register_size (event->arch, reg->regnum))
1f10ba14 7054 warning (_("Remote reply is too short: %s"), buf);
74531fed 7055
1f10ba14
PA
7056 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7057 }
7058 else
7059 {
7060 /* Not a number. Silently skip unknown optional
7061 info. */
8424cc97 7062 p = strchrnul (p1 + 1, ';');
1f10ba14 7063 }
cea39f65 7064 }
c8e38a49 7065
cea39f65
MS
7066 if (*p != ';')
7067 error (_("Remote register badly formatted: %s\nhere: %s"),
7068 buf, p);
7069 ++p;
7070 }
5b5596ff
PA
7071
7072 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7073 break;
7074
c8e38a49
PA
7075 /* fall through */
7076 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7077 {
7078 int sig;
7079
7080 event->ws.kind = TARGET_WAITKIND_STOPPED;
7081 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7082 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7083 event->ws.value.sig = (enum gdb_signal) sig;
7084 else
7085 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7086 }
c8e38a49 7087 break;
65706a29
PA
7088 case 'w': /* Thread exited. */
7089 {
256642e8 7090 const char *p;
65706a29
PA
7091 ULONGEST value;
7092
7093 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7094 p = unpack_varlen_hex (&buf[1], &value);
7095 event->ws.value.integer = value;
7096 if (*p != ';')
7097 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7098 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7099 break;
7100 }
c8e38a49
PA
7101 case 'W': /* Target exited. */
7102 case 'X':
7103 {
256642e8 7104 const char *p;
c8e38a49
PA
7105 int pid;
7106 ULONGEST value;
82f73884 7107
c8e38a49
PA
7108 /* GDB used to accept only 2 hex chars here. Stubs should
7109 only send more if they detect GDB supports multi-process
7110 support. */
7111 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7112
c8e38a49
PA
7113 if (buf[0] == 'W')
7114 {
7115 /* The remote process exited. */
74531fed
PA
7116 event->ws.kind = TARGET_WAITKIND_EXITED;
7117 event->ws.value.integer = value;
c8e38a49
PA
7118 }
7119 else
7120 {
7121 /* The remote process exited with a signal. */
74531fed 7122 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7123 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7124 event->ws.value.sig = (enum gdb_signal) value;
7125 else
7126 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7127 }
82f73884 7128
c8e38a49
PA
7129 /* If no process is specified, assume inferior_ptid. */
7130 pid = ptid_get_pid (inferior_ptid);
7131 if (*p == '\0')
7132 ;
7133 else if (*p == ';')
7134 {
7135 p++;
7136
0b24eb2d 7137 if (*p == '\0')
82f73884 7138 ;
61012eef 7139 else if (startswith (p, "process:"))
82f73884 7140 {
c8e38a49 7141 ULONGEST upid;
a744cf53 7142
c8e38a49
PA
7143 p += sizeof ("process:") - 1;
7144 unpack_varlen_hex (p, &upid);
7145 pid = upid;
82f73884
PA
7146 }
7147 else
7148 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7149 }
c8e38a49
PA
7150 else
7151 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
7152 event->ptid = pid_to_ptid (pid);
7153 }
7154 break;
f2faf941
PA
7155 case 'N':
7156 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7157 event->ptid = minus_one_ptid;
7158 break;
74531fed
PA
7159 }
7160
6efcd9a8 7161 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
7162 error (_("No process or thread specified in stop reply: %s"), buf);
7163}
7164
722247f1
YQ
7165/* When the stub wants to tell GDB about a new notification reply, it
7166 sends a notification (%Stop, for example). Those can come it at
7167 any time, hence, we have to make sure that any pending
7168 putpkt/getpkt sequence we're making is finished, before querying
7169 the stub for more events with the corresponding ack command
7170 (vStopped, for example). E.g., if we started a vStopped sequence
7171 immediately upon receiving the notification, something like this
7172 could happen:
74531fed
PA
7173
7174 1.1) --> Hg 1
7175 1.2) <-- OK
7176 1.3) --> g
7177 1.4) <-- %Stop
7178 1.5) --> vStopped
7179 1.6) <-- (registers reply to step #1.3)
7180
7181 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7182 query.
7183
796cb314 7184 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7185 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7186 doing whatever we were doing:
7187
7188 2.1) --> Hg 1
7189 2.2) <-- OK
7190 2.3) --> g
7191 2.4) <-- %Stop
7192 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7193 2.5) <-- (registers reply to step #2.3)
7194
7195 Eventualy after step #2.5, we return to the event loop, which
7196 notices there's an event on the
7197 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7198 associated callback --- the function below. At this point, we're
7199 always safe to start a vStopped sequence. :
7200
7201 2.6) --> vStopped
7202 2.7) <-- T05 thread:2
7203 2.8) --> vStopped
7204 2.9) --> OK
7205*/
7206
722247f1
YQ
7207void
7208remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
7209{
7210 struct remote_state *rs = get_remote_state ();
74531fed 7211
f48ff2a7 7212 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7213 {
722247f1
YQ
7214 if (notif_debug)
7215 fprintf_unfiltered (gdb_stdlog,
7216 "notif: process: '%s' ack pending event\n",
7217 nc->name);
74531fed 7218
722247f1 7219 /* acknowledge */
f48ff2a7
YQ
7220 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7221 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7222
7223 while (1)
7224 {
7225 getpkt (&rs->buf, &rs->buf_size, 0);
7226 if (strcmp (rs->buf, "OK") == 0)
7227 break;
7228 else
722247f1 7229 remote_notif_ack (nc, rs->buf);
74531fed
PA
7230 }
7231 }
722247f1
YQ
7232 else
7233 {
7234 if (notif_debug)
7235 fprintf_unfiltered (gdb_stdlog,
7236 "notif: process: '%s' no pending reply\n",
7237 nc->name);
7238 }
74531fed
PA
7239}
7240
74531fed
PA
7241/* Called when it is decided that STOP_REPLY holds the info of the
7242 event that is to be returned to the core. This function always
7243 destroys STOP_REPLY. */
7244
7245static ptid_t
7246process_stop_reply (struct stop_reply *stop_reply,
7247 struct target_waitstatus *status)
7248{
7249 ptid_t ptid;
7250
7251 *status = stop_reply->ws;
7252 ptid = stop_reply->ptid;
7253
7254 /* If no thread/process was reported by the stub, assume the current
7255 inferior. */
7256 if (ptid_equal (ptid, null_ptid))
7257 ptid = inferior_ptid;
7258
5f3563ea 7259 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7260 && status->kind != TARGET_WAITKIND_SIGNALLED
7261 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7262 {
799a2abe 7263 struct private_thread_info *remote_thr;
ee154bee 7264
5f3563ea
PA
7265 /* Expedited registers. */
7266 if (stop_reply->regcache)
7267 {
217f1f79 7268 struct regcache *regcache
5cd63fda 7269 = get_thread_arch_regcache (ptid, stop_reply->arch);
5f3563ea
PA
7270 cached_reg_t *reg;
7271 int ix;
7272
7273 for (ix = 0;
d1dff226 7274 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
5f3563ea 7275 ix++)
d1dff226 7276 {
217f1f79 7277 regcache_raw_supply (regcache, reg->num, reg->data);
d1dff226
AH
7278 xfree (reg->data);
7279 }
7280
5f3563ea
PA
7281 VEC_free (cached_reg_t, stop_reply->regcache);
7282 }
74531fed 7283
1941c569 7284 remote_notice_new_inferior (ptid, 0);
85ad3aaf 7285 remote_thr = get_private_info_ptid (ptid);
799a2abe
PA
7286 remote_thr->core = stop_reply->core;
7287 remote_thr->stop_reason = stop_reply->stop_reason;
7288 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7289 remote_thr->vcont_resumed = 0;
74531fed
PA
7290 }
7291
74531fed
PA
7292 stop_reply_xfree (stop_reply);
7293 return ptid;
7294}
7295
7296/* The non-stop mode version of target_wait. */
7297
7298static ptid_t
47608cb1 7299remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7300{
7301 struct remote_state *rs = get_remote_state ();
74531fed
PA
7302 struct stop_reply *stop_reply;
7303 int ret;
fee9eda9 7304 int is_notif = 0;
74531fed
PA
7305
7306 /* If in non-stop mode, get out of getpkt even if a
7307 notification is received. */
7308
7309 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7310 0 /* forever */, &is_notif);
74531fed
PA
7311 while (1)
7312 {
fee9eda9 7313 if (ret != -1 && !is_notif)
74531fed
PA
7314 switch (rs->buf[0])
7315 {
7316 case 'E': /* Error of some sort. */
7317 /* We're out of sync with the target now. Did it continue
7318 or not? We can't tell which thread it was in non-stop,
7319 so just ignore this. */
7320 warning (_("Remote failure reply: %s"), rs->buf);
7321 break;
7322 case 'O': /* Console output. */
7323 remote_console_output (rs->buf + 1);
7324 break;
7325 default:
7326 warning (_("Invalid remote reply: %s"), rs->buf);
7327 break;
7328 }
7329
7330 /* Acknowledge a pending stop reply that may have arrived in the
7331 mean time. */
f48ff2a7 7332 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7333 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7334
7335 /* If indeed we noticed a stop reply, we're done. */
7336 stop_reply = queued_stop_reply (ptid);
7337 if (stop_reply != NULL)
7338 return process_stop_reply (stop_reply, status);
7339
47608cb1 7340 /* Still no event. If we're just polling for an event, then
74531fed 7341 return to the event loop. */
47608cb1 7342 if (options & TARGET_WNOHANG)
74531fed
PA
7343 {
7344 status->kind = TARGET_WAITKIND_IGNORE;
7345 return minus_one_ptid;
7346 }
7347
47608cb1 7348 /* Otherwise do a blocking wait. */
74531fed 7349 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7350 1 /* forever */, &is_notif);
74531fed
PA
7351 }
7352}
7353
7354/* Wait until the remote machine stops, then return, storing status in
7355 STATUS just as `wait' would. */
7356
7357static ptid_t
47608cb1 7358remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7359{
7360 struct remote_state *rs = get_remote_state ();
74531fed 7361 ptid_t event_ptid = null_ptid;
cea39f65 7362 char *buf;
74531fed
PA
7363 struct stop_reply *stop_reply;
7364
47608cb1
PA
7365 again:
7366
74531fed
PA
7367 status->kind = TARGET_WAITKIND_IGNORE;
7368 status->value.integer = 0;
7369
7370 stop_reply = queued_stop_reply (ptid);
7371 if (stop_reply != NULL)
7372 return process_stop_reply (stop_reply, status);
7373
7374 if (rs->cached_wait_status)
7375 /* Use the cached wait status, but only once. */
7376 rs->cached_wait_status = 0;
7377 else
7378 {
7379 int ret;
722247f1 7380 int is_notif;
567420d1
PA
7381 int forever = ((options & TARGET_WNOHANG) == 0
7382 && wait_forever_enabled_p);
7383
7384 if (!rs->waiting_for_stop_reply)
7385 {
7386 status->kind = TARGET_WAITKIND_NO_RESUMED;
7387 return minus_one_ptid;
7388 }
74531fed 7389
74531fed
PA
7390 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7391 _never_ wait for ever -> test on target_is_async_p().
7392 However, before we do that we need to ensure that the caller
7393 knows how to take the target into/out of async mode. */
722247f1 7394 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 7395 forever, &is_notif);
722247f1
YQ
7396
7397 /* GDB gets a notification. Return to core as this event is
7398 not interesting. */
7399 if (ret != -1 && is_notif)
7400 return minus_one_ptid;
567420d1
PA
7401
7402 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7403 return minus_one_ptid;
74531fed
PA
7404 }
7405
7406 buf = rs->buf;
7407
3a29589a
DJ
7408 /* Assume that the target has acknowledged Ctrl-C unless we receive
7409 an 'F' or 'O' packet. */
7410 if (buf[0] != 'F' && buf[0] != 'O')
7411 rs->ctrlc_pending_p = 0;
7412
74531fed
PA
7413 switch (buf[0])
7414 {
7415 case 'E': /* Error of some sort. */
7416 /* We're out of sync with the target now. Did it continue or
7417 not? Not is more likely, so report a stop. */
29090fb6
LM
7418 rs->waiting_for_stop_reply = 0;
7419
74531fed
PA
7420 warning (_("Remote failure reply: %s"), buf);
7421 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7422 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7423 break;
7424 case 'F': /* File-I/O request. */
e42e5352
YQ
7425 /* GDB may access the inferior memory while handling the File-I/O
7426 request, but we don't want GDB accessing memory while waiting
7427 for a stop reply. See the comments in putpkt_binary. Set
7428 waiting_for_stop_reply to 0 temporarily. */
7429 rs->waiting_for_stop_reply = 0;
3a29589a
DJ
7430 remote_fileio_request (buf, rs->ctrlc_pending_p);
7431 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7432 /* GDB handled the File-I/O request, and the target is running
7433 again. Keep waiting for events. */
7434 rs->waiting_for_stop_reply = 1;
74531fed 7435 break;
f2faf941 7436 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7437 {
29090fb6
LM
7438 struct stop_reply *stop_reply;
7439
7440 /* There is a stop reply to handle. */
7441 rs->waiting_for_stop_reply = 0;
7442
7443 stop_reply
722247f1
YQ
7444 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7445 rs->buf);
74531fed 7446
74531fed 7447 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7448 break;
7449 }
7450 case 'O': /* Console output. */
7451 remote_console_output (buf + 1);
c8e38a49
PA
7452 break;
7453 case '\0':
b73be471 7454 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7455 {
7456 /* Zero length reply means that we tried 'S' or 'C' and the
7457 remote system doesn't support it. */
223ffa71 7458 target_terminal::ours_for_output ();
c8e38a49
PA
7459 printf_filtered
7460 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7461 gdb_signal_to_name (rs->last_sent_signal));
7462 rs->last_sent_signal = GDB_SIGNAL_0;
223ffa71 7463 target_terminal::inferior ();
c8e38a49 7464
f5c4fcd9
TT
7465 strcpy (buf, rs->last_sent_step ? "s" : "c");
7466 putpkt (buf);
c8e38a49 7467 break;
43ff13b4 7468 }
c8e38a49
PA
7469 /* else fallthrough */
7470 default:
7471 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7472 break;
43ff13b4 7473 }
c8e38a49 7474
f2faf941
PA
7475 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7476 return minus_one_ptid;
7477 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7478 {
7479 /* Nothing interesting happened. If we're doing a non-blocking
7480 poll, we're done. Otherwise, go back to waiting. */
7481 if (options & TARGET_WNOHANG)
7482 return minus_one_ptid;
7483 else
7484 goto again;
7485 }
74531fed
PA
7486 else if (status->kind != TARGET_WAITKIND_EXITED
7487 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7488 {
7489 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7490 record_currthread (rs, event_ptid);
82f73884
PA
7491 else
7492 event_ptid = inferior_ptid;
43ff13b4 7493 }
74531fed
PA
7494 else
7495 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7496 record_currthread (rs, minus_one_ptid);
79d7f229 7497
82f73884 7498 return event_ptid;
43ff13b4
JM
7499}
7500
74531fed
PA
7501/* Wait until the remote machine stops, then return, storing status in
7502 STATUS just as `wait' would. */
7503
c8e38a49 7504static ptid_t
117de6a9 7505remote_wait (struct target_ops *ops,
47608cb1 7506 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7507{
7508 ptid_t event_ptid;
7509
6efcd9a8 7510 if (target_is_non_stop_p ())
47608cb1 7511 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7512 else
47608cb1 7513 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7514
d9d41e78 7515 if (target_is_async_p ())
c8e38a49 7516 {
74531fed
PA
7517 /* If there are are events left in the queue tell the event loop
7518 to return here. */
722247f1 7519 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7520 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7521 }
c8e38a49
PA
7522
7523 return event_ptid;
7524}
7525
74ca34ce 7526/* Fetch a single register using a 'p' packet. */
c906108c 7527
b96ec7ac 7528static int
56be3814 7529fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac 7530{
ac7936df 7531 struct gdbarch *gdbarch = regcache->arch ();
b96ec7ac 7532 struct remote_state *rs = get_remote_state ();
2e9f7625 7533 char *buf, *p;
9890e433 7534 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
7535 int i;
7536
4082afcc 7537 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7538 return 0;
7539
7540 if (reg->pnum == -1)
7541 return 0;
7542
2e9f7625 7543 p = rs->buf;
fcad0fa4 7544 *p++ = 'p';
74ca34ce 7545 p += hexnumstr (p, reg->pnum);
fcad0fa4 7546 *p++ = '\0';
1f4437a4
MS
7547 putpkt (rs->buf);
7548 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7549
2e9f7625
DJ
7550 buf = rs->buf;
7551
74ca34ce
DJ
7552 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7553 {
7554 case PACKET_OK:
7555 break;
7556 case PACKET_UNKNOWN:
7557 return 0;
7558 case PACKET_ERROR:
27a9c0bf 7559 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
ac7936df 7560 gdbarch_register_name (regcache->arch (),
27a9c0bf
MS
7561 reg->regnum),
7562 buf);
74ca34ce 7563 }
3f9a994c
JB
7564
7565 /* If this register is unfetchable, tell the regcache. */
7566 if (buf[0] == 'x')
8480adf2 7567 {
56be3814 7568 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7569 return 1;
b96ec7ac 7570 }
b96ec7ac 7571
3f9a994c
JB
7572 /* Otherwise, parse and supply the value. */
7573 p = buf;
7574 i = 0;
7575 while (p[0] != 0)
7576 {
7577 if (p[1] == 0)
74ca34ce 7578 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7579
7580 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7581 p += 2;
7582 }
56be3814 7583 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7584 return 1;
b96ec7ac
AC
7585}
7586
74ca34ce
DJ
7587/* Fetch the registers included in the target's 'g' packet. */
7588
29709017
DJ
7589static int
7590send_g_packet (void)
c906108c 7591{
d01949b6 7592 struct remote_state *rs = get_remote_state ();
cea39f65 7593 int buf_len;
c906108c 7594
bba74b36 7595 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7596 remote_send (&rs->buf, &rs->buf_size);
c906108c 7597
29709017
DJ
7598 /* We can get out of synch in various cases. If the first character
7599 in the buffer is not a hex character, assume that has happened
7600 and try to fetch another packet to read. */
7601 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7602 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7603 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7604 && rs->buf[0] != 'x') /* New: unavailable register value. */
7605 {
7606 if (remote_debug)
7607 fprintf_unfiltered (gdb_stdlog,
7608 "Bad register packet; fetching a new packet\n");
7609 getpkt (&rs->buf, &rs->buf_size, 0);
7610 }
7611
74ca34ce
DJ
7612 buf_len = strlen (rs->buf);
7613
7614 /* Sanity check the received packet. */
7615 if (buf_len % 2 != 0)
7616 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7617
7618 return buf_len / 2;
7619}
7620
7621static void
56be3814 7622process_g_packet (struct regcache *regcache)
29709017 7623{
ac7936df 7624 struct gdbarch *gdbarch = regcache->arch ();
29709017 7625 struct remote_state *rs = get_remote_state ();
5cd63fda 7626 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
29709017
DJ
7627 int i, buf_len;
7628 char *p;
7629 char *regs;
7630
7631 buf_len = strlen (rs->buf);
7632
7633 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 7634 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827
SM
7635 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7636 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
74ca34ce
DJ
7637
7638 /* Save the size of the packet sent to us by the target. It is used
7639 as a heuristic when determining the max size of packets that the
7640 target can safely receive. */
7641 if (rsa->actual_register_packet_size == 0)
7642 rsa->actual_register_packet_size = buf_len;
7643
7644 /* If this is smaller than we guessed the 'g' packet would be,
7645 update our records. A 'g' reply that doesn't include a register's
7646 value implies either that the register is not available, or that
7647 the 'p' packet must be used. */
7648 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7649 {
9dc193c3 7650 long sizeof_g_packet = buf_len / 2;
74ca34ce 7651
4a22f64d 7652 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7653 {
9dc193c3
LF
7654 long offset = rsa->regs[i].offset;
7655 long reg_size = register_size (gdbarch, i);
7656
74ca34ce
DJ
7657 if (rsa->regs[i].pnum == -1)
7658 continue;
7659
9dc193c3 7660 if (offset >= sizeof_g_packet)
74ca34ce 7661 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
7662 else if (offset + reg_size > sizeof_g_packet)
7663 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 7664 else
74ca34ce 7665 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7666 }
9dc193c3
LF
7667
7668 /* Looks valid enough, we can assume this is the correct length
7669 for a 'g' packet. It's important not to adjust
7670 rsa->sizeof_g_packet if we have truncated registers otherwise
7671 this "if" won't be run the next time the method is called
7672 with a packet of the same size and one of the internal errors
7673 below will trigger instead. */
7674 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 7675 }
b323314b 7676
224c3ddb 7677 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7678
7679 /* Unimplemented registers read as all bits zero. */
ea9c271d 7680 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7681
c906108c
SS
7682 /* Reply describes registers byte by byte, each byte encoded as two
7683 hex characters. Suck them all up, then supply them to the
7684 register cacheing/storage mechanism. */
7685
74ca34ce 7686 p = rs->buf;
ea9c271d 7687 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7688 {
74ca34ce
DJ
7689 if (p[0] == 0 || p[1] == 0)
7690 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7691 internal_error (__FILE__, __LINE__,
9b20d036 7692 _("unexpected end of 'g' packet reply"));
74ca34ce 7693
c906108c 7694 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7695 regs[i] = 0; /* 'x' */
c906108c
SS
7696 else
7697 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7698 p += 2;
7699 }
7700
a744cf53
MS
7701 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7702 {
7703 struct packet_reg *r = &rsa->regs[i];
9dc193c3 7704 long reg_size = register_size (gdbarch, i);
a744cf53
MS
7705
7706 if (r->in_g_packet)
7707 {
9dc193c3 7708 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
a744cf53
MS
7709 /* This shouldn't happen - we adjusted in_g_packet above. */
7710 internal_error (__FILE__, __LINE__,
9b20d036 7711 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7712 else if (rs->buf[r->offset * 2] == 'x')
7713 {
7714 gdb_assert (r->offset * 2 < strlen (rs->buf));
7715 /* The register isn't available, mark it as such (at
7716 the same time setting the value to zero). */
7717 regcache_raw_supply (regcache, r->regnum, NULL);
7718 }
7719 else
7720 regcache_raw_supply (regcache, r->regnum,
7721 regs + r->offset);
7722 }
7723 }
c906108c
SS
7724}
7725
29709017 7726static void
56be3814 7727fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7728{
7729 send_g_packet ();
56be3814 7730 process_g_packet (regcache);
29709017
DJ
7731}
7732
e6e4e701
PA
7733/* Make the remote selected traceframe match GDB's selected
7734 traceframe. */
7735
7736static void
7737set_remote_traceframe (void)
7738{
7739 int newnum;
262e1174 7740 struct remote_state *rs = get_remote_state ();
e6e4e701 7741
262e1174 7742 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7743 return;
7744
7745 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7746 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7747
7748 newnum = target_trace_find (tfind_number,
7749 get_traceframe_number (), 0, 0, NULL);
7750
7751 /* Should not happen. If it does, all bets are off. */
7752 if (newnum != get_traceframe_number ())
7753 warning (_("could not set remote traceframe"));
7754}
7755
74ca34ce 7756static void
28439f5e
PA
7757remote_fetch_registers (struct target_ops *ops,
7758 struct regcache *regcache, int regnum)
74ca34ce 7759{
ac7936df 7760 struct gdbarch *gdbarch = regcache->arch ();
5cd63fda 7761 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
74ca34ce
DJ
7762 int i;
7763
e6e4e701 7764 set_remote_traceframe ();
bcc0c096 7765 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
7766
7767 if (regnum >= 0)
7768 {
5cd63fda 7769 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 7770
74ca34ce
DJ
7771 gdb_assert (reg != NULL);
7772
7773 /* If this register might be in the 'g' packet, try that first -
7774 we are likely to read more than one register. If this is the
7775 first 'g' packet, we might be overly optimistic about its
7776 contents, so fall back to 'p'. */
7777 if (reg->in_g_packet)
7778 {
56be3814 7779 fetch_registers_using_g (regcache);
74ca34ce
DJ
7780 if (reg->in_g_packet)
7781 return;
7782 }
7783
56be3814 7784 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7785 return;
7786
7787 /* This register is not available. */
56be3814 7788 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7789
7790 return;
7791 }
7792
56be3814 7793 fetch_registers_using_g (regcache);
74ca34ce 7794
5cd63fda 7795 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 7796 if (!rsa->regs[i].in_g_packet)
56be3814 7797 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7798 {
7799 /* This register is not available. */
56be3814 7800 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7801 }
7802}
7803
c906108c
SS
7804/* Prepare to store registers. Since we may send them all (using a
7805 'G' request), we have to read out the ones we don't want to change
7806 first. */
7807
c5aa993b 7808static void
f32dbf8c 7809remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7810{
5cd63fda 7811 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
cf0e1e0d 7812 int i;
cf0e1e0d 7813
c906108c 7814 /* Make sure the entire registers array is valid. */
4082afcc 7815 switch (packet_support (PACKET_P))
5a2468f5
JM
7816 {
7817 case PACKET_DISABLE:
7818 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7819 /* Make sure all the necessary registers are cached. */
ac7936df 7820 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
ea9c271d 7821 if (rsa->regs[i].in_g_packet)
8e368124 7822 regcache_raw_update (regcache, rsa->regs[i].regnum);
5a2468f5
JM
7823 break;
7824 case PACKET_ENABLE:
7825 break;
7826 }
7827}
7828
ad10f812 7829/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7830 packet was not recognized. */
5a2468f5
JM
7831
7832static int
1f4437a4
MS
7833store_register_using_P (const struct regcache *regcache,
7834 struct packet_reg *reg)
5a2468f5 7835{
ac7936df 7836 struct gdbarch *gdbarch = regcache->arch ();
d01949b6 7837 struct remote_state *rs = get_remote_state ();
5a2468f5 7838 /* Try storing a single register. */
6d820c5c 7839 char *buf = rs->buf;
9890e433 7840 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 7841 char *p;
5a2468f5 7842
4082afcc 7843 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7844 return 0;
7845
7846 if (reg->pnum == -1)
7847 return 0;
7848
ea9c271d 7849 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7850 p = buf + strlen (buf);
56be3814 7851 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7852 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7853 putpkt (rs->buf);
7854 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7855
74ca34ce
DJ
7856 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7857 {
7858 case PACKET_OK:
7859 return 1;
7860 case PACKET_ERROR:
27a9c0bf
MS
7861 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7862 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7863 case PACKET_UNKNOWN:
7864 return 0;
7865 default:
7866 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7867 }
c906108c
SS
7868}
7869
23860348
MS
7870/* Store register REGNUM, or all registers if REGNUM == -1, from the
7871 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7872
7873static void
56be3814 7874store_registers_using_G (const struct regcache *regcache)
c906108c 7875{
d01949b6 7876 struct remote_state *rs = get_remote_state ();
5cd63fda 7877 remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
cfd77fa1 7878 gdb_byte *regs;
c906108c
SS
7879 char *p;
7880
193cb69f
AC
7881 /* Extract all the registers in the regcache copying them into a
7882 local buffer. */
7883 {
b323314b 7884 int i;
a744cf53 7885
224c3ddb 7886 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7887 memset (regs, 0, rsa->sizeof_g_packet);
ac7936df 7888 for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
193cb69f 7889 {
ea9c271d 7890 struct packet_reg *r = &rsa->regs[i];
a744cf53 7891
b323314b 7892 if (r->in_g_packet)
56be3814 7893 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7894 }
7895 }
c906108c
SS
7896
7897 /* Command describes registers byte by byte,
7898 each byte encoded as two hex characters. */
6d820c5c 7899 p = rs->buf;
193cb69f 7900 *p++ = 'G';
74ca34ce 7901 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7902 putpkt (rs->buf);
7903 getpkt (&rs->buf, &rs->buf_size, 0);
7904 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7905 error (_("Could not write registers; remote failure reply '%s'"),
7906 rs->buf);
c906108c 7907}
74ca34ce
DJ
7908
7909/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7910 of the register cache buffer. FIXME: ignores errors. */
7911
7912static void
28439f5e
PA
7913remote_store_registers (struct target_ops *ops,
7914 struct regcache *regcache, int regnum)
74ca34ce 7915{
5cd63fda
PA
7916 struct gdbarch *gdbarch = regcache->arch ();
7917 remote_arch_state *rsa = get_remote_arch_state (gdbarch);
74ca34ce
DJ
7918 int i;
7919
e6e4e701 7920 set_remote_traceframe ();
bcc0c096 7921 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
7922
7923 if (regnum >= 0)
7924 {
5cd63fda 7925 packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
a744cf53 7926
74ca34ce
DJ
7927 gdb_assert (reg != NULL);
7928
7929 /* Always prefer to store registers using the 'P' packet if
7930 possible; we often change only a small number of registers.
7931 Sometimes we change a larger number; we'd need help from a
7932 higher layer to know to use 'G'. */
56be3814 7933 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7934 return;
7935
7936 /* For now, don't complain if we have no way to write the
7937 register. GDB loses track of unavailable registers too
7938 easily. Some day, this may be an error. We don't have
0df8b418 7939 any way to read the register, either... */
74ca34ce
DJ
7940 if (!reg->in_g_packet)
7941 return;
7942
56be3814 7943 store_registers_using_G (regcache);
74ca34ce
DJ
7944 return;
7945 }
7946
56be3814 7947 store_registers_using_G (regcache);
74ca34ce 7948
5cd63fda 7949 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
74ca34ce 7950 if (!rsa->regs[i].in_g_packet)
56be3814 7951 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7952 /* See above for why we do not issue an error here. */
7953 continue;
7954}
c906108c
SS
7955\f
7956
7957/* Return the number of hex digits in num. */
7958
7959static int
fba45db2 7960hexnumlen (ULONGEST num)
c906108c
SS
7961{
7962 int i;
7963
7964 for (i = 0; num != 0; i++)
7965 num >>= 4;
7966
325fac50 7967 return std::max (i, 1);
c906108c
SS
7968}
7969
2df3850c 7970/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7971
7972static int
fba45db2 7973hexnumstr (char *buf, ULONGEST num)
c906108c 7974{
c906108c 7975 int len = hexnumlen (num);
a744cf53 7976
2df3850c
JM
7977 return hexnumnstr (buf, num, len);
7978}
7979
c906108c 7980
2df3850c 7981/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7982
2df3850c 7983static int
fba45db2 7984hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7985{
7986 int i;
7987
7988 buf[width] = '\0';
7989
7990 for (i = width - 1; i >= 0; i--)
c906108c 7991 {
c5aa993b 7992 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7993 num >>= 4;
7994 }
7995
2df3850c 7996 return width;
c906108c
SS
7997}
7998
23860348 7999/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
8000
8001static CORE_ADDR
fba45db2 8002remote_address_masked (CORE_ADDR addr)
c906108c 8003{
883b9c6c 8004 unsigned int address_size = remote_address_size;
a744cf53 8005
911c95a5
UW
8006 /* If "remoteaddresssize" was not set, default to target address size. */
8007 if (!address_size)
f5656ead 8008 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
8009
8010 if (address_size > 0
8011 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
8012 {
8013 /* Only create a mask when that mask can safely be constructed
23860348 8014 in a ULONGEST variable. */
c906108c 8015 ULONGEST mask = 1;
a744cf53 8016
911c95a5 8017 mask = (mask << address_size) - 1;
c906108c
SS
8018 addr &= mask;
8019 }
8020 return addr;
8021}
8022
8023/* Determine whether the remote target supports binary downloading.
8024 This is accomplished by sending a no-op memory write of zero length
8025 to the target at the specified address. It does not suffice to send
23860348
MS
8026 the whole packet, since many stubs strip the eighth bit and
8027 subsequently compute a wrong checksum, which causes real havoc with
8028 remote_write_bytes.
7a292a7a 8029
96baa820 8030 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8031 clean. In cases like this, the user should clear "remote
23860348 8032 X-packet". */
96baa820 8033
c906108c 8034static void
fba45db2 8035check_binary_download (CORE_ADDR addr)
c906108c 8036{
d01949b6 8037 struct remote_state *rs = get_remote_state ();
24b06219 8038
4082afcc 8039 switch (packet_support (PACKET_X))
c906108c 8040 {
96baa820
JM
8041 case PACKET_DISABLE:
8042 break;
8043 case PACKET_ENABLE:
8044 break;
8045 case PACKET_SUPPORT_UNKNOWN:
8046 {
96baa820 8047 char *p;
802188a7 8048
2e9f7625 8049 p = rs->buf;
96baa820
JM
8050 *p++ = 'X';
8051 p += hexnumstr (p, (ULONGEST) addr);
8052 *p++ = ',';
8053 p += hexnumstr (p, (ULONGEST) 0);
8054 *p++ = ':';
8055 *p = '\0';
802188a7 8056
2e9f7625 8057 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8058 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8059
2e9f7625 8060 if (rs->buf[0] == '\0')
96baa820
JM
8061 {
8062 if (remote_debug)
8063 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8064 "binary downloading NOT "
8065 "supported by target\n");
444abaca 8066 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8067 }
8068 else
8069 {
8070 if (remote_debug)
8071 fprintf_unfiltered (gdb_stdlog,
64b9b334 8072 "binary downloading supported by target\n");
444abaca 8073 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8074 }
8075 break;
8076 }
c906108c
SS
8077 }
8078}
8079
124e13d9
SM
8080/* Helper function to resize the payload in order to try to get a good
8081 alignment. We try to write an amount of data such that the next write will
8082 start on an address aligned on REMOTE_ALIGN_WRITES. */
8083
8084static int
8085align_for_efficient_write (int todo, CORE_ADDR memaddr)
8086{
8087 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8088}
8089
c906108c
SS
8090/* Write memory data directly to the remote machine.
8091 This does not inform the data cache; the data cache uses this.
a76d924d 8092 HEADER is the starting part of the packet.
c906108c
SS
8093 MEMADDR is the address in the remote memory space.
8094 MYADDR is the address of the buffer in our space.
124e13d9
SM
8095 LEN_UNITS is the number of addressable units to write.
8096 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8097 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8098 should send data as binary ('X'), or hex-encoded ('M').
8099
8100 The function creates packet of the form
8101 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8102
124e13d9 8103 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8104
8105 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8106 are omitted.
8107
9b409511 8108 Return the transferred status, error or OK (an
124e13d9
SM
8109 'enum target_xfer_status' value). Save the number of addressable units
8110 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8111
8112 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8113 exchange between gdb and the stub could look like (?? in place of the
8114 checksum):
8115
8116 -> $m1000,4#??
8117 <- aaaabbbbccccdddd
8118
8119 -> $M1000,3:eeeeffffeeee#??
8120 <- OK
8121
8122 -> $m1000,4#??
8123 <- eeeeffffeeeedddd */
c906108c 8124
9b409511 8125static enum target_xfer_status
a76d924d 8126remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
8127 const gdb_byte *myaddr, ULONGEST len_units,
8128 int unit_size, ULONGEST *xfered_len_units,
8129 char packet_format, int use_length)
c906108c 8130{
6d820c5c 8131 struct remote_state *rs = get_remote_state ();
cfd77fa1 8132 char *p;
a76d924d
DJ
8133 char *plen = NULL;
8134 int plenlen = 0;
124e13d9
SM
8135 int todo_units;
8136 int units_written;
8137 int payload_capacity_bytes;
8138 int payload_length_bytes;
a76d924d
DJ
8139
8140 if (packet_format != 'X' && packet_format != 'M')
8141 internal_error (__FILE__, __LINE__,
9b20d036 8142 _("remote_write_bytes_aux: bad packet format"));
c906108c 8143
124e13d9 8144 if (len_units == 0)
9b409511 8145 return TARGET_XFER_EOF;
b2182ed2 8146
124e13d9 8147 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8148
6d820c5c
DJ
8149 /* The packet buffer will be large enough for the payload;
8150 get_memory_packet_size ensures this. */
a76d924d 8151 rs->buf[0] = '\0';
c906108c 8152
a257b5bb 8153 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8154 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8155
124e13d9 8156 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8157 if (!use_length)
0df8b418 8158 /* The comma won't be used. */
124e13d9
SM
8159 payload_capacity_bytes += 1;
8160 payload_capacity_bytes -= strlen (header);
8161 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8162
a76d924d 8163 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8164
a76d924d
DJ
8165 strcat (rs->buf, header);
8166 p = rs->buf + strlen (header);
8167
8168 /* Compute a best guess of the number of bytes actually transfered. */
8169 if (packet_format == 'X')
c906108c 8170 {
23860348 8171 /* Best guess at number of bytes that will fit. */
325fac50
PA
8172 todo_units = std::min (len_units,
8173 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8174 if (use_length)
124e13d9 8175 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8176 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8177 }
8178 else
8179 {
124e13d9 8180 /* Number of bytes that will fit. */
325fac50
PA
8181 todo_units
8182 = std::min (len_units,
8183 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8184 if (use_length)
124e13d9 8185 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8186 todo_units = std::min (todo_units,
8187 (payload_capacity_bytes / unit_size) / 2);
917317f4 8188 }
a76d924d 8189
124e13d9 8190 if (todo_units <= 0)
3de11b2e 8191 internal_error (__FILE__, __LINE__,
405f8e94 8192 _("minimum packet size too small to write data"));
802188a7 8193
6765f3e5
DJ
8194 /* If we already need another packet, then try to align the end
8195 of this packet to a useful boundary. */
124e13d9
SM
8196 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8197 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8198
a257b5bb 8199 /* Append "<memaddr>". */
917317f4
JM
8200 memaddr = remote_address_masked (memaddr);
8201 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8202
a76d924d
DJ
8203 if (use_length)
8204 {
8205 /* Append ",". */
8206 *p++ = ',';
802188a7 8207
124e13d9
SM
8208 /* Append the length and retain its location and size. It may need to be
8209 adjusted once the packet body has been created. */
a76d924d 8210 plen = p;
124e13d9 8211 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8212 p += plenlen;
8213 }
a257b5bb
AC
8214
8215 /* Append ":". */
917317f4
JM
8216 *p++ = ':';
8217 *p = '\0';
802188a7 8218
a257b5bb 8219 /* Append the packet body. */
a76d924d 8220 if (packet_format == 'X')
917317f4 8221 {
917317f4
JM
8222 /* Binary mode. Send target system values byte by byte, in
8223 increasing byte addresses. Only escape certain critical
8224 characters. */
124e13d9
SM
8225 payload_length_bytes =
8226 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8227 &units_written, payload_capacity_bytes);
6765f3e5 8228
124e13d9 8229 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8230 a second try to keep the end of the packet aligned. Don't do
8231 this if the packet is tiny. */
124e13d9 8232 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8233 {
124e13d9
SM
8234 int new_todo_units;
8235
8236 new_todo_units = align_for_efficient_write (units_written, memaddr);
8237
8238 if (new_todo_units != units_written)
8239 payload_length_bytes =
8240 remote_escape_output (myaddr, new_todo_units, unit_size,
8241 (gdb_byte *) p, &units_written,
8242 payload_capacity_bytes);
6765f3e5
DJ
8243 }
8244
124e13d9
SM
8245 p += payload_length_bytes;
8246 if (use_length && units_written < todo_units)
c906108c 8247 {
802188a7 8248 /* Escape chars have filled up the buffer prematurely,
124e13d9 8249 and we have actually sent fewer units than planned.
917317f4
JM
8250 Fix-up the length field of the packet. Use the same
8251 number of characters as before. */
124e13d9
SM
8252 plen += hexnumnstr (plen, (ULONGEST) units_written,
8253 plenlen);
917317f4 8254 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8255 }
a76d924d
DJ
8256 }
8257 else
8258 {
917317f4
JM
8259 /* Normal mode: Send target system values byte by byte, in
8260 increasing byte addresses. Each byte is encoded as a two hex
8261 value. */
124e13d9
SM
8262 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8263 units_written = todo_units;
c906108c 8264 }
802188a7 8265
2e9f7625 8266 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8267 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8268
2e9f7625 8269 if (rs->buf[0] == 'E')
00d84524 8270 return TARGET_XFER_E_IO;
802188a7 8271
124e13d9
SM
8272 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8273 send fewer units than we'd planned. */
8274 *xfered_len_units = (ULONGEST) units_written;
9b409511 8275 return TARGET_XFER_OK;
c906108c
SS
8276}
8277
a76d924d
DJ
8278/* Write memory data directly to the remote machine.
8279 This does not inform the data cache; the data cache uses this.
8280 MEMADDR is the address in the remote memory space.
8281 MYADDR is the address of the buffer in our space.
8282 LEN is the number of bytes.
8283
9b409511
YQ
8284 Return the transferred status, error or OK (an
8285 'enum target_xfer_status' value). Save the number of bytes
8286 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8287
9b409511
YQ
8288static enum target_xfer_status
8289remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 8290 int unit_size, ULONGEST *xfered_len)
a76d924d 8291{
a121b7c1 8292 const char *packet_format = NULL;
a76d924d
DJ
8293
8294 /* Check whether the target supports binary download. */
8295 check_binary_download (memaddr);
8296
4082afcc 8297 switch (packet_support (PACKET_X))
a76d924d
DJ
8298 {
8299 case PACKET_ENABLE:
8300 packet_format = "X";
8301 break;
8302 case PACKET_DISABLE:
8303 packet_format = "M";
8304 break;
8305 case PACKET_SUPPORT_UNKNOWN:
8306 internal_error (__FILE__, __LINE__,
8307 _("remote_write_bytes: bad internal state"));
8308 default:
8309 internal_error (__FILE__, __LINE__, _("bad switch"));
8310 }
8311
8312 return remote_write_bytes_aux (packet_format,
124e13d9 8313 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8314 packet_format[0], 1);
a76d924d
DJ
8315}
8316
9217e74e
YQ
8317/* Read memory data directly from the remote machine.
8318 This does not use the data cache; the data cache uses this.
8319 MEMADDR is the address in the remote memory space.
8320 MYADDR is the address of the buffer in our space.
124e13d9
SM
8321 LEN_UNITS is the number of addressable memory units to read..
8322 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8323
8324 Return the transferred status, error or OK (an
8325 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8326 transferred in *XFERED_LEN_UNITS.
8327
8328 See the comment of remote_write_bytes_aux for an example of
8329 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
8330
8331static enum target_xfer_status
124e13d9
SM
8332remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8333 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8334{
8335 struct remote_state *rs = get_remote_state ();
124e13d9 8336 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8337 char *p;
124e13d9
SM
8338 int todo_units;
8339 int decoded_bytes;
9217e74e 8340
124e13d9 8341 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8342 /* The packet buffer will be large enough for the payload;
8343 get_memory_packet_size ensures this. */
8344
124e13d9 8345 /* Number of units that will fit. */
325fac50
PA
8346 todo_units = std::min (len_units,
8347 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8348
8349 /* Construct "m"<memaddr>","<len>". */
8350 memaddr = remote_address_masked (memaddr);
8351 p = rs->buf;
8352 *p++ = 'm';
8353 p += hexnumstr (p, (ULONGEST) memaddr);
8354 *p++ = ',';
124e13d9 8355 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8356 *p = '\0';
8357 putpkt (rs->buf);
8358 getpkt (&rs->buf, &rs->buf_size, 0);
8359 if (rs->buf[0] == 'E'
8360 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8361 && rs->buf[3] == '\0')
8362 return TARGET_XFER_E_IO;
8363 /* Reply describes memory byte by byte, each byte encoded as two hex
8364 characters. */
8365 p = rs->buf;
124e13d9 8366 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8367 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8368 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
8369 return TARGET_XFER_OK;
8370}
8371
b55fbac4
YQ
8372/* Using the set of read-only target sections of remote, read live
8373 read-only memory.
8acf9577
YQ
8374
8375 For interface/parameters/return description see target.h,
8376 to_xfer_partial. */
8377
8378static enum target_xfer_status
b55fbac4
YQ
8379remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8380 ULONGEST memaddr, ULONGEST len,
124e13d9 8381 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
8382{
8383 struct target_section *secp;
8384 struct target_section_table *table;
8385
8386 secp = target_section_by_addr (ops, memaddr);
8387 if (secp != NULL
8388 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8389 secp->the_bfd_section)
8390 & SEC_READONLY))
8391 {
8392 struct target_section *p;
8393 ULONGEST memend = memaddr + len;
8394
8395 table = target_get_section_table (ops);
8396
8397 for (p = table->sections; p < table->sections_end; p++)
8398 {
8399 if (memaddr >= p->addr)
8400 {
8401 if (memend <= p->endaddr)
8402 {
8403 /* Entire transfer is within this section. */
124e13d9 8404 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8405 xfered_len);
8acf9577
YQ
8406 }
8407 else if (memaddr >= p->endaddr)
8408 {
8409 /* This section ends before the transfer starts. */
8410 continue;
8411 }
8412 else
8413 {
8414 /* This section overlaps the transfer. Just do half. */
8415 len = p->endaddr - memaddr;
124e13d9 8416 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8417 xfered_len);
8acf9577
YQ
8418 }
8419 }
8420 }
8421 }
8422
8423 return TARGET_XFER_EOF;
8424}
8425
9217e74e
YQ
8426/* Similar to remote_read_bytes_1, but it reads from the remote stub
8427 first if the requested memory is unavailable in traceframe.
8428 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8429
9b409511 8430static enum target_xfer_status
8acf9577 8431remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
8432 gdb_byte *myaddr, ULONGEST len, int unit_size,
8433 ULONGEST *xfered_len)
c906108c 8434{
6b6aa828 8435 if (len == 0)
96c4f946 8436 return TARGET_XFER_EOF;
b2182ed2 8437
8acf9577
YQ
8438 if (get_traceframe_number () != -1)
8439 {
a79b1bc6 8440 std::vector<mem_range> available;
8acf9577
YQ
8441
8442 /* If we fail to get the set of available memory, then the
8443 target does not support querying traceframe info, and so we
8444 attempt reading from the traceframe anyway (assuming the
8445 target implements the old QTro packet then). */
8446 if (traceframe_available_memory (&available, memaddr, len))
8447 {
a79b1bc6 8448 if (available.empty () || available[0].start != memaddr)
8acf9577
YQ
8449 {
8450 enum target_xfer_status res;
8451
8452 /* Don't read into the traceframe's available
8453 memory. */
a79b1bc6 8454 if (!available.empty ())
8acf9577
YQ
8455 {
8456 LONGEST oldlen = len;
8457
a79b1bc6 8458 len = available[0].start - memaddr;
8acf9577
YQ
8459 gdb_assert (len <= oldlen);
8460 }
8461
8acf9577 8462 /* This goes through the topmost target again. */
b55fbac4 8463 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 8464 len, unit_size, xfered_len);
8acf9577
YQ
8465 if (res == TARGET_XFER_OK)
8466 return TARGET_XFER_OK;
8467 else
8468 {
8469 /* No use trying further, we know some memory starting
8470 at MEMADDR isn't available. */
8471 *xfered_len = len;
8472 return TARGET_XFER_UNAVAILABLE;
8473 }
8474 }
8475
8476 /* Don't try to read more than how much is available, in
8477 case the target implements the deprecated QTro packet to
8478 cater for older GDBs (the target's knowledge of read-only
8479 sections may be outdated by now). */
a79b1bc6 8480 len = available[0].length;
8acf9577
YQ
8481 }
8482 }
8483
124e13d9 8484 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8485}
74531fed 8486
c906108c 8487\f
c906108c 8488
a76d924d
DJ
8489/* Sends a packet with content determined by the printf format string
8490 FORMAT and the remaining arguments, then gets the reply. Returns
8491 whether the packet was a success, a failure, or unknown. */
8492
77b64a49
PA
8493static enum packet_result remote_send_printf (const char *format, ...)
8494 ATTRIBUTE_PRINTF (1, 2);
8495
2c0b251b 8496static enum packet_result
a76d924d
DJ
8497remote_send_printf (const char *format, ...)
8498{
8499 struct remote_state *rs = get_remote_state ();
8500 int max_size = get_remote_packet_size ();
a76d924d 8501 va_list ap;
a744cf53 8502
a76d924d
DJ
8503 va_start (ap, format);
8504
8505 rs->buf[0] = '\0';
8506 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8507 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8508
8509 if (putpkt (rs->buf) < 0)
8510 error (_("Communication problem with target."));
8511
8512 rs->buf[0] = '\0';
8513 getpkt (&rs->buf, &rs->buf_size, 0);
8514
8515 return packet_check_result (rs->buf);
8516}
8517
a76d924d
DJ
8518/* Flash writing can take quite some time. We'll set
8519 effectively infinite timeout for flash operations.
8520 In future, we'll need to decide on a better approach. */
8521static const int remote_flash_timeout = 1000;
8522
8523static void
8524remote_flash_erase (struct target_ops *ops,
8525 ULONGEST address, LONGEST length)
8526{
f5656ead 8527 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 8528 enum packet_result ret;
2ec845e7
TT
8529 scoped_restore restore_timeout
8530 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
8531
8532 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8533 phex (address, addr_size),
a76d924d
DJ
8534 phex (length, 4));
8535 switch (ret)
8536 {
8537 case PACKET_UNKNOWN:
8538 error (_("Remote target does not support flash erase"));
8539 case PACKET_ERROR:
8540 error (_("Error erasing flash with vFlashErase packet"));
8541 default:
8542 break;
8543 }
a76d924d
DJ
8544}
8545
9b409511
YQ
8546static enum target_xfer_status
8547remote_flash_write (struct target_ops *ops, ULONGEST address,
8548 ULONGEST length, ULONGEST *xfered_len,
8549 const gdb_byte *data)
a76d924d 8550{
2ec845e7
TT
8551 scoped_restore restore_timeout
8552 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8553 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8554 xfered_len,'X', 0);
a76d924d
DJ
8555}
8556
8557static void
8558remote_flash_done (struct target_ops *ops)
8559{
a76d924d 8560 int ret;
a76d924d 8561
2ec845e7
TT
8562 scoped_restore restore_timeout
8563 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8564
a76d924d 8565 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
8566
8567 switch (ret)
8568 {
8569 case PACKET_UNKNOWN:
8570 error (_("Remote target does not support vFlashDone"));
8571 case PACKET_ERROR:
8572 error (_("Error finishing flash operation"));
8573 default:
8574 break;
8575 }
8576}
8577
c906108c 8578static void
fba45db2 8579remote_files_info (struct target_ops *ignore)
c906108c
SS
8580{
8581 puts_filtered ("Debugging a target over a serial line.\n");
8582}
8583\f
8584/* Stuff for dealing with the packets which are part of this protocol.
8585 See comment at top of file for details. */
8586
1927e618
PA
8587/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8588 error to higher layers. Called when a serial error is detected.
8589 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8590 the system error message for errno at function entry and final dot
8591 for output compatibility with throw_perror_with_name. */
1927e618
PA
8592
8593static void
8594unpush_and_perror (const char *string)
8595{
d6cb50a2 8596 int saved_errno = errno;
1927e618
PA
8597
8598 remote_unpush_target ();
d6cb50a2
JK
8599 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8600 safe_strerror (saved_errno));
1927e618
PA
8601}
8602
048094ac
PA
8603/* Read a single character from the remote end. The current quit
8604 handler is overridden to avoid quitting in the middle of packet
8605 sequence, as that would break communication with the remote server.
8606 See remote_serial_quit_handler for more detail. */
c906108c
SS
8607
8608static int
fba45db2 8609readchar (int timeout)
c906108c
SS
8610{
8611 int ch;
5d93a237 8612 struct remote_state *rs = get_remote_state ();
048094ac 8613
2ec845e7
TT
8614 {
8615 scoped_restore restore_quit
8616 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
c906108c 8617
2ec845e7 8618 rs->got_ctrlc_during_io = 0;
c906108c 8619
2ec845e7 8620 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 8621
2ec845e7
TT
8622 if (rs->got_ctrlc_during_io)
8623 set_quit_flag ();
8624 }
048094ac 8625
2acceee2 8626 if (ch >= 0)
0876f84a 8627 return ch;
2acceee2
JM
8628
8629 switch ((enum serial_rc) ch)
c906108c
SS
8630 {
8631 case SERIAL_EOF:
78a095c3 8632 remote_unpush_target ();
598d3636 8633 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8634 /* no return */
c906108c 8635 case SERIAL_ERROR:
1927e618
PA
8636 unpush_and_perror (_("Remote communication error. "
8637 "Target disconnected."));
2acceee2 8638 /* no return */
c906108c 8639 case SERIAL_TIMEOUT:
2acceee2 8640 break;
c906108c 8641 }
2acceee2 8642 return ch;
c906108c
SS
8643}
8644
c33e31fd 8645/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
8646 writing fails. The current quit handler is overridden to avoid
8647 quitting in the middle of packet sequence, as that would break
8648 communication with the remote server. See
8649 remote_serial_quit_handler for more detail. */
c33e31fd
PA
8650
8651static void
8652remote_serial_write (const char *str, int len)
8653{
5d93a237 8654 struct remote_state *rs = get_remote_state ();
048094ac 8655
2ec845e7
TT
8656 scoped_restore restore_quit
8657 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
048094ac
PA
8658
8659 rs->got_ctrlc_during_io = 0;
5d93a237
TT
8660
8661 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8662 {
1927e618
PA
8663 unpush_and_perror (_("Remote communication error. "
8664 "Target disconnected."));
c33e31fd 8665 }
048094ac
PA
8666
8667 if (rs->got_ctrlc_during_io)
8668 set_quit_flag ();
c33e31fd
PA
8669}
8670
6d820c5c
DJ
8671/* Send the command in *BUF to the remote machine, and read the reply
8672 into *BUF. Report an error if we get an error reply. Resize
8673 *BUF using xrealloc if necessary to hold the result, and update
8674 *SIZEOF_BUF. */
c906108c
SS
8675
8676static void
6d820c5c
DJ
8677remote_send (char **buf,
8678 long *sizeof_buf)
c906108c 8679{
6d820c5c 8680 putpkt (*buf);
c2d11a7d 8681 getpkt (buf, sizeof_buf, 0);
c906108c 8682
6d820c5c
DJ
8683 if ((*buf)[0] == 'E')
8684 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8685}
8686
b3ced9ba
PA
8687/* Return a string representing an escaped version of BUF, of len N.
8688 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 8689
b3ced9ba 8690static std::string
6e5abd65
PA
8691escape_buffer (const char *buf, int n)
8692{
d7e74731 8693 string_file stb;
6e5abd65 8694
d7e74731
PA
8695 stb.putstrn (buf, n, '\\');
8696 return std::move (stb.string ());
6e5abd65
PA
8697}
8698
c906108c
SS
8699/* Display a null-terminated packet on stdout, for debugging, using C
8700 string notation. */
8701
8702static void
baa336ce 8703print_packet (const char *buf)
c906108c
SS
8704{
8705 puts_filtered ("\"");
43e526b9 8706 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8707 puts_filtered ("\"");
8708}
8709
8710int
baa336ce 8711putpkt (const char *buf)
c906108c
SS
8712{
8713 return putpkt_binary (buf, strlen (buf));
8714}
8715
8716/* Send a packet to the remote machine, with error checking. The data
23860348 8717 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8718 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8719 and for a possible /0 if we are debugging (remote_debug) and want
8720 to print the sent packet as a string. */
c906108c
SS
8721
8722static int
baa336ce 8723putpkt_binary (const char *buf, int cnt)
c906108c 8724{
2d717e4f 8725 struct remote_state *rs = get_remote_state ();
c906108c
SS
8726 int i;
8727 unsigned char csum = 0;
b80406ac
TT
8728 gdb::def_vector<char> data (cnt + 6);
8729 char *buf2 = data.data ();
085dd6e6 8730
c906108c
SS
8731 int ch;
8732 int tcount = 0;
8733 char *p;
8734
e24a49d8
PA
8735 /* Catch cases like trying to read memory or listing threads while
8736 we're waiting for a stop reply. The remote server wouldn't be
8737 ready to handle this request, so we'd hang and timeout. We don't
8738 have to worry about this in synchronous mode, because in that
8739 case it's not possible to issue a command while the target is
74531fed
PA
8740 running. This is not a problem in non-stop mode, because in that
8741 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8742 if (!target_is_non_stop_p ()
8743 && target_is_async_p ()
8744 && rs->waiting_for_stop_reply)
9597b22a
DE
8745 {
8746 error (_("Cannot execute this command while the target is running.\n"
8747 "Use the \"interrupt\" command to stop the target\n"
8748 "and then try again."));
8749 }
e24a49d8 8750
2d717e4f
DJ
8751 /* We're sending out a new packet. Make sure we don't look at a
8752 stale cached response. */
8753 rs->cached_wait_status = 0;
8754
c906108c
SS
8755 /* Copy the packet into buffer BUF2, encapsulating it
8756 and giving it a checksum. */
8757
c906108c
SS
8758 p = buf2;
8759 *p++ = '$';
8760
8761 for (i = 0; i < cnt; i++)
8762 {
8763 csum += buf[i];
8764 *p++ = buf[i];
8765 }
8766 *p++ = '#';
8767 *p++ = tohex ((csum >> 4) & 0xf);
8768 *p++ = tohex (csum & 0xf);
8769
8770 /* Send it over and over until we get a positive ack. */
8771
8772 while (1)
8773 {
8774 int started_error_output = 0;
8775
8776 if (remote_debug)
8777 {
8778 *p = '\0';
b3ced9ba 8779
6f8976bf
YQ
8780 int len = (int) (p - buf2);
8781
8782 std::string str
8783 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8784
8785 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8786
8787 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
8788 {
8789 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
8790 str.length () - REMOTE_DEBUG_MAX_CHAR);
8791 }
8792
8793 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 8794
0f71a2f6 8795 gdb_flush (gdb_stdlog);
c906108c 8796 }
c33e31fd 8797 remote_serial_write (buf2, p - buf2);
c906108c 8798
a6f3e723
SL
8799 /* If this is a no acks version of the remote protocol, send the
8800 packet and move on. */
8801 if (rs->noack_mode)
8802 break;
8803
74531fed
PA
8804 /* Read until either a timeout occurs (-2) or '+' is read.
8805 Handle any notification that arrives in the mean time. */
c906108c
SS
8806 while (1)
8807 {
8808 ch = readchar (remote_timeout);
8809
c5aa993b 8810 if (remote_debug)
c906108c
SS
8811 {
8812 switch (ch)
8813 {
8814 case '+':
1216fa2c 8815 case '-':
c906108c
SS
8816 case SERIAL_TIMEOUT:
8817 case '$':
74531fed 8818 case '%':
c906108c
SS
8819 if (started_error_output)
8820 {
8821 putchar_unfiltered ('\n');
8822 started_error_output = 0;
8823 }
8824 }
8825 }
8826
8827 switch (ch)
8828 {
8829 case '+':
8830 if (remote_debug)
0f71a2f6 8831 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 8832 return 1;
1216fa2c
AC
8833 case '-':
8834 if (remote_debug)
8835 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8836 /* FALLTHROUGH */
c906108c 8837 case SERIAL_TIMEOUT:
c5aa993b 8838 tcount++;
c906108c 8839 if (tcount > 3)
b80406ac 8840 return 0;
23860348 8841 break; /* Retransmit buffer. */
c906108c
SS
8842 case '$':
8843 {
40e3f985 8844 if (remote_debug)
2bc416ba 8845 fprintf_unfiltered (gdb_stdlog,
23860348 8846 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8847 /* It's probably an old response sent because an ACK
8848 was lost. Gobble up the packet and ack it so it
8849 doesn't get retransmitted when we resend this
8850 packet. */
6d820c5c 8851 skip_frame ();
c33e31fd 8852 remote_serial_write ("+", 1);
23860348 8853 continue; /* Now, go look for +. */
c906108c 8854 }
74531fed
PA
8855
8856 case '%':
8857 {
8858 int val;
8859
8860 /* If we got a notification, handle it, and go back to looking
8861 for an ack. */
8862 /* We've found the start of a notification. Now
8863 collect the data. */
8864 val = read_frame (&rs->buf, &rs->buf_size);
8865 if (val >= 0)
8866 {
8867 if (remote_debug)
8868 {
b3ced9ba 8869 std::string str = escape_buffer (rs->buf, val);
6e5abd65 8870
6e5abd65
PA
8871 fprintf_unfiltered (gdb_stdlog,
8872 " Notification received: %s\n",
b3ced9ba 8873 str.c_str ());
74531fed 8874 }
5965e028 8875 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8876 /* We're in sync now, rewait for the ack. */
8877 tcount = 0;
8878 }
8879 else
8880 {
8881 if (remote_debug)
8882 {
8883 if (!started_error_output)
8884 {
8885 started_error_output = 1;
8886 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8887 }
8888 fputc_unfiltered (ch & 0177, gdb_stdlog);
8889 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8890 }
8891 }
8892 continue;
8893 }
8894 /* fall-through */
c906108c
SS
8895 default:
8896 if (remote_debug)
8897 {
8898 if (!started_error_output)
8899 {
8900 started_error_output = 1;
0f71a2f6 8901 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8902 }
0f71a2f6 8903 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8904 }
8905 continue;
8906 }
23860348 8907 break; /* Here to retransmit. */
c906108c
SS
8908 }
8909
8910#if 0
8911 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8912 able to get out next time we call QUIT, without anything as
8913 violent as interrupt_query. If we want to provide a way out of
8914 here without getting to the next QUIT, it should be based on
8915 hitting ^C twice as in remote_wait. */
c906108c
SS
8916 if (quit_flag)
8917 {
8918 quit_flag = 0;
8919 interrupt_query ();
8920 }
8921#endif
8922 }
a5c0808e 8923
a6f3e723 8924 return 0;
c906108c
SS
8925}
8926
6d820c5c
DJ
8927/* Come here after finding the start of a frame when we expected an
8928 ack. Do our best to discard the rest of this packet. */
8929
8930static void
8931skip_frame (void)
8932{
8933 int c;
8934
8935 while (1)
8936 {
8937 c = readchar (remote_timeout);
8938 switch (c)
8939 {
8940 case SERIAL_TIMEOUT:
8941 /* Nothing we can do. */
8942 return;
8943 case '#':
8944 /* Discard the two bytes of checksum and stop. */
8945 c = readchar (remote_timeout);
8946 if (c >= 0)
8947 c = readchar (remote_timeout);
8948
8949 return;
8950 case '*': /* Run length encoding. */
8951 /* Discard the repeat count. */
8952 c = readchar (remote_timeout);
8953 if (c < 0)
8954 return;
8955 break;
8956 default:
8957 /* A regular character. */
8958 break;
8959 }
8960 }
8961}
8962
c906108c 8963/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8964 into *BUF, verifying the checksum, length, and handling run-length
8965 compression. NUL terminate the buffer. If there is not enough room,
8966 expand *BUF using xrealloc.
c906108c 8967
c2d11a7d
JM
8968 Returns -1 on error, number of characters in buffer (ignoring the
8969 trailing NULL) on success. (could be extended to return one of the
23860348 8970 SERIAL status indications). */
c2d11a7d
JM
8971
8972static long
6d820c5c
DJ
8973read_frame (char **buf_p,
8974 long *sizeof_buf)
c906108c
SS
8975{
8976 unsigned char csum;
c2d11a7d 8977 long bc;
c906108c 8978 int c;
6d820c5c 8979 char *buf = *buf_p;
a6f3e723 8980 struct remote_state *rs = get_remote_state ();
c906108c
SS
8981
8982 csum = 0;
c2d11a7d 8983 bc = 0;
c906108c
SS
8984
8985 while (1)
8986 {
8987 c = readchar (remote_timeout);
c906108c
SS
8988 switch (c)
8989 {
8990 case SERIAL_TIMEOUT:
8991 if (remote_debug)
0f71a2f6 8992 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8993 return -1;
c906108c
SS
8994 case '$':
8995 if (remote_debug)
0f71a2f6
JM
8996 fputs_filtered ("Saw new packet start in middle of old one\n",
8997 gdb_stdlog);
23860348 8998 return -1; /* Start a new packet, count retries. */
c906108c
SS
8999 case '#':
9000 {
9001 unsigned char pktcsum;
e1b09194
AC
9002 int check_0 = 0;
9003 int check_1 = 0;
c906108c 9004
c2d11a7d 9005 buf[bc] = '\0';
c906108c 9006
e1b09194
AC
9007 check_0 = readchar (remote_timeout);
9008 if (check_0 >= 0)
9009 check_1 = readchar (remote_timeout);
802188a7 9010
e1b09194
AC
9011 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9012 {
9013 if (remote_debug)
2bc416ba 9014 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 9015 gdb_stdlog);
e1b09194
AC
9016 return -1;
9017 }
9018 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
9019 {
9020 if (remote_debug)
2bc416ba 9021 fputs_filtered ("Communication error in checksum\n",
23860348 9022 gdb_stdlog);
40e3f985
FN
9023 return -1;
9024 }
c906108c 9025
a6f3e723
SL
9026 /* Don't recompute the checksum; with no ack packets we
9027 don't have any way to indicate a packet retransmission
9028 is necessary. */
9029 if (rs->noack_mode)
9030 return bc;
9031
e1b09194 9032 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9033 if (csum == pktcsum)
c2d11a7d 9034 return bc;
c906108c 9035
c5aa993b 9036 if (remote_debug)
c906108c 9037 {
b3ced9ba 9038 std::string str = escape_buffer (buf, bc);
6e5abd65 9039
6e5abd65 9040 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9041 "Bad checksum, sentsum=0x%x, "
9042 "csum=0x%x, buf=%s\n",
b3ced9ba 9043 pktcsum, csum, str.c_str ());
c906108c 9044 }
c2d11a7d 9045 /* Number of characters in buffer ignoring trailing
23860348 9046 NULL. */
c2d11a7d 9047 return -1;
c906108c 9048 }
23860348 9049 case '*': /* Run length encoding. */
c2c6d25f
JM
9050 {
9051 int repeat;
c906108c 9052
a744cf53 9053 csum += c;
b4501125
AC
9054 c = readchar (remote_timeout);
9055 csum += c;
23860348 9056 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9057
23860348 9058 /* The character before ``*'' is repeated. */
c2d11a7d 9059
6d820c5c 9060 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9061 {
6d820c5c
DJ
9062 if (bc + repeat - 1 >= *sizeof_buf - 1)
9063 {
9064 /* Make some more room in the buffer. */
9065 *sizeof_buf += repeat;
224c3ddb 9066 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
9067 buf = *buf_p;
9068 }
9069
c2d11a7d
JM
9070 memset (&buf[bc], buf[bc - 1], repeat);
9071 bc += repeat;
c2c6d25f
JM
9072 continue;
9073 }
9074
c2d11a7d 9075 buf[bc] = '\0';
6d820c5c 9076 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9077 return -1;
c2c6d25f 9078 }
c906108c 9079 default:
6d820c5c 9080 if (bc >= *sizeof_buf - 1)
c906108c 9081 {
6d820c5c
DJ
9082 /* Make some more room in the buffer. */
9083 *sizeof_buf *= 2;
224c3ddb 9084 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 9085 buf = *buf_p;
c906108c
SS
9086 }
9087
6d820c5c
DJ
9088 buf[bc++] = c;
9089 csum += c;
9090 continue;
c906108c
SS
9091 }
9092 }
9093}
9094
9095/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9096 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9097 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9098 rather than timing out; this is used (in synchronous mode) to wait
9099 for a target that is is executing user code to stop. */
d9fcf2fb
JM
9100/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9101 don't have to change all the calls to getpkt to deal with the
9102 return value, because at the moment I don't know what the right
23860348 9103 thing to do it for those. */
c906108c 9104void
6d820c5c
DJ
9105getpkt (char **buf,
9106 long *sizeof_buf,
c2d11a7d 9107 int forever)
d9fcf2fb 9108{
54887903 9109 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
9110}
9111
9112
9113/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9114 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9115 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9116 rather than timing out; this is used (in synchronous mode) to wait
9117 for a target that is is executing user code to stop. If FOREVER ==
9118 0, this function is allowed to time out gracefully and return an
74531fed
PA
9119 indication of this to the caller. Otherwise return the number of
9120 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
9121 enough reason to return to the caller. *IS_NOTIF is an output
9122 boolean that indicates whether *BUF holds a notification or not
9123 (a regular packet). */
74531fed 9124
3172dc30 9125static int
74531fed 9126getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 9127 int expecting_notif, int *is_notif)
c906108c 9128{
2d717e4f 9129 struct remote_state *rs = get_remote_state ();
c906108c
SS
9130 int c;
9131 int tries;
9132 int timeout;
df4b58fe 9133 int val = -1;
c906108c 9134
2d717e4f
DJ
9135 /* We're reading a new response. Make sure we don't look at a
9136 previously cached response. */
9137 rs->cached_wait_status = 0;
9138
6d820c5c 9139 strcpy (*buf, "timeout");
c906108c
SS
9140
9141 if (forever)
74531fed
PA
9142 timeout = watchdog > 0 ? watchdog : -1;
9143 else if (expecting_notif)
9144 timeout = 0; /* There should already be a char in the buffer. If
9145 not, bail out. */
c906108c
SS
9146 else
9147 timeout = remote_timeout;
9148
9149#define MAX_TRIES 3
9150
74531fed
PA
9151 /* Process any number of notifications, and then return when
9152 we get a packet. */
9153 for (;;)
c906108c 9154 {
d9c43928 9155 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9156 times. */
9157 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9158 {
74531fed
PA
9159 /* This can loop forever if the remote side sends us
9160 characters continuously, but if it pauses, we'll get
9161 SERIAL_TIMEOUT from readchar because of timeout. Then
9162 we'll count that as a retry.
9163
9164 Note that even when forever is set, we will only wait
9165 forever prior to the start of a packet. After that, we
9166 expect characters to arrive at a brisk pace. They should
9167 show up within remote_timeout intervals. */
9168 do
9169 c = readchar (timeout);
9170 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9171
9172 if (c == SERIAL_TIMEOUT)
9173 {
74531fed
PA
9174 if (expecting_notif)
9175 return -1; /* Don't complain, it's normal to not get
9176 anything in this case. */
9177
23860348 9178 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9179 {
78a095c3 9180 remote_unpush_target ();
598d3636
JK
9181 throw_error (TARGET_CLOSE_ERROR,
9182 _("Watchdog timeout has expired. "
9183 "Target detached."));
c906108c 9184 }
c906108c 9185 if (remote_debug)
0f71a2f6 9186 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9187 }
74531fed
PA
9188 else
9189 {
9190 /* We've found the start of a packet or notification.
9191 Now collect the data. */
9192 val = read_frame (buf, sizeof_buf);
9193 if (val >= 0)
9194 break;
9195 }
9196
c33e31fd 9197 remote_serial_write ("-", 1);
c906108c 9198 }
c906108c 9199
74531fed
PA
9200 if (tries > MAX_TRIES)
9201 {
9202 /* We have tried hard enough, and just can't receive the
9203 packet/notification. Give up. */
9204 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9205
74531fed
PA
9206 /* Skip the ack char if we're in no-ack mode. */
9207 if (!rs->noack_mode)
c33e31fd 9208 remote_serial_write ("+", 1);
74531fed
PA
9209 return -1;
9210 }
c906108c 9211
74531fed
PA
9212 /* If we got an ordinary packet, return that to our caller. */
9213 if (c == '$')
c906108c
SS
9214 {
9215 if (remote_debug)
43e526b9 9216 {
6f8976bf
YQ
9217 std::string str
9218 = escape_buffer (*buf,
9219 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9220
9221 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9222 str.c_str ());
9223
9224 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
9225 {
9226 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
9227 str.length () - REMOTE_DEBUG_MAX_CHAR);
9228 }
6e5abd65 9229
6f8976bf 9230 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9231 }
a6f3e723
SL
9232
9233 /* Skip the ack char if we're in no-ack mode. */
9234 if (!rs->noack_mode)
c33e31fd 9235 remote_serial_write ("+", 1);
fee9eda9
YQ
9236 if (is_notif != NULL)
9237 *is_notif = 0;
0876f84a 9238 return val;
c906108c
SS
9239 }
9240
74531fed
PA
9241 /* If we got a notification, handle it, and go back to looking
9242 for a packet. */
9243 else
9244 {
9245 gdb_assert (c == '%');
9246
9247 if (remote_debug)
9248 {
b3ced9ba 9249 std::string str = escape_buffer (*buf, val);
6e5abd65 9250
6e5abd65
PA
9251 fprintf_unfiltered (gdb_stdlog,
9252 " Notification received: %s\n",
b3ced9ba 9253 str.c_str ());
74531fed 9254 }
fee9eda9
YQ
9255 if (is_notif != NULL)
9256 *is_notif = 1;
c906108c 9257
5965e028 9258 handle_notification (rs->notif_state, *buf);
c906108c 9259
74531fed 9260 /* Notifications require no acknowledgement. */
a6f3e723 9261
74531fed 9262 if (expecting_notif)
fee9eda9 9263 return val;
74531fed
PA
9264 }
9265 }
9266}
9267
9268static int
9269getpkt_sane (char **buf, long *sizeof_buf, int forever)
9270{
fee9eda9 9271 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
9272}
9273
9274static int
fee9eda9
YQ
9275getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9276 int *is_notif)
74531fed 9277{
fee9eda9
YQ
9278 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9279 is_notif);
c906108c 9280}
74531fed 9281
cbb8991c
DB
9282/* Check whether EVENT is a fork event for the process specified
9283 by the pid passed in DATA, and if it is, kill the fork child. */
9284
9285static int
9286kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9287 QUEUE_ITER (stop_reply_p) *iter,
9288 stop_reply_p event,
9289 void *data)
9290{
19ba03f4 9291 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
9292 int parent_pid = *(int *) param->input;
9293
9294 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9295 {
9296 struct remote_state *rs = get_remote_state ();
9297 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9298 int res;
9299
9300 res = remote_vkill (child_pid, rs);
9301 if (res != 0)
9302 error (_("Can't kill fork child process %d"), child_pid);
9303 }
9304
9305 return 1;
9306}
9307
9308/* Kill any new fork children of process PID that haven't been
9309 processed by follow_fork. */
9310
9311static void
9312kill_new_fork_children (int pid, struct remote_state *rs)
9313{
9314 struct thread_info *thread;
9315 struct notif_client *notif = &notif_client_stop;
9316 struct queue_iter_param param;
9317
9318 /* Kill the fork child threads of any threads in process PID
9319 that are stopped at a fork event. */
9320 ALL_NON_EXITED_THREADS (thread)
9321 {
9322 struct target_waitstatus *ws = &thread->pending_follow;
9323
9324 if (is_pending_fork_parent (ws, pid, thread->ptid))
9325 {
9326 struct remote_state *rs = get_remote_state ();
9327 int child_pid = ptid_get_pid (ws->value.related_pid);
9328 int res;
9329
9330 res = remote_vkill (child_pid, rs);
9331 if (res != 0)
9332 error (_("Can't kill fork child process %d"), child_pid);
9333 }
9334 }
9335
9336 /* Check for any pending fork events (not reported or processed yet)
9337 in process PID and kill those fork child threads as well. */
9338 remote_notif_get_pending_events (notif);
9339 param.input = &pid;
9340 param.output = NULL;
9341 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9342 kill_child_of_pending_fork, &param);
9343}
9344
c906108c 9345\f
8020350c
DB
9346/* Target hook to kill the current inferior. */
9347
c906108c 9348static void
7d85a9c0 9349remote_kill (struct target_ops *ops)
43ff13b4 9350{
8020350c
DB
9351 int res = -1;
9352 int pid = ptid_get_pid (inferior_ptid);
9353 struct remote_state *rs = get_remote_state ();
0fdf84ca 9354
8020350c 9355 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9356 {
8020350c
DB
9357 /* If we're stopped while forking and we haven't followed yet,
9358 kill the child task. We need to do this before killing the
9359 parent task because if this is a vfork then the parent will
9360 be sleeping. */
9361 kill_new_fork_children (pid, rs);
9362
9363 res = remote_vkill (pid, rs);
9364 if (res == 0)
0fdf84ca 9365 {
bc1e6c81 9366 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9367 return;
9368 }
8020350c 9369 }
0fdf84ca 9370
8020350c
DB
9371 /* If we are in 'target remote' mode and we are killing the only
9372 inferior, then we will tell gdbserver to exit and unpush the
9373 target. */
9374 if (res == -1 && !remote_multi_process_p (rs)
9375 && number_of_live_inferiors () == 1)
9376 {
9377 remote_kill_k ();
9378
9379 /* We've killed the remote end, we get to mourn it. If we are
9380 not in extended mode, mourning the inferior also unpushes
9381 remote_ops from the target stack, which closes the remote
9382 connection. */
bc1e6c81 9383 target_mourn_inferior (inferior_ptid);
8020350c
DB
9384
9385 return;
0fdf84ca 9386 }
43ff13b4 9387
8020350c 9388 error (_("Can't kill process"));
43ff13b4
JM
9389}
9390
8020350c
DB
9391/* Send a kill request to the target using the 'vKill' packet. */
9392
82f73884
PA
9393static int
9394remote_vkill (int pid, struct remote_state *rs)
9395{
4082afcc 9396 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9397 return -1;
9398
9399 /* Tell the remote target to detach. */
bba74b36 9400 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
9401 putpkt (rs->buf);
9402 getpkt (&rs->buf, &rs->buf_size, 0);
9403
4082afcc
PA
9404 switch (packet_ok (rs->buf,
9405 &remote_protocol_packets[PACKET_vKill]))
9406 {
9407 case PACKET_OK:
9408 return 0;
9409 case PACKET_ERROR:
9410 return 1;
9411 case PACKET_UNKNOWN:
9412 return -1;
9413 default:
9414 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9415 }
82f73884
PA
9416}
9417
8020350c
DB
9418/* Send a kill request to the target using the 'k' packet. */
9419
82f73884 9420static void
8020350c 9421remote_kill_k (void)
82f73884 9422{
8020350c
DB
9423 /* Catch errors so the user can quit from gdb even when we
9424 aren't on speaking terms with the remote system. */
9425 TRY
82f73884 9426 {
82f73884 9427 putpkt ("k");
82f73884 9428 }
8020350c
DB
9429 CATCH (ex, RETURN_MASK_ERROR)
9430 {
9431 if (ex.error == TARGET_CLOSE_ERROR)
9432 {
9433 /* If we got an (EOF) error that caused the target
9434 to go away, then we're done, that's what we wanted.
9435 "k" is susceptible to cause a premature EOF, given
9436 that the remote server isn't actually required to
9437 reply to "k", and it can happen that it doesn't
9438 even get to reply ACK to the "k". */
9439 return;
9440 }
82f73884 9441
8020350c
DB
9442 /* Otherwise, something went wrong. We didn't actually kill
9443 the target. Just propagate the exception, and let the
9444 user or higher layers decide what to do. */
9445 throw_exception (ex);
9446 }
9447 END_CATCH
82f73884
PA
9448}
9449
c906108c 9450static void
20f796c9 9451remote_mourn (struct target_ops *target)
c906108c 9452{
8020350c 9453 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9454
8020350c
DB
9455 /* In 'target remote' mode with one inferior, we close the connection. */
9456 if (!rs->extended && number_of_live_inferiors () <= 1)
9457 {
9458 unpush_target (target);
c906108c 9459
8020350c
DB
9460 /* remote_close takes care of doing most of the clean up. */
9461 generic_mourn_inferior ();
9462 return;
9463 }
c906108c 9464
e24a49d8
PA
9465 /* In case we got here due to an error, but we're going to stay
9466 connected. */
9467 rs->waiting_for_stop_reply = 0;
9468
dc1981d7
PA
9469 /* If the current general thread belonged to the process we just
9470 detached from or has exited, the remote side current general
9471 thread becomes undefined. Considering a case like this:
9472
9473 - We just got here due to a detach.
9474 - The process that we're detaching from happens to immediately
9475 report a global breakpoint being hit in non-stop mode, in the
9476 same thread we had selected before.
9477 - GDB attaches to this process again.
9478 - This event happens to be the next event we handle.
9479
9480 GDB would consider that the current general thread didn't need to
9481 be set on the stub side (with Hg), since for all it knew,
9482 GENERAL_THREAD hadn't changed.
9483
9484 Notice that although in all-stop mode, the remote server always
9485 sets the current thread to the thread reporting the stop event,
9486 that doesn't happen in non-stop mode; in non-stop, the stub *must
9487 not* change the current thread when reporting a breakpoint hit,
9488 due to the decoupling of event reporting and event handling.
9489
9490 To keep things simple, we always invalidate our notion of the
9491 current thread. */
47f8a51d 9492 record_currthread (rs, minus_one_ptid);
dc1981d7 9493
8020350c 9494 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9495 generic_mourn_inferior ();
9496
d729566a 9497 if (!have_inferiors ())
2d717e4f 9498 {
82f73884
PA
9499 if (!remote_multi_process_p (rs))
9500 {
9501 /* Check whether the target is running now - some remote stubs
9502 automatically restart after kill. */
9503 putpkt ("?");
9504 getpkt (&rs->buf, &rs->buf_size, 0);
9505
9506 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9507 {
3e43a32a
MS
9508 /* Assume that the target has been restarted. Set
9509 inferior_ptid so that bits of core GDB realizes
9510 there's something here, e.g., so that the user can
9511 say "kill" again. */
82f73884
PA
9512 inferior_ptid = magic_null_ptid;
9513 }
82f73884 9514 }
2d717e4f
DJ
9515 }
9516}
c906108c 9517
03583c20 9518static int
2bfc0540 9519extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 9520{
4082afcc 9521 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9522}
9523
9524static void
9525extended_remote_disable_randomization (int val)
9526{
9527 struct remote_state *rs = get_remote_state ();
9528 char *reply;
9529
bba74b36
YQ
9530 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9531 val);
03583c20 9532 putpkt (rs->buf);
b6bb3468 9533 reply = remote_get_noisy_reply ();
03583c20
UW
9534 if (*reply == '\0')
9535 error (_("Target does not support QDisableRandomization."));
9536 if (strcmp (reply, "OK") != 0)
9537 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9538}
9539
2d717e4f 9540static int
7c5ded6a 9541extended_remote_run (const std::string &args)
2d717e4f
DJ
9542{
9543 struct remote_state *rs = get_remote_state ();
2d717e4f 9544 int len;
94585166 9545 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9546
2d717e4f
DJ
9547 /* If the user has disabled vRun support, or we have detected that
9548 support is not available, do not try it. */
4082afcc 9549 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9550 return -1;
424163ea 9551
2d717e4f
DJ
9552 strcpy (rs->buf, "vRun;");
9553 len = strlen (rs->buf);
c906108c 9554
2d717e4f
DJ
9555 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9556 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9557 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9558 strlen (remote_exec_file));
2d717e4f 9559
7c5ded6a 9560 if (!args.empty ())
2d717e4f 9561 {
2d717e4f 9562 int i;
2d717e4f 9563
773a1edc 9564 gdb_argv argv (args.c_str ());
2d717e4f
DJ
9565 for (i = 0; argv[i] != NULL; i++)
9566 {
9567 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9568 error (_("Argument list too long for run packet"));
9569 rs->buf[len++] = ';';
9f1b45b0
TT
9570 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9571 strlen (argv[i]));
2d717e4f 9572 }
2d717e4f
DJ
9573 }
9574
9575 rs->buf[len++] = '\0';
9576
9577 putpkt (rs->buf);
9578 getpkt (&rs->buf, &rs->buf_size, 0);
9579
4082afcc 9580 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9581 {
4082afcc 9582 case PACKET_OK:
3405876a 9583 /* We have a wait response. All is well. */
2d717e4f 9584 return 0;
4082afcc
PA
9585 case PACKET_UNKNOWN:
9586 return -1;
9587 case PACKET_ERROR:
2d717e4f
DJ
9588 if (remote_exec_file[0] == '\0')
9589 error (_("Running the default executable on the remote target failed; "
9590 "try \"set remote exec-file\"?"));
9591 else
9592 error (_("Running \"%s\" on the remote target failed"),
9593 remote_exec_file);
4082afcc
PA
9594 default:
9595 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9596 }
c906108c
SS
9597}
9598
0a2dde4a
SDJ
9599/* Helper function to send set/unset environment packets. ACTION is
9600 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9601 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9602 sent. */
9603
9604static void
9605send_environment_packet (struct remote_state *rs,
9606 const char *action,
9607 const char *packet,
9608 const char *value)
9609{
9610 /* Convert the environment variable to an hex string, which
9611 is the best format to be transmitted over the wire. */
9612 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9613 strlen (value));
9614
9615 xsnprintf (rs->buf, get_remote_packet_size (),
9616 "%s:%s", packet, encoded_value.c_str ());
9617
9618 putpkt (rs->buf);
9619 getpkt (&rs->buf, &rs->buf_size, 0);
9620 if (strcmp (rs->buf, "OK") != 0)
9621 warning (_("Unable to %s environment variable '%s' on remote."),
9622 action, value);
9623}
9624
9625/* Helper function to handle the QEnvironment* packets. */
9626
9627static void
9628extended_remote_environment_support (struct remote_state *rs)
9629{
9630 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9631 {
9632 putpkt ("QEnvironmentReset");
9633 getpkt (&rs->buf, &rs->buf_size, 0);
9634 if (strcmp (rs->buf, "OK") != 0)
9635 warning (_("Unable to reset environment on remote."));
9636 }
9637
9638 gdb_environ *e = &current_inferior ()->environment;
9639
9640 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9641 for (const std::string &el : e->user_set_env ())
9642 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9643 el.c_str ());
9644
9645 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9646 for (const std::string &el : e->user_unset_env ())
9647 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9648}
9649
bc3b087d
SDJ
9650/* Helper function to set the current working directory for the
9651 inferior in the remote target. */
9652
9653static void
9654extended_remote_set_inferior_cwd (struct remote_state *rs)
9655{
9656 if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9657 {
9658 const char *inferior_cwd = get_inferior_cwd ();
9659
9660 if (inferior_cwd != NULL)
9661 {
9662 std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9663 strlen (inferior_cwd));
9664
9665 xsnprintf (rs->buf, get_remote_packet_size (),
9666 "QSetWorkingDir:%s", hexpath.c_str ());
9667 }
9668 else
9669 {
9670 /* An empty inferior_cwd means that the user wants us to
9671 reset the remote server's inferior's cwd. */
9672 xsnprintf (rs->buf, get_remote_packet_size (),
9673 "QSetWorkingDir:");
9674 }
9675
9676 putpkt (rs->buf);
9677 getpkt (&rs->buf, &rs->buf_size, 0);
9678 if (packet_ok (rs->buf,
9679 &remote_protocol_packets[PACKET_QSetWorkingDir])
9680 != PACKET_OK)
9681 error (_("\
9682Remote replied unexpectedly while setting the inferior's working\n\
9683directory: %s"),
9684 rs->buf);
9685
9686 }
9687}
9688
2d717e4f
DJ
9689/* In the extended protocol we want to be able to do things like
9690 "run" and have them basically work as expected. So we need
9691 a special create_inferior function. We support changing the
9692 executable file and the command line arguments, but not the
9693 environment. */
9694
43ff13b4 9695static void
77a19445 9696extended_remote_create_inferior (struct target_ops *ops,
7c5ded6a
SDJ
9697 const char *exec_file,
9698 const std::string &args,
77a19445 9699 char **env, int from_tty)
43ff13b4 9700{
3405876a
PA
9701 int run_worked;
9702 char *stop_reply;
9703 struct remote_state *rs = get_remote_state ();
94585166 9704 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9705
43ff13b4 9706 /* If running asynchronously, register the target file descriptor
23860348 9707 with the event loop. */
75c99385 9708 if (target_can_async_p ())
6a3753b3 9709 target_async (1);
43ff13b4 9710
03583c20 9711 /* Disable address space randomization if requested (and supported). */
2bfc0540 9712 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9713 extended_remote_disable_randomization (disable_randomization);
9714
aefd8b33
SDJ
9715 /* If startup-with-shell is on, we inform gdbserver to start the
9716 remote inferior using a shell. */
9717 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9718 {
9719 xsnprintf (rs->buf, get_remote_packet_size (),
9720 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9721 putpkt (rs->buf);
9722 getpkt (&rs->buf, &rs->buf_size, 0);
9723 if (strcmp (rs->buf, "OK") != 0)
9724 error (_("\
9725Remote replied unexpectedly while setting startup-with-shell: %s"),
9726 rs->buf);
9727 }
9728
0a2dde4a
SDJ
9729 extended_remote_environment_support (rs);
9730
bc3b087d
SDJ
9731 extended_remote_set_inferior_cwd (rs);
9732
43ff13b4 9733 /* Now restart the remote server. */
3405876a
PA
9734 run_worked = extended_remote_run (args) != -1;
9735 if (!run_worked)
2d717e4f
DJ
9736 {
9737 /* vRun was not supported. Fail if we need it to do what the
9738 user requested. */
9739 if (remote_exec_file[0])
9740 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 9741 if (!args.empty ())
2d717e4f 9742 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9743
2d717e4f
DJ
9744 /* Fall back to "R". */
9745 extended_remote_restart ();
9746 }
424163ea 9747
6c95b8df
PA
9748 if (!have_inferiors ())
9749 {
9750 /* Clean up from the last time we ran, before we mark the target
9751 running again. This will mark breakpoints uninserted, and
9752 get_offsets may insert breakpoints. */
9753 init_thread_list ();
9754 init_wait_for_inferior ();
9755 }
45280a52 9756
3405876a
PA
9757 /* vRun's success return is a stop reply. */
9758 stop_reply = run_worked ? rs->buf : NULL;
9759 add_current_inferior_and_thread (stop_reply);
c0a2216e 9760
2d717e4f
DJ
9761 /* Get updated offsets, if the stub uses qOffsets. */
9762 get_offsets ();
2d717e4f 9763}
c906108c 9764\f
c5aa993b 9765
b775012e
LM
9766/* Given a location's target info BP_TGT and the packet buffer BUF, output
9767 the list of conditions (in agent expression bytecode format), if any, the
9768 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9769 started from BUF and ended at BUF_END. */
b775012e
LM
9770
9771static int
9772remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9773 struct bp_target_info *bp_tgt, char *buf,
9774 char *buf_end)
b775012e 9775{
3cde5c42 9776 if (bp_tgt->conditions.empty ())
b775012e
LM
9777 return 0;
9778
9779 buf += strlen (buf);
bba74b36 9780 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9781 buf++;
9782
83621223 9783 /* Send conditions to the target. */
d538e36d 9784 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 9785 {
bba74b36 9786 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 9787 buf += strlen (buf);
3cde5c42 9788 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
9789 buf = pack_hex_byte (buf, aexpr->buf[i]);
9790 *buf = '\0';
9791 }
b775012e
LM
9792 return 0;
9793}
9794
d3ce09f5
SS
9795static void
9796remote_add_target_side_commands (struct gdbarch *gdbarch,
9797 struct bp_target_info *bp_tgt, char *buf)
9798{
3cde5c42 9799 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
9800 return;
9801
9802 buf += strlen (buf);
9803
9804 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9805 buf += strlen (buf);
9806
9807 /* Concatenate all the agent expressions that are commands into the
9808 cmds parameter. */
df97be55 9809 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
9810 {
9811 sprintf (buf, "X%x,", aexpr->len);
9812 buf += strlen (buf);
3cde5c42 9813 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
9814 buf = pack_hex_byte (buf, aexpr->buf[i]);
9815 *buf = '\0';
9816 }
d3ce09f5
SS
9817}
9818
8181d85f
DJ
9819/* Insert a breakpoint. On targets that have software breakpoint
9820 support, we ask the remote target to do the work; on targets
9821 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9822
9823static int
3db08215
MM
9824remote_insert_breakpoint (struct target_ops *ops,
9825 struct gdbarch *gdbarch,
a6d9a66e 9826 struct bp_target_info *bp_tgt)
c906108c 9827{
d471ea57
AC
9828 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9829 If it succeeds, then set the support to PACKET_ENABLE. If it
9830 fails, and the user has explicitly requested the Z support then
23860348 9831 report an error, otherwise, mark it disabled and go on. */
802188a7 9832
4082afcc 9833 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9834 {
0d5ed153 9835 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9836 struct remote_state *rs;
bba74b36 9837 char *p, *endbuf;
7c0f6dcc 9838 int bpsize;
4fff2411 9839
28439a30
PA
9840 /* Make sure the remote is pointing at the right process, if
9841 necessary. */
9842 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9843 set_general_process ();
9844
4fff2411
JZ
9845 rs = get_remote_state ();
9846 p = rs->buf;
bba74b36 9847 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9848
96baa820
JM
9849 *(p++) = 'Z';
9850 *(p++) = '0';
9851 *(p++) = ',';
7c0f6dcc 9852 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9853 p += hexnumstr (p, addr);
579c6ad9 9854 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 9855
efcc2da7 9856 if (remote_supports_cond_breakpoints (ops))
bba74b36 9857 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9858
78eff0ec 9859 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9860 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9861
6d820c5c
DJ
9862 putpkt (rs->buf);
9863 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9864
6d820c5c 9865 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9866 {
d471ea57
AC
9867 case PACKET_ERROR:
9868 return -1;
9869 case PACKET_OK:
9870 return 0;
9871 case PACKET_UNKNOWN:
9872 break;
96baa820
JM
9873 }
9874 }
c906108c 9875
0000e5cc
PA
9876 /* If this breakpoint has target-side commands but this stub doesn't
9877 support Z0 packets, throw error. */
3cde5c42 9878 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
9879 throw_error (NOT_SUPPORTED_ERROR, _("\
9880Target doesn't support breakpoints that have target side commands."));
9881
3db08215 9882 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9883}
9884
9885static int
3db08215
MM
9886remote_remove_breakpoint (struct target_ops *ops,
9887 struct gdbarch *gdbarch,
73971819
PA
9888 struct bp_target_info *bp_tgt,
9889 enum remove_bp_reason reason)
c906108c 9890{
8181d85f 9891 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9892 struct remote_state *rs = get_remote_state ();
96baa820 9893
4082afcc 9894 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9895 {
6d820c5c 9896 char *p = rs->buf;
bba74b36 9897 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9898
28439a30
PA
9899 /* Make sure the remote is pointing at the right process, if
9900 necessary. */
9901 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9902 set_general_process ();
9903
96baa820
JM
9904 *(p++) = 'z';
9905 *(p++) = '0';
9906 *(p++) = ',';
9907
8181d85f
DJ
9908 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9909 p += hexnumstr (p, addr);
579c6ad9 9910 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 9911
6d820c5c
DJ
9912 putpkt (rs->buf);
9913 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9914
6d820c5c 9915 return (rs->buf[0] == 'E');
96baa820
JM
9916 }
9917
73971819 9918 return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
c906108c
SS
9919}
9920
f486487f 9921static enum Z_packet_type
d471ea57
AC
9922watchpoint_to_Z_packet (int type)
9923{
9924 switch (type)
9925 {
9926 case hw_write:
bb858e6a 9927 return Z_PACKET_WRITE_WP;
d471ea57
AC
9928 break;
9929 case hw_read:
bb858e6a 9930 return Z_PACKET_READ_WP;
d471ea57
AC
9931 break;
9932 case hw_access:
bb858e6a 9933 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9934 break;
9935 default:
8e65ff28 9936 internal_error (__FILE__, __LINE__,
e2e0b3e5 9937 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9938 }
9939}
9940
3c3bea1c 9941static int
f486487f
SM
9942remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9943 enum target_hw_bp_type type, struct expression *cond)
96baa820 9944{
d01949b6 9945 struct remote_state *rs = get_remote_state ();
bba74b36 9946 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9947 char *p;
d471ea57 9948 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9949
4082afcc 9950 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9951 return 1;
802188a7 9952
28439a30
PA
9953 /* Make sure the remote is pointing at the right process, if
9954 necessary. */
9955 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9956 set_general_process ();
9957
bba74b36 9958 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9959 p = strchr (rs->buf, '\0');
96baa820
JM
9960 addr = remote_address_masked (addr);
9961 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9962 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9963
6d820c5c
DJ
9964 putpkt (rs->buf);
9965 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9966
6d820c5c 9967 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9968 {
9969 case PACKET_ERROR:
d471ea57 9970 return -1;
85d721b8
PA
9971 case PACKET_UNKNOWN:
9972 return 1;
d471ea57
AC
9973 case PACKET_OK:
9974 return 0;
9975 }
8e65ff28 9976 internal_error (__FILE__, __LINE__,
e2e0b3e5 9977 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9978}
9979
283002cf
MR
9980static int
9981remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9982 CORE_ADDR start, int length)
9983{
9984 CORE_ADDR diff = remote_address_masked (addr - start);
9985
9986 return diff < length;
9987}
9988
d471ea57 9989
3c3bea1c 9990static int
f486487f
SM
9991remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9992 enum target_hw_bp_type type, struct expression *cond)
96baa820 9993{
d01949b6 9994 struct remote_state *rs = get_remote_state ();
bba74b36 9995 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9996 char *p;
d471ea57
AC
9997 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9998
4082afcc 9999 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 10000 return -1;
802188a7 10001
28439a30
PA
10002 /* Make sure the remote is pointing at the right process, if
10003 necessary. */
10004 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10005 set_general_process ();
10006
bba74b36 10007 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 10008 p = strchr (rs->buf, '\0');
96baa820
JM
10009 addr = remote_address_masked (addr);
10010 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10011 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
10012 putpkt (rs->buf);
10013 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10014
6d820c5c 10015 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
10016 {
10017 case PACKET_ERROR:
10018 case PACKET_UNKNOWN:
10019 return -1;
10020 case PACKET_OK:
10021 return 0;
10022 }
8e65ff28 10023 internal_error (__FILE__, __LINE__,
e2e0b3e5 10024 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
10025}
10026
3c3bea1c 10027
501eef12 10028int remote_hw_watchpoint_limit = -1;
480a3f21 10029int remote_hw_watchpoint_length_limit = -1;
501eef12 10030int remote_hw_breakpoint_limit = -1;
d471ea57 10031
480a3f21 10032static int
31568a15
TT
10033remote_region_ok_for_hw_watchpoint (struct target_ops *self,
10034 CORE_ADDR addr, int len)
480a3f21
PW
10035{
10036 if (remote_hw_watchpoint_length_limit == 0)
10037 return 0;
10038 else if (remote_hw_watchpoint_length_limit < 0)
10039 return 1;
10040 else if (len <= remote_hw_watchpoint_length_limit)
10041 return 1;
10042 else
10043 return 0;
10044}
10045
b9362cc7 10046static int
5461485a 10047remote_check_watch_resources (struct target_ops *self,
f486487f 10048 enum bptype type, int cnt, int ot)
96baa820 10049{
3c3bea1c
GS
10050 if (type == bp_hardware_breakpoint)
10051 {
10052 if (remote_hw_breakpoint_limit == 0)
10053 return 0;
501eef12
AC
10054 else if (remote_hw_breakpoint_limit < 0)
10055 return 1;
3c3bea1c
GS
10056 else if (cnt <= remote_hw_breakpoint_limit)
10057 return 1;
10058 }
10059 else
10060 {
10061 if (remote_hw_watchpoint_limit == 0)
10062 return 0;
501eef12
AC
10063 else if (remote_hw_watchpoint_limit < 0)
10064 return 1;
3c3bea1c
GS
10065 else if (ot)
10066 return -1;
10067 else if (cnt <= remote_hw_watchpoint_limit)
10068 return 1;
10069 }
10070 return -1;
10071}
10072
f7e6eed5
PA
10073/* The to_stopped_by_sw_breakpoint method of target remote. */
10074
10075static int
10076remote_stopped_by_sw_breakpoint (struct target_ops *ops)
10077{
799a2abe 10078 struct thread_info *thread = inferior_thread ();
f7e6eed5 10079
799a2abe
PA
10080 return (thread->priv != NULL
10081 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
10082}
10083
10084/* The to_supports_stopped_by_sw_breakpoint method of target
10085 remote. */
10086
10087static int
10088remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
10089{
f7e6eed5
PA
10090 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10091}
10092
10093/* The to_stopped_by_hw_breakpoint method of target remote. */
10094
10095static int
10096remote_stopped_by_hw_breakpoint (struct target_ops *ops)
10097{
799a2abe 10098 struct thread_info *thread = inferior_thread ();
f7e6eed5 10099
799a2abe
PA
10100 return (thread->priv != NULL
10101 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
10102}
10103
10104/* The to_supports_stopped_by_hw_breakpoint method of target
10105 remote. */
10106
10107static int
10108remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
10109{
f7e6eed5
PA
10110 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10111}
10112
b9362cc7 10113static int
6a109b6b 10114remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 10115{
799a2abe 10116 struct thread_info *thread = inferior_thread ();
ee154bee 10117
799a2abe
PA
10118 return (thread->priv != NULL
10119 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
10120}
10121
4aa7a7f5
JJ
10122static int
10123remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 10124{
799a2abe 10125 struct thread_info *thread = inferior_thread ();
a744cf53 10126
799a2abe
PA
10127 if (thread->priv != NULL
10128 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 10129 {
799a2abe
PA
10130 *addr_p = thread->priv->watch_data_address;
10131 return 1;
4aa7a7f5
JJ
10132 }
10133
799a2abe 10134 return 0;
3c3bea1c
GS
10135}
10136
10137
10138static int
23a26771 10139remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 10140 struct bp_target_info *bp_tgt)
3c3bea1c 10141{
0d5ed153 10142 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10143 struct remote_state *rs;
bba74b36 10144 char *p, *endbuf;
dd61ec5c 10145 char *message;
3c3bea1c 10146
4082afcc 10147 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10148 return -1;
2bc416ba 10149
28439a30
PA
10150 /* Make sure the remote is pointing at the right process, if
10151 necessary. */
10152 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10153 set_general_process ();
10154
4fff2411
JZ
10155 rs = get_remote_state ();
10156 p = rs->buf;
bba74b36 10157 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 10158
96baa820
JM
10159 *(p++) = 'Z';
10160 *(p++) = '1';
10161 *(p++) = ',';
802188a7 10162
0d5ed153 10163 addr = remote_address_masked (addr);
96baa820 10164 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10165 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10166
efcc2da7 10167 if (remote_supports_cond_breakpoints (self))
bba74b36 10168 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10169
78eff0ec 10170 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
10171 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10172
6d820c5c
DJ
10173 putpkt (rs->buf);
10174 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10175
6d820c5c 10176 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10177 {
10178 case PACKET_ERROR:
dd61ec5c
MW
10179 if (rs->buf[1] == '.')
10180 {
10181 message = strchr (rs->buf + 2, '.');
10182 if (message)
0316657e 10183 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10184 }
10185 return -1;
d471ea57
AC
10186 case PACKET_UNKNOWN:
10187 return -1;
10188 case PACKET_OK:
10189 return 0;
10190 }
8e65ff28 10191 internal_error (__FILE__, __LINE__,
e2e0b3e5 10192 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10193}
10194
d471ea57 10195
802188a7 10196static int
a64dc96c 10197remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 10198 struct bp_target_info *bp_tgt)
96baa820 10199{
8181d85f 10200 CORE_ADDR addr;
d01949b6 10201 struct remote_state *rs = get_remote_state ();
6d820c5c 10202 char *p = rs->buf;
bba74b36 10203 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 10204
4082afcc 10205 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10206 return -1;
802188a7 10207
28439a30
PA
10208 /* Make sure the remote is pointing at the right process, if
10209 necessary. */
10210 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10211 set_general_process ();
10212
96baa820
JM
10213 *(p++) = 'z';
10214 *(p++) = '1';
10215 *(p++) = ',';
802188a7 10216
8181d85f 10217 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10218 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10219 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10220
6d820c5c
DJ
10221 putpkt (rs->buf);
10222 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 10223
6d820c5c 10224 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10225 {
10226 case PACKET_ERROR:
10227 case PACKET_UNKNOWN:
10228 return -1;
10229 case PACKET_OK:
10230 return 0;
10231 }
8e65ff28 10232 internal_error (__FILE__, __LINE__,
e2e0b3e5 10233 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10234}
96baa820 10235
4a5e7a5b
PA
10236/* Verify memory using the "qCRC:" request. */
10237
10238static int
10239remote_verify_memory (struct target_ops *ops,
10240 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10241{
10242 struct remote_state *rs = get_remote_state ();
10243 unsigned long host_crc, target_crc;
10244 char *tmp;
10245
936d2992
PA
10246 /* It doesn't make sense to use qCRC if the remote target is
10247 connected but not running. */
10248 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10249 {
10250 enum packet_result result;
28439a30 10251
936d2992
PA
10252 /* Make sure the remote is pointing at the right process. */
10253 set_general_process ();
4a5e7a5b 10254
936d2992
PA
10255 /* FIXME: assumes lma can fit into long. */
10256 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10257 (long) lma, (long) size);
10258 putpkt (rs->buf);
4a5e7a5b 10259
936d2992
PA
10260 /* Be clever; compute the host_crc before waiting for target
10261 reply. */
10262 host_crc = xcrc32 (data, size, 0xffffffff);
10263
10264 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 10265
936d2992
PA
10266 result = packet_ok (rs->buf,
10267 &remote_protocol_packets[PACKET_qCRC]);
10268 if (result == PACKET_ERROR)
10269 return -1;
10270 else if (result == PACKET_OK)
10271 {
10272 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10273 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10274
936d2992
PA
10275 return (host_crc == target_crc);
10276 }
10277 }
4a5e7a5b 10278
936d2992 10279 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
10280}
10281
c906108c
SS
10282/* compare-sections command
10283
10284 With no arguments, compares each loadable section in the exec bfd
10285 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10286 Useful for verifying the image on the target against the exec file. */
e514a9d6 10287
c906108c 10288static void
ac88e2de 10289compare_sections_command (const char *args, int from_tty)
c906108c
SS
10290{
10291 asection *s;
948f8e3d 10292 gdb_byte *sectdata;
ce359b09 10293 const char *sectname;
c906108c
SS
10294 bfd_size_type size;
10295 bfd_vma lma;
10296 int matched = 0;
10297 int mismatched = 0;
4a5e7a5b 10298 int res;
95cf3b38 10299 int read_only = 0;
c906108c
SS
10300
10301 if (!exec_bfd)
8a3fe4f8 10302 error (_("command cannot be used without an exec file"));
c906108c 10303
28439a30
PA
10304 /* Make sure the remote is pointing at the right process. */
10305 set_general_process ();
10306
95cf3b38
DT
10307 if (args != NULL && strcmp (args, "-r") == 0)
10308 {
10309 read_only = 1;
10310 args = NULL;
10311 }
10312
c5aa993b 10313 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10314 {
10315 if (!(s->flags & SEC_LOAD))
0df8b418 10316 continue; /* Skip non-loadable section. */
c906108c 10317
95cf3b38
DT
10318 if (read_only && (s->flags & SEC_READONLY) == 0)
10319 continue; /* Skip writeable sections */
10320
2c500098 10321 size = bfd_get_section_size (s);
c906108c 10322 if (size == 0)
0df8b418 10323 continue; /* Skip zero-length section. */
c906108c 10324
ce359b09 10325 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10326 if (args && strcmp (args, sectname) != 0)
0df8b418 10327 continue; /* Not the section selected by user. */
c906108c 10328
0df8b418 10329 matched = 1; /* Do this section. */
c906108c 10330 lma = s->lma;
c906108c 10331
b80406ac
TT
10332 gdb::byte_vector sectdata (size);
10333 bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
c906108c 10334
b80406ac 10335 res = target_verify_memory (sectdata.data (), lma, size);
4a5e7a5b
PA
10336
10337 if (res == -1)
5af949e3 10338 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10339 paddress (target_gdbarch (), lma),
10340 paddress (target_gdbarch (), lma + size));
c906108c 10341
5af949e3 10342 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10343 paddress (target_gdbarch (), lma),
10344 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10345 if (res)
c906108c
SS
10346 printf_filtered ("matched.\n");
10347 else
c5aa993b
JM
10348 {
10349 printf_filtered ("MIS-MATCHED!\n");
10350 mismatched++;
10351 }
c906108c
SS
10352 }
10353 if (mismatched > 0)
936d2992 10354 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10355the loaded file\n"));
c906108c 10356 if (args && !matched)
a3f17187 10357 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10358}
10359
0e7f50da
UW
10360/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10361 into remote target. The number of bytes written to the remote
10362 target is returned, or -1 for error. */
10363
9b409511 10364static enum target_xfer_status
0e7f50da
UW
10365remote_write_qxfer (struct target_ops *ops, const char *object_name,
10366 const char *annex, const gdb_byte *writebuf,
9b409511 10367 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
10368 struct packet_config *packet)
10369{
10370 int i, buf_len;
10371 ULONGEST n;
0e7f50da
UW
10372 struct remote_state *rs = get_remote_state ();
10373 int max_size = get_memory_write_packet_size ();
10374
10375 if (packet->support == PACKET_DISABLE)
2ed4b548 10376 return TARGET_XFER_E_IO;
0e7f50da
UW
10377
10378 /* Insert header. */
10379 i = snprintf (rs->buf, max_size,
10380 "qXfer:%s:write:%s:%s:",
10381 object_name, annex ? annex : "",
10382 phex_nz (offset, sizeof offset));
10383 max_size -= (i + 1);
10384
10385 /* Escape as much data as fits into rs->buf. */
10386 buf_len = remote_escape_output
124e13d9 10387 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
10388
10389 if (putpkt_binary (rs->buf, i + buf_len) < 0
10390 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10391 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10392 return TARGET_XFER_E_IO;
0e7f50da
UW
10393
10394 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
10395
10396 *xfered_len = n;
10397 return TARGET_XFER_OK;
0e7f50da
UW
10398}
10399
0876f84a
DJ
10400/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10401 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10402 number of bytes read is returned, or 0 for EOF, or -1 for error.
10403 The number of bytes read may be less than LEN without indicating an
10404 EOF. PACKET is checked and updated to indicate whether the remote
10405 target supports this object. */
10406
9b409511 10407static enum target_xfer_status
0876f84a
DJ
10408remote_read_qxfer (struct target_ops *ops, const char *object_name,
10409 const char *annex,
10410 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 10411 ULONGEST *xfered_len,
0876f84a
DJ
10412 struct packet_config *packet)
10413{
0876f84a 10414 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10415 LONGEST i, n, packet_len;
10416
10417 if (packet->support == PACKET_DISABLE)
2ed4b548 10418 return TARGET_XFER_E_IO;
0876f84a
DJ
10419
10420 /* Check whether we've cached an end-of-object packet that matches
10421 this request. */
8e88304f 10422 if (rs->finished_object)
0876f84a 10423 {
8e88304f
TT
10424 if (strcmp (object_name, rs->finished_object) == 0
10425 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10426 && offset == rs->finished_offset)
9b409511
YQ
10427 return TARGET_XFER_EOF;
10428
0876f84a
DJ
10429
10430 /* Otherwise, we're now reading something different. Discard
10431 the cache. */
8e88304f
TT
10432 xfree (rs->finished_object);
10433 xfree (rs->finished_annex);
10434 rs->finished_object = NULL;
10435 rs->finished_annex = NULL;
0876f84a
DJ
10436 }
10437
10438 /* Request only enough to fit in a single packet. The actual data
10439 may not, since we don't know how much of it will need to be escaped;
10440 the target is free to respond with slightly less data. We subtract
10441 five to account for the response type and the protocol frame. */
768adc05 10442 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
0876f84a
DJ
10443 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10444 object_name, annex ? annex : "",
10445 phex_nz (offset, sizeof offset),
10446 phex_nz (n, sizeof n));
10447 i = putpkt (rs->buf);
10448 if (i < 0)
2ed4b548 10449 return TARGET_XFER_E_IO;
0876f84a
DJ
10450
10451 rs->buf[0] = '\0';
10452 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10453 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10454 return TARGET_XFER_E_IO;
0876f84a
DJ
10455
10456 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10457 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10458
10459 /* 'm' means there is (or at least might be) more data after this
10460 batch. That does not make sense unless there's at least one byte
10461 of data in this reply. */
10462 if (rs->buf[0] == 'm' && packet_len == 1)
10463 error (_("Remote qXfer reply contained no data."));
10464
10465 /* Got some data. */
bc20a4af
PA
10466 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10467 packet_len - 1, readbuf, n);
0876f84a
DJ
10468
10469 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10470 or possibly empty. If we have the final block of a non-empty
10471 object, record this fact to bypass a subsequent partial read. */
10472 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10473 {
8e88304f
TT
10474 rs->finished_object = xstrdup (object_name);
10475 rs->finished_annex = xstrdup (annex ? annex : "");
10476 rs->finished_offset = offset + i;
0876f84a
DJ
10477 }
10478
9b409511
YQ
10479 if (i == 0)
10480 return TARGET_XFER_EOF;
10481 else
10482 {
10483 *xfered_len = i;
10484 return TARGET_XFER_OK;
10485 }
0876f84a
DJ
10486}
10487
9b409511 10488static enum target_xfer_status
4b8a223f 10489remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 10490 const char *annex, gdb_byte *readbuf,
9b409511
YQ
10491 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10492 ULONGEST *xfered_len)
c906108c 10493{
82f73884 10494 struct remote_state *rs;
c906108c 10495 int i;
6d820c5c 10496 char *p2;
1e3ff5ad 10497 char query_type;
124e13d9 10498 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 10499
e6e4e701 10500 set_remote_traceframe ();
82f73884
PA
10501 set_general_thread (inferior_ptid);
10502
10503 rs = get_remote_state ();
10504
b2182ed2 10505 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
10506 if (object == TARGET_OBJECT_MEMORY)
10507 {
2d717e4f
DJ
10508 /* If the remote target is connected but not running, we should
10509 pass this request down to a lower stratum (e.g. the executable
10510 file). */
10511 if (!target_has_execution)
9b409511 10512 return TARGET_XFER_EOF;
2d717e4f 10513
21e3b9b9 10514 if (writebuf != NULL)
124e13d9
SM
10515 return remote_write_bytes (offset, writebuf, len, unit_size,
10516 xfered_len);
21e3b9b9 10517 else
124e13d9
SM
10518 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10519 xfered_len);
21e3b9b9
DJ
10520 }
10521
0df8b418 10522 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10523 if (object == TARGET_OBJECT_SPU)
10524 {
10525 if (readbuf)
10526 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
10527 xfered_len, &remote_protocol_packets
10528 [PACKET_qXfer_spu_read]);
0e7f50da
UW
10529 else
10530 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
10531 xfered_len, &remote_protocol_packets
10532 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10533 }
10534
4aa995e1
PA
10535 /* Handle extra signal info using qxfer packets. */
10536 if (object == TARGET_OBJECT_SIGNAL_INFO)
10537 {
10538 if (readbuf)
10539 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 10540 xfered_len, &remote_protocol_packets
4aa995e1
PA
10541 [PACKET_qXfer_siginfo_read]);
10542 else
3e43a32a 10543 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 10544 writebuf, offset, len, xfered_len,
4aa995e1
PA
10545 &remote_protocol_packets
10546 [PACKET_qXfer_siginfo_write]);
10547 }
10548
0fb4aa4b
PA
10549 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10550 {
10551 if (readbuf)
3e43a32a 10552 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 10553 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10554 &remote_protocol_packets
10555 [PACKET_qXfer_statictrace_read]);
10556 else
2ed4b548 10557 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10558 }
10559
a76d924d
DJ
10560 /* Only handle flash writes. */
10561 if (writebuf != NULL)
10562 {
a76d924d
DJ
10563 switch (object)
10564 {
10565 case TARGET_OBJECT_FLASH:
9b409511
YQ
10566 return remote_flash_write (ops, offset, len, xfered_len,
10567 writebuf);
a76d924d
DJ
10568
10569 default:
2ed4b548 10570 return TARGET_XFER_E_IO;
a76d924d
DJ
10571 }
10572 }
4b8a223f 10573
1e3ff5ad
AC
10574 /* Map pre-existing objects onto letters. DO NOT do this for new
10575 objects!!! Instead specify new query packets. */
10576 switch (object)
c906108c 10577 {
1e3ff5ad
AC
10578 case TARGET_OBJECT_AVR:
10579 query_type = 'R';
10580 break;
802188a7
RM
10581
10582 case TARGET_OBJECT_AUXV:
0876f84a
DJ
10583 gdb_assert (annex == NULL);
10584 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 10585 xfered_len,
0876f84a 10586 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10587
23181151
DJ
10588 case TARGET_OBJECT_AVAILABLE_FEATURES:
10589 return remote_read_qxfer
9b409511 10590 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10591 &remote_protocol_packets[PACKET_qXfer_features]);
10592
cfa9d6d9
DJ
10593 case TARGET_OBJECT_LIBRARIES:
10594 return remote_read_qxfer
9b409511 10595 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10596 &remote_protocol_packets[PACKET_qXfer_libraries]);
10597
2268b414
JK
10598 case TARGET_OBJECT_LIBRARIES_SVR4:
10599 return remote_read_qxfer
9b409511 10600 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10601 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10602
fd79ecee
DJ
10603 case TARGET_OBJECT_MEMORY_MAP:
10604 gdb_assert (annex == NULL);
10605 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 10606 xfered_len,
fd79ecee
DJ
10607 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10608
07e059b5
VP
10609 case TARGET_OBJECT_OSDATA:
10610 /* Should only get here if we're connected. */
5d93a237 10611 gdb_assert (rs->remote_desc);
07e059b5 10612 return remote_read_qxfer
9b409511 10613 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10614 &remote_protocol_packets[PACKET_qXfer_osdata]);
10615
dc146f7c
VP
10616 case TARGET_OBJECT_THREADS:
10617 gdb_assert (annex == NULL);
10618 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10619 xfered_len,
dc146f7c
VP
10620 &remote_protocol_packets[PACKET_qXfer_threads]);
10621
b3b9301e
PA
10622 case TARGET_OBJECT_TRACEFRAME_INFO:
10623 gdb_assert (annex == NULL);
10624 return remote_read_qxfer
9b409511 10625 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10626 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10627
10628 case TARGET_OBJECT_FDPIC:
10629 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10630 xfered_len,
78d85199 10631 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10632
10633 case TARGET_OBJECT_OPENVMS_UIB:
10634 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10635 xfered_len,
169081d0
TG
10636 &remote_protocol_packets[PACKET_qXfer_uib]);
10637
9accd112
MM
10638 case TARGET_OBJECT_BTRACE:
10639 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10640 xfered_len,
9accd112
MM
10641 &remote_protocol_packets[PACKET_qXfer_btrace]);
10642
f4abbc16
MM
10643 case TARGET_OBJECT_BTRACE_CONF:
10644 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10645 len, xfered_len,
10646 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10647
c78fa86a
GB
10648 case TARGET_OBJECT_EXEC_FILE:
10649 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10650 len, xfered_len,
10651 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10652
1e3ff5ad 10653 default:
2ed4b548 10654 return TARGET_XFER_E_IO;
c906108c
SS
10655 }
10656
0df8b418 10657 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10658 large enough let the caller deal with it. */
ea9c271d 10659 if (len < get_remote_packet_size ())
2ed4b548 10660 return TARGET_XFER_E_IO;
ea9c271d 10661 len = get_remote_packet_size ();
1e3ff5ad 10662
23860348 10663 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10664 if (!rs->remote_desc)
8a3fe4f8 10665 error (_("remote query is only available after target open"));
c906108c 10666
1e3ff5ad 10667 gdb_assert (annex != NULL);
4b8a223f 10668 gdb_assert (readbuf != NULL);
c906108c 10669
6d820c5c 10670 p2 = rs->buf;
c906108c
SS
10671 *p2++ = 'q';
10672 *p2++ = query_type;
10673
23860348
MS
10674 /* We used one buffer char for the remote protocol q command and
10675 another for the query type. As the remote protocol encapsulation
10676 uses 4 chars plus one extra in case we are debugging
10677 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10678 string. */
c906108c 10679 i = 0;
ea9c271d 10680 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10681 {
1e3ff5ad
AC
10682 /* Bad caller may have sent forbidden characters. */
10683 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10684 *p2++ = annex[i];
c906108c
SS
10685 i++;
10686 }
1e3ff5ad
AC
10687 *p2 = '\0';
10688 gdb_assert (annex[i] == '\0');
c906108c 10689
6d820c5c 10690 i = putpkt (rs->buf);
c5aa993b 10691 if (i < 0)
2ed4b548 10692 return TARGET_XFER_E_IO;
c906108c 10693
6d820c5c
DJ
10694 getpkt (&rs->buf, &rs->buf_size, 0);
10695 strcpy ((char *) readbuf, rs->buf);
c906108c 10696
9b409511
YQ
10697 *xfered_len = strlen ((char *) readbuf);
10698 return TARGET_XFER_OK;
c906108c
SS
10699}
10700
09c98b44
DB
10701/* Implementation of to_get_memory_xfer_limit. */
10702
10703static ULONGEST
10704remote_get_memory_xfer_limit (struct target_ops *ops)
10705{
10706 return get_memory_write_packet_size ();
10707}
10708
08388c79
DE
10709static int
10710remote_search_memory (struct target_ops* ops,
10711 CORE_ADDR start_addr, ULONGEST search_space_len,
10712 const gdb_byte *pattern, ULONGEST pattern_len,
10713 CORE_ADDR *found_addrp)
10714{
f5656ead 10715 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10716 struct remote_state *rs = get_remote_state ();
10717 int max_size = get_memory_write_packet_size ();
10718 struct packet_config *packet =
10719 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10720 /* Number of packet bytes used to encode the pattern;
10721 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10722 int escaped_pattern_len;
0df8b418 10723 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10724 int used_pattern_len;
10725 int i;
10726 int found;
10727 ULONGEST found_addr;
10728
10729 /* Don't go to the target if we don't have to.
10730 This is done before checking packet->support to avoid the possibility that
10731 a success for this edge case means the facility works in general. */
10732 if (pattern_len > search_space_len)
10733 return 0;
10734 if (pattern_len == 0)
10735 {
10736 *found_addrp = start_addr;
10737 return 1;
10738 }
10739
10740 /* If we already know the packet isn't supported, fall back to the simple
10741 way of searching memory. */
10742
4082afcc 10743 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10744 {
10745 /* Target doesn't provided special support, fall back and use the
10746 standard support (copy memory and do the search here). */
10747 return simple_search_memory (ops, start_addr, search_space_len,
10748 pattern, pattern_len, found_addrp);
10749 }
10750
28439a30
PA
10751 /* Make sure the remote is pointing at the right process. */
10752 set_general_process ();
10753
08388c79
DE
10754 /* Insert header. */
10755 i = snprintf (rs->buf, max_size,
10756 "qSearch:memory:%s;%s;",
5af949e3 10757 phex_nz (start_addr, addr_size),
08388c79
DE
10758 phex_nz (search_space_len, sizeof (search_space_len)));
10759 max_size -= (i + 1);
10760
10761 /* Escape as much data as fits into rs->buf. */
10762 escaped_pattern_len =
124e13d9 10763 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10764 &used_pattern_len, max_size);
10765
10766 /* Bail if the pattern is too large. */
10767 if (used_pattern_len != pattern_len)
9b20d036 10768 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10769
10770 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10771 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10772 || packet_ok (rs->buf, packet) != PACKET_OK)
10773 {
10774 /* The request may not have worked because the command is not
10775 supported. If so, fall back to the simple way. */
10776 if (packet->support == PACKET_DISABLE)
10777 {
10778 return simple_search_memory (ops, start_addr, search_space_len,
10779 pattern, pattern_len, found_addrp);
10780 }
10781 return -1;
10782 }
10783
10784 if (rs->buf[0] == '0')
10785 found = 0;
10786 else if (rs->buf[0] == '1')
10787 {
10788 found = 1;
10789 if (rs->buf[1] != ',')
10e0fa18 10790 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10791 unpack_varlen_hex (rs->buf + 2, &found_addr);
10792 *found_addrp = found_addr;
10793 }
10794 else
10e0fa18 10795 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10796
10797 return found;
10798}
10799
96baa820 10800static void
a30bf1f1 10801remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10802 struct ui_file *outbuf)
96baa820 10803{
d01949b6 10804 struct remote_state *rs = get_remote_state ();
2e9f7625 10805 char *p = rs->buf;
96baa820 10806
5d93a237 10807 if (!rs->remote_desc)
8a3fe4f8 10808 error (_("remote rcmd is only available after target open"));
96baa820 10809
23860348 10810 /* Send a NULL command across as an empty command. */
7be570e7
JM
10811 if (command == NULL)
10812 command = "";
10813
23860348 10814 /* The query prefix. */
2e9f7625
DJ
10815 strcpy (rs->buf, "qRcmd,");
10816 p = strchr (rs->buf, '\0');
96baa820 10817
3e43a32a
MS
10818 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10819 > get_remote_packet_size ())
8a3fe4f8 10820 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10821
23860348 10822 /* Encode the actual command. */
a30bf1f1 10823 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10824
6d820c5c 10825 if (putpkt (rs->buf) < 0)
8a3fe4f8 10826 error (_("Communication problem with target."));
96baa820
JM
10827
10828 /* get/display the response */
10829 while (1)
10830 {
2e9f7625
DJ
10831 char *buf;
10832
00bf0b85 10833 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10834 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10835 rs->buf[0] = '\0';
5b37825d
PW
10836 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10837 {
10838 /* Timeout. Continue to (try to) read responses.
10839 This is better than stopping with an error, assuming the stub
10840 is still executing the (long) monitor command.
10841 If needed, the user can interrupt gdb using C-c, obtaining
10842 an effect similar to stop on timeout. */
10843 continue;
10844 }
2e9f7625 10845 buf = rs->buf;
96baa820 10846 if (buf[0] == '\0')
8a3fe4f8 10847 error (_("Target does not support this command."));
96baa820
JM
10848 if (buf[0] == 'O' && buf[1] != 'K')
10849 {
23860348 10850 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10851 continue;
10852 }
10853 if (strcmp (buf, "OK") == 0)
10854 break;
7be570e7
JM
10855 if (strlen (buf) == 3 && buf[0] == 'E'
10856 && isdigit (buf[1]) && isdigit (buf[2]))
10857 {
8a3fe4f8 10858 error (_("Protocol error with Rcmd"));
7be570e7 10859 }
96baa820
JM
10860 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10861 {
10862 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10863
96baa820
JM
10864 fputc_unfiltered (c, outbuf);
10865 }
10866 break;
10867 }
10868}
10869
a664f67e 10870static std::vector<mem_region>
fd79ecee
DJ
10871remote_memory_map (struct target_ops *ops)
10872{
a664f67e 10873 std::vector<mem_region> result;
b7b030ad
TT
10874 gdb::unique_xmalloc_ptr<char> text
10875 = target_read_stralloc (&current_target, TARGET_OBJECT_MEMORY_MAP, NULL);
fd79ecee
DJ
10876
10877 if (text)
b7b030ad 10878 result = parse_memory_map (text.get ());
fd79ecee
DJ
10879
10880 return result;
10881}
10882
c906108c 10883static void
ac88e2de 10884packet_command (const char *args, int from_tty)
c906108c 10885{
d01949b6 10886 struct remote_state *rs = get_remote_state ();
c906108c 10887
5d93a237 10888 if (!rs->remote_desc)
8a3fe4f8 10889 error (_("command can only be used with remote target"));
c906108c 10890
c5aa993b 10891 if (!args)
8a3fe4f8 10892 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10893
10894 puts_filtered ("sending: ");
10895 print_packet (args);
10896 puts_filtered ("\n");
10897 putpkt (args);
10898
6d820c5c 10899 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10900 puts_filtered ("received: ");
6d820c5c 10901 print_packet (rs->buf);
c906108c
SS
10902 puts_filtered ("\n");
10903}
10904
10905#if 0
23860348 10906/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10907
a14ed312 10908static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10909
a14ed312 10910static void threadset_test_cmd (char *cmd, int tty);
c906108c 10911
a14ed312 10912static void threadalive_test (char *cmd, int tty);
c906108c 10913
a14ed312 10914static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10915
23860348 10916int get_and_display_threadinfo (threadref *ref);
c906108c 10917
a14ed312 10918static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10919
23860348 10920static int thread_display_step (threadref *ref, void *context);
c906108c 10921
a14ed312 10922static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10923
a14ed312 10924static void init_remote_threadtests (void);
c906108c 10925
23860348 10926#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10927
10928static void
fba45db2 10929threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10930{
10931 int sample_thread = SAMPLE_THREAD;
10932
a3f17187 10933 printf_filtered (_("Remote threadset test\n"));
79d7f229 10934 set_general_thread (sample_thread);
c906108c
SS
10935}
10936
10937
10938static void
fba45db2 10939threadalive_test (char *cmd, int tty)
c906108c
SS
10940{
10941 int sample_thread = SAMPLE_THREAD;
79d7f229 10942 int pid = ptid_get_pid (inferior_ptid);
ba348170 10943 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10944
79d7f229 10945 if (remote_thread_alive (ptid))
c906108c
SS
10946 printf_filtered ("PASS: Thread alive test\n");
10947 else
10948 printf_filtered ("FAIL: Thread alive test\n");
10949}
10950
23860348 10951void output_threadid (char *title, threadref *ref);
c906108c
SS
10952
10953void
fba45db2 10954output_threadid (char *title, threadref *ref)
c906108c
SS
10955{
10956 char hexid[20];
10957
23860348 10958 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10959 hexid[16] = 0;
10960 printf_filtered ("%s %s\n", title, (&hexid[0]));
10961}
10962
10963static void
fba45db2 10964threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10965{
10966 int startflag = 1;
10967 threadref nextthread;
10968 int done, result_count;
10969 threadref threadlist[3];
10970
10971 printf_filtered ("Remote Threadlist test\n");
10972 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10973 &result_count, &threadlist[0]))
10974 printf_filtered ("FAIL: threadlist test\n");
10975 else
10976 {
10977 threadref *scan = threadlist;
10978 threadref *limit = scan + result_count;
10979
10980 while (scan < limit)
10981 output_threadid (" thread ", scan++);
10982 }
10983}
10984
10985void
fba45db2 10986display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10987{
10988 output_threadid ("Threadid: ", &info->threadid);
10989 printf_filtered ("Name: %s\n ", info->shortname);
10990 printf_filtered ("State: %s\n", info->display);
10991 printf_filtered ("other: %s\n\n", info->more_display);
10992}
10993
10994int
fba45db2 10995get_and_display_threadinfo (threadref *ref)
c906108c
SS
10996{
10997 int result;
10998 int set;
10999 struct gdb_ext_thread_info threadinfo;
11000
11001 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11002 | TAG_MOREDISPLAY | TAG_DISPLAY;
11003 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11004 display_thread_info (&threadinfo);
11005 return result;
11006}
11007
11008static void
fba45db2 11009threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
11010{
11011 int athread = SAMPLE_THREAD;
11012 threadref thread;
11013 int set;
11014
11015 int_to_threadref (&thread, athread);
11016 printf_filtered ("Remote Threadinfo test\n");
11017 if (!get_and_display_threadinfo (&thread))
11018 printf_filtered ("FAIL cannot get thread info\n");
11019}
11020
11021static int
fba45db2 11022thread_display_step (threadref *ref, void *context)
c906108c
SS
11023{
11024 /* output_threadid(" threadstep ",ref); *//* simple test */
11025 return get_and_display_threadinfo (ref);
11026}
11027
11028static void
fba45db2 11029threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
11030{
11031 printf_filtered ("Remote Threadlist update test\n");
11032 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11033}
11034
11035static void
11036init_remote_threadtests (void)
11037{
3e43a32a
MS
11038 add_com ("tlist", class_obscure, threadlist_test_cmd,
11039 _("Fetch and print the remote list of "
11040 "thread identifiers, one pkt only"));
c906108c 11041 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 11042 _("Fetch and display info about one thread"));
c906108c 11043 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 11044 _("Test setting to a different thread"));
c906108c 11045 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 11046 _("Iterate through updating all remote thread info"));
c906108c 11047 add_com ("talive", class_obscure, threadalive_test,
1bedd215 11048 _(" Remote thread alive test "));
c906108c
SS
11049}
11050
11051#endif /* 0 */
11052
f3fb8c85
MS
11053/* Convert a thread ID to a string. Returns the string in a static
11054 buffer. */
11055
7a114964 11056static const char *
117de6a9 11057remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 11058{
79d7f229 11059 static char buf[64];
82f73884 11060 struct remote_state *rs = get_remote_state ();
f3fb8c85 11061
7cee1e54
PA
11062 if (ptid_equal (ptid, null_ptid))
11063 return normal_pid_to_str (ptid);
11064 else if (ptid_is_pid (ptid))
ecd0ada5
PA
11065 {
11066 /* Printing an inferior target id. */
11067
11068 /* When multi-process extensions are off, there's no way in the
11069 remote protocol to know the remote process id, if there's any
11070 at all. There's one exception --- when we're connected with
11071 target extended-remote, and we manually attached to a process
11072 with "attach PID". We don't record anywhere a flag that
11073 allows us to distinguish that case from the case of
11074 connecting with extended-remote and the stub already being
11075 attached to a process, and reporting yes to qAttached, hence
11076 no smart special casing here. */
11077 if (!remote_multi_process_p (rs))
11078 {
11079 xsnprintf (buf, sizeof buf, "Remote target");
11080 return buf;
11081 }
11082
11083 return normal_pid_to_str (ptid);
82f73884 11084 }
ecd0ada5 11085 else
79d7f229 11086 {
ecd0ada5
PA
11087 if (ptid_equal (magic_null_ptid, ptid))
11088 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 11089 else if (remote_multi_process_p (rs))
de0d863e
DB
11090 if (ptid_get_lwp (ptid) == 0)
11091 return normal_pid_to_str (ptid);
11092 else
11093 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11094 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
11095 else
11096 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 11097 ptid_get_lwp (ptid));
79d7f229
PA
11098 return buf;
11099 }
f3fb8c85
MS
11100}
11101
38691318
KB
11102/* Get the address of the thread local variable in OBJFILE which is
11103 stored at OFFSET within the thread local storage for thread PTID. */
11104
11105static CORE_ADDR
117de6a9
PA
11106remote_get_thread_local_address (struct target_ops *ops,
11107 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 11108{
4082afcc 11109 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11110 {
11111 struct remote_state *rs = get_remote_state ();
6d820c5c 11112 char *p = rs->buf;
82f73884 11113 char *endp = rs->buf + get_remote_packet_size ();
571dd617 11114 enum packet_result result;
38691318
KB
11115
11116 strcpy (p, "qGetTLSAddr:");
11117 p += strlen (p);
82f73884 11118 p = write_ptid (p, endp, ptid);
38691318
KB
11119 *p++ = ',';
11120 p += hexnumstr (p, offset);
11121 *p++ = ',';
11122 p += hexnumstr (p, lm);
11123 *p++ = '\0';
11124
6d820c5c
DJ
11125 putpkt (rs->buf);
11126 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
11127 result = packet_ok (rs->buf,
11128 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11129 if (result == PACKET_OK)
38691318
KB
11130 {
11131 ULONGEST result;
11132
6d820c5c 11133 unpack_varlen_hex (rs->buf, &result);
38691318
KB
11134 return result;
11135 }
571dd617 11136 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11137 throw_error (TLS_GENERIC_ERROR,
11138 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11139 else
109c3e39
AC
11140 throw_error (TLS_GENERIC_ERROR,
11141 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11142 }
11143 else
109c3e39
AC
11144 throw_error (TLS_GENERIC_ERROR,
11145 _("TLS not supported or disabled on this target"));
38691318
KB
11146 /* Not reached. */
11147 return 0;
11148}
11149
711e434b
PM
11150/* Provide thread local base, i.e. Thread Information Block address.
11151 Returns 1 if ptid is found and thread_local_base is non zero. */
11152
70221824 11153static int
bd7ae0f5 11154remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 11155{
4082afcc 11156 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11157 {
11158 struct remote_state *rs = get_remote_state ();
11159 char *p = rs->buf;
11160 char *endp = rs->buf + get_remote_packet_size ();
11161 enum packet_result result;
11162
11163 strcpy (p, "qGetTIBAddr:");
11164 p += strlen (p);
11165 p = write_ptid (p, endp, ptid);
11166 *p++ = '\0';
11167
11168 putpkt (rs->buf);
11169 getpkt (&rs->buf, &rs->buf_size, 0);
11170 result = packet_ok (rs->buf,
11171 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11172 if (result == PACKET_OK)
11173 {
11174 ULONGEST result;
11175
11176 unpack_varlen_hex (rs->buf, &result);
11177 if (addr)
11178 *addr = (CORE_ADDR) result;
11179 return 1;
11180 }
11181 else if (result == PACKET_UNKNOWN)
11182 error (_("Remote target doesn't support qGetTIBAddr packet"));
11183 else
11184 error (_("Remote target failed to process qGetTIBAddr request"));
11185 }
11186 else
11187 error (_("qGetTIBAddr not supported or disabled on this target"));
11188 /* Not reached. */
11189 return 0;
11190}
11191
29709017
DJ
11192/* Support for inferring a target description based on the current
11193 architecture and the size of a 'g' packet. While the 'g' packet
11194 can have any size (since optional registers can be left off the
11195 end), some sizes are easily recognizable given knowledge of the
11196 approximate architecture. */
11197
11198struct remote_g_packet_guess
11199{
11200 int bytes;
11201 const struct target_desc *tdesc;
11202};
11203typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11204DEF_VEC_O(remote_g_packet_guess_s);
11205
11206struct remote_g_packet_data
11207{
11208 VEC(remote_g_packet_guess_s) *guesses;
11209};
11210
11211static struct gdbarch_data *remote_g_packet_data_handle;
11212
11213static void *
11214remote_g_packet_data_init (struct obstack *obstack)
11215{
11216 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11217}
11218
11219void
11220register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11221 const struct target_desc *tdesc)
11222{
11223 struct remote_g_packet_data *data
19ba03f4
SM
11224 = ((struct remote_g_packet_data *)
11225 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11226 struct remote_g_packet_guess new_guess, *guess;
11227 int ix;
11228
11229 gdb_assert (tdesc != NULL);
11230
11231 for (ix = 0;
11232 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11233 ix++)
11234 if (guess->bytes == bytes)
11235 internal_error (__FILE__, __LINE__,
9b20d036 11236 _("Duplicate g packet description added for size %d"),
29709017
DJ
11237 bytes);
11238
11239 new_guess.bytes = bytes;
11240 new_guess.tdesc = tdesc;
11241 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11242}
11243
d962ef82
DJ
11244/* Return 1 if remote_read_description would do anything on this target
11245 and architecture, 0 otherwise. */
11246
11247static int
11248remote_read_description_p (struct target_ops *target)
11249{
11250 struct remote_g_packet_data *data
19ba03f4
SM
11251 = ((struct remote_g_packet_data *)
11252 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
11253
11254 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11255 return 1;
11256
11257 return 0;
11258}
11259
29709017
DJ
11260static const struct target_desc *
11261remote_read_description (struct target_ops *target)
11262{
11263 struct remote_g_packet_data *data
19ba03f4
SM
11264 = ((struct remote_g_packet_data *)
11265 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11266
d962ef82
DJ
11267 /* Do not try this during initial connection, when we do not know
11268 whether there is a running but stopped thread. */
11269 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 11270 return target->beneath->to_read_description (target->beneath);
d962ef82 11271
29709017
DJ
11272 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11273 {
11274 struct remote_g_packet_guess *guess;
11275 int ix;
11276 int bytes = send_g_packet ();
11277
11278 for (ix = 0;
11279 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11280 ix++)
11281 if (guess->bytes == bytes)
11282 return guess->tdesc;
11283
11284 /* We discard the g packet. A minor optimization would be to
11285 hold on to it, and fill the register cache once we have selected
11286 an architecture, but it's too tricky to do safely. */
11287 }
11288
2117c711 11289 return target->beneath->to_read_description (target->beneath);
29709017
DJ
11290}
11291
a6b151f1
DJ
11292/* Remote file transfer support. This is host-initiated I/O, not
11293 target-initiated; for target-initiated, see remote-fileio.c. */
11294
11295/* If *LEFT is at least the length of STRING, copy STRING to
11296 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11297 decrease *LEFT. Otherwise raise an error. */
11298
11299static void
a121b7c1 11300remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11301{
11302 int len = strlen (string);
11303
11304 if (len > *left)
11305 error (_("Packet too long for target."));
11306
11307 memcpy (*buffer, string, len);
11308 *buffer += len;
11309 *left -= len;
11310
11311 /* NUL-terminate the buffer as a convenience, if there is
11312 room. */
11313 if (*left)
11314 **buffer = '\0';
11315}
11316
11317/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11318 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11319 decrease *LEFT. Otherwise raise an error. */
11320
11321static void
11322remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11323 int len)
11324{
11325 if (2 * len > *left)
11326 error (_("Packet too long for target."));
11327
11328 bin2hex (bytes, *buffer, len);
11329 *buffer += 2 * len;
11330 *left -= 2 * len;
11331
11332 /* NUL-terminate the buffer as a convenience, if there is
11333 room. */
11334 if (*left)
11335 **buffer = '\0';
11336}
11337
11338/* If *LEFT is large enough, convert VALUE to hex and add it to
11339 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11340 decrease *LEFT. Otherwise raise an error. */
11341
11342static void
11343remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11344{
11345 int len = hexnumlen (value);
11346
11347 if (len > *left)
11348 error (_("Packet too long for target."));
11349
11350 hexnumstr (*buffer, value);
11351 *buffer += len;
11352 *left -= len;
11353
11354 /* NUL-terminate the buffer as a convenience, if there is
11355 room. */
11356 if (*left)
11357 **buffer = '\0';
11358}
11359
11360/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11361 value, *REMOTE_ERRNO to the remote error number or zero if none
11362 was included, and *ATTACHMENT to point to the start of the annex
11363 if any. The length of the packet isn't needed here; there may
11364 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11365
11366 Return 0 if the packet could be parsed, -1 if it could not. If
11367 -1 is returned, the other variables may not be initialized. */
11368
11369static int
11370remote_hostio_parse_result (char *buffer, int *retcode,
11371 int *remote_errno, char **attachment)
11372{
11373 char *p, *p2;
11374
11375 *remote_errno = 0;
11376 *attachment = NULL;
11377
11378 if (buffer[0] != 'F')
11379 return -1;
11380
11381 errno = 0;
11382 *retcode = strtol (&buffer[1], &p, 16);
11383 if (errno != 0 || p == &buffer[1])
11384 return -1;
11385
11386 /* Check for ",errno". */
11387 if (*p == ',')
11388 {
11389 errno = 0;
11390 *remote_errno = strtol (p + 1, &p2, 16);
11391 if (errno != 0 || p + 1 == p2)
11392 return -1;
11393 p = p2;
11394 }
11395
11396 /* Check for ";attachment". If there is no attachment, the
11397 packet should end here. */
11398 if (*p == ';')
11399 {
11400 *attachment = p + 1;
11401 return 0;
11402 }
11403 else if (*p == '\0')
11404 return 0;
11405 else
11406 return -1;
11407}
11408
11409/* Send a prepared I/O packet to the target and read its response.
11410 The prepared packet is in the global RS->BUF before this function
11411 is called, and the answer is there when we return.
11412
11413 COMMAND_BYTES is the length of the request to send, which may include
11414 binary data. WHICH_PACKET is the packet configuration to check
11415 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11416 is set to the error number and -1 is returned. Otherwise the value
11417 returned by the function is returned.
11418
11419 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11420 attachment is expected; an error will be reported if there's a
11421 mismatch. If one is found, *ATTACHMENT will be set to point into
11422 the packet buffer and *ATTACHMENT_LEN will be set to the
11423 attachment's length. */
11424
11425static int
11426remote_hostio_send_command (int command_bytes, int which_packet,
11427 int *remote_errno, char **attachment,
11428 int *attachment_len)
11429{
11430 struct remote_state *rs = get_remote_state ();
11431 int ret, bytes_read;
11432 char *attachment_tmp;
11433
5d93a237 11434 if (!rs->remote_desc
4082afcc 11435 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11436 {
11437 *remote_errno = FILEIO_ENOSYS;
11438 return -1;
11439 }
11440
11441 putpkt_binary (rs->buf, command_bytes);
11442 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11443
11444 /* If it timed out, something is wrong. Don't try to parse the
11445 buffer. */
11446 if (bytes_read < 0)
11447 {
11448 *remote_errno = FILEIO_EINVAL;
11449 return -1;
11450 }
11451
11452 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11453 {
11454 case PACKET_ERROR:
11455 *remote_errno = FILEIO_EINVAL;
11456 return -1;
11457 case PACKET_UNKNOWN:
11458 *remote_errno = FILEIO_ENOSYS;
11459 return -1;
11460 case PACKET_OK:
11461 break;
11462 }
11463
11464 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11465 &attachment_tmp))
11466 {
11467 *remote_errno = FILEIO_EINVAL;
11468 return -1;
11469 }
11470
11471 /* Make sure we saw an attachment if and only if we expected one. */
11472 if ((attachment_tmp == NULL && attachment != NULL)
11473 || (attachment_tmp != NULL && attachment == NULL))
11474 {
11475 *remote_errno = FILEIO_EINVAL;
11476 return -1;
11477 }
11478
11479 /* If an attachment was found, it must point into the packet buffer;
11480 work out how many bytes there were. */
11481 if (attachment_tmp != NULL)
11482 {
11483 *attachment = attachment_tmp;
11484 *attachment_len = bytes_read - (*attachment - rs->buf);
11485 }
11486
11487 return ret;
11488}
11489
80152258
PA
11490/* Invalidate the readahead cache. */
11491
11492static void
11493readahead_cache_invalidate (void)
11494{
11495 struct remote_state *rs = get_remote_state ();
11496
11497 rs->readahead_cache.fd = -1;
11498}
11499
11500/* Invalidate the readahead cache if it is holding data for FD. */
11501
11502static void
11503readahead_cache_invalidate_fd (int fd)
11504{
11505 struct remote_state *rs = get_remote_state ();
11506
11507 if (rs->readahead_cache.fd == fd)
11508 rs->readahead_cache.fd = -1;
11509}
11510
15a201c8
GB
11511/* Set the filesystem remote_hostio functions that take FILENAME
11512 arguments will use. Return 0 on success, or -1 if an error
11513 occurs (and set *REMOTE_ERRNO). */
11514
11515static int
11516remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11517{
11518 struct remote_state *rs = get_remote_state ();
11519 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11520 char *p = rs->buf;
11521 int left = get_remote_packet_size () - 1;
11522 char arg[9];
11523 int ret;
11524
11525 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11526 return 0;
11527
11528 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11529 return 0;
11530
11531 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11532
11533 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11534 remote_buffer_add_string (&p, &left, arg);
11535
11536 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11537 remote_errno, NULL, NULL);
11538
11539 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11540 return 0;
11541
11542 if (ret == 0)
11543 rs->fs_pid = required_pid;
11544
11545 return ret;
11546}
11547
12e2a5fd 11548/* Implementation of to_fileio_open. */
a6b151f1
DJ
11549
11550static int
cd897586 11551remote_hostio_open (struct target_ops *self,
07c138c8 11552 struct inferior *inf, const char *filename,
4313b8c0
GB
11553 int flags, int mode, int warn_if_slow,
11554 int *remote_errno)
a6b151f1
DJ
11555{
11556 struct remote_state *rs = get_remote_state ();
11557 char *p = rs->buf;
11558 int left = get_remote_packet_size () - 1;
11559
4313b8c0
GB
11560 if (warn_if_slow)
11561 {
11562 static int warning_issued = 0;
11563
11564 printf_unfiltered (_("Reading %s from remote target...\n"),
11565 filename);
11566
11567 if (!warning_issued)
11568 {
11569 warning (_("File transfers from remote targets can be slow."
11570 " Use \"set sysroot\" to access files locally"
11571 " instead."));
11572 warning_issued = 1;
11573 }
11574 }
11575
15a201c8
GB
11576 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11577 return -1;
11578
a6b151f1
DJ
11579 remote_buffer_add_string (&p, &left, "vFile:open:");
11580
11581 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11582 strlen (filename));
11583 remote_buffer_add_string (&p, &left, ",");
11584
11585 remote_buffer_add_int (&p, &left, flags);
11586 remote_buffer_add_string (&p, &left, ",");
11587
11588 remote_buffer_add_int (&p, &left, mode);
11589
11590 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11591 remote_errno, NULL, NULL);
11592}
11593
12e2a5fd 11594/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11595
11596static int
0d866f62
TT
11597remote_hostio_pwrite (struct target_ops *self,
11598 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11599 ULONGEST offset, int *remote_errno)
11600{
11601 struct remote_state *rs = get_remote_state ();
11602 char *p = rs->buf;
11603 int left = get_remote_packet_size ();
11604 int out_len;
11605
80152258
PA
11606 readahead_cache_invalidate_fd (fd);
11607
a6b151f1
DJ
11608 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11609
11610 remote_buffer_add_int (&p, &left, fd);
11611 remote_buffer_add_string (&p, &left, ",");
11612
11613 remote_buffer_add_int (&p, &left, offset);
11614 remote_buffer_add_string (&p, &left, ",");
11615
124e13d9 11616 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11617 get_remote_packet_size () - (p - rs->buf));
11618
11619 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11620 remote_errno, NULL, NULL);
11621}
11622
80152258
PA
11623/* Helper for the implementation of to_fileio_pread. Read the file
11624 from the remote side with vFile:pread. */
a6b151f1
DJ
11625
11626static int
80152258
PA
11627remote_hostio_pread_vFile (struct target_ops *self,
11628 int fd, gdb_byte *read_buf, int len,
11629 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11630{
11631 struct remote_state *rs = get_remote_state ();
11632 char *p = rs->buf;
11633 char *attachment;
11634 int left = get_remote_packet_size ();
11635 int ret, attachment_len;
11636 int read_len;
11637
11638 remote_buffer_add_string (&p, &left, "vFile:pread:");
11639
11640 remote_buffer_add_int (&p, &left, fd);
11641 remote_buffer_add_string (&p, &left, ",");
11642
11643 remote_buffer_add_int (&p, &left, len);
11644 remote_buffer_add_string (&p, &left, ",");
11645
11646 remote_buffer_add_int (&p, &left, offset);
11647
11648 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11649 remote_errno, &attachment,
11650 &attachment_len);
11651
11652 if (ret < 0)
11653 return ret;
11654
bc20a4af 11655 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11656 read_buf, len);
11657 if (read_len != ret)
11658 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11659
11660 return ret;
11661}
11662
80152258
PA
11663/* Serve pread from the readahead cache. Returns number of bytes
11664 read, or 0 if the request can't be served from the cache. */
11665
11666static int
11667remote_hostio_pread_from_cache (struct remote_state *rs,
11668 int fd, gdb_byte *read_buf, size_t len,
11669 ULONGEST offset)
11670{
11671 struct readahead_cache *cache = &rs->readahead_cache;
11672
11673 if (cache->fd == fd
11674 && cache->offset <= offset
11675 && offset < cache->offset + cache->bufsize)
11676 {
11677 ULONGEST max = cache->offset + cache->bufsize;
11678
11679 if (offset + len > max)
11680 len = max - offset;
11681
11682 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11683 return len;
11684 }
11685
11686 return 0;
11687}
11688
11689/* Implementation of to_fileio_pread. */
11690
11691static int
11692remote_hostio_pread (struct target_ops *self,
11693 int fd, gdb_byte *read_buf, int len,
11694 ULONGEST offset, int *remote_errno)
11695{
11696 int ret;
11697 struct remote_state *rs = get_remote_state ();
11698 struct readahead_cache *cache = &rs->readahead_cache;
11699
11700 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11701 if (ret > 0)
11702 {
11703 cache->hit_count++;
11704
11705 if (remote_debug)
11706 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11707 pulongest (cache->hit_count));
11708 return ret;
11709 }
11710
11711 cache->miss_count++;
11712 if (remote_debug)
11713 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11714 pulongest (cache->miss_count));
11715
11716 cache->fd = fd;
11717 cache->offset = offset;
11718 cache->bufsize = get_remote_packet_size ();
224c3ddb 11719 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11720
11721 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11722 cache->offset, remote_errno);
11723 if (ret <= 0)
11724 {
11725 readahead_cache_invalidate_fd (fd);
11726 return ret;
11727 }
11728
11729 cache->bufsize = ret;
11730 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11731}
11732
12e2a5fd 11733/* Implementation of to_fileio_close. */
a6b151f1
DJ
11734
11735static int
df39ea25 11736remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11737{
11738 struct remote_state *rs = get_remote_state ();
11739 char *p = rs->buf;
11740 int left = get_remote_packet_size () - 1;
11741
80152258
PA
11742 readahead_cache_invalidate_fd (fd);
11743
a6b151f1
DJ
11744 remote_buffer_add_string (&p, &left, "vFile:close:");
11745
11746 remote_buffer_add_int (&p, &left, fd);
11747
11748 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11749 remote_errno, NULL, NULL);
11750}
11751
12e2a5fd 11752/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11753
11754static int
dbbca37d 11755remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11756 struct inferior *inf, const char *filename,
11757 int *remote_errno)
a6b151f1
DJ
11758{
11759 struct remote_state *rs = get_remote_state ();
11760 char *p = rs->buf;
11761 int left = get_remote_packet_size () - 1;
11762
15a201c8
GB
11763 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11764 return -1;
11765
a6b151f1
DJ
11766 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11767
11768 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11769 strlen (filename));
11770
11771 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11772 remote_errno, NULL, NULL);
11773}
11774
12e2a5fd 11775/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11776
11777static char *
fab5aa7c 11778remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11779 struct inferior *inf, const char *filename,
11780 int *remote_errno)
b9e7b9c3
UW
11781{
11782 struct remote_state *rs = get_remote_state ();
11783 char *p = rs->buf;
11784 char *attachment;
11785 int left = get_remote_packet_size ();
11786 int len, attachment_len;
11787 int read_len;
11788 char *ret;
11789
15a201c8
GB
11790 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11791 return NULL;
11792
b9e7b9c3
UW
11793 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11794
11795 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11796 strlen (filename));
11797
11798 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11799 remote_errno, &attachment,
11800 &attachment_len);
11801
11802 if (len < 0)
11803 return NULL;
11804
224c3ddb 11805 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11806
bc20a4af
PA
11807 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11808 (gdb_byte *) ret, len);
b9e7b9c3
UW
11809 if (read_len != len)
11810 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11811
11812 ret[len] = '\0';
11813 return ret;
11814}
11815
12e2a5fd 11816/* Implementation of to_fileio_fstat. */
0a93529c
GB
11817
11818static int
11819remote_hostio_fstat (struct target_ops *self,
11820 int fd, struct stat *st,
11821 int *remote_errno)
11822{
11823 struct remote_state *rs = get_remote_state ();
11824 char *p = rs->buf;
11825 int left = get_remote_packet_size ();
11826 int attachment_len, ret;
11827 char *attachment;
11828 struct fio_stat fst;
11829 int read_len;
11830
464b0089
GB
11831 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11832
11833 remote_buffer_add_int (&p, &left, fd);
11834
11835 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11836 remote_errno, &attachment,
11837 &attachment_len);
11838 if (ret < 0)
0a93529c 11839 {
464b0089
GB
11840 if (*remote_errno != FILEIO_ENOSYS)
11841 return ret;
11842
0a93529c
GB
11843 /* Strictly we should return -1, ENOSYS here, but when
11844 "set sysroot remote:" was implemented in August 2008
11845 BFD's need for a stat function was sidestepped with
11846 this hack. This was not remedied until March 2015
11847 so we retain the previous behavior to avoid breaking
11848 compatibility.
11849
11850 Note that the memset is a March 2015 addition; older
11851 GDBs set st_size *and nothing else* so the structure
11852 would have garbage in all other fields. This might
11853 break something but retaining the previous behavior
11854 here would be just too wrong. */
11855
11856 memset (st, 0, sizeof (struct stat));
11857 st->st_size = INT_MAX;
11858 return 0;
11859 }
11860
0a93529c
GB
11861 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11862 (gdb_byte *) &fst, sizeof (fst));
11863
11864 if (read_len != ret)
11865 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11866
11867 if (read_len != sizeof (fst))
11868 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11869 read_len, (int) sizeof (fst));
11870
11871 remote_fileio_to_host_stat (&fst, st);
11872
11873 return 0;
11874}
11875
12e2a5fd 11876/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11877
11878static int
11879remote_filesystem_is_local (struct target_ops *self)
11880{
11881 /* Valgrind GDB presents itself as a remote target but works
11882 on the local filesystem: it does not implement remote get
11883 and users are not expected to set a sysroot. To handle
11884 this case we treat the remote filesystem as local if the
11885 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11886 does not support vFile:open. */
a3be80c3 11887 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11888 {
11889 enum packet_support ps = packet_support (PACKET_vFile_open);
11890
11891 if (ps == PACKET_SUPPORT_UNKNOWN)
11892 {
11893 int fd, remote_errno;
11894
11895 /* Try opening a file to probe support. The supplied
11896 filename is irrelevant, we only care about whether
11897 the stub recognizes the packet or not. */
07c138c8 11898 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11899 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11900 &remote_errno);
11901
11902 if (fd >= 0)
11903 remote_hostio_close (self, fd, &remote_errno);
11904
11905 ps = packet_support (PACKET_vFile_open);
11906 }
11907
11908 if (ps == PACKET_DISABLE)
11909 {
11910 static int warning_issued = 0;
11911
11912 if (!warning_issued)
11913 {
11914 warning (_("remote target does not support file"
11915 " transfer, attempting to access files"
11916 " from local filesystem."));
11917 warning_issued = 1;
11918 }
11919
11920 return 1;
11921 }
11922 }
11923
11924 return 0;
11925}
11926
a6b151f1
DJ
11927static int
11928remote_fileio_errno_to_host (int errnum)
11929{
11930 switch (errnum)
11931 {
11932 case FILEIO_EPERM:
11933 return EPERM;
11934 case FILEIO_ENOENT:
11935 return ENOENT;
11936 case FILEIO_EINTR:
11937 return EINTR;
11938 case FILEIO_EIO:
11939 return EIO;
11940 case FILEIO_EBADF:
11941 return EBADF;
11942 case FILEIO_EACCES:
11943 return EACCES;
11944 case FILEIO_EFAULT:
11945 return EFAULT;
11946 case FILEIO_EBUSY:
11947 return EBUSY;
11948 case FILEIO_EEXIST:
11949 return EEXIST;
11950 case FILEIO_ENODEV:
11951 return ENODEV;
11952 case FILEIO_ENOTDIR:
11953 return ENOTDIR;
11954 case FILEIO_EISDIR:
11955 return EISDIR;
11956 case FILEIO_EINVAL:
11957 return EINVAL;
11958 case FILEIO_ENFILE:
11959 return ENFILE;
11960 case FILEIO_EMFILE:
11961 return EMFILE;
11962 case FILEIO_EFBIG:
11963 return EFBIG;
11964 case FILEIO_ENOSPC:
11965 return ENOSPC;
11966 case FILEIO_ESPIPE:
11967 return ESPIPE;
11968 case FILEIO_EROFS:
11969 return EROFS;
11970 case FILEIO_ENOSYS:
11971 return ENOSYS;
11972 case FILEIO_ENAMETOOLONG:
11973 return ENAMETOOLONG;
11974 }
11975 return -1;
11976}
11977
11978static char *
11979remote_hostio_error (int errnum)
11980{
11981 int host_error = remote_fileio_errno_to_host (errnum);
11982
11983 if (host_error == -1)
11984 error (_("Unknown remote I/O error %d"), errnum);
11985 else
11986 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11987}
11988
a6b151f1
DJ
11989static void
11990remote_hostio_close_cleanup (void *opaque)
11991{
11992 int fd = *(int *) opaque;
11993 int remote_errno;
11994
df39ea25 11995 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11996}
11997
11998void
11999remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12000{
12001 struct cleanup *back_to, *close_cleanup;
12002 int retcode, fd, remote_errno, bytes, io_size;
a6b151f1
DJ
12003 gdb_byte *buffer;
12004 int bytes_in_buffer;
12005 int saw_eof;
12006 ULONGEST offset;
5d93a237 12007 struct remote_state *rs = get_remote_state ();
a6b151f1 12008
5d93a237 12009 if (!rs->remote_desc)
a6b151f1
DJ
12010 error (_("command can only be used with remote target"));
12011
d419f42d 12012 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
12013 if (file == NULL)
12014 perror_with_name (local_file);
a6b151f1 12015
07c138c8 12016 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 12017 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 12018 | FILEIO_O_TRUNC),
4313b8c0 12019 0700, 0, &remote_errno);
a6b151f1
DJ
12020 if (fd == -1)
12021 remote_hostio_error (remote_errno);
12022
12023 /* Send up to this many bytes at once. They won't all fit in the
12024 remote packet limit, so we'll transfer slightly fewer. */
12025 io_size = get_remote_packet_size ();
224c3ddb 12026 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 12027 back_to = make_cleanup (xfree, buffer);
a6b151f1
DJ
12028
12029 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12030
12031 bytes_in_buffer = 0;
12032 saw_eof = 0;
12033 offset = 0;
12034 while (bytes_in_buffer || !saw_eof)
12035 {
12036 if (!saw_eof)
12037 {
3e43a32a
MS
12038 bytes = fread (buffer + bytes_in_buffer, 1,
12039 io_size - bytes_in_buffer,
d419f42d 12040 file.get ());
a6b151f1
DJ
12041 if (bytes == 0)
12042 {
d419f42d 12043 if (ferror (file.get ()))
a6b151f1
DJ
12044 error (_("Error reading %s."), local_file);
12045 else
12046 {
12047 /* EOF. Unless there is something still in the
12048 buffer from the last iteration, we are done. */
12049 saw_eof = 1;
12050 if (bytes_in_buffer == 0)
12051 break;
12052 }
12053 }
12054 }
12055 else
12056 bytes = 0;
12057
12058 bytes += bytes_in_buffer;
12059 bytes_in_buffer = 0;
12060
0d866f62
TT
12061 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12062 fd, buffer, bytes,
3e43a32a 12063 offset, &remote_errno);
a6b151f1
DJ
12064
12065 if (retcode < 0)
12066 remote_hostio_error (remote_errno);
12067 else if (retcode == 0)
12068 error (_("Remote write of %d bytes returned 0!"), bytes);
12069 else if (retcode < bytes)
12070 {
12071 /* Short write. Save the rest of the read data for the next
12072 write. */
12073 bytes_in_buffer = bytes - retcode;
12074 memmove (buffer, buffer + retcode, bytes_in_buffer);
12075 }
12076
12077 offset += retcode;
12078 }
12079
12080 discard_cleanups (close_cleanup);
df39ea25 12081 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
12082 remote_hostio_error (remote_errno);
12083
12084 if (from_tty)
12085 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12086 do_cleanups (back_to);
12087}
12088
12089void
12090remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12091{
12092 struct cleanup *back_to, *close_cleanup;
cea39f65 12093 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
12094 gdb_byte *buffer;
12095 ULONGEST offset;
5d93a237 12096 struct remote_state *rs = get_remote_state ();
a6b151f1 12097
5d93a237 12098 if (!rs->remote_desc)
a6b151f1
DJ
12099 error (_("command can only be used with remote target"));
12100
07c138c8 12101 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
12102 remote_file, FILEIO_O_RDONLY, 0, 0,
12103 &remote_errno);
a6b151f1
DJ
12104 if (fd == -1)
12105 remote_hostio_error (remote_errno);
12106
d419f42d 12107 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12108 if (file == NULL)
12109 perror_with_name (local_file);
a6b151f1
DJ
12110
12111 /* Send up to this many bytes at once. They won't all fit in the
12112 remote packet limit, so we'll transfer slightly fewer. */
12113 io_size = get_remote_packet_size ();
224c3ddb 12114 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 12115 back_to = make_cleanup (xfree, buffer);
a6b151f1
DJ
12116
12117 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12118
12119 offset = 0;
12120 while (1)
12121 {
a3be983c
TT
12122 bytes = remote_hostio_pread (find_target_at (process_stratum),
12123 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
12124 if (bytes == 0)
12125 /* Success, but no bytes, means end-of-file. */
12126 break;
12127 if (bytes == -1)
12128 remote_hostio_error (remote_errno);
12129
12130 offset += bytes;
12131
d419f42d 12132 bytes = fwrite (buffer, 1, bytes, file.get ());
a6b151f1
DJ
12133 if (bytes == 0)
12134 perror_with_name (local_file);
12135 }
12136
12137 discard_cleanups (close_cleanup);
df39ea25 12138 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
12139 remote_hostio_error (remote_errno);
12140
12141 if (from_tty)
12142 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12143 do_cleanups (back_to);
12144}
12145
12146void
12147remote_file_delete (const char *remote_file, int from_tty)
12148{
12149 int retcode, remote_errno;
5d93a237 12150 struct remote_state *rs = get_remote_state ();
a6b151f1 12151
5d93a237 12152 if (!rs->remote_desc)
a6b151f1
DJ
12153 error (_("command can only be used with remote target"));
12154
dbbca37d 12155 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 12156 NULL, remote_file, &remote_errno);
a6b151f1
DJ
12157 if (retcode == -1)
12158 remote_hostio_error (remote_errno);
12159
12160 if (from_tty)
12161 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12162}
12163
12164static void
ac88e2de 12165remote_put_command (const char *args, int from_tty)
a6b151f1 12166{
d1a41061
PP
12167 if (args == NULL)
12168 error_no_arg (_("file to put"));
12169
773a1edc 12170 gdb_argv argv (args);
a6b151f1
DJ
12171 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12172 error (_("Invalid parameters to remote put"));
12173
12174 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12175}
12176
12177static void
ac88e2de 12178remote_get_command (const char *args, int from_tty)
a6b151f1 12179{
d1a41061
PP
12180 if (args == NULL)
12181 error_no_arg (_("file to get"));
12182
773a1edc 12183 gdb_argv argv (args);
a6b151f1
DJ
12184 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12185 error (_("Invalid parameters to remote get"));
12186
12187 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12188}
12189
12190static void
ac88e2de 12191remote_delete_command (const char *args, int from_tty)
a6b151f1 12192{
d1a41061
PP
12193 if (args == NULL)
12194 error_no_arg (_("file to delete"));
12195
773a1edc 12196 gdb_argv argv (args);
a6b151f1
DJ
12197 if (argv[0] == NULL || argv[1] != NULL)
12198 error (_("Invalid parameters to remote delete"));
12199
12200 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12201}
12202
12203static void
981a3fb3 12204remote_command (const char *args, int from_tty)
a6b151f1 12205{
635c7e8a 12206 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12207}
12208
b2175913 12209static int
19db3e69 12210remote_can_execute_reverse (struct target_ops *self)
b2175913 12211{
4082afcc
PA
12212 if (packet_support (PACKET_bs) == PACKET_ENABLE
12213 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
12214 return 1;
12215 else
12216 return 0;
b2175913
MS
12217}
12218
74531fed 12219static int
2a9a2795 12220remote_supports_non_stop (struct target_ops *self)
74531fed
PA
12221{
12222 return 1;
12223}
12224
03583c20 12225static int
2bfc0540 12226remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
12227{
12228 /* Only supported in extended mode. */
12229 return 0;
12230}
12231
8a305172 12232static int
86ce2668 12233remote_supports_multi_process (struct target_ops *self)
8a305172
PA
12234{
12235 struct remote_state *rs = get_remote_state ();
a744cf53 12236
8020350c 12237 return remote_multi_process_p (rs);
8a305172
PA
12238}
12239
70221824 12240static int
782b2b07
SS
12241remote_supports_cond_tracepoints (void)
12242{
4082afcc 12243 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12244}
12245
3788aec7 12246static int
efcc2da7 12247remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 12248{
4082afcc 12249 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12250}
12251
70221824 12252static int
7a697b8d
SS
12253remote_supports_fast_tracepoints (void)
12254{
4082afcc 12255 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12256}
12257
0fb4aa4b
PA
12258static int
12259remote_supports_static_tracepoints (void)
12260{
4082afcc 12261 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12262}
12263
1e4d1764
YQ
12264static int
12265remote_supports_install_in_trace (void)
12266{
4082afcc 12267 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12268}
12269
d248b706 12270static int
7d178d6a 12271remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 12272{
4082afcc
PA
12273 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12274 == PACKET_ENABLE);
d248b706
KY
12275}
12276
3065dfb6 12277static int
6de37a3a 12278remote_supports_string_tracing (struct target_ops *self)
3065dfb6 12279{
4082afcc 12280 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12281}
12282
d3ce09f5 12283static int
78eff0ec 12284remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 12285{
4082afcc 12286 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12287}
12288
35b1e5cc 12289static void
ecae04e1 12290remote_trace_init (struct target_ops *self)
35b1e5cc 12291{
b6bb3468
PA
12292 struct remote_state *rs = get_remote_state ();
12293
35b1e5cc 12294 putpkt ("QTinit");
b6bb3468
PA
12295 remote_get_noisy_reply ();
12296 if (strcmp (rs->buf, "OK") != 0)
35b1e5cc
SS
12297 error (_("Target does not support this command."));
12298}
12299
12300static void free_actions_list (char **actions_list);
12301static void free_actions_list_cleanup_wrapper (void *);
12302static void
12303free_actions_list_cleanup_wrapper (void *al)
12304{
19ba03f4 12305 free_actions_list ((char **) al);
35b1e5cc
SS
12306}
12307
12308static void
12309free_actions_list (char **actions_list)
12310{
12311 int ndx;
12312
12313 if (actions_list == 0)
12314 return;
12315
12316 for (ndx = 0; actions_list[ndx]; ndx++)
12317 xfree (actions_list[ndx]);
12318
12319 xfree (actions_list);
12320}
12321
409873ef
SS
12322/* Recursive routine to walk through command list including loops, and
12323 download packets for each command. */
12324
12325static void
12326remote_download_command_source (int num, ULONGEST addr,
12327 struct command_line *cmds)
12328{
12329 struct remote_state *rs = get_remote_state ();
12330 struct command_line *cmd;
12331
12332 for (cmd = cmds; cmd; cmd = cmd->next)
12333 {
0df8b418 12334 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12335 strcpy (rs->buf, "QTDPsrc:");
12336 encode_source_string (num, addr, "cmd", cmd->line,
12337 rs->buf + strlen (rs->buf),
12338 rs->buf_size - strlen (rs->buf));
12339 putpkt (rs->buf);
b6bb3468
PA
12340 remote_get_noisy_reply ();
12341 if (strcmp (rs->buf, "OK"))
409873ef
SS
12342 warning (_("Target does not support source download."));
12343
12344 if (cmd->control_type == while_control
12345 || cmd->control_type == while_stepping_control)
12346 {
12347 remote_download_command_source (num, addr, *cmd->body_list);
12348
0df8b418 12349 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12350 strcpy (rs->buf, "QTDPsrc:");
12351 encode_source_string (num, addr, "cmd", "end",
12352 rs->buf + strlen (rs->buf),
12353 rs->buf_size - strlen (rs->buf));
12354 putpkt (rs->buf);
b6bb3468
PA
12355 remote_get_noisy_reply ();
12356 if (strcmp (rs->buf, "OK"))
409873ef
SS
12357 warning (_("Target does not support source download."));
12358 }
12359 }
12360}
12361
35b1e5cc 12362static void
548f7808 12363remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 12364{
bba74b36 12365#define BUF_SIZE 2048
e8ba3115 12366
35b1e5cc 12367 CORE_ADDR tpaddr;
409873ef 12368 char addrbuf[40];
bba74b36 12369 char buf[BUF_SIZE];
35b1e5cc
SS
12370 char **tdp_actions;
12371 char **stepping_actions;
12372 int ndx;
12373 struct cleanup *old_chain = NULL;
35b1e5cc 12374 char *pkt;
e8ba3115 12375 struct breakpoint *b = loc->owner;
d9b3f62e 12376 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 12377 struct remote_state *rs = get_remote_state ();
35b1e5cc 12378
dc673c81 12379 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12380 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
12381 tdp_actions);
12382 (void) make_cleanup (free_actions_list_cleanup_wrapper,
12383 stepping_actions);
12384
12385 tpaddr = loc->address;
12386 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
12387 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12388 addrbuf, /* address */
12389 (b->enable_state == bp_enabled ? 'E' : 'D'),
12390 t->step_count, t->pass_count);
e8ba3115
YQ
12391 /* Fast tracepoints are mostly handled by the target, but we can
12392 tell the target how big of an instruction block should be moved
12393 around. */
12394 if (b->type == bp_fast_tracepoint)
12395 {
12396 /* Only test for support at download time; we may not know
12397 target capabilities at definition time. */
12398 if (remote_supports_fast_tracepoints ())
35b1e5cc 12399 {
6b940e6a
PL
12400 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12401 NULL))
bba74b36 12402 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 12403 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 12404 else
e8ba3115
YQ
12405 /* If it passed validation at definition but fails now,
12406 something is very wrong. */
12407 internal_error (__FILE__, __LINE__,
12408 _("Fast tracepoint not "
12409 "valid during download"));
35b1e5cc 12410 }
e8ba3115
YQ
12411 else
12412 /* Fast tracepoints are functionally identical to regular
12413 tracepoints, so don't take lack of support as a reason to
12414 give up on the trace run. */
12415 warning (_("Target does not support fast tracepoints, "
12416 "downloading %d as regular tracepoint"), b->number);
12417 }
12418 else if (b->type == bp_static_tracepoint)
12419 {
12420 /* Only test for support at download time; we may not know
12421 target capabilities at definition time. */
12422 if (remote_supports_static_tracepoints ())
0fb4aa4b 12423 {
e8ba3115 12424 struct static_tracepoint_marker marker;
0fb4aa4b 12425
e8ba3115
YQ
12426 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12427 strcat (buf, ":S");
0fb4aa4b 12428 else
e8ba3115 12429 error (_("Static tracepoint not valid during download"));
0fb4aa4b 12430 }
e8ba3115
YQ
12431 else
12432 /* Fast tracepoints are functionally identical to regular
12433 tracepoints, so don't take lack of support as a reason
12434 to give up on the trace run. */
12435 error (_("Target does not support static tracepoints"));
12436 }
12437 /* If the tracepoint has a conditional, make it into an agent
12438 expression and append to the definition. */
12439 if (loc->cond)
12440 {
12441 /* Only test support at download time, we may not know target
12442 capabilities at definition time. */
12443 if (remote_supports_cond_tracepoints ())
35b1e5cc 12444 {
833177a4 12445 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
bba74b36
YQ
12446 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12447 aexpr->len);
e8ba3115
YQ
12448 pkt = buf + strlen (buf);
12449 for (ndx = 0; ndx < aexpr->len; ++ndx)
12450 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12451 *pkt = '\0';
35b1e5cc 12452 }
e8ba3115
YQ
12453 else
12454 warning (_("Target does not support conditional tracepoints, "
12455 "ignoring tp %d cond"), b->number);
12456 }
35b1e5cc 12457
d9b3f62e 12458 if (b->commands || *default_collect)
e8ba3115
YQ
12459 strcat (buf, "-");
12460 putpkt (buf);
b6bb3468
PA
12461 remote_get_noisy_reply ();
12462 if (strcmp (rs->buf, "OK"))
e8ba3115 12463 error (_("Target does not support tracepoints."));
35b1e5cc 12464
e8ba3115
YQ
12465 /* do_single_steps (t); */
12466 if (tdp_actions)
12467 {
12468 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 12469 {
e8ba3115 12470 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
12471 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12472 b->number, addrbuf, /* address */
12473 tdp_actions[ndx],
12474 ((tdp_actions[ndx + 1] || stepping_actions)
12475 ? '-' : 0));
e8ba3115 12476 putpkt (buf);
b6bb3468
PA
12477 remote_get_noisy_reply ();
12478 if (strcmp (rs->buf, "OK"))
e8ba3115 12479 error (_("Error on target while setting tracepoints."));
35b1e5cc 12480 }
e8ba3115
YQ
12481 }
12482 if (stepping_actions)
12483 {
12484 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 12485 {
e8ba3115 12486 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
12487 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12488 b->number, addrbuf, /* address */
12489 ((ndx == 0) ? "S" : ""),
12490 stepping_actions[ndx],
12491 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115 12492 putpkt (buf);
b6bb3468
PA
12493 remote_get_noisy_reply ();
12494 if (strcmp (rs->buf, "OK"))
e8ba3115 12495 error (_("Error on target while setting tracepoints."));
35b1e5cc 12496 }
e8ba3115 12497 }
409873ef 12498
4082afcc 12499 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 12500 {
f00aae0f 12501 if (b->location != NULL)
409873ef 12502 {
e8ba3115 12503 strcpy (buf, "QTDPsrc:");
f00aae0f 12504 encode_source_string (b->number, loc->address, "at",
d28cd78a 12505 event_location_to_string (b->location.get ()),
f00aae0f 12506 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115 12507 putpkt (buf);
b6bb3468
PA
12508 remote_get_noisy_reply ();
12509 if (strcmp (rs->buf, "OK"))
e8ba3115 12510 warning (_("Target does not support source download."));
409873ef 12511 }
e8ba3115
YQ
12512 if (b->cond_string)
12513 {
12514 strcpy (buf, "QTDPsrc:");
12515 encode_source_string (b->number, loc->address,
12516 "cond", b->cond_string, buf + strlen (buf),
12517 2048 - strlen (buf));
12518 putpkt (buf);
b6bb3468
PA
12519 remote_get_noisy_reply ();
12520 if (strcmp (rs->buf, "OK"))
e8ba3115
YQ
12521 warning (_("Target does not support source download."));
12522 }
12523 remote_download_command_source (b->number, loc->address,
12524 breakpoint_commands (b));
35b1e5cc 12525 }
e8ba3115
YQ
12526
12527 do_cleanups (old_chain);
35b1e5cc
SS
12528}
12529
1e4d1764 12530static int
a52a8357 12531remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 12532{
1e51243a
PA
12533 struct remote_state *rs = get_remote_state ();
12534 struct trace_status *ts;
12535 int status;
12536
12537 /* Don't try to install tracepoints until we've relocated our
12538 symbols, and fetched and merged the target's tracepoint list with
12539 ours. */
12540 if (rs->starting_up)
12541 return 0;
12542
12543 ts = current_trace_status ();
8bd200f1 12544 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
12545
12546 if (status == -1 || !ts->running_known || !ts->running)
12547 return 0;
12548
12549 /* If we are in a tracing experiment, but remote stub doesn't support
12550 installing tracepoint in trace, we have to return. */
12551 if (!remote_supports_install_in_trace ())
12552 return 0;
12553
12554 return 1;
12555}
12556
12557
35b1e5cc 12558static void
559d2b81
TT
12559remote_download_trace_state_variable (struct target_ops *self,
12560 struct trace_state_variable *tsv)
35b1e5cc
SS
12561{
12562 struct remote_state *rs = get_remote_state ();
00bf0b85 12563 char *p;
35b1e5cc 12564
bba74b36
YQ
12565 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12566 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12567 tsv->builtin);
00bf0b85
SS
12568 p = rs->buf + strlen (rs->buf);
12569 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12570 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 12571 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 12572 *p++ = '\0';
35b1e5cc 12573 putpkt (rs->buf);
b6bb3468
PA
12574 remote_get_noisy_reply ();
12575 if (*rs->buf == '\0')
ad91cd99 12576 error (_("Target does not support this command."));
b6bb3468 12577 if (strcmp (rs->buf, "OK") != 0)
ad91cd99 12578 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12579}
12580
d248b706 12581static void
46670d57
TT
12582remote_enable_tracepoint (struct target_ops *self,
12583 struct bp_location *location)
d248b706
KY
12584{
12585 struct remote_state *rs = get_remote_state ();
12586 char addr_buf[40];
12587
12588 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12589 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12590 location->owner->number, addr_buf);
d248b706 12591 putpkt (rs->buf);
b6bb3468 12592 remote_get_noisy_reply ();
d248b706
KY
12593 if (*rs->buf == '\0')
12594 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12595 if (strcmp (rs->buf, "OK") != 0)
12596 error (_("Error on target while enabling tracepoint."));
12597}
12598
12599static void
780b049c
TT
12600remote_disable_tracepoint (struct target_ops *self,
12601 struct bp_location *location)
d248b706
KY
12602{
12603 struct remote_state *rs = get_remote_state ();
12604 char addr_buf[40];
12605
12606 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12607 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12608 location->owner->number, addr_buf);
d248b706 12609 putpkt (rs->buf);
b6bb3468 12610 remote_get_noisy_reply ();
d248b706
KY
12611 if (*rs->buf == '\0')
12612 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12613 if (strcmp (rs->buf, "OK") != 0)
12614 error (_("Error on target while disabling tracepoint."));
12615}
12616
35b1e5cc 12617static void
583f9a86 12618remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12619{
12620 asection *s;
81b9b86e 12621 bfd *abfd = NULL;
35b1e5cc 12622 bfd_size_type size;
608bcef2 12623 bfd_vma vma;
35b1e5cc 12624 int anysecs = 0;
c2fa21f1 12625 int offset = 0;
35b1e5cc
SS
12626
12627 if (!exec_bfd)
12628 return; /* No information to give. */
12629
b6bb3468
PA
12630 struct remote_state *rs = get_remote_state ();
12631
12632 strcpy (rs->buf, "QTro");
12633 offset = strlen (rs->buf);
35b1e5cc
SS
12634 for (s = exec_bfd->sections; s; s = s->next)
12635 {
12636 char tmp1[40], tmp2[40];
c2fa21f1 12637 int sec_length;
35b1e5cc
SS
12638
12639 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12640 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12641 (s->flags & SEC_READONLY) == 0)
12642 continue;
12643
12644 anysecs = 1;
81b9b86e 12645 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12646 size = bfd_get_section_size (s);
608bcef2
HZ
12647 sprintf_vma (tmp1, vma);
12648 sprintf_vma (tmp2, vma + size);
c2fa21f1 12649 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
b6bb3468 12650 if (offset + sec_length + 1 > rs->buf_size)
c2fa21f1 12651 {
4082afcc 12652 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12653 warning (_("\
c2fa21f1
HZ
12654Too many sections for read-only sections definition packet."));
12655 break;
12656 }
b6bb3468 12657 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
bba74b36 12658 tmp1, tmp2);
c2fa21f1 12659 offset += sec_length;
35b1e5cc
SS
12660 }
12661 if (anysecs)
12662 {
b6bb3468
PA
12663 putpkt (rs->buf);
12664 getpkt (&rs->buf, &rs->buf_size, 0);
35b1e5cc
SS
12665 }
12666}
12667
12668static void
e2d1aae3 12669remote_trace_start (struct target_ops *self)
35b1e5cc 12670{
b6bb3468
PA
12671 struct remote_state *rs = get_remote_state ();
12672
35b1e5cc 12673 putpkt ("QTStart");
b6bb3468
PA
12674 remote_get_noisy_reply ();
12675 if (*rs->buf == '\0')
ad91cd99 12676 error (_("Target does not support this command."));
b6bb3468
PA
12677 if (strcmp (rs->buf, "OK") != 0)
12678 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
12679}
12680
12681static int
8bd200f1 12682remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12683{
953b98d1 12684 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12685 char *p = NULL;
0df8b418 12686 /* FIXME we need to get register block size some other way. */
00bf0b85 12687 extern int trace_regblock_size;
bd3eecc3 12688 enum packet_result result;
b6bb3468 12689 struct remote_state *rs = get_remote_state ();
bd3eecc3 12690
4082afcc 12691 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12692 return -1;
a744cf53 12693
5cd63fda
PA
12694 trace_regblock_size
12695 = get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
00bf0b85 12696
049dc89b
JK
12697 putpkt ("qTStatus");
12698
492d29ea 12699 TRY
67f41397 12700 {
b6bb3468 12701 p = remote_get_noisy_reply ();
67f41397 12702 }
492d29ea 12703 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12704 {
598d3636
JK
12705 if (ex.error != TARGET_CLOSE_ERROR)
12706 {
12707 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12708 return -1;
12709 }
12710 throw_exception (ex);
67f41397 12711 }
492d29ea 12712 END_CATCH
00bf0b85 12713
bd3eecc3
PA
12714 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12715
00bf0b85 12716 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12717 if (result == PACKET_UNKNOWN)
00bf0b85 12718 return -1;
35b1e5cc 12719
00bf0b85 12720 /* We're working with a live target. */
f5911ea1 12721 ts->filename = NULL;
00bf0b85 12722
00bf0b85 12723 if (*p++ != 'T')
b6bb3468 12724 error (_("Bogus trace status reply from target: %s"), rs->buf);
35b1e5cc 12725
84cebc4a
YQ
12726 /* Function 'parse_trace_status' sets default value of each field of
12727 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12728 parse_trace_status (p, ts);
12729
12730 return ts->running;
35b1e5cc
SS
12731}
12732
70221824 12733static void
db90e85c 12734remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12735 struct uploaded_tp *utp)
12736{
12737 struct remote_state *rs = get_remote_state ();
f196051f
SS
12738 char *reply;
12739 struct bp_location *loc;
12740 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12741 size_t size = get_remote_packet_size ();
f196051f
SS
12742
12743 if (tp)
12744 {
c1fc2657 12745 tp->hit_count = 0;
f196051f 12746 tp->traceframe_usage = 0;
c1fc2657 12747 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
12748 {
12749 /* If the tracepoint was never downloaded, don't go asking for
12750 any status. */
12751 if (tp->number_on_target == 0)
12752 continue;
bba74b36
YQ
12753 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12754 phex_nz (loc->address, 0));
f196051f 12755 putpkt (rs->buf);
b6bb3468 12756 reply = remote_get_noisy_reply ();
f196051f
SS
12757 if (reply && *reply)
12758 {
12759 if (*reply == 'V')
12760 parse_tracepoint_status (reply + 1, bp, utp);
12761 }
12762 }
12763 }
12764 else if (utp)
12765 {
12766 utp->hit_count = 0;
12767 utp->traceframe_usage = 0;
bba74b36
YQ
12768 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12769 phex_nz (utp->addr, 0));
f196051f 12770 putpkt (rs->buf);
b6bb3468 12771 reply = remote_get_noisy_reply ();
f196051f
SS
12772 if (reply && *reply)
12773 {
12774 if (*reply == 'V')
12775 parse_tracepoint_status (reply + 1, bp, utp);
12776 }
12777 }
12778}
12779
35b1e5cc 12780static void
74499f1b 12781remote_trace_stop (struct target_ops *self)
35b1e5cc 12782{
b6bb3468
PA
12783 struct remote_state *rs = get_remote_state ();
12784
35b1e5cc 12785 putpkt ("QTStop");
b6bb3468
PA
12786 remote_get_noisy_reply ();
12787 if (*rs->buf == '\0')
ad91cd99 12788 error (_("Target does not support this command."));
b6bb3468
PA
12789 if (strcmp (rs->buf, "OK") != 0)
12790 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
12791}
12792
12793static int
bd4c6793
TT
12794remote_trace_find (struct target_ops *self,
12795 enum trace_find_type type, int num,
cc5925ad 12796 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12797 int *tpp)
12798{
12799 struct remote_state *rs = get_remote_state ();
bba74b36 12800 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12801 char *p, *reply;
12802 int target_frameno = -1, target_tracept = -1;
12803
e6e4e701
PA
12804 /* Lookups other than by absolute frame number depend on the current
12805 trace selected, so make sure it is correct on the remote end
12806 first. */
12807 if (type != tfind_number)
12808 set_remote_traceframe ();
12809
35b1e5cc
SS
12810 p = rs->buf;
12811 strcpy (p, "QTFrame:");
12812 p = strchr (p, '\0');
12813 switch (type)
12814 {
12815 case tfind_number:
bba74b36 12816 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12817 break;
12818 case tfind_pc:
bba74b36 12819 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12820 break;
12821 case tfind_tp:
bba74b36 12822 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12823 break;
12824 case tfind_range:
bba74b36
YQ
12825 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12826 phex_nz (addr2, 0));
35b1e5cc
SS
12827 break;
12828 case tfind_outside:
bba74b36
YQ
12829 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12830 phex_nz (addr2, 0));
35b1e5cc
SS
12831 break;
12832 default:
9b20d036 12833 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12834 }
12835
12836 putpkt (rs->buf);
b6bb3468 12837 reply = remote_get_noisy_reply ();
ad91cd99
PA
12838 if (*reply == '\0')
12839 error (_("Target does not support this command."));
35b1e5cc
SS
12840
12841 while (reply && *reply)
12842 switch (*reply)
12843 {
12844 case 'F':
f197e0f1
VP
12845 p = ++reply;
12846 target_frameno = (int) strtol (p, &reply, 16);
12847 if (reply == p)
12848 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12849 /* Don't update our remote traceframe number cache on failure
12850 to select a remote traceframe. */
f197e0f1
VP
12851 if (target_frameno == -1)
12852 return -1;
35b1e5cc
SS
12853 break;
12854 case 'T':
f197e0f1
VP
12855 p = ++reply;
12856 target_tracept = (int) strtol (p, &reply, 16);
12857 if (reply == p)
12858 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12859 break;
12860 case 'O': /* "OK"? */
12861 if (reply[1] == 'K' && reply[2] == '\0')
12862 reply += 2;
12863 else
12864 error (_("Bogus reply from target: %s"), reply);
12865 break;
12866 default:
12867 error (_("Bogus reply from target: %s"), reply);
12868 }
12869 if (tpp)
12870 *tpp = target_tracept;
e6e4e701 12871
262e1174 12872 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12873 return target_frameno;
12874}
12875
12876static int
4011015b
TT
12877remote_get_trace_state_variable_value (struct target_ops *self,
12878 int tsvnum, LONGEST *val)
35b1e5cc
SS
12879{
12880 struct remote_state *rs = get_remote_state ();
12881 char *reply;
12882 ULONGEST uval;
12883
e6e4e701
PA
12884 set_remote_traceframe ();
12885
bba74b36 12886 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 12887 putpkt (rs->buf);
b6bb3468 12888 reply = remote_get_noisy_reply ();
35b1e5cc
SS
12889 if (reply && *reply)
12890 {
12891 if (*reply == 'V')
12892 {
12893 unpack_varlen_hex (reply + 1, &uval);
12894 *val = (LONGEST) uval;
12895 return 1;
12896 }
12897 }
12898 return 0;
12899}
12900
00bf0b85 12901static int
dc3decaf 12902remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12903{
12904 struct remote_state *rs = get_remote_state ();
12905 char *p, *reply;
12906
12907 p = rs->buf;
12908 strcpy (p, "QTSave:");
12909 p += strlen (p);
12910 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12911 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12912 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12913 *p++ = '\0';
12914 putpkt (rs->buf);
b6bb3468 12915 reply = remote_get_noisy_reply ();
d6c5869f 12916 if (*reply == '\0')
ad91cd99
PA
12917 error (_("Target does not support this command."));
12918 if (strcmp (reply, "OK") != 0)
12919 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12920 return 0;
12921}
12922
12923/* This is basically a memory transfer, but needs to be its own packet
12924 because we don't know how the target actually organizes its trace
12925 memory, plus we want to be able to ask for as much as possible, but
12926 not be unhappy if we don't get as much as we ask for. */
12927
12928static LONGEST
88ee6f45
TT
12929remote_get_raw_trace_data (struct target_ops *self,
12930 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12931{
12932 struct remote_state *rs = get_remote_state ();
12933 char *reply;
12934 char *p;
12935 int rslt;
12936
12937 p = rs->buf;
12938 strcpy (p, "qTBuffer:");
12939 p += strlen (p);
12940 p += hexnumstr (p, offset);
12941 *p++ = ',';
12942 p += hexnumstr (p, len);
12943 *p++ = '\0';
12944
12945 putpkt (rs->buf);
b6bb3468 12946 reply = remote_get_noisy_reply ();
00bf0b85
SS
12947 if (reply && *reply)
12948 {
12949 /* 'l' by itself means we're at the end of the buffer and
12950 there is nothing more to get. */
12951 if (*reply == 'l')
12952 return 0;
12953
12954 /* Convert the reply into binary. Limit the number of bytes to
12955 convert according to our passed-in buffer size, rather than
12956 what was returned in the packet; if the target is
12957 unexpectedly generous and gives us a bigger reply than we
12958 asked for, we don't want to crash. */
b6bb3468 12959 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
12960 return rslt;
12961 }
12962
12963 /* Something went wrong, flag as an error. */
12964 return -1;
12965}
12966
35b1e5cc 12967static void
37b25738 12968remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12969{
12970 struct remote_state *rs = get_remote_state ();
12971
4082afcc 12972 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12973 {
ad91cd99
PA
12974 char *reply;
12975
bba74b36 12976 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12977 putpkt (rs->buf);
b6bb3468 12978 reply = remote_get_noisy_reply ();
ad91cd99 12979 if (*reply == '\0')
33da3f1c 12980 error (_("Target does not support this command."));
ad91cd99
PA
12981 if (strcmp (reply, "OK") != 0)
12982 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12983 }
12984 else if (val)
12985 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12986}
12987
dc146f7c
VP
12988static int
12989remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12990{
12991 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12992
fe978cb0
PA
12993 if (info && info->priv)
12994 return info->priv->core;
dc146f7c
VP
12995 return -1;
12996}
12997
4daf5ac0 12998static void
736d5b1f 12999remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
13000{
13001 struct remote_state *rs = get_remote_state ();
ad91cd99 13002 char *reply;
4daf5ac0 13003
bba74b36 13004 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 13005 putpkt (rs->buf);
b6bb3468 13006 reply = remote_get_noisy_reply ();
ad91cd99 13007 if (*reply == '\0')
4daf5ac0 13008 error (_("Target does not support this command."));
ad91cd99
PA
13009 if (strcmp (reply, "OK") != 0)
13010 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
13011}
13012
2098b393 13013static traceframe_info_up
a893e81f 13014remote_traceframe_info (struct target_ops *self)
b3b9301e 13015{
b7b030ad
TT
13016 gdb::unique_xmalloc_ptr<char> text
13017 = target_read_stralloc (&current_target, TARGET_OBJECT_TRACEFRAME_INFO,
13018 NULL);
b3b9301e 13019 if (text != NULL)
b7b030ad 13020 return parse_traceframe_info (text.get ());
b3b9301e
PA
13021
13022 return NULL;
13023}
13024
405f8e94
SS
13025/* Handle the qTMinFTPILen packet. Returns the minimum length of
13026 instruction on which a fast tracepoint may be placed. Returns -1
13027 if the packet is not supported, and 0 if the minimum instruction
13028 length is unknown. */
13029
13030static int
0e67620a 13031remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
13032{
13033 struct remote_state *rs = get_remote_state ();
13034 char *reply;
13035
e886a173
PA
13036 /* If we're not debugging a process yet, the IPA can't be
13037 loaded. */
13038 if (!target_has_execution)
13039 return 0;
13040
13041 /* Make sure the remote is pointing at the right process. */
13042 set_general_process ();
13043
bba74b36 13044 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13045 putpkt (rs->buf);
b6bb3468 13046 reply = remote_get_noisy_reply ();
405f8e94
SS
13047 if (*reply == '\0')
13048 return -1;
13049 else
13050 {
13051 ULONGEST min_insn_len;
13052
13053 unpack_varlen_hex (reply, &min_insn_len);
13054
13055 return (int) min_insn_len;
13056 }
13057}
13058
f6f899bf 13059static void
4da384be 13060remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 13061{
4082afcc 13062 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13063 {
13064 struct remote_state *rs = get_remote_state ();
13065 char *buf = rs->buf;
13066 char *endbuf = rs->buf + get_remote_packet_size ();
13067 enum packet_result result;
13068
13069 gdb_assert (val >= 0 || val == -1);
13070 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13071 /* Send -1 as literal "-1" to avoid host size dependency. */
13072 if (val < 0)
13073 {
13074 *buf++ = '-';
13075 buf += hexnumstr (buf, (ULONGEST) -val);
13076 }
13077 else
13078 buf += hexnumstr (buf, (ULONGEST) val);
13079
13080 putpkt (rs->buf);
b6bb3468 13081 remote_get_noisy_reply ();
f6f899bf
HAQ
13082 result = packet_ok (rs->buf,
13083 &remote_protocol_packets[PACKET_QTBuffer_size]);
13084
13085 if (result != PACKET_OK)
13086 warning (_("Bogus reply from target: %s"), rs->buf);
13087 }
13088}
13089
f196051f 13090static int
d9e68a2c
TT
13091remote_set_trace_notes (struct target_ops *self,
13092 const char *user, const char *notes,
ca623f82 13093 const char *stop_notes)
f196051f
SS
13094{
13095 struct remote_state *rs = get_remote_state ();
13096 char *reply;
13097 char *buf = rs->buf;
13098 char *endbuf = rs->buf + get_remote_packet_size ();
13099 int nbytes;
13100
13101 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13102 if (user)
13103 {
13104 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13105 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13106 buf += 2 * nbytes;
13107 *buf++ = ';';
13108 }
13109 if (notes)
13110 {
13111 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13112 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13113 buf += 2 * nbytes;
13114 *buf++ = ';';
13115 }
13116 if (stop_notes)
13117 {
13118 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13119 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13120 buf += 2 * nbytes;
13121 *buf++ = ';';
13122 }
13123 /* Ensure the buffer is terminated. */
13124 *buf = '\0';
13125
13126 putpkt (rs->buf);
b6bb3468 13127 reply = remote_get_noisy_reply ();
f196051f
SS
13128 if (*reply == '\0')
13129 return 0;
13130
13131 if (strcmp (reply, "OK") != 0)
13132 error (_("Bogus reply from target: %s"), reply);
13133
13134 return 1;
13135}
13136
d1feda86 13137static int
2c152180 13138remote_use_agent (struct target_ops *self, int use)
d1feda86 13139{
4082afcc 13140 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13141 {
13142 struct remote_state *rs = get_remote_state ();
13143
13144 /* If the stub supports QAgent. */
bba74b36 13145 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
13146 putpkt (rs->buf);
13147 getpkt (&rs->buf, &rs->buf_size, 0);
13148
13149 if (strcmp (rs->buf, "OK") == 0)
13150 {
13151 use_agent = use;
13152 return 1;
13153 }
13154 }
13155
13156 return 0;
13157}
13158
13159static int
fe38f897 13160remote_can_use_agent (struct target_ops *self)
d1feda86 13161{
4082afcc 13162 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13163}
13164
9accd112
MM
13165struct btrace_target_info
13166{
13167 /* The ptid of the traced thread. */
13168 ptid_t ptid;
f4abbc16
MM
13169
13170 /* The obtained branch trace configuration. */
13171 struct btrace_config conf;
9accd112
MM
13172};
13173
f4abbc16
MM
13174/* Reset our idea of our target's btrace configuration. */
13175
13176static void
13177remote_btrace_reset (void)
13178{
13179 struct remote_state *rs = get_remote_state ();
13180
13181 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13182}
13183
9accd112
MM
13184/* Check whether the target supports branch tracing. */
13185
13186static int
043c3577 13187remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 13188{
4082afcc 13189 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 13190 return 0;
4082afcc 13191 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
13192 return 0;
13193
043c3577
MM
13194 switch (format)
13195 {
13196 case BTRACE_FORMAT_NONE:
13197 return 0;
13198
13199 case BTRACE_FORMAT_BTS:
13200 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
13201
13202 case BTRACE_FORMAT_PT:
13203 /* The trace is decoded on the host. Even if our target supports it,
13204 we still need to have libipt to decode the trace. */
13205#if defined (HAVE_LIBIPT)
13206 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
13207#else /* !defined (HAVE_LIBIPT) */
13208 return 0;
13209#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
13210 }
13211
13212 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
13213}
13214
f4abbc16
MM
13215/* Synchronize the configuration with the target. */
13216
13217static void
13218btrace_sync_conf (const struct btrace_config *conf)
13219{
d33501a5
MM
13220 struct packet_config *packet;
13221 struct remote_state *rs;
13222 char *buf, *pos, *endbuf;
13223
13224 rs = get_remote_state ();
13225 buf = rs->buf;
13226 endbuf = buf + get_remote_packet_size ();
13227
13228 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13229 if (packet_config_support (packet) == PACKET_ENABLE
13230 && conf->bts.size != rs->btrace_config.bts.size)
13231 {
13232 pos = buf;
13233 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13234 conf->bts.size);
13235
13236 putpkt (buf);
13237 getpkt (&buf, &rs->buf_size, 0);
13238
13239 if (packet_ok (buf, packet) == PACKET_ERROR)
13240 {
13241 if (buf[0] == 'E' && buf[1] == '.')
13242 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13243 else
13244 error (_("Failed to configure the BTS buffer size."));
13245 }
13246
13247 rs->btrace_config.bts.size = conf->bts.size;
13248 }
b20a6524
MM
13249
13250 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13251 if (packet_config_support (packet) == PACKET_ENABLE
13252 && conf->pt.size != rs->btrace_config.pt.size)
13253 {
13254 pos = buf;
13255 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13256 conf->pt.size);
13257
13258 putpkt (buf);
13259 getpkt (&buf, &rs->buf_size, 0);
13260
13261 if (packet_ok (buf, packet) == PACKET_ERROR)
13262 {
13263 if (buf[0] == 'E' && buf[1] == '.')
13264 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13265 else
13266 error (_("Failed to configure the trace buffer size."));
13267 }
13268
13269 rs->btrace_config.pt.size = conf->pt.size;
13270 }
f4abbc16
MM
13271}
13272
13273/* Read the current thread's btrace configuration from the target and
13274 store it into CONF. */
13275
13276static void
13277btrace_read_config (struct btrace_config *conf)
13278{
b7b030ad
TT
13279 gdb::unique_xmalloc_ptr<char> xml
13280 = target_read_stralloc (&current_target, TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16 13281 if (xml != NULL)
b7b030ad 13282 parse_xml_btrace_conf (conf, xml.get ());
f4abbc16
MM
13283}
13284
c0272db5
TW
13285/* Maybe reopen target btrace. */
13286
13287static void
13288remote_btrace_maybe_reopen (void)
13289{
13290 struct remote_state *rs = get_remote_state ();
c0272db5
TW
13291 struct thread_info *tp;
13292 int btrace_target_pushed = 0;
13293 int warned = 0;
13294
5ed8105e
PA
13295 scoped_restore_current_thread restore_thread;
13296
c0272db5
TW
13297 ALL_NON_EXITED_THREADS (tp)
13298 {
13299 set_general_thread (tp->ptid);
13300
13301 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13302 btrace_read_config (&rs->btrace_config);
13303
13304 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13305 continue;
13306
13307#if !defined (HAVE_LIBIPT)
13308 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13309 {
13310 if (!warned)
13311 {
13312 warned = 1;
13313 warning (_("GDB does not support Intel Processor Trace. "
13314 "\"record\" will not work in this session."));
13315 }
13316
13317 continue;
13318 }
13319#endif /* !defined (HAVE_LIBIPT) */
13320
13321 /* Push target, once, but before anything else happens. This way our
13322 changes to the threads will be cleaned up by unpushing the target
13323 in case btrace_read_config () throws. */
13324 if (!btrace_target_pushed)
13325 {
13326 btrace_target_pushed = 1;
13327 record_btrace_push_target ();
13328 printf_filtered (_("Target is recording using %s.\n"),
13329 btrace_format_string (rs->btrace_config.format));
13330 }
13331
13332 tp->btrace.target = XCNEW (struct btrace_target_info);
13333 tp->btrace.target->ptid = tp->ptid;
13334 tp->btrace.target->conf = rs->btrace_config;
13335 }
c0272db5
TW
13336}
13337
9accd112
MM
13338/* Enable branch tracing. */
13339
13340static struct btrace_target_info *
f4abbc16
MM
13341remote_enable_btrace (struct target_ops *self, ptid_t ptid,
13342 const struct btrace_config *conf)
9accd112
MM
13343{
13344 struct btrace_target_info *tinfo = NULL;
b20a6524 13345 struct packet_config *packet = NULL;
9accd112
MM
13346 struct remote_state *rs = get_remote_state ();
13347 char *buf = rs->buf;
13348 char *endbuf = rs->buf + get_remote_packet_size ();
13349
b20a6524
MM
13350 switch (conf->format)
13351 {
13352 case BTRACE_FORMAT_BTS:
13353 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13354 break;
13355
13356 case BTRACE_FORMAT_PT:
13357 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13358 break;
13359 }
13360
13361 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13362 error (_("Target does not support branch tracing."));
13363
f4abbc16
MM
13364 btrace_sync_conf (conf);
13365
9accd112
MM
13366 set_general_thread (ptid);
13367
13368 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13369 putpkt (rs->buf);
13370 getpkt (&rs->buf, &rs->buf_size, 0);
13371
13372 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13373 {
13374 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13375 error (_("Could not enable branch tracing for %s: %s"),
13376 target_pid_to_str (ptid), rs->buf + 2);
13377 else
13378 error (_("Could not enable branch tracing for %s."),
13379 target_pid_to_str (ptid));
13380 }
13381
8d749320 13382 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13383 tinfo->ptid = ptid;
13384
f4abbc16
MM
13385 /* If we fail to read the configuration, we lose some information, but the
13386 tracing itself is not impacted. */
492d29ea
PA
13387 TRY
13388 {
13389 btrace_read_config (&tinfo->conf);
13390 }
13391 CATCH (err, RETURN_MASK_ERROR)
13392 {
13393 if (err.message != NULL)
13394 warning ("%s", err.message);
13395 }
13396 END_CATCH
f4abbc16 13397
9accd112
MM
13398 return tinfo;
13399}
13400
13401/* Disable branch tracing. */
13402
13403static void
25e95349
TT
13404remote_disable_btrace (struct target_ops *self,
13405 struct btrace_target_info *tinfo)
9accd112
MM
13406{
13407 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13408 struct remote_state *rs = get_remote_state ();
13409 char *buf = rs->buf;
13410 char *endbuf = rs->buf + get_remote_packet_size ();
13411
4082afcc 13412 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13413 error (_("Target does not support branch tracing."));
13414
13415 set_general_thread (tinfo->ptid);
13416
13417 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13418 putpkt (rs->buf);
13419 getpkt (&rs->buf, &rs->buf_size, 0);
13420
13421 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13422 {
13423 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13424 error (_("Could not disable branch tracing for %s: %s"),
13425 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13426 else
13427 error (_("Could not disable branch tracing for %s."),
13428 target_pid_to_str (tinfo->ptid));
13429 }
13430
13431 xfree (tinfo);
13432}
13433
13434/* Teardown branch tracing. */
13435
13436static void
1777056d
TT
13437remote_teardown_btrace (struct target_ops *self,
13438 struct btrace_target_info *tinfo)
9accd112
MM
13439{
13440 /* We must not talk to the target during teardown. */
13441 xfree (tinfo);
13442}
13443
13444/* Read the branch trace. */
13445
969c39fb 13446static enum btrace_error
39c49f83 13447remote_read_btrace (struct target_ops *self,
734b0e4b 13448 struct btrace_data *btrace,
969c39fb 13449 struct btrace_target_info *tinfo,
9accd112
MM
13450 enum btrace_read_type type)
13451{
13452 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
9accd112 13453 const char *annex;
9accd112 13454
4082afcc 13455 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13456 error (_("Target does not support branch tracing."));
13457
13458#if !defined(HAVE_LIBEXPAT)
13459 error (_("Cannot process branch tracing result. XML parsing not supported."));
13460#endif
13461
13462 switch (type)
13463 {
864089d2 13464 case BTRACE_READ_ALL:
9accd112
MM
13465 annex = "all";
13466 break;
864089d2 13467 case BTRACE_READ_NEW:
9accd112
MM
13468 annex = "new";
13469 break;
969c39fb
MM
13470 case BTRACE_READ_DELTA:
13471 annex = "delta";
13472 break;
9accd112
MM
13473 default:
13474 internal_error (__FILE__, __LINE__,
13475 _("Bad branch tracing read type: %u."),
13476 (unsigned int) type);
13477 }
13478
b7b030ad
TT
13479 gdb::unique_xmalloc_ptr<char> xml
13480 = target_read_stralloc (&current_target, TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
13481 if (xml == NULL)
13482 return BTRACE_ERR_UNKNOWN;
9accd112 13483
b7b030ad 13484 parse_xml_btrace (btrace, xml.get ());
9accd112 13485
969c39fb 13486 return BTRACE_ERR_NONE;
9accd112
MM
13487}
13488
f4abbc16
MM
13489static const struct btrace_config *
13490remote_btrace_conf (struct target_ops *self,
13491 const struct btrace_target_info *tinfo)
13492{
13493 return &tinfo->conf;
13494}
13495
ced63ec0 13496static int
5436ff03 13497remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 13498{
4082afcc
PA
13499 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13500 == PACKET_ENABLE);
ced63ec0
GB
13501}
13502
9dd130a0
TT
13503/* Implementation of to_load. */
13504
13505static void
9cbe5fff 13506remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
13507{
13508 generic_load (name, from_tty);
13509}
13510
c78fa86a
GB
13511/* Accepts an integer PID; returns a string representing a file that
13512 can be opened on the remote side to get the symbols for the child
13513 process. Returns NULL if the operation is not supported. */
13514
13515static char *
13516remote_pid_to_exec_file (struct target_ops *self, int pid)
13517{
b7b030ad 13518 static gdb::unique_xmalloc_ptr<char> filename;
835205d0
GB
13519 struct inferior *inf;
13520 char *annex = NULL;
c78fa86a
GB
13521
13522 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13523 return NULL;
13524
835205d0
GB
13525 inf = find_inferior_pid (pid);
13526 if (inf == NULL)
13527 internal_error (__FILE__, __LINE__,
13528 _("not currently attached to process %d"), pid);
13529
13530 if (!inf->fake_pid_p)
13531 {
13532 const int annex_size = 9;
13533
224c3ddb 13534 annex = (char *) alloca (annex_size);
835205d0
GB
13535 xsnprintf (annex, annex_size, "%x", pid);
13536 }
13537
c78fa86a
GB
13538 filename = target_read_stralloc (&current_target,
13539 TARGET_OBJECT_EXEC_FILE, annex);
13540
b7b030ad 13541 return filename.get ();
c78fa86a
GB
13542}
13543
750ce8d1
YQ
13544/* Implement the to_can_do_single_step target_ops method. */
13545
13546static int
13547remote_can_do_single_step (struct target_ops *ops)
13548{
13549 /* We can only tell whether target supports single step or not by
13550 supported s and S vCont actions if the stub supports vContSupported
13551 feature. If the stub doesn't support vContSupported feature,
13552 we have conservatively to think target doesn't supports single
13553 step. */
13554 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13555 {
13556 struct remote_state *rs = get_remote_state ();
13557
13558 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13559 remote_vcont_probe (rs);
13560
13561 return rs->supports_vCont.s && rs->supports_vCont.S;
13562 }
13563 else
13564 return 0;
13565}
13566
3a00c802
PA
13567/* Implementation of the to_execution_direction method for the remote
13568 target. */
13569
13570static enum exec_direction_kind
13571remote_execution_direction (struct target_ops *self)
13572{
13573 struct remote_state *rs = get_remote_state ();
13574
13575 return rs->last_resume_exec_dir;
13576}
13577
f6327dcb
KB
13578/* Return pointer to the thread_info struct which corresponds to
13579 THREAD_HANDLE (having length HANDLE_LEN). */
13580
13581static struct thread_info *
13582remote_thread_handle_to_thread_info (struct target_ops *ops,
13583 const gdb_byte *thread_handle,
13584 int handle_len,
13585 struct inferior *inf)
13586{
13587 struct thread_info *tp;
13588
13589 ALL_NON_EXITED_THREADS (tp)
13590 {
13591 struct private_thread_info *priv = get_private_info_thread (tp);
13592
13593 if (tp->inf == inf && priv != NULL)
13594 {
13595 if (handle_len != priv->thread_handle->size ())
13596 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13597 handle_len, priv->thread_handle->size ());
13598 if (memcmp (thread_handle, priv->thread_handle->data (),
13599 handle_len) == 0)
13600 return tp;
13601 }
13602 }
13603
13604 return NULL;
13605}
13606
c906108c 13607static void
fba45db2 13608init_remote_ops (void)
c906108c 13609{
c5aa993b 13610 remote_ops.to_shortname = "remote";
c906108c 13611 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 13612 remote_ops.to_doc =
c906108c 13613 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
13614Specify the serial device it is connected to\n\
13615(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
13616 remote_ops.to_open = remote_open;
13617 remote_ops.to_close = remote_close;
c906108c 13618 remote_ops.to_detach = remote_detach;
6ad8ae5c 13619 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 13620 remote_ops.to_resume = remote_resume;
85ad3aaf 13621 remote_ops.to_commit_resume = remote_commit_resume;
c906108c
SS
13622 remote_ops.to_wait = remote_wait;
13623 remote_ops.to_fetch_registers = remote_fetch_registers;
13624 remote_ops.to_store_registers = remote_store_registers;
13625 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 13626 remote_ops.to_files_info = remote_files_info;
c906108c
SS
13627 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13628 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
13629 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13630 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13631 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13632 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
13633 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13634 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
13635 remote_ops.to_watchpoint_addr_within_range =
13636 remote_watchpoint_addr_within_range;
3c3bea1c
GS
13637 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13638 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13639 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
13640 remote_ops.to_region_ok_for_hw_watchpoint
13641 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
13642 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13643 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 13644 remote_ops.to_kill = remote_kill;
9dd130a0 13645 remote_ops.to_load = remote_load;
c906108c 13646 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 13647 remote_ops.to_pass_signals = remote_pass_signals;
82075af2 13648 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
9b224c5e 13649 remote_ops.to_program_signals = remote_program_signals;
c906108c 13650 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 13651 remote_ops.to_thread_name = remote_thread_name;
e8032dde 13652 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 13653 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 13654 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 13655 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 13656 remote_ops.to_stop = remote_stop;
bfedc46a 13657 remote_ops.to_interrupt = remote_interrupt;
93692b58 13658 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
4b8a223f 13659 remote_ops.to_xfer_partial = remote_xfer_partial;
09c98b44 13660 remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
96baa820 13661 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 13662 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 13663 remote_ops.to_log_command = serial_log_command;
38691318 13664 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 13665 remote_ops.to_stratum = process_stratum;
c35b1492
PA
13666 remote_ops.to_has_all_memory = default_child_has_all_memory;
13667 remote_ops.to_has_memory = default_child_has_memory;
13668 remote_ops.to_has_stack = default_child_has_stack;
13669 remote_ops.to_has_registers = default_child_has_registers;
13670 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 13671 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13672 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13673 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13674 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13675 remote_ops.to_flash_erase = remote_flash_erase;
13676 remote_ops.to_flash_done = remote_flash_done;
29709017 13677 remote_ops.to_read_description = remote_read_description;
08388c79 13678 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13679 remote_ops.to_can_async_p = remote_can_async_p;
13680 remote_ops.to_is_async_p = remote_is_async_p;
13681 remote_ops.to_async = remote_async;
65706a29 13682 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13683 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13684 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13685 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13686 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13687 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13688 remote_ops.to_supports_disable_randomization
13689 = remote_supports_disable_randomization;
4bd7dc42 13690 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13691 remote_ops.to_fileio_open = remote_hostio_open;
13692 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13693 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13694 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13695 remote_ops.to_fileio_close = remote_hostio_close;
13696 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13697 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13698 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13699 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13700 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13701 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13702 remote_ops.to_trace_init = remote_trace_init;
13703 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13704 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13705 remote_ops.to_download_trace_state_variable
13706 = remote_download_trace_state_variable;
d248b706
KY
13707 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13708 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13709 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13710 remote_ops.to_trace_start = remote_trace_start;
13711 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13712 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13713 remote_ops.to_trace_stop = remote_trace_stop;
13714 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13715 remote_ops.to_get_trace_state_variable_value
13716 = remote_get_trace_state_variable_value;
00bf0b85
SS
13717 remote_ops.to_save_trace_data = remote_save_trace_data;
13718 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13719 remote_ops.to_upload_trace_state_variables
13720 = remote_upload_trace_state_variables;
00bf0b85 13721 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13722 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13723 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13724 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13725 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13726 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13727 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13728 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13729 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13730 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13731 remote_ops.to_static_tracepoint_marker_at
13732 = remote_static_tracepoint_marker_at;
13733 remote_ops.to_static_tracepoint_markers_by_strid
13734 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13735 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13736 remote_ops.to_use_agent = remote_use_agent;
13737 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13738 remote_ops.to_supports_btrace = remote_supports_btrace;
13739 remote_ops.to_enable_btrace = remote_enable_btrace;
13740 remote_ops.to_disable_btrace = remote_disable_btrace;
13741 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13742 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13743 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13744 remote_ops.to_augmented_libraries_svr4_read =
13745 remote_augmented_libraries_svr4_read;
8020350c
DB
13746 remote_ops.to_follow_fork = remote_follow_fork;
13747 remote_ops.to_follow_exec = remote_follow_exec;
13748 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13749 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13750 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13751 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13752 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13753 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
3a00c802 13754 remote_ops.to_execution_direction = remote_execution_direction;
f6327dcb
KB
13755 remote_ops.to_thread_handle_to_thread_info =
13756 remote_thread_handle_to_thread_info;
c906108c
SS
13757}
13758
13759/* Set up the extended remote vector by making a copy of the standard
13760 remote vector and adding to it. */
13761
13762static void
fba45db2 13763init_extended_remote_ops (void)
c906108c
SS
13764{
13765 extended_remote_ops = remote_ops;
13766
0f71a2f6 13767 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13768 extended_remote_ops.to_longname =
c906108c 13769 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13770 extended_remote_ops.to_doc =
c906108c 13771 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13772Specify the serial device it is connected to (e.g. /dev/ttya).";
13773 extended_remote_ops.to_open = extended_remote_open;
c906108c 13774 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
2d717e4f
DJ
13775 extended_remote_ops.to_detach = extended_remote_detach;
13776 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13777 extended_remote_ops.to_post_attach = extended_remote_post_attach;
03583c20
UW
13778 extended_remote_ops.to_supports_disable_randomization
13779 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
13780}
13781
6426a772 13782static int
6a109b6b 13783remote_can_async_p (struct target_ops *ops)
6426a772 13784{
5d93a237
TT
13785 struct remote_state *rs = get_remote_state ();
13786
3015c064
SM
13787 /* We don't go async if the user has explicitly prevented it with the
13788 "maint set target-async" command. */
c6ebd6cf 13789 if (!target_async_permitted)
75c99385
PA
13790 return 0;
13791
23860348 13792 /* We're async whenever the serial device is. */
5d93a237 13793 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13794}
13795
13796static int
6a109b6b 13797remote_is_async_p (struct target_ops *ops)
6426a772 13798{
5d93a237
TT
13799 struct remote_state *rs = get_remote_state ();
13800
c6ebd6cf 13801 if (!target_async_permitted)
75c99385
PA
13802 /* We only enable async when the user specifically asks for it. */
13803 return 0;
13804
23860348 13805 /* We're async whenever the serial device is. */
5d93a237 13806 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13807}
13808
2acceee2
JM
13809/* Pass the SERIAL event on and up to the client. One day this code
13810 will be able to delay notifying the client of an event until the
23860348 13811 point where an entire packet has been received. */
2acceee2 13812
2acceee2
JM
13813static serial_event_ftype remote_async_serial_handler;
13814
6426a772 13815static void
819cc324 13816remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13817{
2acceee2
JM
13818 /* Don't propogate error information up to the client. Instead let
13819 the client find out about the error by querying the target. */
6a3753b3 13820 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13821}
13822
74531fed
PA
13823static void
13824remote_async_inferior_event_handler (gdb_client_data data)
13825{
13826 inferior_event_handler (INF_REG_EVENT, NULL);
13827}
13828
2acceee2 13829static void
6a3753b3 13830remote_async (struct target_ops *ops, int enable)
2acceee2 13831{
5d93a237
TT
13832 struct remote_state *rs = get_remote_state ();
13833
6a3753b3 13834 if (enable)
2acceee2 13835 {
88b496c3 13836 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13837
13838 /* If there are pending events in the stop reply queue tell the
13839 event loop to process them. */
13840 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13841 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13842 /* For simplicity, below we clear the pending events token
13843 without remembering whether it is marked, so here we always
13844 mark it. If there's actually no pending notification to
13845 process, this ends up being a no-op (other than a spurious
13846 event-loop wakeup). */
13847 if (target_is_non_stop_p ())
13848 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13849 }
13850 else
b7d2e916
PA
13851 {
13852 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13853 /* If the core is disabling async, it doesn't want to be
13854 disturbed with target events. Clear all async event sources
13855 too. */
b7d2e916 13856 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13857 if (target_is_non_stop_p ())
13858 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13859 }
6426a772
JM
13860}
13861
65706a29
PA
13862/* Implementation of the to_thread_events method. */
13863
13864static void
13865remote_thread_events (struct target_ops *ops, int enable)
13866{
13867 struct remote_state *rs = get_remote_state ();
13868 size_t size = get_remote_packet_size ();
65706a29
PA
13869
13870 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13871 return;
13872
13873 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13874 putpkt (rs->buf);
13875 getpkt (&rs->buf, &rs->buf_size, 0);
13876
13877 switch (packet_ok (rs->buf,
13878 &remote_protocol_packets[PACKET_QThreadEvents]))
13879 {
13880 case PACKET_OK:
13881 if (strcmp (rs->buf, "OK") != 0)
13882 error (_("Remote refused setting thread events: %s"), rs->buf);
13883 break;
13884 case PACKET_ERROR:
13885 warning (_("Remote failure reply: %s"), rs->buf);
13886 break;
13887 case PACKET_UNKNOWN:
13888 break;
13889 }
13890}
13891
5a2468f5 13892static void
981a3fb3 13893set_remote_cmd (const char *args, int from_tty)
5a2468f5 13894{
635c7e8a 13895 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13896}
13897
d471ea57 13898static void
981a3fb3 13899show_remote_cmd (const char *args, int from_tty)
d471ea57 13900{
37a105a1 13901 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13902 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 13903 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13904 struct ui_out *uiout = current_uiout;
37a105a1 13905
2e783024 13906 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
13907 for (; list != NULL; list = list->next)
13908 if (strcmp (list->name, "Z-packet") == 0)
13909 continue;
427c3a89
DJ
13910 else if (list->type == not_set_cmd)
13911 /* Alias commands are exactly like the original, except they
13912 don't have the normal type. */
13913 continue;
13914 else
37a105a1 13915 {
2e783024 13916 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 13917
112e8700
SM
13918 uiout->field_string ("name", list->name);
13919 uiout->text (": ");
427c3a89 13920 if (list->type == show_cmd)
f5c4fcd9 13921 do_show_command (NULL, from_tty, list);
427c3a89
DJ
13922 else
13923 cmd_func (list, NULL, from_tty);
37a105a1 13924 }
d471ea57 13925}
5a2468f5 13926
0f71a2f6 13927
23860348 13928/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13929static void
13930remote_new_objfile (struct objfile *objfile)
13931{
5d93a237
TT
13932 struct remote_state *rs = get_remote_state ();
13933
13934 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13935 remote_check_symbols ();
dc8acb97
MS
13936}
13937
00bf0b85
SS
13938/* Pull all the tracepoints defined on the target and create local
13939 data structures representing them. We don't want to create real
13940 tracepoints yet, we don't want to mess up the user's existing
13941 collection. */
13942
13943static int
ab6617cc 13944remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13945{
00bf0b85
SS
13946 struct remote_state *rs = get_remote_state ();
13947 char *p;
d5551862 13948
00bf0b85
SS
13949 /* Ask for a first packet of tracepoint definition. */
13950 putpkt ("qTfP");
13951 getpkt (&rs->buf, &rs->buf_size, 0);
13952 p = rs->buf;
13953 while (*p && *p != 'l')
d5551862 13954 {
00bf0b85
SS
13955 parse_tracepoint_definition (p, utpp);
13956 /* Ask for another packet of tracepoint definition. */
13957 putpkt ("qTsP");
13958 getpkt (&rs->buf, &rs->buf_size, 0);
13959 p = rs->buf;
d5551862 13960 }
00bf0b85 13961 return 0;
d5551862
SS
13962}
13963
00bf0b85 13964static int
181e3713
TT
13965remote_upload_trace_state_variables (struct target_ops *self,
13966 struct uploaded_tsv **utsvp)
d5551862 13967{
00bf0b85 13968 struct remote_state *rs = get_remote_state ();
d5551862 13969 char *p;
d5551862 13970
00bf0b85
SS
13971 /* Ask for a first packet of variable definition. */
13972 putpkt ("qTfV");
d5551862
SS
13973 getpkt (&rs->buf, &rs->buf_size, 0);
13974 p = rs->buf;
00bf0b85 13975 while (*p && *p != 'l')
d5551862 13976 {
00bf0b85
SS
13977 parse_tsv_definition (p, utsvp);
13978 /* Ask for another packet of variable definition. */
13979 putpkt ("qTsV");
d5551862
SS
13980 getpkt (&rs->buf, &rs->buf_size, 0);
13981 p = rs->buf;
13982 }
00bf0b85 13983 return 0;
d5551862
SS
13984}
13985
c1e36e3e
PA
13986/* The "set/show range-stepping" show hook. */
13987
13988static void
13989show_range_stepping (struct ui_file *file, int from_tty,
13990 struct cmd_list_element *c,
13991 const char *value)
13992{
13993 fprintf_filtered (file,
13994 _("Debugger's willingness to use range stepping "
13995 "is %s.\n"), value);
13996}
13997
13998/* The "set/show range-stepping" set hook. */
13999
14000static void
14001set_range_stepping (char *ignore_args, int from_tty,
14002 struct cmd_list_element *c)
14003{
5d93a237
TT
14004 struct remote_state *rs = get_remote_state ();
14005
c1e36e3e
PA
14006 /* Whene enabling, check whether range stepping is actually
14007 supported by the target, and warn if not. */
14008 if (use_range_stepping)
14009 {
5d93a237 14010 if (rs->remote_desc != NULL)
c1e36e3e 14011 {
4082afcc 14012 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
14013 remote_vcont_probe (rs);
14014
4082afcc 14015 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
14016 && rs->supports_vCont.r)
14017 return;
14018 }
14019
14020 warning (_("Range stepping is not supported by the current target"));
14021 }
14022}
14023
c906108c 14024void
fba45db2 14025_initialize_remote (void)
c906108c 14026{
9a7071a8 14027 struct cmd_list_element *cmd;
6f937416 14028 const char *cmd_name;
ea9c271d 14029
0f71a2f6 14030 /* architecture specific data */
2bc416ba 14031 remote_gdbarch_data_handle =
23860348 14032 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
14033 remote_g_packet_data_handle =
14034 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14035
94585166
DB
14036 remote_pspace_data
14037 = register_program_space_data_with_cleanup (NULL,
14038 remote_pspace_data_cleanup);
14039
ea9c271d
DJ
14040 /* Initialize the per-target state. At the moment there is only one
14041 of these, not one per target. Only one target is active at a
cf792862
TT
14042 time. */
14043 remote_state = new_remote_state ();
ea9c271d 14044
c906108c
SS
14045 init_remote_ops ();
14046 add_target (&remote_ops);
14047
14048 init_extended_remote_ops ();
14049 add_target (&extended_remote_ops);
cce74817 14050
dc8acb97 14051 /* Hook into new objfile notification. */
06d3b283 14052 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
14053 /* We're no longer interested in notification events of an inferior
14054 when it exits. */
14055 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 14056
c906108c
SS
14057#if 0
14058 init_remote_threadtests ();
14059#endif
14060
722247f1 14061 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 14062 /* set/show remote ... */
d471ea57 14063
1bedd215 14064 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
14065Remote protocol specific variables\n\
14066Configure various remote-protocol specific variables such as\n\
1bedd215 14067the packets being used"),
cff3e48b 14068 &remote_set_cmdlist, "set remote ",
23860348 14069 0 /* allow-unknown */, &setlist);
1bedd215 14070 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
14071Remote protocol specific variables\n\
14072Configure various remote-protocol specific variables such as\n\
1bedd215 14073the packets being used"),
cff3e48b 14074 &remote_show_cmdlist, "show remote ",
23860348 14075 0 /* allow-unknown */, &showlist);
5a2468f5 14076
1a966eab
AC
14077 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14078Compare section data on target to the exec file.\n\
95cf3b38
DT
14079Argument is a single section name (default: all loaded sections).\n\
14080To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14081 &cmdlist);
14082
1a966eab
AC
14083 add_cmd ("packet", class_maintenance, packet_command, _("\
14084Send an arbitrary packet to a remote target.\n\
c906108c
SS
14085 maintenance packet TEXT\n\
14086If GDB is talking to an inferior via the GDB serial protocol, then\n\
14087this command sends the string TEXT to the inferior, and displays the\n\
14088response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14089terminating `#' character and checksum."),
c906108c
SS
14090 &maintenancelist);
14091
7915a72c
AC
14092 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14093Set whether to send break if interrupted."), _("\
14094Show whether to send break if interrupted."), _("\
14095If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14096 set_remotebreak, show_remotebreak,
e707bbc2 14097 &setlist, &showlist);
9a7071a8
JB
14098 cmd_name = "remotebreak";
14099 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14100 deprecate_cmd (cmd, "set remote interrupt-sequence");
14101 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14102 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14103 deprecate_cmd (cmd, "show remote interrupt-sequence");
14104
14105 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14106 interrupt_sequence_modes, &interrupt_sequence_mode,
14107 _("\
9a7071a8
JB
14108Set interrupt sequence to remote target."), _("\
14109Show interrupt sequence to remote target."), _("\
14110Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14111 NULL, show_interrupt_sequence,
14112 &remote_set_cmdlist,
14113 &remote_show_cmdlist);
14114
14115 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14116 &interrupt_on_connect, _("\
14117Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14118Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14119If set, interrupt sequence is sent to remote target."),
14120 NULL, NULL,
14121 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14122
23860348 14123 /* Install commands for configuring memory read/write packets. */
11cf8741 14124
1a966eab
AC
14125 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14126Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14127 &setlist);
1a966eab
AC
14128 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14129Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14130 &showlist);
14131 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14132 set_memory_write_packet_size, _("\
14133Set the maximum number of bytes per memory-write packet.\n\
14134Specify the number of bytes in a packet or 0 (zero) for the\n\
14135default packet size. The actual limit is further reduced\n\
14136dependent on the target. Specify ``fixed'' to disable the\n\
14137further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14138 &remote_set_cmdlist);
14139 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14140 set_memory_read_packet_size, _("\
14141Set the maximum number of bytes per memory-read packet.\n\
14142Specify the number of bytes in a packet or 0 (zero) for the\n\
14143default packet size. The actual limit is further reduced\n\
14144dependent on the target. Specify ``fixed'' to disable the\n\
14145further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14146 &remote_set_cmdlist);
14147 add_cmd ("memory-write-packet-size", no_class,
14148 show_memory_write_packet_size,
1a966eab 14149 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14150 &remote_show_cmdlist);
14151 add_cmd ("memory-read-packet-size", no_class,
14152 show_memory_read_packet_size,
1a966eab 14153 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14154 &remote_show_cmdlist);
c906108c 14155
b3f42336 14156 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14157 &remote_hw_watchpoint_limit, _("\
14158Set the maximum number of target hardware watchpoints."), _("\
14159Show the maximum number of target hardware watchpoints."), _("\
14160Specify a negative limit for unlimited."),
3e43a32a
MS
14161 NULL, NULL, /* FIXME: i18n: The maximum
14162 number of target hardware
14163 watchpoints is %s. */
b3f42336 14164 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
14165 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14166 &remote_hw_watchpoint_length_limit, _("\
14167Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14168Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14169Specify a negative limit for unlimited."),
14170 NULL, NULL, /* FIXME: i18n: The maximum
14171 length (in bytes) of a target
14172 hardware watchpoint is %s. */
14173 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 14174 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14175 &remote_hw_breakpoint_limit, _("\
14176Set the maximum number of target hardware breakpoints."), _("\
14177Show the maximum number of target hardware breakpoints."), _("\
14178Specify a negative limit for unlimited."),
3e43a32a
MS
14179 NULL, NULL, /* FIXME: i18n: The maximum
14180 number of target hardware
14181 breakpoints is %s. */
b3f42336 14182 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14183
1b493192
PA
14184 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14185 &remote_address_size, _("\
4d28ad1e
AC
14186Set the maximum size of the address (in bits) in a memory packet."), _("\
14187Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14188 NULL,
14189 NULL, /* FIXME: i18n: */
14190 &setlist, &showlist);
c906108c 14191
ca4f7f8b
PA
14192 init_all_packet_configs ();
14193
444abaca 14194 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14195 "X", "binary-download", 1);
0f71a2f6 14196
444abaca 14197 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14198 "vCont", "verbose-resume", 0);
506fb367 14199
89be2091
DJ
14200 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14201 "QPassSignals", "pass-signals", 0);
14202
82075af2
JS
14203 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14204 "QCatchSyscalls", "catch-syscalls", 0);
14205
9b224c5e
PA
14206 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14207 "QProgramSignals", "program-signals", 0);
14208
bc3b087d
SDJ
14209 add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14210 "QSetWorkingDir", "set-working-dir", 0);
14211
aefd8b33
SDJ
14212 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14213 "QStartupWithShell", "startup-with-shell", 0);
14214
0a2dde4a
SDJ
14215 add_packet_config_cmd (&remote_protocol_packets
14216 [PACKET_QEnvironmentHexEncoded],
14217 "QEnvironmentHexEncoded", "environment-hex-encoded",
14218 0);
14219
14220 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14221 "QEnvironmentReset", "environment-reset",
14222 0);
14223
14224 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14225 "QEnvironmentUnset", "environment-unset",
14226 0);
14227
444abaca 14228 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14229 "qSymbol", "symbol-lookup", 0);
dc8acb97 14230
444abaca 14231 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14232 "P", "set-register", 1);
d471ea57 14233
444abaca 14234 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14235 "p", "fetch-register", 1);
b96ec7ac 14236
444abaca 14237 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14238 "Z0", "software-breakpoint", 0);
d471ea57 14239
444abaca 14240 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14241 "Z1", "hardware-breakpoint", 0);
d471ea57 14242
444abaca 14243 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14244 "Z2", "write-watchpoint", 0);
d471ea57 14245
444abaca 14246 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14247 "Z3", "read-watchpoint", 0);
d471ea57 14248
444abaca 14249 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14250 "Z4", "access-watchpoint", 0);
d471ea57 14251
0876f84a
DJ
14252 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14253 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14254
c78fa86a
GB
14255 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14256 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14257
23181151
DJ
14258 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14259 "qXfer:features:read", "target-features", 0);
14260
cfa9d6d9
DJ
14261 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14262 "qXfer:libraries:read", "library-info", 0);
14263
2268b414
JK
14264 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14265 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14266
fd79ecee
DJ
14267 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14268 "qXfer:memory-map:read", "memory-map", 0);
14269
0e7f50da
UW
14270 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14271 "qXfer:spu:read", "read-spu-object", 0);
14272
14273 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14274 "qXfer:spu:write", "write-spu-object", 0);
14275
07e059b5
VP
14276 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14277 "qXfer:osdata:read", "osdata", 0);
14278
dc146f7c
VP
14279 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14280 "qXfer:threads:read", "threads", 0);
14281
4aa995e1
PA
14282 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14283 "qXfer:siginfo:read", "read-siginfo-object", 0);
14284
14285 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14286 "qXfer:siginfo:write", "write-siginfo-object", 0);
14287
b3b9301e
PA
14288 add_packet_config_cmd
14289 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14290 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14291
169081d0
TG
14292 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14293 "qXfer:uib:read", "unwind-info-block", 0);
14294
444abaca 14295 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14296 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14297 0);
14298
711e434b
PM
14299 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14300 "qGetTIBAddr", "get-thread-information-block-address",
14301 0);
14302
40ab02ce
MS
14303 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14304 "bc", "reverse-continue", 0);
14305
14306 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14307 "bs", "reverse-step", 0);
14308
be2a5f71
DJ
14309 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14310 "qSupported", "supported-packets", 0);
14311
08388c79
DE
14312 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14313 "qSearch:memory", "search-memory", 0);
14314
bd3eecc3
PA
14315 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14316 "qTStatus", "trace-status", 0);
14317
15a201c8
GB
14318 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14319 "vFile:setfs", "hostio-setfs", 0);
14320
a6b151f1
DJ
14321 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14322 "vFile:open", "hostio-open", 0);
14323
14324 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14325 "vFile:pread", "hostio-pread", 0);
14326
14327 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14328 "vFile:pwrite", "hostio-pwrite", 0);
14329
14330 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14331 "vFile:close", "hostio-close", 0);
14332
14333 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14334 "vFile:unlink", "hostio-unlink", 0);
14335
b9e7b9c3
UW
14336 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14337 "vFile:readlink", "hostio-readlink", 0);
14338
0a93529c
GB
14339 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14340 "vFile:fstat", "hostio-fstat", 0);
14341
2d717e4f
DJ
14342 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14343 "vAttach", "attach", 0);
14344
14345 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14346 "vRun", "run", 0);
14347
a6f3e723
SL
14348 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14349 "QStartNoAckMode", "noack", 0);
14350
82f73884
PA
14351 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14352 "vKill", "kill", 0);
14353
0b16c5cf
PA
14354 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14355 "qAttached", "query-attached", 0);
14356
782b2b07 14357 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14358 "ConditionalTracepoints",
14359 "conditional-tracepoints", 0);
3788aec7
LM
14360
14361 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14362 "ConditionalBreakpoints",
14363 "conditional-breakpoints", 0);
14364
d3ce09f5
SS
14365 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14366 "BreakpointCommands",
14367 "breakpoint-commands", 0);
14368
7a697b8d
SS
14369 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14370 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14371
409873ef
SS
14372 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14373 "TracepointSource", "TracepointSource", 0);
14374
d914c394
SS
14375 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14376 "QAllow", "allow", 0);
14377
0fb4aa4b
PA
14378 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14379 "StaticTracepoints", "static-tracepoints", 0);
14380
1e4d1764
YQ
14381 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14382 "InstallInTrace", "install-in-trace", 0);
14383
0fb4aa4b
PA
14384 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14385 "qXfer:statictrace:read", "read-sdata-object", 0);
14386
78d85199
YQ
14387 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14388 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14389
03583c20
UW
14390 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14391 "QDisableRandomization", "disable-randomization", 0);
14392
d1feda86
YQ
14393 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14394 "QAgent", "agent", 0);
14395
f6f899bf
HAQ
14396 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14397 "QTBuffer:size", "trace-buffer-size", 0);
14398
9accd112
MM
14399 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14400 "Qbtrace:off", "disable-btrace", 0);
14401
14402 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14403 "Qbtrace:bts", "enable-btrace-bts", 0);
14404
14405 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14406 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14407
14408 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14409 "qXfer:btrace", "read-btrace", 0);
14410
f4abbc16
MM
14411 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14412 "qXfer:btrace-conf", "read-btrace-conf", 0);
14413
d33501a5
MM
14414 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14415 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14416
73b8c1fd
PA
14417 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14418 "multiprocess-feature", "multiprocess-feature", 0);
14419
f7e6eed5
PA
14420 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14421 "swbreak-feature", "swbreak-feature", 0);
14422
14423 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14424 "hwbreak-feature", "hwbreak-feature", 0);
14425
89245bc0
DB
14426 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14427 "fork-event-feature", "fork-event-feature", 0);
14428
14429 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14430 "vfork-event-feature", "vfork-event-feature", 0);
14431
b20a6524
MM
14432 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14433 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14434
750ce8d1
YQ
14435 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14436 "vContSupported", "verbose-resume-supported", 0);
14437
94585166
DB
14438 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14439 "exec-event-feature", "exec-event-feature", 0);
14440
de979965
PA
14441 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14442 "vCtrlC", "ctrl-c", 0);
14443
65706a29
PA
14444 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14445 "QThreadEvents", "thread-events", 0);
14446
f2faf941
PA
14447 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14448 "N stop reply", "no-resumed-stop-reply", 0);
14449
0b736949
DB
14450 /* Assert that we've registered "set remote foo-packet" commands
14451 for all packet configs. */
ca4f7f8b
PA
14452 {
14453 int i;
14454
14455 for (i = 0; i < PACKET_MAX; i++)
14456 {
14457 /* Ideally all configs would have a command associated. Some
14458 still don't though. */
14459 int excepted;
14460
14461 switch (i)
14462 {
14463 case PACKET_QNonStop:
ca4f7f8b
PA
14464 case PACKET_EnableDisableTracepoints_feature:
14465 case PACKET_tracenz_feature:
14466 case PACKET_DisconnectedTracing_feature:
14467 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14468 case PACKET_qCRC:
14469 /* Additions to this list need to be well justified:
14470 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14471 excepted = 1;
14472 break;
14473 default:
14474 excepted = 0;
14475 break;
14476 }
14477
14478 /* This catches both forgetting to add a config command, and
14479 forgetting to remove a packet from the exception list. */
14480 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14481 }
14482 }
14483
37a105a1
DJ
14484 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14485 Z sub-packet has its own set and show commands, but users may
14486 have sets to this variable in their .gdbinit files (or in their
14487 documentation). */
e9e68a56 14488 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14489 &remote_Z_packet_detect, _("\
14490Set use of remote protocol `Z' packets"), _("\
14491Show use of remote protocol `Z' packets "), _("\
3b64bf98 14492When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14493packets."),
e9e68a56 14494 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14495 show_remote_protocol_Z_packet_cmd,
14496 /* FIXME: i18n: Use of remote protocol
14497 `Z' packets is %s. */
e9e68a56 14498 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14499
a6b151f1
DJ
14500 add_prefix_cmd ("remote", class_files, remote_command, _("\
14501Manipulate files on the remote system\n\
14502Transfer files to and from the remote target system."),
14503 &remote_cmdlist, "remote ",
14504 0 /* allow-unknown */, &cmdlist);
14505
14506 add_cmd ("put", class_files, remote_put_command,
14507 _("Copy a local file to the remote system."),
14508 &remote_cmdlist);
14509
14510 add_cmd ("get", class_files, remote_get_command,
14511 _("Copy a remote file to the local system."),
14512 &remote_cmdlist);
14513
14514 add_cmd ("delete", class_files, remote_delete_command,
14515 _("Delete a remote file."),
14516 &remote_cmdlist);
14517
2d717e4f 14518 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14519 &remote_exec_file_var, _("\
2d717e4f 14520Set the remote pathname for \"run\""), _("\
94585166
DB
14521Show the remote pathname for \"run\""), NULL,
14522 set_remote_exec_file,
14523 show_remote_exec_file,
14524 &remote_set_cmdlist,
14525 &remote_show_cmdlist);
2d717e4f 14526
c1e36e3e
PA
14527 add_setshow_boolean_cmd ("range-stepping", class_run,
14528 &use_range_stepping, _("\
14529Enable or disable range stepping."), _("\
14530Show whether target-assisted range stepping is enabled."), _("\
14531If on, and the target supports it, when stepping a source line, GDB\n\
14532tells the target to step the corresponding range of addresses itself instead\n\
14533of issuing multiple single-steps. This speeds up source level\n\
14534stepping. If off, GDB always issues single-steps, even if range\n\
14535stepping is supported by the target. The default is on."),
14536 set_range_stepping,
14537 show_range_stepping,
14538 &setlist,
14539 &showlist);
14540
449092f6
CV
14541 /* Eventually initialize fileio. See fileio.c */
14542 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14543
ba348170 14544 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14545 special ptids with it set to != 0. */
ba348170
PA
14546 magic_null_ptid = ptid_build (42000, -1, 1);
14547 not_sent_ptid = ptid_build (42000, -2, 1);
14548 any_thread_ptid = ptid_build (42000, 0, 1);
c906108c 14549}