Implement "set cwd" command on GDB
[deliverable/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
DJ
656static struct remote_arch_state *
657get_remote_arch_state (void)
d01949b6 658{
17d8546e 659 gdb_assert (target_gdbarch () != NULL);
19ba03f4
SM
660 return ((struct remote_arch_state *)
661 gdbarch_data (target_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. */
674 get_remote_arch_state ();
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 struct packet_reg *regs;
807 struct cleanup *old_chain;
808
809 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
810
224c3ddb 811 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
c21236dc
PA
812 old_chain = make_cleanup (xfree, regs);
813
54887903 814 map_regcache_remote_table (gdbarch, regs);
c21236dc
PA
815
816 *pnum = regs[regnum].pnum;
817 *poffset = regs[regnum].offset;
818
819 do_cleanups (old_chain);
820
821 return *pnum != -1;
822}
823
824static void *
825init_remote_state (struct gdbarch *gdbarch)
826{
827 struct remote_state *rs = get_remote_state_raw ();
828 struct remote_arch_state *rsa;
829
830 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
831
832 /* Use the architecture to build a regnum<->pnum table, which will be
833 1:1 unless a feature set specifies otherwise. */
834 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
835 gdbarch_num_regs (gdbarch),
836 struct packet_reg);
837
74ca34ce
DJ
838 /* Record the maximum possible size of the g packet - it may turn out
839 to be smaller. */
c21236dc 840 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 841
0df8b418 842 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
843 remote stubs have a hardwired buffer size of 400 bytes
844 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
845 as the maximum packet-size to ensure that the packet and an extra
846 NUL character can always fit in the buffer. This stops GDB
847 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
848 already a full buffer (As of 1999-12-04 that was most stubs). */
849 rsa->remote_packet_size = 400 - 1;
d01949b6 850
ea9c271d
DJ
851 /* This one is filled in when a ``g'' packet is received. */
852 rsa->actual_register_packet_size = 0;
853
854 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
855 default, adjust the size accordingly. Remember that each byte is
856 encoded as two characters. 32 is the overhead for the packet
857 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 858 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 859 little. */
ea9c271d
DJ
860 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
861 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 862
ea9c271d
DJ
863 /* Make sure that the packet buffer is plenty big enough for
864 this architecture. */
865 if (rs->buf_size < rsa->remote_packet_size)
866 {
867 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 868 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 869 }
6d820c5c 870
ea9c271d
DJ
871 return rsa;
872}
873
874/* Return the current allowed size of a remote packet. This is
875 inferred from the current architecture, and should be used to
876 limit the length of outgoing packets. */
877static long
878get_remote_packet_size (void)
879{
be2a5f71 880 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
881 struct remote_arch_state *rsa = get_remote_arch_state ();
882
be2a5f71
DJ
883 if (rs->explicit_packet_size)
884 return rs->explicit_packet_size;
885
ea9c271d 886 return rsa->remote_packet_size;
d01949b6
AC
887}
888
ad10f812 889static struct packet_reg *
ea9c271d 890packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 891{
f5656ead 892 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
893 return NULL;
894 else
ad10f812 895 {
ea9c271d 896 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 897
b323314b
AC
898 gdb_assert (r->regnum == regnum);
899 return r;
ad10f812 900 }
ad10f812
AC
901}
902
903static struct packet_reg *
ea9c271d 904packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 905{
b323314b 906 int i;
a744cf53 907
f5656ead 908 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 909 {
ea9c271d 910 struct packet_reg *r = &rsa->regs[i];
a744cf53 911
b323314b
AC
912 if (r->pnum == pnum)
913 return r;
ad10f812
AC
914 }
915 return NULL;
d01949b6
AC
916}
917
c906108c
SS
918static struct target_ops remote_ops;
919
920static struct target_ops extended_remote_ops;
921
6426a772
JM
922/* FIXME: cagney/1999-09-23: Even though getpkt was called with
923 ``forever'' still use the normal timeout mechanism. This is
924 currently used by the ASYNC code to guarentee that target reads
925 during the initial connect always time-out. Once getpkt has been
926 modified to return a timeout indication and, in turn
927 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 928 this can go away. */
6426a772
JM
929static int wait_forever_enabled_p = 1;
930
9a7071a8
JB
931/* Allow the user to specify what sequence to send to the remote
932 when he requests a program interruption: Although ^C is usually
933 what remote systems expect (this is the default, here), it is
934 sometimes preferable to send a break. On other systems such
935 as the Linux kernel, a break followed by g, which is Magic SysRq g
936 is required in order to interrupt the execution. */
937const char interrupt_sequence_control_c[] = "Ctrl-C";
938const char interrupt_sequence_break[] = "BREAK";
939const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 940static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
941 {
942 interrupt_sequence_control_c,
943 interrupt_sequence_break,
944 interrupt_sequence_break_g,
945 NULL
946 };
947static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
948
949static void
950show_interrupt_sequence (struct ui_file *file, int from_tty,
951 struct cmd_list_element *c,
952 const char *value)
953{
954 if (interrupt_sequence_mode == interrupt_sequence_control_c)
955 fprintf_filtered (file,
956 _("Send the ASCII ETX character (Ctrl-c) "
957 "to the remote target to interrupt the "
958 "execution of the program.\n"));
959 else if (interrupt_sequence_mode == interrupt_sequence_break)
960 fprintf_filtered (file,
961 _("send a break signal to the remote target "
962 "to interrupt the execution of the program.\n"));
963 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
964 fprintf_filtered (file,
965 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
966 "the remote target to interrupt the execution "
967 "of Linux kernel.\n"));
968 else
969 internal_error (__FILE__, __LINE__,
970 _("Invalid value for interrupt_sequence_mode: %s."),
971 interrupt_sequence_mode);
972}
6426a772 973
9a7071a8
JB
974/* This boolean variable specifies whether interrupt_sequence is sent
975 to the remote target when gdb connects to it.
976 This is mostly needed when you debug the Linux kernel: The Linux kernel
977 expects BREAK g which is Magic SysRq g for connecting gdb. */
978static int interrupt_on_connect = 0;
c906108c 979
9a7071a8
JB
980/* This variable is used to implement the "set/show remotebreak" commands.
981 Since these commands are now deprecated in favor of "set/show remote
982 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
983static int remote_break;
984
9a7071a8
JB
985static void
986set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
987{
988 if (remote_break)
989 interrupt_sequence_mode = interrupt_sequence_break;
990 else
991 interrupt_sequence_mode = interrupt_sequence_control_c;
992}
993
994static void
995show_remotebreak (struct ui_file *file, int from_tty,
996 struct cmd_list_element *c,
997 const char *value)
998{
999}
1000
c906108c
SS
1001/* This variable sets the number of bits in an address that are to be
1002 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1003 leading zeros, the entire address would be sent. This variable
c906108c
SS
1004 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1005 initial implementation of remote.c restricted the address sent in
1006 memory packets to ``host::sizeof long'' bytes - (typically 32
1007 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1008 address was never sent. Since fixing this bug may cause a break in
1009 some remote targets this variable is principly provided to
23860348 1010 facilitate backward compatibility. */
c906108c 1011
883b9c6c 1012static unsigned int remote_address_size;
c906108c 1013
75c99385
PA
1014/* Temporary to track who currently owns the terminal. See
1015 remote_terminal_* for more details. */
6426a772
JM
1016
1017static int remote_async_terminal_ours_p;
1018
11cf8741 1019\f
11cf8741 1020/* User configurable variables for the number of characters in a
ea9c271d
DJ
1021 memory read/write packet. MIN (rsa->remote_packet_size,
1022 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1023 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1024 (speed up transfers). The variables ``preferred_*'' (the user
1025 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1026 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1027
1028struct memory_packet_config
1029{
a121b7c1 1030 const char *name;
11cf8741
JM
1031 long size;
1032 int fixed_p;
1033};
1034
a5c0808e
PA
1035/* The default max memory-write-packet-size. The 16k is historical.
1036 (It came from older GDB's using alloca for buffers and the
1037 knowledge (folklore?) that some hosts don't cope very well with
1038 large alloca calls.) */
1039#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1040
1041/* The minimum remote packet size for memory transfers. Ensures we
1042 can write at least one byte. */
1043#define MIN_MEMORY_PACKET_SIZE 20
1044
11cf8741
JM
1045/* Compute the current size of a read/write packet. Since this makes
1046 use of ``actual_register_packet_size'' the computation is dynamic. */
1047
1048static long
1049get_memory_packet_size (struct memory_packet_config *config)
1050{
d01949b6 1051 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
1052 struct remote_arch_state *rsa = get_remote_arch_state ();
1053
11cf8741
JM
1054 long what_they_get;
1055 if (config->fixed_p)
1056 {
1057 if (config->size <= 0)
a5c0808e 1058 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1059 else
1060 what_they_get = config->size;
1061 }
1062 else
1063 {
ea9c271d 1064 what_they_get = get_remote_packet_size ();
23860348 1065 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1066 if (config->size > 0
1067 && what_they_get > config->size)
1068 what_they_get = config->size;
be2a5f71
DJ
1069
1070 /* Limit it to the size of the targets ``g'' response unless we have
1071 permission from the stub to use a larger packet size. */
1072 if (rs->explicit_packet_size == 0
1073 && rsa->actual_register_packet_size > 0
1074 && what_they_get > rsa->actual_register_packet_size)
1075 what_they_get = rsa->actual_register_packet_size;
11cf8741 1076 }
a5c0808e
PA
1077 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1078 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1079
1080 /* Make sure there is room in the global buffer for this packet
1081 (including its trailing NUL byte). */
1082 if (rs->buf_size < what_they_get + 1)
1083 {
1084 rs->buf_size = 2 * what_they_get;
224c3ddb 1085 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1086 }
1087
11cf8741
JM
1088 return what_they_get;
1089}
1090
0df8b418 1091/* Update the size of a read/write packet. If they user wants
23860348 1092 something really big then do a sanity check. */
11cf8741
JM
1093
1094static void
ac88e2de 1095set_memory_packet_size (const char *args, struct memory_packet_config *config)
11cf8741
JM
1096{
1097 int fixed_p = config->fixed_p;
1098 long size = config->size;
a744cf53 1099
11cf8741 1100 if (args == NULL)
8a3fe4f8 1101 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1102 else if (strcmp (args, "hard") == 0
1103 || strcmp (args, "fixed") == 0)
1104 fixed_p = 1;
1105 else if (strcmp (args, "soft") == 0
1106 || strcmp (args, "limit") == 0)
1107 fixed_p = 0;
1108 else
1109 {
1110 char *end;
a744cf53 1111
11cf8741
JM
1112 size = strtoul (args, &end, 0);
1113 if (args == end)
8a3fe4f8 1114 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1115
1116 /* Instead of explicitly capping the size of a packet to or
1117 disallowing it, the user is allowed to set the size to
1118 something arbitrarily large. */
11cf8741 1119 }
a5c0808e
PA
1120
1121 /* So that the query shows the correct value. */
1122 if (size <= 0)
1123 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1124
23860348 1125 /* Extra checks? */
11cf8741
JM
1126 if (fixed_p && !config->fixed_p)
1127 {
e2e0b3e5
AC
1128 if (! query (_("The target may not be able to correctly handle a %s\n"
1129 "of %ld bytes. Change the packet size? "),
11cf8741 1130 config->name, size))
8a3fe4f8 1131 error (_("Packet size not changed."));
11cf8741 1132 }
23860348 1133 /* Update the config. */
11cf8741
JM
1134 config->fixed_p = fixed_p;
1135 config->size = size;
1136}
1137
1138static void
1139show_memory_packet_size (struct memory_packet_config *config)
1140{
a3f17187 1141 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1142 if (config->fixed_p)
a3f17187 1143 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1144 get_memory_packet_size (config));
1145 else
a3f17187 1146 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1147 get_memory_packet_size (config));
1148}
1149
1150static struct memory_packet_config memory_write_packet_config =
1151{
1152 "memory-write-packet-size",
1153};
1154
1155static void
ac88e2de 1156set_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1157{
1158 set_memory_packet_size (args, &memory_write_packet_config);
1159}
1160
1161static void
ac88e2de 1162show_memory_write_packet_size (const char *args, int from_tty)
11cf8741
JM
1163{
1164 show_memory_packet_size (&memory_write_packet_config);
1165}
1166
1167static long
1168get_memory_write_packet_size (void)
1169{
1170 return get_memory_packet_size (&memory_write_packet_config);
1171}
1172
1173static struct memory_packet_config memory_read_packet_config =
1174{
1175 "memory-read-packet-size",
1176};
1177
1178static void
ac88e2de 1179set_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1180{
1181 set_memory_packet_size (args, &memory_read_packet_config);
1182}
1183
1184static void
ac88e2de 1185show_memory_read_packet_size (const char *args, int from_tty)
11cf8741
JM
1186{
1187 show_memory_packet_size (&memory_read_packet_config);
1188}
1189
1190static long
1191get_memory_read_packet_size (void)
1192{
1193 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1194
11cf8741
JM
1195 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1196 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1197 increased beyond this. */
1198 if (size > get_remote_packet_size ())
1199 size = get_remote_packet_size ();
11cf8741
JM
1200 return size;
1201}
1202
11cf8741 1203\f
5a2468f5 1204/* Generic configuration support for packets the stub optionally
0df8b418 1205 supports. Allows the user to specify the use of the packet as well
23860348 1206 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1207
1208enum packet_support
1209 {
1210 PACKET_SUPPORT_UNKNOWN = 0,
1211 PACKET_ENABLE,
1212 PACKET_DISABLE
1213 };
1214
5a2468f5
JM
1215struct packet_config
1216 {
bb572ddd
DJ
1217 const char *name;
1218 const char *title;
4082afcc
PA
1219
1220 /* If auto, GDB auto-detects support for this packet or feature,
1221 either through qSupported, or by trying the packet and looking
1222 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1223 packet. If false, the packet is disabled. Configs that don't
1224 have an associated command always have this set to auto. */
7f19b9a2 1225 enum auto_boolean detect;
4082afcc
PA
1226
1227 /* Does the target support this packet? */
5a2468f5
JM
1228 enum packet_support support;
1229 };
1230
d471ea57 1231/* Analyze a packet's return value and update the packet config
23860348 1232 accordingly. */
d471ea57
AC
1233
1234enum packet_result
1235{
1236 PACKET_ERROR,
1237 PACKET_OK,
1238 PACKET_UNKNOWN
1239};
1240
4082afcc
PA
1241static enum packet_support packet_config_support (struct packet_config *config);
1242static enum packet_support packet_support (int packet);
5a2468f5
JM
1243
1244static void
fba45db2 1245show_packet_config_cmd (struct packet_config *config)
5a2468f5 1246{
a121b7c1 1247 const char *support = "internal-error";
a744cf53 1248
4082afcc 1249 switch (packet_config_support (config))
5a2468f5
JM
1250 {
1251 case PACKET_ENABLE:
1252 support = "enabled";
1253 break;
1254 case PACKET_DISABLE:
1255 support = "disabled";
1256 break;
1257 case PACKET_SUPPORT_UNKNOWN:
1258 support = "unknown";
1259 break;
1260 }
1261 switch (config->detect)
1262 {
7f19b9a2 1263 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1264 printf_filtered (_("Support for the `%s' packet "
1265 "is auto-detected, currently %s.\n"),
37a105a1 1266 config->name, support);
5a2468f5 1267 break;
7f19b9a2
AC
1268 case AUTO_BOOLEAN_TRUE:
1269 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1270 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1271 config->name, support);
8e248173 1272 break;
5a2468f5
JM
1273 }
1274}
1275
1276static void
bb572ddd
DJ
1277add_packet_config_cmd (struct packet_config *config, const char *name,
1278 const char *title, int legacy)
d471ea57 1279{
5a2468f5
JM
1280 char *set_doc;
1281 char *show_doc;
d471ea57 1282 char *cmd_name;
3ed07be4 1283
5a2468f5
JM
1284 config->name = name;
1285 config->title = title;
b435e160
AC
1286 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1287 name, title);
3e43a32a
MS
1288 show_doc = xstrprintf ("Show current use of remote "
1289 "protocol `%s' (%s) packet",
b435e160 1290 name, title);
d471ea57 1291 /* set/show TITLE-packet {auto,on,off} */
b435e160 1292 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1293 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1294 &config->detect, set_doc,
1295 show_doc, NULL, /* help_doc */
4082afcc 1296 NULL,
bb572ddd
DJ
1297 show_remote_protocol_packet_cmd,
1298 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1299 /* The command code copies the documentation strings. */
1300 xfree (set_doc);
1301 xfree (show_doc);
23860348 1302 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1303 if (legacy)
1304 {
1305 char *legacy_name;
a744cf53 1306
b435e160 1307 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1308 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1309 &remote_set_cmdlist);
d471ea57 1310 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1311 &remote_show_cmdlist);
d471ea57 1312 }
5a2468f5
JM
1313}
1314
d471ea57 1315static enum packet_result
a76d924d 1316packet_check_result (const char *buf)
5a2468f5 1317{
d471ea57 1318 if (buf[0] != '\0')
5a2468f5 1319 {
d471ea57 1320 /* The stub recognized the packet request. Check that the
23860348 1321 operation succeeded. */
a76d924d
DJ
1322 if (buf[0] == 'E'
1323 && isxdigit (buf[1]) && isxdigit (buf[2])
1324 && buf[3] == '\0')
1325 /* "Enn" - definitly an error. */
1326 return PACKET_ERROR;
1327
1328 /* Always treat "E." as an error. This will be used for
1329 more verbose error messages, such as E.memtypes. */
1330 if (buf[0] == 'E' && buf[1] == '.')
1331 return PACKET_ERROR;
1332
1333 /* The packet may or may not be OK. Just assume it is. */
1334 return PACKET_OK;
1335 }
1336 else
1337 /* The stub does not support the packet. */
1338 return PACKET_UNKNOWN;
1339}
1340
1341static enum packet_result
1342packet_ok (const char *buf, struct packet_config *config)
1343{
1344 enum packet_result result;
1345
4082afcc
PA
1346 if (config->detect != AUTO_BOOLEAN_TRUE
1347 && config->support == PACKET_DISABLE)
1348 internal_error (__FILE__, __LINE__,
1349 _("packet_ok: attempt to use a disabled packet"));
1350
a76d924d
DJ
1351 result = packet_check_result (buf);
1352 switch (result)
1353 {
1354 case PACKET_OK:
1355 case PACKET_ERROR:
1356 /* The stub recognized the packet request. */
4082afcc 1357 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1358 {
d471ea57
AC
1359 if (remote_debug)
1360 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1361 "Packet %s (%s) is supported\n",
1362 config->name, config->title);
d471ea57 1363 config->support = PACKET_ENABLE;
d471ea57 1364 }
a76d924d
DJ
1365 break;
1366 case PACKET_UNKNOWN:
23860348 1367 /* The stub does not support the packet. */
4082afcc
PA
1368 if (config->detect == AUTO_BOOLEAN_AUTO
1369 && config->support == PACKET_ENABLE)
d471ea57 1370 {
4082afcc
PA
1371 /* If the stub previously indicated that the packet was
1372 supported then there is a protocol error. */
1373 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1374 config->name, config->title);
1375 }
1376 else if (config->detect == AUTO_BOOLEAN_TRUE)
1377 {
1378 /* The user set it wrong. */
1379 error (_("Enabled packet %s (%s) not recognized by stub"),
1380 config->name, config->title);
d471ea57 1381 }
4082afcc
PA
1382
1383 if (remote_debug)
1384 fprintf_unfiltered (gdb_stdlog,
1385 "Packet %s (%s) is NOT supported\n",
1386 config->name, config->title);
1387 config->support = PACKET_DISABLE;
a76d924d 1388 break;
5a2468f5 1389 }
a76d924d
DJ
1390
1391 return result;
5a2468f5
JM
1392}
1393
444abaca
DJ
1394enum {
1395 PACKET_vCont = 0,
1396 PACKET_X,
1397 PACKET_qSymbol,
1398 PACKET_P,
1399 PACKET_p,
1400 PACKET_Z0,
1401 PACKET_Z1,
1402 PACKET_Z2,
1403 PACKET_Z3,
1404 PACKET_Z4,
15a201c8 1405 PACKET_vFile_setfs,
a6b151f1
DJ
1406 PACKET_vFile_open,
1407 PACKET_vFile_pread,
1408 PACKET_vFile_pwrite,
1409 PACKET_vFile_close,
1410 PACKET_vFile_unlink,
b9e7b9c3 1411 PACKET_vFile_readlink,
0a93529c 1412 PACKET_vFile_fstat,
0876f84a 1413 PACKET_qXfer_auxv,
23181151 1414 PACKET_qXfer_features,
c78fa86a 1415 PACKET_qXfer_exec_file,
cfa9d6d9 1416 PACKET_qXfer_libraries,
2268b414 1417 PACKET_qXfer_libraries_svr4,
fd79ecee 1418 PACKET_qXfer_memory_map,
0e7f50da
UW
1419 PACKET_qXfer_spu_read,
1420 PACKET_qXfer_spu_write,
07e059b5 1421 PACKET_qXfer_osdata,
dc146f7c 1422 PACKET_qXfer_threads,
0fb4aa4b 1423 PACKET_qXfer_statictrace_read,
b3b9301e 1424 PACKET_qXfer_traceframe_info,
169081d0 1425 PACKET_qXfer_uib,
711e434b 1426 PACKET_qGetTIBAddr,
444abaca 1427 PACKET_qGetTLSAddr,
be2a5f71 1428 PACKET_qSupported,
bd3eecc3 1429 PACKET_qTStatus,
89be2091 1430 PACKET_QPassSignals,
82075af2 1431 PACKET_QCatchSyscalls,
9b224c5e 1432 PACKET_QProgramSignals,
aefd8b33 1433 PACKET_QStartupWithShell,
0a2dde4a
SDJ
1434 PACKET_QEnvironmentHexEncoded,
1435 PACKET_QEnvironmentReset,
1436 PACKET_QEnvironmentUnset,
936d2992 1437 PACKET_qCRC,
08388c79 1438 PACKET_qSearch_memory,
2d717e4f
DJ
1439 PACKET_vAttach,
1440 PACKET_vRun,
a6f3e723 1441 PACKET_QStartNoAckMode,
82f73884 1442 PACKET_vKill,
4aa995e1
PA
1443 PACKET_qXfer_siginfo_read,
1444 PACKET_qXfer_siginfo_write,
0b16c5cf 1445 PACKET_qAttached,
4082afcc
PA
1446
1447 /* Support for conditional tracepoints. */
782b2b07 1448 PACKET_ConditionalTracepoints,
4082afcc
PA
1449
1450 /* Support for target-side breakpoint conditions. */
3788aec7 1451 PACKET_ConditionalBreakpoints,
4082afcc
PA
1452
1453 /* Support for target-side breakpoint commands. */
d3ce09f5 1454 PACKET_BreakpointCommands,
4082afcc
PA
1455
1456 /* Support for fast tracepoints. */
7a697b8d 1457 PACKET_FastTracepoints,
4082afcc
PA
1458
1459 /* Support for static tracepoints. */
0fb4aa4b 1460 PACKET_StaticTracepoints,
4082afcc
PA
1461
1462 /* Support for installing tracepoints while a trace experiment is
1463 running. */
1e4d1764 1464 PACKET_InstallInTrace,
4082afcc 1465
40ab02ce
MS
1466 PACKET_bc,
1467 PACKET_bs,
409873ef 1468 PACKET_TracepointSource,
d914c394 1469 PACKET_QAllow,
78d85199 1470 PACKET_qXfer_fdpic,
03583c20 1471 PACKET_QDisableRandomization,
d1feda86 1472 PACKET_QAgent,
f6f899bf 1473 PACKET_QTBuffer_size,
9accd112
MM
1474 PACKET_Qbtrace_off,
1475 PACKET_Qbtrace_bts,
b20a6524 1476 PACKET_Qbtrace_pt,
9accd112 1477 PACKET_qXfer_btrace,
4082afcc
PA
1478
1479 /* Support for the QNonStop packet. */
1480 PACKET_QNonStop,
1481
65706a29
PA
1482 /* Support for the QThreadEvents packet. */
1483 PACKET_QThreadEvents,
1484
4082afcc
PA
1485 /* Support for multi-process extensions. */
1486 PACKET_multiprocess_feature,
1487
1488 /* Support for enabling and disabling tracepoints while a trace
1489 experiment is running. */
1490 PACKET_EnableDisableTracepoints_feature,
1491
1492 /* Support for collecting strings using the tracenz bytecode. */
1493 PACKET_tracenz_feature,
1494
1495 /* Support for continuing to run a trace experiment while GDB is
1496 disconnected. */
1497 PACKET_DisconnectedTracing_feature,
1498
1499 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1500 PACKET_augmented_libraries_svr4_read_feature,
1501
f4abbc16
MM
1502 /* Support for the qXfer:btrace-conf:read packet. */
1503 PACKET_qXfer_btrace_conf,
1504
d33501a5
MM
1505 /* Support for the Qbtrace-conf:bts:size packet. */
1506 PACKET_Qbtrace_conf_bts_size,
1507
f7e6eed5
PA
1508 /* Support for swbreak+ feature. */
1509 PACKET_swbreak_feature,
1510
1511 /* Support for hwbreak+ feature. */
1512 PACKET_hwbreak_feature,
1513
89245bc0
DB
1514 /* Support for fork events. */
1515 PACKET_fork_event_feature,
1516
1517 /* Support for vfork events. */
1518 PACKET_vfork_event_feature,
1519
b20a6524
MM
1520 /* Support for the Qbtrace-conf:pt:size packet. */
1521 PACKET_Qbtrace_conf_pt_size,
1522
94585166
DB
1523 /* Support for exec events. */
1524 PACKET_exec_event_feature,
1525
750ce8d1
YQ
1526 /* Support for query supported vCont actions. */
1527 PACKET_vContSupported,
1528
de979965
PA
1529 /* Support remote CTRL-C. */
1530 PACKET_vCtrlC,
1531
f2faf941
PA
1532 /* Support TARGET_WAITKIND_NO_RESUMED. */
1533 PACKET_no_resumed,
1534
444abaca
DJ
1535 PACKET_MAX
1536};
506fb367 1537
444abaca 1538static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1539
f7e6eed5
PA
1540/* Returns the packet's corresponding "set remote foo-packet" command
1541 state. See struct packet_config for more details. */
1542
1543static enum auto_boolean
1544packet_set_cmd_state (int packet)
1545{
1546 return remote_protocol_packets[packet].detect;
1547}
1548
4082afcc
PA
1549/* Returns whether a given packet or feature is supported. This takes
1550 into account the state of the corresponding "set remote foo-packet"
1551 command, which may be used to bypass auto-detection. */
dc8acb97 1552
4082afcc
PA
1553static enum packet_support
1554packet_config_support (struct packet_config *config)
1555{
1556 switch (config->detect)
444abaca 1557 {
4082afcc
PA
1558 case AUTO_BOOLEAN_TRUE:
1559 return PACKET_ENABLE;
1560 case AUTO_BOOLEAN_FALSE:
1561 return PACKET_DISABLE;
1562 case AUTO_BOOLEAN_AUTO:
1563 return config->support;
1564 default:
1565 gdb_assert_not_reached (_("bad switch"));
444abaca 1566 }
4082afcc
PA
1567}
1568
1569/* Same as packet_config_support, but takes the packet's enum value as
1570 argument. */
1571
1572static enum packet_support
1573packet_support (int packet)
1574{
1575 struct packet_config *config = &remote_protocol_packets[packet];
1576
1577 return packet_config_support (config);
dc8acb97
MS
1578}
1579
5a2468f5 1580static void
444abaca
DJ
1581show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1582 struct cmd_list_element *c,
1583 const char *value)
5a2468f5 1584{
444abaca 1585 struct packet_config *packet;
5a2468f5 1586
444abaca
DJ
1587 for (packet = remote_protocol_packets;
1588 packet < &remote_protocol_packets[PACKET_MAX];
1589 packet++)
1590 {
1591 if (&packet->detect == c->var)
1592 {
1593 show_packet_config_cmd (packet);
1594 return;
1595 }
1596 }
9b20d036 1597 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1598 c->name);
5a2468f5
JM
1599}
1600
d471ea57
AC
1601/* Should we try one of the 'Z' requests? */
1602
1603enum Z_packet_type
1604{
1605 Z_PACKET_SOFTWARE_BP,
1606 Z_PACKET_HARDWARE_BP,
1607 Z_PACKET_WRITE_WP,
1608 Z_PACKET_READ_WP,
1609 Z_PACKET_ACCESS_WP,
1610 NR_Z_PACKET_TYPES
1611};
96baa820 1612
d471ea57 1613/* For compatibility with older distributions. Provide a ``set remote
23860348 1614 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1615
7f19b9a2 1616static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1617
1618static void
fba45db2
KB
1619set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1620 struct cmd_list_element *c)
96baa820 1621{
d471ea57 1622 int i;
a744cf53 1623
d471ea57 1624 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1625 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1626}
1627
1628static void
08546159
AC
1629show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1630 struct cmd_list_element *c,
1631 const char *value)
96baa820 1632{
d471ea57 1633 int i;
a744cf53 1634
d471ea57
AC
1635 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1636 {
444abaca 1637 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1638 }
96baa820
JM
1639}
1640
4082afcc
PA
1641/* Returns true if the multi-process extensions are in effect. */
1642
1643static int
1644remote_multi_process_p (struct remote_state *rs)
1645{
1646 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1647}
1648
de0d863e
DB
1649/* Returns true if fork events are supported. */
1650
1651static int
1652remote_fork_event_p (struct remote_state *rs)
1653{
1654 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1655}
1656
c269dbdb
DB
1657/* Returns true if vfork events are supported. */
1658
1659static int
1660remote_vfork_event_p (struct remote_state *rs)
1661{
1662 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1663}
1664
d46addbb
DB
1665/* Returns true if exec events are supported. */
1666
1667static int
1668remote_exec_event_p (struct remote_state *rs)
1669{
1670 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1671}
1672
cbb8991c
DB
1673/* Insert fork catchpoint target routine. If fork events are enabled
1674 then return success, nothing more to do. */
1675
1676static int
1677remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1678{
1679 struct remote_state *rs = get_remote_state ();
1680
1681 return !remote_fork_event_p (rs);
1682}
1683
1684/* Remove fork catchpoint target routine. Nothing to do, just
1685 return success. */
1686
1687static int
1688remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1689{
1690 return 0;
1691}
1692
1693/* Insert vfork catchpoint target routine. If vfork events are enabled
1694 then return success, nothing more to do. */
1695
1696static int
1697remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1698{
1699 struct remote_state *rs = get_remote_state ();
1700
1701 return !remote_vfork_event_p (rs);
1702}
1703
1704/* Remove vfork catchpoint target routine. Nothing to do, just
1705 return success. */
1706
1707static int
1708remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1709{
1710 return 0;
1711}
1712
d46addbb
DB
1713/* Insert exec catchpoint target routine. If exec events are
1714 enabled, just return success. */
1715
1716static int
1717remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1718{
1719 struct remote_state *rs = get_remote_state ();
1720
1721 return !remote_exec_event_p (rs);
1722}
1723
1724/* Remove exec catchpoint target routine. Nothing to do, just
1725 return success. */
1726
1727static int
1728remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1729{
1730 return 0;
1731}
1732
74531fed
PA
1733\f
1734/* Asynchronous signal handle registered as event loop source for
1735 when we have pending events ready to be passed to the core. */
1736
1737static struct async_event_handler *remote_async_inferior_event_token;
1738
c906108c
SS
1739\f
1740
79d7f229
PA
1741static ptid_t magic_null_ptid;
1742static ptid_t not_sent_ptid;
1743static ptid_t any_thread_ptid;
1744
0b16c5cf
PA
1745/* Find out if the stub attached to PID (and hence GDB should offer to
1746 detach instead of killing it when bailing out). */
1747
1748static int
1749remote_query_attached (int pid)
1750{
1751 struct remote_state *rs = get_remote_state ();
bba74b36 1752 size_t size = get_remote_packet_size ();
0b16c5cf 1753
4082afcc 1754 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1755 return 0;
1756
1757 if (remote_multi_process_p (rs))
bba74b36 1758 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1759 else
bba74b36 1760 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1761
1762 putpkt (rs->buf);
1763 getpkt (&rs->buf, &rs->buf_size, 0);
1764
1765 switch (packet_ok (rs->buf,
1554e9be 1766 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1767 {
1768 case PACKET_OK:
1769 if (strcmp (rs->buf, "1") == 0)
1770 return 1;
1771 break;
1772 case PACKET_ERROR:
1773 warning (_("Remote failure reply: %s"), rs->buf);
1774 break;
1775 case PACKET_UNKNOWN:
1776 break;
1777 }
1778
1779 return 0;
1780}
1781
49c62f2e
PA
1782/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1783 has been invented by GDB, instead of reported by the target. Since
1784 we can be connected to a remote system before before knowing about
1785 any inferior, mark the target with execution when we find the first
1786 inferior. If ATTACHED is 1, then we had just attached to this
1787 inferior. If it is 0, then we just created this inferior. If it
1788 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1789 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1790 attempt to open this inferior's executable as the main executable
1791 if no main executable is open already. */
1941c569
PA
1792
1793static struct inferior *
1b6e6f5c
GB
1794remote_add_inferior (int fake_pid_p, int pid, int attached,
1795 int try_open_exec)
1941c569 1796{
1941c569
PA
1797 struct inferior *inf;
1798
0b16c5cf
PA
1799 /* Check whether this process we're learning about is to be
1800 considered attached, or if is to be considered to have been
1801 spawned by the stub. */
1802 if (attached == -1)
1803 attached = remote_query_attached (pid);
1804
f5656ead 1805 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1806 {
1807 /* If the target shares code across all inferiors, then every
1808 attach adds a new inferior. */
1809 inf = add_inferior (pid);
1810
1811 /* ... and every inferior is bound to the same program space.
1812 However, each inferior may still have its own address
1813 space. */
1814 inf->aspace = maybe_new_address_space ();
1815 inf->pspace = current_program_space;
1816 }
1817 else
1818 {
1819 /* In the traditional debugging scenario, there's a 1-1 match
1820 between program/address spaces. We simply bind the inferior
1821 to the program space's address space. */
1822 inf = current_inferior ();
1823 inferior_appeared (inf, pid);
1824 }
1941c569 1825
0b16c5cf 1826 inf->attach_flag = attached;
49c62f2e 1827 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1828
1b6e6f5c
GB
1829 /* If no main executable is currently open then attempt to
1830 open the file that was executed to create this inferior. */
835205d0 1831 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 1832 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 1833
1941c569
PA
1834 return inf;
1835}
1836
85ad3aaf
PA
1837static struct private_thread_info *
1838 get_private_info_thread (struct thread_info *info);
1839
1941c569
PA
1840/* Add thread PTID to GDB's thread list. Tag it as executing/running
1841 according to RUNNING. */
1842
c906108c 1843static void
0d5b594f 1844remote_add_thread (ptid_t ptid, int running, int executing)
c906108c 1845{
b7ea362b 1846 struct remote_state *rs = get_remote_state ();
85ad3aaf 1847 struct thread_info *thread;
b7ea362b
PA
1848
1849 /* GDB historically didn't pull threads in the initial connection
1850 setup. If the remote target doesn't even have a concept of
1851 threads (e.g., a bare-metal target), even if internally we
1852 consider that a single-threaded target, mentioning a new thread
1853 might be confusing to the user. Be silent then, preserving the
1854 age old behavior. */
1855 if (rs->starting_up)
85ad3aaf 1856 thread = add_thread_silent (ptid);
b7ea362b 1857 else
85ad3aaf 1858 thread = add_thread (ptid);
1941c569 1859
85ad3aaf 1860 get_private_info_thread (thread)->vcont_resumed = executing;
0d5b594f 1861 set_executing (ptid, executing);
1941c569
PA
1862 set_running (ptid, running);
1863}
1864
1865/* Come here when we learn about a thread id from the remote target.
1866 It may be the first time we hear about such thread, so take the
1867 opportunity to add it to GDB's thread list. In case this is the
1868 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
1869 GDB's inferior list as well. EXECUTING indicates whether the
1870 thread is (internally) executing or stopped. */
1941c569
PA
1871
1872static void
0d5b594f 1873remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 1874{
0d5b594f
PA
1875 /* In non-stop mode, we assume new found threads are (externally)
1876 running until proven otherwise with a stop reply. In all-stop,
1877 we can only get here if all threads are stopped. */
1878 int running = target_is_non_stop_p () ? 1 : 0;
1879
c906108c
SS
1880 /* If this is a new thread, add it to GDB's thread list.
1881 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1882
1883 if (in_thread_list (currthread) && is_exited (currthread))
1884 {
1885 /* We're seeing an event on a thread id we knew had exited.
1886 This has to be a new thread reusing the old id. Add it. */
0d5b594f 1887 remote_add_thread (currthread, running, executing);
82f73884
PA
1888 return;
1889 }
1890
79d7f229 1891 if (!in_thread_list (currthread))
c0a2216e 1892 {
1941c569 1893 struct inferior *inf = NULL;
bad34192 1894 int pid = ptid_get_pid (currthread);
1941c569 1895
bad34192
PA
1896 if (ptid_is_pid (inferior_ptid)
1897 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1898 {
1899 /* inferior_ptid has no thread member yet. This can happen
1900 with the vAttach -> remote_wait,"TAAthread:" path if the
1901 stub doesn't support qC. This is the first stop reported
1902 after an attach, so this is the main thread. Update the
1903 ptid in the thread list. */
bad34192
PA
1904 if (in_thread_list (pid_to_ptid (pid)))
1905 thread_change_ptid (inferior_ptid, currthread);
1906 else
1907 {
0d5b594f 1908 remote_add_thread (currthread, running, executing);
bad34192
PA
1909 inferior_ptid = currthread;
1910 }
dc146f7c 1911 return;
c0a2216e 1912 }
82f73884
PA
1913
1914 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1915 {
1916 /* inferior_ptid is not set yet. This can happen with the
1917 vRun -> remote_wait,"TAAthread:" path if the stub
1918 doesn't support qC. This is the first stop reported
1919 after an attach, so this is the main thread. Update the
1920 ptid in the thread list. */
dc146f7c 1921 thread_change_ptid (inferior_ptid, currthread);
82f73884 1922 return;
c0a2216e 1923 }
82f73884 1924
29c87f7f
PA
1925 /* When connecting to a target remote, or to a target
1926 extended-remote which already was debugging an inferior, we
1927 may not know about it yet. Add it before adding its child
1928 thread, so notifications are emitted in a sensible order. */
1929 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1930 {
1931 struct remote_state *rs = get_remote_state ();
1932 int fake_pid_p = !remote_multi_process_p (rs);
1933
1934 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1935 ptid_get_pid (currthread), -1, 1);
49c62f2e 1936 }
29c87f7f 1937
82f73884 1938 /* This is really a new thread. Add it. */
0d5b594f 1939 remote_add_thread (currthread, running, executing);
1941c569
PA
1940
1941 /* If we found a new inferior, let the common code do whatever
1942 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1943 breakpoints), unless we're just setting up an all-stop
1944 connection. */
1941c569 1945 if (inf != NULL)
b7ea362b
PA
1946 {
1947 struct remote_state *rs = get_remote_state ();
1948
6efcd9a8 1949 if (!rs->starting_up)
0d5b594f 1950 notice_new_inferior (currthread, executing, 0);
b7ea362b 1951 }
c0a2216e 1952 }
c906108c
SS
1953}
1954
85ad3aaf 1955/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 1956
70221824 1957static struct private_thread_info *
85ad3aaf 1958get_private_info_thread (struct thread_info *thread)
dc146f7c 1959{
85ad3aaf 1960 gdb_assert (thread != NULL);
dc146f7c 1961
85ad3aaf 1962 if (thread->priv == NULL)
dc146f7c 1963 {
85ad3aaf
PA
1964 struct private_thread_info *priv = XNEW (struct private_thread_info);
1965
1966 thread->private_dtor = free_private_thread_info;
1967 thread->priv = priv;
1968
1969 priv->core = -1;
1970 priv->extra = NULL;
1971 priv->name = NULL;
1972 priv->name = NULL;
1973 priv->last_resume_step = 0;
1974 priv->last_resume_sig = GDB_SIGNAL_0;
1975 priv->vcont_resumed = 0;
f6327dcb 1976 priv->thread_handle = nullptr;
dc146f7c
VP
1977 }
1978
85ad3aaf
PA
1979 return thread->priv;
1980}
1981
1982/* Return PTID's private thread data, creating it if necessary. */
1983
1984static struct private_thread_info *
1985get_private_info_ptid (ptid_t ptid)
1986{
1987 struct thread_info *info = find_thread_ptid (ptid);
1988
1989 return get_private_info_thread (info);
dc146f7c
VP
1990}
1991
74531fed
PA
1992/* Call this function as a result of
1993 1) A halt indication (T packet) containing a thread id
1994 2) A direct query of currthread
0df8b418 1995 3) Successful execution of set thread */
74531fed
PA
1996
1997static void
47f8a51d 1998record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1999{
47f8a51d 2000 rs->general_thread = currthread;
74531fed
PA
2001}
2002
89be2091
DJ
2003/* If 'QPassSignals' is supported, tell the remote stub what signals
2004 it can simply pass through to the inferior without reporting. */
2005
2006static void
94bedb42
TT
2007remote_pass_signals (struct target_ops *self,
2008 int numsigs, unsigned char *pass_signals)
89be2091 2009{
4082afcc 2010 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2011 {
2012 char *pass_packet, *p;
89be2091 2013 int count = 0, i;
747dc59d 2014 struct remote_state *rs = get_remote_state ();
89be2091
DJ
2015
2016 gdb_assert (numsigs < 256);
2017 for (i = 0; i < numsigs; i++)
2018 {
2455069d 2019 if (pass_signals[i])
89be2091
DJ
2020 count++;
2021 }
224c3ddb 2022 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2023 strcpy (pass_packet, "QPassSignals:");
2024 p = pass_packet + strlen (pass_packet);
2025 for (i = 0; i < numsigs; i++)
2026 {
2455069d 2027 if (pass_signals[i])
89be2091
DJ
2028 {
2029 if (i >= 16)
2030 *p++ = tohex (i >> 4);
2031 *p++ = tohex (i & 15);
2032 if (count)
2033 *p++ = ';';
2034 else
2035 break;
2036 count--;
2037 }
2038 }
2039 *p = 0;
747dc59d 2040 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2041 {
89be2091
DJ
2042 putpkt (pass_packet);
2043 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2044 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2045 if (rs->last_pass_packet)
2046 xfree (rs->last_pass_packet);
2047 rs->last_pass_packet = pass_packet;
89be2091
DJ
2048 }
2049 else
2050 xfree (pass_packet);
2051 }
2052}
2053
82075af2
JS
2054/* If 'QCatchSyscalls' is supported, tell the remote stub
2055 to report syscalls to GDB. */
2056
2057static int
2058remote_set_syscall_catchpoint (struct target_ops *self,
2059 int pid, int needed, int any_count,
2060 int table_size, int *table)
2061{
2062 char *catch_packet;
2063 enum packet_result result;
2064 int n_sysno = 0;
2065
2066 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2067 {
2068 /* Not supported. */
2069 return 1;
2070 }
2071
2072 if (needed && !any_count)
2073 {
2074 int i;
2075
2076 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2077 for (i = 0; i < table_size; i++)
2078 {
2079 if (table[i] != 0)
2080 n_sysno++;
2081 }
2082 }
2083
2084 if (remote_debug)
2085 {
2086 fprintf_unfiltered (gdb_stdlog,
2087 "remote_set_syscall_catchpoint "
2088 "pid %d needed %d any_count %d n_sysno %d\n",
2089 pid, needed, any_count, n_sysno);
2090 }
2091
2092 if (needed)
2093 {
2094 /* Prepare a packet with the sysno list, assuming max 8+1
2095 characters for a sysno. If the resulting packet size is too
2096 big, fallback on the non-selective packet. */
2097 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2098
c0518081 2099 catch_packet = (char *) xmalloc (maxpktsz);
82075af2
JS
2100 strcpy (catch_packet, "QCatchSyscalls:1");
2101 if (!any_count)
2102 {
2103 int i;
2104 char *p;
2105
2106 p = catch_packet;
2107 p += strlen (p);
2108
2109 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2110 for (i = 0; i < table_size; i++)
2111 {
2112 if (table[i] != 0)
2113 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2114 }
2115 }
2116 if (strlen (catch_packet) > get_remote_packet_size ())
2117 {
2118 /* catch_packet too big. Fallback to less efficient
2119 non selective mode, with GDB doing the filtering. */
2120 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2121 }
2122 }
2123 else
2124 catch_packet = xstrdup ("QCatchSyscalls:0");
2125
2126 {
2127 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2128 struct remote_state *rs = get_remote_state ();
2129
2130 putpkt (catch_packet);
2131 getpkt (&rs->buf, &rs->buf_size, 0);
2132 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2133 do_cleanups (old_chain);
2134 if (result == PACKET_OK)
2135 return 0;
2136 else
2137 return -1;
2138 }
2139}
2140
9b224c5e
PA
2141/* If 'QProgramSignals' is supported, tell the remote stub what
2142 signals it should pass through to the inferior when detaching. */
2143
2144static void
daf5e9b6
TT
2145remote_program_signals (struct target_ops *self,
2146 int numsigs, unsigned char *signals)
9b224c5e 2147{
4082afcc 2148 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2149 {
2150 char *packet, *p;
2151 int count = 0, i;
5e4a05c4 2152 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2153
2154 gdb_assert (numsigs < 256);
2155 for (i = 0; i < numsigs; i++)
2156 {
2157 if (signals[i])
2158 count++;
2159 }
224c3ddb 2160 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2161 strcpy (packet, "QProgramSignals:");
2162 p = packet + strlen (packet);
2163 for (i = 0; i < numsigs; i++)
2164 {
2165 if (signal_pass_state (i))
2166 {
2167 if (i >= 16)
2168 *p++ = tohex (i >> 4);
2169 *p++ = tohex (i & 15);
2170 if (count)
2171 *p++ = ';';
2172 else
2173 break;
2174 count--;
2175 }
2176 }
2177 *p = 0;
5e4a05c4
TT
2178 if (!rs->last_program_signals_packet
2179 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2180 {
9b224c5e
PA
2181 putpkt (packet);
2182 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2183 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2184 xfree (rs->last_program_signals_packet);
2185 rs->last_program_signals_packet = packet;
9b224c5e
PA
2186 }
2187 else
2188 xfree (packet);
2189 }
2190}
2191
79d7f229
PA
2192/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2193 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2194 thread. If GEN is set, set the general thread, if not, then set
2195 the step/continue thread. */
c906108c 2196static void
d62a8ae2 2197set_thread (ptid_t ptid, int gen)
c906108c 2198{
d01949b6 2199 struct remote_state *rs = get_remote_state ();
47f8a51d 2200 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2201 char *buf = rs->buf;
79d7f229 2202 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2203
79d7f229 2204 if (ptid_equal (state, ptid))
c906108c
SS
2205 return;
2206
79d7f229
PA
2207 *buf++ = 'H';
2208 *buf++ = gen ? 'g' : 'c';
2209 if (ptid_equal (ptid, magic_null_ptid))
2210 xsnprintf (buf, endbuf - buf, "0");
2211 else if (ptid_equal (ptid, any_thread_ptid))
2212 xsnprintf (buf, endbuf - buf, "0");
2213 else if (ptid_equal (ptid, minus_one_ptid))
2214 xsnprintf (buf, endbuf - buf, "-1");
2215 else
82f73884 2216 write_ptid (buf, endbuf, ptid);
79d7f229 2217 putpkt (rs->buf);
6d820c5c 2218 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2219 if (gen)
47f8a51d 2220 rs->general_thread = ptid;
c906108c 2221 else
47f8a51d 2222 rs->continue_thread = ptid;
c906108c 2223}
79d7f229
PA
2224
2225static void
d62a8ae2 2226set_general_thread (ptid_t ptid)
79d7f229
PA
2227{
2228 set_thread (ptid, 1);
2229}
2230
2231static void
d62a8ae2 2232set_continue_thread (ptid_t ptid)
79d7f229
PA
2233{
2234 set_thread (ptid, 0);
2235}
2236
3c9c4b83
PA
2237/* Change the remote current process. Which thread within the process
2238 ends up selected isn't important, as long as it is the same process
2239 as what INFERIOR_PTID points to.
2240
2241 This comes from that fact that there is no explicit notion of
2242 "selected process" in the protocol. The selected process for
2243 general operations is the process the selected general thread
2244 belongs to. */
2245
2246static void
2247set_general_process (void)
2248{
2249 struct remote_state *rs = get_remote_state ();
2250
2251 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2252 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2253 return;
2254
2255 /* We only need to change the remote current thread if it's pointing
2256 at some other process. */
47f8a51d 2257 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2258 set_general_thread (inferior_ptid);
2259}
2260
c906108c 2261\f
7d1a114c
PA
2262/* Return nonzero if this is the main thread that we made up ourselves
2263 to model non-threaded targets as single-threaded. */
c906108c
SS
2264
2265static int
7d1a114c 2266remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2267{
c0a2216e
PA
2268 if (ptid_equal (ptid, magic_null_ptid))
2269 /* The main thread is always alive. */
2270 return 1;
2271
ba348170 2272 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2273 /* The main thread is always alive. This can happen after a
2274 vAttach, if the remote side doesn't support
2275 multi-threading. */
2276 return 1;
2277
7d1a114c
PA
2278 return 0;
2279}
2280
2281/* Return nonzero if the thread PTID is still alive on the remote
2282 system. */
2283
2284static int
2285remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2286{
2287 struct remote_state *rs = get_remote_state ();
2288 char *p, *endp;
2289
2290 /* Check if this is a thread that we made up ourselves to model
2291 non-threaded targets as single-threaded. */
2292 if (remote_thread_always_alive (ops, ptid))
2293 return 1;
2294
82f73884
PA
2295 p = rs->buf;
2296 endp = rs->buf + get_remote_packet_size ();
2297
2298 *p++ = 'T';
2299 write_ptid (p, endp, ptid);
2300
2e9f7625 2301 putpkt (rs->buf);
6d820c5c 2302 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2303 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2304}
2305
79efa585
SM
2306/* Return a pointer to a thread name if we know it and NULL otherwise.
2307 The thread_info object owns the memory for the name. */
2308
2309static const char *
2310remote_thread_name (struct target_ops *ops, struct thread_info *info)
2311{
2312 if (info->priv != NULL)
2313 return info->priv->name;
2314
2315 return NULL;
2316}
2317
c906108c
SS
2318/* About these extended threadlist and threadinfo packets. They are
2319 variable length packets but, the fields within them are often fixed
2320 length. They are redundent enough to send over UDP as is the
2321 remote protocol in general. There is a matching unit test module
2322 in libstub. */
2323
23860348 2324/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2325 libstub protocol encoding, and remote.c. It is not particularly
23860348 2326 changable. */
cce74817
JM
2327
2328/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2329 Plan to fix this. */
cce74817 2330
23860348 2331typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2332
9d1f7ab2 2333/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2334 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2335
2336struct gdb_ext_thread_info
c5aa993b 2337 {
23860348 2338 threadref threadid; /* External form of thread reference. */
2bc416ba 2339 int active; /* Has state interesting to GDB?
23860348 2340 regs, stack. */
2bc416ba 2341 char display[256]; /* Brief state display, name,
cedea757 2342 blocked/suspended. */
23860348 2343 char shortname[32]; /* To be used to name threads. */
2bc416ba 2344 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2345 whatever. */
c5aa993b 2346 };
cce74817
JM
2347
2348/* The volume of remote transfers can be limited by submitting
2349 a mask containing bits specifying the desired information.
2350 Use a union of these values as the 'selection' parameter to
0df8b418 2351 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2352
2353#define TAG_THREADID 1
2354#define TAG_EXISTS 2
2355#define TAG_DISPLAY 4
2356#define TAG_THREADNAME 8
c5aa993b 2357#define TAG_MOREDISPLAY 16
cce74817 2358
23860348 2359#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2360
a14ed312 2361static char *unpack_nibble (char *buf, int *val);
cce74817 2362
a14ed312 2363static char *unpack_byte (char *buf, int *value);
cce74817 2364
a14ed312 2365static char *pack_int (char *buf, int value);
cce74817 2366
a14ed312 2367static char *unpack_int (char *buf, int *value);
cce74817 2368
a14ed312 2369static char *unpack_string (char *src, char *dest, int length);
cce74817 2370
23860348 2371static char *pack_threadid (char *pkt, threadref *id);
cce74817 2372
23860348 2373static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2374
23860348 2375void int_to_threadref (threadref *id, int value);
cce74817 2376
23860348 2377static int threadref_to_int (threadref *ref);
cce74817 2378
23860348 2379static void copy_threadref (threadref *dest, threadref *src);
cce74817 2380
23860348 2381static int threadmatch (threadref *dest, threadref *src);
cce74817 2382
2bc416ba 2383static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2384 threadref *id);
cce74817 2385
a14ed312 2386static int remote_unpack_thread_info_response (char *pkt,
23860348 2387 threadref *expectedref,
a14ed312
KB
2388 struct gdb_ext_thread_info
2389 *info);
cce74817
JM
2390
2391
2bc416ba 2392static int remote_get_threadinfo (threadref *threadid,
23860348 2393 int fieldset, /*TAG mask */
a14ed312 2394 struct gdb_ext_thread_info *info);
cce74817 2395
a14ed312
KB
2396static char *pack_threadlist_request (char *pkt, int startflag,
2397 int threadcount,
23860348 2398 threadref *nextthread);
cce74817 2399
a14ed312
KB
2400static int parse_threadlist_response (char *pkt,
2401 int result_limit,
23860348 2402 threadref *original_echo,
2bc416ba 2403 threadref *resultlist,
23860348 2404 int *doneflag);
cce74817 2405
a14ed312 2406static int remote_get_threadlist (int startflag,
23860348 2407 threadref *nextthread,
a14ed312
KB
2408 int result_limit,
2409 int *done,
2bc416ba 2410 int *result_count,
23860348 2411 threadref *threadlist);
cce74817 2412
23860348 2413typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2414
a14ed312
KB
2415static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2416 void *context, int looplimit);
cce74817 2417
23860348 2418static int remote_newthread_step (threadref *ref, void *context);
cce74817 2419
82f73884
PA
2420
2421/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2422 buffer we're allowed to write to. Returns
2423 BUF+CHARACTERS_WRITTEN. */
2424
2425static char *
2426write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2427{
2428 int pid, tid;
2429 struct remote_state *rs = get_remote_state ();
2430
2431 if (remote_multi_process_p (rs))
2432 {
2433 pid = ptid_get_pid (ptid);
2434 if (pid < 0)
2435 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2436 else
2437 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2438 }
ba348170 2439 tid = ptid_get_lwp (ptid);
82f73884
PA
2440 if (tid < 0)
2441 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2442 else
2443 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2444
2445 return buf;
2446}
2447
256642e8
PA
2448/* Extract a PTID from BUF. If non-null, OBUF is set to one past the
2449 last parsed char. Returns null_ptid if no thread id is found, and
2450 throws an error if the thread id has an invalid format. */
82f73884
PA
2451
2452static ptid_t
256642e8 2453read_ptid (const char *buf, const char **obuf)
82f73884 2454{
256642e8
PA
2455 const char *p = buf;
2456 const char *pp;
82f73884 2457 ULONGEST pid = 0, tid = 0;
82f73884
PA
2458
2459 if (*p == 'p')
2460 {
2461 /* Multi-process ptid. */
2462 pp = unpack_varlen_hex (p + 1, &pid);
2463 if (*pp != '.')
b37520b6 2464 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2465
2466 p = pp;
2467 pp = unpack_varlen_hex (p + 1, &tid);
2468 if (obuf)
2469 *obuf = pp;
ba348170 2470 return ptid_build (pid, tid, 0);
82f73884
PA
2471 }
2472
2473 /* No multi-process. Just a tid. */
2474 pp = unpack_varlen_hex (p, &tid);
2475
c9f35b34
KB
2476 /* Return null_ptid when no thread id is found. */
2477 if (p == pp)
2478 {
2479 if (obuf)
2480 *obuf = pp;
2481 return null_ptid;
2482 }
2483
82f73884 2484 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2485 what's in inferior_ptid, unless it's null at this point. If so,
2486 then since there's no way to know the pid of the reported
2487 threads, use the magic number. */
2488 if (ptid_equal (inferior_ptid, null_ptid))
2489 pid = ptid_get_pid (magic_null_ptid);
2490 else
2491 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2492
2493 if (obuf)
2494 *obuf = pp;
ba348170 2495 return ptid_build (pid, tid, 0);
82f73884
PA
2496}
2497
c906108c 2498static int
fba45db2 2499stubhex (int ch)
c906108c
SS
2500{
2501 if (ch >= 'a' && ch <= 'f')
2502 return ch - 'a' + 10;
2503 if (ch >= '0' && ch <= '9')
2504 return ch - '0';
2505 if (ch >= 'A' && ch <= 'F')
2506 return ch - 'A' + 10;
2507 return -1;
2508}
2509
2510static int
fba45db2 2511stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2512{
2513 int nibble;
2514 int retval = 0;
2515
2516 while (fieldlength)
2517 {
2518 nibble = stubhex (*buff++);
2519 retval |= nibble;
2520 fieldlength--;
2521 if (fieldlength)
2522 retval = retval << 4;
2523 }
2524 return retval;
2525}
2526
c906108c 2527static char *
fba45db2 2528unpack_nibble (char *buf, int *val)
c906108c 2529{
b7589f7d 2530 *val = fromhex (*buf++);
c906108c
SS
2531 return buf;
2532}
2533
c906108c 2534static char *
fba45db2 2535unpack_byte (char *buf, int *value)
c906108c
SS
2536{
2537 *value = stub_unpack_int (buf, 2);
2538 return buf + 2;
2539}
2540
2541static char *
fba45db2 2542pack_int (char *buf, int value)
c906108c
SS
2543{
2544 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2545 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2546 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2547 buf = pack_hex_byte (buf, (value & 0xff));
2548 return buf;
2549}
2550
2551static char *
fba45db2 2552unpack_int (char *buf, int *value)
c906108c
SS
2553{
2554 *value = stub_unpack_int (buf, 8);
2555 return buf + 8;
2556}
2557
23860348 2558#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2559static char *pack_string (char *pkt, char *string);
c906108c
SS
2560
2561static char *
fba45db2 2562pack_string (char *pkt, char *string)
c906108c
SS
2563{
2564 char ch;
2565 int len;
2566
2567 len = strlen (string);
2568 if (len > 200)
23860348 2569 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2570 pkt = pack_hex_byte (pkt, len);
2571 while (len-- > 0)
2572 {
2573 ch = *string++;
2574 if ((ch == '\0') || (ch == '#'))
23860348 2575 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2576 *pkt++ = ch;
2577 }
2578 return pkt;
2579}
2580#endif /* 0 (unused) */
2581
2582static char *
fba45db2 2583unpack_string (char *src, char *dest, int length)
c906108c
SS
2584{
2585 while (length--)
2586 *dest++ = *src++;
2587 *dest = '\0';
2588 return src;
2589}
2590
2591static char *
fba45db2 2592pack_threadid (char *pkt, threadref *id)
c906108c
SS
2593{
2594 char *limit;
2595 unsigned char *altid;
2596
2597 altid = (unsigned char *) id;
2598 limit = pkt + BUF_THREAD_ID_SIZE;
2599 while (pkt < limit)
2600 pkt = pack_hex_byte (pkt, *altid++);
2601 return pkt;
2602}
2603
2604
2605static char *
fba45db2 2606unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2607{
2608 char *altref;
2609 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2610 int x, y;
2611
2612 altref = (char *) id;
2613
2614 while (inbuf < limit)
2615 {
2616 x = stubhex (*inbuf++);
2617 y = stubhex (*inbuf++);
2618 *altref++ = (x << 4) | y;
2619 }
2620 return inbuf;
2621}
2622
2623/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2624 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2625 to use 64bit thread references internally. This is an adapter
2626 function. */
2627
2628void
fba45db2 2629int_to_threadref (threadref *id, int value)
c906108c
SS
2630{
2631 unsigned char *scan;
2632
2633 scan = (unsigned char *) id;
2634 {
2635 int i = 4;
2636 while (i--)
2637 *scan++ = 0;
2638 }
2639 *scan++ = (value >> 24) & 0xff;
2640 *scan++ = (value >> 16) & 0xff;
2641 *scan++ = (value >> 8) & 0xff;
2642 *scan++ = (value & 0xff);
2643}
2644
2645static int
fba45db2 2646threadref_to_int (threadref *ref)
c906108c
SS
2647{
2648 int i, value = 0;
2649 unsigned char *scan;
2650
cfd77fa1 2651 scan = *ref;
c906108c
SS
2652 scan += 4;
2653 i = 4;
2654 while (i-- > 0)
2655 value = (value << 8) | ((*scan++) & 0xff);
2656 return value;
2657}
2658
2659static void
fba45db2 2660copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2661{
2662 int i;
2663 unsigned char *csrc, *cdest;
2664
2665 csrc = (unsigned char *) src;
2666 cdest = (unsigned char *) dest;
2667 i = 8;
2668 while (i--)
2669 *cdest++ = *csrc++;
2670}
2671
2672static int
fba45db2 2673threadmatch (threadref *dest, threadref *src)
c906108c 2674{
23860348 2675 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2676#if 0
2677 unsigned char *srcp, *destp;
2678 int i, result;
2679 srcp = (char *) src;
2680 destp = (char *) dest;
2681
2682 result = 1;
2683 while (i-- > 0)
2684 result &= (*srcp++ == *destp++) ? 1 : 0;
2685 return result;
2686#endif
2687 return 1;
2688}
2689
2690/*
c5aa993b
JM
2691 threadid:1, # always request threadid
2692 context_exists:2,
2693 display:4,
2694 unique_name:8,
2695 more_display:16
2696 */
c906108c
SS
2697
2698/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2699
2700static char *
fba45db2 2701pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2702{
23860348
MS
2703 *pkt++ = 'q'; /* Info Query */
2704 *pkt++ = 'P'; /* process or thread info */
2705 pkt = pack_int (pkt, mode); /* mode */
c906108c 2706 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2707 *pkt = '\0'; /* terminate */
c906108c
SS
2708 return pkt;
2709}
2710
23860348 2711/* These values tag the fields in a thread info response packet. */
c906108c 2712/* Tagging the fields allows us to request specific fields and to
23860348 2713 add more fields as time goes by. */
c906108c 2714
23860348 2715#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2716#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2717 fetch registers and its stack? */
c5aa993b 2718#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2719#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2720#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2721 the process. */
c906108c
SS
2722
2723static int
fba45db2
KB
2724remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2725 struct gdb_ext_thread_info *info)
c906108c 2726{
d01949b6 2727 struct remote_state *rs = get_remote_state ();
c906108c 2728 int mask, length;
cfd77fa1 2729 int tag;
c906108c 2730 threadref ref;
6d820c5c 2731 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2732 int retval = 1;
2733
23860348 2734 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2735 info->active = 0;
2736 info->display[0] = '\0';
2737 info->shortname[0] = '\0';
2738 info->more_display[0] = '\0';
2739
23860348
MS
2740 /* Assume the characters indicating the packet type have been
2741 stripped. */
c906108c
SS
2742 pkt = unpack_int (pkt, &mask); /* arg mask */
2743 pkt = unpack_threadid (pkt, &ref);
2744
2745 if (mask == 0)
8a3fe4f8 2746 warning (_("Incomplete response to threadinfo request."));
c906108c 2747 if (!threadmatch (&ref, expectedref))
23860348 2748 { /* This is an answer to a different request. */
8a3fe4f8 2749 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2750 return 0;
2751 }
2752 copy_threadref (&info->threadid, &ref);
2753
23860348 2754 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2755
23860348
MS
2756 /* Packets are terminated with nulls. */
2757 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2758 {
2759 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2760 pkt = unpack_byte (pkt, &length); /* length */
2761 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2762 {
8a3fe4f8 2763 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2764 retval = 0;
2765 break;
2766 }
2767 if (tag == TAG_THREADID)
2768 {
2769 if (length != 16)
2770 {
8a3fe4f8 2771 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2772 retval = 0;
2773 break;
2774 }
2775 pkt = unpack_threadid (pkt, &ref);
2776 mask = mask & ~TAG_THREADID;
2777 continue;
2778 }
2779 if (tag == TAG_EXISTS)
2780 {
2781 info->active = stub_unpack_int (pkt, length);
2782 pkt += length;
2783 mask = mask & ~(TAG_EXISTS);
2784 if (length > 8)
2785 {
8a3fe4f8 2786 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2787 retval = 0;
2788 break;
2789 }
2790 continue;
2791 }
2792 if (tag == TAG_THREADNAME)
2793 {
2794 pkt = unpack_string (pkt, &info->shortname[0], length);
2795 mask = mask & ~TAG_THREADNAME;
2796 continue;
2797 }
2798 if (tag == TAG_DISPLAY)
2799 {
2800 pkt = unpack_string (pkt, &info->display[0], length);
2801 mask = mask & ~TAG_DISPLAY;
2802 continue;
2803 }
2804 if (tag == TAG_MOREDISPLAY)
2805 {
2806 pkt = unpack_string (pkt, &info->more_display[0], length);
2807 mask = mask & ~TAG_MOREDISPLAY;
2808 continue;
2809 }
8a3fe4f8 2810 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2811 break; /* Not a tag we know about. */
c906108c
SS
2812 }
2813 return retval;
2814}
2815
2816static int
fba45db2
KB
2817remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2818 struct gdb_ext_thread_info *info)
c906108c 2819{
d01949b6 2820 struct remote_state *rs = get_remote_state ();
c906108c 2821 int result;
c906108c 2822
2e9f7625
DJ
2823 pack_threadinfo_request (rs->buf, fieldset, threadid);
2824 putpkt (rs->buf);
6d820c5c 2825 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2826
2827 if (rs->buf[0] == '\0')
2828 return 0;
2829
2e9f7625 2830 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2831 threadid, info);
c906108c
SS
2832 return result;
2833}
2834
c906108c
SS
2835/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2836
2837static char *
fba45db2
KB
2838pack_threadlist_request (char *pkt, int startflag, int threadcount,
2839 threadref *nextthread)
c906108c
SS
2840{
2841 *pkt++ = 'q'; /* info query packet */
2842 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2843 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2844 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2845 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2846 *pkt = '\0';
2847 return pkt;
2848}
2849
2850/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2851
2852static int
fba45db2
KB
2853parse_threadlist_response (char *pkt, int result_limit,
2854 threadref *original_echo, threadref *resultlist,
2855 int *doneflag)
c906108c 2856{
d01949b6 2857 struct remote_state *rs = get_remote_state ();
c906108c
SS
2858 char *limit;
2859 int count, resultcount, done;
2860
2861 resultcount = 0;
2862 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2863 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2864 /* done parse past here */
c906108c
SS
2865 pkt = unpack_byte (pkt, &count); /* count field */
2866 pkt = unpack_nibble (pkt, &done);
2867 /* The first threadid is the argument threadid. */
2868 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2869 while ((count-- > 0) && (pkt < limit))
2870 {
2871 pkt = unpack_threadid (pkt, resultlist++);
2872 if (resultcount++ >= result_limit)
2873 break;
2874 }
2875 if (doneflag)
2876 *doneflag = done;
2877 return resultcount;
2878}
2879
6dc54d91
PA
2880/* Fetch the next batch of threads from the remote. Returns -1 if the
2881 qL packet is not supported, 0 on error and 1 on success. */
2882
c906108c 2883static int
fba45db2
KB
2884remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2885 int *done, int *result_count, threadref *threadlist)
c906108c 2886{
d01949b6 2887 struct remote_state *rs = get_remote_state ();
c906108c
SS
2888 int result = 1;
2889
23860348 2890 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2891 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2892 >= get_remote_packet_size ())
ea9c271d 2893 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2894
6d820c5c
DJ
2895 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2896 putpkt (rs->buf);
2897 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2898 if (*rs->buf == '\0')
6dc54d91
PA
2899 {
2900 /* Packet not supported. */
2901 return -1;
2902 }
2903
2904 *result_count =
2905 parse_threadlist_response (rs->buf + 2, result_limit,
2906 &rs->echo_nextthread, threadlist, done);
c906108c 2907
0d031856 2908 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2909 {
23860348
MS
2910 /* FIXME: This is a good reason to drop the packet. */
2911 /* Possably, there is a duplicate response. */
c906108c
SS
2912 /* Possabilities :
2913 retransmit immediatly - race conditions
2914 retransmit after timeout - yes
2915 exit
2916 wait for packet, then exit
2917 */
8a3fe4f8 2918 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2919 return 0; /* I choose simply exiting. */
c906108c
SS
2920 }
2921 if (*result_count <= 0)
2922 {
2923 if (*done != 1)
2924 {
8a3fe4f8 2925 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2926 result = 0;
2927 }
2928 return result; /* break; */
2929 }
2930 if (*result_count > result_limit)
2931 {
2932 *result_count = 0;
8a3fe4f8 2933 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2934 return 0;
2935 }
2936 return result;
2937}
2938
6dc54d91
PA
2939/* Fetch the list of remote threads, with the qL packet, and call
2940 STEPFUNCTION for each thread found. Stops iterating and returns 1
2941 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2942 STEPFUNCTION returns false. If the packet is not supported,
2943 returns -1. */
c906108c 2944
c906108c 2945static int
fba45db2
KB
2946remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2947 int looplimit)
c906108c 2948{
0d031856 2949 struct remote_state *rs = get_remote_state ();
c906108c
SS
2950 int done, i, result_count;
2951 int startflag = 1;
2952 int result = 1;
2953 int loopcount = 0;
c906108c
SS
2954
2955 done = 0;
2956 while (!done)
2957 {
2958 if (loopcount++ > looplimit)
2959 {
2960 result = 0;
8a3fe4f8 2961 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2962 break;
2963 }
6dc54d91
PA
2964 result = remote_get_threadlist (startflag, &rs->nextthread,
2965 MAXTHREADLISTRESULTS,
2966 &done, &result_count,
2967 rs->resultthreadlist);
2968 if (result <= 0)
2969 break;
23860348 2970 /* Clear for later iterations. */
c906108c
SS
2971 startflag = 0;
2972 /* Setup to resume next batch of thread references, set nextthread. */
2973 if (result_count >= 1)
0d031856
TT
2974 copy_threadref (&rs->nextthread,
2975 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2976 i = 0;
2977 while (result_count--)
6dc54d91
PA
2978 {
2979 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2980 {
2981 result = 0;
2982 break;
2983 }
2984 }
c906108c
SS
2985 }
2986 return result;
2987}
2988
6dc54d91
PA
2989/* A thread found on the remote target. */
2990
2991typedef struct thread_item
2992{
2993 /* The thread's PTID. */
2994 ptid_t ptid;
2995
2996 /* The thread's extra info. May be NULL. */
2997 char *extra;
2998
79efa585
SM
2999 /* The thread's name. May be NULL. */
3000 char *name;
3001
6dc54d91
PA
3002 /* The core the thread was running on. -1 if not known. */
3003 int core;
f6327dcb
KB
3004
3005 /* The thread handle associated with the thread. */
3006 gdb::byte_vector *thread_handle;
3007
6dc54d91
PA
3008} thread_item_t;
3009DEF_VEC_O(thread_item_t);
3010
3011/* Context passed around to the various methods listing remote
3012 threads. As new threads are found, they're added to the ITEMS
3013 vector. */
3014
3015struct threads_listing_context
3016{
3017 /* The threads found on the remote target. */
3018 VEC (thread_item_t) *items;
3019};
3020
80134cf5
PA
3021/* Discard the contents of the constructed thread listing context. */
3022
3023static void
3024clear_threads_listing_context (void *p)
3025{
19ba03f4
SM
3026 struct threads_listing_context *context
3027 = (struct threads_listing_context *) p;
80134cf5
PA
3028 int i;
3029 struct thread_item *item;
3030
3031 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
3032 {
3033 xfree (item->extra);
3034 xfree (item->name);
f6327dcb 3035 delete item->thread_handle;
79efa585 3036 }
80134cf5
PA
3037
3038 VEC_free (thread_item_t, context->items);
3039}
3040
cbb8991c
DB
3041/* Remove the thread specified as the related_pid field of WS
3042 from the CONTEXT list. */
3043
3044static void
3045threads_listing_context_remove (struct target_waitstatus *ws,
3046 struct threads_listing_context *context)
3047{
3048 struct thread_item *item;
3049 int i;
3050 ptid_t child_ptid = ws->value.related_pid;
3051
3052 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3053 {
3054 if (ptid_equal (item->ptid, child_ptid))
3055 {
3056 VEC_ordered_remove (thread_item_t, context->items, i);
3057 break;
3058 }
3059 }
3060}
3061
c906108c 3062static int
6dc54d91 3063remote_newthread_step (threadref *ref, void *data)
c906108c 3064{
19ba03f4
SM
3065 struct threads_listing_context *context
3066 = (struct threads_listing_context *) data;
6dc54d91 3067 struct thread_item item;
79d7f229 3068 int pid = ptid_get_pid (inferior_ptid);
39f77062 3069
6dc54d91
PA
3070 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3071 item.core = -1;
2e3b657e 3072 item.name = NULL;
6dc54d91 3073 item.extra = NULL;
f6327dcb 3074 item.thread_handle = nullptr;
6dc54d91
PA
3075
3076 VEC_safe_push (thread_item_t, context->items, &item);
3077
c906108c
SS
3078 return 1; /* continue iterator */
3079}
3080
3081#define CRAZY_MAX_THREADS 1000
3082
39f77062
KB
3083static ptid_t
3084remote_current_thread (ptid_t oldpid)
c906108c 3085{
d01949b6 3086 struct remote_state *rs = get_remote_state ();
c906108c
SS
3087
3088 putpkt ("qC");
6d820c5c 3089 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3090 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34 3091 {
256642e8 3092 const char *obuf;
c9f35b34
KB
3093 ptid_t result;
3094
3095 result = read_ptid (&rs->buf[2], &obuf);
3096 if (*obuf != '\0' && remote_debug)
3097 fprintf_unfiltered (gdb_stdlog,
3098 "warning: garbage in qC reply\n");
3099
3100 return result;
3101 }
c906108c
SS
3102 else
3103 return oldpid;
3104}
3105
6dc54d91 3106/* List remote threads using the deprecated qL packet. */
cce74817 3107
6dc54d91
PA
3108static int
3109remote_get_threads_with_ql (struct target_ops *ops,
3110 struct threads_listing_context *context)
c906108c 3111{
6dc54d91
PA
3112 if (remote_threadlist_iterator (remote_newthread_step, context,
3113 CRAZY_MAX_THREADS) >= 0)
3114 return 1;
3115
3116 return 0;
c906108c
SS
3117}
3118
dc146f7c
VP
3119#if defined(HAVE_LIBEXPAT)
3120
dc146f7c
VP
3121static void
3122start_thread (struct gdb_xml_parser *parser,
3123 const struct gdb_xml_element *element,
3124 void *user_data, VEC(gdb_xml_value_s) *attributes)
3125{
19ba03f4
SM
3126 struct threads_listing_context *data
3127 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3128
3129 struct thread_item item;
3130 char *id;
3d2c1d41 3131 struct gdb_xml_value *attr;
dc146f7c 3132
19ba03f4 3133 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
3134 item.ptid = read_ptid (id, NULL);
3135
3d2c1d41
PA
3136 attr = xml_find_attribute (attributes, "core");
3137 if (attr != NULL)
3138 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
3139 else
3140 item.core = -1;
3141
79efa585 3142 attr = xml_find_attribute (attributes, "name");
e1961661 3143 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 3144
f6327dcb
KB
3145 attr = xml_find_attribute (attributes, "handle");
3146 if (attr != NULL)
3147 {
3148 item.thread_handle = new gdb::byte_vector
3149 (strlen ((const char *) attr->value) / 2);
3150 hex2bin ((const char *) attr->value, item.thread_handle->data (),
3151 item.thread_handle->size ());
3152 }
3153 else
3154 item.thread_handle = nullptr;
3155
dc146f7c
VP
3156 item.extra = 0;
3157
3158 VEC_safe_push (thread_item_t, data->items, &item);
3159}
3160
3161static void
3162end_thread (struct gdb_xml_parser *parser,
3163 const struct gdb_xml_element *element,
3164 void *user_data, const char *body_text)
3165{
19ba03f4
SM
3166 struct threads_listing_context *data
3167 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3168
3169 if (body_text && *body_text)
2ae2a0b7 3170 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3171}
3172
3173const struct gdb_xml_attribute thread_attributes[] = {
3174 { "id", GDB_XML_AF_NONE, NULL, NULL },
3175 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3176 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
f6327dcb 3177 { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3178 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3179};
3180
3181const struct gdb_xml_element thread_children[] = {
3182 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3183};
3184
3185const struct gdb_xml_element threads_children[] = {
3186 { "thread", thread_attributes, thread_children,
3187 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3188 start_thread, end_thread },
3189 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3190};
3191
3192const struct gdb_xml_element threads_elements[] = {
3193 { "threads", NULL, threads_children,
3194 GDB_XML_EF_NONE, NULL, NULL },
3195 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3196};
3197
3198#endif
3199
6dc54d91 3200/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3201
6dc54d91
PA
3202static int
3203remote_get_threads_with_qxfer (struct target_ops *ops,
3204 struct threads_listing_context *context)
0f71a2f6 3205{
dc146f7c 3206#if defined(HAVE_LIBEXPAT)
4082afcc 3207 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3208 {
6dc54d91 3209 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3210 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3211
6dc54d91 3212 if (xml != NULL && *xml != '\0')
dc146f7c 3213 {
6dc54d91
PA
3214 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3215 threads_elements, xml, context);
dc146f7c
VP
3216 }
3217
3218 do_cleanups (back_to);
6dc54d91 3219 return 1;
dc146f7c
VP
3220 }
3221#endif
3222
6dc54d91
PA
3223 return 0;
3224}
3225
3226/* List remote threads using qfThreadInfo/qsThreadInfo. */
3227
3228static int
3229remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3230 struct threads_listing_context *context)
3231{
3232 struct remote_state *rs = get_remote_state ();
3233
b80fafe3 3234 if (rs->use_threadinfo_query)
9d1f7ab2 3235 {
256642e8 3236 const char *bufp;
6dc54d91 3237
9d1f7ab2 3238 putpkt ("qfThreadInfo");
6d820c5c 3239 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3240 bufp = rs->buf;
9d1f7ab2 3241 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3242 {
9d1f7ab2
MS
3243 while (*bufp++ == 'm') /* reply contains one or more TID */
3244 {
3245 do
3246 {
6dc54d91
PA
3247 struct thread_item item;
3248
3249 item.ptid = read_ptid (bufp, &bufp);
3250 item.core = -1;
2e3b657e 3251 item.name = NULL;
6dc54d91 3252 item.extra = NULL;
f6327dcb 3253 item.thread_handle = nullptr;
6dc54d91
PA
3254
3255 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3256 }
3257 while (*bufp++ == ','); /* comma-separated list */
3258 putpkt ("qsThreadInfo");
6d820c5c 3259 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3260 bufp = rs->buf;
9d1f7ab2 3261 }
6dc54d91
PA
3262 return 1;
3263 }
3264 else
3265 {
3266 /* Packet not recognized. */
3267 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3268 }
3269 }
3270
6dc54d91
PA
3271 return 0;
3272}
3273
e8032dde 3274/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3275 targets. */
3276
3277static void
e8032dde 3278remote_update_thread_list (struct target_ops *ops)
6dc54d91 3279{
6dc54d91
PA
3280 struct threads_listing_context context;
3281 struct cleanup *old_chain;
ab970af1 3282 int got_list = 0;
e8032dde 3283
6dc54d91
PA
3284 context.items = NULL;
3285 old_chain = make_cleanup (clear_threads_listing_context, &context);
3286
3287 /* We have a few different mechanisms to fetch the thread list. Try
3288 them all, starting with the most preferred one first, falling
3289 back to older methods. */
3290 if (remote_get_threads_with_qxfer (ops, &context)
3291 || remote_get_threads_with_qthreadinfo (ops, &context)
3292 || remote_get_threads_with_ql (ops, &context))
3293 {
3294 int i;
3295 struct thread_item *item;
ab970af1
PA
3296 struct thread_info *tp, *tmp;
3297
3298 got_list = 1;
3299
7d1a114c
PA
3300 if (VEC_empty (thread_item_t, context.items)
3301 && remote_thread_always_alive (ops, inferior_ptid))
3302 {
3303 /* Some targets don't really support threads, but still
3304 reply an (empty) thread list in response to the thread
3305 listing packets, instead of replying "packet not
3306 supported". Exit early so we don't delete the main
3307 thread. */
3308 do_cleanups (old_chain);
3309 return;
3310 }
3311
ab970af1
PA
3312 /* CONTEXT now holds the current thread list on the remote
3313 target end. Delete GDB-side threads no longer found on the
3314 target. */
8a06aea7 3315 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3316 {
ab970af1
PA
3317 for (i = 0;
3318 VEC_iterate (thread_item_t, context.items, i, item);
3319 ++i)
3320 {
3321 if (ptid_equal (item->ptid, tp->ptid))
3322 break;
3323 }
3324
3325 if (i == VEC_length (thread_item_t, context.items))
3326 {
3327 /* Not found. */
3328 delete_thread (tp->ptid);
3329 }
cbb8991c
DB
3330 }
3331
3332 /* Remove any unreported fork child threads from CONTEXT so
3333 that we don't interfere with follow fork, which is where
3334 creation of such threads is handled. */
3335 remove_new_fork_children (&context);
74531fed 3336
ab970af1 3337 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3338 for (i = 0;
3339 VEC_iterate (thread_item_t, context.items, i, item);
3340 ++i)
3341 {
3342 if (!ptid_equal (item->ptid, null_ptid))
3343 {
3344 struct private_thread_info *info;
3345 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3346 executing until proven otherwise with a stop reply.
3347 In all-stop, we can only get here if all threads are
6dc54d91 3348 stopped. */
0d5b594f 3349 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3350
0d5b594f 3351 remote_notice_new_inferior (item->ptid, executing);
6dc54d91 3352
85ad3aaf 3353 info = get_private_info_ptid (item->ptid);
6dc54d91
PA
3354 info->core = item->core;
3355 info->extra = item->extra;
3356 item->extra = NULL;
79efa585
SM
3357 info->name = item->name;
3358 item->name = NULL;
f6327dcb
KB
3359 info->thread_handle = item->thread_handle;
3360 item->thread_handle = nullptr;
6dc54d91
PA
3361 }
3362 }
3363 }
3364
ab970af1
PA
3365 if (!got_list)
3366 {
3367 /* If no thread listing method is supported, then query whether
3368 each known thread is alive, one by one, with the T packet.
3369 If the target doesn't support threads at all, then this is a
3370 no-op. See remote_thread_alive. */
3371 prune_threads ();
3372 }
3373
6dc54d91 3374 do_cleanups (old_chain);
9d1f7ab2
MS
3375}
3376
802188a7 3377/*
9d1f7ab2
MS
3378 * Collect a descriptive string about the given thread.
3379 * The target may say anything it wants to about the thread
3380 * (typically info about its blocked / runnable state, name, etc.).
3381 * This string will appear in the info threads display.
802188a7 3382 *
9d1f7ab2
MS
3383 * Optional: targets are not required to implement this function.
3384 */
3385
7a114964 3386static const char *
c15906d8 3387remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3388{
d01949b6 3389 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3390 int result;
3391 int set;
3392 threadref id;
3393 struct gdb_ext_thread_info threadinfo;
23860348 3394 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3395 int n = 0; /* position in display_buf */
3396
5d93a237 3397 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3398 internal_error (__FILE__, __LINE__,
e2e0b3e5 3399 _("remote_threads_extra_info"));
9d1f7ab2 3400
60e569b9 3401 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3402 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3403 /* This is the main thread which was added by GDB. The remote
3404 server doesn't know about it. */
3405 return NULL;
3406
4082afcc 3407 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3408 {
3409 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3410
fe978cb0
PA
3411 if (info && info->priv)
3412 return info->priv->extra;
dc146f7c
VP
3413 else
3414 return NULL;
3415 }
3416
b80fafe3 3417 if (rs->use_threadextra_query)
9d1f7ab2 3418 {
82f73884
PA
3419 char *b = rs->buf;
3420 char *endb = rs->buf + get_remote_packet_size ();
3421
3422 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3423 b += strlen (b);
3424 write_ptid (b, endb, tp->ptid);
3425
2e9f7625 3426 putpkt (rs->buf);
6d820c5c 3427 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3428 if (rs->buf[0] != 0)
9d1f7ab2 3429 {
325fac50 3430 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
2e9f7625 3431 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3432 display_buf [result] = '\0';
9d1f7ab2
MS
3433 return display_buf;
3434 }
0f71a2f6 3435 }
9d1f7ab2
MS
3436
3437 /* If the above query fails, fall back to the old method. */
b80fafe3 3438 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3439 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3440 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3441 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3442 if (remote_get_threadinfo (&id, set, &threadinfo))
3443 if (threadinfo.active)
0f71a2f6 3444 {
9d1f7ab2 3445 if (*threadinfo.shortname)
2bc416ba 3446 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3447 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3448 if (*threadinfo.display)
2bc416ba 3449 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3450 " State: %s,", threadinfo.display);
9d1f7ab2 3451 if (*threadinfo.more_display)
2bc416ba 3452 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3453 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3454
3455 if (n > 0)
c5aa993b 3456 {
23860348 3457 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3458 if (',' == display_buf[n-1])
3459 display_buf[n-1] = ' ';
3460 return display_buf;
c5aa993b 3461 }
0f71a2f6 3462 }
9d1f7ab2 3463 return NULL;
0f71a2f6 3464}
c906108c 3465\f
c5aa993b 3466
0fb4aa4b 3467static int
61fc905d 3468remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3469 struct static_tracepoint_marker *marker)
3470{
3471 struct remote_state *rs = get_remote_state ();
3472 char *p = rs->buf;
3473
bba74b36 3474 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3475 p += strlen (p);
3476 p += hexnumstr (p, addr);
3477 putpkt (rs->buf);
3478 getpkt (&rs->buf, &rs->buf_size, 0);
3479 p = rs->buf;
3480
3481 if (*p == 'E')
3482 error (_("Remote failure reply: %s"), p);
3483
3484 if (*p++ == 'm')
3485 {
256642e8 3486 parse_static_tracepoint_marker_definition (p, NULL, marker);
0fb4aa4b
PA
3487 return 1;
3488 }
3489
3490 return 0;
3491}
3492
0fb4aa4b 3493static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3494remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3495 const char *strid)
0fb4aa4b
PA
3496{
3497 struct remote_state *rs = get_remote_state ();
3498 VEC(static_tracepoint_marker_p) *markers = NULL;
3499 struct static_tracepoint_marker *marker = NULL;
3500 struct cleanup *old_chain;
256642e8 3501 const char *p;
0fb4aa4b
PA
3502
3503 /* Ask for a first packet of static tracepoint marker
3504 definition. */
3505 putpkt ("qTfSTM");
3506 getpkt (&rs->buf, &rs->buf_size, 0);
3507 p = rs->buf;
3508 if (*p == 'E')
3509 error (_("Remote failure reply: %s"), p);
3510
3511 old_chain = make_cleanup (free_current_marker, &marker);
3512
3513 while (*p++ == 'm')
3514 {
3515 if (marker == NULL)
3516 marker = XCNEW (struct static_tracepoint_marker);
3517
3518 do
3519 {
3520 parse_static_tracepoint_marker_definition (p, &p, marker);
3521
3522 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3523 {
3524 VEC_safe_push (static_tracepoint_marker_p,
3525 markers, marker);
3526 marker = NULL;
3527 }
3528 else
3529 {
3530 release_static_tracepoint_marker (marker);
3531 memset (marker, 0, sizeof (*marker));
3532 }
3533 }
3534 while (*p++ == ','); /* comma-separated list */
3535 /* Ask for another packet of static tracepoint definition. */
3536 putpkt ("qTsSTM");
3537 getpkt (&rs->buf, &rs->buf_size, 0);
3538 p = rs->buf;
3539 }
3540
3541 do_cleanups (old_chain);
3542 return markers;
3543}
3544
3545\f
10760264
JB
3546/* Implement the to_get_ada_task_ptid function for the remote targets. */
3547
3548static ptid_t
1e6b91a4 3549remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3550{
ba348170 3551 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3552}
3553\f
3554
24b06219 3555/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3556
3557static void
fba45db2 3558extended_remote_restart (void)
c906108c 3559{
d01949b6 3560 struct remote_state *rs = get_remote_state ();
c906108c
SS
3561
3562 /* Send the restart command; for reasons I don't understand the
3563 remote side really expects a number after the "R". */
ea9c271d 3564 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3565 putpkt (rs->buf);
c906108c 3566
ad9a8f3f 3567 remote_fileio_reset ();
c906108c
SS
3568}
3569\f
3570/* Clean up connection to a remote debugger. */
3571
c906108c 3572static void
de90e03d 3573remote_close (struct target_ops *self)
c906108c 3574{
5d93a237
TT
3575 struct remote_state *rs = get_remote_state ();
3576
3577 if (rs->remote_desc == NULL)
d3fd5342
PA
3578 return; /* already closed */
3579
048094ac 3580 /* Make sure we leave stdin registered in the event loop. */
e3594fd1 3581 remote_terminal_ours (self);
ce5ce7ed 3582
5d93a237
TT
3583 serial_close (rs->remote_desc);
3584 rs->remote_desc = NULL;
ce5ce7ed
PA
3585
3586 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3587 of all the inferiors and their threads we were controlling.
3588 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3589 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3590 inferior_ptid = null_ptid;
f67fd822 3591 discard_all_inferiors ();
ce5ce7ed 3592
f48ff2a7
YQ
3593 /* We are closing the remote target, so we should discard
3594 everything of this target. */
bcc75809 3595 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3596
3597 if (remote_async_inferior_event_token)
3598 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3599
5965e028 3600 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3601
3602 trace_reset_local_state ();
c906108c
SS
3603}
3604
23860348 3605/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3606
3607static void
fba45db2 3608get_offsets (void)
c906108c 3609{
d01949b6 3610 struct remote_state *rs = get_remote_state ();
2e9f7625 3611 char *buf;
085dd6e6 3612 char *ptr;
31d99776
DJ
3613 int lose, num_segments = 0, do_sections, do_segments;
3614 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3615 struct section_offsets *offs;
31d99776
DJ
3616 struct symfile_segment_data *data;
3617
3618 if (symfile_objfile == NULL)
3619 return;
c906108c
SS
3620
3621 putpkt ("qOffsets");
6d820c5c 3622 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3623 buf = rs->buf;
c906108c
SS
3624
3625 if (buf[0] == '\000')
3626 return; /* Return silently. Stub doesn't support
23860348 3627 this command. */
c906108c
SS
3628 if (buf[0] == 'E')
3629 {
8a3fe4f8 3630 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3631 return;
3632 }
3633
3634 /* Pick up each field in turn. This used to be done with scanf, but
3635 scanf will make trouble if CORE_ADDR size doesn't match
3636 conversion directives correctly. The following code will work
3637 with any size of CORE_ADDR. */
3638 text_addr = data_addr = bss_addr = 0;
3639 ptr = buf;
3640 lose = 0;
3641
61012eef 3642 if (startswith (ptr, "Text="))
c906108c
SS
3643 {
3644 ptr += 5;
3645 /* Don't use strtol, could lose on big values. */
3646 while (*ptr && *ptr != ';')
3647 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3648
61012eef 3649 if (startswith (ptr, ";Data="))
31d99776
DJ
3650 {
3651 ptr += 6;
3652 while (*ptr && *ptr != ';')
3653 data_addr = (data_addr << 4) + fromhex (*ptr++);
3654 }
3655 else
3656 lose = 1;
3657
61012eef 3658 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3659 {
3660 ptr += 5;
3661 while (*ptr && *ptr != ';')
3662 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3663
31d99776
DJ
3664 if (bss_addr != data_addr)
3665 warning (_("Target reported unsupported offsets: %s"), buf);
3666 }
3667 else
3668 lose = 1;
3669 }
61012eef 3670 else if (startswith (ptr, "TextSeg="))
c906108c 3671 {
31d99776
DJ
3672 ptr += 8;
3673 /* Don't use strtol, could lose on big values. */
c906108c 3674 while (*ptr && *ptr != ';')
31d99776
DJ
3675 text_addr = (text_addr << 4) + fromhex (*ptr++);
3676 num_segments = 1;
3677
61012eef 3678 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3679 {
3680 ptr += 9;
3681 while (*ptr && *ptr != ';')
3682 data_addr = (data_addr << 4) + fromhex (*ptr++);
3683 num_segments++;
3684 }
c906108c
SS
3685 }
3686 else
3687 lose = 1;
3688
3689 if (lose)
8a3fe4f8 3690 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3691 else if (*ptr != '\0')
3692 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3693
802188a7 3694 offs = ((struct section_offsets *)
a39a16c4 3695 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3696 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3697 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3698
31d99776
DJ
3699 data = get_symfile_segment_data (symfile_objfile->obfd);
3700 do_segments = (data != NULL);
3701 do_sections = num_segments == 0;
c906108c 3702
28c32713 3703 if (num_segments > 0)
31d99776 3704 {
31d99776
DJ
3705 segments[0] = text_addr;
3706 segments[1] = data_addr;
3707 }
28c32713
JB
3708 /* If we have two segments, we can still try to relocate everything
3709 by assuming that the .text and .data offsets apply to the whole
3710 text and data segments. Convert the offsets given in the packet
3711 to base addresses for symfile_map_offsets_to_segments. */
3712 else if (data && data->num_segments == 2)
3713 {
3714 segments[0] = data->segment_bases[0] + text_addr;
3715 segments[1] = data->segment_bases[1] + data_addr;
3716 num_segments = 2;
3717 }
8d385431
DJ
3718 /* If the object file has only one segment, assume that it is text
3719 rather than data; main programs with no writable data are rare,
3720 but programs with no code are useless. Of course the code might
3721 have ended up in the data segment... to detect that we would need
3722 the permissions here. */
3723 else if (data && data->num_segments == 1)
3724 {
3725 segments[0] = data->segment_bases[0] + text_addr;
3726 num_segments = 1;
3727 }
28c32713
JB
3728 /* There's no way to relocate by segment. */
3729 else
3730 do_segments = 0;
31d99776
DJ
3731
3732 if (do_segments)
3733 {
3734 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3735 offs, num_segments, segments);
3736
3737 if (ret == 0 && !do_sections)
3e43a32a
MS
3738 error (_("Can not handle qOffsets TextSeg "
3739 "response with this symbol file"));
31d99776
DJ
3740
3741 if (ret > 0)
3742 do_sections = 0;
3743 }
c906108c 3744
9ef895d6
DJ
3745 if (data)
3746 free_symfile_segment_data (data);
31d99776
DJ
3747
3748 if (do_sections)
3749 {
3750 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3751
3e43a32a
MS
3752 /* This is a temporary kludge to force data and bss to use the
3753 same offsets because that's what nlmconv does now. The real
3754 solution requires changes to the stub and remote.c that I
3755 don't have time to do right now. */
31d99776
DJ
3756
3757 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3758 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3759 }
c906108c
SS
3760
3761 objfile_relocate (symfile_objfile, offs);
3762}
3763
9a7071a8
JB
3764/* Send interrupt_sequence to remote target. */
3765static void
eeae04df 3766send_interrupt_sequence (void)
9a7071a8 3767{
5d93a237
TT
3768 struct remote_state *rs = get_remote_state ();
3769
9a7071a8 3770 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3771 remote_serial_write ("\x03", 1);
9a7071a8 3772 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3773 serial_send_break (rs->remote_desc);
9a7071a8
JB
3774 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3775 {
5d93a237 3776 serial_send_break (rs->remote_desc);
c33e31fd 3777 remote_serial_write ("g", 1);
9a7071a8
JB
3778 }
3779 else
3780 internal_error (__FILE__, __LINE__,
3781 _("Invalid value for interrupt_sequence_mode: %s."),
3782 interrupt_sequence_mode);
3783}
3784
3405876a
PA
3785
3786/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3787 and extract the PTID. Returns NULL_PTID if not found. */
3788
3789static ptid_t
3790stop_reply_extract_thread (char *stop_reply)
3791{
3792 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3793 {
256642e8 3794 const char *p;
3405876a
PA
3795
3796 /* Txx r:val ; r:val (...) */
3797 p = &stop_reply[3];
3798
3799 /* Look for "register" named "thread". */
3800 while (*p != '\0')
3801 {
256642e8 3802 const char *p1;
3405876a
PA
3803
3804 p1 = strchr (p, ':');
3805 if (p1 == NULL)
3806 return null_ptid;
3807
3808 if (strncmp (p, "thread", p1 - p) == 0)
3809 return read_ptid (++p1, &p);
3810
3811 p1 = strchr (p, ';');
3812 if (p1 == NULL)
3813 return null_ptid;
3814 p1++;
3815
3816 p = p1;
3817 }
3818 }
3819
3820 return null_ptid;
3821}
3822
b7ea362b
PA
3823/* Determine the remote side's current thread. If we have a stop
3824 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3825 "thread" register we can extract the current thread from. If not,
3826 ask the remote which is the current thread with qC. The former
3827 method avoids a roundtrip. */
3828
3829static ptid_t
3830get_current_thread (char *wait_status)
3831{
6a49a997 3832 ptid_t ptid = null_ptid;
b7ea362b
PA
3833
3834 /* Note we don't use remote_parse_stop_reply as that makes use of
3835 the target architecture, which we haven't yet fully determined at
3836 this point. */
3837 if (wait_status != NULL)
3838 ptid = stop_reply_extract_thread (wait_status);
3839 if (ptid_equal (ptid, null_ptid))
3840 ptid = remote_current_thread (inferior_ptid);
3841
3842 return ptid;
3843}
3844
49c62f2e
PA
3845/* Query the remote target for which is the current thread/process,
3846 add it to our tables, and update INFERIOR_PTID. The caller is
3847 responsible for setting the state such that the remote end is ready
3405876a
PA
3848 to return the current thread.
3849
3850 This function is called after handling the '?' or 'vRun' packets,
3851 whose response is a stop reply from which we can also try
3852 extracting the thread. If the target doesn't support the explicit
3853 qC query, we infer the current thread from that stop reply, passed
3854 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3855
3856static void
3405876a 3857add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3858{
3859 struct remote_state *rs = get_remote_state ();
3860 int fake_pid_p = 0;
49c62f2e
PA
3861
3862 inferior_ptid = null_ptid;
3863
b7ea362b 3864 /* Now, if we have thread information, update inferior_ptid. */
87215ad1 3865 ptid_t curr_ptid = get_current_thread (wait_status);
3405876a 3866
87215ad1 3867 if (curr_ptid != null_ptid)
49c62f2e
PA
3868 {
3869 if (!remote_multi_process_p (rs))
3870 fake_pid_p = 1;
49c62f2e
PA
3871 }
3872 else
3873 {
3874 /* Without this, some commands which require an active target
3875 (such as kill) won't work. This variable serves (at least)
3876 double duty as both the pid of the target process (if it has
3877 such), and as a flag indicating that a target is active. */
87215ad1 3878 curr_ptid = magic_null_ptid;
49c62f2e
PA
3879 fake_pid_p = 1;
3880 }
3881
87215ad1 3882 remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
49c62f2e 3883
87215ad1
SDJ
3884 /* Add the main thread and switch to it. Don't try reading
3885 registers yet, since we haven't fetched the target description
3886 yet. */
3887 thread_info *tp = add_thread_silent (curr_ptid);
3888 switch_to_thread_no_regs (tp);
49c62f2e
PA
3889}
3890
6efcd9a8
PA
3891/* Print info about a thread that was found already stopped on
3892 connection. */
3893
3894static void
3895print_one_stopped_thread (struct thread_info *thread)
3896{
3897 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3898
3899 switch_to_thread (thread->ptid);
3900 stop_pc = get_frame_pc (get_current_frame ());
3901 set_current_sal_from_frame (get_current_frame ());
3902
3903 thread->suspend.waitstatus_pending_p = 0;
3904
3905 if (ws->kind == TARGET_WAITKIND_STOPPED)
3906 {
3907 enum gdb_signal sig = ws->value.sig;
3908
3909 if (signal_print_state (sig))
3910 observer_notify_signal_received (sig);
3911 }
3912 observer_notify_normal_stop (NULL, 1);
3913}
3914
221e1a37
PA
3915/* Process all initial stop replies the remote side sent in response
3916 to the ? packet. These indicate threads that were already stopped
3917 on initial connection. We mark these threads as stopped and print
3918 their current frame before giving the user the prompt. */
3919
3920static void
6efcd9a8 3921process_initial_stop_replies (int from_tty)
221e1a37
PA
3922{
3923 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3924 struct inferior *inf;
3925 struct thread_info *thread;
3926 struct thread_info *selected = NULL;
3927 struct thread_info *lowest_stopped = NULL;
3928 struct thread_info *first = NULL;
221e1a37
PA
3929
3930 /* Consume the initial pending events. */
3931 while (pending_stop_replies-- > 0)
3932 {
3933 ptid_t waiton_ptid = minus_one_ptid;
3934 ptid_t event_ptid;
3935 struct target_waitstatus ws;
3936 int ignore_event = 0;
6efcd9a8 3937 struct thread_info *thread;
221e1a37
PA
3938
3939 memset (&ws, 0, sizeof (ws));
3940 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3941 if (remote_debug)
3942 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3943
3944 switch (ws.kind)
3945 {
3946 case TARGET_WAITKIND_IGNORE:
3947 case TARGET_WAITKIND_NO_RESUMED:
3948 case TARGET_WAITKIND_SIGNALLED:
3949 case TARGET_WAITKIND_EXITED:
3950 /* We shouldn't see these, but if we do, just ignore. */
3951 if (remote_debug)
3952 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3953 ignore_event = 1;
3954 break;
3955
3956 case TARGET_WAITKIND_EXECD:
3957 xfree (ws.value.execd_pathname);
3958 break;
3959 default:
3960 break;
3961 }
3962
3963 if (ignore_event)
3964 continue;
3965
6efcd9a8 3966 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3967
3968 if (ws.kind == TARGET_WAITKIND_STOPPED)
3969 {
3970 enum gdb_signal sig = ws.value.sig;
3971
3972 /* Stubs traditionally report SIGTRAP as initial signal,
3973 instead of signal 0. Suppress it. */
3974 if (sig == GDB_SIGNAL_TRAP)
3975 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3976 thread->suspend.stop_signal = sig;
3977 ws.value.sig = sig;
3978 }
221e1a37 3979
6efcd9a8
PA
3980 thread->suspend.waitstatus = ws;
3981
3982 if (ws.kind != TARGET_WAITKIND_STOPPED
3983 || ws.value.sig != GDB_SIGNAL_0)
3984 thread->suspend.waitstatus_pending_p = 1;
3985
3986 set_executing (event_ptid, 0);
3987 set_running (event_ptid, 0);
85ad3aaf 3988 thread->priv->vcont_resumed = 0;
6efcd9a8
PA
3989 }
3990
3991 /* "Notice" the new inferiors before anything related to
3992 registers/memory. */
3993 ALL_INFERIORS (inf)
3994 {
3995 if (inf->pid == 0)
3996 continue;
3997
3998 inf->needs_setup = 1;
3999
4000 if (non_stop)
4001 {
4002 thread = any_live_thread_of_process (inf->pid);
4003 notice_new_inferior (thread->ptid,
4004 thread->state == THREAD_RUNNING,
4005 from_tty);
4006 }
4007 }
4008
4009 /* If all-stop on top of non-stop, pause all threads. Note this
4010 records the threads' stop pc, so must be done after "noticing"
4011 the inferiors. */
4012 if (!non_stop)
4013 {
4014 stop_all_threads ();
4015
4016 /* If all threads of an inferior were already stopped, we
4017 haven't setup the inferior yet. */
4018 ALL_INFERIORS (inf)
4019 {
4020 if (inf->pid == 0)
4021 continue;
221e1a37 4022
6efcd9a8
PA
4023 if (inf->needs_setup)
4024 {
4025 thread = any_live_thread_of_process (inf->pid);
4026 switch_to_thread_no_regs (thread);
4027 setup_inferior (0);
4028 }
4029 }
221e1a37 4030 }
6efcd9a8
PA
4031
4032 /* Now go over all threads that are stopped, and print their current
4033 frame. If all-stop, then if there's a signalled thread, pick
4034 that as current. */
4035 ALL_NON_EXITED_THREADS (thread)
4036 {
6efcd9a8
PA
4037 if (first == NULL)
4038 first = thread;
4039
4040 if (!non_stop)
4041 set_running (thread->ptid, 0);
4042 else if (thread->state != THREAD_STOPPED)
4043 continue;
4044
6efcd9a8
PA
4045 if (selected == NULL
4046 && thread->suspend.waitstatus_pending_p)
4047 selected = thread;
4048
5d5658a1
PA
4049 if (lowest_stopped == NULL
4050 || thread->inf->num < lowest_stopped->inf->num
4051 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4052 lowest_stopped = thread;
4053
4054 if (non_stop)
4055 print_one_stopped_thread (thread);
4056 }
4057
4058 /* In all-stop, we only print the status of one thread, and leave
4059 others with their status pending. */
4060 if (!non_stop)
4061 {
4062 thread = selected;
4063 if (thread == NULL)
4064 thread = lowest_stopped;
4065 if (thread == NULL)
4066 thread = first;
4067
4068 print_one_stopped_thread (thread);
4069 }
4070
4071 /* For "info program". */
4072 thread = inferior_thread ();
4073 if (thread->state == THREAD_STOPPED)
4074 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4075}
4076
048094ac
PA
4077/* Start the remote connection and sync state. */
4078
9cbc821d 4079static void
04bd08de 4080remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 4081{
c8d104ad
PA
4082 struct remote_state *rs = get_remote_state ();
4083 struct packet_config *noack_config;
2d717e4f 4084 char *wait_status = NULL;
8621d6a9 4085
048094ac
PA
4086 /* Signal other parts that we're going through the initial setup,
4087 and so things may not be stable yet. E.g., we don't try to
4088 install tracepoints until we've relocated symbols. Also, a
4089 Ctrl-C before we're connected and synced up can't interrupt the
4090 target. Instead, it offers to drop the (potentially wedged)
4091 connection. */
4092 rs->starting_up = 1;
4093
522002f9 4094 QUIT;
c906108c 4095
9a7071a8
JB
4096 if (interrupt_on_connect)
4097 send_interrupt_sequence ();
4098
57e12211 4099 /* Ack any packet which the remote side has already sent. */
048094ac 4100 remote_serial_write ("+", 1);
1e51243a 4101
c8d104ad
PA
4102 /* The first packet we send to the target is the optional "supported
4103 packets" request. If the target can answer this, it will tell us
4104 which later probes to skip. */
4105 remote_query_supported ();
4106
d914c394 4107 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4108 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 4109 remote_set_permissions (target);
d914c394 4110
57809e5e
JK
4111 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4112 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4113 as a reply to known packet. For packet "vFile:setfs:" it is an
4114 invalid reply and GDB would return error in
4115 remote_hostio_set_filesystem, making remote files access impossible.
4116 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4117 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4118 {
4119 const char v_mustreplyempty[] = "vMustReplyEmpty";
4120
4121 putpkt (v_mustreplyempty);
4122 getpkt (&rs->buf, &rs->buf_size, 0);
4123 if (strcmp (rs->buf, "OK") == 0)
4124 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4125 else if (strcmp (rs->buf, "") != 0)
4126 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4127 rs->buf);
4128 }
4129
c8d104ad
PA
4130 /* Next, we possibly activate noack mode.
4131
4132 If the QStartNoAckMode packet configuration is set to AUTO,
4133 enable noack mode if the stub reported a wish for it with
4134 qSupported.
4135
4136 If set to TRUE, then enable noack mode even if the stub didn't
4137 report it in qSupported. If the stub doesn't reply OK, the
4138 session ends with an error.
4139
4140 If FALSE, then don't activate noack mode, regardless of what the
4141 stub claimed should be the default with qSupported. */
4142
4143 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4144 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4145 {
4146 putpkt ("QStartNoAckMode");
4147 getpkt (&rs->buf, &rs->buf_size, 0);
4148 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4149 rs->noack_mode = 1;
4150 }
4151
04bd08de 4152 if (extended_p)
5fe04517
PA
4153 {
4154 /* Tell the remote that we are using the extended protocol. */
4155 putpkt ("!");
4156 getpkt (&rs->buf, &rs->buf_size, 0);
4157 }
4158
9b224c5e
PA
4159 /* Let the target know which signals it is allowed to pass down to
4160 the program. */
4161 update_signals_program_target ();
4162
d962ef82
DJ
4163 /* Next, if the target can specify a description, read it. We do
4164 this before anything involving memory or registers. */
4165 target_find_description ();
4166
6c95b8df
PA
4167 /* Next, now that we know something about the target, update the
4168 address spaces in the program spaces. */
4169 update_address_spaces ();
4170
50c71eaf
PA
4171 /* On OSs where the list of libraries is global to all
4172 processes, we fetch them early. */
f5656ead 4173 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4174 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4175
6efcd9a8 4176 if (target_is_non_stop_p ())
74531fed 4177 {
4082afcc 4178 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4179 error (_("Non-stop mode requested, but remote "
4180 "does not support non-stop"));
74531fed
PA
4181
4182 putpkt ("QNonStop:1");
4183 getpkt (&rs->buf, &rs->buf_size, 0);
4184
4185 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4186 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4187
4188 /* Find about threads and processes the stub is already
4189 controlling. We default to adding them in the running state.
4190 The '?' query below will then tell us about which threads are
4191 stopped. */
e8032dde 4192 remote_update_thread_list (target);
74531fed 4193 }
4082afcc 4194 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4195 {
4196 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4197 Request it explicitly. */
74531fed
PA
4198 putpkt ("QNonStop:0");
4199 getpkt (&rs->buf, &rs->buf_size, 0);
4200
4201 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4202 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4203 }
4204
a0743c90
YQ
4205 /* Upload TSVs regardless of whether the target is running or not. The
4206 remote stub, such as GDBserver, may have some predefined or builtin
4207 TSVs, even if the target is not running. */
8bd200f1 4208 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4209 {
4210 struct uploaded_tsv *uploaded_tsvs = NULL;
4211
181e3713 4212 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4213 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4214 }
4215
2d717e4f
DJ
4216 /* Check whether the target is running now. */
4217 putpkt ("?");
4218 getpkt (&rs->buf, &rs->buf_size, 0);
4219
6efcd9a8 4220 if (!target_is_non_stop_p ())
2d717e4f 4221 {
74531fed 4222 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4223 {
04bd08de 4224 if (!extended_p)
74531fed 4225 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4226
4227 /* We're connected, but not running. Drop out before we
4228 call start_remote. */
e278ad5b 4229 rs->starting_up = 0;
c35b1492 4230 return;
2d717e4f
DJ
4231 }
4232 else
74531fed 4233 {
74531fed 4234 /* Save the reply for later. */
224c3ddb 4235 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4236 strcpy (wait_status, rs->buf);
4237 }
4238
b7ea362b 4239 /* Fetch thread list. */
e8032dde 4240 target_update_thread_list ();
b7ea362b 4241
74531fed
PA
4242 /* Let the stub know that we want it to return the thread. */
4243 set_continue_thread (minus_one_ptid);
4244
b7ea362b
PA
4245 if (thread_count () == 0)
4246 {
4247 /* Target has no concept of threads at all. GDB treats
4248 non-threaded target as single-threaded; add a main
4249 thread. */
4250 add_current_inferior_and_thread (wait_status);
4251 }
4252 else
4253 {
4254 /* We have thread information; select the thread the target
4255 says should be current. If we're reconnecting to a
4256 multi-threaded program, this will ideally be the thread
4257 that last reported an event before GDB disconnected. */
4258 inferior_ptid = get_current_thread (wait_status);
4259 if (ptid_equal (inferior_ptid, null_ptid))
4260 {
4261 /* Odd... The target was able to list threads, but not
4262 tell us which thread was current (no "thread"
4263 register in T stop reply?). Just pick the first
4264 thread in the thread list then. */
c9f35b34
KB
4265
4266 if (remote_debug)
4267 fprintf_unfiltered (gdb_stdlog,
4268 "warning: couldn't determine remote "
4269 "current thread; picking first in list.\n");
4270
b7ea362b
PA
4271 inferior_ptid = thread_list->ptid;
4272 }
4273 }
74531fed 4274
6e586cc5
YQ
4275 /* init_wait_for_inferior should be called before get_offsets in order
4276 to manage `inserted' flag in bp loc in a correct state.
4277 breakpoint_init_inferior, called from init_wait_for_inferior, set
4278 `inserted' flag to 0, while before breakpoint_re_set, called from
4279 start_remote, set `inserted' flag to 1. In the initialization of
4280 inferior, breakpoint_init_inferior should be called first, and then
4281 breakpoint_re_set can be called. If this order is broken, state of
4282 `inserted' flag is wrong, and cause some problems on breakpoint
4283 manipulation. */
4284 init_wait_for_inferior ();
4285
74531fed
PA
4286 get_offsets (); /* Get text, data & bss offsets. */
4287
d962ef82
DJ
4288 /* If we could not find a description using qXfer, and we know
4289 how to do it some other way, try again. This is not
4290 supported for non-stop; it could be, but it is tricky if
4291 there are no stopped threads when we connect. */
04bd08de 4292 if (remote_read_description_p (target)
f5656ead 4293 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4294 {
4295 target_clear_description ();
4296 target_find_description ();
4297 }
4298
74531fed
PA
4299 /* Use the previously fetched status. */
4300 gdb_assert (wait_status != NULL);
4301 strcpy (rs->buf, wait_status);
4302 rs->cached_wait_status = 1;
4303
04bd08de 4304 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4305 }
4306 else
4307 {
68c97600
PA
4308 /* Clear WFI global state. Do this before finding about new
4309 threads and inferiors, and setting the current inferior.
4310 Otherwise we would clear the proceed status of the current
4311 inferior when we want its stop_soon state to be preserved
4312 (see notice_new_inferior). */
4313 init_wait_for_inferior ();
4314
74531fed
PA
4315 /* In non-stop, we will either get an "OK", meaning that there
4316 are no stopped threads at this time; or, a regular stop
4317 reply. In the latter case, there may be more than one thread
4318 stopped --- we pull them all out using the vStopped
4319 mechanism. */
4320 if (strcmp (rs->buf, "OK") != 0)
4321 {
722247f1 4322 struct notif_client *notif = &notif_client_stop;
2d717e4f 4323
722247f1
YQ
4324 /* remote_notif_get_pending_replies acks this one, and gets
4325 the rest out. */
f48ff2a7 4326 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4327 = remote_notif_parse (notif, rs->buf);
4328 remote_notif_get_pending_events (notif);
74531fed 4329 }
2d717e4f 4330
74531fed
PA
4331 if (thread_count () == 0)
4332 {
04bd08de 4333 if (!extended_p)
74531fed 4334 error (_("The target is not running (try extended-remote?)"));
82f73884 4335
c35b1492
PA
4336 /* We're connected, but not running. Drop out before we
4337 call start_remote. */
e278ad5b 4338 rs->starting_up = 0;
c35b1492
PA
4339 return;
4340 }
74531fed 4341
74531fed
PA
4342 /* In non-stop mode, any cached wait status will be stored in
4343 the stop reply queue. */
4344 gdb_assert (wait_status == NULL);
f0223081 4345
2455069d 4346 /* Report all signals during attach/startup. */
94bedb42 4347 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4348
4349 /* If there are already stopped threads, mark them stopped and
4350 report their stops before giving the prompt to the user. */
6efcd9a8 4351 process_initial_stop_replies (from_tty);
221e1a37
PA
4352
4353 if (target_can_async_p ())
4354 target_async (1);
74531fed 4355 }
c8d104ad 4356
c8d104ad
PA
4357 /* If we connected to a live target, do some additional setup. */
4358 if (target_has_execution)
4359 {
f4ccffad 4360 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4361 remote_check_symbols ();
c8d104ad 4362 }
50c71eaf 4363
d5551862
SS
4364 /* Possibly the target has been engaged in a trace run started
4365 previously; find out where things are at. */
8bd200f1 4366 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4367 {
00bf0b85 4368 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4369
00bf0b85
SS
4370 if (current_trace_status ()->running)
4371 printf_filtered (_("Trace is already running on the target.\n"));
4372
ab6617cc 4373 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4374
4375 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4376 }
4377
c0272db5
TW
4378 /* Possibly the target has been engaged in a btrace record started
4379 previously; find out where things are at. */
4380 remote_btrace_maybe_reopen ();
4381
1e51243a
PA
4382 /* The thread and inferior lists are now synchronized with the
4383 target, our symbols have been relocated, and we're merged the
4384 target's tracepoints with ours. We're done with basic start
4385 up. */
4386 rs->starting_up = 0;
4387
a25a5a45
PA
4388 /* Maybe breakpoints are global and need to be inserted now. */
4389 if (breakpoints_should_be_inserted_now ())
50c71eaf 4390 insert_breakpoints ();
c906108c
SS
4391}
4392
4393/* Open a connection to a remote debugger.
4394 NAME is the filename used for communication. */
4395
4396static void
014f9477 4397remote_open (const char *name, int from_tty)
c906108c 4398{
75c99385 4399 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4400}
4401
c906108c
SS
4402/* Open a connection to a remote debugger using the extended
4403 remote gdb protocol. NAME is the filename used for communication. */
4404
4405static void
014f9477 4406extended_remote_open (const char *name, int from_tty)
c906108c 4407{
75c99385 4408 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4409}
4410
ca4f7f8b
PA
4411/* Reset all packets back to "unknown support". Called when opening a
4412 new connection to a remote target. */
c906108c 4413
d471ea57 4414static void
ca4f7f8b 4415reset_all_packet_configs_support (void)
d471ea57
AC
4416{
4417 int i;
a744cf53 4418
444abaca 4419 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4420 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4421}
4422
ca4f7f8b
PA
4423/* Initialize all packet configs. */
4424
4425static void
4426init_all_packet_configs (void)
4427{
4428 int i;
4429
4430 for (i = 0; i < PACKET_MAX; i++)
4431 {
4432 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4433 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4434 }
4435}
4436
23860348 4437/* Symbol look-up. */
dc8acb97
MS
4438
4439static void
36d25514 4440remote_check_symbols (void)
dc8acb97 4441{
d01949b6 4442 struct remote_state *rs = get_remote_state ();
dc8acb97 4443 char *msg, *reply, *tmp;
dc8acb97 4444 int end;
28170b88 4445 long reply_size;
a5c0808e 4446 struct cleanup *old_chain;
dc8acb97 4447
63154eca
PA
4448 /* The remote side has no concept of inferiors that aren't running
4449 yet, it only knows about running processes. If we're connected
4450 but our current inferior is not running, we should not invite the
4451 remote target to request symbol lookups related to its
4452 (unrelated) current process. */
4453 if (!target_has_execution)
4454 return;
4455
4082afcc 4456 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4457 return;
4458
63154eca
PA
4459 /* Make sure the remote is pointing at the right process. Note
4460 there's no way to select "no process". */
3c9c4b83
PA
4461 set_general_process ();
4462
6d820c5c
DJ
4463 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4464 because we need both at the same time. */
224c3ddb 4465 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4466 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4467 reply = (char *) xmalloc (get_remote_packet_size ());
4468 make_cleanup (free_current_contents, &reply);
4469 reply_size = get_remote_packet_size ();
6d820c5c 4470
23860348 4471 /* Invite target to request symbol lookups. */
dc8acb97
MS
4472
4473 putpkt ("qSymbol::");
28170b88
MK
4474 getpkt (&reply, &reply_size, 0);
4475 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4476
61012eef 4477 while (startswith (reply, "qSymbol:"))
dc8acb97 4478 {
77e371c0
TT
4479 struct bound_minimal_symbol sym;
4480
dc8acb97 4481 tmp = &reply[8];
cfd77fa1 4482 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4483 msg[end] = '\0';
4484 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4485 if (sym.minsym == NULL)
ea9c271d 4486 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4487 else
2bbe3cc1 4488 {
f5656ead 4489 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4490 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4491
4492 /* If this is a function address, return the start of code
4493 instead of any data function descriptor. */
f5656ead 4494 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4495 sym_addr,
4496 &current_target);
4497
4498 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4499 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4500 }
4501
dc8acb97 4502 putpkt (msg);
28170b88 4503 getpkt (&reply, &reply_size, 0);
dc8acb97 4504 }
a5c0808e
PA
4505
4506 do_cleanups (old_chain);
dc8acb97
MS
4507}
4508
9db8d71f 4509static struct serial *
baa336ce 4510remote_serial_open (const char *name)
9db8d71f
DJ
4511{
4512 static int udp_warning = 0;
4513
4514 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4515 of in ser-tcp.c, because it is the remote protocol assuming that the
4516 serial connection is reliable and not the serial connection promising
4517 to be. */
61012eef 4518 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4519 {
3e43a32a
MS
4520 warning (_("The remote protocol may be unreliable over UDP.\n"
4521 "Some events may be lost, rendering further debugging "
4522 "impossible."));
9db8d71f
DJ
4523 udp_warning = 1;
4524 }
4525
4526 return serial_open (name);
4527}
4528
d914c394
SS
4529/* Inform the target of our permission settings. The permission flags
4530 work without this, but if the target knows the settings, it can do
4531 a couple things. First, it can add its own check, to catch cases
4532 that somehow manage to get by the permissions checks in target
4533 methods. Second, if the target is wired to disallow particular
4534 settings (for instance, a system in the field that is not set up to
4535 be able to stop at a breakpoint), it can object to any unavailable
4536 permissions. */
4537
4538void
c378d69d 4539remote_set_permissions (struct target_ops *self)
d914c394
SS
4540{
4541 struct remote_state *rs = get_remote_state ();
4542
bba74b36
YQ
4543 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4544 "WriteReg:%x;WriteMem:%x;"
4545 "InsertBreak:%x;InsertTrace:%x;"
4546 "InsertFastTrace:%x;Stop:%x",
4547 may_write_registers, may_write_memory,
4548 may_insert_breakpoints, may_insert_tracepoints,
4549 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4550 putpkt (rs->buf);
4551 getpkt (&rs->buf, &rs->buf_size, 0);
4552
4553 /* If the target didn't like the packet, warn the user. Do not try
4554 to undo the user's settings, that would just be maddening. */
4555 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4556 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4557}
4558
be2a5f71
DJ
4559/* This type describes each known response to the qSupported
4560 packet. */
4561struct protocol_feature
4562{
4563 /* The name of this protocol feature. */
4564 const char *name;
4565
4566 /* The default for this protocol feature. */
4567 enum packet_support default_support;
4568
4569 /* The function to call when this feature is reported, or after
4570 qSupported processing if the feature is not supported.
4571 The first argument points to this structure. The second
4572 argument indicates whether the packet requested support be
4573 enabled, disabled, or probed (or the default, if this function
4574 is being called at the end of processing and this feature was
4575 not reported). The third argument may be NULL; if not NULL, it
4576 is a NUL-terminated string taken from the packet following
4577 this feature's name and an equals sign. */
4578 void (*func) (const struct protocol_feature *, enum packet_support,
4579 const char *);
4580
4581 /* The corresponding packet for this feature. Only used if
4582 FUNC is remote_supported_packet. */
4583 int packet;
4584};
4585
be2a5f71
DJ
4586static void
4587remote_supported_packet (const struct protocol_feature *feature,
4588 enum packet_support support,
4589 const char *argument)
4590{
4591 if (argument)
4592 {
4593 warning (_("Remote qSupported response supplied an unexpected value for"
4594 " \"%s\"."), feature->name);
4595 return;
4596 }
4597
4082afcc 4598 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4599}
be2a5f71
DJ
4600
4601static void
4602remote_packet_size (const struct protocol_feature *feature,
4603 enum packet_support support, const char *value)
4604{
4605 struct remote_state *rs = get_remote_state ();
4606
4607 int packet_size;
4608 char *value_end;
4609
4610 if (support != PACKET_ENABLE)
4611 return;
4612
4613 if (value == NULL || *value == '\0')
4614 {
4615 warning (_("Remote target reported \"%s\" without a size."),
4616 feature->name);
4617 return;
4618 }
4619
4620 errno = 0;
4621 packet_size = strtol (value, &value_end, 16);
4622 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4623 {
4624 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4625 feature->name, value);
4626 return;
4627 }
4628
be2a5f71
DJ
4629 /* Record the new maximum packet size. */
4630 rs->explicit_packet_size = packet_size;
4631}
4632
dc473cfb 4633static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4634 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4635 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4636 PACKET_qXfer_auxv },
c78fa86a
GB
4637 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4638 PACKET_qXfer_exec_file },
23181151
DJ
4639 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4640 PACKET_qXfer_features },
cfa9d6d9
DJ
4641 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4642 PACKET_qXfer_libraries },
2268b414
JK
4643 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4644 PACKET_qXfer_libraries_svr4 },
ced63ec0 4645 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4646 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4647 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4648 PACKET_qXfer_memory_map },
4de6483e
UW
4649 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4650 PACKET_qXfer_spu_read },
4651 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4652 PACKET_qXfer_spu_write },
07e059b5
VP
4653 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4654 PACKET_qXfer_osdata },
dc146f7c
VP
4655 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4656 PACKET_qXfer_threads },
b3b9301e
PA
4657 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4658 PACKET_qXfer_traceframe_info },
89be2091
DJ
4659 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4660 PACKET_QPassSignals },
82075af2
JS
4661 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4662 PACKET_QCatchSyscalls },
9b224c5e
PA
4663 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4664 PACKET_QProgramSignals },
aefd8b33
SDJ
4665 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4666 PACKET_QStartupWithShell },
0a2dde4a
SDJ
4667 { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4668 PACKET_QEnvironmentHexEncoded },
4669 { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4670 PACKET_QEnvironmentReset },
4671 { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4672 PACKET_QEnvironmentUnset },
a6f3e723
SL
4673 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4674 PACKET_QStartNoAckMode },
4082afcc
PA
4675 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4676 PACKET_multiprocess_feature },
4677 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4678 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4679 PACKET_qXfer_siginfo_read },
4680 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4681 PACKET_qXfer_siginfo_write },
4082afcc 4682 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4683 PACKET_ConditionalTracepoints },
4082afcc 4684 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4685 PACKET_ConditionalBreakpoints },
4082afcc 4686 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4687 PACKET_BreakpointCommands },
4082afcc 4688 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4689 PACKET_FastTracepoints },
4082afcc 4690 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4691 PACKET_StaticTracepoints },
4082afcc 4692 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4693 PACKET_InstallInTrace},
4082afcc
PA
4694 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4695 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4696 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4697 PACKET_bc },
4698 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4699 PACKET_bs },
409873ef
SS
4700 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4701 PACKET_TracepointSource },
d914c394
SS
4702 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4703 PACKET_QAllow },
4082afcc
PA
4704 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4705 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4706 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4707 PACKET_qXfer_fdpic },
169081d0
TG
4708 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4709 PACKET_qXfer_uib },
03583c20
UW
4710 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4711 PACKET_QDisableRandomization },
d1feda86 4712 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4713 { "QTBuffer:size", PACKET_DISABLE,
4714 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4715 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4716 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4717 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4718 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4719 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4720 PACKET_qXfer_btrace },
4721 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4722 PACKET_qXfer_btrace_conf },
4723 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4724 PACKET_Qbtrace_conf_bts_size },
4725 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4726 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4727 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4728 PACKET_fork_event_feature },
4729 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4730 PACKET_vfork_event_feature },
94585166
DB
4731 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4732 PACKET_exec_event_feature },
b20a6524 4733 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4734 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4735 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4736 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4737 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4738};
4739
c8d5aac9
L
4740static char *remote_support_xml;
4741
4742/* Register string appended to "xmlRegisters=" in qSupported query. */
4743
4744void
6e39997a 4745register_remote_support_xml (const char *xml)
c8d5aac9
L
4746{
4747#if defined(HAVE_LIBEXPAT)
4748 if (remote_support_xml == NULL)
c4f7c687 4749 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4750 else
4751 {
4752 char *copy = xstrdup (remote_support_xml + 13);
4753 char *p = strtok (copy, ",");
4754
4755 do
4756 {
4757 if (strcmp (p, xml) == 0)
4758 {
4759 /* already there */
4760 xfree (copy);
4761 return;
4762 }
4763 }
4764 while ((p = strtok (NULL, ",")) != NULL);
4765 xfree (copy);
4766
94b0dee1
PA
4767 remote_support_xml = reconcat (remote_support_xml,
4768 remote_support_xml, ",", xml,
4769 (char *) NULL);
c8d5aac9
L
4770 }
4771#endif
4772}
4773
4774static char *
4775remote_query_supported_append (char *msg, const char *append)
4776{
4777 if (msg)
94b0dee1 4778 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4779 else
4780 return xstrdup (append);
4781}
4782
be2a5f71
DJ
4783static void
4784remote_query_supported (void)
4785{
4786 struct remote_state *rs = get_remote_state ();
4787 char *next;
4788 int i;
4789 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4790
4791 /* The packet support flags are handled differently for this packet
4792 than for most others. We treat an error, a disabled packet, and
4793 an empty response identically: any features which must be reported
4794 to be used will be automatically disabled. An empty buffer
4795 accomplishes this, since that is also the representation for a list
4796 containing no features. */
4797
4798 rs->buf[0] = 0;
4082afcc 4799 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4800 {
c8d5aac9 4801 char *q = NULL;
94b0dee1 4802 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4803
73b8c1fd
PA
4804 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4805 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4806
f7e6eed5
PA
4807 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4808 q = remote_query_supported_append (q, "swbreak+");
4809 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4810 q = remote_query_supported_append (q, "hwbreak+");
4811
dde08ee1
PA
4812 q = remote_query_supported_append (q, "qRelocInsn+");
4813
8020350c
DB
4814 if (packet_set_cmd_state (PACKET_fork_event_feature)
4815 != AUTO_BOOLEAN_FALSE)
4816 q = remote_query_supported_append (q, "fork-events+");
4817 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4818 != AUTO_BOOLEAN_FALSE)
4819 q = remote_query_supported_append (q, "vfork-events+");
4820 if (packet_set_cmd_state (PACKET_exec_event_feature)
4821 != AUTO_BOOLEAN_FALSE)
4822 q = remote_query_supported_append (q, "exec-events+");
89245bc0 4823
750ce8d1
YQ
4824 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4825 q = remote_query_supported_append (q, "vContSupported+");
4826
65706a29
PA
4827 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4828 q = remote_query_supported_append (q, "QThreadEvents+");
4829
f2faf941
PA
4830 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4831 q = remote_query_supported_append (q, "no-resumed+");
4832
b35d5edb
PA
4833 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4834 the qSupported:xmlRegisters=i386 handling. */
4835 if (remote_support_xml != NULL)
4836 q = remote_query_supported_append (q, remote_support_xml);
4837
dde08ee1
PA
4838 q = reconcat (q, "qSupported:", q, (char *) NULL);
4839 putpkt (q);
82f73884 4840
94b0dee1
PA
4841 do_cleanups (old_chain);
4842
be2a5f71
DJ
4843 getpkt (&rs->buf, &rs->buf_size, 0);
4844
4845 /* If an error occured, warn, but do not return - just reset the
4846 buffer to empty and go on to disable features. */
4847 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4848 == PACKET_ERROR)
4849 {
4850 warning (_("Remote failure reply: %s"), rs->buf);
4851 rs->buf[0] = 0;
4852 }
4853 }
4854
4855 memset (seen, 0, sizeof (seen));
4856
4857 next = rs->buf;
4858 while (*next)
4859 {
4860 enum packet_support is_supported;
4861 char *p, *end, *name_end, *value;
4862
4863 /* First separate out this item from the rest of the packet. If
4864 there's another item after this, we overwrite the separator
4865 (terminated strings are much easier to work with). */
4866 p = next;
4867 end = strchr (p, ';');
4868 if (end == NULL)
4869 {
4870 end = p + strlen (p);
4871 next = end;
4872 }
4873 else
4874 {
89be2091
DJ
4875 *end = '\0';
4876 next = end + 1;
4877
be2a5f71
DJ
4878 if (end == p)
4879 {
4880 warning (_("empty item in \"qSupported\" response"));
4881 continue;
4882 }
be2a5f71
DJ
4883 }
4884
4885 name_end = strchr (p, '=');
4886 if (name_end)
4887 {
4888 /* This is a name=value entry. */
4889 is_supported = PACKET_ENABLE;
4890 value = name_end + 1;
4891 *name_end = '\0';
4892 }
4893 else
4894 {
4895 value = NULL;
4896 switch (end[-1])
4897 {
4898 case '+':
4899 is_supported = PACKET_ENABLE;
4900 break;
4901
4902 case '-':
4903 is_supported = PACKET_DISABLE;
4904 break;
4905
4906 case '?':
4907 is_supported = PACKET_SUPPORT_UNKNOWN;
4908 break;
4909
4910 default:
3e43a32a
MS
4911 warning (_("unrecognized item \"%s\" "
4912 "in \"qSupported\" response"), p);
be2a5f71
DJ
4913 continue;
4914 }
4915 end[-1] = '\0';
4916 }
4917
4918 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4919 if (strcmp (remote_protocol_features[i].name, p) == 0)
4920 {
4921 const struct protocol_feature *feature;
4922
4923 seen[i] = 1;
4924 feature = &remote_protocol_features[i];
4925 feature->func (feature, is_supported, value);
4926 break;
4927 }
4928 }
4929
4930 /* If we increased the packet size, make sure to increase the global
4931 buffer size also. We delay this until after parsing the entire
4932 qSupported packet, because this is the same buffer we were
4933 parsing. */
4934 if (rs->buf_size < rs->explicit_packet_size)
4935 {
4936 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4937 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4938 }
4939
4940 /* Handle the defaults for unmentioned features. */
4941 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4942 if (!seen[i])
4943 {
4944 const struct protocol_feature *feature;
4945
4946 feature = &remote_protocol_features[i];
4947 feature->func (feature, feature->default_support, NULL);
4948 }
4949}
4950
048094ac
PA
4951/* Serial QUIT handler for the remote serial descriptor.
4952
4953 Defers handling a Ctrl-C until we're done with the current
4954 command/response packet sequence, unless:
4955
4956 - We're setting up the connection. Don't send a remote interrupt
4957 request, as we're not fully synced yet. Quit immediately
4958 instead.
4959
4960 - The target has been resumed in the foreground
223ffa71 4961 (target_terminal::is_ours is false) with a synchronous resume
048094ac
PA
4962 packet, and we're blocked waiting for the stop reply, thus a
4963 Ctrl-C should be immediately sent to the target.
4964
4965 - We get a second Ctrl-C while still within the same serial read or
4966 write. In that case the serial is seemingly wedged --- offer to
4967 quit/disconnect.
4968
4969 - We see a second Ctrl-C without target response, after having
4970 previously interrupted the target. In that case the target/stub
4971 is probably wedged --- offer to quit/disconnect.
4972*/
4973
4974static void
4975remote_serial_quit_handler (void)
4976{
4977 struct remote_state *rs = get_remote_state ();
4978
4979 if (check_quit_flag ())
4980 {
4981 /* If we're starting up, we're not fully synced yet. Quit
4982 immediately. */
4983 if (rs->starting_up)
4984 quit ();
4985 else if (rs->got_ctrlc_during_io)
4986 {
4987 if (query (_("The target is not responding to GDB commands.\n"
4988 "Stop debugging it? ")))
4989 remote_unpush_and_throw ();
4990 }
4991 /* If ^C has already been sent once, offer to disconnect. */
223ffa71 4992 else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
048094ac
PA
4993 interrupt_query ();
4994 /* All-stop protocol, and blocked waiting for stop reply. Send
4995 an interrupt request. */
223ffa71 4996 else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
048094ac
PA
4997 target_interrupt (inferior_ptid);
4998 else
4999 rs->got_ctrlc_during_io = 1;
5000 }
5001}
5002
78a095c3
JK
5003/* Remove any of the remote.c targets from target stack. Upper targets depend
5004 on it so remove them first. */
5005
5006static void
5007remote_unpush_target (void)
5008{
915ef8b1 5009 pop_all_targets_at_and_above (process_stratum);
78a095c3 5010}
be2a5f71 5011
048094ac
PA
5012static void
5013remote_unpush_and_throw (void)
5014{
5015 remote_unpush_target ();
5016 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5017}
5018
c906108c 5019static void
014f9477 5020remote_open_1 (const char *name, int from_tty,
3e43a32a 5021 struct target_ops *target, int extended_p)
c906108c 5022{
d01949b6 5023 struct remote_state *rs = get_remote_state ();
a6f3e723 5024
c906108c 5025 if (name == 0)
8a3fe4f8 5026 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 5027 "serial device is attached to the remote system\n"
8a3fe4f8 5028 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 5029
23860348 5030 /* See FIXME above. */
c6ebd6cf 5031 if (!target_async_permitted)
92d1e331 5032 wait_forever_enabled_p = 1;
6426a772 5033
2d717e4f 5034 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5035 Ask this question first, before target_preopen has a chance to kill
5036 anything. */
5d93a237 5037 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 5038 {
78a095c3
JK
5039 if (from_tty
5040 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5041 error (_("Still connected."));
5042 }
5043
78a095c3 5044 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5045 target_preopen (from_tty);
5046
89be2091 5047 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
5048 xfree (rs->last_pass_packet);
5049 rs->last_pass_packet = NULL;
89be2091 5050
9b224c5e
PA
5051 /* Make sure we send the program signals list the next time we
5052 resume. */
5e4a05c4
TT
5053 xfree (rs->last_program_signals_packet);
5054 rs->last_program_signals_packet = NULL;
9b224c5e 5055
ad9a8f3f 5056 remote_fileio_reset ();
1dd41f16
NS
5057 reopen_exec_file ();
5058 reread_symbols ();
5059
5d93a237
TT
5060 rs->remote_desc = remote_serial_open (name);
5061 if (!rs->remote_desc)
c906108c
SS
5062 perror_with_name (name);
5063
5064 if (baud_rate != -1)
5065 {
5d93a237 5066 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5067 {
9b74d5d3
KB
5068 /* The requested speed could not be set. Error out to
5069 top level after closing remote_desc. Take care to
5070 set remote_desc to NULL to avoid closing remote_desc
5071 more than once. */
5d93a237
TT
5072 serial_close (rs->remote_desc);
5073 rs->remote_desc = NULL;
c906108c
SS
5074 perror_with_name (name);
5075 }
5076 }
5077
236af5e3 5078 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5079 serial_raw (rs->remote_desc);
c906108c
SS
5080
5081 /* If there is something sitting in the buffer we might take it as a
5082 response to a command, which would be bad. */
5d93a237 5083 serial_flush_input (rs->remote_desc);
c906108c
SS
5084
5085 if (from_tty)
5086 {
5087 puts_filtered ("Remote debugging using ");
5088 puts_filtered (name);
5089 puts_filtered ("\n");
5090 }
23860348 5091 push_target (target); /* Switch to using remote target now. */
c906108c 5092
74531fed
PA
5093 /* Register extra event sources in the event loop. */
5094 remote_async_inferior_event_token
5095 = create_async_event_handler (remote_async_inferior_event_handler,
5096 NULL);
5965e028 5097 rs->notif_state = remote_notif_state_allocate ();
74531fed 5098
be2a5f71
DJ
5099 /* Reset the target state; these things will be queried either by
5100 remote_query_supported or as they are needed. */
ca4f7f8b 5101 reset_all_packet_configs_support ();
74531fed 5102 rs->cached_wait_status = 0;
be2a5f71 5103 rs->explicit_packet_size = 0;
a6f3e723 5104 rs->noack_mode = 0;
82f73884 5105 rs->extended = extended_p;
e24a49d8 5106 rs->waiting_for_stop_reply = 0;
3a29589a 5107 rs->ctrlc_pending_p = 0;
048094ac 5108 rs->got_ctrlc_during_io = 0;
802188a7 5109
47f8a51d
TT
5110 rs->general_thread = not_sent_ptid;
5111 rs->continue_thread = not_sent_ptid;
262e1174 5112 rs->remote_traceframe_number = -1;
c906108c 5113
3a00c802
PA
5114 rs->last_resume_exec_dir = EXEC_FORWARD;
5115
9d1f7ab2 5116 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5117 rs->use_threadinfo_query = 1;
5118 rs->use_threadextra_query = 1;
9d1f7ab2 5119
80152258
PA
5120 readahead_cache_invalidate ();
5121
048094ac
PA
5122 /* Start out by owning the terminal. */
5123 remote_async_terminal_ours_p = 1;
5124
c6ebd6cf 5125 if (target_async_permitted)
92d1e331 5126 {
92d1e331
DJ
5127 /* FIXME: cagney/1999-09-23: During the initial connection it is
5128 assumed that the target is already ready and able to respond to
0df8b418 5129 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5130 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5131 around this. Eventually a mechanism that allows
92d1e331 5132 wait_for_inferior() to expect/get timeouts will be
23860348 5133 implemented. */
92d1e331
DJ
5134 wait_forever_enabled_p = 0;
5135 }
5136
23860348 5137 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5138 no_shared_libraries (NULL, 0);
f78f6cf1 5139
74531fed
PA
5140 /* Start afresh. */
5141 init_thread_list ();
5142
36918e70 5143 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5144 target (we'd otherwise be in an inconsistent state) and then
5145 propogate the error on up the exception chain. This ensures that
5146 the caller doesn't stumble along blindly assuming that the
5147 function succeeded. The CLI doesn't have this problem but other
5148 UI's, such as MI do.
36918e70
AC
5149
5150 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5151 this function should return an error indication letting the
ce2826aa 5152 caller restore the previous state. Unfortunately the command
36918e70
AC
5153 ``target remote'' is directly wired to this function making that
5154 impossible. On a positive note, the CLI side of this problem has
5155 been fixed - the function set_cmd_context() makes it possible for
5156 all the ``target ....'' commands to share a common callback
5157 function. See cli-dump.c. */
109c3e39 5158 {
2d717e4f 5159
492d29ea 5160 TRY
04bd08de
TT
5161 {
5162 remote_start_remote (from_tty, target, extended_p);
5163 }
492d29ea 5164 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5165 {
c8d104ad
PA
5166 /* Pop the partially set up target - unless something else did
5167 already before throwing the exception. */
5d93a237 5168 if (rs->remote_desc != NULL)
78a095c3 5169 remote_unpush_target ();
c6ebd6cf 5170 if (target_async_permitted)
109c3e39
AC
5171 wait_forever_enabled_p = 1;
5172 throw_exception (ex);
5173 }
492d29ea 5174 END_CATCH
109c3e39 5175 }
c906108c 5176
f4abbc16
MM
5177 remote_btrace_reset ();
5178
c6ebd6cf 5179 if (target_async_permitted)
92d1e331 5180 wait_forever_enabled_p = 1;
43ff13b4
JM
5181}
5182
de0d863e
DB
5183/* Detach the specified process. */
5184
5185static void
5186remote_detach_pid (int pid)
5187{
5188 struct remote_state *rs = get_remote_state ();
5189
5190 if (remote_multi_process_p (rs))
5191 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5192 else
5193 strcpy (rs->buf, "D");
5194
5195 putpkt (rs->buf);
5196 getpkt (&rs->buf, &rs->buf_size, 0);
5197
5198 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5199 ;
5200 else if (rs->buf[0] == '\0')
5201 error (_("Remote doesn't know how to detach"));
5202 else
5203 error (_("Can't detach process."));
5204}
5205
5206/* This detaches a program to which we previously attached, using
5207 inferior_ptid to identify the process. After this is done, GDB
5208 can be used to debug some other program. We better not have left
5209 any breakpoints in the target program or it'll die when it hits
5210 one. */
c906108c
SS
5211
5212static void
de0d863e 5213remote_detach_1 (const char *args, int from_tty)
c906108c 5214{
82f73884 5215 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5216 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5217 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5218 int is_fork_parent;
c906108c
SS
5219
5220 if (args)
8a3fe4f8 5221 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 5222
2d717e4f
DJ
5223 if (!target_has_execution)
5224 error (_("No process to detach from."));
5225
0f48b757 5226 target_announce_detach (from_tty);
7cee1e54 5227
c906108c 5228 /* Tell the remote target to detach. */
de0d863e 5229 remote_detach_pid (pid);
82f73884 5230
8020350c
DB
5231 /* Exit only if this is the only active inferior. */
5232 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5233 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5234
de0d863e
DB
5235 /* Check to see if we are detaching a fork parent. Note that if we
5236 are detaching a fork child, tp == NULL. */
5237 is_fork_parent = (tp != NULL
5238 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5239
5240 /* If doing detach-on-fork, we don't mourn, because that will delete
5241 breakpoints that should be available for the followed inferior. */
5242 if (!is_fork_parent)
bc1e6c81 5243 target_mourn_inferior (inferior_ptid);
de0d863e
DB
5244 else
5245 {
5246 inferior_ptid = null_ptid;
5247 detach_inferior (pid);
5248 }
2d717e4f
DJ
5249}
5250
5251static void
52554a0e 5252remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5253{
de0d863e 5254 remote_detach_1 (args, from_tty);
2d717e4f
DJ
5255}
5256
5257static void
52554a0e 5258extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5259{
de0d863e
DB
5260 remote_detach_1 (args, from_tty);
5261}
5262
5263/* Target follow-fork function for remote targets. On entry, and
5264 at return, the current inferior is the fork parent.
5265
5266 Note that although this is currently only used for extended-remote,
5267 it is named remote_follow_fork in anticipation of using it for the
5268 remote target as well. */
5269
5270static int
5271remote_follow_fork (struct target_ops *ops, int follow_child,
5272 int detach_fork)
5273{
5274 struct remote_state *rs = get_remote_state ();
c269dbdb 5275 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5276
c269dbdb
DB
5277 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5278 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5279 {
5280 /* When following the parent and detaching the child, we detach
5281 the child here. For the case of following the child and
5282 detaching the parent, the detach is done in the target-
5283 independent follow fork code in infrun.c. We can't use
5284 target_detach when detaching an unfollowed child because
5285 the client side doesn't know anything about the child. */
5286 if (detach_fork && !follow_child)
5287 {
5288 /* Detach the fork child. */
5289 ptid_t child_ptid;
5290 pid_t child_pid;
5291
5292 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5293 child_pid = ptid_get_pid (child_ptid);
5294
5295 remote_detach_pid (child_pid);
5296 detach_inferior (child_pid);
5297 }
5298 }
5299 return 0;
c906108c
SS
5300}
5301
94585166
DB
5302/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5303 in the program space of the new inferior. On entry and at return the
5304 current inferior is the exec'ing inferior. INF is the new exec'd
5305 inferior, which may be the same as the exec'ing inferior unless
5306 follow-exec-mode is "new". */
5307
5308static void
5309remote_follow_exec (struct target_ops *ops,
5310 struct inferior *inf, char *execd_pathname)
5311{
5312 /* We know that this is a target file name, so if it has the "target:"
5313 prefix we strip it off before saving it in the program space. */
5314 if (is_target_filename (execd_pathname))
5315 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5316
5317 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5318}
5319
6ad8ae5c
DJ
5320/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5321
43ff13b4 5322static void
fee354ee 5323remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5324{
43ff13b4 5325 if (args)
2d717e4f 5326 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5327
8020350c
DB
5328 /* Make sure we unpush even the extended remote targets. Calling
5329 target_mourn_inferior won't unpush, and remote_mourn won't
5330 unpush if there is more than one inferior left. */
5331 unpush_target (target);
5332 generic_mourn_inferior ();
2d717e4f 5333
43ff13b4
JM
5334 if (from_tty)
5335 puts_filtered ("Ending remote debugging.\n");
5336}
5337
2d717e4f
DJ
5338/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5339 be chatty about it. */
5340
5341static void
20f796c9
GB
5342extended_remote_attach (struct target_ops *target, const char *args,
5343 int from_tty)
2d717e4f
DJ
5344{
5345 struct remote_state *rs = get_remote_state ();
be86555c 5346 int pid;
96ef3384 5347 char *wait_status = NULL;
2d717e4f 5348
74164c56 5349 pid = parse_pid_to_attach (args);
2d717e4f 5350
74164c56
JK
5351 /* Remote PID can be freely equal to getpid, do not check it here the same
5352 way as in other targets. */
2d717e4f 5353
4082afcc 5354 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5355 error (_("This target does not support attaching to a process"));
5356
7cee1e54
PA
5357 if (from_tty)
5358 {
5359 char *exec_file = get_exec_file (0);
5360
5361 if (exec_file)
5362 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5363 target_pid_to_str (pid_to_ptid (pid)));
5364 else
5365 printf_unfiltered (_("Attaching to %s\n"),
5366 target_pid_to_str (pid_to_ptid (pid)));
5367
5368 gdb_flush (gdb_stdout);
5369 }
5370
bba74b36 5371 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5372 putpkt (rs->buf);
5373 getpkt (&rs->buf, &rs->buf_size, 0);
5374
4082afcc
PA
5375 switch (packet_ok (rs->buf,
5376 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5377 {
4082afcc 5378 case PACKET_OK:
6efcd9a8 5379 if (!target_is_non_stop_p ())
74531fed
PA
5380 {
5381 /* Save the reply for later. */
224c3ddb 5382 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5383 strcpy (wait_status, rs->buf);
5384 }
5385 else if (strcmp (rs->buf, "OK") != 0)
5386 error (_("Attaching to %s failed with: %s"),
5387 target_pid_to_str (pid_to_ptid (pid)),
5388 rs->buf);
4082afcc
PA
5389 break;
5390 case PACKET_UNKNOWN:
5391 error (_("This target does not support attaching to a process"));
5392 default:
5393 error (_("Attaching to %s failed"),
5394 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5395 }
2d717e4f 5396
1b6e6f5c 5397 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5398
2d717e4f 5399 inferior_ptid = pid_to_ptid (pid);
79d7f229 5400
6efcd9a8 5401 if (target_is_non_stop_p ())
bad34192
PA
5402 {
5403 struct thread_info *thread;
79d7f229 5404
bad34192 5405 /* Get list of threads. */
e8032dde 5406 remote_update_thread_list (target);
82f73884 5407
bad34192
PA
5408 thread = first_thread_of_process (pid);
5409 if (thread)
5410 inferior_ptid = thread->ptid;
5411 else
5412 inferior_ptid = pid_to_ptid (pid);
5413
5414 /* Invalidate our notion of the remote current thread. */
47f8a51d 5415 record_currthread (rs, minus_one_ptid);
bad34192 5416 }
74531fed 5417 else
bad34192
PA
5418 {
5419 /* Now, if we have thread information, update inferior_ptid. */
5420 inferior_ptid = remote_current_thread (inferior_ptid);
5421
5422 /* Add the main thread to the thread list. */
5423 add_thread_silent (inferior_ptid);
5424 }
c0a2216e 5425
96ef3384
UW
5426 /* Next, if the target can specify a description, read it. We do
5427 this before anything involving memory or registers. */
5428 target_find_description ();
5429
6efcd9a8 5430 if (!target_is_non_stop_p ())
74531fed
PA
5431 {
5432 /* Use the previously fetched status. */
5433 gdb_assert (wait_status != NULL);
5434
5435 if (target_can_async_p ())
5436 {
722247f1
YQ
5437 struct notif_event *reply
5438 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5439
722247f1 5440 push_stop_reply ((struct stop_reply *) reply);
74531fed 5441
6a3753b3 5442 target_async (1);
74531fed
PA
5443 }
5444 else
5445 {
5446 gdb_assert (wait_status != NULL);
5447 strcpy (rs->buf, wait_status);
5448 rs->cached_wait_status = 1;
5449 }
5450 }
5451 else
5452 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5453}
5454
b9c1d481
AS
5455/* Implementation of the to_post_attach method. */
5456
5457static void
5458extended_remote_post_attach (struct target_ops *ops, int pid)
5459{
6efcd9a8
PA
5460 /* Get text, data & bss offsets. */
5461 get_offsets ();
5462
b9c1d481
AS
5463 /* In certain cases GDB might not have had the chance to start
5464 symbol lookup up until now. This could happen if the debugged
5465 binary is not using shared libraries, the vsyscall page is not
5466 present (on Linux) and the binary itself hadn't changed since the
5467 debugging process was started. */
5468 if (symfile_objfile != NULL)
5469 remote_check_symbols();
5470}
5471
c906108c 5472\f
506fb367
DJ
5473/* Check for the availability of vCont. This function should also check
5474 the response. */
c906108c
SS
5475
5476static void
6d820c5c 5477remote_vcont_probe (struct remote_state *rs)
c906108c 5478{
2e9f7625 5479 char *buf;
6d820c5c 5480
2e9f7625
DJ
5481 strcpy (rs->buf, "vCont?");
5482 putpkt (rs->buf);
6d820c5c 5483 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5484 buf = rs->buf;
c906108c 5485
506fb367 5486 /* Make sure that the features we assume are supported. */
61012eef 5487 if (startswith (buf, "vCont"))
506fb367
DJ
5488 {
5489 char *p = &buf[5];
750ce8d1 5490 int support_c, support_C;
506fb367 5491
750ce8d1
YQ
5492 rs->supports_vCont.s = 0;
5493 rs->supports_vCont.S = 0;
506fb367
DJ
5494 support_c = 0;
5495 support_C = 0;
d458bd84 5496 rs->supports_vCont.t = 0;
c1e36e3e 5497 rs->supports_vCont.r = 0;
506fb367
DJ
5498 while (p && *p == ';')
5499 {
5500 p++;
5501 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5502 rs->supports_vCont.s = 1;
506fb367 5503 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5504 rs->supports_vCont.S = 1;
506fb367
DJ
5505 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5506 support_c = 1;
5507 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5508 support_C = 1;
74531fed 5509 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5510 rs->supports_vCont.t = 1;
c1e36e3e
PA
5511 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5512 rs->supports_vCont.r = 1;
506fb367
DJ
5513
5514 p = strchr (p, ';');
5515 }
c906108c 5516
750ce8d1
YQ
5517 /* If c, and C are not all supported, we can't use vCont. Clearing
5518 BUF will make packet_ok disable the packet. */
5519 if (!support_c || !support_C)
506fb367
DJ
5520 buf[0] = 0;
5521 }
c906108c 5522
444abaca 5523 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5524}
c906108c 5525
0d8f58ca
PA
5526/* Helper function for building "vCont" resumptions. Write a
5527 resumption to P. ENDP points to one-passed-the-end of the buffer
5528 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5529 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5530 resumed thread should be single-stepped and/or signalled. If PTID
5531 equals minus_one_ptid, then all threads are resumed; if PTID
5532 represents a process, then all threads of the process are resumed;
5533 the thread to be stepped and/or signalled is given in the global
5534 INFERIOR_PTID. */
5535
5536static char *
5537append_resumption (char *p, char *endp,
2ea28649 5538 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5539{
5540 struct remote_state *rs = get_remote_state ();
5541
a493e3e2 5542 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5543 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5544 else if (step
5545 /* GDB is willing to range step. */
5546 && use_range_stepping
5547 /* Target supports range stepping. */
5548 && rs->supports_vCont.r
5549 /* We don't currently support range stepping multiple
5550 threads with a wildcard (though the protocol allows it,
5551 so stubs shouldn't make an active effort to forbid
5552 it). */
5553 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5554 {
5555 struct thread_info *tp;
5556
5557 if (ptid_equal (ptid, minus_one_ptid))
5558 {
5559 /* If we don't know about the target thread's tid, then
5560 we're resuming magic_null_ptid (see caller). */
5561 tp = find_thread_ptid (magic_null_ptid);
5562 }
5563 else
5564 tp = find_thread_ptid (ptid);
5565 gdb_assert (tp != NULL);
5566
5567 if (tp->control.may_range_step)
5568 {
5569 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5570
5571 p += xsnprintf (p, endp - p, ";r%s,%s",
5572 phex_nz (tp->control.step_range_start,
5573 addr_size),
5574 phex_nz (tp->control.step_range_end,
5575 addr_size));
5576 }
5577 else
5578 p += xsnprintf (p, endp - p, ";s");
5579 }
0d8f58ca
PA
5580 else if (step)
5581 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5582 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5583 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5584 else
5585 p += xsnprintf (p, endp - p, ";c");
5586
5587 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5588 {
5589 ptid_t nptid;
5590
5591 /* All (-1) threads of process. */
ba348170 5592 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5593
5594 p += xsnprintf (p, endp - p, ":");
5595 p = write_ptid (p, endp, nptid);
5596 }
5597 else if (!ptid_equal (ptid, minus_one_ptid))
5598 {
5599 p += xsnprintf (p, endp - p, ":");
5600 p = write_ptid (p, endp, ptid);
5601 }
5602
5603 return p;
5604}
5605
799a2abe
PA
5606/* Clear the thread's private info on resume. */
5607
5608static void
5609resume_clear_thread_private_info (struct thread_info *thread)
5610{
5611 if (thread->priv != NULL)
5612 {
5613 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5614 thread->priv->watch_data_address = 0;
5615 }
5616}
5617
e5ef252a
PA
5618/* Append a vCont continue-with-signal action for threads that have a
5619 non-zero stop signal. */
5620
5621static char *
5622append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5623{
5624 struct thread_info *thread;
5625
034f788c 5626 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5627 if (ptid_match (thread->ptid, ptid)
5628 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5629 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5630 {
5631 p = append_resumption (p, endp, thread->ptid,
5632 0, thread->suspend.stop_signal);
5633 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5634 resume_clear_thread_private_info (thread);
e5ef252a
PA
5635 }
5636
5637 return p;
5638}
5639
7b68ffbb
PA
5640/* Set the target running, using the packets that use Hc
5641 (c/s/C/S). */
5642
5643static void
5644remote_resume_with_hc (struct target_ops *ops,
5645 ptid_t ptid, int step, enum gdb_signal siggnal)
5646{
5647 struct remote_state *rs = get_remote_state ();
5648 struct thread_info *thread;
5649 char *buf;
5650
5651 rs->last_sent_signal = siggnal;
5652 rs->last_sent_step = step;
5653
5654 /* The c/s/C/S resume packets use Hc, so set the continue
5655 thread. */
5656 if (ptid_equal (ptid, minus_one_ptid))
5657 set_continue_thread (any_thread_ptid);
5658 else
5659 set_continue_thread (ptid);
5660
5661 ALL_NON_EXITED_THREADS (thread)
5662 resume_clear_thread_private_info (thread);
5663
5664 buf = rs->buf;
5665 if (execution_direction == EXEC_REVERSE)
5666 {
5667 /* We don't pass signals to the target in reverse exec mode. */
5668 if (info_verbose && siggnal != GDB_SIGNAL_0)
5669 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5670 siggnal);
5671
5672 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5673 error (_("Remote reverse-step not supported."));
5674 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5675 error (_("Remote reverse-continue not supported."));
5676
5677 strcpy (buf, step ? "bs" : "bc");
5678 }
5679 else if (siggnal != GDB_SIGNAL_0)
5680 {
5681 buf[0] = step ? 'S' : 'C';
5682 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5683 buf[2] = tohex (((int) siggnal) & 0xf);
5684 buf[3] = '\0';
5685 }
5686 else
5687 strcpy (buf, step ? "s" : "c");
5688
5689 putpkt (buf);
5690}
5691
506fb367
DJ
5692/* Resume the remote inferior by using a "vCont" packet. The thread
5693 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5694 resumed thread should be single-stepped and/or signalled. If PTID
5695 equals minus_one_ptid, then all threads are resumed; the thread to
5696 be stepped and/or signalled is given in the global INFERIOR_PTID.
5697 This function returns non-zero iff it resumes the inferior.
44eaed12 5698
7b68ffbb
PA
5699 This function issues a strict subset of all possible vCont commands
5700 at the moment. */
44eaed12 5701
506fb367 5702static int
7b68ffbb 5703remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5704{
5705 struct remote_state *rs = get_remote_state ();
82f73884
PA
5706 char *p;
5707 char *endp;
44eaed12 5708
7b68ffbb
PA
5709 /* No reverse execution actions defined for vCont. */
5710 if (execution_direction == EXEC_REVERSE)
5711 return 0;
5712
4082afcc 5713 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5714 remote_vcont_probe (rs);
44eaed12 5715
4082afcc 5716 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5717 return 0;
44eaed12 5718
82f73884
PA
5719 p = rs->buf;
5720 endp = rs->buf + get_remote_packet_size ();
5721
506fb367
DJ
5722 /* If we could generate a wider range of packets, we'd have to worry
5723 about overflowing BUF. Should there be a generic
5724 "multi-part-packet" packet? */
5725
0d8f58ca
PA
5726 p += xsnprintf (p, endp - p, "vCont");
5727
79d7f229 5728 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5729 {
79d7f229
PA
5730 /* MAGIC_NULL_PTID means that we don't have any active threads,
5731 so we don't have any TID numbers the inferior will
5732 understand. Make sure to only send forms that do not specify
5733 a TID. */
a9cbf802 5734 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5735 }
0d8f58ca 5736 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5737 {
0d8f58ca
PA
5738 /* Resume all threads (of all processes, or of a single
5739 process), with preference for INFERIOR_PTID. This assumes
5740 inferior_ptid belongs to the set of all threads we are about
5741 to resume. */
a493e3e2 5742 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5743 {
0d8f58ca
PA
5744 /* Step inferior_ptid, with or without signal. */
5745 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5746 }
0d8f58ca 5747
e5ef252a
PA
5748 /* Also pass down any pending signaled resumption for other
5749 threads not the current. */
5750 p = append_pending_thread_resumptions (p, endp, ptid);
5751
0d8f58ca 5752 /* And continue others without a signal. */
a493e3e2 5753 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5754 }
5755 else
506fb367
DJ
5756 {
5757 /* Scheduler locking; resume only PTID. */
a9cbf802 5758 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5759 }
c906108c 5760
82f73884
PA
5761 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5762 putpkt (rs->buf);
506fb367 5763
6efcd9a8 5764 if (target_is_non_stop_p ())
74531fed
PA
5765 {
5766 /* In non-stop, the stub replies to vCont with "OK". The stop
5767 reply will be reported asynchronously by means of a `%Stop'
5768 notification. */
5769 getpkt (&rs->buf, &rs->buf_size, 0);
5770 if (strcmp (rs->buf, "OK") != 0)
5771 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5772 }
5773
506fb367 5774 return 1;
c906108c 5775}
43ff13b4 5776
506fb367
DJ
5777/* Tell the remote machine to resume. */
5778
43ff13b4 5779static void
28439f5e 5780remote_resume (struct target_ops *ops,
2ea28649 5781 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5782{
d01949b6 5783 struct remote_state *rs = get_remote_state ();
43ff13b4 5784
85ad3aaf
PA
5785 /* When connected in non-stop mode, the core resumes threads
5786 individually. Resuming remote threads directly in target_resume
5787 would thus result in sending one packet per thread. Instead, to
5788 minimize roundtrip latency, here we just store the resume
5789 request; the actual remote resumption will be done in
5790 target_commit_resume / remote_commit_resume, where we'll be able
5791 to do vCont action coalescing. */
5792 if (target_is_non_stop_p () && execution_direction != EXEC_REVERSE)
5793 {
5794 struct private_thread_info *remote_thr;
5795
5796 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5797 remote_thr = get_private_info_ptid (inferior_ptid);
5798 else
5799 remote_thr = get_private_info_ptid (ptid);
5800 remote_thr->last_resume_step = step;
5801 remote_thr->last_resume_sig = siggnal;
5802 return;
5803 }
5804
722247f1
YQ
5805 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5806 (explained in remote-notif.c:handle_notification) so
5807 remote_notif_process is not called. We need find a place where
5808 it is safe to start a 'vNotif' sequence. It is good to do it
5809 before resuming inferior, because inferior was stopped and no RSP
5810 traffic at that moment. */
6efcd9a8 5811 if (!target_is_non_stop_p ())
5965e028 5812 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5813
3a00c802
PA
5814 rs->last_resume_exec_dir = execution_direction;
5815
7b68ffbb
PA
5816 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
5817 if (!remote_resume_with_vcont (ptid, step, siggnal))
5818 remote_resume_with_hc (ops, ptid, step, siggnal);
43ff13b4 5819
2acceee2 5820 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5821 with the event loop. NOTE: this is the one place where all the
5822 execution commands end up. We could alternatively do this in each
23860348 5823 of the execution commands in infcmd.c. */
2acceee2
JM
5824 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5825 into infcmd.c in order to allow inferior function calls to work
23860348 5826 NOT asynchronously. */
362646f5 5827 if (target_can_async_p ())
6a3753b3 5828 target_async (1);
e24a49d8
PA
5829
5830 /* We've just told the target to resume. The remote server will
5831 wait for the inferior to stop, and then send a stop reply. In
5832 the mean time, we can't start another command/query ourselves
74531fed
PA
5833 because the stub wouldn't be ready to process it. This applies
5834 only to the base all-stop protocol, however. In non-stop (which
5835 only supports vCont), the stub replies with an "OK", and is
5836 immediate able to process further serial input. */
6efcd9a8 5837 if (!target_is_non_stop_p ())
74531fed 5838 rs->waiting_for_stop_reply = 1;
43ff13b4 5839}
85ad3aaf
PA
5840
5841static void check_pending_events_prevent_wildcard_vcont
5842 (int *may_global_wildcard_vcont);
5843static int is_pending_fork_parent_thread (struct thread_info *thread);
5844
5845/* Private per-inferior info for target remote processes. */
5846
5847struct private_inferior
5848{
5849 /* Whether we can send a wildcard vCont for this process. */
5850 int may_wildcard_vcont;
5851};
5852
5853/* Structure used to track the construction of a vCont packet in the
5854 outgoing packet buffer. This is used to send multiple vCont
5855 packets if we have more actions than would fit a single packet. */
5856
5857struct vcont_builder
5858{
5859 /* Pointer to the first action. P points here if no action has been
5860 appended yet. */
5861 char *first_action;
5862
5863 /* Where the next action will be appended. */
5864 char *p;
5865
5866 /* The end of the buffer. Must never write past this. */
5867 char *endp;
5868};
5869
5870/* Prepare the outgoing buffer for a new vCont packet. */
5871
5872static void
5873vcont_builder_restart (struct vcont_builder *builder)
5874{
5875 struct remote_state *rs = get_remote_state ();
5876
5877 builder->p = rs->buf;
5878 builder->endp = rs->buf + get_remote_packet_size ();
5879 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
5880 builder->first_action = builder->p;
5881}
5882
5883/* If the vCont packet being built has any action, send it to the
5884 remote end. */
5885
5886static void
5887vcont_builder_flush (struct vcont_builder *builder)
5888{
5889 struct remote_state *rs;
5890
5891 if (builder->p == builder->first_action)
5892 return;
5893
5894 rs = get_remote_state ();
5895 putpkt (rs->buf);
5896 getpkt (&rs->buf, &rs->buf_size, 0);
5897 if (strcmp (rs->buf, "OK") != 0)
5898 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5899}
5900
5901/* The largest action is range-stepping, with its two addresses. This
5902 is more than sufficient. If a new, bigger action is created, it'll
5903 quickly trigger a failed assertion in append_resumption (and we'll
5904 just bump this). */
5905#define MAX_ACTION_SIZE 200
5906
5907/* Append a new vCont action in the outgoing packet being built. If
5908 the action doesn't fit the packet along with previous actions, push
5909 what we've got so far to the remote end and start over a new vCont
5910 packet (with the new action). */
5911
5912static void
5913vcont_builder_push_action (struct vcont_builder *builder,
5914 ptid_t ptid, int step, enum gdb_signal siggnal)
5915{
5916 char buf[MAX_ACTION_SIZE + 1];
5917 char *endp;
5918 size_t rsize;
5919
5920 endp = append_resumption (buf, buf + sizeof (buf),
5921 ptid, step, siggnal);
5922
5923 /* Check whether this new action would fit in the vCont packet along
5924 with previous actions. If not, send what we've got so far and
5925 start a new vCont packet. */
5926 rsize = endp - buf;
5927 if (rsize > builder->endp - builder->p)
5928 {
5929 vcont_builder_flush (builder);
5930 vcont_builder_restart (builder);
5931
5932 /* Should now fit. */
5933 gdb_assert (rsize <= builder->endp - builder->p);
5934 }
5935
5936 memcpy (builder->p, buf, rsize);
5937 builder->p += rsize;
5938 *builder->p = '\0';
5939}
5940
5941/* to_commit_resume implementation. */
5942
5943static void
5944remote_commit_resume (struct target_ops *ops)
5945{
5946 struct remote_state *rs = get_remote_state ();
5947 struct inferior *inf;
5948 struct thread_info *tp;
5949 int any_process_wildcard;
5950 int may_global_wildcard_vcont;
5951 struct vcont_builder vcont_builder;
5952
5953 /* If connected in all-stop mode, we'd send the remote resume
5954 request directly from remote_resume. Likewise if
5955 reverse-debugging, as there are no defined vCont actions for
5956 reverse execution. */
5957 if (!target_is_non_stop_p () || execution_direction == EXEC_REVERSE)
5958 return;
5959
5960 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
5961 instead of resuming all threads of each process individually.
5962 However, if any thread of a process must remain halted, we can't
5963 send wildcard resumes and must send one action per thread.
5964
5965 Care must be taken to not resume threads/processes the server
5966 side already told us are stopped, but the core doesn't know about
5967 yet, because the events are still in the vStopped notification
5968 queue. For example:
5969
5970 #1 => vCont s:p1.1;c
5971 #2 <= OK
5972 #3 <= %Stopped T05 p1.1
5973 #4 => vStopped
5974 #5 <= T05 p1.2
5975 #6 => vStopped
5976 #7 <= OK
5977 #8 (infrun handles the stop for p1.1 and continues stepping)
5978 #9 => vCont s:p1.1;c
5979
5980 The last vCont above would resume thread p1.2 by mistake, because
5981 the server has no idea that the event for p1.2 had not been
5982 handled yet.
5983
5984 The server side must similarly ignore resume actions for the
5985 thread that has a pending %Stopped notification (and any other
5986 threads with events pending), until GDB acks the notification
5987 with vStopped. Otherwise, e.g., the following case is
5988 mishandled:
5989
5990 #1 => g (or any other packet)
5991 #2 <= [registers]
5992 #3 <= %Stopped T05 p1.2
5993 #4 => vCont s:p1.1;c
5994 #5 <= OK
5995
5996 Above, the server must not resume thread p1.2. GDB can't know
5997 that p1.2 stopped until it acks the %Stopped notification, and
5998 since from GDB's perspective all threads should be running, it
5999 sends a "c" action.
6000
6001 Finally, special care must also be given to handling fork/vfork
6002 events. A (v)fork event actually tells us that two processes
6003 stopped -- the parent and the child. Until we follow the fork,
6004 we must not resume the child. Therefore, if we have a pending
6005 fork follow, we must not send a global wildcard resume action
6006 (vCont;c). We can still send process-wide wildcards though. */
6007
6008 /* Start by assuming a global wildcard (vCont;c) is possible. */
6009 may_global_wildcard_vcont = 1;
6010
6011 /* And assume every process is individually wildcard-able too. */
6012 ALL_NON_EXITED_INFERIORS (inf)
6013 {
6014 if (inf->priv == NULL)
6015 inf->priv = XNEW (struct private_inferior);
6016 inf->priv->may_wildcard_vcont = 1;
6017 }
6018
6019 /* Check for any pending events (not reported or processed yet) and
6020 disable process and global wildcard resumes appropriately. */
6021 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6022
6023 ALL_NON_EXITED_THREADS (tp)
6024 {
6025 /* If a thread of a process is not meant to be resumed, then we
6026 can't wildcard that process. */
6027 if (!tp->executing)
6028 {
6029 tp->inf->priv->may_wildcard_vcont = 0;
6030
6031 /* And if we can't wildcard a process, we can't wildcard
6032 everything either. */
6033 may_global_wildcard_vcont = 0;
6034 continue;
6035 }
6036
6037 /* If a thread is the parent of an unfollowed fork, then we
6038 can't do a global wildcard, as that would resume the fork
6039 child. */
6040 if (is_pending_fork_parent_thread (tp))
6041 may_global_wildcard_vcont = 0;
6042 }
6043
6044 /* Now let's build the vCont packet(s). Actions must be appended
6045 from narrower to wider scopes (thread -> process -> global). If
6046 we end up with too many actions for a single packet vcont_builder
6047 flushes the current vCont packet to the remote side and starts a
6048 new one. */
6049 vcont_builder_restart (&vcont_builder);
6050
6051 /* Threads first. */
6052 ALL_NON_EXITED_THREADS (tp)
6053 {
6054 struct private_thread_info *remote_thr = tp->priv;
6055
6056 if (!tp->executing || remote_thr->vcont_resumed)
6057 continue;
6058
6059 gdb_assert (!thread_is_in_step_over_chain (tp));
6060
6061 if (!remote_thr->last_resume_step
6062 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6063 && tp->inf->priv->may_wildcard_vcont)
6064 {
6065 /* We'll send a wildcard resume instead. */
6066 remote_thr->vcont_resumed = 1;
6067 continue;
6068 }
6069
6070 vcont_builder_push_action (&vcont_builder, tp->ptid,
6071 remote_thr->last_resume_step,
6072 remote_thr->last_resume_sig);
6073 remote_thr->vcont_resumed = 1;
6074 }
6075
6076 /* Now check whether we can send any process-wide wildcard. This is
6077 to avoid sending a global wildcard in the case nothing is
6078 supposed to be resumed. */
6079 any_process_wildcard = 0;
6080
6081 ALL_NON_EXITED_INFERIORS (inf)
6082 {
6083 if (inf->priv->may_wildcard_vcont)
6084 {
6085 any_process_wildcard = 1;
6086 break;
6087 }
6088 }
6089
6090 if (any_process_wildcard)
6091 {
6092 /* If all processes are wildcard-able, then send a single "c"
6093 action, otherwise, send an "all (-1) threads of process"
6094 continue action for each running process, if any. */
6095 if (may_global_wildcard_vcont)
6096 {
6097 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6098 0, GDB_SIGNAL_0);
6099 }
6100 else
6101 {
6102 ALL_NON_EXITED_INFERIORS (inf)
6103 {
6104 if (inf->priv->may_wildcard_vcont)
6105 {
6106 vcont_builder_push_action (&vcont_builder,
6107 pid_to_ptid (inf->pid),
6108 0, GDB_SIGNAL_0);
6109 }
6110 }
6111 }
6112 }
6113
6114 vcont_builder_flush (&vcont_builder);
6115}
6116
c906108c 6117\f
43ff13b4 6118
74531fed
PA
6119/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6120 thread, all threads of a remote process, or all threads of all
6121 processes. */
6122
6123static void
6124remote_stop_ns (ptid_t ptid)
6125{
6126 struct remote_state *rs = get_remote_state ();
6127 char *p = rs->buf;
6128 char *endp = rs->buf + get_remote_packet_size ();
74531fed 6129
4082afcc 6130 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
6131 remote_vcont_probe (rs);
6132
d458bd84 6133 if (!rs->supports_vCont.t)
74531fed
PA
6134 error (_("Remote server does not support stopping threads"));
6135
f91d3df5
PA
6136 if (ptid_equal (ptid, minus_one_ptid)
6137 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
6138 p += xsnprintf (p, endp - p, "vCont;t");
6139 else
6140 {
6141 ptid_t nptid;
6142
74531fed
PA
6143 p += xsnprintf (p, endp - p, "vCont;t:");
6144
6145 if (ptid_is_pid (ptid))
6146 /* All (-1) threads of process. */
ba348170 6147 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
6148 else
6149 {
6150 /* Small optimization: if we already have a stop reply for
6151 this thread, no use in telling the stub we want this
6152 stopped. */
6153 if (peek_stop_reply (ptid))
6154 return;
6155
6156 nptid = ptid;
6157 }
6158
a9cbf802 6159 write_ptid (p, endp, nptid);
74531fed
PA
6160 }
6161
6162 /* In non-stop, we get an immediate OK reply. The stop reply will
6163 come in asynchronously by notification. */
6164 putpkt (rs->buf);
6165 getpkt (&rs->buf, &rs->buf_size, 0);
6166 if (strcmp (rs->buf, "OK") != 0)
6167 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6168}
6169
bfedc46a
PA
6170/* All-stop version of target_interrupt. Sends a break or a ^C to
6171 interrupt the remote target. It is undefined which thread of which
6172 process reports the interrupt. */
74531fed
PA
6173
6174static void
de979965 6175remote_interrupt_as (void)
74531fed
PA
6176{
6177 struct remote_state *rs = get_remote_state ();
6178
3a29589a
DJ
6179 rs->ctrlc_pending_p = 1;
6180
74531fed
PA
6181 /* If the inferior is stopped already, but the core didn't know
6182 about it yet, just ignore the request. The cached wait status
6183 will be collected in remote_wait. */
6184 if (rs->cached_wait_status)
6185 return;
6186
9a7071a8
JB
6187 /* Send interrupt_sequence to remote target. */
6188 send_interrupt_sequence ();
74531fed
PA
6189}
6190
de979965
PA
6191/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6192 the remote target. It is undefined which thread of which process
e42de8c7
PA
6193 reports the interrupt. Throws an error if the packet is not
6194 supported by the server. */
de979965 6195
e42de8c7 6196static void
de979965
PA
6197remote_interrupt_ns (void)
6198{
6199 struct remote_state *rs = get_remote_state ();
6200 char *p = rs->buf;
6201 char *endp = rs->buf + get_remote_packet_size ();
6202
6203 xsnprintf (p, endp - p, "vCtrlC");
6204
6205 /* In non-stop, we get an immediate OK reply. The stop reply will
6206 come in asynchronously by notification. */
6207 putpkt (rs->buf);
6208 getpkt (&rs->buf, &rs->buf_size, 0);
6209
6210 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6211 {
6212 case PACKET_OK:
6213 break;
6214 case PACKET_UNKNOWN:
e42de8c7 6215 error (_("No support for interrupting the remote target."));
de979965
PA
6216 case PACKET_ERROR:
6217 error (_("Interrupting target failed: %s"), rs->buf);
6218 }
de979965
PA
6219}
6220
bfedc46a 6221/* Implement the to_stop function for the remote targets. */
74531fed 6222
c906108c 6223static void
1eab8a48 6224remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 6225{
7a292a7a 6226 if (remote_debug)
0f71a2f6 6227 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6228
6efcd9a8 6229 if (target_is_non_stop_p ())
74531fed 6230 remote_stop_ns (ptid);
c906108c 6231 else
bfedc46a
PA
6232 {
6233 /* We don't currently have a way to transparently pause the
6234 remote target in all-stop mode. Interrupt it instead. */
de979965 6235 remote_interrupt_as ();
bfedc46a
PA
6236 }
6237}
6238
6239/* Implement the to_interrupt function for the remote targets. */
6240
6241static void
6242remote_interrupt (struct target_ops *self, ptid_t ptid)
6243{
e42de8c7
PA
6244 struct remote_state *rs = get_remote_state ();
6245
bfedc46a
PA
6246 if (remote_debug)
6247 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6248
e42de8c7
PA
6249 if (target_is_non_stop_p ())
6250 remote_interrupt_ns ();
bfedc46a 6251 else
e42de8c7 6252 remote_interrupt_as ();
c906108c
SS
6253}
6254
93692b58
PA
6255/* Implement the to_pass_ctrlc function for the remote targets. */
6256
6257static void
6258remote_pass_ctrlc (struct target_ops *self)
6259{
6260 struct remote_state *rs = get_remote_state ();
6261
6262 if (remote_debug)
6263 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6264
6265 /* If we're starting up, we're not fully synced yet. Quit
6266 immediately. */
6267 if (rs->starting_up)
6268 quit ();
6269 /* If ^C has already been sent once, offer to disconnect. */
6270 else if (rs->ctrlc_pending_p)
6271 interrupt_query ();
6272 else
6273 target_interrupt (inferior_ptid);
6274}
6275
c906108c
SS
6276/* Ask the user what to do when an interrupt is received. */
6277
6278static void
fba45db2 6279interrupt_query (void)
c906108c 6280{
abc56d60 6281 struct remote_state *rs = get_remote_state ();
c906108c 6282
abc56d60 6283 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6284 {
abc56d60
PA
6285 if (query (_("The target is not responding to interrupt requests.\n"
6286 "Stop debugging it? ")))
74531fed 6287 {
78a095c3 6288 remote_unpush_target ();
abc56d60 6289 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6290 }
6291 }
abc56d60
PA
6292 else
6293 {
6294 if (query (_("Interrupted while waiting for the program.\n"
6295 "Give up waiting? ")))
6296 quit ();
6297 }
c906108c
SS
6298}
6299
6426a772
JM
6300/* Enable/disable target terminal ownership. Most targets can use
6301 terminal groups to control terminal ownership. Remote targets are
6302 different in that explicit transfer of ownership to/from GDB/target
23860348 6303 is required. */
6426a772
JM
6304
6305static void
d2f640d4 6306remote_terminal_inferior (struct target_ops *self)
6426a772 6307{
223ffa71 6308 /* FIXME: cagney/1999-09-27: Make calls to target_terminal::*()
d9d2d8b6
PA
6309 idempotent. The event-loop GDB talking to an asynchronous target
6310 with a synchronous command calls this function from both
6311 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
6312 transfer the terminal to the target when it shouldn't this guard
6313 can go away. */
6426a772
JM
6314 if (!remote_async_terminal_ours_p)
6315 return;
6426a772 6316 remote_async_terminal_ours_p = 0;
6426a772
JM
6317 /* NOTE: At this point we could also register our selves as the
6318 recipient of all input. Any characters typed could then be
23860348 6319 passed on down to the target. */
6426a772
JM
6320}
6321
6322static void
e3594fd1 6323remote_terminal_ours (struct target_ops *self)
6426a772 6324{
75c99385 6325 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
6326 if (remote_async_terminal_ours_p)
6327 return;
6426a772
JM
6328 remote_async_terminal_ours_p = 1;
6329}
6330
176a6961 6331static void
917317f4 6332remote_console_output (char *msg)
c906108c
SS
6333{
6334 char *p;
6335
c5aa993b 6336 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6337 {
6338 char tb[2];
6339 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6340
c906108c
SS
6341 tb[0] = c;
6342 tb[1] = 0;
43ff13b4 6343 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6344 }
00db5b94
PA
6345 gdb_flush (gdb_stdtarg);
6346}
74531fed 6347
74531fed
PA
6348DEF_VEC_O(cached_reg_t);
6349
722247f1 6350typedef struct stop_reply
74531fed 6351{
722247f1 6352 struct notif_event base;
74531fed 6353
722247f1 6354 /* The identifier of the thread about this event */
74531fed
PA
6355 ptid_t ptid;
6356
340e3c99 6357 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6358 connection, represented by a remote_state object, is closed,
6359 all the associated stop_reply events should be released. */
6360 struct remote_state *rs;
6361
74531fed
PA
6362 struct target_waitstatus ws;
6363
15148d6a
PA
6364 /* Expedited registers. This makes remote debugging a bit more
6365 efficient for those targets that provide critical registers as
6366 part of their normal status mechanism (as another roundtrip to
6367 fetch them is avoided). */
74531fed
PA
6368 VEC(cached_reg_t) *regcache;
6369
f7e6eed5
PA
6370 enum target_stop_reason stop_reason;
6371
74531fed
PA
6372 CORE_ADDR watch_data_address;
6373
dc146f7c 6374 int core;
722247f1 6375} *stop_reply_p;
a744cf53 6376
722247f1
YQ
6377DECLARE_QUEUE_P (stop_reply_p);
6378DEFINE_QUEUE_P (stop_reply_p);
6379/* The list of already fetched and acknowledged stop events. This
6380 queue is used for notification Stop, and other notifications
6381 don't need queue for their events, because the notification events
6382 of Stop can't be consumed immediately, so that events should be
6383 queued first, and be consumed by remote_wait_{ns,as} one per
6384 time. Other notifications can consume their events immediately,
6385 so queue is not needed for them. */
6386static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
6387
6388static void
6389stop_reply_xfree (struct stop_reply *r)
6390{
f48ff2a7 6391 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6392}
6393
221e1a37
PA
6394/* Return the length of the stop reply queue. */
6395
6396static int
6397stop_reply_queue_length (void)
6398{
6399 return QUEUE_length (stop_reply_p, stop_reply_queue);
6400}
6401
722247f1
YQ
6402static void
6403remote_notif_stop_parse (struct notif_client *self, char *buf,
6404 struct notif_event *event)
6405{
6406 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6407}
6408
6409static void
6410remote_notif_stop_ack (struct notif_client *self, char *buf,
6411 struct notif_event *event)
6412{
6413 struct stop_reply *stop_reply = (struct stop_reply *) event;
6414
6415 /* acknowledge */
f5c4fcd9 6416 putpkt (self->ack_command);
722247f1
YQ
6417
6418 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6419 /* We got an unknown stop reply. */
6420 error (_("Unknown stop reply"));
6421
6422 push_stop_reply (stop_reply);
6423}
6424
6425static int
6426remote_notif_stop_can_get_pending_events (struct notif_client *self)
6427{
6428 /* We can't get pending events in remote_notif_process for
6429 notification stop, and we have to do this in remote_wait_ns
6430 instead. If we fetch all queued events from stub, remote stub
6431 may exit and we have no chance to process them back in
6432 remote_wait_ns. */
6433 mark_async_event_handler (remote_async_inferior_event_token);
6434 return 0;
6435}
6436
6437static void
6438stop_reply_dtr (struct notif_event *event)
6439{
6440 struct stop_reply *r = (struct stop_reply *) event;
d1dff226
AH
6441 cached_reg_t *reg;
6442 int ix;
6443
6444 for (ix = 0;
6445 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6446 ix++)
6447 xfree (reg->data);
722247f1
YQ
6448
6449 VEC_free (cached_reg_t, r->regcache);
6450}
6451
6452static struct notif_event *
6453remote_notif_stop_alloc_reply (void)
6454{
8d749320
SM
6455 /* We cast to a pointer to the "base class". */
6456 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6457
6458 r->dtr = stop_reply_dtr;
6459
6460 return r;
6461}
6462
6463/* A client of notification Stop. */
6464
6465struct notif_client notif_client_stop =
6466{
6467 "Stop",
6468 "vStopped",
6469 remote_notif_stop_parse,
6470 remote_notif_stop_ack,
6471 remote_notif_stop_can_get_pending_events,
6472 remote_notif_stop_alloc_reply,
f48ff2a7 6473 REMOTE_NOTIF_STOP,
722247f1
YQ
6474};
6475
6476/* A parameter to pass data in and out. */
6477
6478struct queue_iter_param
6479{
6480 void *input;
6481 struct stop_reply *output;
6482};
6483
85ad3aaf 6484/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6485 the pid of the process that owns the threads we want to check, or
6486 -1 if we want to check all threads. */
6487
6488static int
6489is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6490 ptid_t thread_ptid)
6491{
6492 if (ws->kind == TARGET_WAITKIND_FORKED
6493 || ws->kind == TARGET_WAITKIND_VFORKED)
6494 {
6495 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6496 return 1;
6497 }
6498
6499 return 0;
6500}
6501
85ad3aaf
PA
6502/* Return the thread's pending status used to determine whether the
6503 thread is a fork parent stopped at a fork event. */
6504
6505static struct target_waitstatus *
6506thread_pending_fork_status (struct thread_info *thread)
6507{
6508 if (thread->suspend.waitstatus_pending_p)
6509 return &thread->suspend.waitstatus;
6510 else
6511 return &thread->pending_follow;
6512}
6513
6514/* Determine if THREAD is a pending fork parent thread. */
6515
6516static int
6517is_pending_fork_parent_thread (struct thread_info *thread)
6518{
6519 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6520 int pid = -1;
6521
6522 return is_pending_fork_parent (ws, pid, thread->ptid);
6523}
6524
cbb8991c
DB
6525/* Check whether EVENT is a fork event, and if it is, remove the
6526 fork child from the context list passed in DATA. */
6527
6528static int
6529remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6530 QUEUE_ITER (stop_reply_p) *iter,
6531 stop_reply_p event,
6532 void *data)
6533{
19ba03f4
SM
6534 struct queue_iter_param *param = (struct queue_iter_param *) data;
6535 struct threads_listing_context *context
6536 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6537
6538 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6539 || event->ws.kind == TARGET_WAITKIND_VFORKED
6540 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6541 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6542
6543 return 1;
6544}
6545
6546/* If CONTEXT contains any fork child threads that have not been
6547 reported yet, remove them from the CONTEXT list. If such a
6548 thread exists it is because we are stopped at a fork catchpoint
6549 and have not yet called follow_fork, which will set up the
6550 host-side data structures for the new process. */
6551
6552static void
6553remove_new_fork_children (struct threads_listing_context *context)
6554{
6555 struct thread_info * thread;
6556 int pid = -1;
6557 struct notif_client *notif = &notif_client_stop;
6558 struct queue_iter_param param;
6559
6560 /* For any threads stopped at a fork event, remove the corresponding
6561 fork child threads from the CONTEXT list. */
6562 ALL_NON_EXITED_THREADS (thread)
6563 {
85ad3aaf 6564 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
6565
6566 if (is_pending_fork_parent (ws, pid, thread->ptid))
6567 {
6568 threads_listing_context_remove (ws, context);
6569 }
6570 }
6571
6572 /* Check for any pending fork events (not reported or processed yet)
6573 in process PID and remove those fork child threads from the
6574 CONTEXT list as well. */
6575 remote_notif_get_pending_events (notif);
6576 param.input = context;
6577 param.output = NULL;
6578 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6579 remove_child_of_pending_fork, &param);
6580}
6581
85ad3aaf
PA
6582/* Check whether EVENT would prevent a global or process wildcard
6583 vCont action. */
6584
6585static int
6586check_pending_event_prevents_wildcard_vcont_callback
6587 (QUEUE (stop_reply_p) *q,
6588 QUEUE_ITER (stop_reply_p) *iter,
6589 stop_reply_p event,
6590 void *data)
6591{
6592 struct inferior *inf;
6593 int *may_global_wildcard_vcont = (int *) data;
6594
6595 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6596 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6597 return 1;
6598
6599 if (event->ws.kind == TARGET_WAITKIND_FORKED
6600 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6601 *may_global_wildcard_vcont = 0;
6602
6603 inf = find_inferior_ptid (event->ptid);
6604
6605 /* This may be the first time we heard about this process.
6606 Regardless, we must not do a global wildcard resume, otherwise
6607 we'd resume this process too. */
6608 *may_global_wildcard_vcont = 0;
6609 if (inf != NULL)
6610 inf->priv->may_wildcard_vcont = 0;
6611
6612 return 1;
6613}
6614
6615/* Check whether any event pending in the vStopped queue would prevent
6616 a global or process wildcard vCont action. Clear
6617 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6618 and clear the event inferior's may_wildcard_vcont flag if we can't
6619 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6620
6621static void
6622check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6623{
6624 struct notif_client *notif = &notif_client_stop;
6625
6626 remote_notif_get_pending_events (notif);
6627 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6628 check_pending_event_prevents_wildcard_vcont_callback,
6629 may_global_wildcard);
6630}
6631
f48ff2a7
YQ
6632/* Remove stop replies in the queue if its pid is equal to the given
6633 inferior's pid. */
722247f1
YQ
6634
6635static int
f48ff2a7
YQ
6636remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6637 QUEUE_ITER (stop_reply_p) *iter,
6638 stop_reply_p event,
6639 void *data)
722247f1 6640{
19ba03f4
SM
6641 struct queue_iter_param *param = (struct queue_iter_param *) data;
6642 struct inferior *inf = (struct inferior *) param->input;
722247f1 6643
f48ff2a7 6644 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6645 {
6646 stop_reply_xfree (event);
6647 QUEUE_remove_elem (stop_reply_p, q, iter);
6648 }
6649
6650 return 1;
6651}
6652
f48ff2a7 6653/* Discard all pending stop replies of inferior INF. */
c906108c 6654
74531fed 6655static void
5f4cf0bb 6656discard_pending_stop_replies (struct inferior *inf)
c906108c 6657{
722247f1 6658 struct queue_iter_param param;
f48ff2a7
YQ
6659 struct stop_reply *reply;
6660 struct remote_state *rs = get_remote_state ();
6661 struct remote_notif_state *rns = rs->notif_state;
6662
6663 /* This function can be notified when an inferior exists. When the
6664 target is not remote, the notification state is NULL. */
6665 if (rs->remote_desc == NULL)
6666 return;
6667
6668 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6669
74531fed 6670 /* Discard the in-flight notification. */
f48ff2a7 6671 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6672 {
722247f1 6673 stop_reply_xfree (reply);
f48ff2a7 6674 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6675 }
c906108c 6676
722247f1
YQ
6677 param.input = inf;
6678 param.output = NULL;
74531fed
PA
6679 /* Discard the stop replies we have already pulled with
6680 vStopped. */
722247f1 6681 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6682 remove_stop_reply_for_inferior, &param);
6683}
6684
bcc75809
YQ
6685/* If its remote state is equal to the given remote state,
6686 remove EVENT from the stop reply queue. */
6687
6688static int
6689remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6690 QUEUE_ITER (stop_reply_p) *iter,
6691 stop_reply_p event,
6692 void *data)
6693{
19ba03f4
SM
6694 struct queue_iter_param *param = (struct queue_iter_param *) data;
6695 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6696
6697 if (event->rs == rs)
6698 {
6699 stop_reply_xfree (event);
6700 QUEUE_remove_elem (stop_reply_p, q, iter);
6701 }
6702
6703 return 1;
6704}
6705
6706/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6707
6708static void
bcc75809 6709discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6710{
6711 struct queue_iter_param param;
6712
bcc75809 6713 param.input = rs;
f48ff2a7
YQ
6714 param.output = NULL;
6715 /* Discard the stop replies we have already pulled with
6716 vStopped. */
6717 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6718 remove_stop_reply_of_remote_state, &param);
722247f1 6719}
74531fed 6720
722247f1
YQ
6721/* A parameter to pass data in and out. */
6722
6723static int
6724remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6725 QUEUE_ITER (stop_reply_p) *iter,
6726 stop_reply_p event,
6727 void *data)
6728{
19ba03f4
SM
6729 struct queue_iter_param *param = (struct queue_iter_param *) data;
6730 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6731
6732 if (ptid_match (event->ptid, *ptid))
6733 {
6734 param->output = event;
6735 QUEUE_remove_elem (stop_reply_p, q, iter);
6736 return 0;
c8e38a49 6737 }
722247f1
YQ
6738
6739 return 1;
74531fed 6740}
43ff13b4 6741
722247f1
YQ
6742/* Remove the first reply in 'stop_reply_queue' which matches
6743 PTID. */
2e9f7625 6744
722247f1
YQ
6745static struct stop_reply *
6746remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6747{
722247f1
YQ
6748 struct queue_iter_param param;
6749
6750 param.input = &ptid;
6751 param.output = NULL;
6752
6753 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6754 remote_notif_remove_once_on_match, &param);
6755 if (notif_debug)
6756 fprintf_unfiltered (gdb_stdlog,
6757 "notif: discard queued event: 'Stop' in %s\n",
6758 target_pid_to_str (ptid));
a744cf53 6759
722247f1 6760 return param.output;
74531fed 6761}
75c99385 6762
74531fed
PA
6763/* Look for a queued stop reply belonging to PTID. If one is found,
6764 remove it from the queue, and return it. Returns NULL if none is
6765 found. If there are still queued events left to process, tell the
6766 event loop to get back to target_wait soon. */
e24a49d8 6767
74531fed
PA
6768static struct stop_reply *
6769queued_stop_reply (ptid_t ptid)
6770{
722247f1 6771 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6772
722247f1 6773 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6774 /* There's still at least an event left. */
6775 mark_async_event_handler (remote_async_inferior_event_token);
6776
722247f1 6777 return r;
74531fed
PA
6778}
6779
6780/* Push a fully parsed stop reply in the stop reply queue. Since we
6781 know that we now have at least one queued event left to pass to the
6782 core side, tell the event loop to get back to target_wait soon. */
6783
6784static void
6785push_stop_reply (struct stop_reply *new_event)
6786{
722247f1 6787 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6788
722247f1
YQ
6789 if (notif_debug)
6790 fprintf_unfiltered (gdb_stdlog,
6791 "notif: push 'Stop' %s to queue %d\n",
6792 target_pid_to_str (new_event->ptid),
6793 QUEUE_length (stop_reply_p,
6794 stop_reply_queue));
74531fed
PA
6795
6796 mark_async_event_handler (remote_async_inferior_event_token);
6797}
6798
722247f1
YQ
6799static int
6800stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6801 QUEUE_ITER (stop_reply_p) *iter,
6802 struct stop_reply *event,
6803 void *data)
6804{
19ba03f4 6805 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6806
6807 return !(ptid_equal (*ptid, event->ptid)
6808 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6809}
6810
74531fed
PA
6811/* Returns true if we have a stop reply for PTID. */
6812
6813static int
6814peek_stop_reply (ptid_t ptid)
6815{
722247f1
YQ
6816 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6817 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6818}
6819
26d56a93
SL
6820/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6821 starting with P and ending with PEND matches PREFIX. */
6822
6823static int
6824strprefix (const char *p, const char *pend, const char *prefix)
6825{
6826 for ( ; p < pend; p++, prefix++)
6827 if (*p != *prefix)
6828 return 0;
6829 return *prefix == '\0';
6830}
6831
74531fed
PA
6832/* Parse the stop reply in BUF. Either the function succeeds, and the
6833 result is stored in EVENT, or throws an error. */
6834
6835static void
6836remote_parse_stop_reply (char *buf, struct stop_reply *event)
6837{
6838 struct remote_arch_state *rsa = get_remote_arch_state ();
6839 ULONGEST addr;
256642e8 6840 const char *p;
94585166 6841 int skipregs = 0;
74531fed
PA
6842
6843 event->ptid = null_ptid;
bcc75809 6844 event->rs = get_remote_state ();
74531fed
PA
6845 event->ws.kind = TARGET_WAITKIND_IGNORE;
6846 event->ws.value.integer = 0;
f7e6eed5 6847 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6848 event->regcache = NULL;
dc146f7c 6849 event->core = -1;
74531fed
PA
6850
6851 switch (buf[0])
6852 {
6853 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6854 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6855 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6856 ss = signal number
6857 n... = register number
6858 r... = register contents
6859 */
6860
6861 p = &buf[3]; /* after Txx */
6862 while (*p)
6863 {
256642e8 6864 const char *p1;
cea39f65 6865 int fieldsize;
43ff13b4 6866
1f10ba14
PA
6867 p1 = strchr (p, ':');
6868 if (p1 == NULL)
6869 error (_("Malformed packet(a) (missing colon): %s\n\
6870Packet: '%s'\n"),
6871 p, buf);
6872 if (p == p1)
6873 error (_("Malformed packet(a) (missing register number): %s\n\
6874Packet: '%s'\n"),
6875 p, buf);
3c3bea1c 6876
1f10ba14
PA
6877 /* Some "registers" are actually extended stop information.
6878 Note if you're adding a new entry here: GDB 7.9 and
6879 earlier assume that all register "numbers" that start
6880 with an hex digit are real register numbers. Make sure
6881 the server only sends such a packet if it knows the
6882 client understands it. */
c8e38a49 6883
26d56a93 6884 if (strprefix (p, p1, "thread"))
1f10ba14 6885 event->ptid = read_ptid (++p1, &p);
82075af2
JS
6886 else if (strprefix (p, p1, "syscall_entry"))
6887 {
6888 ULONGEST sysno;
6889
6890 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6891 p = unpack_varlen_hex (++p1, &sysno);
6892 event->ws.value.syscall_number = (int) sysno;
6893 }
6894 else if (strprefix (p, p1, "syscall_return"))
6895 {
6896 ULONGEST sysno;
6897
6898 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6899 p = unpack_varlen_hex (++p1, &sysno);
6900 event->ws.value.syscall_number = (int) sysno;
6901 }
26d56a93
SL
6902 else if (strprefix (p, p1, "watch")
6903 || strprefix (p, p1, "rwatch")
6904 || strprefix (p, p1, "awatch"))
cea39f65 6905 {
f7e6eed5 6906 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6907 p = unpack_varlen_hex (++p1, &addr);
6908 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6909 }
26d56a93 6910 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6911 {
6912 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6913
6914 /* Make sure the stub doesn't forget to indicate support
6915 with qSupported. */
6916 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6917 error (_("Unexpected swbreak stop reason"));
6918
6919 /* The value part is documented as "must be empty",
6920 though we ignore it, in case we ever decide to make
6921 use of it in a backward compatible way. */
8424cc97 6922 p = strchrnul (p1 + 1, ';');
f7e6eed5 6923 }
26d56a93 6924 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6925 {
6926 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6927
6928 /* Make sure the stub doesn't forget to indicate support
6929 with qSupported. */
6930 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6931 error (_("Unexpected hwbreak stop reason"));
6932
6933 /* See above. */
8424cc97 6934 p = strchrnul (p1 + 1, ';');
f7e6eed5 6935 }
26d56a93 6936 else if (strprefix (p, p1, "library"))
cea39f65 6937 {
1f10ba14 6938 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 6939 p = strchrnul (p1 + 1, ';');
1f10ba14 6940 }
26d56a93 6941 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6942 {
6943 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6944 /* p1 will indicate "begin" or "end", but it makes
6945 no difference for now, so ignore it. */
8424cc97 6946 p = strchrnul (p1 + 1, ';');
1f10ba14 6947 }
26d56a93 6948 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6949 {
6950 ULONGEST c;
a744cf53 6951
1f10ba14
PA
6952 p = unpack_varlen_hex (++p1, &c);
6953 event->core = c;
cea39f65 6954 }
26d56a93 6955 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6956 {
6957 event->ws.value.related_pid = read_ptid (++p1, &p);
6958 event->ws.kind = TARGET_WAITKIND_FORKED;
6959 }
26d56a93 6960 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6961 {
6962 event->ws.value.related_pid = read_ptid (++p1, &p);
6963 event->ws.kind = TARGET_WAITKIND_VFORKED;
6964 }
26d56a93 6965 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6966 {
6967 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 6968 p = strchrnul (p1 + 1, ';');
c269dbdb 6969 }
6ab24463 6970 else if (strprefix (p, p1, "exec"))
94585166
DB
6971 {
6972 ULONGEST ignored;
6973 char pathname[PATH_MAX];
6974 int pathlen;
6975
6976 /* Determine the length of the execd pathname. */
6977 p = unpack_varlen_hex (++p1, &ignored);
6978 pathlen = (p - p1) / 2;
6979
6980 /* Save the pathname for event reporting and for
6981 the next run command. */
6982 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6983 pathname[pathlen] = '\0';
6984
6985 /* This is freed during event handling. */
6986 event->ws.value.execd_pathname = xstrdup (pathname);
6987 event->ws.kind = TARGET_WAITKIND_EXECD;
6988
6989 /* Skip the registers included in this packet, since
6990 they may be for an architecture different from the
6991 one used by the original program. */
6992 skipregs = 1;
6993 }
65706a29
PA
6994 else if (strprefix (p, p1, "create"))
6995 {
6996 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 6997 p = strchrnul (p1 + 1, ';');
65706a29 6998 }
cea39f65
MS
6999 else
7000 {
1f10ba14 7001 ULONGEST pnum;
256642e8 7002 const char *p_temp;
1f10ba14 7003
94585166
DB
7004 if (skipregs)
7005 {
8424cc97 7006 p = strchrnul (p1 + 1, ';');
94585166
DB
7007 p++;
7008 continue;
7009 }
7010
1f10ba14
PA
7011 /* Maybe a real ``P'' register number. */
7012 p_temp = unpack_varlen_hex (p, &pnum);
7013 /* If the first invalid character is the colon, we got a
7014 register number. Otherwise, it's an unknown stop
7015 reason. */
7016 if (p_temp == p1)
7017 {
7018 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
7019 cached_reg_t cached_reg;
d1dff226 7020 struct gdbarch *gdbarch = target_gdbarch ();
43ff13b4 7021
1f10ba14
PA
7022 if (reg == NULL)
7023 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 7024Packet: '%s'\n"),
1f10ba14 7025 hex_string (pnum), p, buf);
c8e38a49 7026
1f10ba14 7027 cached_reg.num = reg->regnum;
d1dff226
AH
7028 cached_reg.data = (gdb_byte *)
7029 xmalloc (register_size (gdbarch, reg->regnum));
4100683b 7030
1f10ba14
PA
7031 p = p1 + 1;
7032 fieldsize = hex2bin (p, cached_reg.data,
d1dff226 7033 register_size (gdbarch, reg->regnum));
1f10ba14 7034 p += 2 * fieldsize;
d1dff226 7035 if (fieldsize < register_size (gdbarch, reg->regnum))
1f10ba14 7036 warning (_("Remote reply is too short: %s"), buf);
74531fed 7037
1f10ba14
PA
7038 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7039 }
7040 else
7041 {
7042 /* Not a number. Silently skip unknown optional
7043 info. */
8424cc97 7044 p = strchrnul (p1 + 1, ';');
1f10ba14 7045 }
cea39f65 7046 }
c8e38a49 7047
cea39f65
MS
7048 if (*p != ';')
7049 error (_("Remote register badly formatted: %s\nhere: %s"),
7050 buf, p);
7051 ++p;
7052 }
5b5596ff
PA
7053
7054 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7055 break;
7056
c8e38a49
PA
7057 /* fall through */
7058 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7059 {
7060 int sig;
7061
7062 event->ws.kind = TARGET_WAITKIND_STOPPED;
7063 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7064 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7065 event->ws.value.sig = (enum gdb_signal) sig;
7066 else
7067 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7068 }
c8e38a49 7069 break;
65706a29
PA
7070 case 'w': /* Thread exited. */
7071 {
256642e8 7072 const char *p;
65706a29
PA
7073 ULONGEST value;
7074
7075 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7076 p = unpack_varlen_hex (&buf[1], &value);
7077 event->ws.value.integer = value;
7078 if (*p != ';')
7079 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7080 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7081 break;
7082 }
c8e38a49
PA
7083 case 'W': /* Target exited. */
7084 case 'X':
7085 {
256642e8 7086 const char *p;
c8e38a49
PA
7087 int pid;
7088 ULONGEST value;
82f73884 7089
c8e38a49
PA
7090 /* GDB used to accept only 2 hex chars here. Stubs should
7091 only send more if they detect GDB supports multi-process
7092 support. */
7093 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7094
c8e38a49
PA
7095 if (buf[0] == 'W')
7096 {
7097 /* The remote process exited. */
74531fed
PA
7098 event->ws.kind = TARGET_WAITKIND_EXITED;
7099 event->ws.value.integer = value;
c8e38a49
PA
7100 }
7101 else
7102 {
7103 /* The remote process exited with a signal. */
74531fed 7104 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7105 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7106 event->ws.value.sig = (enum gdb_signal) value;
7107 else
7108 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7109 }
82f73884 7110
c8e38a49
PA
7111 /* If no process is specified, assume inferior_ptid. */
7112 pid = ptid_get_pid (inferior_ptid);
7113 if (*p == '\0')
7114 ;
7115 else if (*p == ';')
7116 {
7117 p++;
7118
0b24eb2d 7119 if (*p == '\0')
82f73884 7120 ;
61012eef 7121 else if (startswith (p, "process:"))
82f73884 7122 {
c8e38a49 7123 ULONGEST upid;
a744cf53 7124
c8e38a49
PA
7125 p += sizeof ("process:") - 1;
7126 unpack_varlen_hex (p, &upid);
7127 pid = upid;
82f73884
PA
7128 }
7129 else
7130 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7131 }
c8e38a49
PA
7132 else
7133 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
7134 event->ptid = pid_to_ptid (pid);
7135 }
7136 break;
f2faf941
PA
7137 case 'N':
7138 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7139 event->ptid = minus_one_ptid;
7140 break;
74531fed
PA
7141 }
7142
6efcd9a8 7143 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
7144 error (_("No process or thread specified in stop reply: %s"), buf);
7145}
7146
722247f1
YQ
7147/* When the stub wants to tell GDB about a new notification reply, it
7148 sends a notification (%Stop, for example). Those can come it at
7149 any time, hence, we have to make sure that any pending
7150 putpkt/getpkt sequence we're making is finished, before querying
7151 the stub for more events with the corresponding ack command
7152 (vStopped, for example). E.g., if we started a vStopped sequence
7153 immediately upon receiving the notification, something like this
7154 could happen:
74531fed
PA
7155
7156 1.1) --> Hg 1
7157 1.2) <-- OK
7158 1.3) --> g
7159 1.4) <-- %Stop
7160 1.5) --> vStopped
7161 1.6) <-- (registers reply to step #1.3)
7162
7163 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7164 query.
7165
796cb314 7166 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7167 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7168 doing whatever we were doing:
7169
7170 2.1) --> Hg 1
7171 2.2) <-- OK
7172 2.3) --> g
7173 2.4) <-- %Stop
7174 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7175 2.5) <-- (registers reply to step #2.3)
7176
7177 Eventualy after step #2.5, we return to the event loop, which
7178 notices there's an event on the
7179 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7180 associated callback --- the function below. At this point, we're
7181 always safe to start a vStopped sequence. :
7182
7183 2.6) --> vStopped
7184 2.7) <-- T05 thread:2
7185 2.8) --> vStopped
7186 2.9) --> OK
7187*/
7188
722247f1
YQ
7189void
7190remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
7191{
7192 struct remote_state *rs = get_remote_state ();
74531fed 7193
f48ff2a7 7194 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7195 {
722247f1
YQ
7196 if (notif_debug)
7197 fprintf_unfiltered (gdb_stdlog,
7198 "notif: process: '%s' ack pending event\n",
7199 nc->name);
74531fed 7200
722247f1 7201 /* acknowledge */
f48ff2a7
YQ
7202 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7203 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7204
7205 while (1)
7206 {
7207 getpkt (&rs->buf, &rs->buf_size, 0);
7208 if (strcmp (rs->buf, "OK") == 0)
7209 break;
7210 else
722247f1 7211 remote_notif_ack (nc, rs->buf);
74531fed
PA
7212 }
7213 }
722247f1
YQ
7214 else
7215 {
7216 if (notif_debug)
7217 fprintf_unfiltered (gdb_stdlog,
7218 "notif: process: '%s' no pending reply\n",
7219 nc->name);
7220 }
74531fed
PA
7221}
7222
74531fed
PA
7223/* Called when it is decided that STOP_REPLY holds the info of the
7224 event that is to be returned to the core. This function always
7225 destroys STOP_REPLY. */
7226
7227static ptid_t
7228process_stop_reply (struct stop_reply *stop_reply,
7229 struct target_waitstatus *status)
7230{
7231 ptid_t ptid;
7232
7233 *status = stop_reply->ws;
7234 ptid = stop_reply->ptid;
7235
7236 /* If no thread/process was reported by the stub, assume the current
7237 inferior. */
7238 if (ptid_equal (ptid, null_ptid))
7239 ptid = inferior_ptid;
7240
5f3563ea 7241 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7242 && status->kind != TARGET_WAITKIND_SIGNALLED
7243 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7244 {
799a2abe 7245 struct private_thread_info *remote_thr;
ee154bee 7246
5f3563ea
PA
7247 /* Expedited registers. */
7248 if (stop_reply->regcache)
7249 {
217f1f79 7250 struct regcache *regcache
f5656ead 7251 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
7252 cached_reg_t *reg;
7253 int ix;
7254
7255 for (ix = 0;
d1dff226 7256 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
5f3563ea 7257 ix++)
d1dff226 7258 {
217f1f79 7259 regcache_raw_supply (regcache, reg->num, reg->data);
d1dff226
AH
7260 xfree (reg->data);
7261 }
7262
5f3563ea
PA
7263 VEC_free (cached_reg_t, stop_reply->regcache);
7264 }
74531fed 7265
1941c569 7266 remote_notice_new_inferior (ptid, 0);
85ad3aaf 7267 remote_thr = get_private_info_ptid (ptid);
799a2abe
PA
7268 remote_thr->core = stop_reply->core;
7269 remote_thr->stop_reason = stop_reply->stop_reason;
7270 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7271 remote_thr->vcont_resumed = 0;
74531fed
PA
7272 }
7273
74531fed
PA
7274 stop_reply_xfree (stop_reply);
7275 return ptid;
7276}
7277
7278/* The non-stop mode version of target_wait. */
7279
7280static ptid_t
47608cb1 7281remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7282{
7283 struct remote_state *rs = get_remote_state ();
74531fed
PA
7284 struct stop_reply *stop_reply;
7285 int ret;
fee9eda9 7286 int is_notif = 0;
74531fed
PA
7287
7288 /* If in non-stop mode, get out of getpkt even if a
7289 notification is received. */
7290
7291 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7292 0 /* forever */, &is_notif);
74531fed
PA
7293 while (1)
7294 {
fee9eda9 7295 if (ret != -1 && !is_notif)
74531fed
PA
7296 switch (rs->buf[0])
7297 {
7298 case 'E': /* Error of some sort. */
7299 /* We're out of sync with the target now. Did it continue
7300 or not? We can't tell which thread it was in non-stop,
7301 so just ignore this. */
7302 warning (_("Remote failure reply: %s"), rs->buf);
7303 break;
7304 case 'O': /* Console output. */
7305 remote_console_output (rs->buf + 1);
7306 break;
7307 default:
7308 warning (_("Invalid remote reply: %s"), rs->buf);
7309 break;
7310 }
7311
7312 /* Acknowledge a pending stop reply that may have arrived in the
7313 mean time. */
f48ff2a7 7314 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7315 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7316
7317 /* If indeed we noticed a stop reply, we're done. */
7318 stop_reply = queued_stop_reply (ptid);
7319 if (stop_reply != NULL)
7320 return process_stop_reply (stop_reply, status);
7321
47608cb1 7322 /* Still no event. If we're just polling for an event, then
74531fed 7323 return to the event loop. */
47608cb1 7324 if (options & TARGET_WNOHANG)
74531fed
PA
7325 {
7326 status->kind = TARGET_WAITKIND_IGNORE;
7327 return minus_one_ptid;
7328 }
7329
47608cb1 7330 /* Otherwise do a blocking wait. */
74531fed 7331 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7332 1 /* forever */, &is_notif);
74531fed
PA
7333 }
7334}
7335
7336/* Wait until the remote machine stops, then return, storing status in
7337 STATUS just as `wait' would. */
7338
7339static ptid_t
47608cb1 7340remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7341{
7342 struct remote_state *rs = get_remote_state ();
74531fed 7343 ptid_t event_ptid = null_ptid;
cea39f65 7344 char *buf;
74531fed
PA
7345 struct stop_reply *stop_reply;
7346
47608cb1
PA
7347 again:
7348
74531fed
PA
7349 status->kind = TARGET_WAITKIND_IGNORE;
7350 status->value.integer = 0;
7351
7352 stop_reply = queued_stop_reply (ptid);
7353 if (stop_reply != NULL)
7354 return process_stop_reply (stop_reply, status);
7355
7356 if (rs->cached_wait_status)
7357 /* Use the cached wait status, but only once. */
7358 rs->cached_wait_status = 0;
7359 else
7360 {
7361 int ret;
722247f1 7362 int is_notif;
567420d1
PA
7363 int forever = ((options & TARGET_WNOHANG) == 0
7364 && wait_forever_enabled_p);
7365
7366 if (!rs->waiting_for_stop_reply)
7367 {
7368 status->kind = TARGET_WAITKIND_NO_RESUMED;
7369 return minus_one_ptid;
7370 }
74531fed 7371
74531fed
PA
7372 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7373 _never_ wait for ever -> test on target_is_async_p().
7374 However, before we do that we need to ensure that the caller
7375 knows how to take the target into/out of async mode. */
722247f1 7376 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 7377 forever, &is_notif);
722247f1
YQ
7378
7379 /* GDB gets a notification. Return to core as this event is
7380 not interesting. */
7381 if (ret != -1 && is_notif)
7382 return minus_one_ptid;
567420d1
PA
7383
7384 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7385 return minus_one_ptid;
74531fed
PA
7386 }
7387
7388 buf = rs->buf;
7389
3a29589a
DJ
7390 /* Assume that the target has acknowledged Ctrl-C unless we receive
7391 an 'F' or 'O' packet. */
7392 if (buf[0] != 'F' && buf[0] != 'O')
7393 rs->ctrlc_pending_p = 0;
7394
74531fed
PA
7395 switch (buf[0])
7396 {
7397 case 'E': /* Error of some sort. */
7398 /* We're out of sync with the target now. Did it continue or
7399 not? Not is more likely, so report a stop. */
29090fb6
LM
7400 rs->waiting_for_stop_reply = 0;
7401
74531fed
PA
7402 warning (_("Remote failure reply: %s"), buf);
7403 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7404 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7405 break;
7406 case 'F': /* File-I/O request. */
e42e5352
YQ
7407 /* GDB may access the inferior memory while handling the File-I/O
7408 request, but we don't want GDB accessing memory while waiting
7409 for a stop reply. See the comments in putpkt_binary. Set
7410 waiting_for_stop_reply to 0 temporarily. */
7411 rs->waiting_for_stop_reply = 0;
3a29589a
DJ
7412 remote_fileio_request (buf, rs->ctrlc_pending_p);
7413 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7414 /* GDB handled the File-I/O request, and the target is running
7415 again. Keep waiting for events. */
7416 rs->waiting_for_stop_reply = 1;
74531fed 7417 break;
f2faf941 7418 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7419 {
29090fb6
LM
7420 struct stop_reply *stop_reply;
7421
7422 /* There is a stop reply to handle. */
7423 rs->waiting_for_stop_reply = 0;
7424
7425 stop_reply
722247f1
YQ
7426 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7427 rs->buf);
74531fed 7428
74531fed 7429 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7430 break;
7431 }
7432 case 'O': /* Console output. */
7433 remote_console_output (buf + 1);
c8e38a49
PA
7434 break;
7435 case '\0':
b73be471 7436 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7437 {
7438 /* Zero length reply means that we tried 'S' or 'C' and the
7439 remote system doesn't support it. */
223ffa71 7440 target_terminal::ours_for_output ();
c8e38a49
PA
7441 printf_filtered
7442 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7443 gdb_signal_to_name (rs->last_sent_signal));
7444 rs->last_sent_signal = GDB_SIGNAL_0;
223ffa71 7445 target_terminal::inferior ();
c8e38a49 7446
f5c4fcd9
TT
7447 strcpy (buf, rs->last_sent_step ? "s" : "c");
7448 putpkt (buf);
c8e38a49 7449 break;
43ff13b4 7450 }
c8e38a49
PA
7451 /* else fallthrough */
7452 default:
7453 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7454 break;
43ff13b4 7455 }
c8e38a49 7456
f2faf941
PA
7457 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7458 return minus_one_ptid;
7459 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7460 {
7461 /* Nothing interesting happened. If we're doing a non-blocking
7462 poll, we're done. Otherwise, go back to waiting. */
7463 if (options & TARGET_WNOHANG)
7464 return minus_one_ptid;
7465 else
7466 goto again;
7467 }
74531fed
PA
7468 else if (status->kind != TARGET_WAITKIND_EXITED
7469 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7470 {
7471 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7472 record_currthread (rs, event_ptid);
82f73884
PA
7473 else
7474 event_ptid = inferior_ptid;
43ff13b4 7475 }
74531fed
PA
7476 else
7477 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7478 record_currthread (rs, minus_one_ptid);
79d7f229 7479
82f73884 7480 return event_ptid;
43ff13b4
JM
7481}
7482
74531fed
PA
7483/* Wait until the remote machine stops, then return, storing status in
7484 STATUS just as `wait' would. */
7485
c8e38a49 7486static ptid_t
117de6a9 7487remote_wait (struct target_ops *ops,
47608cb1 7488 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7489{
7490 ptid_t event_ptid;
7491
6efcd9a8 7492 if (target_is_non_stop_p ())
47608cb1 7493 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7494 else
47608cb1 7495 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7496
d9d41e78 7497 if (target_is_async_p ())
c8e38a49 7498 {
74531fed
PA
7499 /* If there are are events left in the queue tell the event loop
7500 to return here. */
722247f1 7501 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7502 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7503 }
c8e38a49
PA
7504
7505 return event_ptid;
7506}
7507
74ca34ce 7508/* Fetch a single register using a 'p' packet. */
c906108c 7509
b96ec7ac 7510static int
56be3814 7511fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac 7512{
9890e433 7513 struct gdbarch *gdbarch = get_regcache_arch (regcache);
b96ec7ac 7514 struct remote_state *rs = get_remote_state ();
2e9f7625 7515 char *buf, *p;
9890e433 7516 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
7517 int i;
7518
4082afcc 7519 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7520 return 0;
7521
7522 if (reg->pnum == -1)
7523 return 0;
7524
2e9f7625 7525 p = rs->buf;
fcad0fa4 7526 *p++ = 'p';
74ca34ce 7527 p += hexnumstr (p, reg->pnum);
fcad0fa4 7528 *p++ = '\0';
1f4437a4
MS
7529 putpkt (rs->buf);
7530 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7531
2e9f7625
DJ
7532 buf = rs->buf;
7533
74ca34ce
DJ
7534 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7535 {
7536 case PACKET_OK:
7537 break;
7538 case PACKET_UNKNOWN:
7539 return 0;
7540 case PACKET_ERROR:
27a9c0bf
MS
7541 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7542 gdbarch_register_name (get_regcache_arch (regcache),
7543 reg->regnum),
7544 buf);
74ca34ce 7545 }
3f9a994c
JB
7546
7547 /* If this register is unfetchable, tell the regcache. */
7548 if (buf[0] == 'x')
8480adf2 7549 {
56be3814 7550 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7551 return 1;
b96ec7ac 7552 }
b96ec7ac 7553
3f9a994c
JB
7554 /* Otherwise, parse and supply the value. */
7555 p = buf;
7556 i = 0;
7557 while (p[0] != 0)
7558 {
7559 if (p[1] == 0)
74ca34ce 7560 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7561
7562 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7563 p += 2;
7564 }
56be3814 7565 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7566 return 1;
b96ec7ac
AC
7567}
7568
74ca34ce
DJ
7569/* Fetch the registers included in the target's 'g' packet. */
7570
29709017
DJ
7571static int
7572send_g_packet (void)
c906108c 7573{
d01949b6 7574 struct remote_state *rs = get_remote_state ();
cea39f65 7575 int buf_len;
c906108c 7576
bba74b36 7577 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7578 remote_send (&rs->buf, &rs->buf_size);
c906108c 7579
29709017
DJ
7580 /* We can get out of synch in various cases. If the first character
7581 in the buffer is not a hex character, assume that has happened
7582 and try to fetch another packet to read. */
7583 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7584 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7585 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7586 && rs->buf[0] != 'x') /* New: unavailable register value. */
7587 {
7588 if (remote_debug)
7589 fprintf_unfiltered (gdb_stdlog,
7590 "Bad register packet; fetching a new packet\n");
7591 getpkt (&rs->buf, &rs->buf_size, 0);
7592 }
7593
74ca34ce
DJ
7594 buf_len = strlen (rs->buf);
7595
7596 /* Sanity check the received packet. */
7597 if (buf_len % 2 != 0)
7598 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7599
7600 return buf_len / 2;
7601}
7602
7603static void
56be3814 7604process_g_packet (struct regcache *regcache)
29709017 7605{
4a22f64d 7606 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7607 struct remote_state *rs = get_remote_state ();
7608 struct remote_arch_state *rsa = get_remote_arch_state ();
7609 int i, buf_len;
7610 char *p;
7611 char *regs;
7612
7613 buf_len = strlen (rs->buf);
7614
7615 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce 7616 if (buf_len > 2 * rsa->sizeof_g_packet)
fc809827
SM
7617 error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7618 "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
74ca34ce
DJ
7619
7620 /* Save the size of the packet sent to us by the target. It is used
7621 as a heuristic when determining the max size of packets that the
7622 target can safely receive. */
7623 if (rsa->actual_register_packet_size == 0)
7624 rsa->actual_register_packet_size = buf_len;
7625
7626 /* If this is smaller than we guessed the 'g' packet would be,
7627 update our records. A 'g' reply that doesn't include a register's
7628 value implies either that the register is not available, or that
7629 the 'p' packet must be used. */
7630 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7631 {
9dc193c3 7632 long sizeof_g_packet = buf_len / 2;
74ca34ce 7633
4a22f64d 7634 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7635 {
9dc193c3
LF
7636 long offset = rsa->regs[i].offset;
7637 long reg_size = register_size (gdbarch, i);
7638
74ca34ce
DJ
7639 if (rsa->regs[i].pnum == -1)
7640 continue;
7641
9dc193c3 7642 if (offset >= sizeof_g_packet)
74ca34ce 7643 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
7644 else if (offset + reg_size > sizeof_g_packet)
7645 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 7646 else
74ca34ce 7647 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7648 }
9dc193c3
LF
7649
7650 /* Looks valid enough, we can assume this is the correct length
7651 for a 'g' packet. It's important not to adjust
7652 rsa->sizeof_g_packet if we have truncated registers otherwise
7653 this "if" won't be run the next time the method is called
7654 with a packet of the same size and one of the internal errors
7655 below will trigger instead. */
7656 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 7657 }
b323314b 7658
224c3ddb 7659 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7660
7661 /* Unimplemented registers read as all bits zero. */
ea9c271d 7662 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7663
c906108c
SS
7664 /* Reply describes registers byte by byte, each byte encoded as two
7665 hex characters. Suck them all up, then supply them to the
7666 register cacheing/storage mechanism. */
7667
74ca34ce 7668 p = rs->buf;
ea9c271d 7669 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7670 {
74ca34ce
DJ
7671 if (p[0] == 0 || p[1] == 0)
7672 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7673 internal_error (__FILE__, __LINE__,
9b20d036 7674 _("unexpected end of 'g' packet reply"));
74ca34ce 7675
c906108c 7676 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7677 regs[i] = 0; /* 'x' */
c906108c
SS
7678 else
7679 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7680 p += 2;
7681 }
7682
a744cf53
MS
7683 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7684 {
7685 struct packet_reg *r = &rsa->regs[i];
9dc193c3 7686 long reg_size = register_size (gdbarch, i);
a744cf53
MS
7687
7688 if (r->in_g_packet)
7689 {
9dc193c3 7690 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
a744cf53
MS
7691 /* This shouldn't happen - we adjusted in_g_packet above. */
7692 internal_error (__FILE__, __LINE__,
9b20d036 7693 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7694 else if (rs->buf[r->offset * 2] == 'x')
7695 {
7696 gdb_assert (r->offset * 2 < strlen (rs->buf));
7697 /* The register isn't available, mark it as such (at
7698 the same time setting the value to zero). */
7699 regcache_raw_supply (regcache, r->regnum, NULL);
7700 }
7701 else
7702 regcache_raw_supply (regcache, r->regnum,
7703 regs + r->offset);
7704 }
7705 }
c906108c
SS
7706}
7707
29709017 7708static void
56be3814 7709fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7710{
7711 send_g_packet ();
56be3814 7712 process_g_packet (regcache);
29709017
DJ
7713}
7714
e6e4e701
PA
7715/* Make the remote selected traceframe match GDB's selected
7716 traceframe. */
7717
7718static void
7719set_remote_traceframe (void)
7720{
7721 int newnum;
262e1174 7722 struct remote_state *rs = get_remote_state ();
e6e4e701 7723
262e1174 7724 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7725 return;
7726
7727 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7728 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7729
7730 newnum = target_trace_find (tfind_number,
7731 get_traceframe_number (), 0, 0, NULL);
7732
7733 /* Should not happen. If it does, all bets are off. */
7734 if (newnum != get_traceframe_number ())
7735 warning (_("could not set remote traceframe"));
7736}
7737
74ca34ce 7738static void
28439f5e
PA
7739remote_fetch_registers (struct target_ops *ops,
7740 struct regcache *regcache, int regnum)
74ca34ce 7741{
74ca34ce
DJ
7742 struct remote_arch_state *rsa = get_remote_arch_state ();
7743 int i;
7744
e6e4e701 7745 set_remote_traceframe ();
bcc0c096 7746 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
7747
7748 if (regnum >= 0)
7749 {
7750 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7751
74ca34ce
DJ
7752 gdb_assert (reg != NULL);
7753
7754 /* If this register might be in the 'g' packet, try that first -
7755 we are likely to read more than one register. If this is the
7756 first 'g' packet, we might be overly optimistic about its
7757 contents, so fall back to 'p'. */
7758 if (reg->in_g_packet)
7759 {
56be3814 7760 fetch_registers_using_g (regcache);
74ca34ce
DJ
7761 if (reg->in_g_packet)
7762 return;
7763 }
7764
56be3814 7765 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7766 return;
7767
7768 /* This register is not available. */
56be3814 7769 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7770
7771 return;
7772 }
7773
56be3814 7774 fetch_registers_using_g (regcache);
74ca34ce 7775
4a22f64d 7776 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7777 if (!rsa->regs[i].in_g_packet)
56be3814 7778 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7779 {
7780 /* This register is not available. */
56be3814 7781 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7782 }
7783}
7784
c906108c
SS
7785/* Prepare to store registers. Since we may send them all (using a
7786 'G' request), we have to read out the ones we don't want to change
7787 first. */
7788
c5aa993b 7789static void
f32dbf8c 7790remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7791{
ea9c271d 7792 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7793 int i;
cf0e1e0d 7794
c906108c 7795 /* Make sure the entire registers array is valid. */
4082afcc 7796 switch (packet_support (PACKET_P))
5a2468f5
JM
7797 {
7798 case PACKET_DISABLE:
7799 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7800 /* Make sure all the necessary registers are cached. */
4a22f64d 7801 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7802 if (rsa->regs[i].in_g_packet)
8e368124 7803 regcache_raw_update (regcache, rsa->regs[i].regnum);
5a2468f5
JM
7804 break;
7805 case PACKET_ENABLE:
7806 break;
7807 }
7808}
7809
ad10f812 7810/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7811 packet was not recognized. */
5a2468f5
JM
7812
7813static int
1f4437a4
MS
7814store_register_using_P (const struct regcache *regcache,
7815 struct packet_reg *reg)
5a2468f5 7816{
4a22f64d 7817 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7818 struct remote_state *rs = get_remote_state ();
5a2468f5 7819 /* Try storing a single register. */
6d820c5c 7820 char *buf = rs->buf;
9890e433 7821 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 7822 char *p;
5a2468f5 7823
4082afcc 7824 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7825 return 0;
7826
7827 if (reg->pnum == -1)
7828 return 0;
7829
ea9c271d 7830 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7831 p = buf + strlen (buf);
56be3814 7832 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7833 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7834 putpkt (rs->buf);
7835 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7836
74ca34ce
DJ
7837 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7838 {
7839 case PACKET_OK:
7840 return 1;
7841 case PACKET_ERROR:
27a9c0bf
MS
7842 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7843 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7844 case PACKET_UNKNOWN:
7845 return 0;
7846 default:
7847 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7848 }
c906108c
SS
7849}
7850
23860348
MS
7851/* Store register REGNUM, or all registers if REGNUM == -1, from the
7852 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7853
7854static void
56be3814 7855store_registers_using_G (const struct regcache *regcache)
c906108c 7856{
d01949b6 7857 struct remote_state *rs = get_remote_state ();
ea9c271d 7858 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7859 gdb_byte *regs;
c906108c
SS
7860 char *p;
7861
193cb69f
AC
7862 /* Extract all the registers in the regcache copying them into a
7863 local buffer. */
7864 {
b323314b 7865 int i;
a744cf53 7866
224c3ddb 7867 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7868 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7869 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7870 {
ea9c271d 7871 struct packet_reg *r = &rsa->regs[i];
a744cf53 7872
b323314b 7873 if (r->in_g_packet)
56be3814 7874 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7875 }
7876 }
c906108c
SS
7877
7878 /* Command describes registers byte by byte,
7879 each byte encoded as two hex characters. */
6d820c5c 7880 p = rs->buf;
193cb69f 7881 *p++ = 'G';
74ca34ce 7882 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7883 putpkt (rs->buf);
7884 getpkt (&rs->buf, &rs->buf_size, 0);
7885 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7886 error (_("Could not write registers; remote failure reply '%s'"),
7887 rs->buf);
c906108c 7888}
74ca34ce
DJ
7889
7890/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7891 of the register cache buffer. FIXME: ignores errors. */
7892
7893static void
28439f5e
PA
7894remote_store_registers (struct target_ops *ops,
7895 struct regcache *regcache, int regnum)
74ca34ce 7896{
74ca34ce
DJ
7897 struct remote_arch_state *rsa = get_remote_arch_state ();
7898 int i;
7899
e6e4e701 7900 set_remote_traceframe ();
bcc0c096 7901 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
7902
7903 if (regnum >= 0)
7904 {
7905 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7906
74ca34ce
DJ
7907 gdb_assert (reg != NULL);
7908
7909 /* Always prefer to store registers using the 'P' packet if
7910 possible; we often change only a small number of registers.
7911 Sometimes we change a larger number; we'd need help from a
7912 higher layer to know to use 'G'. */
56be3814 7913 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7914 return;
7915
7916 /* For now, don't complain if we have no way to write the
7917 register. GDB loses track of unavailable registers too
7918 easily. Some day, this may be an error. We don't have
0df8b418 7919 any way to read the register, either... */
74ca34ce
DJ
7920 if (!reg->in_g_packet)
7921 return;
7922
56be3814 7923 store_registers_using_G (regcache);
74ca34ce
DJ
7924 return;
7925 }
7926
56be3814 7927 store_registers_using_G (regcache);
74ca34ce 7928
4a22f64d 7929 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7930 if (!rsa->regs[i].in_g_packet)
56be3814 7931 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7932 /* See above for why we do not issue an error here. */
7933 continue;
7934}
c906108c
SS
7935\f
7936
7937/* Return the number of hex digits in num. */
7938
7939static int
fba45db2 7940hexnumlen (ULONGEST num)
c906108c
SS
7941{
7942 int i;
7943
7944 for (i = 0; num != 0; i++)
7945 num >>= 4;
7946
325fac50 7947 return std::max (i, 1);
c906108c
SS
7948}
7949
2df3850c 7950/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7951
7952static int
fba45db2 7953hexnumstr (char *buf, ULONGEST num)
c906108c 7954{
c906108c 7955 int len = hexnumlen (num);
a744cf53 7956
2df3850c
JM
7957 return hexnumnstr (buf, num, len);
7958}
7959
c906108c 7960
2df3850c 7961/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7962
2df3850c 7963static int
fba45db2 7964hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7965{
7966 int i;
7967
7968 buf[width] = '\0';
7969
7970 for (i = width - 1; i >= 0; i--)
c906108c 7971 {
c5aa993b 7972 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7973 num >>= 4;
7974 }
7975
2df3850c 7976 return width;
c906108c
SS
7977}
7978
23860348 7979/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7980
7981static CORE_ADDR
fba45db2 7982remote_address_masked (CORE_ADDR addr)
c906108c 7983{
883b9c6c 7984 unsigned int address_size = remote_address_size;
a744cf53 7985
911c95a5
UW
7986 /* If "remoteaddresssize" was not set, default to target address size. */
7987 if (!address_size)
f5656ead 7988 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7989
7990 if (address_size > 0
7991 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7992 {
7993 /* Only create a mask when that mask can safely be constructed
23860348 7994 in a ULONGEST variable. */
c906108c 7995 ULONGEST mask = 1;
a744cf53 7996
911c95a5 7997 mask = (mask << address_size) - 1;
c906108c
SS
7998 addr &= mask;
7999 }
8000 return addr;
8001}
8002
8003/* Determine whether the remote target supports binary downloading.
8004 This is accomplished by sending a no-op memory write of zero length
8005 to the target at the specified address. It does not suffice to send
23860348
MS
8006 the whole packet, since many stubs strip the eighth bit and
8007 subsequently compute a wrong checksum, which causes real havoc with
8008 remote_write_bytes.
7a292a7a 8009
96baa820 8010 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 8011 clean. In cases like this, the user should clear "remote
23860348 8012 X-packet". */
96baa820 8013
c906108c 8014static void
fba45db2 8015check_binary_download (CORE_ADDR addr)
c906108c 8016{
d01949b6 8017 struct remote_state *rs = get_remote_state ();
24b06219 8018
4082afcc 8019 switch (packet_support (PACKET_X))
c906108c 8020 {
96baa820
JM
8021 case PACKET_DISABLE:
8022 break;
8023 case PACKET_ENABLE:
8024 break;
8025 case PACKET_SUPPORT_UNKNOWN:
8026 {
96baa820 8027 char *p;
802188a7 8028
2e9f7625 8029 p = rs->buf;
96baa820
JM
8030 *p++ = 'X';
8031 p += hexnumstr (p, (ULONGEST) addr);
8032 *p++ = ',';
8033 p += hexnumstr (p, (ULONGEST) 0);
8034 *p++ = ':';
8035 *p = '\0';
802188a7 8036
2e9f7625 8037 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8038 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8039
2e9f7625 8040 if (rs->buf[0] == '\0')
96baa820
JM
8041 {
8042 if (remote_debug)
8043 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8044 "binary downloading NOT "
8045 "supported by target\n");
444abaca 8046 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8047 }
8048 else
8049 {
8050 if (remote_debug)
8051 fprintf_unfiltered (gdb_stdlog,
64b9b334 8052 "binary downloading supported by target\n");
444abaca 8053 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8054 }
8055 break;
8056 }
c906108c
SS
8057 }
8058}
8059
124e13d9
SM
8060/* Helper function to resize the payload in order to try to get a good
8061 alignment. We try to write an amount of data such that the next write will
8062 start on an address aligned on REMOTE_ALIGN_WRITES. */
8063
8064static int
8065align_for_efficient_write (int todo, CORE_ADDR memaddr)
8066{
8067 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8068}
8069
c906108c
SS
8070/* Write memory data directly to the remote machine.
8071 This does not inform the data cache; the data cache uses this.
a76d924d 8072 HEADER is the starting part of the packet.
c906108c
SS
8073 MEMADDR is the address in the remote memory space.
8074 MYADDR is the address of the buffer in our space.
124e13d9
SM
8075 LEN_UNITS is the number of addressable units to write.
8076 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8077 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8078 should send data as binary ('X'), or hex-encoded ('M').
8079
8080 The function creates packet of the form
8081 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8082
124e13d9 8083 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8084
8085 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8086 are omitted.
8087
9b409511 8088 Return the transferred status, error or OK (an
124e13d9
SM
8089 'enum target_xfer_status' value). Save the number of addressable units
8090 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8091
8092 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8093 exchange between gdb and the stub could look like (?? in place of the
8094 checksum):
8095
8096 -> $m1000,4#??
8097 <- aaaabbbbccccdddd
8098
8099 -> $M1000,3:eeeeffffeeee#??
8100 <- OK
8101
8102 -> $m1000,4#??
8103 <- eeeeffffeeeedddd */
c906108c 8104
9b409511 8105static enum target_xfer_status
a76d924d 8106remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
8107 const gdb_byte *myaddr, ULONGEST len_units,
8108 int unit_size, ULONGEST *xfered_len_units,
8109 char packet_format, int use_length)
c906108c 8110{
6d820c5c 8111 struct remote_state *rs = get_remote_state ();
cfd77fa1 8112 char *p;
a76d924d
DJ
8113 char *plen = NULL;
8114 int plenlen = 0;
124e13d9
SM
8115 int todo_units;
8116 int units_written;
8117 int payload_capacity_bytes;
8118 int payload_length_bytes;
a76d924d
DJ
8119
8120 if (packet_format != 'X' && packet_format != 'M')
8121 internal_error (__FILE__, __LINE__,
9b20d036 8122 _("remote_write_bytes_aux: bad packet format"));
c906108c 8123
124e13d9 8124 if (len_units == 0)
9b409511 8125 return TARGET_XFER_EOF;
b2182ed2 8126
124e13d9 8127 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8128
6d820c5c
DJ
8129 /* The packet buffer will be large enough for the payload;
8130 get_memory_packet_size ensures this. */
a76d924d 8131 rs->buf[0] = '\0';
c906108c 8132
a257b5bb 8133 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8134 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8135
124e13d9 8136 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8137 if (!use_length)
0df8b418 8138 /* The comma won't be used. */
124e13d9
SM
8139 payload_capacity_bytes += 1;
8140 payload_capacity_bytes -= strlen (header);
8141 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8142
a76d924d 8143 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8144
a76d924d
DJ
8145 strcat (rs->buf, header);
8146 p = rs->buf + strlen (header);
8147
8148 /* Compute a best guess of the number of bytes actually transfered. */
8149 if (packet_format == 'X')
c906108c 8150 {
23860348 8151 /* Best guess at number of bytes that will fit. */
325fac50
PA
8152 todo_units = std::min (len_units,
8153 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8154 if (use_length)
124e13d9 8155 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8156 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8157 }
8158 else
8159 {
124e13d9 8160 /* Number of bytes that will fit. */
325fac50
PA
8161 todo_units
8162 = std::min (len_units,
8163 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8164 if (use_length)
124e13d9 8165 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8166 todo_units = std::min (todo_units,
8167 (payload_capacity_bytes / unit_size) / 2);
917317f4 8168 }
a76d924d 8169
124e13d9 8170 if (todo_units <= 0)
3de11b2e 8171 internal_error (__FILE__, __LINE__,
405f8e94 8172 _("minimum packet size too small to write data"));
802188a7 8173
6765f3e5
DJ
8174 /* If we already need another packet, then try to align the end
8175 of this packet to a useful boundary. */
124e13d9
SM
8176 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8177 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8178
a257b5bb 8179 /* Append "<memaddr>". */
917317f4
JM
8180 memaddr = remote_address_masked (memaddr);
8181 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8182
a76d924d
DJ
8183 if (use_length)
8184 {
8185 /* Append ",". */
8186 *p++ = ',';
802188a7 8187
124e13d9
SM
8188 /* Append the length and retain its location and size. It may need to be
8189 adjusted once the packet body has been created. */
a76d924d 8190 plen = p;
124e13d9 8191 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8192 p += plenlen;
8193 }
a257b5bb
AC
8194
8195 /* Append ":". */
917317f4
JM
8196 *p++ = ':';
8197 *p = '\0';
802188a7 8198
a257b5bb 8199 /* Append the packet body. */
a76d924d 8200 if (packet_format == 'X')
917317f4 8201 {
917317f4
JM
8202 /* Binary mode. Send target system values byte by byte, in
8203 increasing byte addresses. Only escape certain critical
8204 characters. */
124e13d9
SM
8205 payload_length_bytes =
8206 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8207 &units_written, payload_capacity_bytes);
6765f3e5 8208
124e13d9 8209 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8210 a second try to keep the end of the packet aligned. Don't do
8211 this if the packet is tiny. */
124e13d9 8212 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8213 {
124e13d9
SM
8214 int new_todo_units;
8215
8216 new_todo_units = align_for_efficient_write (units_written, memaddr);
8217
8218 if (new_todo_units != units_written)
8219 payload_length_bytes =
8220 remote_escape_output (myaddr, new_todo_units, unit_size,
8221 (gdb_byte *) p, &units_written,
8222 payload_capacity_bytes);
6765f3e5
DJ
8223 }
8224
124e13d9
SM
8225 p += payload_length_bytes;
8226 if (use_length && units_written < todo_units)
c906108c 8227 {
802188a7 8228 /* Escape chars have filled up the buffer prematurely,
124e13d9 8229 and we have actually sent fewer units than planned.
917317f4
JM
8230 Fix-up the length field of the packet. Use the same
8231 number of characters as before. */
124e13d9
SM
8232 plen += hexnumnstr (plen, (ULONGEST) units_written,
8233 plenlen);
917317f4 8234 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8235 }
a76d924d
DJ
8236 }
8237 else
8238 {
917317f4
JM
8239 /* Normal mode: Send target system values byte by byte, in
8240 increasing byte addresses. Each byte is encoded as a two hex
8241 value. */
124e13d9
SM
8242 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8243 units_written = todo_units;
c906108c 8244 }
802188a7 8245
2e9f7625 8246 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8247 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8248
2e9f7625 8249 if (rs->buf[0] == 'E')
00d84524 8250 return TARGET_XFER_E_IO;
802188a7 8251
124e13d9
SM
8252 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8253 send fewer units than we'd planned. */
8254 *xfered_len_units = (ULONGEST) units_written;
9b409511 8255 return TARGET_XFER_OK;
c906108c
SS
8256}
8257
a76d924d
DJ
8258/* Write memory data directly to the remote machine.
8259 This does not inform the data cache; the data cache uses this.
8260 MEMADDR is the address in the remote memory space.
8261 MYADDR is the address of the buffer in our space.
8262 LEN is the number of bytes.
8263
9b409511
YQ
8264 Return the transferred status, error or OK (an
8265 'enum target_xfer_status' value). Save the number of bytes
8266 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8267
9b409511
YQ
8268static enum target_xfer_status
8269remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 8270 int unit_size, ULONGEST *xfered_len)
a76d924d 8271{
a121b7c1 8272 const char *packet_format = NULL;
a76d924d
DJ
8273
8274 /* Check whether the target supports binary download. */
8275 check_binary_download (memaddr);
8276
4082afcc 8277 switch (packet_support (PACKET_X))
a76d924d
DJ
8278 {
8279 case PACKET_ENABLE:
8280 packet_format = "X";
8281 break;
8282 case PACKET_DISABLE:
8283 packet_format = "M";
8284 break;
8285 case PACKET_SUPPORT_UNKNOWN:
8286 internal_error (__FILE__, __LINE__,
8287 _("remote_write_bytes: bad internal state"));
8288 default:
8289 internal_error (__FILE__, __LINE__, _("bad switch"));
8290 }
8291
8292 return remote_write_bytes_aux (packet_format,
124e13d9 8293 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8294 packet_format[0], 1);
a76d924d
DJ
8295}
8296
9217e74e
YQ
8297/* Read memory data directly from the remote machine.
8298 This does not use the data cache; the data cache uses this.
8299 MEMADDR is the address in the remote memory space.
8300 MYADDR is the address of the buffer in our space.
124e13d9
SM
8301 LEN_UNITS is the number of addressable memory units to read..
8302 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8303
8304 Return the transferred status, error or OK (an
8305 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8306 transferred in *XFERED_LEN_UNITS.
8307
8308 See the comment of remote_write_bytes_aux for an example of
8309 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
8310
8311static enum target_xfer_status
124e13d9
SM
8312remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8313 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8314{
8315 struct remote_state *rs = get_remote_state ();
124e13d9 8316 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8317 char *p;
124e13d9
SM
8318 int todo_units;
8319 int decoded_bytes;
9217e74e 8320
124e13d9 8321 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8322 /* The packet buffer will be large enough for the payload;
8323 get_memory_packet_size ensures this. */
8324
124e13d9 8325 /* Number of units that will fit. */
325fac50
PA
8326 todo_units = std::min (len_units,
8327 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8328
8329 /* Construct "m"<memaddr>","<len>". */
8330 memaddr = remote_address_masked (memaddr);
8331 p = rs->buf;
8332 *p++ = 'm';
8333 p += hexnumstr (p, (ULONGEST) memaddr);
8334 *p++ = ',';
124e13d9 8335 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8336 *p = '\0';
8337 putpkt (rs->buf);
8338 getpkt (&rs->buf, &rs->buf_size, 0);
8339 if (rs->buf[0] == 'E'
8340 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8341 && rs->buf[3] == '\0')
8342 return TARGET_XFER_E_IO;
8343 /* Reply describes memory byte by byte, each byte encoded as two hex
8344 characters. */
8345 p = rs->buf;
124e13d9 8346 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8347 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8348 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
8349 return TARGET_XFER_OK;
8350}
8351
b55fbac4
YQ
8352/* Using the set of read-only target sections of remote, read live
8353 read-only memory.
8acf9577
YQ
8354
8355 For interface/parameters/return description see target.h,
8356 to_xfer_partial. */
8357
8358static enum target_xfer_status
b55fbac4
YQ
8359remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8360 ULONGEST memaddr, ULONGEST len,
124e13d9 8361 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
8362{
8363 struct target_section *secp;
8364 struct target_section_table *table;
8365
8366 secp = target_section_by_addr (ops, memaddr);
8367 if (secp != NULL
8368 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8369 secp->the_bfd_section)
8370 & SEC_READONLY))
8371 {
8372 struct target_section *p;
8373 ULONGEST memend = memaddr + len;
8374
8375 table = target_get_section_table (ops);
8376
8377 for (p = table->sections; p < table->sections_end; p++)
8378 {
8379 if (memaddr >= p->addr)
8380 {
8381 if (memend <= p->endaddr)
8382 {
8383 /* Entire transfer is within this section. */
124e13d9 8384 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8385 xfered_len);
8acf9577
YQ
8386 }
8387 else if (memaddr >= p->endaddr)
8388 {
8389 /* This section ends before the transfer starts. */
8390 continue;
8391 }
8392 else
8393 {
8394 /* This section overlaps the transfer. Just do half. */
8395 len = p->endaddr - memaddr;
124e13d9 8396 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8397 xfered_len);
8acf9577
YQ
8398 }
8399 }
8400 }
8401 }
8402
8403 return TARGET_XFER_EOF;
8404}
8405
9217e74e
YQ
8406/* Similar to remote_read_bytes_1, but it reads from the remote stub
8407 first if the requested memory is unavailable in traceframe.
8408 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8409
9b409511 8410static enum target_xfer_status
8acf9577 8411remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
8412 gdb_byte *myaddr, ULONGEST len, int unit_size,
8413 ULONGEST *xfered_len)
c906108c 8414{
6b6aa828 8415 if (len == 0)
96c4f946 8416 return TARGET_XFER_EOF;
b2182ed2 8417
8acf9577
YQ
8418 if (get_traceframe_number () != -1)
8419 {
8420 VEC(mem_range_s) *available;
8421
8422 /* If we fail to get the set of available memory, then the
8423 target does not support querying traceframe info, and so we
8424 attempt reading from the traceframe anyway (assuming the
8425 target implements the old QTro packet then). */
8426 if (traceframe_available_memory (&available, memaddr, len))
8427 {
8428 struct cleanup *old_chain;
8429
8430 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
8431
8432 if (VEC_empty (mem_range_s, available)
8433 || VEC_index (mem_range_s, available, 0)->start != memaddr)
8434 {
8435 enum target_xfer_status res;
8436
8437 /* Don't read into the traceframe's available
8438 memory. */
8439 if (!VEC_empty (mem_range_s, available))
8440 {
8441 LONGEST oldlen = len;
8442
8443 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8444 gdb_assert (len <= oldlen);
8445 }
8446
8447 do_cleanups (old_chain);
8448
8449 /* This goes through the topmost target again. */
b55fbac4 8450 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 8451 len, unit_size, xfered_len);
8acf9577
YQ
8452 if (res == TARGET_XFER_OK)
8453 return TARGET_XFER_OK;
8454 else
8455 {
8456 /* No use trying further, we know some memory starting
8457 at MEMADDR isn't available. */
8458 *xfered_len = len;
8459 return TARGET_XFER_UNAVAILABLE;
8460 }
8461 }
8462
8463 /* Don't try to read more than how much is available, in
8464 case the target implements the deprecated QTro packet to
8465 cater for older GDBs (the target's knowledge of read-only
8466 sections may be outdated by now). */
8467 len = VEC_index (mem_range_s, available, 0)->length;
8468
8469 do_cleanups (old_chain);
8470 }
8471 }
8472
124e13d9 8473 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8474}
74531fed 8475
c906108c 8476\f
c906108c 8477
a76d924d
DJ
8478/* Sends a packet with content determined by the printf format string
8479 FORMAT and the remaining arguments, then gets the reply. Returns
8480 whether the packet was a success, a failure, or unknown. */
8481
77b64a49
PA
8482static enum packet_result remote_send_printf (const char *format, ...)
8483 ATTRIBUTE_PRINTF (1, 2);
8484
2c0b251b 8485static enum packet_result
a76d924d
DJ
8486remote_send_printf (const char *format, ...)
8487{
8488 struct remote_state *rs = get_remote_state ();
8489 int max_size = get_remote_packet_size ();
a76d924d 8490 va_list ap;
a744cf53 8491
a76d924d
DJ
8492 va_start (ap, format);
8493
8494 rs->buf[0] = '\0';
8495 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8496 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8497
8498 if (putpkt (rs->buf) < 0)
8499 error (_("Communication problem with target."));
8500
8501 rs->buf[0] = '\0';
8502 getpkt (&rs->buf, &rs->buf_size, 0);
8503
8504 return packet_check_result (rs->buf);
8505}
8506
a76d924d
DJ
8507/* Flash writing can take quite some time. We'll set
8508 effectively infinite timeout for flash operations.
8509 In future, we'll need to decide on a better approach. */
8510static const int remote_flash_timeout = 1000;
8511
8512static void
8513remote_flash_erase (struct target_ops *ops,
8514 ULONGEST address, LONGEST length)
8515{
f5656ead 8516 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 8517 enum packet_result ret;
2ec845e7
TT
8518 scoped_restore restore_timeout
8519 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
8520
8521 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8522 phex (address, addr_size),
a76d924d
DJ
8523 phex (length, 4));
8524 switch (ret)
8525 {
8526 case PACKET_UNKNOWN:
8527 error (_("Remote target does not support flash erase"));
8528 case PACKET_ERROR:
8529 error (_("Error erasing flash with vFlashErase packet"));
8530 default:
8531 break;
8532 }
a76d924d
DJ
8533}
8534
9b409511
YQ
8535static enum target_xfer_status
8536remote_flash_write (struct target_ops *ops, ULONGEST address,
8537 ULONGEST length, ULONGEST *xfered_len,
8538 const gdb_byte *data)
a76d924d 8539{
2ec845e7
TT
8540 scoped_restore restore_timeout
8541 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8542 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8543 xfered_len,'X', 0);
a76d924d
DJ
8544}
8545
8546static void
8547remote_flash_done (struct target_ops *ops)
8548{
a76d924d 8549 int ret;
a76d924d 8550
2ec845e7
TT
8551 scoped_restore restore_timeout
8552 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8553
a76d924d 8554 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
8555
8556 switch (ret)
8557 {
8558 case PACKET_UNKNOWN:
8559 error (_("Remote target does not support vFlashDone"));
8560 case PACKET_ERROR:
8561 error (_("Error finishing flash operation"));
8562 default:
8563 break;
8564 }
8565}
8566
c906108c 8567static void
fba45db2 8568remote_files_info (struct target_ops *ignore)
c906108c
SS
8569{
8570 puts_filtered ("Debugging a target over a serial line.\n");
8571}
8572\f
8573/* Stuff for dealing with the packets which are part of this protocol.
8574 See comment at top of file for details. */
8575
1927e618
PA
8576/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8577 error to higher layers. Called when a serial error is detected.
8578 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8579 the system error message for errno at function entry and final dot
8580 for output compatibility with throw_perror_with_name. */
1927e618
PA
8581
8582static void
8583unpush_and_perror (const char *string)
8584{
d6cb50a2 8585 int saved_errno = errno;
1927e618
PA
8586
8587 remote_unpush_target ();
d6cb50a2
JK
8588 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8589 safe_strerror (saved_errno));
1927e618
PA
8590}
8591
048094ac
PA
8592/* Read a single character from the remote end. The current quit
8593 handler is overridden to avoid quitting in the middle of packet
8594 sequence, as that would break communication with the remote server.
8595 See remote_serial_quit_handler for more detail. */
c906108c
SS
8596
8597static int
fba45db2 8598readchar (int timeout)
c906108c
SS
8599{
8600 int ch;
5d93a237 8601 struct remote_state *rs = get_remote_state ();
048094ac 8602
2ec845e7
TT
8603 {
8604 scoped_restore restore_quit
8605 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
c906108c 8606
2ec845e7 8607 rs->got_ctrlc_during_io = 0;
c906108c 8608
2ec845e7 8609 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 8610
2ec845e7
TT
8611 if (rs->got_ctrlc_during_io)
8612 set_quit_flag ();
8613 }
048094ac 8614
2acceee2 8615 if (ch >= 0)
0876f84a 8616 return ch;
2acceee2
JM
8617
8618 switch ((enum serial_rc) ch)
c906108c
SS
8619 {
8620 case SERIAL_EOF:
78a095c3 8621 remote_unpush_target ();
598d3636 8622 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8623 /* no return */
c906108c 8624 case SERIAL_ERROR:
1927e618
PA
8625 unpush_and_perror (_("Remote communication error. "
8626 "Target disconnected."));
2acceee2 8627 /* no return */
c906108c 8628 case SERIAL_TIMEOUT:
2acceee2 8629 break;
c906108c 8630 }
2acceee2 8631 return ch;
c906108c
SS
8632}
8633
c33e31fd 8634/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
8635 writing fails. The current quit handler is overridden to avoid
8636 quitting in the middle of packet sequence, as that would break
8637 communication with the remote server. See
8638 remote_serial_quit_handler for more detail. */
c33e31fd
PA
8639
8640static void
8641remote_serial_write (const char *str, int len)
8642{
5d93a237 8643 struct remote_state *rs = get_remote_state ();
048094ac 8644
2ec845e7
TT
8645 scoped_restore restore_quit
8646 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
048094ac
PA
8647
8648 rs->got_ctrlc_during_io = 0;
5d93a237
TT
8649
8650 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8651 {
1927e618
PA
8652 unpush_and_perror (_("Remote communication error. "
8653 "Target disconnected."));
c33e31fd 8654 }
048094ac
PA
8655
8656 if (rs->got_ctrlc_during_io)
8657 set_quit_flag ();
c33e31fd
PA
8658}
8659
6d820c5c
DJ
8660/* Send the command in *BUF to the remote machine, and read the reply
8661 into *BUF. Report an error if we get an error reply. Resize
8662 *BUF using xrealloc if necessary to hold the result, and update
8663 *SIZEOF_BUF. */
c906108c
SS
8664
8665static void
6d820c5c
DJ
8666remote_send (char **buf,
8667 long *sizeof_buf)
c906108c 8668{
6d820c5c 8669 putpkt (*buf);
c2d11a7d 8670 getpkt (buf, sizeof_buf, 0);
c906108c 8671
6d820c5c
DJ
8672 if ((*buf)[0] == 'E')
8673 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8674}
8675
b3ced9ba
PA
8676/* Return a string representing an escaped version of BUF, of len N.
8677 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 8678
b3ced9ba 8679static std::string
6e5abd65
PA
8680escape_buffer (const char *buf, int n)
8681{
d7e74731 8682 string_file stb;
6e5abd65 8683
d7e74731
PA
8684 stb.putstrn (buf, n, '\\');
8685 return std::move (stb.string ());
6e5abd65
PA
8686}
8687
c906108c
SS
8688/* Display a null-terminated packet on stdout, for debugging, using C
8689 string notation. */
8690
8691static void
baa336ce 8692print_packet (const char *buf)
c906108c
SS
8693{
8694 puts_filtered ("\"");
43e526b9 8695 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8696 puts_filtered ("\"");
8697}
8698
8699int
baa336ce 8700putpkt (const char *buf)
c906108c
SS
8701{
8702 return putpkt_binary (buf, strlen (buf));
8703}
8704
8705/* Send a packet to the remote machine, with error checking. The data
23860348 8706 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8707 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8708 and for a possible /0 if we are debugging (remote_debug) and want
8709 to print the sent packet as a string. */
c906108c
SS
8710
8711static int
baa336ce 8712putpkt_binary (const char *buf, int cnt)
c906108c 8713{
2d717e4f 8714 struct remote_state *rs = get_remote_state ();
c906108c
SS
8715 int i;
8716 unsigned char csum = 0;
224c3ddb 8717 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8718 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8719
c906108c
SS
8720 int ch;
8721 int tcount = 0;
8722 char *p;
8723
e24a49d8
PA
8724 /* Catch cases like trying to read memory or listing threads while
8725 we're waiting for a stop reply. The remote server wouldn't be
8726 ready to handle this request, so we'd hang and timeout. We don't
8727 have to worry about this in synchronous mode, because in that
8728 case it's not possible to issue a command while the target is
74531fed
PA
8729 running. This is not a problem in non-stop mode, because in that
8730 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8731 if (!target_is_non_stop_p ()
8732 && target_is_async_p ()
8733 && rs->waiting_for_stop_reply)
9597b22a
DE
8734 {
8735 error (_("Cannot execute this command while the target is running.\n"
8736 "Use the \"interrupt\" command to stop the target\n"
8737 "and then try again."));
8738 }
e24a49d8 8739
2d717e4f
DJ
8740 /* We're sending out a new packet. Make sure we don't look at a
8741 stale cached response. */
8742 rs->cached_wait_status = 0;
8743
c906108c
SS
8744 /* Copy the packet into buffer BUF2, encapsulating it
8745 and giving it a checksum. */
8746
c906108c
SS
8747 p = buf2;
8748 *p++ = '$';
8749
8750 for (i = 0; i < cnt; i++)
8751 {
8752 csum += buf[i];
8753 *p++ = buf[i];
8754 }
8755 *p++ = '#';
8756 *p++ = tohex ((csum >> 4) & 0xf);
8757 *p++ = tohex (csum & 0xf);
8758
8759 /* Send it over and over until we get a positive ack. */
8760
8761 while (1)
8762 {
8763 int started_error_output = 0;
8764
8765 if (remote_debug)
8766 {
8767 *p = '\0';
b3ced9ba 8768
6f8976bf
YQ
8769 int len = (int) (p - buf2);
8770
8771 std::string str
8772 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8773
8774 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8775
8776 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
8777 {
8778 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
8779 str.length () - REMOTE_DEBUG_MAX_CHAR);
8780 }
8781
8782 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 8783
0f71a2f6 8784 gdb_flush (gdb_stdlog);
c906108c 8785 }
c33e31fd 8786 remote_serial_write (buf2, p - buf2);
c906108c 8787
a6f3e723
SL
8788 /* If this is a no acks version of the remote protocol, send the
8789 packet and move on. */
8790 if (rs->noack_mode)
8791 break;
8792
74531fed
PA
8793 /* Read until either a timeout occurs (-2) or '+' is read.
8794 Handle any notification that arrives in the mean time. */
c906108c
SS
8795 while (1)
8796 {
8797 ch = readchar (remote_timeout);
8798
c5aa993b 8799 if (remote_debug)
c906108c
SS
8800 {
8801 switch (ch)
8802 {
8803 case '+':
1216fa2c 8804 case '-':
c906108c
SS
8805 case SERIAL_TIMEOUT:
8806 case '$':
74531fed 8807 case '%':
c906108c
SS
8808 if (started_error_output)
8809 {
8810 putchar_unfiltered ('\n');
8811 started_error_output = 0;
8812 }
8813 }
8814 }
8815
8816 switch (ch)
8817 {
8818 case '+':
8819 if (remote_debug)
0f71a2f6 8820 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8821 do_cleanups (old_chain);
c906108c 8822 return 1;
1216fa2c
AC
8823 case '-':
8824 if (remote_debug)
8825 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8826 /* FALLTHROUGH */
c906108c 8827 case SERIAL_TIMEOUT:
c5aa993b 8828 tcount++;
c906108c 8829 if (tcount > 3)
a5c0808e
PA
8830 {
8831 do_cleanups (old_chain);
8832 return 0;
8833 }
23860348 8834 break; /* Retransmit buffer. */
c906108c
SS
8835 case '$':
8836 {
40e3f985 8837 if (remote_debug)
2bc416ba 8838 fprintf_unfiltered (gdb_stdlog,
23860348 8839 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8840 /* It's probably an old response sent because an ACK
8841 was lost. Gobble up the packet and ack it so it
8842 doesn't get retransmitted when we resend this
8843 packet. */
6d820c5c 8844 skip_frame ();
c33e31fd 8845 remote_serial_write ("+", 1);
23860348 8846 continue; /* Now, go look for +. */
c906108c 8847 }
74531fed
PA
8848
8849 case '%':
8850 {
8851 int val;
8852
8853 /* If we got a notification, handle it, and go back to looking
8854 for an ack. */
8855 /* We've found the start of a notification. Now
8856 collect the data. */
8857 val = read_frame (&rs->buf, &rs->buf_size);
8858 if (val >= 0)
8859 {
8860 if (remote_debug)
8861 {
b3ced9ba 8862 std::string str = escape_buffer (rs->buf, val);
6e5abd65 8863
6e5abd65
PA
8864 fprintf_unfiltered (gdb_stdlog,
8865 " Notification received: %s\n",
b3ced9ba 8866 str.c_str ());
74531fed 8867 }
5965e028 8868 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8869 /* We're in sync now, rewait for the ack. */
8870 tcount = 0;
8871 }
8872 else
8873 {
8874 if (remote_debug)
8875 {
8876 if (!started_error_output)
8877 {
8878 started_error_output = 1;
8879 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8880 }
8881 fputc_unfiltered (ch & 0177, gdb_stdlog);
8882 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8883 }
8884 }
8885 continue;
8886 }
8887 /* fall-through */
c906108c
SS
8888 default:
8889 if (remote_debug)
8890 {
8891 if (!started_error_output)
8892 {
8893 started_error_output = 1;
0f71a2f6 8894 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8895 }
0f71a2f6 8896 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8897 }
8898 continue;
8899 }
23860348 8900 break; /* Here to retransmit. */
c906108c
SS
8901 }
8902
8903#if 0
8904 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8905 able to get out next time we call QUIT, without anything as
8906 violent as interrupt_query. If we want to provide a way out of
8907 here without getting to the next QUIT, it should be based on
8908 hitting ^C twice as in remote_wait. */
c906108c
SS
8909 if (quit_flag)
8910 {
8911 quit_flag = 0;
8912 interrupt_query ();
8913 }
8914#endif
8915 }
a5c0808e
PA
8916
8917 do_cleanups (old_chain);
a6f3e723 8918 return 0;
c906108c
SS
8919}
8920
6d820c5c
DJ
8921/* Come here after finding the start of a frame when we expected an
8922 ack. Do our best to discard the rest of this packet. */
8923
8924static void
8925skip_frame (void)
8926{
8927 int c;
8928
8929 while (1)
8930 {
8931 c = readchar (remote_timeout);
8932 switch (c)
8933 {
8934 case SERIAL_TIMEOUT:
8935 /* Nothing we can do. */
8936 return;
8937 case '#':
8938 /* Discard the two bytes of checksum and stop. */
8939 c = readchar (remote_timeout);
8940 if (c >= 0)
8941 c = readchar (remote_timeout);
8942
8943 return;
8944 case '*': /* Run length encoding. */
8945 /* Discard the repeat count. */
8946 c = readchar (remote_timeout);
8947 if (c < 0)
8948 return;
8949 break;
8950 default:
8951 /* A regular character. */
8952 break;
8953 }
8954 }
8955}
8956
c906108c 8957/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8958 into *BUF, verifying the checksum, length, and handling run-length
8959 compression. NUL terminate the buffer. If there is not enough room,
8960 expand *BUF using xrealloc.
c906108c 8961
c2d11a7d
JM
8962 Returns -1 on error, number of characters in buffer (ignoring the
8963 trailing NULL) on success. (could be extended to return one of the
23860348 8964 SERIAL status indications). */
c2d11a7d
JM
8965
8966static long
6d820c5c
DJ
8967read_frame (char **buf_p,
8968 long *sizeof_buf)
c906108c
SS
8969{
8970 unsigned char csum;
c2d11a7d 8971 long bc;
c906108c 8972 int c;
6d820c5c 8973 char *buf = *buf_p;
a6f3e723 8974 struct remote_state *rs = get_remote_state ();
c906108c
SS
8975
8976 csum = 0;
c2d11a7d 8977 bc = 0;
c906108c
SS
8978
8979 while (1)
8980 {
8981 c = readchar (remote_timeout);
c906108c
SS
8982 switch (c)
8983 {
8984 case SERIAL_TIMEOUT:
8985 if (remote_debug)
0f71a2f6 8986 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8987 return -1;
c906108c
SS
8988 case '$':
8989 if (remote_debug)
0f71a2f6
JM
8990 fputs_filtered ("Saw new packet start in middle of old one\n",
8991 gdb_stdlog);
23860348 8992 return -1; /* Start a new packet, count retries. */
c906108c
SS
8993 case '#':
8994 {
8995 unsigned char pktcsum;
e1b09194
AC
8996 int check_0 = 0;
8997 int check_1 = 0;
c906108c 8998
c2d11a7d 8999 buf[bc] = '\0';
c906108c 9000
e1b09194
AC
9001 check_0 = readchar (remote_timeout);
9002 if (check_0 >= 0)
9003 check_1 = readchar (remote_timeout);
802188a7 9004
e1b09194
AC
9005 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9006 {
9007 if (remote_debug)
2bc416ba 9008 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 9009 gdb_stdlog);
e1b09194
AC
9010 return -1;
9011 }
9012 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
9013 {
9014 if (remote_debug)
2bc416ba 9015 fputs_filtered ("Communication error in checksum\n",
23860348 9016 gdb_stdlog);
40e3f985
FN
9017 return -1;
9018 }
c906108c 9019
a6f3e723
SL
9020 /* Don't recompute the checksum; with no ack packets we
9021 don't have any way to indicate a packet retransmission
9022 is necessary. */
9023 if (rs->noack_mode)
9024 return bc;
9025
e1b09194 9026 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 9027 if (csum == pktcsum)
c2d11a7d 9028 return bc;
c906108c 9029
c5aa993b 9030 if (remote_debug)
c906108c 9031 {
b3ced9ba 9032 std::string str = escape_buffer (buf, bc);
6e5abd65 9033
6e5abd65 9034 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9035 "Bad checksum, sentsum=0x%x, "
9036 "csum=0x%x, buf=%s\n",
b3ced9ba 9037 pktcsum, csum, str.c_str ());
c906108c 9038 }
c2d11a7d 9039 /* Number of characters in buffer ignoring trailing
23860348 9040 NULL. */
c2d11a7d 9041 return -1;
c906108c 9042 }
23860348 9043 case '*': /* Run length encoding. */
c2c6d25f
JM
9044 {
9045 int repeat;
c906108c 9046
a744cf53 9047 csum += c;
b4501125
AC
9048 c = readchar (remote_timeout);
9049 csum += c;
23860348 9050 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9051
23860348 9052 /* The character before ``*'' is repeated. */
c2d11a7d 9053
6d820c5c 9054 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9055 {
6d820c5c
DJ
9056 if (bc + repeat - 1 >= *sizeof_buf - 1)
9057 {
9058 /* Make some more room in the buffer. */
9059 *sizeof_buf += repeat;
224c3ddb 9060 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
9061 buf = *buf_p;
9062 }
9063
c2d11a7d
JM
9064 memset (&buf[bc], buf[bc - 1], repeat);
9065 bc += repeat;
c2c6d25f
JM
9066 continue;
9067 }
9068
c2d11a7d 9069 buf[bc] = '\0';
6d820c5c 9070 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9071 return -1;
c2c6d25f 9072 }
c906108c 9073 default:
6d820c5c 9074 if (bc >= *sizeof_buf - 1)
c906108c 9075 {
6d820c5c
DJ
9076 /* Make some more room in the buffer. */
9077 *sizeof_buf *= 2;
224c3ddb 9078 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 9079 buf = *buf_p;
c906108c
SS
9080 }
9081
6d820c5c
DJ
9082 buf[bc++] = c;
9083 csum += c;
9084 continue;
c906108c
SS
9085 }
9086 }
9087}
9088
9089/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9090 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9091 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9092 rather than timing out; this is used (in synchronous mode) to wait
9093 for a target that is is executing user code to stop. */
d9fcf2fb
JM
9094/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9095 don't have to change all the calls to getpkt to deal with the
9096 return value, because at the moment I don't know what the right
23860348 9097 thing to do it for those. */
c906108c 9098void
6d820c5c
DJ
9099getpkt (char **buf,
9100 long *sizeof_buf,
c2d11a7d 9101 int forever)
d9fcf2fb 9102{
54887903 9103 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
9104}
9105
9106
9107/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9108 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9109 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9110 rather than timing out; this is used (in synchronous mode) to wait
9111 for a target that is is executing user code to stop. If FOREVER ==
9112 0, this function is allowed to time out gracefully and return an
74531fed
PA
9113 indication of this to the caller. Otherwise return the number of
9114 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
9115 enough reason to return to the caller. *IS_NOTIF is an output
9116 boolean that indicates whether *BUF holds a notification or not
9117 (a regular packet). */
74531fed 9118
3172dc30 9119static int
74531fed 9120getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 9121 int expecting_notif, int *is_notif)
c906108c 9122{
2d717e4f 9123 struct remote_state *rs = get_remote_state ();
c906108c
SS
9124 int c;
9125 int tries;
9126 int timeout;
df4b58fe 9127 int val = -1;
c906108c 9128
2d717e4f
DJ
9129 /* We're reading a new response. Make sure we don't look at a
9130 previously cached response. */
9131 rs->cached_wait_status = 0;
9132
6d820c5c 9133 strcpy (*buf, "timeout");
c906108c
SS
9134
9135 if (forever)
74531fed
PA
9136 timeout = watchdog > 0 ? watchdog : -1;
9137 else if (expecting_notif)
9138 timeout = 0; /* There should already be a char in the buffer. If
9139 not, bail out. */
c906108c
SS
9140 else
9141 timeout = remote_timeout;
9142
9143#define MAX_TRIES 3
9144
74531fed
PA
9145 /* Process any number of notifications, and then return when
9146 we get a packet. */
9147 for (;;)
c906108c 9148 {
d9c43928 9149 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9150 times. */
9151 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9152 {
74531fed
PA
9153 /* This can loop forever if the remote side sends us
9154 characters continuously, but if it pauses, we'll get
9155 SERIAL_TIMEOUT from readchar because of timeout. Then
9156 we'll count that as a retry.
9157
9158 Note that even when forever is set, we will only wait
9159 forever prior to the start of a packet. After that, we
9160 expect characters to arrive at a brisk pace. They should
9161 show up within remote_timeout intervals. */
9162 do
9163 c = readchar (timeout);
9164 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9165
9166 if (c == SERIAL_TIMEOUT)
9167 {
74531fed
PA
9168 if (expecting_notif)
9169 return -1; /* Don't complain, it's normal to not get
9170 anything in this case. */
9171
23860348 9172 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9173 {
78a095c3 9174 remote_unpush_target ();
598d3636
JK
9175 throw_error (TARGET_CLOSE_ERROR,
9176 _("Watchdog timeout has expired. "
9177 "Target detached."));
c906108c 9178 }
c906108c 9179 if (remote_debug)
0f71a2f6 9180 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9181 }
74531fed
PA
9182 else
9183 {
9184 /* We've found the start of a packet or notification.
9185 Now collect the data. */
9186 val = read_frame (buf, sizeof_buf);
9187 if (val >= 0)
9188 break;
9189 }
9190
c33e31fd 9191 remote_serial_write ("-", 1);
c906108c 9192 }
c906108c 9193
74531fed
PA
9194 if (tries > MAX_TRIES)
9195 {
9196 /* We have tried hard enough, and just can't receive the
9197 packet/notification. Give up. */
9198 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9199
74531fed
PA
9200 /* Skip the ack char if we're in no-ack mode. */
9201 if (!rs->noack_mode)
c33e31fd 9202 remote_serial_write ("+", 1);
74531fed
PA
9203 return -1;
9204 }
c906108c 9205
74531fed
PA
9206 /* If we got an ordinary packet, return that to our caller. */
9207 if (c == '$')
c906108c
SS
9208 {
9209 if (remote_debug)
43e526b9 9210 {
6f8976bf
YQ
9211 std::string str
9212 = escape_buffer (*buf,
9213 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9214
9215 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9216 str.c_str ());
9217
9218 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
9219 {
9220 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
9221 str.length () - REMOTE_DEBUG_MAX_CHAR);
9222 }
6e5abd65 9223
6f8976bf 9224 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9225 }
a6f3e723
SL
9226
9227 /* Skip the ack char if we're in no-ack mode. */
9228 if (!rs->noack_mode)
c33e31fd 9229 remote_serial_write ("+", 1);
fee9eda9
YQ
9230 if (is_notif != NULL)
9231 *is_notif = 0;
0876f84a 9232 return val;
c906108c
SS
9233 }
9234
74531fed
PA
9235 /* If we got a notification, handle it, and go back to looking
9236 for a packet. */
9237 else
9238 {
9239 gdb_assert (c == '%');
9240
9241 if (remote_debug)
9242 {
b3ced9ba 9243 std::string str = escape_buffer (*buf, val);
6e5abd65 9244
6e5abd65
PA
9245 fprintf_unfiltered (gdb_stdlog,
9246 " Notification received: %s\n",
b3ced9ba 9247 str.c_str ());
74531fed 9248 }
fee9eda9
YQ
9249 if (is_notif != NULL)
9250 *is_notif = 1;
c906108c 9251
5965e028 9252 handle_notification (rs->notif_state, *buf);
c906108c 9253
74531fed 9254 /* Notifications require no acknowledgement. */
a6f3e723 9255
74531fed 9256 if (expecting_notif)
fee9eda9 9257 return val;
74531fed
PA
9258 }
9259 }
9260}
9261
9262static int
9263getpkt_sane (char **buf, long *sizeof_buf, int forever)
9264{
fee9eda9 9265 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
9266}
9267
9268static int
fee9eda9
YQ
9269getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9270 int *is_notif)
74531fed 9271{
fee9eda9
YQ
9272 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9273 is_notif);
c906108c 9274}
74531fed 9275
cbb8991c
DB
9276/* Check whether EVENT is a fork event for the process specified
9277 by the pid passed in DATA, and if it is, kill the fork child. */
9278
9279static int
9280kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9281 QUEUE_ITER (stop_reply_p) *iter,
9282 stop_reply_p event,
9283 void *data)
9284{
19ba03f4 9285 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
9286 int parent_pid = *(int *) param->input;
9287
9288 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9289 {
9290 struct remote_state *rs = get_remote_state ();
9291 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9292 int res;
9293
9294 res = remote_vkill (child_pid, rs);
9295 if (res != 0)
9296 error (_("Can't kill fork child process %d"), child_pid);
9297 }
9298
9299 return 1;
9300}
9301
9302/* Kill any new fork children of process PID that haven't been
9303 processed by follow_fork. */
9304
9305static void
9306kill_new_fork_children (int pid, struct remote_state *rs)
9307{
9308 struct thread_info *thread;
9309 struct notif_client *notif = &notif_client_stop;
9310 struct queue_iter_param param;
9311
9312 /* Kill the fork child threads of any threads in process PID
9313 that are stopped at a fork event. */
9314 ALL_NON_EXITED_THREADS (thread)
9315 {
9316 struct target_waitstatus *ws = &thread->pending_follow;
9317
9318 if (is_pending_fork_parent (ws, pid, thread->ptid))
9319 {
9320 struct remote_state *rs = get_remote_state ();
9321 int child_pid = ptid_get_pid (ws->value.related_pid);
9322 int res;
9323
9324 res = remote_vkill (child_pid, rs);
9325 if (res != 0)
9326 error (_("Can't kill fork child process %d"), child_pid);
9327 }
9328 }
9329
9330 /* Check for any pending fork events (not reported or processed yet)
9331 in process PID and kill those fork child threads as well. */
9332 remote_notif_get_pending_events (notif);
9333 param.input = &pid;
9334 param.output = NULL;
9335 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9336 kill_child_of_pending_fork, &param);
9337}
9338
c906108c 9339\f
8020350c
DB
9340/* Target hook to kill the current inferior. */
9341
c906108c 9342static void
7d85a9c0 9343remote_kill (struct target_ops *ops)
43ff13b4 9344{
8020350c
DB
9345 int res = -1;
9346 int pid = ptid_get_pid (inferior_ptid);
9347 struct remote_state *rs = get_remote_state ();
0fdf84ca 9348
8020350c 9349 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9350 {
8020350c
DB
9351 /* If we're stopped while forking and we haven't followed yet,
9352 kill the child task. We need to do this before killing the
9353 parent task because if this is a vfork then the parent will
9354 be sleeping. */
9355 kill_new_fork_children (pid, rs);
9356
9357 res = remote_vkill (pid, rs);
9358 if (res == 0)
0fdf84ca 9359 {
bc1e6c81 9360 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9361 return;
9362 }
8020350c 9363 }
0fdf84ca 9364
8020350c
DB
9365 /* If we are in 'target remote' mode and we are killing the only
9366 inferior, then we will tell gdbserver to exit and unpush the
9367 target. */
9368 if (res == -1 && !remote_multi_process_p (rs)
9369 && number_of_live_inferiors () == 1)
9370 {
9371 remote_kill_k ();
9372
9373 /* We've killed the remote end, we get to mourn it. If we are
9374 not in extended mode, mourning the inferior also unpushes
9375 remote_ops from the target stack, which closes the remote
9376 connection. */
bc1e6c81 9377 target_mourn_inferior (inferior_ptid);
8020350c
DB
9378
9379 return;
0fdf84ca 9380 }
43ff13b4 9381
8020350c 9382 error (_("Can't kill process"));
43ff13b4
JM
9383}
9384
8020350c
DB
9385/* Send a kill request to the target using the 'vKill' packet. */
9386
82f73884
PA
9387static int
9388remote_vkill (int pid, struct remote_state *rs)
9389{
4082afcc 9390 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9391 return -1;
9392
9393 /* Tell the remote target to detach. */
bba74b36 9394 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
9395 putpkt (rs->buf);
9396 getpkt (&rs->buf, &rs->buf_size, 0);
9397
4082afcc
PA
9398 switch (packet_ok (rs->buf,
9399 &remote_protocol_packets[PACKET_vKill]))
9400 {
9401 case PACKET_OK:
9402 return 0;
9403 case PACKET_ERROR:
9404 return 1;
9405 case PACKET_UNKNOWN:
9406 return -1;
9407 default:
9408 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9409 }
82f73884
PA
9410}
9411
8020350c
DB
9412/* Send a kill request to the target using the 'k' packet. */
9413
82f73884 9414static void
8020350c 9415remote_kill_k (void)
82f73884 9416{
8020350c
DB
9417 /* Catch errors so the user can quit from gdb even when we
9418 aren't on speaking terms with the remote system. */
9419 TRY
82f73884 9420 {
82f73884 9421 putpkt ("k");
82f73884 9422 }
8020350c
DB
9423 CATCH (ex, RETURN_MASK_ERROR)
9424 {
9425 if (ex.error == TARGET_CLOSE_ERROR)
9426 {
9427 /* If we got an (EOF) error that caused the target
9428 to go away, then we're done, that's what we wanted.
9429 "k" is susceptible to cause a premature EOF, given
9430 that the remote server isn't actually required to
9431 reply to "k", and it can happen that it doesn't
9432 even get to reply ACK to the "k". */
9433 return;
9434 }
82f73884 9435
8020350c
DB
9436 /* Otherwise, something went wrong. We didn't actually kill
9437 the target. Just propagate the exception, and let the
9438 user or higher layers decide what to do. */
9439 throw_exception (ex);
9440 }
9441 END_CATCH
82f73884
PA
9442}
9443
c906108c 9444static void
20f796c9 9445remote_mourn (struct target_ops *target)
c906108c 9446{
8020350c 9447 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9448
8020350c
DB
9449 /* In 'target remote' mode with one inferior, we close the connection. */
9450 if (!rs->extended && number_of_live_inferiors () <= 1)
9451 {
9452 unpush_target (target);
c906108c 9453
8020350c
DB
9454 /* remote_close takes care of doing most of the clean up. */
9455 generic_mourn_inferior ();
9456 return;
9457 }
c906108c 9458
e24a49d8
PA
9459 /* In case we got here due to an error, but we're going to stay
9460 connected. */
9461 rs->waiting_for_stop_reply = 0;
9462
dc1981d7
PA
9463 /* If the current general thread belonged to the process we just
9464 detached from or has exited, the remote side current general
9465 thread becomes undefined. Considering a case like this:
9466
9467 - We just got here due to a detach.
9468 - The process that we're detaching from happens to immediately
9469 report a global breakpoint being hit in non-stop mode, in the
9470 same thread we had selected before.
9471 - GDB attaches to this process again.
9472 - This event happens to be the next event we handle.
9473
9474 GDB would consider that the current general thread didn't need to
9475 be set on the stub side (with Hg), since for all it knew,
9476 GENERAL_THREAD hadn't changed.
9477
9478 Notice that although in all-stop mode, the remote server always
9479 sets the current thread to the thread reporting the stop event,
9480 that doesn't happen in non-stop mode; in non-stop, the stub *must
9481 not* change the current thread when reporting a breakpoint hit,
9482 due to the decoupling of event reporting and event handling.
9483
9484 To keep things simple, we always invalidate our notion of the
9485 current thread. */
47f8a51d 9486 record_currthread (rs, minus_one_ptid);
dc1981d7 9487
8020350c 9488 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9489 generic_mourn_inferior ();
9490
d729566a 9491 if (!have_inferiors ())
2d717e4f 9492 {
82f73884
PA
9493 if (!remote_multi_process_p (rs))
9494 {
9495 /* Check whether the target is running now - some remote stubs
9496 automatically restart after kill. */
9497 putpkt ("?");
9498 getpkt (&rs->buf, &rs->buf_size, 0);
9499
9500 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9501 {
3e43a32a
MS
9502 /* Assume that the target has been restarted. Set
9503 inferior_ptid so that bits of core GDB realizes
9504 there's something here, e.g., so that the user can
9505 say "kill" again. */
82f73884
PA
9506 inferior_ptid = magic_null_ptid;
9507 }
82f73884 9508 }
2d717e4f
DJ
9509 }
9510}
c906108c 9511
03583c20 9512static int
2bfc0540 9513extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 9514{
4082afcc 9515 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9516}
9517
9518static void
9519extended_remote_disable_randomization (int val)
9520{
9521 struct remote_state *rs = get_remote_state ();
9522 char *reply;
9523
bba74b36
YQ
9524 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9525 val);
03583c20 9526 putpkt (rs->buf);
b6bb3468 9527 reply = remote_get_noisy_reply ();
03583c20
UW
9528 if (*reply == '\0')
9529 error (_("Target does not support QDisableRandomization."));
9530 if (strcmp (reply, "OK") != 0)
9531 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9532}
9533
2d717e4f 9534static int
7c5ded6a 9535extended_remote_run (const std::string &args)
2d717e4f
DJ
9536{
9537 struct remote_state *rs = get_remote_state ();
2d717e4f 9538 int len;
94585166 9539 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9540
2d717e4f
DJ
9541 /* If the user has disabled vRun support, or we have detected that
9542 support is not available, do not try it. */
4082afcc 9543 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9544 return -1;
424163ea 9545
2d717e4f
DJ
9546 strcpy (rs->buf, "vRun;");
9547 len = strlen (rs->buf);
c906108c 9548
2d717e4f
DJ
9549 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9550 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9551 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9552 strlen (remote_exec_file));
2d717e4f 9553
7c5ded6a 9554 if (!args.empty ())
2d717e4f 9555 {
2d717e4f 9556 int i;
2d717e4f 9557
773a1edc 9558 gdb_argv argv (args.c_str ());
2d717e4f
DJ
9559 for (i = 0; argv[i] != NULL; i++)
9560 {
9561 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9562 error (_("Argument list too long for run packet"));
9563 rs->buf[len++] = ';';
9f1b45b0
TT
9564 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9565 strlen (argv[i]));
2d717e4f 9566 }
2d717e4f
DJ
9567 }
9568
9569 rs->buf[len++] = '\0';
9570
9571 putpkt (rs->buf);
9572 getpkt (&rs->buf, &rs->buf_size, 0);
9573
4082afcc 9574 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9575 {
4082afcc 9576 case PACKET_OK:
3405876a 9577 /* We have a wait response. All is well. */
2d717e4f 9578 return 0;
4082afcc
PA
9579 case PACKET_UNKNOWN:
9580 return -1;
9581 case PACKET_ERROR:
2d717e4f
DJ
9582 if (remote_exec_file[0] == '\0')
9583 error (_("Running the default executable on the remote target failed; "
9584 "try \"set remote exec-file\"?"));
9585 else
9586 error (_("Running \"%s\" on the remote target failed"),
9587 remote_exec_file);
4082afcc
PA
9588 default:
9589 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9590 }
c906108c
SS
9591}
9592
0a2dde4a
SDJ
9593/* Helper function to send set/unset environment packets. ACTION is
9594 either "set" or "unset". PACKET is either "QEnvironmentHexEncoded"
9595 or "QEnvironmentUnsetVariable". VALUE is the variable to be
9596 sent. */
9597
9598static void
9599send_environment_packet (struct remote_state *rs,
9600 const char *action,
9601 const char *packet,
9602 const char *value)
9603{
9604 /* Convert the environment variable to an hex string, which
9605 is the best format to be transmitted over the wire. */
9606 std::string encoded_value = bin2hex ((const gdb_byte *) value,
9607 strlen (value));
9608
9609 xsnprintf (rs->buf, get_remote_packet_size (),
9610 "%s:%s", packet, encoded_value.c_str ());
9611
9612 putpkt (rs->buf);
9613 getpkt (&rs->buf, &rs->buf_size, 0);
9614 if (strcmp (rs->buf, "OK") != 0)
9615 warning (_("Unable to %s environment variable '%s' on remote."),
9616 action, value);
9617}
9618
9619/* Helper function to handle the QEnvironment* packets. */
9620
9621static void
9622extended_remote_environment_support (struct remote_state *rs)
9623{
9624 if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9625 {
9626 putpkt ("QEnvironmentReset");
9627 getpkt (&rs->buf, &rs->buf_size, 0);
9628 if (strcmp (rs->buf, "OK") != 0)
9629 warning (_("Unable to reset environment on remote."));
9630 }
9631
9632 gdb_environ *e = &current_inferior ()->environment;
9633
9634 if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9635 for (const std::string &el : e->user_set_env ())
9636 send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9637 el.c_str ());
9638
9639 if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9640 for (const std::string &el : e->user_unset_env ())
9641 send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9642}
9643
2d717e4f
DJ
9644/* In the extended protocol we want to be able to do things like
9645 "run" and have them basically work as expected. So we need
9646 a special create_inferior function. We support changing the
9647 executable file and the command line arguments, but not the
9648 environment. */
9649
43ff13b4 9650static void
77a19445 9651extended_remote_create_inferior (struct target_ops *ops,
7c5ded6a
SDJ
9652 const char *exec_file,
9653 const std::string &args,
77a19445 9654 char **env, int from_tty)
43ff13b4 9655{
3405876a
PA
9656 int run_worked;
9657 char *stop_reply;
9658 struct remote_state *rs = get_remote_state ();
94585166 9659 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9660
43ff13b4 9661 /* If running asynchronously, register the target file descriptor
23860348 9662 with the event loop. */
75c99385 9663 if (target_can_async_p ())
6a3753b3 9664 target_async (1);
43ff13b4 9665
03583c20 9666 /* Disable address space randomization if requested (and supported). */
2bfc0540 9667 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9668 extended_remote_disable_randomization (disable_randomization);
9669
aefd8b33
SDJ
9670 /* If startup-with-shell is on, we inform gdbserver to start the
9671 remote inferior using a shell. */
9672 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9673 {
9674 xsnprintf (rs->buf, get_remote_packet_size (),
9675 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9676 putpkt (rs->buf);
9677 getpkt (&rs->buf, &rs->buf_size, 0);
9678 if (strcmp (rs->buf, "OK") != 0)
9679 error (_("\
9680Remote replied unexpectedly while setting startup-with-shell: %s"),
9681 rs->buf);
9682 }
9683
0a2dde4a
SDJ
9684 extended_remote_environment_support (rs);
9685
43ff13b4 9686 /* Now restart the remote server. */
3405876a
PA
9687 run_worked = extended_remote_run (args) != -1;
9688 if (!run_worked)
2d717e4f
DJ
9689 {
9690 /* vRun was not supported. Fail if we need it to do what the
9691 user requested. */
9692 if (remote_exec_file[0])
9693 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 9694 if (!args.empty ())
2d717e4f 9695 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9696
2d717e4f
DJ
9697 /* Fall back to "R". */
9698 extended_remote_restart ();
9699 }
424163ea 9700
6c95b8df
PA
9701 if (!have_inferiors ())
9702 {
9703 /* Clean up from the last time we ran, before we mark the target
9704 running again. This will mark breakpoints uninserted, and
9705 get_offsets may insert breakpoints. */
9706 init_thread_list ();
9707 init_wait_for_inferior ();
9708 }
45280a52 9709
3405876a
PA
9710 /* vRun's success return is a stop reply. */
9711 stop_reply = run_worked ? rs->buf : NULL;
9712 add_current_inferior_and_thread (stop_reply);
c0a2216e 9713
2d717e4f
DJ
9714 /* Get updated offsets, if the stub uses qOffsets. */
9715 get_offsets ();
2d717e4f 9716}
c906108c 9717\f
c5aa993b 9718
b775012e
LM
9719/* Given a location's target info BP_TGT and the packet buffer BUF, output
9720 the list of conditions (in agent expression bytecode format), if any, the
9721 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9722 started from BUF and ended at BUF_END. */
b775012e
LM
9723
9724static int
9725remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9726 struct bp_target_info *bp_tgt, char *buf,
9727 char *buf_end)
b775012e 9728{
3cde5c42 9729 if (bp_tgt->conditions.empty ())
b775012e
LM
9730 return 0;
9731
9732 buf += strlen (buf);
bba74b36 9733 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9734 buf++;
9735
83621223 9736 /* Send conditions to the target. */
d538e36d 9737 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 9738 {
bba74b36 9739 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 9740 buf += strlen (buf);
3cde5c42 9741 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
9742 buf = pack_hex_byte (buf, aexpr->buf[i]);
9743 *buf = '\0';
9744 }
b775012e
LM
9745 return 0;
9746}
9747
d3ce09f5
SS
9748static void
9749remote_add_target_side_commands (struct gdbarch *gdbarch,
9750 struct bp_target_info *bp_tgt, char *buf)
9751{
3cde5c42 9752 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
9753 return;
9754
9755 buf += strlen (buf);
9756
9757 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9758 buf += strlen (buf);
9759
9760 /* Concatenate all the agent expressions that are commands into the
9761 cmds parameter. */
df97be55 9762 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
9763 {
9764 sprintf (buf, "X%x,", aexpr->len);
9765 buf += strlen (buf);
3cde5c42 9766 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
9767 buf = pack_hex_byte (buf, aexpr->buf[i]);
9768 *buf = '\0';
9769 }
d3ce09f5
SS
9770}
9771
8181d85f
DJ
9772/* Insert a breakpoint. On targets that have software breakpoint
9773 support, we ask the remote target to do the work; on targets
9774 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9775
9776static int
3db08215
MM
9777remote_insert_breakpoint (struct target_ops *ops,
9778 struct gdbarch *gdbarch,
a6d9a66e 9779 struct bp_target_info *bp_tgt)
c906108c 9780{
d471ea57
AC
9781 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9782 If it succeeds, then set the support to PACKET_ENABLE. If it
9783 fails, and the user has explicitly requested the Z support then
23860348 9784 report an error, otherwise, mark it disabled and go on. */
802188a7 9785
4082afcc 9786 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9787 {
0d5ed153 9788 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9789 struct remote_state *rs;
bba74b36 9790 char *p, *endbuf;
7c0f6dcc 9791 int bpsize;
4fff2411 9792
28439a30
PA
9793 /* Make sure the remote is pointing at the right process, if
9794 necessary. */
9795 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9796 set_general_process ();
9797
4fff2411
JZ
9798 rs = get_remote_state ();
9799 p = rs->buf;
bba74b36 9800 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9801
96baa820
JM
9802 *(p++) = 'Z';
9803 *(p++) = '0';
9804 *(p++) = ',';
7c0f6dcc 9805 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9806 p += hexnumstr (p, addr);
579c6ad9 9807 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 9808
efcc2da7 9809 if (remote_supports_cond_breakpoints (ops))
bba74b36 9810 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9811
78eff0ec 9812 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9813 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9814
6d820c5c
DJ
9815 putpkt (rs->buf);
9816 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9817
6d820c5c 9818 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9819 {
d471ea57
AC
9820 case PACKET_ERROR:
9821 return -1;
9822 case PACKET_OK:
9823 return 0;
9824 case PACKET_UNKNOWN:
9825 break;
96baa820
JM
9826 }
9827 }
c906108c 9828
0000e5cc
PA
9829 /* If this breakpoint has target-side commands but this stub doesn't
9830 support Z0 packets, throw error. */
3cde5c42 9831 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
9832 throw_error (NOT_SUPPORTED_ERROR, _("\
9833Target doesn't support breakpoints that have target side commands."));
9834
3db08215 9835 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9836}
9837
9838static int
3db08215
MM
9839remote_remove_breakpoint (struct target_ops *ops,
9840 struct gdbarch *gdbarch,
73971819
PA
9841 struct bp_target_info *bp_tgt,
9842 enum remove_bp_reason reason)
c906108c 9843{
8181d85f 9844 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9845 struct remote_state *rs = get_remote_state ();
96baa820 9846
4082afcc 9847 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9848 {
6d820c5c 9849 char *p = rs->buf;
bba74b36 9850 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9851
28439a30
PA
9852 /* Make sure the remote is pointing at the right process, if
9853 necessary. */
9854 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9855 set_general_process ();
9856
96baa820
JM
9857 *(p++) = 'z';
9858 *(p++) = '0';
9859 *(p++) = ',';
9860
8181d85f
DJ
9861 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9862 p += hexnumstr (p, addr);
579c6ad9 9863 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 9864
6d820c5c
DJ
9865 putpkt (rs->buf);
9866 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9867
6d820c5c 9868 return (rs->buf[0] == 'E');
96baa820
JM
9869 }
9870
73971819 9871 return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
c906108c
SS
9872}
9873
f486487f 9874static enum Z_packet_type
d471ea57
AC
9875watchpoint_to_Z_packet (int type)
9876{
9877 switch (type)
9878 {
9879 case hw_write:
bb858e6a 9880 return Z_PACKET_WRITE_WP;
d471ea57
AC
9881 break;
9882 case hw_read:
bb858e6a 9883 return Z_PACKET_READ_WP;
d471ea57
AC
9884 break;
9885 case hw_access:
bb858e6a 9886 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9887 break;
9888 default:
8e65ff28 9889 internal_error (__FILE__, __LINE__,
e2e0b3e5 9890 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9891 }
9892}
9893
3c3bea1c 9894static int
f486487f
SM
9895remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9896 enum target_hw_bp_type type, struct expression *cond)
96baa820 9897{
d01949b6 9898 struct remote_state *rs = get_remote_state ();
bba74b36 9899 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9900 char *p;
d471ea57 9901 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9902
4082afcc 9903 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9904 return 1;
802188a7 9905
28439a30
PA
9906 /* Make sure the remote is pointing at the right process, if
9907 necessary. */
9908 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9909 set_general_process ();
9910
bba74b36 9911 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9912 p = strchr (rs->buf, '\0');
96baa820
JM
9913 addr = remote_address_masked (addr);
9914 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9915 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9916
6d820c5c
DJ
9917 putpkt (rs->buf);
9918 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9919
6d820c5c 9920 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9921 {
9922 case PACKET_ERROR:
d471ea57 9923 return -1;
85d721b8
PA
9924 case PACKET_UNKNOWN:
9925 return 1;
d471ea57
AC
9926 case PACKET_OK:
9927 return 0;
9928 }
8e65ff28 9929 internal_error (__FILE__, __LINE__,
e2e0b3e5 9930 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9931}
9932
283002cf
MR
9933static int
9934remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9935 CORE_ADDR start, int length)
9936{
9937 CORE_ADDR diff = remote_address_masked (addr - start);
9938
9939 return diff < length;
9940}
9941
d471ea57 9942
3c3bea1c 9943static int
f486487f
SM
9944remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9945 enum target_hw_bp_type type, struct expression *cond)
96baa820 9946{
d01949b6 9947 struct remote_state *rs = get_remote_state ();
bba74b36 9948 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9949 char *p;
d471ea57
AC
9950 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9951
4082afcc 9952 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9953 return -1;
802188a7 9954
28439a30
PA
9955 /* Make sure the remote is pointing at the right process, if
9956 necessary. */
9957 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9958 set_general_process ();
9959
bba74b36 9960 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9961 p = strchr (rs->buf, '\0');
96baa820
JM
9962 addr = remote_address_masked (addr);
9963 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9964 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9965 putpkt (rs->buf);
9966 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9967
6d820c5c 9968 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9969 {
9970 case PACKET_ERROR:
9971 case PACKET_UNKNOWN:
9972 return -1;
9973 case PACKET_OK:
9974 return 0;
9975 }
8e65ff28 9976 internal_error (__FILE__, __LINE__,
e2e0b3e5 9977 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9978}
9979
3c3bea1c 9980
501eef12 9981int remote_hw_watchpoint_limit = -1;
480a3f21 9982int remote_hw_watchpoint_length_limit = -1;
501eef12 9983int remote_hw_breakpoint_limit = -1;
d471ea57 9984
480a3f21 9985static int
31568a15
TT
9986remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9987 CORE_ADDR addr, int len)
480a3f21
PW
9988{
9989 if (remote_hw_watchpoint_length_limit == 0)
9990 return 0;
9991 else if (remote_hw_watchpoint_length_limit < 0)
9992 return 1;
9993 else if (len <= remote_hw_watchpoint_length_limit)
9994 return 1;
9995 else
9996 return 0;
9997}
9998
b9362cc7 9999static int
5461485a 10000remote_check_watch_resources (struct target_ops *self,
f486487f 10001 enum bptype type, int cnt, int ot)
96baa820 10002{
3c3bea1c
GS
10003 if (type == bp_hardware_breakpoint)
10004 {
10005 if (remote_hw_breakpoint_limit == 0)
10006 return 0;
501eef12
AC
10007 else if (remote_hw_breakpoint_limit < 0)
10008 return 1;
3c3bea1c
GS
10009 else if (cnt <= remote_hw_breakpoint_limit)
10010 return 1;
10011 }
10012 else
10013 {
10014 if (remote_hw_watchpoint_limit == 0)
10015 return 0;
501eef12
AC
10016 else if (remote_hw_watchpoint_limit < 0)
10017 return 1;
3c3bea1c
GS
10018 else if (ot)
10019 return -1;
10020 else if (cnt <= remote_hw_watchpoint_limit)
10021 return 1;
10022 }
10023 return -1;
10024}
10025
f7e6eed5
PA
10026/* The to_stopped_by_sw_breakpoint method of target remote. */
10027
10028static int
10029remote_stopped_by_sw_breakpoint (struct target_ops *ops)
10030{
799a2abe 10031 struct thread_info *thread = inferior_thread ();
f7e6eed5 10032
799a2abe
PA
10033 return (thread->priv != NULL
10034 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
10035}
10036
10037/* The to_supports_stopped_by_sw_breakpoint method of target
10038 remote. */
10039
10040static int
10041remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
10042{
f7e6eed5
PA
10043 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10044}
10045
10046/* The to_stopped_by_hw_breakpoint method of target remote. */
10047
10048static int
10049remote_stopped_by_hw_breakpoint (struct target_ops *ops)
10050{
799a2abe 10051 struct thread_info *thread = inferior_thread ();
f7e6eed5 10052
799a2abe
PA
10053 return (thread->priv != NULL
10054 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
10055}
10056
10057/* The to_supports_stopped_by_hw_breakpoint method of target
10058 remote. */
10059
10060static int
10061remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
10062{
f7e6eed5
PA
10063 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10064}
10065
b9362cc7 10066static int
6a109b6b 10067remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 10068{
799a2abe 10069 struct thread_info *thread = inferior_thread ();
ee154bee 10070
799a2abe
PA
10071 return (thread->priv != NULL
10072 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
10073}
10074
4aa7a7f5
JJ
10075static int
10076remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 10077{
799a2abe 10078 struct thread_info *thread = inferior_thread ();
a744cf53 10079
799a2abe
PA
10080 if (thread->priv != NULL
10081 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 10082 {
799a2abe
PA
10083 *addr_p = thread->priv->watch_data_address;
10084 return 1;
4aa7a7f5
JJ
10085 }
10086
799a2abe 10087 return 0;
3c3bea1c
GS
10088}
10089
10090
10091static int
23a26771 10092remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 10093 struct bp_target_info *bp_tgt)
3c3bea1c 10094{
0d5ed153 10095 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10096 struct remote_state *rs;
bba74b36 10097 char *p, *endbuf;
dd61ec5c 10098 char *message;
3c3bea1c 10099
4082afcc 10100 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10101 return -1;
2bc416ba 10102
28439a30
PA
10103 /* Make sure the remote is pointing at the right process, if
10104 necessary. */
10105 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10106 set_general_process ();
10107
4fff2411
JZ
10108 rs = get_remote_state ();
10109 p = rs->buf;
bba74b36 10110 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 10111
96baa820
JM
10112 *(p++) = 'Z';
10113 *(p++) = '1';
10114 *(p++) = ',';
802188a7 10115
0d5ed153 10116 addr = remote_address_masked (addr);
96baa820 10117 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10118 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10119
efcc2da7 10120 if (remote_supports_cond_breakpoints (self))
bba74b36 10121 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10122
78eff0ec 10123 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
10124 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10125
6d820c5c
DJ
10126 putpkt (rs->buf);
10127 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10128
6d820c5c 10129 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10130 {
10131 case PACKET_ERROR:
dd61ec5c
MW
10132 if (rs->buf[1] == '.')
10133 {
10134 message = strchr (rs->buf + 2, '.');
10135 if (message)
0316657e 10136 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10137 }
10138 return -1;
d471ea57
AC
10139 case PACKET_UNKNOWN:
10140 return -1;
10141 case PACKET_OK:
10142 return 0;
10143 }
8e65ff28 10144 internal_error (__FILE__, __LINE__,
e2e0b3e5 10145 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10146}
10147
d471ea57 10148
802188a7 10149static int
a64dc96c 10150remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 10151 struct bp_target_info *bp_tgt)
96baa820 10152{
8181d85f 10153 CORE_ADDR addr;
d01949b6 10154 struct remote_state *rs = get_remote_state ();
6d820c5c 10155 char *p = rs->buf;
bba74b36 10156 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 10157
4082afcc 10158 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10159 return -1;
802188a7 10160
28439a30
PA
10161 /* Make sure the remote is pointing at the right process, if
10162 necessary. */
10163 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10164 set_general_process ();
10165
96baa820
JM
10166 *(p++) = 'z';
10167 *(p++) = '1';
10168 *(p++) = ',';
802188a7 10169
8181d85f 10170 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10171 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10172 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10173
6d820c5c
DJ
10174 putpkt (rs->buf);
10175 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 10176
6d820c5c 10177 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10178 {
10179 case PACKET_ERROR:
10180 case PACKET_UNKNOWN:
10181 return -1;
10182 case PACKET_OK:
10183 return 0;
10184 }
8e65ff28 10185 internal_error (__FILE__, __LINE__,
e2e0b3e5 10186 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10187}
96baa820 10188
4a5e7a5b
PA
10189/* Verify memory using the "qCRC:" request. */
10190
10191static int
10192remote_verify_memory (struct target_ops *ops,
10193 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10194{
10195 struct remote_state *rs = get_remote_state ();
10196 unsigned long host_crc, target_crc;
10197 char *tmp;
10198
936d2992
PA
10199 /* It doesn't make sense to use qCRC if the remote target is
10200 connected but not running. */
10201 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10202 {
10203 enum packet_result result;
28439a30 10204
936d2992
PA
10205 /* Make sure the remote is pointing at the right process. */
10206 set_general_process ();
4a5e7a5b 10207
936d2992
PA
10208 /* FIXME: assumes lma can fit into long. */
10209 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10210 (long) lma, (long) size);
10211 putpkt (rs->buf);
4a5e7a5b 10212
936d2992
PA
10213 /* Be clever; compute the host_crc before waiting for target
10214 reply. */
10215 host_crc = xcrc32 (data, size, 0xffffffff);
10216
10217 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 10218
936d2992
PA
10219 result = packet_ok (rs->buf,
10220 &remote_protocol_packets[PACKET_qCRC]);
10221 if (result == PACKET_ERROR)
10222 return -1;
10223 else if (result == PACKET_OK)
10224 {
10225 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10226 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10227
936d2992
PA
10228 return (host_crc == target_crc);
10229 }
10230 }
4a5e7a5b 10231
936d2992 10232 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
10233}
10234
c906108c
SS
10235/* compare-sections command
10236
10237 With no arguments, compares each loadable section in the exec bfd
10238 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10239 Useful for verifying the image on the target against the exec file. */
e514a9d6 10240
c906108c 10241static void
ac88e2de 10242compare_sections_command (const char *args, int from_tty)
c906108c
SS
10243{
10244 asection *s;
c906108c 10245 struct cleanup *old_chain;
948f8e3d 10246 gdb_byte *sectdata;
ce359b09 10247 const char *sectname;
c906108c
SS
10248 bfd_size_type size;
10249 bfd_vma lma;
10250 int matched = 0;
10251 int mismatched = 0;
4a5e7a5b 10252 int res;
95cf3b38 10253 int read_only = 0;
c906108c
SS
10254
10255 if (!exec_bfd)
8a3fe4f8 10256 error (_("command cannot be used without an exec file"));
c906108c 10257
28439a30
PA
10258 /* Make sure the remote is pointing at the right process. */
10259 set_general_process ();
10260
95cf3b38
DT
10261 if (args != NULL && strcmp (args, "-r") == 0)
10262 {
10263 read_only = 1;
10264 args = NULL;
10265 }
10266
c5aa993b 10267 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10268 {
10269 if (!(s->flags & SEC_LOAD))
0df8b418 10270 continue; /* Skip non-loadable section. */
c906108c 10271
95cf3b38
DT
10272 if (read_only && (s->flags & SEC_READONLY) == 0)
10273 continue; /* Skip writeable sections */
10274
2c500098 10275 size = bfd_get_section_size (s);
c906108c 10276 if (size == 0)
0df8b418 10277 continue; /* Skip zero-length section. */
c906108c 10278
ce359b09 10279 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10280 if (args && strcmp (args, sectname) != 0)
0df8b418 10281 continue; /* Not the section selected by user. */
c906108c 10282
0df8b418 10283 matched = 1; /* Do this section. */
c906108c 10284 lma = s->lma;
c906108c 10285
224c3ddb 10286 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 10287 old_chain = make_cleanup (xfree, sectdata);
c906108c 10288 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 10289
4a5e7a5b
PA
10290 res = target_verify_memory (sectdata, lma, size);
10291
10292 if (res == -1)
5af949e3 10293 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10294 paddress (target_gdbarch (), lma),
10295 paddress (target_gdbarch (), lma + size));
c906108c 10296
5af949e3 10297 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10298 paddress (target_gdbarch (), lma),
10299 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10300 if (res)
c906108c
SS
10301 printf_filtered ("matched.\n");
10302 else
c5aa993b
JM
10303 {
10304 printf_filtered ("MIS-MATCHED!\n");
10305 mismatched++;
10306 }
c906108c
SS
10307
10308 do_cleanups (old_chain);
10309 }
10310 if (mismatched > 0)
936d2992 10311 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10312the loaded file\n"));
c906108c 10313 if (args && !matched)
a3f17187 10314 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10315}
10316
0e7f50da
UW
10317/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10318 into remote target. The number of bytes written to the remote
10319 target is returned, or -1 for error. */
10320
9b409511 10321static enum target_xfer_status
0e7f50da
UW
10322remote_write_qxfer (struct target_ops *ops, const char *object_name,
10323 const char *annex, const gdb_byte *writebuf,
9b409511 10324 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
10325 struct packet_config *packet)
10326{
10327 int i, buf_len;
10328 ULONGEST n;
0e7f50da
UW
10329 struct remote_state *rs = get_remote_state ();
10330 int max_size = get_memory_write_packet_size ();
10331
10332 if (packet->support == PACKET_DISABLE)
2ed4b548 10333 return TARGET_XFER_E_IO;
0e7f50da
UW
10334
10335 /* Insert header. */
10336 i = snprintf (rs->buf, max_size,
10337 "qXfer:%s:write:%s:%s:",
10338 object_name, annex ? annex : "",
10339 phex_nz (offset, sizeof offset));
10340 max_size -= (i + 1);
10341
10342 /* Escape as much data as fits into rs->buf. */
10343 buf_len = remote_escape_output
124e13d9 10344 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
10345
10346 if (putpkt_binary (rs->buf, i + buf_len) < 0
10347 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10348 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10349 return TARGET_XFER_E_IO;
0e7f50da
UW
10350
10351 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
10352
10353 *xfered_len = n;
10354 return TARGET_XFER_OK;
0e7f50da
UW
10355}
10356
0876f84a
DJ
10357/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10358 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10359 number of bytes read is returned, or 0 for EOF, or -1 for error.
10360 The number of bytes read may be less than LEN without indicating an
10361 EOF. PACKET is checked and updated to indicate whether the remote
10362 target supports this object. */
10363
9b409511 10364static enum target_xfer_status
0876f84a
DJ
10365remote_read_qxfer (struct target_ops *ops, const char *object_name,
10366 const char *annex,
10367 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 10368 ULONGEST *xfered_len,
0876f84a
DJ
10369 struct packet_config *packet)
10370{
0876f84a 10371 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10372 LONGEST i, n, packet_len;
10373
10374 if (packet->support == PACKET_DISABLE)
2ed4b548 10375 return TARGET_XFER_E_IO;
0876f84a
DJ
10376
10377 /* Check whether we've cached an end-of-object packet that matches
10378 this request. */
8e88304f 10379 if (rs->finished_object)
0876f84a 10380 {
8e88304f
TT
10381 if (strcmp (object_name, rs->finished_object) == 0
10382 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10383 && offset == rs->finished_offset)
9b409511
YQ
10384 return TARGET_XFER_EOF;
10385
0876f84a
DJ
10386
10387 /* Otherwise, we're now reading something different. Discard
10388 the cache. */
8e88304f
TT
10389 xfree (rs->finished_object);
10390 xfree (rs->finished_annex);
10391 rs->finished_object = NULL;
10392 rs->finished_annex = NULL;
0876f84a
DJ
10393 }
10394
10395 /* Request only enough to fit in a single packet. The actual data
10396 may not, since we don't know how much of it will need to be escaped;
10397 the target is free to respond with slightly less data. We subtract
10398 five to account for the response type and the protocol frame. */
768adc05 10399 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
0876f84a
DJ
10400 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10401 object_name, annex ? annex : "",
10402 phex_nz (offset, sizeof offset),
10403 phex_nz (n, sizeof n));
10404 i = putpkt (rs->buf);
10405 if (i < 0)
2ed4b548 10406 return TARGET_XFER_E_IO;
0876f84a
DJ
10407
10408 rs->buf[0] = '\0';
10409 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10410 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10411 return TARGET_XFER_E_IO;
0876f84a
DJ
10412
10413 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10414 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10415
10416 /* 'm' means there is (or at least might be) more data after this
10417 batch. That does not make sense unless there's at least one byte
10418 of data in this reply. */
10419 if (rs->buf[0] == 'm' && packet_len == 1)
10420 error (_("Remote qXfer reply contained no data."));
10421
10422 /* Got some data. */
bc20a4af
PA
10423 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10424 packet_len - 1, readbuf, n);
0876f84a
DJ
10425
10426 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10427 or possibly empty. If we have the final block of a non-empty
10428 object, record this fact to bypass a subsequent partial read. */
10429 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10430 {
8e88304f
TT
10431 rs->finished_object = xstrdup (object_name);
10432 rs->finished_annex = xstrdup (annex ? annex : "");
10433 rs->finished_offset = offset + i;
0876f84a
DJ
10434 }
10435
9b409511
YQ
10436 if (i == 0)
10437 return TARGET_XFER_EOF;
10438 else
10439 {
10440 *xfered_len = i;
10441 return TARGET_XFER_OK;
10442 }
0876f84a
DJ
10443}
10444
9b409511 10445static enum target_xfer_status
4b8a223f 10446remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 10447 const char *annex, gdb_byte *readbuf,
9b409511
YQ
10448 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10449 ULONGEST *xfered_len)
c906108c 10450{
82f73884 10451 struct remote_state *rs;
c906108c 10452 int i;
6d820c5c 10453 char *p2;
1e3ff5ad 10454 char query_type;
124e13d9 10455 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 10456
e6e4e701 10457 set_remote_traceframe ();
82f73884
PA
10458 set_general_thread (inferior_ptid);
10459
10460 rs = get_remote_state ();
10461
b2182ed2 10462 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
10463 if (object == TARGET_OBJECT_MEMORY)
10464 {
2d717e4f
DJ
10465 /* If the remote target is connected but not running, we should
10466 pass this request down to a lower stratum (e.g. the executable
10467 file). */
10468 if (!target_has_execution)
9b409511 10469 return TARGET_XFER_EOF;
2d717e4f 10470
21e3b9b9 10471 if (writebuf != NULL)
124e13d9
SM
10472 return remote_write_bytes (offset, writebuf, len, unit_size,
10473 xfered_len);
21e3b9b9 10474 else
124e13d9
SM
10475 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10476 xfered_len);
21e3b9b9
DJ
10477 }
10478
0df8b418 10479 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10480 if (object == TARGET_OBJECT_SPU)
10481 {
10482 if (readbuf)
10483 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
10484 xfered_len, &remote_protocol_packets
10485 [PACKET_qXfer_spu_read]);
0e7f50da
UW
10486 else
10487 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
10488 xfered_len, &remote_protocol_packets
10489 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10490 }
10491
4aa995e1
PA
10492 /* Handle extra signal info using qxfer packets. */
10493 if (object == TARGET_OBJECT_SIGNAL_INFO)
10494 {
10495 if (readbuf)
10496 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 10497 xfered_len, &remote_protocol_packets
4aa995e1
PA
10498 [PACKET_qXfer_siginfo_read]);
10499 else
3e43a32a 10500 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 10501 writebuf, offset, len, xfered_len,
4aa995e1
PA
10502 &remote_protocol_packets
10503 [PACKET_qXfer_siginfo_write]);
10504 }
10505
0fb4aa4b
PA
10506 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10507 {
10508 if (readbuf)
3e43a32a 10509 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 10510 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10511 &remote_protocol_packets
10512 [PACKET_qXfer_statictrace_read]);
10513 else
2ed4b548 10514 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10515 }
10516
a76d924d
DJ
10517 /* Only handle flash writes. */
10518 if (writebuf != NULL)
10519 {
a76d924d
DJ
10520 switch (object)
10521 {
10522 case TARGET_OBJECT_FLASH:
9b409511
YQ
10523 return remote_flash_write (ops, offset, len, xfered_len,
10524 writebuf);
a76d924d
DJ
10525
10526 default:
2ed4b548 10527 return TARGET_XFER_E_IO;
a76d924d
DJ
10528 }
10529 }
4b8a223f 10530
1e3ff5ad
AC
10531 /* Map pre-existing objects onto letters. DO NOT do this for new
10532 objects!!! Instead specify new query packets. */
10533 switch (object)
c906108c 10534 {
1e3ff5ad
AC
10535 case TARGET_OBJECT_AVR:
10536 query_type = 'R';
10537 break;
802188a7
RM
10538
10539 case TARGET_OBJECT_AUXV:
0876f84a
DJ
10540 gdb_assert (annex == NULL);
10541 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 10542 xfered_len,
0876f84a 10543 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10544
23181151
DJ
10545 case TARGET_OBJECT_AVAILABLE_FEATURES:
10546 return remote_read_qxfer
9b409511 10547 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10548 &remote_protocol_packets[PACKET_qXfer_features]);
10549
cfa9d6d9
DJ
10550 case TARGET_OBJECT_LIBRARIES:
10551 return remote_read_qxfer
9b409511 10552 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10553 &remote_protocol_packets[PACKET_qXfer_libraries]);
10554
2268b414
JK
10555 case TARGET_OBJECT_LIBRARIES_SVR4:
10556 return remote_read_qxfer
9b409511 10557 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10558 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10559
fd79ecee
DJ
10560 case TARGET_OBJECT_MEMORY_MAP:
10561 gdb_assert (annex == NULL);
10562 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 10563 xfered_len,
fd79ecee
DJ
10564 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10565
07e059b5
VP
10566 case TARGET_OBJECT_OSDATA:
10567 /* Should only get here if we're connected. */
5d93a237 10568 gdb_assert (rs->remote_desc);
07e059b5 10569 return remote_read_qxfer
9b409511 10570 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10571 &remote_protocol_packets[PACKET_qXfer_osdata]);
10572
dc146f7c
VP
10573 case TARGET_OBJECT_THREADS:
10574 gdb_assert (annex == NULL);
10575 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10576 xfered_len,
dc146f7c
VP
10577 &remote_protocol_packets[PACKET_qXfer_threads]);
10578
b3b9301e
PA
10579 case TARGET_OBJECT_TRACEFRAME_INFO:
10580 gdb_assert (annex == NULL);
10581 return remote_read_qxfer
9b409511 10582 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10583 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10584
10585 case TARGET_OBJECT_FDPIC:
10586 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10587 xfered_len,
78d85199 10588 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10589
10590 case TARGET_OBJECT_OPENVMS_UIB:
10591 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10592 xfered_len,
169081d0
TG
10593 &remote_protocol_packets[PACKET_qXfer_uib]);
10594
9accd112
MM
10595 case TARGET_OBJECT_BTRACE:
10596 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10597 xfered_len,
9accd112
MM
10598 &remote_protocol_packets[PACKET_qXfer_btrace]);
10599
f4abbc16
MM
10600 case TARGET_OBJECT_BTRACE_CONF:
10601 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10602 len, xfered_len,
10603 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10604
c78fa86a
GB
10605 case TARGET_OBJECT_EXEC_FILE:
10606 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10607 len, xfered_len,
10608 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10609
1e3ff5ad 10610 default:
2ed4b548 10611 return TARGET_XFER_E_IO;
c906108c
SS
10612 }
10613
0df8b418 10614 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10615 large enough let the caller deal with it. */
ea9c271d 10616 if (len < get_remote_packet_size ())
2ed4b548 10617 return TARGET_XFER_E_IO;
ea9c271d 10618 len = get_remote_packet_size ();
1e3ff5ad 10619
23860348 10620 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10621 if (!rs->remote_desc)
8a3fe4f8 10622 error (_("remote query is only available after target open"));
c906108c 10623
1e3ff5ad 10624 gdb_assert (annex != NULL);
4b8a223f 10625 gdb_assert (readbuf != NULL);
c906108c 10626
6d820c5c 10627 p2 = rs->buf;
c906108c
SS
10628 *p2++ = 'q';
10629 *p2++ = query_type;
10630
23860348
MS
10631 /* We used one buffer char for the remote protocol q command and
10632 another for the query type. As the remote protocol encapsulation
10633 uses 4 chars plus one extra in case we are debugging
10634 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10635 string. */
c906108c 10636 i = 0;
ea9c271d 10637 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10638 {
1e3ff5ad
AC
10639 /* Bad caller may have sent forbidden characters. */
10640 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10641 *p2++ = annex[i];
c906108c
SS
10642 i++;
10643 }
1e3ff5ad
AC
10644 *p2 = '\0';
10645 gdb_assert (annex[i] == '\0');
c906108c 10646
6d820c5c 10647 i = putpkt (rs->buf);
c5aa993b 10648 if (i < 0)
2ed4b548 10649 return TARGET_XFER_E_IO;
c906108c 10650
6d820c5c
DJ
10651 getpkt (&rs->buf, &rs->buf_size, 0);
10652 strcpy ((char *) readbuf, rs->buf);
c906108c 10653
9b409511
YQ
10654 *xfered_len = strlen ((char *) readbuf);
10655 return TARGET_XFER_OK;
c906108c
SS
10656}
10657
09c98b44
DB
10658/* Implementation of to_get_memory_xfer_limit. */
10659
10660static ULONGEST
10661remote_get_memory_xfer_limit (struct target_ops *ops)
10662{
10663 return get_memory_write_packet_size ();
10664}
10665
08388c79
DE
10666static int
10667remote_search_memory (struct target_ops* ops,
10668 CORE_ADDR start_addr, ULONGEST search_space_len,
10669 const gdb_byte *pattern, ULONGEST pattern_len,
10670 CORE_ADDR *found_addrp)
10671{
f5656ead 10672 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10673 struct remote_state *rs = get_remote_state ();
10674 int max_size = get_memory_write_packet_size ();
10675 struct packet_config *packet =
10676 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10677 /* Number of packet bytes used to encode the pattern;
10678 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10679 int escaped_pattern_len;
0df8b418 10680 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10681 int used_pattern_len;
10682 int i;
10683 int found;
10684 ULONGEST found_addr;
10685
10686 /* Don't go to the target if we don't have to.
10687 This is done before checking packet->support to avoid the possibility that
10688 a success for this edge case means the facility works in general. */
10689 if (pattern_len > search_space_len)
10690 return 0;
10691 if (pattern_len == 0)
10692 {
10693 *found_addrp = start_addr;
10694 return 1;
10695 }
10696
10697 /* If we already know the packet isn't supported, fall back to the simple
10698 way of searching memory. */
10699
4082afcc 10700 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10701 {
10702 /* Target doesn't provided special support, fall back and use the
10703 standard support (copy memory and do the search here). */
10704 return simple_search_memory (ops, start_addr, search_space_len,
10705 pattern, pattern_len, found_addrp);
10706 }
10707
28439a30
PA
10708 /* Make sure the remote is pointing at the right process. */
10709 set_general_process ();
10710
08388c79
DE
10711 /* Insert header. */
10712 i = snprintf (rs->buf, max_size,
10713 "qSearch:memory:%s;%s;",
5af949e3 10714 phex_nz (start_addr, addr_size),
08388c79
DE
10715 phex_nz (search_space_len, sizeof (search_space_len)));
10716 max_size -= (i + 1);
10717
10718 /* Escape as much data as fits into rs->buf. */
10719 escaped_pattern_len =
124e13d9 10720 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10721 &used_pattern_len, max_size);
10722
10723 /* Bail if the pattern is too large. */
10724 if (used_pattern_len != pattern_len)
9b20d036 10725 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10726
10727 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10728 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10729 || packet_ok (rs->buf, packet) != PACKET_OK)
10730 {
10731 /* The request may not have worked because the command is not
10732 supported. If so, fall back to the simple way. */
10733 if (packet->support == PACKET_DISABLE)
10734 {
10735 return simple_search_memory (ops, start_addr, search_space_len,
10736 pattern, pattern_len, found_addrp);
10737 }
10738 return -1;
10739 }
10740
10741 if (rs->buf[0] == '0')
10742 found = 0;
10743 else if (rs->buf[0] == '1')
10744 {
10745 found = 1;
10746 if (rs->buf[1] != ',')
10e0fa18 10747 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10748 unpack_varlen_hex (rs->buf + 2, &found_addr);
10749 *found_addrp = found_addr;
10750 }
10751 else
10e0fa18 10752 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10753
10754 return found;
10755}
10756
96baa820 10757static void
a30bf1f1 10758remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10759 struct ui_file *outbuf)
96baa820 10760{
d01949b6 10761 struct remote_state *rs = get_remote_state ();
2e9f7625 10762 char *p = rs->buf;
96baa820 10763
5d93a237 10764 if (!rs->remote_desc)
8a3fe4f8 10765 error (_("remote rcmd is only available after target open"));
96baa820 10766
23860348 10767 /* Send a NULL command across as an empty command. */
7be570e7
JM
10768 if (command == NULL)
10769 command = "";
10770
23860348 10771 /* The query prefix. */
2e9f7625
DJ
10772 strcpy (rs->buf, "qRcmd,");
10773 p = strchr (rs->buf, '\0');
96baa820 10774
3e43a32a
MS
10775 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10776 > get_remote_packet_size ())
8a3fe4f8 10777 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10778
23860348 10779 /* Encode the actual command. */
a30bf1f1 10780 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10781
6d820c5c 10782 if (putpkt (rs->buf) < 0)
8a3fe4f8 10783 error (_("Communication problem with target."));
96baa820
JM
10784
10785 /* get/display the response */
10786 while (1)
10787 {
2e9f7625
DJ
10788 char *buf;
10789
00bf0b85 10790 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10791 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10792 rs->buf[0] = '\0';
5b37825d
PW
10793 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10794 {
10795 /* Timeout. Continue to (try to) read responses.
10796 This is better than stopping with an error, assuming the stub
10797 is still executing the (long) monitor command.
10798 If needed, the user can interrupt gdb using C-c, obtaining
10799 an effect similar to stop on timeout. */
10800 continue;
10801 }
2e9f7625 10802 buf = rs->buf;
96baa820 10803 if (buf[0] == '\0')
8a3fe4f8 10804 error (_("Target does not support this command."));
96baa820
JM
10805 if (buf[0] == 'O' && buf[1] != 'K')
10806 {
23860348 10807 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10808 continue;
10809 }
10810 if (strcmp (buf, "OK") == 0)
10811 break;
7be570e7
JM
10812 if (strlen (buf) == 3 && buf[0] == 'E'
10813 && isdigit (buf[1]) && isdigit (buf[2]))
10814 {
8a3fe4f8 10815 error (_("Protocol error with Rcmd"));
7be570e7 10816 }
96baa820
JM
10817 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10818 {
10819 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10820
96baa820
JM
10821 fputc_unfiltered (c, outbuf);
10822 }
10823 break;
10824 }
10825}
10826
fd79ecee
DJ
10827static VEC(mem_region_s) *
10828remote_memory_map (struct target_ops *ops)
10829{
10830 VEC(mem_region_s) *result = NULL;
10831 char *text = target_read_stralloc (&current_target,
10832 TARGET_OBJECT_MEMORY_MAP, NULL);
10833
10834 if (text)
10835 {
10836 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10837
fd79ecee
DJ
10838 result = parse_memory_map (text);
10839 do_cleanups (back_to);
10840 }
10841
10842 return result;
10843}
10844
c906108c 10845static void
ac88e2de 10846packet_command (const char *args, int from_tty)
c906108c 10847{
d01949b6 10848 struct remote_state *rs = get_remote_state ();
c906108c 10849
5d93a237 10850 if (!rs->remote_desc)
8a3fe4f8 10851 error (_("command can only be used with remote target"));
c906108c 10852
c5aa993b 10853 if (!args)
8a3fe4f8 10854 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10855
10856 puts_filtered ("sending: ");
10857 print_packet (args);
10858 puts_filtered ("\n");
10859 putpkt (args);
10860
6d820c5c 10861 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10862 puts_filtered ("received: ");
6d820c5c 10863 print_packet (rs->buf);
c906108c
SS
10864 puts_filtered ("\n");
10865}
10866
10867#if 0
23860348 10868/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10869
a14ed312 10870static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10871
a14ed312 10872static void threadset_test_cmd (char *cmd, int tty);
c906108c 10873
a14ed312 10874static void threadalive_test (char *cmd, int tty);
c906108c 10875
a14ed312 10876static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10877
23860348 10878int get_and_display_threadinfo (threadref *ref);
c906108c 10879
a14ed312 10880static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10881
23860348 10882static int thread_display_step (threadref *ref, void *context);
c906108c 10883
a14ed312 10884static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10885
a14ed312 10886static void init_remote_threadtests (void);
c906108c 10887
23860348 10888#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10889
10890static void
fba45db2 10891threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10892{
10893 int sample_thread = SAMPLE_THREAD;
10894
a3f17187 10895 printf_filtered (_("Remote threadset test\n"));
79d7f229 10896 set_general_thread (sample_thread);
c906108c
SS
10897}
10898
10899
10900static void
fba45db2 10901threadalive_test (char *cmd, int tty)
c906108c
SS
10902{
10903 int sample_thread = SAMPLE_THREAD;
79d7f229 10904 int pid = ptid_get_pid (inferior_ptid);
ba348170 10905 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10906
79d7f229 10907 if (remote_thread_alive (ptid))
c906108c
SS
10908 printf_filtered ("PASS: Thread alive test\n");
10909 else
10910 printf_filtered ("FAIL: Thread alive test\n");
10911}
10912
23860348 10913void output_threadid (char *title, threadref *ref);
c906108c
SS
10914
10915void
fba45db2 10916output_threadid (char *title, threadref *ref)
c906108c
SS
10917{
10918 char hexid[20];
10919
23860348 10920 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10921 hexid[16] = 0;
10922 printf_filtered ("%s %s\n", title, (&hexid[0]));
10923}
10924
10925static void
fba45db2 10926threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10927{
10928 int startflag = 1;
10929 threadref nextthread;
10930 int done, result_count;
10931 threadref threadlist[3];
10932
10933 printf_filtered ("Remote Threadlist test\n");
10934 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10935 &result_count, &threadlist[0]))
10936 printf_filtered ("FAIL: threadlist test\n");
10937 else
10938 {
10939 threadref *scan = threadlist;
10940 threadref *limit = scan + result_count;
10941
10942 while (scan < limit)
10943 output_threadid (" thread ", scan++);
10944 }
10945}
10946
10947void
fba45db2 10948display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10949{
10950 output_threadid ("Threadid: ", &info->threadid);
10951 printf_filtered ("Name: %s\n ", info->shortname);
10952 printf_filtered ("State: %s\n", info->display);
10953 printf_filtered ("other: %s\n\n", info->more_display);
10954}
10955
10956int
fba45db2 10957get_and_display_threadinfo (threadref *ref)
c906108c
SS
10958{
10959 int result;
10960 int set;
10961 struct gdb_ext_thread_info threadinfo;
10962
10963 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10964 | TAG_MOREDISPLAY | TAG_DISPLAY;
10965 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10966 display_thread_info (&threadinfo);
10967 return result;
10968}
10969
10970static void
fba45db2 10971threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10972{
10973 int athread = SAMPLE_THREAD;
10974 threadref thread;
10975 int set;
10976
10977 int_to_threadref (&thread, athread);
10978 printf_filtered ("Remote Threadinfo test\n");
10979 if (!get_and_display_threadinfo (&thread))
10980 printf_filtered ("FAIL cannot get thread info\n");
10981}
10982
10983static int
fba45db2 10984thread_display_step (threadref *ref, void *context)
c906108c
SS
10985{
10986 /* output_threadid(" threadstep ",ref); *//* simple test */
10987 return get_and_display_threadinfo (ref);
10988}
10989
10990static void
fba45db2 10991threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10992{
10993 printf_filtered ("Remote Threadlist update test\n");
10994 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10995}
10996
10997static void
10998init_remote_threadtests (void)
10999{
3e43a32a
MS
11000 add_com ("tlist", class_obscure, threadlist_test_cmd,
11001 _("Fetch and print the remote list of "
11002 "thread identifiers, one pkt only"));
c906108c 11003 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 11004 _("Fetch and display info about one thread"));
c906108c 11005 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 11006 _("Test setting to a different thread"));
c906108c 11007 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 11008 _("Iterate through updating all remote thread info"));
c906108c 11009 add_com ("talive", class_obscure, threadalive_test,
1bedd215 11010 _(" Remote thread alive test "));
c906108c
SS
11011}
11012
11013#endif /* 0 */
11014
f3fb8c85
MS
11015/* Convert a thread ID to a string. Returns the string in a static
11016 buffer. */
11017
7a114964 11018static const char *
117de6a9 11019remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 11020{
79d7f229 11021 static char buf[64];
82f73884 11022 struct remote_state *rs = get_remote_state ();
f3fb8c85 11023
7cee1e54
PA
11024 if (ptid_equal (ptid, null_ptid))
11025 return normal_pid_to_str (ptid);
11026 else if (ptid_is_pid (ptid))
ecd0ada5
PA
11027 {
11028 /* Printing an inferior target id. */
11029
11030 /* When multi-process extensions are off, there's no way in the
11031 remote protocol to know the remote process id, if there's any
11032 at all. There's one exception --- when we're connected with
11033 target extended-remote, and we manually attached to a process
11034 with "attach PID". We don't record anywhere a flag that
11035 allows us to distinguish that case from the case of
11036 connecting with extended-remote and the stub already being
11037 attached to a process, and reporting yes to qAttached, hence
11038 no smart special casing here. */
11039 if (!remote_multi_process_p (rs))
11040 {
11041 xsnprintf (buf, sizeof buf, "Remote target");
11042 return buf;
11043 }
11044
11045 return normal_pid_to_str (ptid);
82f73884 11046 }
ecd0ada5 11047 else
79d7f229 11048 {
ecd0ada5
PA
11049 if (ptid_equal (magic_null_ptid, ptid))
11050 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 11051 else if (remote_multi_process_p (rs))
de0d863e
DB
11052 if (ptid_get_lwp (ptid) == 0)
11053 return normal_pid_to_str (ptid);
11054 else
11055 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11056 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
11057 else
11058 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 11059 ptid_get_lwp (ptid));
79d7f229
PA
11060 return buf;
11061 }
f3fb8c85
MS
11062}
11063
38691318
KB
11064/* Get the address of the thread local variable in OBJFILE which is
11065 stored at OFFSET within the thread local storage for thread PTID. */
11066
11067static CORE_ADDR
117de6a9
PA
11068remote_get_thread_local_address (struct target_ops *ops,
11069 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 11070{
4082afcc 11071 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
11072 {
11073 struct remote_state *rs = get_remote_state ();
6d820c5c 11074 char *p = rs->buf;
82f73884 11075 char *endp = rs->buf + get_remote_packet_size ();
571dd617 11076 enum packet_result result;
38691318
KB
11077
11078 strcpy (p, "qGetTLSAddr:");
11079 p += strlen (p);
82f73884 11080 p = write_ptid (p, endp, ptid);
38691318
KB
11081 *p++ = ',';
11082 p += hexnumstr (p, offset);
11083 *p++ = ',';
11084 p += hexnumstr (p, lm);
11085 *p++ = '\0';
11086
6d820c5c
DJ
11087 putpkt (rs->buf);
11088 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
11089 result = packet_ok (rs->buf,
11090 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11091 if (result == PACKET_OK)
38691318
KB
11092 {
11093 ULONGEST result;
11094
6d820c5c 11095 unpack_varlen_hex (rs->buf, &result);
38691318
KB
11096 return result;
11097 }
571dd617 11098 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11099 throw_error (TLS_GENERIC_ERROR,
11100 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11101 else
109c3e39
AC
11102 throw_error (TLS_GENERIC_ERROR,
11103 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11104 }
11105 else
109c3e39
AC
11106 throw_error (TLS_GENERIC_ERROR,
11107 _("TLS not supported or disabled on this target"));
38691318
KB
11108 /* Not reached. */
11109 return 0;
11110}
11111
711e434b
PM
11112/* Provide thread local base, i.e. Thread Information Block address.
11113 Returns 1 if ptid is found and thread_local_base is non zero. */
11114
70221824 11115static int
bd7ae0f5 11116remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 11117{
4082afcc 11118 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11119 {
11120 struct remote_state *rs = get_remote_state ();
11121 char *p = rs->buf;
11122 char *endp = rs->buf + get_remote_packet_size ();
11123 enum packet_result result;
11124
11125 strcpy (p, "qGetTIBAddr:");
11126 p += strlen (p);
11127 p = write_ptid (p, endp, ptid);
11128 *p++ = '\0';
11129
11130 putpkt (rs->buf);
11131 getpkt (&rs->buf, &rs->buf_size, 0);
11132 result = packet_ok (rs->buf,
11133 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11134 if (result == PACKET_OK)
11135 {
11136 ULONGEST result;
11137
11138 unpack_varlen_hex (rs->buf, &result);
11139 if (addr)
11140 *addr = (CORE_ADDR) result;
11141 return 1;
11142 }
11143 else if (result == PACKET_UNKNOWN)
11144 error (_("Remote target doesn't support qGetTIBAddr packet"));
11145 else
11146 error (_("Remote target failed to process qGetTIBAddr request"));
11147 }
11148 else
11149 error (_("qGetTIBAddr not supported or disabled on this target"));
11150 /* Not reached. */
11151 return 0;
11152}
11153
29709017
DJ
11154/* Support for inferring a target description based on the current
11155 architecture and the size of a 'g' packet. While the 'g' packet
11156 can have any size (since optional registers can be left off the
11157 end), some sizes are easily recognizable given knowledge of the
11158 approximate architecture. */
11159
11160struct remote_g_packet_guess
11161{
11162 int bytes;
11163 const struct target_desc *tdesc;
11164};
11165typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11166DEF_VEC_O(remote_g_packet_guess_s);
11167
11168struct remote_g_packet_data
11169{
11170 VEC(remote_g_packet_guess_s) *guesses;
11171};
11172
11173static struct gdbarch_data *remote_g_packet_data_handle;
11174
11175static void *
11176remote_g_packet_data_init (struct obstack *obstack)
11177{
11178 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11179}
11180
11181void
11182register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11183 const struct target_desc *tdesc)
11184{
11185 struct remote_g_packet_data *data
19ba03f4
SM
11186 = ((struct remote_g_packet_data *)
11187 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11188 struct remote_g_packet_guess new_guess, *guess;
11189 int ix;
11190
11191 gdb_assert (tdesc != NULL);
11192
11193 for (ix = 0;
11194 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11195 ix++)
11196 if (guess->bytes == bytes)
11197 internal_error (__FILE__, __LINE__,
9b20d036 11198 _("Duplicate g packet description added for size %d"),
29709017
DJ
11199 bytes);
11200
11201 new_guess.bytes = bytes;
11202 new_guess.tdesc = tdesc;
11203 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11204}
11205
d962ef82
DJ
11206/* Return 1 if remote_read_description would do anything on this target
11207 and architecture, 0 otherwise. */
11208
11209static int
11210remote_read_description_p (struct target_ops *target)
11211{
11212 struct remote_g_packet_data *data
19ba03f4
SM
11213 = ((struct remote_g_packet_data *)
11214 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
11215
11216 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11217 return 1;
11218
11219 return 0;
11220}
11221
29709017
DJ
11222static const struct target_desc *
11223remote_read_description (struct target_ops *target)
11224{
11225 struct remote_g_packet_data *data
19ba03f4
SM
11226 = ((struct remote_g_packet_data *)
11227 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11228
d962ef82
DJ
11229 /* Do not try this during initial connection, when we do not know
11230 whether there is a running but stopped thread. */
11231 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 11232 return target->beneath->to_read_description (target->beneath);
d962ef82 11233
29709017
DJ
11234 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11235 {
11236 struct remote_g_packet_guess *guess;
11237 int ix;
11238 int bytes = send_g_packet ();
11239
11240 for (ix = 0;
11241 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11242 ix++)
11243 if (guess->bytes == bytes)
11244 return guess->tdesc;
11245
11246 /* We discard the g packet. A minor optimization would be to
11247 hold on to it, and fill the register cache once we have selected
11248 an architecture, but it's too tricky to do safely. */
11249 }
11250
2117c711 11251 return target->beneath->to_read_description (target->beneath);
29709017
DJ
11252}
11253
a6b151f1
DJ
11254/* Remote file transfer support. This is host-initiated I/O, not
11255 target-initiated; for target-initiated, see remote-fileio.c. */
11256
11257/* If *LEFT is at least the length of STRING, copy STRING to
11258 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11259 decrease *LEFT. Otherwise raise an error. */
11260
11261static void
a121b7c1 11262remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11263{
11264 int len = strlen (string);
11265
11266 if (len > *left)
11267 error (_("Packet too long for target."));
11268
11269 memcpy (*buffer, string, len);
11270 *buffer += len;
11271 *left -= len;
11272
11273 /* NUL-terminate the buffer as a convenience, if there is
11274 room. */
11275 if (*left)
11276 **buffer = '\0';
11277}
11278
11279/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11280 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11281 decrease *LEFT. Otherwise raise an error. */
11282
11283static void
11284remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11285 int len)
11286{
11287 if (2 * len > *left)
11288 error (_("Packet too long for target."));
11289
11290 bin2hex (bytes, *buffer, len);
11291 *buffer += 2 * len;
11292 *left -= 2 * len;
11293
11294 /* NUL-terminate the buffer as a convenience, if there is
11295 room. */
11296 if (*left)
11297 **buffer = '\0';
11298}
11299
11300/* If *LEFT is large enough, convert VALUE to hex and add it to
11301 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11302 decrease *LEFT. Otherwise raise an error. */
11303
11304static void
11305remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11306{
11307 int len = hexnumlen (value);
11308
11309 if (len > *left)
11310 error (_("Packet too long for target."));
11311
11312 hexnumstr (*buffer, value);
11313 *buffer += len;
11314 *left -= len;
11315
11316 /* NUL-terminate the buffer as a convenience, if there is
11317 room. */
11318 if (*left)
11319 **buffer = '\0';
11320}
11321
11322/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11323 value, *REMOTE_ERRNO to the remote error number or zero if none
11324 was included, and *ATTACHMENT to point to the start of the annex
11325 if any. The length of the packet isn't needed here; there may
11326 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11327
11328 Return 0 if the packet could be parsed, -1 if it could not. If
11329 -1 is returned, the other variables may not be initialized. */
11330
11331static int
11332remote_hostio_parse_result (char *buffer, int *retcode,
11333 int *remote_errno, char **attachment)
11334{
11335 char *p, *p2;
11336
11337 *remote_errno = 0;
11338 *attachment = NULL;
11339
11340 if (buffer[0] != 'F')
11341 return -1;
11342
11343 errno = 0;
11344 *retcode = strtol (&buffer[1], &p, 16);
11345 if (errno != 0 || p == &buffer[1])
11346 return -1;
11347
11348 /* Check for ",errno". */
11349 if (*p == ',')
11350 {
11351 errno = 0;
11352 *remote_errno = strtol (p + 1, &p2, 16);
11353 if (errno != 0 || p + 1 == p2)
11354 return -1;
11355 p = p2;
11356 }
11357
11358 /* Check for ";attachment". If there is no attachment, the
11359 packet should end here. */
11360 if (*p == ';')
11361 {
11362 *attachment = p + 1;
11363 return 0;
11364 }
11365 else if (*p == '\0')
11366 return 0;
11367 else
11368 return -1;
11369}
11370
11371/* Send a prepared I/O packet to the target and read its response.
11372 The prepared packet is in the global RS->BUF before this function
11373 is called, and the answer is there when we return.
11374
11375 COMMAND_BYTES is the length of the request to send, which may include
11376 binary data. WHICH_PACKET is the packet configuration to check
11377 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11378 is set to the error number and -1 is returned. Otherwise the value
11379 returned by the function is returned.
11380
11381 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11382 attachment is expected; an error will be reported if there's a
11383 mismatch. If one is found, *ATTACHMENT will be set to point into
11384 the packet buffer and *ATTACHMENT_LEN will be set to the
11385 attachment's length. */
11386
11387static int
11388remote_hostio_send_command (int command_bytes, int which_packet,
11389 int *remote_errno, char **attachment,
11390 int *attachment_len)
11391{
11392 struct remote_state *rs = get_remote_state ();
11393 int ret, bytes_read;
11394 char *attachment_tmp;
11395
5d93a237 11396 if (!rs->remote_desc
4082afcc 11397 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11398 {
11399 *remote_errno = FILEIO_ENOSYS;
11400 return -1;
11401 }
11402
11403 putpkt_binary (rs->buf, command_bytes);
11404 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11405
11406 /* If it timed out, something is wrong. Don't try to parse the
11407 buffer. */
11408 if (bytes_read < 0)
11409 {
11410 *remote_errno = FILEIO_EINVAL;
11411 return -1;
11412 }
11413
11414 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11415 {
11416 case PACKET_ERROR:
11417 *remote_errno = FILEIO_EINVAL;
11418 return -1;
11419 case PACKET_UNKNOWN:
11420 *remote_errno = FILEIO_ENOSYS;
11421 return -1;
11422 case PACKET_OK:
11423 break;
11424 }
11425
11426 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11427 &attachment_tmp))
11428 {
11429 *remote_errno = FILEIO_EINVAL;
11430 return -1;
11431 }
11432
11433 /* Make sure we saw an attachment if and only if we expected one. */
11434 if ((attachment_tmp == NULL && attachment != NULL)
11435 || (attachment_tmp != NULL && attachment == NULL))
11436 {
11437 *remote_errno = FILEIO_EINVAL;
11438 return -1;
11439 }
11440
11441 /* If an attachment was found, it must point into the packet buffer;
11442 work out how many bytes there were. */
11443 if (attachment_tmp != NULL)
11444 {
11445 *attachment = attachment_tmp;
11446 *attachment_len = bytes_read - (*attachment - rs->buf);
11447 }
11448
11449 return ret;
11450}
11451
80152258
PA
11452/* Invalidate the readahead cache. */
11453
11454static void
11455readahead_cache_invalidate (void)
11456{
11457 struct remote_state *rs = get_remote_state ();
11458
11459 rs->readahead_cache.fd = -1;
11460}
11461
11462/* Invalidate the readahead cache if it is holding data for FD. */
11463
11464static void
11465readahead_cache_invalidate_fd (int fd)
11466{
11467 struct remote_state *rs = get_remote_state ();
11468
11469 if (rs->readahead_cache.fd == fd)
11470 rs->readahead_cache.fd = -1;
11471}
11472
15a201c8
GB
11473/* Set the filesystem remote_hostio functions that take FILENAME
11474 arguments will use. Return 0 on success, or -1 if an error
11475 occurs (and set *REMOTE_ERRNO). */
11476
11477static int
11478remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11479{
11480 struct remote_state *rs = get_remote_state ();
11481 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11482 char *p = rs->buf;
11483 int left = get_remote_packet_size () - 1;
11484 char arg[9];
11485 int ret;
11486
11487 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11488 return 0;
11489
11490 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11491 return 0;
11492
11493 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11494
11495 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11496 remote_buffer_add_string (&p, &left, arg);
11497
11498 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11499 remote_errno, NULL, NULL);
11500
11501 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11502 return 0;
11503
11504 if (ret == 0)
11505 rs->fs_pid = required_pid;
11506
11507 return ret;
11508}
11509
12e2a5fd 11510/* Implementation of to_fileio_open. */
a6b151f1
DJ
11511
11512static int
cd897586 11513remote_hostio_open (struct target_ops *self,
07c138c8 11514 struct inferior *inf, const char *filename,
4313b8c0
GB
11515 int flags, int mode, int warn_if_slow,
11516 int *remote_errno)
a6b151f1
DJ
11517{
11518 struct remote_state *rs = get_remote_state ();
11519 char *p = rs->buf;
11520 int left = get_remote_packet_size () - 1;
11521
4313b8c0
GB
11522 if (warn_if_slow)
11523 {
11524 static int warning_issued = 0;
11525
11526 printf_unfiltered (_("Reading %s from remote target...\n"),
11527 filename);
11528
11529 if (!warning_issued)
11530 {
11531 warning (_("File transfers from remote targets can be slow."
11532 " Use \"set sysroot\" to access files locally"
11533 " instead."));
11534 warning_issued = 1;
11535 }
11536 }
11537
15a201c8
GB
11538 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11539 return -1;
11540
a6b151f1
DJ
11541 remote_buffer_add_string (&p, &left, "vFile:open:");
11542
11543 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11544 strlen (filename));
11545 remote_buffer_add_string (&p, &left, ",");
11546
11547 remote_buffer_add_int (&p, &left, flags);
11548 remote_buffer_add_string (&p, &left, ",");
11549
11550 remote_buffer_add_int (&p, &left, mode);
11551
11552 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11553 remote_errno, NULL, NULL);
11554}
11555
12e2a5fd 11556/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11557
11558static int
0d866f62
TT
11559remote_hostio_pwrite (struct target_ops *self,
11560 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11561 ULONGEST offset, int *remote_errno)
11562{
11563 struct remote_state *rs = get_remote_state ();
11564 char *p = rs->buf;
11565 int left = get_remote_packet_size ();
11566 int out_len;
11567
80152258
PA
11568 readahead_cache_invalidate_fd (fd);
11569
a6b151f1
DJ
11570 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11571
11572 remote_buffer_add_int (&p, &left, fd);
11573 remote_buffer_add_string (&p, &left, ",");
11574
11575 remote_buffer_add_int (&p, &left, offset);
11576 remote_buffer_add_string (&p, &left, ",");
11577
124e13d9 11578 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11579 get_remote_packet_size () - (p - rs->buf));
11580
11581 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11582 remote_errno, NULL, NULL);
11583}
11584
80152258
PA
11585/* Helper for the implementation of to_fileio_pread. Read the file
11586 from the remote side with vFile:pread. */
a6b151f1
DJ
11587
11588static int
80152258
PA
11589remote_hostio_pread_vFile (struct target_ops *self,
11590 int fd, gdb_byte *read_buf, int len,
11591 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11592{
11593 struct remote_state *rs = get_remote_state ();
11594 char *p = rs->buf;
11595 char *attachment;
11596 int left = get_remote_packet_size ();
11597 int ret, attachment_len;
11598 int read_len;
11599
11600 remote_buffer_add_string (&p, &left, "vFile:pread:");
11601
11602 remote_buffer_add_int (&p, &left, fd);
11603 remote_buffer_add_string (&p, &left, ",");
11604
11605 remote_buffer_add_int (&p, &left, len);
11606 remote_buffer_add_string (&p, &left, ",");
11607
11608 remote_buffer_add_int (&p, &left, offset);
11609
11610 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11611 remote_errno, &attachment,
11612 &attachment_len);
11613
11614 if (ret < 0)
11615 return ret;
11616
bc20a4af 11617 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11618 read_buf, len);
11619 if (read_len != ret)
11620 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11621
11622 return ret;
11623}
11624
80152258
PA
11625/* Serve pread from the readahead cache. Returns number of bytes
11626 read, or 0 if the request can't be served from the cache. */
11627
11628static int
11629remote_hostio_pread_from_cache (struct remote_state *rs,
11630 int fd, gdb_byte *read_buf, size_t len,
11631 ULONGEST offset)
11632{
11633 struct readahead_cache *cache = &rs->readahead_cache;
11634
11635 if (cache->fd == fd
11636 && cache->offset <= offset
11637 && offset < cache->offset + cache->bufsize)
11638 {
11639 ULONGEST max = cache->offset + cache->bufsize;
11640
11641 if (offset + len > max)
11642 len = max - offset;
11643
11644 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11645 return len;
11646 }
11647
11648 return 0;
11649}
11650
11651/* Implementation of to_fileio_pread. */
11652
11653static int
11654remote_hostio_pread (struct target_ops *self,
11655 int fd, gdb_byte *read_buf, int len,
11656 ULONGEST offset, int *remote_errno)
11657{
11658 int ret;
11659 struct remote_state *rs = get_remote_state ();
11660 struct readahead_cache *cache = &rs->readahead_cache;
11661
11662 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11663 if (ret > 0)
11664 {
11665 cache->hit_count++;
11666
11667 if (remote_debug)
11668 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11669 pulongest (cache->hit_count));
11670 return ret;
11671 }
11672
11673 cache->miss_count++;
11674 if (remote_debug)
11675 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11676 pulongest (cache->miss_count));
11677
11678 cache->fd = fd;
11679 cache->offset = offset;
11680 cache->bufsize = get_remote_packet_size ();
224c3ddb 11681 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11682
11683 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11684 cache->offset, remote_errno);
11685 if (ret <= 0)
11686 {
11687 readahead_cache_invalidate_fd (fd);
11688 return ret;
11689 }
11690
11691 cache->bufsize = ret;
11692 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11693}
11694
12e2a5fd 11695/* Implementation of to_fileio_close. */
a6b151f1
DJ
11696
11697static int
df39ea25 11698remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11699{
11700 struct remote_state *rs = get_remote_state ();
11701 char *p = rs->buf;
11702 int left = get_remote_packet_size () - 1;
11703
80152258
PA
11704 readahead_cache_invalidate_fd (fd);
11705
a6b151f1
DJ
11706 remote_buffer_add_string (&p, &left, "vFile:close:");
11707
11708 remote_buffer_add_int (&p, &left, fd);
11709
11710 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11711 remote_errno, NULL, NULL);
11712}
11713
12e2a5fd 11714/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11715
11716static int
dbbca37d 11717remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11718 struct inferior *inf, const char *filename,
11719 int *remote_errno)
a6b151f1
DJ
11720{
11721 struct remote_state *rs = get_remote_state ();
11722 char *p = rs->buf;
11723 int left = get_remote_packet_size () - 1;
11724
15a201c8
GB
11725 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11726 return -1;
11727
a6b151f1
DJ
11728 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11729
11730 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11731 strlen (filename));
11732
11733 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11734 remote_errno, NULL, NULL);
11735}
11736
12e2a5fd 11737/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11738
11739static char *
fab5aa7c 11740remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11741 struct inferior *inf, const char *filename,
11742 int *remote_errno)
b9e7b9c3
UW
11743{
11744 struct remote_state *rs = get_remote_state ();
11745 char *p = rs->buf;
11746 char *attachment;
11747 int left = get_remote_packet_size ();
11748 int len, attachment_len;
11749 int read_len;
11750 char *ret;
11751
15a201c8
GB
11752 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11753 return NULL;
11754
b9e7b9c3
UW
11755 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11756
11757 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11758 strlen (filename));
11759
11760 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11761 remote_errno, &attachment,
11762 &attachment_len);
11763
11764 if (len < 0)
11765 return NULL;
11766
224c3ddb 11767 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11768
bc20a4af
PA
11769 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11770 (gdb_byte *) ret, len);
b9e7b9c3
UW
11771 if (read_len != len)
11772 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11773
11774 ret[len] = '\0';
11775 return ret;
11776}
11777
12e2a5fd 11778/* Implementation of to_fileio_fstat. */
0a93529c
GB
11779
11780static int
11781remote_hostio_fstat (struct target_ops *self,
11782 int fd, struct stat *st,
11783 int *remote_errno)
11784{
11785 struct remote_state *rs = get_remote_state ();
11786 char *p = rs->buf;
11787 int left = get_remote_packet_size ();
11788 int attachment_len, ret;
11789 char *attachment;
11790 struct fio_stat fst;
11791 int read_len;
11792
464b0089
GB
11793 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11794
11795 remote_buffer_add_int (&p, &left, fd);
11796
11797 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11798 remote_errno, &attachment,
11799 &attachment_len);
11800 if (ret < 0)
0a93529c 11801 {
464b0089
GB
11802 if (*remote_errno != FILEIO_ENOSYS)
11803 return ret;
11804
0a93529c
GB
11805 /* Strictly we should return -1, ENOSYS here, but when
11806 "set sysroot remote:" was implemented in August 2008
11807 BFD's need for a stat function was sidestepped with
11808 this hack. This was not remedied until March 2015
11809 so we retain the previous behavior to avoid breaking
11810 compatibility.
11811
11812 Note that the memset is a March 2015 addition; older
11813 GDBs set st_size *and nothing else* so the structure
11814 would have garbage in all other fields. This might
11815 break something but retaining the previous behavior
11816 here would be just too wrong. */
11817
11818 memset (st, 0, sizeof (struct stat));
11819 st->st_size = INT_MAX;
11820 return 0;
11821 }
11822
0a93529c
GB
11823 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11824 (gdb_byte *) &fst, sizeof (fst));
11825
11826 if (read_len != ret)
11827 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11828
11829 if (read_len != sizeof (fst))
11830 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11831 read_len, (int) sizeof (fst));
11832
11833 remote_fileio_to_host_stat (&fst, st);
11834
11835 return 0;
11836}
11837
12e2a5fd 11838/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11839
11840static int
11841remote_filesystem_is_local (struct target_ops *self)
11842{
11843 /* Valgrind GDB presents itself as a remote target but works
11844 on the local filesystem: it does not implement remote get
11845 and users are not expected to set a sysroot. To handle
11846 this case we treat the remote filesystem as local if the
11847 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11848 does not support vFile:open. */
a3be80c3 11849 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11850 {
11851 enum packet_support ps = packet_support (PACKET_vFile_open);
11852
11853 if (ps == PACKET_SUPPORT_UNKNOWN)
11854 {
11855 int fd, remote_errno;
11856
11857 /* Try opening a file to probe support. The supplied
11858 filename is irrelevant, we only care about whether
11859 the stub recognizes the packet or not. */
07c138c8 11860 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11861 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11862 &remote_errno);
11863
11864 if (fd >= 0)
11865 remote_hostio_close (self, fd, &remote_errno);
11866
11867 ps = packet_support (PACKET_vFile_open);
11868 }
11869
11870 if (ps == PACKET_DISABLE)
11871 {
11872 static int warning_issued = 0;
11873
11874 if (!warning_issued)
11875 {
11876 warning (_("remote target does not support file"
11877 " transfer, attempting to access files"
11878 " from local filesystem."));
11879 warning_issued = 1;
11880 }
11881
11882 return 1;
11883 }
11884 }
11885
11886 return 0;
11887}
11888
a6b151f1
DJ
11889static int
11890remote_fileio_errno_to_host (int errnum)
11891{
11892 switch (errnum)
11893 {
11894 case FILEIO_EPERM:
11895 return EPERM;
11896 case FILEIO_ENOENT:
11897 return ENOENT;
11898 case FILEIO_EINTR:
11899 return EINTR;
11900 case FILEIO_EIO:
11901 return EIO;
11902 case FILEIO_EBADF:
11903 return EBADF;
11904 case FILEIO_EACCES:
11905 return EACCES;
11906 case FILEIO_EFAULT:
11907 return EFAULT;
11908 case FILEIO_EBUSY:
11909 return EBUSY;
11910 case FILEIO_EEXIST:
11911 return EEXIST;
11912 case FILEIO_ENODEV:
11913 return ENODEV;
11914 case FILEIO_ENOTDIR:
11915 return ENOTDIR;
11916 case FILEIO_EISDIR:
11917 return EISDIR;
11918 case FILEIO_EINVAL:
11919 return EINVAL;
11920 case FILEIO_ENFILE:
11921 return ENFILE;
11922 case FILEIO_EMFILE:
11923 return EMFILE;
11924 case FILEIO_EFBIG:
11925 return EFBIG;
11926 case FILEIO_ENOSPC:
11927 return ENOSPC;
11928 case FILEIO_ESPIPE:
11929 return ESPIPE;
11930 case FILEIO_EROFS:
11931 return EROFS;
11932 case FILEIO_ENOSYS:
11933 return ENOSYS;
11934 case FILEIO_ENAMETOOLONG:
11935 return ENAMETOOLONG;
11936 }
11937 return -1;
11938}
11939
11940static char *
11941remote_hostio_error (int errnum)
11942{
11943 int host_error = remote_fileio_errno_to_host (errnum);
11944
11945 if (host_error == -1)
11946 error (_("Unknown remote I/O error %d"), errnum);
11947 else
11948 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11949}
11950
a6b151f1
DJ
11951static void
11952remote_hostio_close_cleanup (void *opaque)
11953{
11954 int fd = *(int *) opaque;
11955 int remote_errno;
11956
df39ea25 11957 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11958}
11959
11960void
11961remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11962{
11963 struct cleanup *back_to, *close_cleanup;
11964 int retcode, fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11965 gdb_byte *buffer;
11966 int bytes_in_buffer;
11967 int saw_eof;
11968 ULONGEST offset;
5d93a237 11969 struct remote_state *rs = get_remote_state ();
a6b151f1 11970
5d93a237 11971 if (!rs->remote_desc)
a6b151f1
DJ
11972 error (_("command can only be used with remote target"));
11973
d419f42d 11974 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11975 if (file == NULL)
11976 perror_with_name (local_file);
a6b151f1 11977
07c138c8 11978 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11979 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11980 | FILEIO_O_TRUNC),
4313b8c0 11981 0700, 0, &remote_errno);
a6b151f1
DJ
11982 if (fd == -1)
11983 remote_hostio_error (remote_errno);
11984
11985 /* Send up to this many bytes at once. They won't all fit in the
11986 remote packet limit, so we'll transfer slightly fewer. */
11987 io_size = get_remote_packet_size ();
224c3ddb 11988 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 11989 back_to = make_cleanup (xfree, buffer);
a6b151f1
DJ
11990
11991 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11992
11993 bytes_in_buffer = 0;
11994 saw_eof = 0;
11995 offset = 0;
11996 while (bytes_in_buffer || !saw_eof)
11997 {
11998 if (!saw_eof)
11999 {
3e43a32a
MS
12000 bytes = fread (buffer + bytes_in_buffer, 1,
12001 io_size - bytes_in_buffer,
d419f42d 12002 file.get ());
a6b151f1
DJ
12003 if (bytes == 0)
12004 {
d419f42d 12005 if (ferror (file.get ()))
a6b151f1
DJ
12006 error (_("Error reading %s."), local_file);
12007 else
12008 {
12009 /* EOF. Unless there is something still in the
12010 buffer from the last iteration, we are done. */
12011 saw_eof = 1;
12012 if (bytes_in_buffer == 0)
12013 break;
12014 }
12015 }
12016 }
12017 else
12018 bytes = 0;
12019
12020 bytes += bytes_in_buffer;
12021 bytes_in_buffer = 0;
12022
0d866f62
TT
12023 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
12024 fd, buffer, bytes,
3e43a32a 12025 offset, &remote_errno);
a6b151f1
DJ
12026
12027 if (retcode < 0)
12028 remote_hostio_error (remote_errno);
12029 else if (retcode == 0)
12030 error (_("Remote write of %d bytes returned 0!"), bytes);
12031 else if (retcode < bytes)
12032 {
12033 /* Short write. Save the rest of the read data for the next
12034 write. */
12035 bytes_in_buffer = bytes - retcode;
12036 memmove (buffer, buffer + retcode, bytes_in_buffer);
12037 }
12038
12039 offset += retcode;
12040 }
12041
12042 discard_cleanups (close_cleanup);
df39ea25 12043 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
12044 remote_hostio_error (remote_errno);
12045
12046 if (from_tty)
12047 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12048 do_cleanups (back_to);
12049}
12050
12051void
12052remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12053{
12054 struct cleanup *back_to, *close_cleanup;
cea39f65 12055 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
12056 gdb_byte *buffer;
12057 ULONGEST offset;
5d93a237 12058 struct remote_state *rs = get_remote_state ();
a6b151f1 12059
5d93a237 12060 if (!rs->remote_desc)
a6b151f1
DJ
12061 error (_("command can only be used with remote target"));
12062
07c138c8 12063 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
12064 remote_file, FILEIO_O_RDONLY, 0, 0,
12065 &remote_errno);
a6b151f1
DJ
12066 if (fd == -1)
12067 remote_hostio_error (remote_errno);
12068
d419f42d 12069 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12070 if (file == NULL)
12071 perror_with_name (local_file);
a6b151f1
DJ
12072
12073 /* Send up to this many bytes at once. They won't all fit in the
12074 remote packet limit, so we'll transfer slightly fewer. */
12075 io_size = get_remote_packet_size ();
224c3ddb 12076 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 12077 back_to = make_cleanup (xfree, buffer);
a6b151f1
DJ
12078
12079 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12080
12081 offset = 0;
12082 while (1)
12083 {
a3be983c
TT
12084 bytes = remote_hostio_pread (find_target_at (process_stratum),
12085 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
12086 if (bytes == 0)
12087 /* Success, but no bytes, means end-of-file. */
12088 break;
12089 if (bytes == -1)
12090 remote_hostio_error (remote_errno);
12091
12092 offset += bytes;
12093
d419f42d 12094 bytes = fwrite (buffer, 1, bytes, file.get ());
a6b151f1
DJ
12095 if (bytes == 0)
12096 perror_with_name (local_file);
12097 }
12098
12099 discard_cleanups (close_cleanup);
df39ea25 12100 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
12101 remote_hostio_error (remote_errno);
12102
12103 if (from_tty)
12104 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12105 do_cleanups (back_to);
12106}
12107
12108void
12109remote_file_delete (const char *remote_file, int from_tty)
12110{
12111 int retcode, remote_errno;
5d93a237 12112 struct remote_state *rs = get_remote_state ();
a6b151f1 12113
5d93a237 12114 if (!rs->remote_desc)
a6b151f1
DJ
12115 error (_("command can only be used with remote target"));
12116
dbbca37d 12117 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 12118 NULL, remote_file, &remote_errno);
a6b151f1
DJ
12119 if (retcode == -1)
12120 remote_hostio_error (remote_errno);
12121
12122 if (from_tty)
12123 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12124}
12125
12126static void
ac88e2de 12127remote_put_command (const char *args, int from_tty)
a6b151f1 12128{
d1a41061
PP
12129 if (args == NULL)
12130 error_no_arg (_("file to put"));
12131
773a1edc 12132 gdb_argv argv (args);
a6b151f1
DJ
12133 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12134 error (_("Invalid parameters to remote put"));
12135
12136 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12137}
12138
12139static void
ac88e2de 12140remote_get_command (const char *args, int from_tty)
a6b151f1 12141{
d1a41061
PP
12142 if (args == NULL)
12143 error_no_arg (_("file to get"));
12144
773a1edc 12145 gdb_argv argv (args);
a6b151f1
DJ
12146 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12147 error (_("Invalid parameters to remote get"));
12148
12149 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12150}
12151
12152static void
ac88e2de 12153remote_delete_command (const char *args, int from_tty)
a6b151f1 12154{
d1a41061
PP
12155 if (args == NULL)
12156 error_no_arg (_("file to delete"));
12157
773a1edc 12158 gdb_argv argv (args);
a6b151f1
DJ
12159 if (argv[0] == NULL || argv[1] != NULL)
12160 error (_("Invalid parameters to remote delete"));
12161
12162 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12163}
12164
12165static void
12166remote_command (char *args, int from_tty)
12167{
635c7e8a 12168 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12169}
12170
b2175913 12171static int
19db3e69 12172remote_can_execute_reverse (struct target_ops *self)
b2175913 12173{
4082afcc
PA
12174 if (packet_support (PACKET_bs) == PACKET_ENABLE
12175 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
12176 return 1;
12177 else
12178 return 0;
b2175913
MS
12179}
12180
74531fed 12181static int
2a9a2795 12182remote_supports_non_stop (struct target_ops *self)
74531fed
PA
12183{
12184 return 1;
12185}
12186
03583c20 12187static int
2bfc0540 12188remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
12189{
12190 /* Only supported in extended mode. */
12191 return 0;
12192}
12193
8a305172 12194static int
86ce2668 12195remote_supports_multi_process (struct target_ops *self)
8a305172
PA
12196{
12197 struct remote_state *rs = get_remote_state ();
a744cf53 12198
8020350c 12199 return remote_multi_process_p (rs);
8a305172
PA
12200}
12201
70221824 12202static int
782b2b07
SS
12203remote_supports_cond_tracepoints (void)
12204{
4082afcc 12205 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12206}
12207
3788aec7 12208static int
efcc2da7 12209remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 12210{
4082afcc 12211 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12212}
12213
70221824 12214static int
7a697b8d
SS
12215remote_supports_fast_tracepoints (void)
12216{
4082afcc 12217 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12218}
12219
0fb4aa4b
PA
12220static int
12221remote_supports_static_tracepoints (void)
12222{
4082afcc 12223 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12224}
12225
1e4d1764
YQ
12226static int
12227remote_supports_install_in_trace (void)
12228{
4082afcc 12229 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12230}
12231
d248b706 12232static int
7d178d6a 12233remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 12234{
4082afcc
PA
12235 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12236 == PACKET_ENABLE);
d248b706
KY
12237}
12238
3065dfb6 12239static int
6de37a3a 12240remote_supports_string_tracing (struct target_ops *self)
3065dfb6 12241{
4082afcc 12242 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12243}
12244
d3ce09f5 12245static int
78eff0ec 12246remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 12247{
4082afcc 12248 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12249}
12250
35b1e5cc 12251static void
ecae04e1 12252remote_trace_init (struct target_ops *self)
35b1e5cc 12253{
b6bb3468
PA
12254 struct remote_state *rs = get_remote_state ();
12255
35b1e5cc 12256 putpkt ("QTinit");
b6bb3468
PA
12257 remote_get_noisy_reply ();
12258 if (strcmp (rs->buf, "OK") != 0)
35b1e5cc
SS
12259 error (_("Target does not support this command."));
12260}
12261
12262static void free_actions_list (char **actions_list);
12263static void free_actions_list_cleanup_wrapper (void *);
12264static void
12265free_actions_list_cleanup_wrapper (void *al)
12266{
19ba03f4 12267 free_actions_list ((char **) al);
35b1e5cc
SS
12268}
12269
12270static void
12271free_actions_list (char **actions_list)
12272{
12273 int ndx;
12274
12275 if (actions_list == 0)
12276 return;
12277
12278 for (ndx = 0; actions_list[ndx]; ndx++)
12279 xfree (actions_list[ndx]);
12280
12281 xfree (actions_list);
12282}
12283
409873ef
SS
12284/* Recursive routine to walk through command list including loops, and
12285 download packets for each command. */
12286
12287static void
12288remote_download_command_source (int num, ULONGEST addr,
12289 struct command_line *cmds)
12290{
12291 struct remote_state *rs = get_remote_state ();
12292 struct command_line *cmd;
12293
12294 for (cmd = cmds; cmd; cmd = cmd->next)
12295 {
0df8b418 12296 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12297 strcpy (rs->buf, "QTDPsrc:");
12298 encode_source_string (num, addr, "cmd", cmd->line,
12299 rs->buf + strlen (rs->buf),
12300 rs->buf_size - strlen (rs->buf));
12301 putpkt (rs->buf);
b6bb3468
PA
12302 remote_get_noisy_reply ();
12303 if (strcmp (rs->buf, "OK"))
409873ef
SS
12304 warning (_("Target does not support source download."));
12305
12306 if (cmd->control_type == while_control
12307 || cmd->control_type == while_stepping_control)
12308 {
12309 remote_download_command_source (num, addr, *cmd->body_list);
12310
0df8b418 12311 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12312 strcpy (rs->buf, "QTDPsrc:");
12313 encode_source_string (num, addr, "cmd", "end",
12314 rs->buf + strlen (rs->buf),
12315 rs->buf_size - strlen (rs->buf));
12316 putpkt (rs->buf);
b6bb3468
PA
12317 remote_get_noisy_reply ();
12318 if (strcmp (rs->buf, "OK"))
409873ef
SS
12319 warning (_("Target does not support source download."));
12320 }
12321 }
12322}
12323
35b1e5cc 12324static void
548f7808 12325remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 12326{
bba74b36 12327#define BUF_SIZE 2048
e8ba3115 12328
35b1e5cc 12329 CORE_ADDR tpaddr;
409873ef 12330 char addrbuf[40];
bba74b36 12331 char buf[BUF_SIZE];
35b1e5cc
SS
12332 char **tdp_actions;
12333 char **stepping_actions;
12334 int ndx;
12335 struct cleanup *old_chain = NULL;
35b1e5cc 12336 char *pkt;
e8ba3115 12337 struct breakpoint *b = loc->owner;
d9b3f62e 12338 struct tracepoint *t = (struct tracepoint *) b;
b6bb3468 12339 struct remote_state *rs = get_remote_state ();
35b1e5cc 12340
dc673c81 12341 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12342 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
12343 tdp_actions);
12344 (void) make_cleanup (free_actions_list_cleanup_wrapper,
12345 stepping_actions);
12346
12347 tpaddr = loc->address;
12348 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
12349 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12350 addrbuf, /* address */
12351 (b->enable_state == bp_enabled ? 'E' : 'D'),
12352 t->step_count, t->pass_count);
e8ba3115
YQ
12353 /* Fast tracepoints are mostly handled by the target, but we can
12354 tell the target how big of an instruction block should be moved
12355 around. */
12356 if (b->type == bp_fast_tracepoint)
12357 {
12358 /* Only test for support at download time; we may not know
12359 target capabilities at definition time. */
12360 if (remote_supports_fast_tracepoints ())
35b1e5cc 12361 {
6b940e6a
PL
12362 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12363 NULL))
bba74b36 12364 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 12365 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 12366 else
e8ba3115
YQ
12367 /* If it passed validation at definition but fails now,
12368 something is very wrong. */
12369 internal_error (__FILE__, __LINE__,
12370 _("Fast tracepoint not "
12371 "valid during download"));
35b1e5cc 12372 }
e8ba3115
YQ
12373 else
12374 /* Fast tracepoints are functionally identical to regular
12375 tracepoints, so don't take lack of support as a reason to
12376 give up on the trace run. */
12377 warning (_("Target does not support fast tracepoints, "
12378 "downloading %d as regular tracepoint"), b->number);
12379 }
12380 else if (b->type == bp_static_tracepoint)
12381 {
12382 /* Only test for support at download time; we may not know
12383 target capabilities at definition time. */
12384 if (remote_supports_static_tracepoints ())
0fb4aa4b 12385 {
e8ba3115 12386 struct static_tracepoint_marker marker;
0fb4aa4b 12387
e8ba3115
YQ
12388 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12389 strcat (buf, ":S");
0fb4aa4b 12390 else
e8ba3115 12391 error (_("Static tracepoint not valid during download"));
0fb4aa4b 12392 }
e8ba3115
YQ
12393 else
12394 /* Fast tracepoints are functionally identical to regular
12395 tracepoints, so don't take lack of support as a reason
12396 to give up on the trace run. */
12397 error (_("Target does not support static tracepoints"));
12398 }
12399 /* If the tracepoint has a conditional, make it into an agent
12400 expression and append to the definition. */
12401 if (loc->cond)
12402 {
12403 /* Only test support at download time, we may not know target
12404 capabilities at definition time. */
12405 if (remote_supports_cond_tracepoints ())
35b1e5cc 12406 {
833177a4 12407 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
bba74b36
YQ
12408 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12409 aexpr->len);
e8ba3115
YQ
12410 pkt = buf + strlen (buf);
12411 for (ndx = 0; ndx < aexpr->len; ++ndx)
12412 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12413 *pkt = '\0';
35b1e5cc 12414 }
e8ba3115
YQ
12415 else
12416 warning (_("Target does not support conditional tracepoints, "
12417 "ignoring tp %d cond"), b->number);
12418 }
35b1e5cc 12419
d9b3f62e 12420 if (b->commands || *default_collect)
e8ba3115
YQ
12421 strcat (buf, "-");
12422 putpkt (buf);
b6bb3468
PA
12423 remote_get_noisy_reply ();
12424 if (strcmp (rs->buf, "OK"))
e8ba3115 12425 error (_("Target does not support tracepoints."));
35b1e5cc 12426
e8ba3115
YQ
12427 /* do_single_steps (t); */
12428 if (tdp_actions)
12429 {
12430 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 12431 {
e8ba3115 12432 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
12433 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12434 b->number, addrbuf, /* address */
12435 tdp_actions[ndx],
12436 ((tdp_actions[ndx + 1] || stepping_actions)
12437 ? '-' : 0));
e8ba3115 12438 putpkt (buf);
b6bb3468
PA
12439 remote_get_noisy_reply ();
12440 if (strcmp (rs->buf, "OK"))
e8ba3115 12441 error (_("Error on target while setting tracepoints."));
35b1e5cc 12442 }
e8ba3115
YQ
12443 }
12444 if (stepping_actions)
12445 {
12446 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 12447 {
e8ba3115 12448 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
12449 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12450 b->number, addrbuf, /* address */
12451 ((ndx == 0) ? "S" : ""),
12452 stepping_actions[ndx],
12453 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115 12454 putpkt (buf);
b6bb3468
PA
12455 remote_get_noisy_reply ();
12456 if (strcmp (rs->buf, "OK"))
e8ba3115 12457 error (_("Error on target while setting tracepoints."));
35b1e5cc 12458 }
e8ba3115 12459 }
409873ef 12460
4082afcc 12461 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 12462 {
f00aae0f 12463 if (b->location != NULL)
409873ef 12464 {
e8ba3115 12465 strcpy (buf, "QTDPsrc:");
f00aae0f 12466 encode_source_string (b->number, loc->address, "at",
d28cd78a 12467 event_location_to_string (b->location.get ()),
f00aae0f 12468 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115 12469 putpkt (buf);
b6bb3468
PA
12470 remote_get_noisy_reply ();
12471 if (strcmp (rs->buf, "OK"))
e8ba3115 12472 warning (_("Target does not support source download."));
409873ef 12473 }
e8ba3115
YQ
12474 if (b->cond_string)
12475 {
12476 strcpy (buf, "QTDPsrc:");
12477 encode_source_string (b->number, loc->address,
12478 "cond", b->cond_string, buf + strlen (buf),
12479 2048 - strlen (buf));
12480 putpkt (buf);
b6bb3468
PA
12481 remote_get_noisy_reply ();
12482 if (strcmp (rs->buf, "OK"))
e8ba3115
YQ
12483 warning (_("Target does not support source download."));
12484 }
12485 remote_download_command_source (b->number, loc->address,
12486 breakpoint_commands (b));
35b1e5cc 12487 }
e8ba3115
YQ
12488
12489 do_cleanups (old_chain);
35b1e5cc
SS
12490}
12491
1e4d1764 12492static int
a52a8357 12493remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 12494{
1e51243a
PA
12495 struct remote_state *rs = get_remote_state ();
12496 struct trace_status *ts;
12497 int status;
12498
12499 /* Don't try to install tracepoints until we've relocated our
12500 symbols, and fetched and merged the target's tracepoint list with
12501 ours. */
12502 if (rs->starting_up)
12503 return 0;
12504
12505 ts = current_trace_status ();
8bd200f1 12506 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
12507
12508 if (status == -1 || !ts->running_known || !ts->running)
12509 return 0;
12510
12511 /* If we are in a tracing experiment, but remote stub doesn't support
12512 installing tracepoint in trace, we have to return. */
12513 if (!remote_supports_install_in_trace ())
12514 return 0;
12515
12516 return 1;
12517}
12518
12519
35b1e5cc 12520static void
559d2b81
TT
12521remote_download_trace_state_variable (struct target_ops *self,
12522 struct trace_state_variable *tsv)
35b1e5cc
SS
12523{
12524 struct remote_state *rs = get_remote_state ();
00bf0b85 12525 char *p;
35b1e5cc 12526
bba74b36
YQ
12527 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12528 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12529 tsv->builtin);
00bf0b85
SS
12530 p = rs->buf + strlen (rs->buf);
12531 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12532 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 12533 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 12534 *p++ = '\0';
35b1e5cc 12535 putpkt (rs->buf);
b6bb3468
PA
12536 remote_get_noisy_reply ();
12537 if (*rs->buf == '\0')
ad91cd99 12538 error (_("Target does not support this command."));
b6bb3468 12539 if (strcmp (rs->buf, "OK") != 0)
ad91cd99 12540 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12541}
12542
d248b706 12543static void
46670d57
TT
12544remote_enable_tracepoint (struct target_ops *self,
12545 struct bp_location *location)
d248b706
KY
12546{
12547 struct remote_state *rs = get_remote_state ();
12548 char addr_buf[40];
12549
12550 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12551 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12552 location->owner->number, addr_buf);
d248b706 12553 putpkt (rs->buf);
b6bb3468 12554 remote_get_noisy_reply ();
d248b706
KY
12555 if (*rs->buf == '\0')
12556 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12557 if (strcmp (rs->buf, "OK") != 0)
12558 error (_("Error on target while enabling tracepoint."));
12559}
12560
12561static void
780b049c
TT
12562remote_disable_tracepoint (struct target_ops *self,
12563 struct bp_location *location)
d248b706
KY
12564{
12565 struct remote_state *rs = get_remote_state ();
12566 char addr_buf[40];
12567
12568 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12569 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12570 location->owner->number, addr_buf);
d248b706 12571 putpkt (rs->buf);
b6bb3468 12572 remote_get_noisy_reply ();
d248b706
KY
12573 if (*rs->buf == '\0')
12574 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12575 if (strcmp (rs->buf, "OK") != 0)
12576 error (_("Error on target while disabling tracepoint."));
12577}
12578
35b1e5cc 12579static void
583f9a86 12580remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12581{
12582 asection *s;
81b9b86e 12583 bfd *abfd = NULL;
35b1e5cc 12584 bfd_size_type size;
608bcef2 12585 bfd_vma vma;
35b1e5cc 12586 int anysecs = 0;
c2fa21f1 12587 int offset = 0;
35b1e5cc
SS
12588
12589 if (!exec_bfd)
12590 return; /* No information to give. */
12591
b6bb3468
PA
12592 struct remote_state *rs = get_remote_state ();
12593
12594 strcpy (rs->buf, "QTro");
12595 offset = strlen (rs->buf);
35b1e5cc
SS
12596 for (s = exec_bfd->sections; s; s = s->next)
12597 {
12598 char tmp1[40], tmp2[40];
c2fa21f1 12599 int sec_length;
35b1e5cc
SS
12600
12601 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12602 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12603 (s->flags & SEC_READONLY) == 0)
12604 continue;
12605
12606 anysecs = 1;
81b9b86e 12607 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12608 size = bfd_get_section_size (s);
608bcef2
HZ
12609 sprintf_vma (tmp1, vma);
12610 sprintf_vma (tmp2, vma + size);
c2fa21f1 12611 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
b6bb3468 12612 if (offset + sec_length + 1 > rs->buf_size)
c2fa21f1 12613 {
4082afcc 12614 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12615 warning (_("\
c2fa21f1
HZ
12616Too many sections for read-only sections definition packet."));
12617 break;
12618 }
b6bb3468 12619 xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
bba74b36 12620 tmp1, tmp2);
c2fa21f1 12621 offset += sec_length;
35b1e5cc
SS
12622 }
12623 if (anysecs)
12624 {
b6bb3468
PA
12625 putpkt (rs->buf);
12626 getpkt (&rs->buf, &rs->buf_size, 0);
35b1e5cc
SS
12627 }
12628}
12629
12630static void
e2d1aae3 12631remote_trace_start (struct target_ops *self)
35b1e5cc 12632{
b6bb3468
PA
12633 struct remote_state *rs = get_remote_state ();
12634
35b1e5cc 12635 putpkt ("QTStart");
b6bb3468
PA
12636 remote_get_noisy_reply ();
12637 if (*rs->buf == '\0')
ad91cd99 12638 error (_("Target does not support this command."));
b6bb3468
PA
12639 if (strcmp (rs->buf, "OK") != 0)
12640 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
12641}
12642
12643static int
8bd200f1 12644remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12645{
953b98d1 12646 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12647 char *p = NULL;
0df8b418 12648 /* FIXME we need to get register block size some other way. */
00bf0b85 12649 extern int trace_regblock_size;
bd3eecc3 12650 enum packet_result result;
b6bb3468 12651 struct remote_state *rs = get_remote_state ();
bd3eecc3 12652
4082afcc 12653 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12654 return -1;
a744cf53 12655
00bf0b85
SS
12656 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12657
049dc89b
JK
12658 putpkt ("qTStatus");
12659
492d29ea 12660 TRY
67f41397 12661 {
b6bb3468 12662 p = remote_get_noisy_reply ();
67f41397 12663 }
492d29ea 12664 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12665 {
598d3636
JK
12666 if (ex.error != TARGET_CLOSE_ERROR)
12667 {
12668 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12669 return -1;
12670 }
12671 throw_exception (ex);
67f41397 12672 }
492d29ea 12673 END_CATCH
00bf0b85 12674
bd3eecc3
PA
12675 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12676
00bf0b85 12677 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12678 if (result == PACKET_UNKNOWN)
00bf0b85 12679 return -1;
35b1e5cc 12680
00bf0b85 12681 /* We're working with a live target. */
f5911ea1 12682 ts->filename = NULL;
00bf0b85 12683
00bf0b85 12684 if (*p++ != 'T')
b6bb3468 12685 error (_("Bogus trace status reply from target: %s"), rs->buf);
35b1e5cc 12686
84cebc4a
YQ
12687 /* Function 'parse_trace_status' sets default value of each field of
12688 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12689 parse_trace_status (p, ts);
12690
12691 return ts->running;
35b1e5cc
SS
12692}
12693
70221824 12694static void
db90e85c 12695remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12696 struct uploaded_tp *utp)
12697{
12698 struct remote_state *rs = get_remote_state ();
f196051f
SS
12699 char *reply;
12700 struct bp_location *loc;
12701 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12702 size_t size = get_remote_packet_size ();
f196051f
SS
12703
12704 if (tp)
12705 {
c1fc2657 12706 tp->hit_count = 0;
f196051f 12707 tp->traceframe_usage = 0;
c1fc2657 12708 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
12709 {
12710 /* If the tracepoint was never downloaded, don't go asking for
12711 any status. */
12712 if (tp->number_on_target == 0)
12713 continue;
bba74b36
YQ
12714 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12715 phex_nz (loc->address, 0));
f196051f 12716 putpkt (rs->buf);
b6bb3468 12717 reply = remote_get_noisy_reply ();
f196051f
SS
12718 if (reply && *reply)
12719 {
12720 if (*reply == 'V')
12721 parse_tracepoint_status (reply + 1, bp, utp);
12722 }
12723 }
12724 }
12725 else if (utp)
12726 {
12727 utp->hit_count = 0;
12728 utp->traceframe_usage = 0;
bba74b36
YQ
12729 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12730 phex_nz (utp->addr, 0));
f196051f 12731 putpkt (rs->buf);
b6bb3468 12732 reply = remote_get_noisy_reply ();
f196051f
SS
12733 if (reply && *reply)
12734 {
12735 if (*reply == 'V')
12736 parse_tracepoint_status (reply + 1, bp, utp);
12737 }
12738 }
12739}
12740
35b1e5cc 12741static void
74499f1b 12742remote_trace_stop (struct target_ops *self)
35b1e5cc 12743{
b6bb3468
PA
12744 struct remote_state *rs = get_remote_state ();
12745
35b1e5cc 12746 putpkt ("QTStop");
b6bb3468
PA
12747 remote_get_noisy_reply ();
12748 if (*rs->buf == '\0')
ad91cd99 12749 error (_("Target does not support this command."));
b6bb3468
PA
12750 if (strcmp (rs->buf, "OK") != 0)
12751 error (_("Bogus reply from target: %s"), rs->buf);
35b1e5cc
SS
12752}
12753
12754static int
bd4c6793
TT
12755remote_trace_find (struct target_ops *self,
12756 enum trace_find_type type, int num,
cc5925ad 12757 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12758 int *tpp)
12759{
12760 struct remote_state *rs = get_remote_state ();
bba74b36 12761 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12762 char *p, *reply;
12763 int target_frameno = -1, target_tracept = -1;
12764
e6e4e701
PA
12765 /* Lookups other than by absolute frame number depend on the current
12766 trace selected, so make sure it is correct on the remote end
12767 first. */
12768 if (type != tfind_number)
12769 set_remote_traceframe ();
12770
35b1e5cc
SS
12771 p = rs->buf;
12772 strcpy (p, "QTFrame:");
12773 p = strchr (p, '\0');
12774 switch (type)
12775 {
12776 case tfind_number:
bba74b36 12777 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12778 break;
12779 case tfind_pc:
bba74b36 12780 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12781 break;
12782 case tfind_tp:
bba74b36 12783 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12784 break;
12785 case tfind_range:
bba74b36
YQ
12786 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12787 phex_nz (addr2, 0));
35b1e5cc
SS
12788 break;
12789 case tfind_outside:
bba74b36
YQ
12790 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12791 phex_nz (addr2, 0));
35b1e5cc
SS
12792 break;
12793 default:
9b20d036 12794 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12795 }
12796
12797 putpkt (rs->buf);
b6bb3468 12798 reply = remote_get_noisy_reply ();
ad91cd99
PA
12799 if (*reply == '\0')
12800 error (_("Target does not support this command."));
35b1e5cc
SS
12801
12802 while (reply && *reply)
12803 switch (*reply)
12804 {
12805 case 'F':
f197e0f1
VP
12806 p = ++reply;
12807 target_frameno = (int) strtol (p, &reply, 16);
12808 if (reply == p)
12809 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12810 /* Don't update our remote traceframe number cache on failure
12811 to select a remote traceframe. */
f197e0f1
VP
12812 if (target_frameno == -1)
12813 return -1;
35b1e5cc
SS
12814 break;
12815 case 'T':
f197e0f1
VP
12816 p = ++reply;
12817 target_tracept = (int) strtol (p, &reply, 16);
12818 if (reply == p)
12819 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12820 break;
12821 case 'O': /* "OK"? */
12822 if (reply[1] == 'K' && reply[2] == '\0')
12823 reply += 2;
12824 else
12825 error (_("Bogus reply from target: %s"), reply);
12826 break;
12827 default:
12828 error (_("Bogus reply from target: %s"), reply);
12829 }
12830 if (tpp)
12831 *tpp = target_tracept;
e6e4e701 12832
262e1174 12833 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12834 return target_frameno;
12835}
12836
12837static int
4011015b
TT
12838remote_get_trace_state_variable_value (struct target_ops *self,
12839 int tsvnum, LONGEST *val)
35b1e5cc
SS
12840{
12841 struct remote_state *rs = get_remote_state ();
12842 char *reply;
12843 ULONGEST uval;
12844
e6e4e701
PA
12845 set_remote_traceframe ();
12846
bba74b36 12847 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc 12848 putpkt (rs->buf);
b6bb3468 12849 reply = remote_get_noisy_reply ();
35b1e5cc
SS
12850 if (reply && *reply)
12851 {
12852 if (*reply == 'V')
12853 {
12854 unpack_varlen_hex (reply + 1, &uval);
12855 *val = (LONGEST) uval;
12856 return 1;
12857 }
12858 }
12859 return 0;
12860}
12861
00bf0b85 12862static int
dc3decaf 12863remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12864{
12865 struct remote_state *rs = get_remote_state ();
12866 char *p, *reply;
12867
12868 p = rs->buf;
12869 strcpy (p, "QTSave:");
12870 p += strlen (p);
12871 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12872 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12873 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12874 *p++ = '\0';
12875 putpkt (rs->buf);
b6bb3468 12876 reply = remote_get_noisy_reply ();
d6c5869f 12877 if (*reply == '\0')
ad91cd99
PA
12878 error (_("Target does not support this command."));
12879 if (strcmp (reply, "OK") != 0)
12880 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12881 return 0;
12882}
12883
12884/* This is basically a memory transfer, but needs to be its own packet
12885 because we don't know how the target actually organizes its trace
12886 memory, plus we want to be able to ask for as much as possible, but
12887 not be unhappy if we don't get as much as we ask for. */
12888
12889static LONGEST
88ee6f45
TT
12890remote_get_raw_trace_data (struct target_ops *self,
12891 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12892{
12893 struct remote_state *rs = get_remote_state ();
12894 char *reply;
12895 char *p;
12896 int rslt;
12897
12898 p = rs->buf;
12899 strcpy (p, "qTBuffer:");
12900 p += strlen (p);
12901 p += hexnumstr (p, offset);
12902 *p++ = ',';
12903 p += hexnumstr (p, len);
12904 *p++ = '\0';
12905
12906 putpkt (rs->buf);
b6bb3468 12907 reply = remote_get_noisy_reply ();
00bf0b85
SS
12908 if (reply && *reply)
12909 {
12910 /* 'l' by itself means we're at the end of the buffer and
12911 there is nothing more to get. */
12912 if (*reply == 'l')
12913 return 0;
12914
12915 /* Convert the reply into binary. Limit the number of bytes to
12916 convert according to our passed-in buffer size, rather than
12917 what was returned in the packet; if the target is
12918 unexpectedly generous and gives us a bigger reply than we
12919 asked for, we don't want to crash. */
b6bb3468 12920 rslt = hex2bin (reply, buf, len);
00bf0b85
SS
12921 return rslt;
12922 }
12923
12924 /* Something went wrong, flag as an error. */
12925 return -1;
12926}
12927
35b1e5cc 12928static void
37b25738 12929remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12930{
12931 struct remote_state *rs = get_remote_state ();
12932
4082afcc 12933 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12934 {
ad91cd99
PA
12935 char *reply;
12936
bba74b36 12937 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12938 putpkt (rs->buf);
b6bb3468 12939 reply = remote_get_noisy_reply ();
ad91cd99 12940 if (*reply == '\0')
33da3f1c 12941 error (_("Target does not support this command."));
ad91cd99
PA
12942 if (strcmp (reply, "OK") != 0)
12943 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12944 }
12945 else if (val)
12946 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12947}
12948
dc146f7c
VP
12949static int
12950remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12951{
12952 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12953
fe978cb0
PA
12954 if (info && info->priv)
12955 return info->priv->core;
dc146f7c
VP
12956 return -1;
12957}
12958
4daf5ac0 12959static void
736d5b1f 12960remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12961{
12962 struct remote_state *rs = get_remote_state ();
ad91cd99 12963 char *reply;
4daf5ac0 12964
bba74b36 12965 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12966 putpkt (rs->buf);
b6bb3468 12967 reply = remote_get_noisy_reply ();
ad91cd99 12968 if (*reply == '\0')
4daf5ac0 12969 error (_("Target does not support this command."));
ad91cd99
PA
12970 if (strcmp (reply, "OK") != 0)
12971 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12972}
12973
b3b9301e 12974static struct traceframe_info *
a893e81f 12975remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12976{
12977 char *text;
12978
12979 text = target_read_stralloc (&current_target,
12980 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12981 if (text != NULL)
12982 {
12983 struct traceframe_info *info;
12984 struct cleanup *back_to = make_cleanup (xfree, text);
12985
12986 info = parse_traceframe_info (text);
12987 do_cleanups (back_to);
12988 return info;
12989 }
12990
12991 return NULL;
12992}
12993
405f8e94
SS
12994/* Handle the qTMinFTPILen packet. Returns the minimum length of
12995 instruction on which a fast tracepoint may be placed. Returns -1
12996 if the packet is not supported, and 0 if the minimum instruction
12997 length is unknown. */
12998
12999static int
0e67620a 13000remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
13001{
13002 struct remote_state *rs = get_remote_state ();
13003 char *reply;
13004
e886a173
PA
13005 /* If we're not debugging a process yet, the IPA can't be
13006 loaded. */
13007 if (!target_has_execution)
13008 return 0;
13009
13010 /* Make sure the remote is pointing at the right process. */
13011 set_general_process ();
13012
bba74b36 13013 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94 13014 putpkt (rs->buf);
b6bb3468 13015 reply = remote_get_noisy_reply ();
405f8e94
SS
13016 if (*reply == '\0')
13017 return -1;
13018 else
13019 {
13020 ULONGEST min_insn_len;
13021
13022 unpack_varlen_hex (reply, &min_insn_len);
13023
13024 return (int) min_insn_len;
13025 }
13026}
13027
f6f899bf 13028static void
4da384be 13029remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 13030{
4082afcc 13031 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
13032 {
13033 struct remote_state *rs = get_remote_state ();
13034 char *buf = rs->buf;
13035 char *endbuf = rs->buf + get_remote_packet_size ();
13036 enum packet_result result;
13037
13038 gdb_assert (val >= 0 || val == -1);
13039 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13040 /* Send -1 as literal "-1" to avoid host size dependency. */
13041 if (val < 0)
13042 {
13043 *buf++ = '-';
13044 buf += hexnumstr (buf, (ULONGEST) -val);
13045 }
13046 else
13047 buf += hexnumstr (buf, (ULONGEST) val);
13048
13049 putpkt (rs->buf);
b6bb3468 13050 remote_get_noisy_reply ();
f6f899bf
HAQ
13051 result = packet_ok (rs->buf,
13052 &remote_protocol_packets[PACKET_QTBuffer_size]);
13053
13054 if (result != PACKET_OK)
13055 warning (_("Bogus reply from target: %s"), rs->buf);
13056 }
13057}
13058
f196051f 13059static int
d9e68a2c
TT
13060remote_set_trace_notes (struct target_ops *self,
13061 const char *user, const char *notes,
ca623f82 13062 const char *stop_notes)
f196051f
SS
13063{
13064 struct remote_state *rs = get_remote_state ();
13065 char *reply;
13066 char *buf = rs->buf;
13067 char *endbuf = rs->buf + get_remote_packet_size ();
13068 int nbytes;
13069
13070 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13071 if (user)
13072 {
13073 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13074 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13075 buf += 2 * nbytes;
13076 *buf++ = ';';
13077 }
13078 if (notes)
13079 {
13080 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13081 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13082 buf += 2 * nbytes;
13083 *buf++ = ';';
13084 }
13085 if (stop_notes)
13086 {
13087 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13088 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13089 buf += 2 * nbytes;
13090 *buf++ = ';';
13091 }
13092 /* Ensure the buffer is terminated. */
13093 *buf = '\0';
13094
13095 putpkt (rs->buf);
b6bb3468 13096 reply = remote_get_noisy_reply ();
f196051f
SS
13097 if (*reply == '\0')
13098 return 0;
13099
13100 if (strcmp (reply, "OK") != 0)
13101 error (_("Bogus reply from target: %s"), reply);
13102
13103 return 1;
13104}
13105
d1feda86 13106static int
2c152180 13107remote_use_agent (struct target_ops *self, int use)
d1feda86 13108{
4082afcc 13109 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13110 {
13111 struct remote_state *rs = get_remote_state ();
13112
13113 /* If the stub supports QAgent. */
bba74b36 13114 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
13115 putpkt (rs->buf);
13116 getpkt (&rs->buf, &rs->buf_size, 0);
13117
13118 if (strcmp (rs->buf, "OK") == 0)
13119 {
13120 use_agent = use;
13121 return 1;
13122 }
13123 }
13124
13125 return 0;
13126}
13127
13128static int
fe38f897 13129remote_can_use_agent (struct target_ops *self)
d1feda86 13130{
4082afcc 13131 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13132}
13133
9accd112
MM
13134struct btrace_target_info
13135{
13136 /* The ptid of the traced thread. */
13137 ptid_t ptid;
f4abbc16
MM
13138
13139 /* The obtained branch trace configuration. */
13140 struct btrace_config conf;
9accd112
MM
13141};
13142
f4abbc16
MM
13143/* Reset our idea of our target's btrace configuration. */
13144
13145static void
13146remote_btrace_reset (void)
13147{
13148 struct remote_state *rs = get_remote_state ();
13149
13150 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13151}
13152
9accd112
MM
13153/* Check whether the target supports branch tracing. */
13154
13155static int
043c3577 13156remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 13157{
4082afcc 13158 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 13159 return 0;
4082afcc 13160 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
13161 return 0;
13162
043c3577
MM
13163 switch (format)
13164 {
13165 case BTRACE_FORMAT_NONE:
13166 return 0;
13167
13168 case BTRACE_FORMAT_BTS:
13169 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
13170
13171 case BTRACE_FORMAT_PT:
13172 /* The trace is decoded on the host. Even if our target supports it,
13173 we still need to have libipt to decode the trace. */
13174#if defined (HAVE_LIBIPT)
13175 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
13176#else /* !defined (HAVE_LIBIPT) */
13177 return 0;
13178#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
13179 }
13180
13181 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
13182}
13183
f4abbc16
MM
13184/* Synchronize the configuration with the target. */
13185
13186static void
13187btrace_sync_conf (const struct btrace_config *conf)
13188{
d33501a5
MM
13189 struct packet_config *packet;
13190 struct remote_state *rs;
13191 char *buf, *pos, *endbuf;
13192
13193 rs = get_remote_state ();
13194 buf = rs->buf;
13195 endbuf = buf + get_remote_packet_size ();
13196
13197 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13198 if (packet_config_support (packet) == PACKET_ENABLE
13199 && conf->bts.size != rs->btrace_config.bts.size)
13200 {
13201 pos = buf;
13202 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13203 conf->bts.size);
13204
13205 putpkt (buf);
13206 getpkt (&buf, &rs->buf_size, 0);
13207
13208 if (packet_ok (buf, packet) == PACKET_ERROR)
13209 {
13210 if (buf[0] == 'E' && buf[1] == '.')
13211 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13212 else
13213 error (_("Failed to configure the BTS buffer size."));
13214 }
13215
13216 rs->btrace_config.bts.size = conf->bts.size;
13217 }
b20a6524
MM
13218
13219 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13220 if (packet_config_support (packet) == PACKET_ENABLE
13221 && conf->pt.size != rs->btrace_config.pt.size)
13222 {
13223 pos = buf;
13224 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13225 conf->pt.size);
13226
13227 putpkt (buf);
13228 getpkt (&buf, &rs->buf_size, 0);
13229
13230 if (packet_ok (buf, packet) == PACKET_ERROR)
13231 {
13232 if (buf[0] == 'E' && buf[1] == '.')
13233 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13234 else
13235 error (_("Failed to configure the trace buffer size."));
13236 }
13237
13238 rs->btrace_config.pt.size = conf->pt.size;
13239 }
f4abbc16
MM
13240}
13241
13242/* Read the current thread's btrace configuration from the target and
13243 store it into CONF. */
13244
13245static void
13246btrace_read_config (struct btrace_config *conf)
13247{
13248 char *xml;
13249
13250 xml = target_read_stralloc (&current_target,
b20a6524 13251 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
13252 if (xml != NULL)
13253 {
13254 struct cleanup *cleanup;
13255
13256 cleanup = make_cleanup (xfree, xml);
13257 parse_xml_btrace_conf (conf, xml);
13258 do_cleanups (cleanup);
13259 }
13260}
13261
c0272db5
TW
13262/* Maybe reopen target btrace. */
13263
13264static void
13265remote_btrace_maybe_reopen (void)
13266{
13267 struct remote_state *rs = get_remote_state ();
c0272db5
TW
13268 struct thread_info *tp;
13269 int btrace_target_pushed = 0;
13270 int warned = 0;
13271
5ed8105e
PA
13272 scoped_restore_current_thread restore_thread;
13273
c0272db5
TW
13274 ALL_NON_EXITED_THREADS (tp)
13275 {
13276 set_general_thread (tp->ptid);
13277
13278 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13279 btrace_read_config (&rs->btrace_config);
13280
13281 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13282 continue;
13283
13284#if !defined (HAVE_LIBIPT)
13285 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13286 {
13287 if (!warned)
13288 {
13289 warned = 1;
13290 warning (_("GDB does not support Intel Processor Trace. "
13291 "\"record\" will not work in this session."));
13292 }
13293
13294 continue;
13295 }
13296#endif /* !defined (HAVE_LIBIPT) */
13297
13298 /* Push target, once, but before anything else happens. This way our
13299 changes to the threads will be cleaned up by unpushing the target
13300 in case btrace_read_config () throws. */
13301 if (!btrace_target_pushed)
13302 {
13303 btrace_target_pushed = 1;
13304 record_btrace_push_target ();
13305 printf_filtered (_("Target is recording using %s.\n"),
13306 btrace_format_string (rs->btrace_config.format));
13307 }
13308
13309 tp->btrace.target = XCNEW (struct btrace_target_info);
13310 tp->btrace.target->ptid = tp->ptid;
13311 tp->btrace.target->conf = rs->btrace_config;
13312 }
c0272db5
TW
13313}
13314
9accd112
MM
13315/* Enable branch tracing. */
13316
13317static struct btrace_target_info *
f4abbc16
MM
13318remote_enable_btrace (struct target_ops *self, ptid_t ptid,
13319 const struct btrace_config *conf)
9accd112
MM
13320{
13321 struct btrace_target_info *tinfo = NULL;
b20a6524 13322 struct packet_config *packet = NULL;
9accd112
MM
13323 struct remote_state *rs = get_remote_state ();
13324 char *buf = rs->buf;
13325 char *endbuf = rs->buf + get_remote_packet_size ();
13326
b20a6524
MM
13327 switch (conf->format)
13328 {
13329 case BTRACE_FORMAT_BTS:
13330 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13331 break;
13332
13333 case BTRACE_FORMAT_PT:
13334 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13335 break;
13336 }
13337
13338 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13339 error (_("Target does not support branch tracing."));
13340
f4abbc16
MM
13341 btrace_sync_conf (conf);
13342
9accd112
MM
13343 set_general_thread (ptid);
13344
13345 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13346 putpkt (rs->buf);
13347 getpkt (&rs->buf, &rs->buf_size, 0);
13348
13349 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13350 {
13351 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13352 error (_("Could not enable branch tracing for %s: %s"),
13353 target_pid_to_str (ptid), rs->buf + 2);
13354 else
13355 error (_("Could not enable branch tracing for %s."),
13356 target_pid_to_str (ptid));
13357 }
13358
8d749320 13359 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13360 tinfo->ptid = ptid;
13361
f4abbc16
MM
13362 /* If we fail to read the configuration, we lose some information, but the
13363 tracing itself is not impacted. */
492d29ea
PA
13364 TRY
13365 {
13366 btrace_read_config (&tinfo->conf);
13367 }
13368 CATCH (err, RETURN_MASK_ERROR)
13369 {
13370 if (err.message != NULL)
13371 warning ("%s", err.message);
13372 }
13373 END_CATCH
f4abbc16 13374
9accd112
MM
13375 return tinfo;
13376}
13377
13378/* Disable branch tracing. */
13379
13380static void
25e95349
TT
13381remote_disable_btrace (struct target_ops *self,
13382 struct btrace_target_info *tinfo)
9accd112
MM
13383{
13384 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13385 struct remote_state *rs = get_remote_state ();
13386 char *buf = rs->buf;
13387 char *endbuf = rs->buf + get_remote_packet_size ();
13388
4082afcc 13389 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13390 error (_("Target does not support branch tracing."));
13391
13392 set_general_thread (tinfo->ptid);
13393
13394 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13395 putpkt (rs->buf);
13396 getpkt (&rs->buf, &rs->buf_size, 0);
13397
13398 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13399 {
13400 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13401 error (_("Could not disable branch tracing for %s: %s"),
13402 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13403 else
13404 error (_("Could not disable branch tracing for %s."),
13405 target_pid_to_str (tinfo->ptid));
13406 }
13407
13408 xfree (tinfo);
13409}
13410
13411/* Teardown branch tracing. */
13412
13413static void
1777056d
TT
13414remote_teardown_btrace (struct target_ops *self,
13415 struct btrace_target_info *tinfo)
9accd112
MM
13416{
13417 /* We must not talk to the target during teardown. */
13418 xfree (tinfo);
13419}
13420
13421/* Read the branch trace. */
13422
969c39fb 13423static enum btrace_error
39c49f83 13424remote_read_btrace (struct target_ops *self,
734b0e4b 13425 struct btrace_data *btrace,
969c39fb 13426 struct btrace_target_info *tinfo,
9accd112
MM
13427 enum btrace_read_type type)
13428{
13429 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
969c39fb 13430 struct cleanup *cleanup;
9accd112
MM
13431 const char *annex;
13432 char *xml;
13433
4082afcc 13434 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13435 error (_("Target does not support branch tracing."));
13436
13437#if !defined(HAVE_LIBEXPAT)
13438 error (_("Cannot process branch tracing result. XML parsing not supported."));
13439#endif
13440
13441 switch (type)
13442 {
864089d2 13443 case BTRACE_READ_ALL:
9accd112
MM
13444 annex = "all";
13445 break;
864089d2 13446 case BTRACE_READ_NEW:
9accd112
MM
13447 annex = "new";
13448 break;
969c39fb
MM
13449 case BTRACE_READ_DELTA:
13450 annex = "delta";
13451 break;
9accd112
MM
13452 default:
13453 internal_error (__FILE__, __LINE__,
13454 _("Bad branch tracing read type: %u."),
13455 (unsigned int) type);
13456 }
13457
13458 xml = target_read_stralloc (&current_target,
b20a6524 13459 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
13460 if (xml == NULL)
13461 return BTRACE_ERR_UNKNOWN;
9accd112 13462
969c39fb 13463 cleanup = make_cleanup (xfree, xml);
734b0e4b 13464 parse_xml_btrace (btrace, xml);
969c39fb 13465 do_cleanups (cleanup);
9accd112 13466
969c39fb 13467 return BTRACE_ERR_NONE;
9accd112
MM
13468}
13469
f4abbc16
MM
13470static const struct btrace_config *
13471remote_btrace_conf (struct target_ops *self,
13472 const struct btrace_target_info *tinfo)
13473{
13474 return &tinfo->conf;
13475}
13476
ced63ec0 13477static int
5436ff03 13478remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 13479{
4082afcc
PA
13480 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13481 == PACKET_ENABLE);
ced63ec0
GB
13482}
13483
9dd130a0
TT
13484/* Implementation of to_load. */
13485
13486static void
9cbe5fff 13487remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
13488{
13489 generic_load (name, from_tty);
13490}
13491
c78fa86a
GB
13492/* Accepts an integer PID; returns a string representing a file that
13493 can be opened on the remote side to get the symbols for the child
13494 process. Returns NULL if the operation is not supported. */
13495
13496static char *
13497remote_pid_to_exec_file (struct target_ops *self, int pid)
13498{
13499 static char *filename = NULL;
835205d0
GB
13500 struct inferior *inf;
13501 char *annex = NULL;
c78fa86a
GB
13502
13503 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13504 return NULL;
13505
13506 if (filename != NULL)
13507 xfree (filename);
13508
835205d0
GB
13509 inf = find_inferior_pid (pid);
13510 if (inf == NULL)
13511 internal_error (__FILE__, __LINE__,
13512 _("not currently attached to process %d"), pid);
13513
13514 if (!inf->fake_pid_p)
13515 {
13516 const int annex_size = 9;
13517
224c3ddb 13518 annex = (char *) alloca (annex_size);
835205d0
GB
13519 xsnprintf (annex, annex_size, "%x", pid);
13520 }
13521
c78fa86a
GB
13522 filename = target_read_stralloc (&current_target,
13523 TARGET_OBJECT_EXEC_FILE, annex);
13524
13525 return filename;
13526}
13527
750ce8d1
YQ
13528/* Implement the to_can_do_single_step target_ops method. */
13529
13530static int
13531remote_can_do_single_step (struct target_ops *ops)
13532{
13533 /* We can only tell whether target supports single step or not by
13534 supported s and S vCont actions if the stub supports vContSupported
13535 feature. If the stub doesn't support vContSupported feature,
13536 we have conservatively to think target doesn't supports single
13537 step. */
13538 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13539 {
13540 struct remote_state *rs = get_remote_state ();
13541
13542 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13543 remote_vcont_probe (rs);
13544
13545 return rs->supports_vCont.s && rs->supports_vCont.S;
13546 }
13547 else
13548 return 0;
13549}
13550
3a00c802
PA
13551/* Implementation of the to_execution_direction method for the remote
13552 target. */
13553
13554static enum exec_direction_kind
13555remote_execution_direction (struct target_ops *self)
13556{
13557 struct remote_state *rs = get_remote_state ();
13558
13559 return rs->last_resume_exec_dir;
13560}
13561
f6327dcb
KB
13562/* Return pointer to the thread_info struct which corresponds to
13563 THREAD_HANDLE (having length HANDLE_LEN). */
13564
13565static struct thread_info *
13566remote_thread_handle_to_thread_info (struct target_ops *ops,
13567 const gdb_byte *thread_handle,
13568 int handle_len,
13569 struct inferior *inf)
13570{
13571 struct thread_info *tp;
13572
13573 ALL_NON_EXITED_THREADS (tp)
13574 {
13575 struct private_thread_info *priv = get_private_info_thread (tp);
13576
13577 if (tp->inf == inf && priv != NULL)
13578 {
13579 if (handle_len != priv->thread_handle->size ())
13580 error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13581 handle_len, priv->thread_handle->size ());
13582 if (memcmp (thread_handle, priv->thread_handle->data (),
13583 handle_len) == 0)
13584 return tp;
13585 }
13586 }
13587
13588 return NULL;
13589}
13590
c906108c 13591static void
fba45db2 13592init_remote_ops (void)
c906108c 13593{
c5aa993b 13594 remote_ops.to_shortname = "remote";
c906108c 13595 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 13596 remote_ops.to_doc =
c906108c 13597 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
13598Specify the serial device it is connected to\n\
13599(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
13600 remote_ops.to_open = remote_open;
13601 remote_ops.to_close = remote_close;
c906108c 13602 remote_ops.to_detach = remote_detach;
6ad8ae5c 13603 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 13604 remote_ops.to_resume = remote_resume;
85ad3aaf 13605 remote_ops.to_commit_resume = remote_commit_resume;
c906108c
SS
13606 remote_ops.to_wait = remote_wait;
13607 remote_ops.to_fetch_registers = remote_fetch_registers;
13608 remote_ops.to_store_registers = remote_store_registers;
13609 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 13610 remote_ops.to_files_info = remote_files_info;
c906108c
SS
13611 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13612 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
13613 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13614 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13615 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13616 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
13617 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13618 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
13619 remote_ops.to_watchpoint_addr_within_range =
13620 remote_watchpoint_addr_within_range;
3c3bea1c
GS
13621 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13622 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13623 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
13624 remote_ops.to_region_ok_for_hw_watchpoint
13625 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
13626 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13627 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 13628 remote_ops.to_kill = remote_kill;
9dd130a0 13629 remote_ops.to_load = remote_load;
c906108c 13630 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 13631 remote_ops.to_pass_signals = remote_pass_signals;
82075af2 13632 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
9b224c5e 13633 remote_ops.to_program_signals = remote_program_signals;
c906108c 13634 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 13635 remote_ops.to_thread_name = remote_thread_name;
e8032dde 13636 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 13637 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 13638 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 13639 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 13640 remote_ops.to_stop = remote_stop;
bfedc46a 13641 remote_ops.to_interrupt = remote_interrupt;
93692b58 13642 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
4b8a223f 13643 remote_ops.to_xfer_partial = remote_xfer_partial;
09c98b44 13644 remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
96baa820 13645 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 13646 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 13647 remote_ops.to_log_command = serial_log_command;
38691318 13648 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 13649 remote_ops.to_stratum = process_stratum;
c35b1492
PA
13650 remote_ops.to_has_all_memory = default_child_has_all_memory;
13651 remote_ops.to_has_memory = default_child_has_memory;
13652 remote_ops.to_has_stack = default_child_has_stack;
13653 remote_ops.to_has_registers = default_child_has_registers;
13654 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 13655 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13656 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13657 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13658 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13659 remote_ops.to_flash_erase = remote_flash_erase;
13660 remote_ops.to_flash_done = remote_flash_done;
29709017 13661 remote_ops.to_read_description = remote_read_description;
08388c79 13662 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13663 remote_ops.to_can_async_p = remote_can_async_p;
13664 remote_ops.to_is_async_p = remote_is_async_p;
13665 remote_ops.to_async = remote_async;
65706a29 13666 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13667 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13668 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13669 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13670 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13671 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13672 remote_ops.to_supports_disable_randomization
13673 = remote_supports_disable_randomization;
4bd7dc42 13674 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13675 remote_ops.to_fileio_open = remote_hostio_open;
13676 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13677 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13678 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13679 remote_ops.to_fileio_close = remote_hostio_close;
13680 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13681 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13682 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13683 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13684 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13685 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13686 remote_ops.to_trace_init = remote_trace_init;
13687 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13688 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13689 remote_ops.to_download_trace_state_variable
13690 = remote_download_trace_state_variable;
d248b706
KY
13691 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13692 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13693 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13694 remote_ops.to_trace_start = remote_trace_start;
13695 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13696 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13697 remote_ops.to_trace_stop = remote_trace_stop;
13698 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13699 remote_ops.to_get_trace_state_variable_value
13700 = remote_get_trace_state_variable_value;
00bf0b85
SS
13701 remote_ops.to_save_trace_data = remote_save_trace_data;
13702 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13703 remote_ops.to_upload_trace_state_variables
13704 = remote_upload_trace_state_variables;
00bf0b85 13705 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13706 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13707 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13708 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13709 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13710 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13711 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13712 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13713 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13714 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13715 remote_ops.to_static_tracepoint_marker_at
13716 = remote_static_tracepoint_marker_at;
13717 remote_ops.to_static_tracepoint_markers_by_strid
13718 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13719 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13720 remote_ops.to_use_agent = remote_use_agent;
13721 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13722 remote_ops.to_supports_btrace = remote_supports_btrace;
13723 remote_ops.to_enable_btrace = remote_enable_btrace;
13724 remote_ops.to_disable_btrace = remote_disable_btrace;
13725 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13726 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13727 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13728 remote_ops.to_augmented_libraries_svr4_read =
13729 remote_augmented_libraries_svr4_read;
8020350c
DB
13730 remote_ops.to_follow_fork = remote_follow_fork;
13731 remote_ops.to_follow_exec = remote_follow_exec;
13732 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13733 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13734 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13735 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13736 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13737 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
3a00c802 13738 remote_ops.to_execution_direction = remote_execution_direction;
f6327dcb
KB
13739 remote_ops.to_thread_handle_to_thread_info =
13740 remote_thread_handle_to_thread_info;
c906108c
SS
13741}
13742
13743/* Set up the extended remote vector by making a copy of the standard
13744 remote vector and adding to it. */
13745
13746static void
fba45db2 13747init_extended_remote_ops (void)
c906108c
SS
13748{
13749 extended_remote_ops = remote_ops;
13750
0f71a2f6 13751 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13752 extended_remote_ops.to_longname =
c906108c 13753 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13754 extended_remote_ops.to_doc =
c906108c 13755 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13756Specify the serial device it is connected to (e.g. /dev/ttya).";
13757 extended_remote_ops.to_open = extended_remote_open;
c906108c 13758 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
2d717e4f
DJ
13759 extended_remote_ops.to_detach = extended_remote_detach;
13760 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13761 extended_remote_ops.to_post_attach = extended_remote_post_attach;
03583c20
UW
13762 extended_remote_ops.to_supports_disable_randomization
13763 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
13764}
13765
6426a772 13766static int
6a109b6b 13767remote_can_async_p (struct target_ops *ops)
6426a772 13768{
5d93a237
TT
13769 struct remote_state *rs = get_remote_state ();
13770
3015c064
SM
13771 /* We don't go async if the user has explicitly prevented it with the
13772 "maint set target-async" command. */
c6ebd6cf 13773 if (!target_async_permitted)
75c99385
PA
13774 return 0;
13775
23860348 13776 /* We're async whenever the serial device is. */
5d93a237 13777 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13778}
13779
13780static int
6a109b6b 13781remote_is_async_p (struct target_ops *ops)
6426a772 13782{
5d93a237
TT
13783 struct remote_state *rs = get_remote_state ();
13784
c6ebd6cf 13785 if (!target_async_permitted)
75c99385
PA
13786 /* We only enable async when the user specifically asks for it. */
13787 return 0;
13788
23860348 13789 /* We're async whenever the serial device is. */
5d93a237 13790 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13791}
13792
2acceee2
JM
13793/* Pass the SERIAL event on and up to the client. One day this code
13794 will be able to delay notifying the client of an event until the
23860348 13795 point where an entire packet has been received. */
2acceee2 13796
2acceee2
JM
13797static serial_event_ftype remote_async_serial_handler;
13798
6426a772 13799static void
819cc324 13800remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13801{
2acceee2
JM
13802 /* Don't propogate error information up to the client. Instead let
13803 the client find out about the error by querying the target. */
6a3753b3 13804 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13805}
13806
74531fed
PA
13807static void
13808remote_async_inferior_event_handler (gdb_client_data data)
13809{
13810 inferior_event_handler (INF_REG_EVENT, NULL);
13811}
13812
2acceee2 13813static void
6a3753b3 13814remote_async (struct target_ops *ops, int enable)
2acceee2 13815{
5d93a237
TT
13816 struct remote_state *rs = get_remote_state ();
13817
6a3753b3 13818 if (enable)
2acceee2 13819 {
88b496c3 13820 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13821
13822 /* If there are pending events in the stop reply queue tell the
13823 event loop to process them. */
13824 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13825 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13826 /* For simplicity, below we clear the pending events token
13827 without remembering whether it is marked, so here we always
13828 mark it. If there's actually no pending notification to
13829 process, this ends up being a no-op (other than a spurious
13830 event-loop wakeup). */
13831 if (target_is_non_stop_p ())
13832 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13833 }
13834 else
b7d2e916
PA
13835 {
13836 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13837 /* If the core is disabling async, it doesn't want to be
13838 disturbed with target events. Clear all async event sources
13839 too. */
b7d2e916 13840 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13841 if (target_is_non_stop_p ())
13842 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13843 }
6426a772
JM
13844}
13845
65706a29
PA
13846/* Implementation of the to_thread_events method. */
13847
13848static void
13849remote_thread_events (struct target_ops *ops, int enable)
13850{
13851 struct remote_state *rs = get_remote_state ();
13852 size_t size = get_remote_packet_size ();
65706a29
PA
13853
13854 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13855 return;
13856
13857 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13858 putpkt (rs->buf);
13859 getpkt (&rs->buf, &rs->buf_size, 0);
13860
13861 switch (packet_ok (rs->buf,
13862 &remote_protocol_packets[PACKET_QThreadEvents]))
13863 {
13864 case PACKET_OK:
13865 if (strcmp (rs->buf, "OK") != 0)
13866 error (_("Remote refused setting thread events: %s"), rs->buf);
13867 break;
13868 case PACKET_ERROR:
13869 warning (_("Remote failure reply: %s"), rs->buf);
13870 break;
13871 case PACKET_UNKNOWN:
13872 break;
13873 }
13874}
13875
5a2468f5 13876static void
c2d11a7d 13877set_remote_cmd (char *args, int from_tty)
5a2468f5 13878{
635c7e8a 13879 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13880}
13881
d471ea57
AC
13882static void
13883show_remote_cmd (char *args, int from_tty)
13884{
37a105a1 13885 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13886 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 13887 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13888 struct ui_out *uiout = current_uiout;
37a105a1 13889
2e783024 13890 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
13891 for (; list != NULL; list = list->next)
13892 if (strcmp (list->name, "Z-packet") == 0)
13893 continue;
427c3a89
DJ
13894 else if (list->type == not_set_cmd)
13895 /* Alias commands are exactly like the original, except they
13896 don't have the normal type. */
13897 continue;
13898 else
37a105a1 13899 {
2e783024 13900 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 13901
112e8700
SM
13902 uiout->field_string ("name", list->name);
13903 uiout->text (": ");
427c3a89 13904 if (list->type == show_cmd)
f5c4fcd9 13905 do_show_command (NULL, from_tty, list);
427c3a89
DJ
13906 else
13907 cmd_func (list, NULL, from_tty);
37a105a1 13908 }
d471ea57 13909}
5a2468f5 13910
0f71a2f6 13911
23860348 13912/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13913static void
13914remote_new_objfile (struct objfile *objfile)
13915{
5d93a237
TT
13916 struct remote_state *rs = get_remote_state ();
13917
13918 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13919 remote_check_symbols ();
dc8acb97
MS
13920}
13921
00bf0b85
SS
13922/* Pull all the tracepoints defined on the target and create local
13923 data structures representing them. We don't want to create real
13924 tracepoints yet, we don't want to mess up the user's existing
13925 collection. */
13926
13927static int
ab6617cc 13928remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13929{
00bf0b85
SS
13930 struct remote_state *rs = get_remote_state ();
13931 char *p;
d5551862 13932
00bf0b85
SS
13933 /* Ask for a first packet of tracepoint definition. */
13934 putpkt ("qTfP");
13935 getpkt (&rs->buf, &rs->buf_size, 0);
13936 p = rs->buf;
13937 while (*p && *p != 'l')
d5551862 13938 {
00bf0b85
SS
13939 parse_tracepoint_definition (p, utpp);
13940 /* Ask for another packet of tracepoint definition. */
13941 putpkt ("qTsP");
13942 getpkt (&rs->buf, &rs->buf_size, 0);
13943 p = rs->buf;
d5551862 13944 }
00bf0b85 13945 return 0;
d5551862
SS
13946}
13947
00bf0b85 13948static int
181e3713
TT
13949remote_upload_trace_state_variables (struct target_ops *self,
13950 struct uploaded_tsv **utsvp)
d5551862 13951{
00bf0b85 13952 struct remote_state *rs = get_remote_state ();
d5551862 13953 char *p;
d5551862 13954
00bf0b85
SS
13955 /* Ask for a first packet of variable definition. */
13956 putpkt ("qTfV");
d5551862
SS
13957 getpkt (&rs->buf, &rs->buf_size, 0);
13958 p = rs->buf;
00bf0b85 13959 while (*p && *p != 'l')
d5551862 13960 {
00bf0b85
SS
13961 parse_tsv_definition (p, utsvp);
13962 /* Ask for another packet of variable definition. */
13963 putpkt ("qTsV");
d5551862
SS
13964 getpkt (&rs->buf, &rs->buf_size, 0);
13965 p = rs->buf;
13966 }
00bf0b85 13967 return 0;
d5551862
SS
13968}
13969
c1e36e3e
PA
13970/* The "set/show range-stepping" show hook. */
13971
13972static void
13973show_range_stepping (struct ui_file *file, int from_tty,
13974 struct cmd_list_element *c,
13975 const char *value)
13976{
13977 fprintf_filtered (file,
13978 _("Debugger's willingness to use range stepping "
13979 "is %s.\n"), value);
13980}
13981
13982/* The "set/show range-stepping" set hook. */
13983
13984static void
13985set_range_stepping (char *ignore_args, int from_tty,
13986 struct cmd_list_element *c)
13987{
5d93a237
TT
13988 struct remote_state *rs = get_remote_state ();
13989
c1e36e3e
PA
13990 /* Whene enabling, check whether range stepping is actually
13991 supported by the target, and warn if not. */
13992 if (use_range_stepping)
13993 {
5d93a237 13994 if (rs->remote_desc != NULL)
c1e36e3e 13995 {
4082afcc 13996 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13997 remote_vcont_probe (rs);
13998
4082afcc 13999 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
14000 && rs->supports_vCont.r)
14001 return;
14002 }
14003
14004 warning (_("Range stepping is not supported by the current target"));
14005 }
14006}
14007
c906108c 14008void
fba45db2 14009_initialize_remote (void)
c906108c 14010{
9a7071a8 14011 struct cmd_list_element *cmd;
6f937416 14012 const char *cmd_name;
ea9c271d 14013
0f71a2f6 14014 /* architecture specific data */
2bc416ba 14015 remote_gdbarch_data_handle =
23860348 14016 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
14017 remote_g_packet_data_handle =
14018 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 14019
94585166
DB
14020 remote_pspace_data
14021 = register_program_space_data_with_cleanup (NULL,
14022 remote_pspace_data_cleanup);
14023
ea9c271d
DJ
14024 /* Initialize the per-target state. At the moment there is only one
14025 of these, not one per target. Only one target is active at a
cf792862
TT
14026 time. */
14027 remote_state = new_remote_state ();
ea9c271d 14028
c906108c
SS
14029 init_remote_ops ();
14030 add_target (&remote_ops);
14031
14032 init_extended_remote_ops ();
14033 add_target (&extended_remote_ops);
cce74817 14034
dc8acb97 14035 /* Hook into new objfile notification. */
06d3b283 14036 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
14037 /* We're no longer interested in notification events of an inferior
14038 when it exits. */
14039 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 14040
c906108c
SS
14041#if 0
14042 init_remote_threadtests ();
14043#endif
14044
722247f1 14045 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 14046 /* set/show remote ... */
d471ea57 14047
1bedd215 14048 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
14049Remote protocol specific variables\n\
14050Configure various remote-protocol specific variables such as\n\
1bedd215 14051the packets being used"),
cff3e48b 14052 &remote_set_cmdlist, "set remote ",
23860348 14053 0 /* allow-unknown */, &setlist);
1bedd215 14054 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
14055Remote protocol specific variables\n\
14056Configure various remote-protocol specific variables such as\n\
1bedd215 14057the packets being used"),
cff3e48b 14058 &remote_show_cmdlist, "show remote ",
23860348 14059 0 /* allow-unknown */, &showlist);
5a2468f5 14060
1a966eab
AC
14061 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14062Compare section data on target to the exec file.\n\
95cf3b38
DT
14063Argument is a single section name (default: all loaded sections).\n\
14064To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
14065 &cmdlist);
14066
1a966eab
AC
14067 add_cmd ("packet", class_maintenance, packet_command, _("\
14068Send an arbitrary packet to a remote target.\n\
c906108c
SS
14069 maintenance packet TEXT\n\
14070If GDB is talking to an inferior via the GDB serial protocol, then\n\
14071this command sends the string TEXT to the inferior, and displays the\n\
14072response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 14073terminating `#' character and checksum."),
c906108c
SS
14074 &maintenancelist);
14075
7915a72c
AC
14076 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14077Set whether to send break if interrupted."), _("\
14078Show whether to send break if interrupted."), _("\
14079If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14080 set_remotebreak, show_remotebreak,
e707bbc2 14081 &setlist, &showlist);
9a7071a8
JB
14082 cmd_name = "remotebreak";
14083 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14084 deprecate_cmd (cmd, "set remote interrupt-sequence");
14085 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14086 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14087 deprecate_cmd (cmd, "show remote interrupt-sequence");
14088
14089 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14090 interrupt_sequence_modes, &interrupt_sequence_mode,
14091 _("\
9a7071a8
JB
14092Set interrupt sequence to remote target."), _("\
14093Show interrupt sequence to remote target."), _("\
14094Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14095 NULL, show_interrupt_sequence,
14096 &remote_set_cmdlist,
14097 &remote_show_cmdlist);
14098
14099 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14100 &interrupt_on_connect, _("\
14101Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14102Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14103If set, interrupt sequence is sent to remote target."),
14104 NULL, NULL,
14105 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14106
23860348 14107 /* Install commands for configuring memory read/write packets. */
11cf8741 14108
1a966eab
AC
14109 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14110Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14111 &setlist);
1a966eab
AC
14112 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14113Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14114 &showlist);
14115 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14116 set_memory_write_packet_size, _("\
14117Set the maximum number of bytes per memory-write packet.\n\
14118Specify the number of bytes in a packet or 0 (zero) for the\n\
14119default packet size. The actual limit is further reduced\n\
14120dependent on the target. Specify ``fixed'' to disable the\n\
14121further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14122 &remote_set_cmdlist);
14123 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14124 set_memory_read_packet_size, _("\
14125Set the maximum number of bytes per memory-read packet.\n\
14126Specify the number of bytes in a packet or 0 (zero) for the\n\
14127default packet size. The actual limit is further reduced\n\
14128dependent on the target. Specify ``fixed'' to disable the\n\
14129further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14130 &remote_set_cmdlist);
14131 add_cmd ("memory-write-packet-size", no_class,
14132 show_memory_write_packet_size,
1a966eab 14133 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14134 &remote_show_cmdlist);
14135 add_cmd ("memory-read-packet-size", no_class,
14136 show_memory_read_packet_size,
1a966eab 14137 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14138 &remote_show_cmdlist);
c906108c 14139
b3f42336 14140 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14141 &remote_hw_watchpoint_limit, _("\
14142Set the maximum number of target hardware watchpoints."), _("\
14143Show the maximum number of target hardware watchpoints."), _("\
14144Specify a negative limit for unlimited."),
3e43a32a
MS
14145 NULL, NULL, /* FIXME: i18n: The maximum
14146 number of target hardware
14147 watchpoints is %s. */
b3f42336 14148 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
14149 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14150 &remote_hw_watchpoint_length_limit, _("\
14151Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14152Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14153Specify a negative limit for unlimited."),
14154 NULL, NULL, /* FIXME: i18n: The maximum
14155 length (in bytes) of a target
14156 hardware watchpoint is %s. */
14157 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 14158 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14159 &remote_hw_breakpoint_limit, _("\
14160Set the maximum number of target hardware breakpoints."), _("\
14161Show the maximum number of target hardware breakpoints."), _("\
14162Specify a negative limit for unlimited."),
3e43a32a
MS
14163 NULL, NULL, /* FIXME: i18n: The maximum
14164 number of target hardware
14165 breakpoints is %s. */
b3f42336 14166 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14167
1b493192
PA
14168 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14169 &remote_address_size, _("\
4d28ad1e
AC
14170Set the maximum size of the address (in bits) in a memory packet."), _("\
14171Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14172 NULL,
14173 NULL, /* FIXME: i18n: */
14174 &setlist, &showlist);
c906108c 14175
ca4f7f8b
PA
14176 init_all_packet_configs ();
14177
444abaca 14178 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14179 "X", "binary-download", 1);
0f71a2f6 14180
444abaca 14181 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14182 "vCont", "verbose-resume", 0);
506fb367 14183
89be2091
DJ
14184 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14185 "QPassSignals", "pass-signals", 0);
14186
82075af2
JS
14187 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14188 "QCatchSyscalls", "catch-syscalls", 0);
14189
9b224c5e
PA
14190 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14191 "QProgramSignals", "program-signals", 0);
14192
aefd8b33
SDJ
14193 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14194 "QStartupWithShell", "startup-with-shell", 0);
14195
0a2dde4a
SDJ
14196 add_packet_config_cmd (&remote_protocol_packets
14197 [PACKET_QEnvironmentHexEncoded],
14198 "QEnvironmentHexEncoded", "environment-hex-encoded",
14199 0);
14200
14201 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14202 "QEnvironmentReset", "environment-reset",
14203 0);
14204
14205 add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14206 "QEnvironmentUnset", "environment-unset",
14207 0);
14208
444abaca 14209 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14210 "qSymbol", "symbol-lookup", 0);
dc8acb97 14211
444abaca 14212 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14213 "P", "set-register", 1);
d471ea57 14214
444abaca 14215 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14216 "p", "fetch-register", 1);
b96ec7ac 14217
444abaca 14218 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14219 "Z0", "software-breakpoint", 0);
d471ea57 14220
444abaca 14221 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14222 "Z1", "hardware-breakpoint", 0);
d471ea57 14223
444abaca 14224 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14225 "Z2", "write-watchpoint", 0);
d471ea57 14226
444abaca 14227 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14228 "Z3", "read-watchpoint", 0);
d471ea57 14229
444abaca 14230 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14231 "Z4", "access-watchpoint", 0);
d471ea57 14232
0876f84a
DJ
14233 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14234 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14235
c78fa86a
GB
14236 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14237 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14238
23181151
DJ
14239 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14240 "qXfer:features:read", "target-features", 0);
14241
cfa9d6d9
DJ
14242 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14243 "qXfer:libraries:read", "library-info", 0);
14244
2268b414
JK
14245 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14246 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14247
fd79ecee
DJ
14248 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14249 "qXfer:memory-map:read", "memory-map", 0);
14250
0e7f50da
UW
14251 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14252 "qXfer:spu:read", "read-spu-object", 0);
14253
14254 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14255 "qXfer:spu:write", "write-spu-object", 0);
14256
07e059b5
VP
14257 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14258 "qXfer:osdata:read", "osdata", 0);
14259
dc146f7c
VP
14260 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14261 "qXfer:threads:read", "threads", 0);
14262
4aa995e1
PA
14263 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14264 "qXfer:siginfo:read", "read-siginfo-object", 0);
14265
14266 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14267 "qXfer:siginfo:write", "write-siginfo-object", 0);
14268
b3b9301e
PA
14269 add_packet_config_cmd
14270 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14271 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14272
169081d0
TG
14273 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14274 "qXfer:uib:read", "unwind-info-block", 0);
14275
444abaca 14276 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14277 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14278 0);
14279
711e434b
PM
14280 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14281 "qGetTIBAddr", "get-thread-information-block-address",
14282 0);
14283
40ab02ce
MS
14284 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14285 "bc", "reverse-continue", 0);
14286
14287 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14288 "bs", "reverse-step", 0);
14289
be2a5f71
DJ
14290 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14291 "qSupported", "supported-packets", 0);
14292
08388c79
DE
14293 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14294 "qSearch:memory", "search-memory", 0);
14295
bd3eecc3
PA
14296 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14297 "qTStatus", "trace-status", 0);
14298
15a201c8
GB
14299 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14300 "vFile:setfs", "hostio-setfs", 0);
14301
a6b151f1
DJ
14302 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14303 "vFile:open", "hostio-open", 0);
14304
14305 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14306 "vFile:pread", "hostio-pread", 0);
14307
14308 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14309 "vFile:pwrite", "hostio-pwrite", 0);
14310
14311 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14312 "vFile:close", "hostio-close", 0);
14313
14314 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14315 "vFile:unlink", "hostio-unlink", 0);
14316
b9e7b9c3
UW
14317 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14318 "vFile:readlink", "hostio-readlink", 0);
14319
0a93529c
GB
14320 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14321 "vFile:fstat", "hostio-fstat", 0);
14322
2d717e4f
DJ
14323 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14324 "vAttach", "attach", 0);
14325
14326 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14327 "vRun", "run", 0);
14328
a6f3e723
SL
14329 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14330 "QStartNoAckMode", "noack", 0);
14331
82f73884
PA
14332 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14333 "vKill", "kill", 0);
14334
0b16c5cf
PA
14335 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14336 "qAttached", "query-attached", 0);
14337
782b2b07 14338 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14339 "ConditionalTracepoints",
14340 "conditional-tracepoints", 0);
3788aec7
LM
14341
14342 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14343 "ConditionalBreakpoints",
14344 "conditional-breakpoints", 0);
14345
d3ce09f5
SS
14346 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14347 "BreakpointCommands",
14348 "breakpoint-commands", 0);
14349
7a697b8d
SS
14350 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14351 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14352
409873ef
SS
14353 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14354 "TracepointSource", "TracepointSource", 0);
14355
d914c394
SS
14356 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14357 "QAllow", "allow", 0);
14358
0fb4aa4b
PA
14359 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14360 "StaticTracepoints", "static-tracepoints", 0);
14361
1e4d1764
YQ
14362 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14363 "InstallInTrace", "install-in-trace", 0);
14364
0fb4aa4b
PA
14365 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14366 "qXfer:statictrace:read", "read-sdata-object", 0);
14367
78d85199
YQ
14368 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14369 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14370
03583c20
UW
14371 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14372 "QDisableRandomization", "disable-randomization", 0);
14373
d1feda86
YQ
14374 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14375 "QAgent", "agent", 0);
14376
f6f899bf
HAQ
14377 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14378 "QTBuffer:size", "trace-buffer-size", 0);
14379
9accd112
MM
14380 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14381 "Qbtrace:off", "disable-btrace", 0);
14382
14383 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14384 "Qbtrace:bts", "enable-btrace-bts", 0);
14385
14386 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14387 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14388
14389 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14390 "qXfer:btrace", "read-btrace", 0);
14391
f4abbc16
MM
14392 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14393 "qXfer:btrace-conf", "read-btrace-conf", 0);
14394
d33501a5
MM
14395 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14396 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14397
73b8c1fd
PA
14398 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14399 "multiprocess-feature", "multiprocess-feature", 0);
14400
f7e6eed5
PA
14401 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14402 "swbreak-feature", "swbreak-feature", 0);
14403
14404 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14405 "hwbreak-feature", "hwbreak-feature", 0);
14406
89245bc0
DB
14407 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14408 "fork-event-feature", "fork-event-feature", 0);
14409
14410 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14411 "vfork-event-feature", "vfork-event-feature", 0);
14412
b20a6524
MM
14413 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14414 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14415
750ce8d1
YQ
14416 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14417 "vContSupported", "verbose-resume-supported", 0);
14418
94585166
DB
14419 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14420 "exec-event-feature", "exec-event-feature", 0);
14421
de979965
PA
14422 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14423 "vCtrlC", "ctrl-c", 0);
14424
65706a29
PA
14425 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14426 "QThreadEvents", "thread-events", 0);
14427
f2faf941
PA
14428 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14429 "N stop reply", "no-resumed-stop-reply", 0);
14430
0b736949
DB
14431 /* Assert that we've registered "set remote foo-packet" commands
14432 for all packet configs. */
ca4f7f8b
PA
14433 {
14434 int i;
14435
14436 for (i = 0; i < PACKET_MAX; i++)
14437 {
14438 /* Ideally all configs would have a command associated. Some
14439 still don't though. */
14440 int excepted;
14441
14442 switch (i)
14443 {
14444 case PACKET_QNonStop:
ca4f7f8b
PA
14445 case PACKET_EnableDisableTracepoints_feature:
14446 case PACKET_tracenz_feature:
14447 case PACKET_DisconnectedTracing_feature:
14448 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14449 case PACKET_qCRC:
14450 /* Additions to this list need to be well justified:
14451 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14452 excepted = 1;
14453 break;
14454 default:
14455 excepted = 0;
14456 break;
14457 }
14458
14459 /* This catches both forgetting to add a config command, and
14460 forgetting to remove a packet from the exception list. */
14461 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14462 }
14463 }
14464
37a105a1
DJ
14465 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14466 Z sub-packet has its own set and show commands, but users may
14467 have sets to this variable in their .gdbinit files (or in their
14468 documentation). */
e9e68a56 14469 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14470 &remote_Z_packet_detect, _("\
14471Set use of remote protocol `Z' packets"), _("\
14472Show use of remote protocol `Z' packets "), _("\
3b64bf98 14473When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14474packets."),
e9e68a56 14475 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14476 show_remote_protocol_Z_packet_cmd,
14477 /* FIXME: i18n: Use of remote protocol
14478 `Z' packets is %s. */
e9e68a56 14479 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14480
a6b151f1
DJ
14481 add_prefix_cmd ("remote", class_files, remote_command, _("\
14482Manipulate files on the remote system\n\
14483Transfer files to and from the remote target system."),
14484 &remote_cmdlist, "remote ",
14485 0 /* allow-unknown */, &cmdlist);
14486
14487 add_cmd ("put", class_files, remote_put_command,
14488 _("Copy a local file to the remote system."),
14489 &remote_cmdlist);
14490
14491 add_cmd ("get", class_files, remote_get_command,
14492 _("Copy a remote file to the local system."),
14493 &remote_cmdlist);
14494
14495 add_cmd ("delete", class_files, remote_delete_command,
14496 _("Delete a remote file."),
14497 &remote_cmdlist);
14498
2d717e4f 14499 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14500 &remote_exec_file_var, _("\
2d717e4f 14501Set the remote pathname for \"run\""), _("\
94585166
DB
14502Show the remote pathname for \"run\""), NULL,
14503 set_remote_exec_file,
14504 show_remote_exec_file,
14505 &remote_set_cmdlist,
14506 &remote_show_cmdlist);
2d717e4f 14507
c1e36e3e
PA
14508 add_setshow_boolean_cmd ("range-stepping", class_run,
14509 &use_range_stepping, _("\
14510Enable or disable range stepping."), _("\
14511Show whether target-assisted range stepping is enabled."), _("\
14512If on, and the target supports it, when stepping a source line, GDB\n\
14513tells the target to step the corresponding range of addresses itself instead\n\
14514of issuing multiple single-steps. This speeds up source level\n\
14515stepping. If off, GDB always issues single-steps, even if range\n\
14516stepping is supported by the target. The default is on."),
14517 set_range_stepping,
14518 show_range_stepping,
14519 &setlist,
14520 &showlist);
14521
449092f6
CV
14522 /* Eventually initialize fileio. See fileio.c */
14523 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14524
ba348170 14525 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14526 special ptids with it set to != 0. */
ba348170
PA
14527 magic_null_ptid = ptid_build (42000, -1, 1);
14528 not_sent_ptid = ptid_build (42000, -2, 1);
14529 any_thread_ptid = ptid_build (42000, 0, 1);
c906108c 14530}
This page took 4.763744 seconds and 4 git commands to generate.