Class-fy dwarf2_frame_state
[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"
35b1e5cc 76
0df8b418 77/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
78static char *target_buf;
79static long target_buf_size;
35b1e5cc 80
94585166
DB
81/* Per-program-space data key. */
82static const struct program_space_data *remote_pspace_data;
83
84/* The variable registered as the control variable used by the
85 remote exec-file commands. While the remote exec-file setting is
86 per-program-space, the set/show machinery uses this as the
87 location of the remote exec-file value. */
88static char *remote_exec_file_var;
89
6765f3e5
DJ
90/* The size to align memory write packets, when practical. The protocol
91 does not guarantee any alignment, and gdb will generate short
92 writes and unaligned writes, but even as a best-effort attempt this
93 can improve bulk transfers. For instance, if a write is misaligned
94 relative to the target's data bus, the stub may need to make an extra
95 round trip fetching data from the target. This doesn't make a
96 huge difference, but it's easy to do, so we try to be helpful.
97
98 The alignment chosen is arbitrary; usually data bus width is
99 important here, not the possibly larger cache line size. */
100enum { REMOTE_ALIGN_WRITES = 16 };
101
23860348 102/* Prototypes for local functions. */
6d820c5c 103static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 104static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 105 int forever, int *is_notif);
6426a772 106
a14ed312 107static void remote_files_info (struct target_ops *ignore);
c906108c 108
f32dbf8c
MM
109static void remote_prepare_to_store (struct target_ops *self,
110 struct regcache *regcache);
c906108c 111
014f9477
TT
112static void remote_open_1 (const char *, int, struct target_ops *,
113 int extended_p);
c906108c 114
de90e03d 115static void remote_close (struct target_ops *self);
c906108c 116
cbb8991c
DB
117struct remote_state;
118
119static int remote_vkill (int pid, struct remote_state *rs);
120
8020350c
DB
121static void remote_kill_k (void);
122
136d6dae 123static void remote_mourn (struct target_ops *ops);
c906108c 124
a14ed312 125static void extended_remote_restart (void);
c906108c 126
6d820c5c 127static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 128
a14ed312 129static int readchar (int timeout);
c906108c 130
c33e31fd
PA
131static void remote_serial_write (const char *str, int len);
132
7d85a9c0 133static void remote_kill (struct target_ops *ops);
c906108c 134
6a109b6b 135static int remote_can_async_p (struct target_ops *);
75c99385 136
6a109b6b 137static int remote_is_async_p (struct target_ops *);
75c99385 138
6a3753b3 139static void remote_async (struct target_ops *ops, int enable);
75c99385 140
65706a29
PA
141static void remote_thread_events (struct target_ops *ops, int enable);
142
a14ed312 143static void interrupt_query (void);
c906108c 144
d62a8ae2
SM
145static void set_general_thread (ptid_t ptid);
146static void set_continue_thread (ptid_t ptid);
c906108c 147
a14ed312 148static void get_offsets (void);
c906108c 149
6d820c5c
DJ
150static void skip_frame (void);
151
152static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 153
a14ed312 154static int hexnumlen (ULONGEST num);
c906108c 155
a14ed312 156static void init_remote_ops (void);
c906108c 157
a14ed312 158static void init_extended_remote_ops (void);
c906108c 159
1eab8a48 160static void remote_stop (struct target_ops *self, ptid_t);
c906108c 161
a14ed312 162static int stubhex (int ch);
c906108c 163
a14ed312 164static int hexnumstr (char *, ULONGEST);
c906108c 165
a14ed312 166static int hexnumnstr (char *, ULONGEST, int);
2df3850c 167
a14ed312 168static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 169
baa336ce 170static void print_packet (const char *);
c906108c 171
a14ed312 172static void compare_sections_command (char *, int);
c906108c 173
a14ed312 174static void packet_command (char *, int);
c906108c 175
a14ed312 176static int stub_unpack_int (char *buff, int fieldlength);
c906108c 177
39f77062 178static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 179
baa336ce 180static int putpkt_binary (const char *buf, int cnt);
c906108c 181
a14ed312 182static void check_binary_download (CORE_ADDR addr);
c906108c 183
5a2468f5 184struct packet_config;
5a2468f5 185
a14ed312 186static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 187
bb572ddd
DJ
188static void show_remote_protocol_packet_cmd (struct ui_file *file,
189 int from_tty,
190 struct cmd_list_element *c,
191 const char *value);
192
82f73884
PA
193static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
194static ptid_t read_ptid (char *buf, char **obuf);
195
c378d69d 196static void remote_set_permissions (struct target_ops *self);
d914c394 197
8bd200f1
TT
198static int remote_get_trace_status (struct target_ops *self,
199 struct trace_status *ts);
d5551862 200
ab6617cc
TT
201static int remote_upload_tracepoints (struct target_ops *self,
202 struct uploaded_tp **utpp);
00bf0b85 203
181e3713
TT
204static int remote_upload_trace_state_variables (struct target_ops *self,
205 struct uploaded_tsv **utsvp);
00bf0b85 206
c8d104ad
PA
207static void remote_query_supported (void);
208
36d25514 209static void remote_check_symbols (void);
c8d104ad 210
a14ed312 211void _initialize_remote (void);
c906108c 212
74531fed 213struct stop_reply;
74531fed 214static void stop_reply_xfree (struct stop_reply *);
722247f1 215static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 216static void push_stop_reply (struct stop_reply *);
bcc75809 217static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
218static int peek_stop_reply (ptid_t ptid);
219
cbb8991c
DB
220struct threads_listing_context;
221static void remove_new_fork_children (struct threads_listing_context *);
222
74531fed 223static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 224
e3594fd1 225static void remote_terminal_ours (struct target_ops *self);
d3fd5342 226
d962ef82
DJ
227static int remote_read_description_p (struct target_ops *target);
228
176a6961 229static void remote_console_output (char *msg);
dde08ee1 230
efcc2da7 231static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 232
78eff0ec 233static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 234
f4abbc16
MM
235static void remote_btrace_reset (void);
236
c0272db5
TW
237static void remote_btrace_maybe_reopen (void);
238
221e1a37
PA
239static int stop_reply_queue_length (void);
240
80152258
PA
241static void readahead_cache_invalidate (void);
242
048094ac
PA
243static void remote_unpush_and_throw (void);
244
a6b151f1
DJ
245/* For "remote". */
246
247static struct cmd_list_element *remote_cmdlist;
248
bb572ddd
DJ
249/* For "set remote" and "show remote". */
250
251static struct cmd_list_element *remote_set_cmdlist;
252static struct cmd_list_element *remote_show_cmdlist;
253
d458bd84
PA
254/* Stub vCont actions support.
255
256 Each field is a boolean flag indicating whether the stub reports
257 support for the corresponding action. */
258
259struct vCont_action_support
260{
261 /* vCont;t */
262 int t;
c1e36e3e
PA
263
264 /* vCont;r */
265 int r;
750ce8d1
YQ
266
267 /* vCont;s */
268 int s;
269
270 /* vCont;S */
271 int S;
d458bd84
PA
272};
273
c1e36e3e
PA
274/* Controls whether GDB is willing to use range stepping. */
275
276static int use_range_stepping = 1;
277
0d031856
TT
278#define OPAQUETHREADBYTES 8
279
280/* a 64 bit opaque identifier */
281typedef unsigned char threadref[OPAQUETHREADBYTES];
282
283/* About this many threadisds fit in a packet. */
284
285#define MAXTHREADLISTRESULTS 32
286
6f8976bf
YQ
287/* The max number of chars in debug output. The rest of chars are
288 omitted. */
289
290#define REMOTE_DEBUG_MAX_CHAR 512
291
80152258
PA
292/* Data for the vFile:pread readahead cache. */
293
294struct readahead_cache
295{
296 /* The file descriptor for the file that is being cached. -1 if the
297 cache is invalid. */
298 int fd;
299
300 /* The offset into the file that the cache buffer corresponds
301 to. */
302 ULONGEST offset;
303
304 /* The buffer holding the cache contents. */
305 gdb_byte *buf;
306 /* The buffer's size. We try to read as much as fits into a packet
307 at a time. */
308 size_t bufsize;
309
310 /* Cache hit and miss counters. */
311 ULONGEST hit_count;
312 ULONGEST miss_count;
313};
314
ea9c271d
DJ
315/* Description of the remote protocol state for the currently
316 connected target. This is per-target state, and independent of the
317 selected architecture. */
318
319struct remote_state
320{
321 /* A buffer to use for incoming packets, and its current size. The
322 buffer is grown dynamically for larger incoming packets.
323 Outgoing packets may also be constructed in this buffer.
324 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
325 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
326 packets. */
327 char *buf;
328 long buf_size;
be2a5f71 329
1e51243a
PA
330 /* True if we're going through initial connection setup (finding out
331 about the remote side's threads, relocating symbols, etc.). */
332 int starting_up;
333
be2a5f71
DJ
334 /* If we negotiated packet size explicitly (and thus can bypass
335 heuristics for the largest packet size that will not overflow
336 a buffer in the stub), this will be set to that packet size.
337 Otherwise zero, meaning to use the guessed size. */
338 long explicit_packet_size;
2d717e4f
DJ
339
340 /* remote_wait is normally called when the target is running and
341 waits for a stop reply packet. But sometimes we need to call it
342 when the target is already stopped. We can send a "?" packet
343 and have remote_wait read the response. Or, if we already have
344 the response, we can stash it in BUF and tell remote_wait to
345 skip calling getpkt. This flag is set when BUF contains a
346 stop reply packet and the target is not waiting. */
347 int cached_wait_status;
a6f3e723
SL
348
349 /* True, if in no ack mode. That is, neither GDB nor the stub will
350 expect acks from each other. The connection is assumed to be
351 reliable. */
352 int noack_mode;
82f73884
PA
353
354 /* True if we're connected in extended remote mode. */
355 int extended;
356
e24a49d8
PA
357 /* True if we resumed the target and we're waiting for the target to
358 stop. In the mean time, we can't start another command/query.
359 The remote server wouldn't be ready to process it, so we'd
360 timeout waiting for a reply that would never come and eventually
361 we'd close the connection. This can happen in asynchronous mode
362 because we allow GDB commands while the target is running. */
363 int waiting_for_stop_reply;
74531fed 364
d458bd84
PA
365 /* The status of the stub support for the various vCont actions. */
366 struct vCont_action_support supports_vCont;
782b2b07 367
3a29589a
DJ
368 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
369 responded to that. */
370 int ctrlc_pending_p;
5d93a237 371
048094ac
PA
372 /* True if we saw a Ctrl-C while reading or writing from/to the
373 remote descriptor. At that point it is not safe to send a remote
374 interrupt packet, so we instead remember we saw the Ctrl-C and
375 process it once we're done with sending/receiving the current
376 packet, which should be shortly. If however that takes too long,
377 and the user presses Ctrl-C again, we offer to disconnect. */
378 int got_ctrlc_during_io;
379
5d93a237
TT
380 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
381 remote_open knows that we don't have a file open when the program
382 starts. */
383 struct serial *remote_desc;
47f8a51d
TT
384
385 /* These are the threads which we last sent to the remote system. The
386 TID member will be -1 for all or -2 for not sent yet. */
387 ptid_t general_thread;
388 ptid_t continue_thread;
262e1174
TT
389
390 /* This is the traceframe which we last selected on the remote system.
391 It will be -1 if no traceframe is selected. */
392 int remote_traceframe_number;
747dc59d
TT
393
394 char *last_pass_packet;
5e4a05c4
TT
395
396 /* The last QProgramSignals packet sent to the target. We bypass
397 sending a new program signals list down to the target if the new
398 packet is exactly the same as the last we sent. IOW, we only let
399 the target know about program signals list changes. */
400 char *last_program_signals_packet;
b73be471
TT
401
402 enum gdb_signal last_sent_signal;
280ceea3
TT
403
404 int last_sent_step;
8e88304f 405
3a00c802
PA
406 /* The execution direction of the last resume we got. */
407 enum exec_direction_kind last_resume_exec_dir;
408
8e88304f
TT
409 char *finished_object;
410 char *finished_annex;
411 ULONGEST finished_offset;
b80fafe3
TT
412
413 /* Should we try the 'ThreadInfo' query packet?
414
415 This variable (NOT available to the user: auto-detect only!)
416 determines whether GDB will use the new, simpler "ThreadInfo"
417 query or the older, more complex syntax for thread queries.
418 This is an auto-detect variable (set to true at each connect,
419 and set to false when the target fails to recognize it). */
420 int use_threadinfo_query;
421 int use_threadextra_query;
88b496c3 422
0d031856
TT
423 threadref echo_nextthread;
424 threadref nextthread;
425 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
426
427 /* The state of remote notification. */
428 struct remote_notif_state *notif_state;
f4abbc16
MM
429
430 /* The branch trace configuration. */
431 struct btrace_config btrace_config;
15a201c8
GB
432
433 /* The argument to the last "vFile:setfs:" packet we sent, used
434 to avoid sending repeated unnecessary "vFile:setfs:" packets.
435 Initialized to -1 to indicate that no "vFile:setfs:" packet
436 has yet been sent. */
437 int fs_pid;
80152258
PA
438
439 /* A readahead cache for vFile:pread. Often, reading a binary
440 involves a sequence of small reads. E.g., when parsing an ELF
441 file. A readahead cache helps mostly the case of remote
442 debugging on a connection with higher latency, due to the
443 request/reply nature of the RSP. We only cache data for a single
444 file descriptor at a time. */
445 struct readahead_cache readahead_cache;
ea9c271d
DJ
446};
447
dc146f7c
VP
448/* Private data that we'll store in (struct thread_info)->private. */
449struct private_thread_info
450{
451 char *extra;
79efa585 452 char *name;
dc146f7c 453 int core;
799a2abe
PA
454
455 /* Whether the target stopped for a breakpoint/watchpoint. */
456 enum target_stop_reason stop_reason;
457
458 /* This is set to the data address of the access causing the target
459 to stop for a watchpoint. */
460 CORE_ADDR watch_data_address;
85ad3aaf
PA
461
462 /* Fields used by the vCont action coalescing implemented in
463 remote_resume / remote_commit_resume. remote_resume stores each
464 thread's last resume request in these fields, so that a later
465 remote_commit_resume knows which is the proper action for this
466 thread to include in the vCont packet. */
467
468 /* True if the last target_resume call for this thread was a step
469 request, false if a continue request. */
470 int last_resume_step;
471
472 /* The signal specified in the last target_resume call for this
473 thread. */
474 enum gdb_signal last_resume_sig;
475
476 /* Whether this thread was already vCont-resumed on the remote
477 side. */
478 int vcont_resumed;
dc146f7c
VP
479};
480
481static void
482free_private_thread_info (struct private_thread_info *info)
483{
484 xfree (info->extra);
79efa585 485 xfree (info->name);
dc146f7c
VP
486 xfree (info);
487}
488
ea9c271d
DJ
489/* This data could be associated with a target, but we do not always
490 have access to the current target when we need it, so for now it is
491 static. This will be fine for as long as only one target is in use
492 at a time. */
cf792862 493static struct remote_state *remote_state;
ea9c271d
DJ
494
495static struct remote_state *
0b83947e 496get_remote_state_raw (void)
ea9c271d 497{
cf792862
TT
498 return remote_state;
499}
500
501/* Allocate a new struct remote_state with xmalloc, initialize it, and
502 return it. */
503
504static struct remote_state *
505new_remote_state (void)
506{
507 struct remote_state *result = XCNEW (struct remote_state);
508
509 /* The default buffer size is unimportant; it will be expanded
510 whenever a larger buffer is needed. */
511 result->buf_size = 400;
224c3ddb 512 result->buf = (char *) xmalloc (result->buf_size);
262e1174 513 result->remote_traceframe_number = -1;
b73be471 514 result->last_sent_signal = GDB_SIGNAL_0;
3a00c802 515 result->last_resume_exec_dir = EXEC_FORWARD;
15a201c8 516 result->fs_pid = -1;
cf792862
TT
517
518 return result;
ea9c271d
DJ
519}
520
521/* Description of the remote protocol for a given architecture. */
d01949b6 522
ad10f812
AC
523struct packet_reg
524{
525 long offset; /* Offset into G packet. */
526 long regnum; /* GDB's internal register number. */
527 LONGEST pnum; /* Remote protocol register number. */
b323314b 528 int in_g_packet; /* Always part of G packet. */
f5656ead 529 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 530 at present. */
f5656ead 531 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 532 at present. */
ad10f812
AC
533};
534
ea9c271d 535struct remote_arch_state
d01949b6 536{
ad10f812
AC
537 /* Description of the remote protocol registers. */
538 long sizeof_g_packet;
b323314b
AC
539
540 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 541 (making an array gdbarch_num_regs in size). */
b323314b 542 struct packet_reg *regs;
ad10f812 543
d01949b6
AC
544 /* This is the size (in chars) of the first response to the ``g''
545 packet. It is used as a heuristic when determining the maximum
546 size of memory-read and memory-write packets. A target will
547 typically only reserve a buffer large enough to hold the ``g''
548 packet. The size does not include packet overhead (headers and
23860348 549 trailers). */
d01949b6
AC
550 long actual_register_packet_size;
551
552 /* This is the maximum size (in chars) of a non read/write packet.
23860348 553 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
554 long remote_packet_size;
555};
556
35b1e5cc
SS
557/* Utility: generate error from an incoming stub packet. */
558static void
559trace_error (char *buf)
560{
561 if (*buf++ != 'E')
562 return; /* not an error msg */
563 switch (*buf)
564 {
565 case '1': /* malformed packet error */
566 if (*++buf == '0') /* general case: */
567 error (_("remote.c: error in outgoing packet."));
568 else
569 error (_("remote.c: error in outgoing packet at field #%ld."),
570 strtol (buf, NULL, 16));
35b1e5cc
SS
571 default:
572 error (_("Target returns error code '%s'."), buf);
573 }
574}
575
576/* Utility: wait for reply from stub, while accepting "O" packets. */
577static char *
578remote_get_noisy_reply (char **buf_p,
579 long *sizeof_buf)
580{
581 do /* Loop on reply from remote stub. */
582 {
583 char *buf;
a744cf53 584
0df8b418 585 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
586 getpkt (buf_p, sizeof_buf, 0);
587 buf = *buf_p;
ad91cd99 588 if (buf[0] == 'E')
35b1e5cc 589 trace_error (buf);
61012eef 590 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
591 {
592 ULONGEST ul;
593 CORE_ADDR from, to, org_to;
594 char *p, *pp;
595 int adjusted_size = 0;
7556d4a4 596 int relocated = 0;
dde08ee1
PA
597
598 p = buf + strlen ("qRelocInsn:");
599 pp = unpack_varlen_hex (p, &ul);
600 if (*pp != ';')
cb91c06a 601 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
602 from = ul;
603
604 p = pp + 1;
a9cbf802 605 unpack_varlen_hex (p, &ul);
dde08ee1
PA
606 to = ul;
607
608 org_to = to;
609
492d29ea 610 TRY
dde08ee1 611 {
f5656ead 612 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 613 relocated = 1;
dde08ee1 614 }
492d29ea 615 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
616 {
617 if (ex.error == MEMORY_ERROR)
618 {
619 /* Propagate memory errors silently back to the
620 target. The stub may have limited the range of
621 addresses we can write to, for example. */
622 }
623 else
624 {
625 /* Something unexpectedly bad happened. Be verbose
626 so we can tell what, and propagate the error back
627 to the stub, so it doesn't get stuck waiting for
628 a response. */
629 exception_fprintf (gdb_stderr, ex,
630 _("warning: relocating instruction: "));
631 }
632 putpkt ("E01");
633 }
492d29ea 634 END_CATCH
7556d4a4
PA
635
636 if (relocated)
dde08ee1
PA
637 {
638 adjusted_size = to - org_to;
639
bba74b36 640 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
641 putpkt (buf);
642 }
dde08ee1 643 }
ad91cd99 644 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
645 remote_console_output (buf + 1); /* 'O' message from stub */
646 else
0df8b418 647 return buf; /* Here's the actual reply. */
35b1e5cc
SS
648 }
649 while (1);
650}
3c3bea1c 651
d01949b6
AC
652/* Handle for retreving the remote protocol data from gdbarch. */
653static struct gdbarch_data *remote_gdbarch_data_handle;
654
ea9c271d
DJ
655static struct remote_arch_state *
656get_remote_arch_state (void)
d01949b6 657{
17d8546e 658 gdb_assert (target_gdbarch () != NULL);
19ba03f4
SM
659 return ((struct remote_arch_state *)
660 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
d01949b6
AC
661}
662
0b83947e
DJ
663/* Fetch the global remote target state. */
664
665static struct remote_state *
666get_remote_state (void)
667{
668 /* Make sure that the remote architecture state has been
669 initialized, because doing so might reallocate rs->buf. Any
670 function which calls getpkt also needs to be mindful of changes
671 to rs->buf, but this call limits the number of places which run
672 into trouble. */
673 get_remote_arch_state ();
674
675 return get_remote_state_raw ();
676}
677
94585166
DB
678/* Cleanup routine for the remote module's pspace data. */
679
680static void
681remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
682{
19ba03f4 683 char *remote_exec_file = (char *) arg;
94585166
DB
684
685 xfree (remote_exec_file);
686}
687
688/* Fetch the remote exec-file from the current program space. */
689
690static const char *
691get_remote_exec_file (void)
692{
693 char *remote_exec_file;
694
19ba03f4
SM
695 remote_exec_file
696 = (char *) program_space_data (current_program_space,
697 remote_pspace_data);
94585166
DB
698 if (remote_exec_file == NULL)
699 return "";
700
701 return remote_exec_file;
702}
703
704/* Set the remote exec file for PSPACE. */
705
706static void
707set_pspace_remote_exec_file (struct program_space *pspace,
708 char *remote_exec_file)
709{
19ba03f4 710 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
711
712 xfree (old_file);
713 set_program_space_data (pspace, remote_pspace_data,
714 xstrdup (remote_exec_file));
715}
716
717/* The "set/show remote exec-file" set command hook. */
718
719static void
720set_remote_exec_file (char *ignored, int from_tty,
721 struct cmd_list_element *c)
722{
723 gdb_assert (remote_exec_file_var != NULL);
724 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
725}
726
727/* The "set/show remote exec-file" show command hook. */
728
729static void
730show_remote_exec_file (struct ui_file *file, int from_tty,
731 struct cmd_list_element *cmd, const char *value)
732{
733 fprintf_filtered (file, "%s\n", remote_exec_file_var);
734}
735
74ca34ce
DJ
736static int
737compare_pnums (const void *lhs_, const void *rhs_)
738{
19ba03f4
SM
739 const struct packet_reg * const *lhs
740 = (const struct packet_reg * const *) lhs_;
741 const struct packet_reg * const *rhs
742 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
743
744 if ((*lhs)->pnum < (*rhs)->pnum)
745 return -1;
746 else if ((*lhs)->pnum == (*rhs)->pnum)
747 return 0;
748 else
749 return 1;
750}
751
c21236dc
PA
752static int
753map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 754{
74ca34ce 755 int regnum, num_remote_regs, offset;
74ca34ce 756 struct packet_reg **remote_regs;
ea9c271d 757
4a22f64d 758 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 759 {
c21236dc 760 struct packet_reg *r = &regs[regnum];
baef701f 761
4a22f64d 762 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
763 /* Do not try to fetch zero-sized (placeholder) registers. */
764 r->pnum = -1;
765 else
766 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
767
b323314b 768 r->regnum = regnum;
74ca34ce
DJ
769 }
770
771 /* Define the g/G packet format as the contents of each register
772 with a remote protocol number, in order of ascending protocol
773 number. */
774
224c3ddb 775 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 776 for (num_remote_regs = 0, regnum = 0;
4a22f64d 777 regnum < gdbarch_num_regs (gdbarch);
f57d151a 778 regnum++)
c21236dc
PA
779 if (regs[regnum].pnum != -1)
780 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 781
74ca34ce
DJ
782 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
783 compare_pnums);
784
785 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
786 {
787 remote_regs[regnum]->in_g_packet = 1;
788 remote_regs[regnum]->offset = offset;
4a22f64d 789 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
790 }
791
c21236dc
PA
792 return offset;
793}
794
795/* Given the architecture described by GDBARCH, return the remote
796 protocol register's number and the register's offset in the g/G
797 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
798 If the target does not have a mapping for REGNUM, return false,
799 otherwise, return true. */
800
801int
802remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
803 int *pnum, int *poffset)
804{
c21236dc
PA
805 struct packet_reg *regs;
806 struct cleanup *old_chain;
807
808 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
809
224c3ddb 810 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
c21236dc
PA
811 old_chain = make_cleanup (xfree, regs);
812
54887903 813 map_regcache_remote_table (gdbarch, regs);
c21236dc
PA
814
815 *pnum = regs[regnum].pnum;
816 *poffset = regs[regnum].offset;
817
818 do_cleanups (old_chain);
819
820 return *pnum != -1;
821}
822
823static void *
824init_remote_state (struct gdbarch *gdbarch)
825{
826 struct remote_state *rs = get_remote_state_raw ();
827 struct remote_arch_state *rsa;
828
829 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
830
831 /* Use the architecture to build a regnum<->pnum table, which will be
832 1:1 unless a feature set specifies otherwise. */
833 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
834 gdbarch_num_regs (gdbarch),
835 struct packet_reg);
836
74ca34ce
DJ
837 /* Record the maximum possible size of the g packet - it may turn out
838 to be smaller. */
c21236dc 839 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 840
0df8b418 841 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
842 remote stubs have a hardwired buffer size of 400 bytes
843 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
844 as the maximum packet-size to ensure that the packet and an extra
845 NUL character can always fit in the buffer. This stops GDB
846 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
847 already a full buffer (As of 1999-12-04 that was most stubs). */
848 rsa->remote_packet_size = 400 - 1;
d01949b6 849
ea9c271d
DJ
850 /* This one is filled in when a ``g'' packet is received. */
851 rsa->actual_register_packet_size = 0;
852
853 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
854 default, adjust the size accordingly. Remember that each byte is
855 encoded as two characters. 32 is the overhead for the packet
856 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 857 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 858 little. */
ea9c271d
DJ
859 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
860 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 861
ea9c271d
DJ
862 /* Make sure that the packet buffer is plenty big enough for
863 this architecture. */
864 if (rs->buf_size < rsa->remote_packet_size)
865 {
866 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 867 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 868 }
6d820c5c 869
ea9c271d
DJ
870 return rsa;
871}
872
873/* Return the current allowed size of a remote packet. This is
874 inferred from the current architecture, and should be used to
875 limit the length of outgoing packets. */
876static long
877get_remote_packet_size (void)
878{
be2a5f71 879 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
880 struct remote_arch_state *rsa = get_remote_arch_state ();
881
be2a5f71
DJ
882 if (rs->explicit_packet_size)
883 return rs->explicit_packet_size;
884
ea9c271d 885 return rsa->remote_packet_size;
d01949b6
AC
886}
887
ad10f812 888static struct packet_reg *
ea9c271d 889packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 890{
f5656ead 891 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
892 return NULL;
893 else
ad10f812 894 {
ea9c271d 895 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 896
b323314b
AC
897 gdb_assert (r->regnum == regnum);
898 return r;
ad10f812 899 }
ad10f812
AC
900}
901
902static struct packet_reg *
ea9c271d 903packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 904{
b323314b 905 int i;
a744cf53 906
f5656ead 907 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 908 {
ea9c271d 909 struct packet_reg *r = &rsa->regs[i];
a744cf53 910
b323314b
AC
911 if (r->pnum == pnum)
912 return r;
ad10f812
AC
913 }
914 return NULL;
d01949b6
AC
915}
916
c906108c
SS
917static struct target_ops remote_ops;
918
919static struct target_ops extended_remote_ops;
920
6426a772
JM
921/* FIXME: cagney/1999-09-23: Even though getpkt was called with
922 ``forever'' still use the normal timeout mechanism. This is
923 currently used by the ASYNC code to guarentee that target reads
924 during the initial connect always time-out. Once getpkt has been
925 modified to return a timeout indication and, in turn
926 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 927 this can go away. */
6426a772
JM
928static int wait_forever_enabled_p = 1;
929
9a7071a8
JB
930/* Allow the user to specify what sequence to send to the remote
931 when he requests a program interruption: Although ^C is usually
932 what remote systems expect (this is the default, here), it is
933 sometimes preferable to send a break. On other systems such
934 as the Linux kernel, a break followed by g, which is Magic SysRq g
935 is required in order to interrupt the execution. */
936const char interrupt_sequence_control_c[] = "Ctrl-C";
937const char interrupt_sequence_break[] = "BREAK";
938const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 939static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
940 {
941 interrupt_sequence_control_c,
942 interrupt_sequence_break,
943 interrupt_sequence_break_g,
944 NULL
945 };
946static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
947
948static void
949show_interrupt_sequence (struct ui_file *file, int from_tty,
950 struct cmd_list_element *c,
951 const char *value)
952{
953 if (interrupt_sequence_mode == interrupt_sequence_control_c)
954 fprintf_filtered (file,
955 _("Send the ASCII ETX character (Ctrl-c) "
956 "to the remote target to interrupt the "
957 "execution of the program.\n"));
958 else if (interrupt_sequence_mode == interrupt_sequence_break)
959 fprintf_filtered (file,
960 _("send a break signal to the remote target "
961 "to interrupt the execution of the program.\n"));
962 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
963 fprintf_filtered (file,
964 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
965 "the remote target to interrupt the execution "
966 "of Linux kernel.\n"));
967 else
968 internal_error (__FILE__, __LINE__,
969 _("Invalid value for interrupt_sequence_mode: %s."),
970 interrupt_sequence_mode);
971}
6426a772 972
9a7071a8
JB
973/* This boolean variable specifies whether interrupt_sequence is sent
974 to the remote target when gdb connects to it.
975 This is mostly needed when you debug the Linux kernel: The Linux kernel
976 expects BREAK g which is Magic SysRq g for connecting gdb. */
977static int interrupt_on_connect = 0;
c906108c 978
9a7071a8
JB
979/* This variable is used to implement the "set/show remotebreak" commands.
980 Since these commands are now deprecated in favor of "set/show remote
981 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
982static int remote_break;
983
9a7071a8
JB
984static void
985set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
986{
987 if (remote_break)
988 interrupt_sequence_mode = interrupt_sequence_break;
989 else
990 interrupt_sequence_mode = interrupt_sequence_control_c;
991}
992
993static void
994show_remotebreak (struct ui_file *file, int from_tty,
995 struct cmd_list_element *c,
996 const char *value)
997{
998}
999
c906108c
SS
1000/* This variable sets the number of bits in an address that are to be
1001 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 1002 leading zeros, the entire address would be sent. This variable
c906108c
SS
1003 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
1004 initial implementation of remote.c restricted the address sent in
1005 memory packets to ``host::sizeof long'' bytes - (typically 32
1006 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1007 address was never sent. Since fixing this bug may cause a break in
1008 some remote targets this variable is principly provided to
23860348 1009 facilitate backward compatibility. */
c906108c 1010
883b9c6c 1011static unsigned int remote_address_size;
c906108c 1012
75c99385
PA
1013/* Temporary to track who currently owns the terminal. See
1014 remote_terminal_* for more details. */
6426a772
JM
1015
1016static int remote_async_terminal_ours_p;
1017
11cf8741 1018\f
11cf8741 1019/* User configurable variables for the number of characters in a
ea9c271d
DJ
1020 memory read/write packet. MIN (rsa->remote_packet_size,
1021 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1022 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1023 (speed up transfers). The variables ``preferred_*'' (the user
1024 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1025 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1026
1027struct memory_packet_config
1028{
a121b7c1 1029 const char *name;
11cf8741
JM
1030 long size;
1031 int fixed_p;
1032};
1033
a5c0808e
PA
1034/* The default max memory-write-packet-size. The 16k is historical.
1035 (It came from older GDB's using alloca for buffers and the
1036 knowledge (folklore?) that some hosts don't cope very well with
1037 large alloca calls.) */
1038#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1039
1040/* The minimum remote packet size for memory transfers. Ensures we
1041 can write at least one byte. */
1042#define MIN_MEMORY_PACKET_SIZE 20
1043
11cf8741
JM
1044/* Compute the current size of a read/write packet. Since this makes
1045 use of ``actual_register_packet_size'' the computation is dynamic. */
1046
1047static long
1048get_memory_packet_size (struct memory_packet_config *config)
1049{
d01949b6 1050 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
1051 struct remote_arch_state *rsa = get_remote_arch_state ();
1052
11cf8741
JM
1053 long what_they_get;
1054 if (config->fixed_p)
1055 {
1056 if (config->size <= 0)
a5c0808e 1057 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1058 else
1059 what_they_get = config->size;
1060 }
1061 else
1062 {
ea9c271d 1063 what_they_get = get_remote_packet_size ();
23860348 1064 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1065 if (config->size > 0
1066 && what_they_get > config->size)
1067 what_they_get = config->size;
be2a5f71
DJ
1068
1069 /* Limit it to the size of the targets ``g'' response unless we have
1070 permission from the stub to use a larger packet size. */
1071 if (rs->explicit_packet_size == 0
1072 && rsa->actual_register_packet_size > 0
1073 && what_they_get > rsa->actual_register_packet_size)
1074 what_they_get = rsa->actual_register_packet_size;
11cf8741 1075 }
a5c0808e
PA
1076 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1077 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1078
1079 /* Make sure there is room in the global buffer for this packet
1080 (including its trailing NUL byte). */
1081 if (rs->buf_size < what_they_get + 1)
1082 {
1083 rs->buf_size = 2 * what_they_get;
224c3ddb 1084 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1085 }
1086
11cf8741
JM
1087 return what_they_get;
1088}
1089
0df8b418 1090/* Update the size of a read/write packet. If they user wants
23860348 1091 something really big then do a sanity check. */
11cf8741
JM
1092
1093static void
1094set_memory_packet_size (char *args, struct memory_packet_config *config)
1095{
1096 int fixed_p = config->fixed_p;
1097 long size = config->size;
a744cf53 1098
11cf8741 1099 if (args == NULL)
8a3fe4f8 1100 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1101 else if (strcmp (args, "hard") == 0
1102 || strcmp (args, "fixed") == 0)
1103 fixed_p = 1;
1104 else if (strcmp (args, "soft") == 0
1105 || strcmp (args, "limit") == 0)
1106 fixed_p = 0;
1107 else
1108 {
1109 char *end;
a744cf53 1110
11cf8741
JM
1111 size = strtoul (args, &end, 0);
1112 if (args == end)
8a3fe4f8 1113 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1114
1115 /* Instead of explicitly capping the size of a packet to or
1116 disallowing it, the user is allowed to set the size to
1117 something arbitrarily large. */
11cf8741 1118 }
a5c0808e
PA
1119
1120 /* So that the query shows the correct value. */
1121 if (size <= 0)
1122 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1123
23860348 1124 /* Extra checks? */
11cf8741
JM
1125 if (fixed_p && !config->fixed_p)
1126 {
e2e0b3e5
AC
1127 if (! query (_("The target may not be able to correctly handle a %s\n"
1128 "of %ld bytes. Change the packet size? "),
11cf8741 1129 config->name, size))
8a3fe4f8 1130 error (_("Packet size not changed."));
11cf8741 1131 }
23860348 1132 /* Update the config. */
11cf8741
JM
1133 config->fixed_p = fixed_p;
1134 config->size = size;
1135}
1136
1137static void
1138show_memory_packet_size (struct memory_packet_config *config)
1139{
a3f17187 1140 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1141 if (config->fixed_p)
a3f17187 1142 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1143 get_memory_packet_size (config));
1144 else
a3f17187 1145 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1146 get_memory_packet_size (config));
1147}
1148
1149static struct memory_packet_config memory_write_packet_config =
1150{
1151 "memory-write-packet-size",
1152};
1153
1154static void
1155set_memory_write_packet_size (char *args, int from_tty)
1156{
1157 set_memory_packet_size (args, &memory_write_packet_config);
1158}
1159
1160static void
1161show_memory_write_packet_size (char *args, int from_tty)
1162{
1163 show_memory_packet_size (&memory_write_packet_config);
1164}
1165
1166static long
1167get_memory_write_packet_size (void)
1168{
1169 return get_memory_packet_size (&memory_write_packet_config);
1170}
1171
1172static struct memory_packet_config memory_read_packet_config =
1173{
1174 "memory-read-packet-size",
1175};
1176
1177static void
1178set_memory_read_packet_size (char *args, int from_tty)
1179{
1180 set_memory_packet_size (args, &memory_read_packet_config);
1181}
1182
1183static void
1184show_memory_read_packet_size (char *args, int from_tty)
1185{
1186 show_memory_packet_size (&memory_read_packet_config);
1187}
1188
1189static long
1190get_memory_read_packet_size (void)
1191{
1192 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1193
11cf8741
JM
1194 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1195 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1196 increased beyond this. */
1197 if (size > get_remote_packet_size ())
1198 size = get_remote_packet_size ();
11cf8741
JM
1199 return size;
1200}
1201
11cf8741 1202\f
5a2468f5 1203/* Generic configuration support for packets the stub optionally
0df8b418 1204 supports. Allows the user to specify the use of the packet as well
23860348 1205 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1206
1207enum packet_support
1208 {
1209 PACKET_SUPPORT_UNKNOWN = 0,
1210 PACKET_ENABLE,
1211 PACKET_DISABLE
1212 };
1213
5a2468f5
JM
1214struct packet_config
1215 {
bb572ddd
DJ
1216 const char *name;
1217 const char *title;
4082afcc
PA
1218
1219 /* If auto, GDB auto-detects support for this packet or feature,
1220 either through qSupported, or by trying the packet and looking
1221 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1222 packet. If false, the packet is disabled. Configs that don't
1223 have an associated command always have this set to auto. */
7f19b9a2 1224 enum auto_boolean detect;
4082afcc
PA
1225
1226 /* Does the target support this packet? */
5a2468f5
JM
1227 enum packet_support support;
1228 };
1229
d471ea57 1230/* Analyze a packet's return value and update the packet config
23860348 1231 accordingly. */
d471ea57
AC
1232
1233enum packet_result
1234{
1235 PACKET_ERROR,
1236 PACKET_OK,
1237 PACKET_UNKNOWN
1238};
1239
4082afcc
PA
1240static enum packet_support packet_config_support (struct packet_config *config);
1241static enum packet_support packet_support (int packet);
5a2468f5
JM
1242
1243static void
fba45db2 1244show_packet_config_cmd (struct packet_config *config)
5a2468f5 1245{
a121b7c1 1246 const char *support = "internal-error";
a744cf53 1247
4082afcc 1248 switch (packet_config_support (config))
5a2468f5
JM
1249 {
1250 case PACKET_ENABLE:
1251 support = "enabled";
1252 break;
1253 case PACKET_DISABLE:
1254 support = "disabled";
1255 break;
1256 case PACKET_SUPPORT_UNKNOWN:
1257 support = "unknown";
1258 break;
1259 }
1260 switch (config->detect)
1261 {
7f19b9a2 1262 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1263 printf_filtered (_("Support for the `%s' packet "
1264 "is auto-detected, currently %s.\n"),
37a105a1 1265 config->name, support);
5a2468f5 1266 break;
7f19b9a2
AC
1267 case AUTO_BOOLEAN_TRUE:
1268 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1269 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1270 config->name, support);
8e248173 1271 break;
5a2468f5
JM
1272 }
1273}
1274
1275static void
bb572ddd
DJ
1276add_packet_config_cmd (struct packet_config *config, const char *name,
1277 const char *title, int legacy)
d471ea57 1278{
5a2468f5
JM
1279 char *set_doc;
1280 char *show_doc;
d471ea57 1281 char *cmd_name;
3ed07be4 1282
5a2468f5
JM
1283 config->name = name;
1284 config->title = title;
b435e160
AC
1285 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1286 name, title);
3e43a32a
MS
1287 show_doc = xstrprintf ("Show current use of remote "
1288 "protocol `%s' (%s) packet",
b435e160 1289 name, title);
d471ea57 1290 /* set/show TITLE-packet {auto,on,off} */
b435e160 1291 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1292 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1293 &config->detect, set_doc,
1294 show_doc, NULL, /* help_doc */
4082afcc 1295 NULL,
bb572ddd
DJ
1296 show_remote_protocol_packet_cmd,
1297 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1298 /* The command code copies the documentation strings. */
1299 xfree (set_doc);
1300 xfree (show_doc);
23860348 1301 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1302 if (legacy)
1303 {
1304 char *legacy_name;
a744cf53 1305
b435e160 1306 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1307 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1308 &remote_set_cmdlist);
d471ea57 1309 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1310 &remote_show_cmdlist);
d471ea57 1311 }
5a2468f5
JM
1312}
1313
d471ea57 1314static enum packet_result
a76d924d 1315packet_check_result (const char *buf)
5a2468f5 1316{
d471ea57 1317 if (buf[0] != '\0')
5a2468f5 1318 {
d471ea57 1319 /* The stub recognized the packet request. Check that the
23860348 1320 operation succeeded. */
a76d924d
DJ
1321 if (buf[0] == 'E'
1322 && isxdigit (buf[1]) && isxdigit (buf[2])
1323 && buf[3] == '\0')
1324 /* "Enn" - definitly an error. */
1325 return PACKET_ERROR;
1326
1327 /* Always treat "E." as an error. This will be used for
1328 more verbose error messages, such as E.memtypes. */
1329 if (buf[0] == 'E' && buf[1] == '.')
1330 return PACKET_ERROR;
1331
1332 /* The packet may or may not be OK. Just assume it is. */
1333 return PACKET_OK;
1334 }
1335 else
1336 /* The stub does not support the packet. */
1337 return PACKET_UNKNOWN;
1338}
1339
1340static enum packet_result
1341packet_ok (const char *buf, struct packet_config *config)
1342{
1343 enum packet_result result;
1344
4082afcc
PA
1345 if (config->detect != AUTO_BOOLEAN_TRUE
1346 && config->support == PACKET_DISABLE)
1347 internal_error (__FILE__, __LINE__,
1348 _("packet_ok: attempt to use a disabled packet"));
1349
a76d924d
DJ
1350 result = packet_check_result (buf);
1351 switch (result)
1352 {
1353 case PACKET_OK:
1354 case PACKET_ERROR:
1355 /* The stub recognized the packet request. */
4082afcc 1356 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1357 {
d471ea57
AC
1358 if (remote_debug)
1359 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1360 "Packet %s (%s) is supported\n",
1361 config->name, config->title);
d471ea57 1362 config->support = PACKET_ENABLE;
d471ea57 1363 }
a76d924d
DJ
1364 break;
1365 case PACKET_UNKNOWN:
23860348 1366 /* The stub does not support the packet. */
4082afcc
PA
1367 if (config->detect == AUTO_BOOLEAN_AUTO
1368 && config->support == PACKET_ENABLE)
d471ea57 1369 {
4082afcc
PA
1370 /* If the stub previously indicated that the packet was
1371 supported then there is a protocol error. */
1372 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1373 config->name, config->title);
1374 }
1375 else if (config->detect == AUTO_BOOLEAN_TRUE)
1376 {
1377 /* The user set it wrong. */
1378 error (_("Enabled packet %s (%s) not recognized by stub"),
1379 config->name, config->title);
d471ea57 1380 }
4082afcc
PA
1381
1382 if (remote_debug)
1383 fprintf_unfiltered (gdb_stdlog,
1384 "Packet %s (%s) is NOT supported\n",
1385 config->name, config->title);
1386 config->support = PACKET_DISABLE;
a76d924d 1387 break;
5a2468f5 1388 }
a76d924d
DJ
1389
1390 return result;
5a2468f5
JM
1391}
1392
444abaca
DJ
1393enum {
1394 PACKET_vCont = 0,
1395 PACKET_X,
1396 PACKET_qSymbol,
1397 PACKET_P,
1398 PACKET_p,
1399 PACKET_Z0,
1400 PACKET_Z1,
1401 PACKET_Z2,
1402 PACKET_Z3,
1403 PACKET_Z4,
15a201c8 1404 PACKET_vFile_setfs,
a6b151f1
DJ
1405 PACKET_vFile_open,
1406 PACKET_vFile_pread,
1407 PACKET_vFile_pwrite,
1408 PACKET_vFile_close,
1409 PACKET_vFile_unlink,
b9e7b9c3 1410 PACKET_vFile_readlink,
0a93529c 1411 PACKET_vFile_fstat,
0876f84a 1412 PACKET_qXfer_auxv,
23181151 1413 PACKET_qXfer_features,
c78fa86a 1414 PACKET_qXfer_exec_file,
cfa9d6d9 1415 PACKET_qXfer_libraries,
2268b414 1416 PACKET_qXfer_libraries_svr4,
fd79ecee 1417 PACKET_qXfer_memory_map,
0e7f50da
UW
1418 PACKET_qXfer_spu_read,
1419 PACKET_qXfer_spu_write,
07e059b5 1420 PACKET_qXfer_osdata,
dc146f7c 1421 PACKET_qXfer_threads,
0fb4aa4b 1422 PACKET_qXfer_statictrace_read,
b3b9301e 1423 PACKET_qXfer_traceframe_info,
169081d0 1424 PACKET_qXfer_uib,
711e434b 1425 PACKET_qGetTIBAddr,
444abaca 1426 PACKET_qGetTLSAddr,
be2a5f71 1427 PACKET_qSupported,
bd3eecc3 1428 PACKET_qTStatus,
89be2091 1429 PACKET_QPassSignals,
82075af2 1430 PACKET_QCatchSyscalls,
9b224c5e 1431 PACKET_QProgramSignals,
aefd8b33 1432 PACKET_QStartupWithShell,
936d2992 1433 PACKET_qCRC,
08388c79 1434 PACKET_qSearch_memory,
2d717e4f
DJ
1435 PACKET_vAttach,
1436 PACKET_vRun,
a6f3e723 1437 PACKET_QStartNoAckMode,
82f73884 1438 PACKET_vKill,
4aa995e1
PA
1439 PACKET_qXfer_siginfo_read,
1440 PACKET_qXfer_siginfo_write,
0b16c5cf 1441 PACKET_qAttached,
4082afcc
PA
1442
1443 /* Support for conditional tracepoints. */
782b2b07 1444 PACKET_ConditionalTracepoints,
4082afcc
PA
1445
1446 /* Support for target-side breakpoint conditions. */
3788aec7 1447 PACKET_ConditionalBreakpoints,
4082afcc
PA
1448
1449 /* Support for target-side breakpoint commands. */
d3ce09f5 1450 PACKET_BreakpointCommands,
4082afcc
PA
1451
1452 /* Support for fast tracepoints. */
7a697b8d 1453 PACKET_FastTracepoints,
4082afcc
PA
1454
1455 /* Support for static tracepoints. */
0fb4aa4b 1456 PACKET_StaticTracepoints,
4082afcc
PA
1457
1458 /* Support for installing tracepoints while a trace experiment is
1459 running. */
1e4d1764 1460 PACKET_InstallInTrace,
4082afcc 1461
40ab02ce
MS
1462 PACKET_bc,
1463 PACKET_bs,
409873ef 1464 PACKET_TracepointSource,
d914c394 1465 PACKET_QAllow,
78d85199 1466 PACKET_qXfer_fdpic,
03583c20 1467 PACKET_QDisableRandomization,
d1feda86 1468 PACKET_QAgent,
f6f899bf 1469 PACKET_QTBuffer_size,
9accd112
MM
1470 PACKET_Qbtrace_off,
1471 PACKET_Qbtrace_bts,
b20a6524 1472 PACKET_Qbtrace_pt,
9accd112 1473 PACKET_qXfer_btrace,
4082afcc
PA
1474
1475 /* Support for the QNonStop packet. */
1476 PACKET_QNonStop,
1477
65706a29
PA
1478 /* Support for the QThreadEvents packet. */
1479 PACKET_QThreadEvents,
1480
4082afcc
PA
1481 /* Support for multi-process extensions. */
1482 PACKET_multiprocess_feature,
1483
1484 /* Support for enabling and disabling tracepoints while a trace
1485 experiment is running. */
1486 PACKET_EnableDisableTracepoints_feature,
1487
1488 /* Support for collecting strings using the tracenz bytecode. */
1489 PACKET_tracenz_feature,
1490
1491 /* Support for continuing to run a trace experiment while GDB is
1492 disconnected. */
1493 PACKET_DisconnectedTracing_feature,
1494
1495 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1496 PACKET_augmented_libraries_svr4_read_feature,
1497
f4abbc16
MM
1498 /* Support for the qXfer:btrace-conf:read packet. */
1499 PACKET_qXfer_btrace_conf,
1500
d33501a5
MM
1501 /* Support for the Qbtrace-conf:bts:size packet. */
1502 PACKET_Qbtrace_conf_bts_size,
1503
f7e6eed5
PA
1504 /* Support for swbreak+ feature. */
1505 PACKET_swbreak_feature,
1506
1507 /* Support for hwbreak+ feature. */
1508 PACKET_hwbreak_feature,
1509
89245bc0
DB
1510 /* Support for fork events. */
1511 PACKET_fork_event_feature,
1512
1513 /* Support for vfork events. */
1514 PACKET_vfork_event_feature,
1515
b20a6524
MM
1516 /* Support for the Qbtrace-conf:pt:size packet. */
1517 PACKET_Qbtrace_conf_pt_size,
1518
94585166
DB
1519 /* Support for exec events. */
1520 PACKET_exec_event_feature,
1521
750ce8d1
YQ
1522 /* Support for query supported vCont actions. */
1523 PACKET_vContSupported,
1524
de979965
PA
1525 /* Support remote CTRL-C. */
1526 PACKET_vCtrlC,
1527
f2faf941
PA
1528 /* Support TARGET_WAITKIND_NO_RESUMED. */
1529 PACKET_no_resumed,
1530
444abaca
DJ
1531 PACKET_MAX
1532};
506fb367 1533
444abaca 1534static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1535
f7e6eed5
PA
1536/* Returns the packet's corresponding "set remote foo-packet" command
1537 state. See struct packet_config for more details. */
1538
1539static enum auto_boolean
1540packet_set_cmd_state (int packet)
1541{
1542 return remote_protocol_packets[packet].detect;
1543}
1544
4082afcc
PA
1545/* Returns whether a given packet or feature is supported. This takes
1546 into account the state of the corresponding "set remote foo-packet"
1547 command, which may be used to bypass auto-detection. */
dc8acb97 1548
4082afcc
PA
1549static enum packet_support
1550packet_config_support (struct packet_config *config)
1551{
1552 switch (config->detect)
444abaca 1553 {
4082afcc
PA
1554 case AUTO_BOOLEAN_TRUE:
1555 return PACKET_ENABLE;
1556 case AUTO_BOOLEAN_FALSE:
1557 return PACKET_DISABLE;
1558 case AUTO_BOOLEAN_AUTO:
1559 return config->support;
1560 default:
1561 gdb_assert_not_reached (_("bad switch"));
444abaca 1562 }
4082afcc
PA
1563}
1564
1565/* Same as packet_config_support, but takes the packet's enum value as
1566 argument. */
1567
1568static enum packet_support
1569packet_support (int packet)
1570{
1571 struct packet_config *config = &remote_protocol_packets[packet];
1572
1573 return packet_config_support (config);
dc8acb97
MS
1574}
1575
5a2468f5 1576static void
444abaca
DJ
1577show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1578 struct cmd_list_element *c,
1579 const char *value)
5a2468f5 1580{
444abaca 1581 struct packet_config *packet;
5a2468f5 1582
444abaca
DJ
1583 for (packet = remote_protocol_packets;
1584 packet < &remote_protocol_packets[PACKET_MAX];
1585 packet++)
1586 {
1587 if (&packet->detect == c->var)
1588 {
1589 show_packet_config_cmd (packet);
1590 return;
1591 }
1592 }
9b20d036 1593 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1594 c->name);
5a2468f5
JM
1595}
1596
d471ea57
AC
1597/* Should we try one of the 'Z' requests? */
1598
1599enum Z_packet_type
1600{
1601 Z_PACKET_SOFTWARE_BP,
1602 Z_PACKET_HARDWARE_BP,
1603 Z_PACKET_WRITE_WP,
1604 Z_PACKET_READ_WP,
1605 Z_PACKET_ACCESS_WP,
1606 NR_Z_PACKET_TYPES
1607};
96baa820 1608
d471ea57 1609/* For compatibility with older distributions. Provide a ``set remote
23860348 1610 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1611
7f19b9a2 1612static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1613
1614static void
fba45db2
KB
1615set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1616 struct cmd_list_element *c)
96baa820 1617{
d471ea57 1618 int i;
a744cf53 1619
d471ea57 1620 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1621 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1622}
1623
1624static void
08546159
AC
1625show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1626 struct cmd_list_element *c,
1627 const char *value)
96baa820 1628{
d471ea57 1629 int i;
a744cf53 1630
d471ea57
AC
1631 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1632 {
444abaca 1633 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1634 }
96baa820
JM
1635}
1636
4082afcc
PA
1637/* Returns true if the multi-process extensions are in effect. */
1638
1639static int
1640remote_multi_process_p (struct remote_state *rs)
1641{
1642 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1643}
1644
de0d863e
DB
1645/* Returns true if fork events are supported. */
1646
1647static int
1648remote_fork_event_p (struct remote_state *rs)
1649{
1650 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1651}
1652
c269dbdb
DB
1653/* Returns true if vfork events are supported. */
1654
1655static int
1656remote_vfork_event_p (struct remote_state *rs)
1657{
1658 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1659}
1660
d46addbb
DB
1661/* Returns true if exec events are supported. */
1662
1663static int
1664remote_exec_event_p (struct remote_state *rs)
1665{
1666 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1667}
1668
cbb8991c
DB
1669/* Insert fork catchpoint target routine. If fork events are enabled
1670 then return success, nothing more to do. */
1671
1672static int
1673remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1674{
1675 struct remote_state *rs = get_remote_state ();
1676
1677 return !remote_fork_event_p (rs);
1678}
1679
1680/* Remove fork catchpoint target routine. Nothing to do, just
1681 return success. */
1682
1683static int
1684remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1685{
1686 return 0;
1687}
1688
1689/* Insert vfork catchpoint target routine. If vfork events are enabled
1690 then return success, nothing more to do. */
1691
1692static int
1693remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1694{
1695 struct remote_state *rs = get_remote_state ();
1696
1697 return !remote_vfork_event_p (rs);
1698}
1699
1700/* Remove vfork catchpoint target routine. Nothing to do, just
1701 return success. */
1702
1703static int
1704remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1705{
1706 return 0;
1707}
1708
d46addbb
DB
1709/* Insert exec catchpoint target routine. If exec events are
1710 enabled, just return success. */
1711
1712static int
1713remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1714{
1715 struct remote_state *rs = get_remote_state ();
1716
1717 return !remote_exec_event_p (rs);
1718}
1719
1720/* Remove exec catchpoint target routine. Nothing to do, just
1721 return success. */
1722
1723static int
1724remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1725{
1726 return 0;
1727}
1728
74531fed
PA
1729\f
1730/* Asynchronous signal handle registered as event loop source for
1731 when we have pending events ready to be passed to the core. */
1732
1733static struct async_event_handler *remote_async_inferior_event_token;
1734
c906108c
SS
1735\f
1736
79d7f229
PA
1737static ptid_t magic_null_ptid;
1738static ptid_t not_sent_ptid;
1739static ptid_t any_thread_ptid;
1740
0b16c5cf
PA
1741/* Find out if the stub attached to PID (and hence GDB should offer to
1742 detach instead of killing it when bailing out). */
1743
1744static int
1745remote_query_attached (int pid)
1746{
1747 struct remote_state *rs = get_remote_state ();
bba74b36 1748 size_t size = get_remote_packet_size ();
0b16c5cf 1749
4082afcc 1750 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1751 return 0;
1752
1753 if (remote_multi_process_p (rs))
bba74b36 1754 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1755 else
bba74b36 1756 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1757
1758 putpkt (rs->buf);
1759 getpkt (&rs->buf, &rs->buf_size, 0);
1760
1761 switch (packet_ok (rs->buf,
1554e9be 1762 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1763 {
1764 case PACKET_OK:
1765 if (strcmp (rs->buf, "1") == 0)
1766 return 1;
1767 break;
1768 case PACKET_ERROR:
1769 warning (_("Remote failure reply: %s"), rs->buf);
1770 break;
1771 case PACKET_UNKNOWN:
1772 break;
1773 }
1774
1775 return 0;
1776}
1777
49c62f2e
PA
1778/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1779 has been invented by GDB, instead of reported by the target. Since
1780 we can be connected to a remote system before before knowing about
1781 any inferior, mark the target with execution when we find the first
1782 inferior. If ATTACHED is 1, then we had just attached to this
1783 inferior. If it is 0, then we just created this inferior. If it
1784 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1785 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1786 attempt to open this inferior's executable as the main executable
1787 if no main executable is open already. */
1941c569
PA
1788
1789static struct inferior *
1b6e6f5c
GB
1790remote_add_inferior (int fake_pid_p, int pid, int attached,
1791 int try_open_exec)
1941c569 1792{
1941c569
PA
1793 struct inferior *inf;
1794
0b16c5cf
PA
1795 /* Check whether this process we're learning about is to be
1796 considered attached, or if is to be considered to have been
1797 spawned by the stub. */
1798 if (attached == -1)
1799 attached = remote_query_attached (pid);
1800
f5656ead 1801 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1802 {
1803 /* If the target shares code across all inferiors, then every
1804 attach adds a new inferior. */
1805 inf = add_inferior (pid);
1806
1807 /* ... and every inferior is bound to the same program space.
1808 However, each inferior may still have its own address
1809 space. */
1810 inf->aspace = maybe_new_address_space ();
1811 inf->pspace = current_program_space;
1812 }
1813 else
1814 {
1815 /* In the traditional debugging scenario, there's a 1-1 match
1816 between program/address spaces. We simply bind the inferior
1817 to the program space's address space. */
1818 inf = current_inferior ();
1819 inferior_appeared (inf, pid);
1820 }
1941c569 1821
0b16c5cf 1822 inf->attach_flag = attached;
49c62f2e 1823 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1824
1b6e6f5c
GB
1825 /* If no main executable is currently open then attempt to
1826 open the file that was executed to create this inferior. */
835205d0 1827 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 1828 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 1829
1941c569
PA
1830 return inf;
1831}
1832
85ad3aaf
PA
1833static struct private_thread_info *
1834 get_private_info_thread (struct thread_info *info);
1835
1941c569
PA
1836/* Add thread PTID to GDB's thread list. Tag it as executing/running
1837 according to RUNNING. */
1838
c906108c 1839static void
0d5b594f 1840remote_add_thread (ptid_t ptid, int running, int executing)
c906108c 1841{
b7ea362b 1842 struct remote_state *rs = get_remote_state ();
85ad3aaf 1843 struct thread_info *thread;
b7ea362b
PA
1844
1845 /* GDB historically didn't pull threads in the initial connection
1846 setup. If the remote target doesn't even have a concept of
1847 threads (e.g., a bare-metal target), even if internally we
1848 consider that a single-threaded target, mentioning a new thread
1849 might be confusing to the user. Be silent then, preserving the
1850 age old behavior. */
1851 if (rs->starting_up)
85ad3aaf 1852 thread = add_thread_silent (ptid);
b7ea362b 1853 else
85ad3aaf 1854 thread = add_thread (ptid);
1941c569 1855
85ad3aaf 1856 get_private_info_thread (thread)->vcont_resumed = executing;
0d5b594f 1857 set_executing (ptid, executing);
1941c569
PA
1858 set_running (ptid, running);
1859}
1860
1861/* Come here when we learn about a thread id from the remote target.
1862 It may be the first time we hear about such thread, so take the
1863 opportunity to add it to GDB's thread list. In case this is the
1864 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
1865 GDB's inferior list as well. EXECUTING indicates whether the
1866 thread is (internally) executing or stopped. */
1941c569
PA
1867
1868static void
0d5b594f 1869remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 1870{
0d5b594f
PA
1871 /* In non-stop mode, we assume new found threads are (externally)
1872 running until proven otherwise with a stop reply. In all-stop,
1873 we can only get here if all threads are stopped. */
1874 int running = target_is_non_stop_p () ? 1 : 0;
1875
c906108c
SS
1876 /* If this is a new thread, add it to GDB's thread list.
1877 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1878
1879 if (in_thread_list (currthread) && is_exited (currthread))
1880 {
1881 /* We're seeing an event on a thread id we knew had exited.
1882 This has to be a new thread reusing the old id. Add it. */
0d5b594f 1883 remote_add_thread (currthread, running, executing);
82f73884
PA
1884 return;
1885 }
1886
79d7f229 1887 if (!in_thread_list (currthread))
c0a2216e 1888 {
1941c569 1889 struct inferior *inf = NULL;
bad34192 1890 int pid = ptid_get_pid (currthread);
1941c569 1891
bad34192
PA
1892 if (ptid_is_pid (inferior_ptid)
1893 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1894 {
1895 /* inferior_ptid has no thread member yet. This can happen
1896 with the vAttach -> remote_wait,"TAAthread:" path if the
1897 stub doesn't support qC. This is the first stop reported
1898 after an attach, so this is the main thread. Update the
1899 ptid in the thread list. */
bad34192
PA
1900 if (in_thread_list (pid_to_ptid (pid)))
1901 thread_change_ptid (inferior_ptid, currthread);
1902 else
1903 {
0d5b594f 1904 remote_add_thread (currthread, running, executing);
bad34192
PA
1905 inferior_ptid = currthread;
1906 }
dc146f7c 1907 return;
c0a2216e 1908 }
82f73884
PA
1909
1910 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1911 {
1912 /* inferior_ptid is not set yet. This can happen with the
1913 vRun -> remote_wait,"TAAthread:" path if the stub
1914 doesn't support qC. This is the first stop reported
1915 after an attach, so this is the main thread. Update the
1916 ptid in the thread list. */
dc146f7c 1917 thread_change_ptid (inferior_ptid, currthread);
82f73884 1918 return;
c0a2216e 1919 }
82f73884 1920
29c87f7f
PA
1921 /* When connecting to a target remote, or to a target
1922 extended-remote which already was debugging an inferior, we
1923 may not know about it yet. Add it before adding its child
1924 thread, so notifications are emitted in a sensible order. */
1925 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1926 {
1927 struct remote_state *rs = get_remote_state ();
1928 int fake_pid_p = !remote_multi_process_p (rs);
1929
1930 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1931 ptid_get_pid (currthread), -1, 1);
49c62f2e 1932 }
29c87f7f 1933
82f73884 1934 /* This is really a new thread. Add it. */
0d5b594f 1935 remote_add_thread (currthread, running, executing);
1941c569
PA
1936
1937 /* If we found a new inferior, let the common code do whatever
1938 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1939 breakpoints), unless we're just setting up an all-stop
1940 connection. */
1941c569 1941 if (inf != NULL)
b7ea362b
PA
1942 {
1943 struct remote_state *rs = get_remote_state ();
1944
6efcd9a8 1945 if (!rs->starting_up)
0d5b594f 1946 notice_new_inferior (currthread, executing, 0);
b7ea362b 1947 }
c0a2216e 1948 }
c906108c
SS
1949}
1950
85ad3aaf 1951/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 1952
70221824 1953static struct private_thread_info *
85ad3aaf 1954get_private_info_thread (struct thread_info *thread)
dc146f7c 1955{
85ad3aaf 1956 gdb_assert (thread != NULL);
dc146f7c 1957
85ad3aaf 1958 if (thread->priv == NULL)
dc146f7c 1959 {
85ad3aaf
PA
1960 struct private_thread_info *priv = XNEW (struct private_thread_info);
1961
1962 thread->private_dtor = free_private_thread_info;
1963 thread->priv = priv;
1964
1965 priv->core = -1;
1966 priv->extra = NULL;
1967 priv->name = NULL;
1968 priv->name = NULL;
1969 priv->last_resume_step = 0;
1970 priv->last_resume_sig = GDB_SIGNAL_0;
1971 priv->vcont_resumed = 0;
dc146f7c
VP
1972 }
1973
85ad3aaf
PA
1974 return thread->priv;
1975}
1976
1977/* Return PTID's private thread data, creating it if necessary. */
1978
1979static struct private_thread_info *
1980get_private_info_ptid (ptid_t ptid)
1981{
1982 struct thread_info *info = find_thread_ptid (ptid);
1983
1984 return get_private_info_thread (info);
dc146f7c
VP
1985}
1986
74531fed
PA
1987/* Call this function as a result of
1988 1) A halt indication (T packet) containing a thread id
1989 2) A direct query of currthread
0df8b418 1990 3) Successful execution of set thread */
74531fed
PA
1991
1992static void
47f8a51d 1993record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1994{
47f8a51d 1995 rs->general_thread = currthread;
74531fed
PA
1996}
1997
89be2091
DJ
1998/* If 'QPassSignals' is supported, tell the remote stub what signals
1999 it can simply pass through to the inferior without reporting. */
2000
2001static void
94bedb42
TT
2002remote_pass_signals (struct target_ops *self,
2003 int numsigs, unsigned char *pass_signals)
89be2091 2004{
4082afcc 2005 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
2006 {
2007 char *pass_packet, *p;
89be2091 2008 int count = 0, i;
747dc59d 2009 struct remote_state *rs = get_remote_state ();
89be2091
DJ
2010
2011 gdb_assert (numsigs < 256);
2012 for (i = 0; i < numsigs; i++)
2013 {
2455069d 2014 if (pass_signals[i])
89be2091
DJ
2015 count++;
2016 }
224c3ddb 2017 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2018 strcpy (pass_packet, "QPassSignals:");
2019 p = pass_packet + strlen (pass_packet);
2020 for (i = 0; i < numsigs; i++)
2021 {
2455069d 2022 if (pass_signals[i])
89be2091
DJ
2023 {
2024 if (i >= 16)
2025 *p++ = tohex (i >> 4);
2026 *p++ = tohex (i & 15);
2027 if (count)
2028 *p++ = ';';
2029 else
2030 break;
2031 count--;
2032 }
2033 }
2034 *p = 0;
747dc59d 2035 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2036 {
89be2091
DJ
2037 putpkt (pass_packet);
2038 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2039 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2040 if (rs->last_pass_packet)
2041 xfree (rs->last_pass_packet);
2042 rs->last_pass_packet = pass_packet;
89be2091
DJ
2043 }
2044 else
2045 xfree (pass_packet);
2046 }
2047}
2048
82075af2
JS
2049/* If 'QCatchSyscalls' is supported, tell the remote stub
2050 to report syscalls to GDB. */
2051
2052static int
2053remote_set_syscall_catchpoint (struct target_ops *self,
2054 int pid, int needed, int any_count,
2055 int table_size, int *table)
2056{
2057 char *catch_packet;
2058 enum packet_result result;
2059 int n_sysno = 0;
2060
2061 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2062 {
2063 /* Not supported. */
2064 return 1;
2065 }
2066
2067 if (needed && !any_count)
2068 {
2069 int i;
2070
2071 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2072 for (i = 0; i < table_size; i++)
2073 {
2074 if (table[i] != 0)
2075 n_sysno++;
2076 }
2077 }
2078
2079 if (remote_debug)
2080 {
2081 fprintf_unfiltered (gdb_stdlog,
2082 "remote_set_syscall_catchpoint "
2083 "pid %d needed %d any_count %d n_sysno %d\n",
2084 pid, needed, any_count, n_sysno);
2085 }
2086
2087 if (needed)
2088 {
2089 /* Prepare a packet with the sysno list, assuming max 8+1
2090 characters for a sysno. If the resulting packet size is too
2091 big, fallback on the non-selective packet. */
2092 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2093
c0518081 2094 catch_packet = (char *) xmalloc (maxpktsz);
82075af2
JS
2095 strcpy (catch_packet, "QCatchSyscalls:1");
2096 if (!any_count)
2097 {
2098 int i;
2099 char *p;
2100
2101 p = catch_packet;
2102 p += strlen (p);
2103
2104 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2105 for (i = 0; i < table_size; i++)
2106 {
2107 if (table[i] != 0)
2108 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2109 }
2110 }
2111 if (strlen (catch_packet) > get_remote_packet_size ())
2112 {
2113 /* catch_packet too big. Fallback to less efficient
2114 non selective mode, with GDB doing the filtering. */
2115 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2116 }
2117 }
2118 else
2119 catch_packet = xstrdup ("QCatchSyscalls:0");
2120
2121 {
2122 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2123 struct remote_state *rs = get_remote_state ();
2124
2125 putpkt (catch_packet);
2126 getpkt (&rs->buf, &rs->buf_size, 0);
2127 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2128 do_cleanups (old_chain);
2129 if (result == PACKET_OK)
2130 return 0;
2131 else
2132 return -1;
2133 }
2134}
2135
9b224c5e
PA
2136/* If 'QProgramSignals' is supported, tell the remote stub what
2137 signals it should pass through to the inferior when detaching. */
2138
2139static void
daf5e9b6
TT
2140remote_program_signals (struct target_ops *self,
2141 int numsigs, unsigned char *signals)
9b224c5e 2142{
4082afcc 2143 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2144 {
2145 char *packet, *p;
2146 int count = 0, i;
5e4a05c4 2147 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2148
2149 gdb_assert (numsigs < 256);
2150 for (i = 0; i < numsigs; i++)
2151 {
2152 if (signals[i])
2153 count++;
2154 }
224c3ddb 2155 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2156 strcpy (packet, "QProgramSignals:");
2157 p = packet + strlen (packet);
2158 for (i = 0; i < numsigs; i++)
2159 {
2160 if (signal_pass_state (i))
2161 {
2162 if (i >= 16)
2163 *p++ = tohex (i >> 4);
2164 *p++ = tohex (i & 15);
2165 if (count)
2166 *p++ = ';';
2167 else
2168 break;
2169 count--;
2170 }
2171 }
2172 *p = 0;
5e4a05c4
TT
2173 if (!rs->last_program_signals_packet
2174 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2175 {
9b224c5e
PA
2176 putpkt (packet);
2177 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2178 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2179 xfree (rs->last_program_signals_packet);
2180 rs->last_program_signals_packet = packet;
9b224c5e
PA
2181 }
2182 else
2183 xfree (packet);
2184 }
2185}
2186
79d7f229
PA
2187/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2188 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2189 thread. If GEN is set, set the general thread, if not, then set
2190 the step/continue thread. */
c906108c 2191static void
d62a8ae2 2192set_thread (ptid_t ptid, int gen)
c906108c 2193{
d01949b6 2194 struct remote_state *rs = get_remote_state ();
47f8a51d 2195 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2196 char *buf = rs->buf;
79d7f229 2197 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2198
79d7f229 2199 if (ptid_equal (state, ptid))
c906108c
SS
2200 return;
2201
79d7f229
PA
2202 *buf++ = 'H';
2203 *buf++ = gen ? 'g' : 'c';
2204 if (ptid_equal (ptid, magic_null_ptid))
2205 xsnprintf (buf, endbuf - buf, "0");
2206 else if (ptid_equal (ptid, any_thread_ptid))
2207 xsnprintf (buf, endbuf - buf, "0");
2208 else if (ptid_equal (ptid, minus_one_ptid))
2209 xsnprintf (buf, endbuf - buf, "-1");
2210 else
82f73884 2211 write_ptid (buf, endbuf, ptid);
79d7f229 2212 putpkt (rs->buf);
6d820c5c 2213 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2214 if (gen)
47f8a51d 2215 rs->general_thread = ptid;
c906108c 2216 else
47f8a51d 2217 rs->continue_thread = ptid;
c906108c 2218}
79d7f229
PA
2219
2220static void
d62a8ae2 2221set_general_thread (ptid_t ptid)
79d7f229
PA
2222{
2223 set_thread (ptid, 1);
2224}
2225
2226static void
d62a8ae2 2227set_continue_thread (ptid_t ptid)
79d7f229
PA
2228{
2229 set_thread (ptid, 0);
2230}
2231
3c9c4b83
PA
2232/* Change the remote current process. Which thread within the process
2233 ends up selected isn't important, as long as it is the same process
2234 as what INFERIOR_PTID points to.
2235
2236 This comes from that fact that there is no explicit notion of
2237 "selected process" in the protocol. The selected process for
2238 general operations is the process the selected general thread
2239 belongs to. */
2240
2241static void
2242set_general_process (void)
2243{
2244 struct remote_state *rs = get_remote_state ();
2245
2246 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2247 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2248 return;
2249
2250 /* We only need to change the remote current thread if it's pointing
2251 at some other process. */
47f8a51d 2252 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2253 set_general_thread (inferior_ptid);
2254}
2255
c906108c 2256\f
7d1a114c
PA
2257/* Return nonzero if this is the main thread that we made up ourselves
2258 to model non-threaded targets as single-threaded. */
c906108c
SS
2259
2260static int
7d1a114c 2261remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2262{
c0a2216e
PA
2263 if (ptid_equal (ptid, magic_null_ptid))
2264 /* The main thread is always alive. */
2265 return 1;
2266
ba348170 2267 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2268 /* The main thread is always alive. This can happen after a
2269 vAttach, if the remote side doesn't support
2270 multi-threading. */
2271 return 1;
2272
7d1a114c
PA
2273 return 0;
2274}
2275
2276/* Return nonzero if the thread PTID is still alive on the remote
2277 system. */
2278
2279static int
2280remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2281{
2282 struct remote_state *rs = get_remote_state ();
2283 char *p, *endp;
2284
2285 /* Check if this is a thread that we made up ourselves to model
2286 non-threaded targets as single-threaded. */
2287 if (remote_thread_always_alive (ops, ptid))
2288 return 1;
2289
82f73884
PA
2290 p = rs->buf;
2291 endp = rs->buf + get_remote_packet_size ();
2292
2293 *p++ = 'T';
2294 write_ptid (p, endp, ptid);
2295
2e9f7625 2296 putpkt (rs->buf);
6d820c5c 2297 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2298 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2299}
2300
79efa585
SM
2301/* Return a pointer to a thread name if we know it and NULL otherwise.
2302 The thread_info object owns the memory for the name. */
2303
2304static const char *
2305remote_thread_name (struct target_ops *ops, struct thread_info *info)
2306{
2307 if (info->priv != NULL)
2308 return info->priv->name;
2309
2310 return NULL;
2311}
2312
c906108c
SS
2313/* About these extended threadlist and threadinfo packets. They are
2314 variable length packets but, the fields within them are often fixed
2315 length. They are redundent enough to send over UDP as is the
2316 remote protocol in general. There is a matching unit test module
2317 in libstub. */
2318
23860348 2319/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2320 libstub protocol encoding, and remote.c. It is not particularly
23860348 2321 changable. */
cce74817
JM
2322
2323/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2324 Plan to fix this. */
cce74817 2325
23860348 2326typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2327
9d1f7ab2 2328/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2329 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2330
2331struct gdb_ext_thread_info
c5aa993b 2332 {
23860348 2333 threadref threadid; /* External form of thread reference. */
2bc416ba 2334 int active; /* Has state interesting to GDB?
23860348 2335 regs, stack. */
2bc416ba 2336 char display[256]; /* Brief state display, name,
cedea757 2337 blocked/suspended. */
23860348 2338 char shortname[32]; /* To be used to name threads. */
2bc416ba 2339 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2340 whatever. */
c5aa993b 2341 };
cce74817
JM
2342
2343/* The volume of remote transfers can be limited by submitting
2344 a mask containing bits specifying the desired information.
2345 Use a union of these values as the 'selection' parameter to
0df8b418 2346 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2347
2348#define TAG_THREADID 1
2349#define TAG_EXISTS 2
2350#define TAG_DISPLAY 4
2351#define TAG_THREADNAME 8
c5aa993b 2352#define TAG_MOREDISPLAY 16
cce74817 2353
23860348 2354#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2355
a14ed312 2356static char *unpack_nibble (char *buf, int *val);
cce74817 2357
a14ed312 2358static char *unpack_byte (char *buf, int *value);
cce74817 2359
a14ed312 2360static char *pack_int (char *buf, int value);
cce74817 2361
a14ed312 2362static char *unpack_int (char *buf, int *value);
cce74817 2363
a14ed312 2364static char *unpack_string (char *src, char *dest, int length);
cce74817 2365
23860348 2366static char *pack_threadid (char *pkt, threadref *id);
cce74817 2367
23860348 2368static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2369
23860348 2370void int_to_threadref (threadref *id, int value);
cce74817 2371
23860348 2372static int threadref_to_int (threadref *ref);
cce74817 2373
23860348 2374static void copy_threadref (threadref *dest, threadref *src);
cce74817 2375
23860348 2376static int threadmatch (threadref *dest, threadref *src);
cce74817 2377
2bc416ba 2378static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2379 threadref *id);
cce74817 2380
a14ed312 2381static int remote_unpack_thread_info_response (char *pkt,
23860348 2382 threadref *expectedref,
a14ed312
KB
2383 struct gdb_ext_thread_info
2384 *info);
cce74817
JM
2385
2386
2bc416ba 2387static int remote_get_threadinfo (threadref *threadid,
23860348 2388 int fieldset, /*TAG mask */
a14ed312 2389 struct gdb_ext_thread_info *info);
cce74817 2390
a14ed312
KB
2391static char *pack_threadlist_request (char *pkt, int startflag,
2392 int threadcount,
23860348 2393 threadref *nextthread);
cce74817 2394
a14ed312
KB
2395static int parse_threadlist_response (char *pkt,
2396 int result_limit,
23860348 2397 threadref *original_echo,
2bc416ba 2398 threadref *resultlist,
23860348 2399 int *doneflag);
cce74817 2400
a14ed312 2401static int remote_get_threadlist (int startflag,
23860348 2402 threadref *nextthread,
a14ed312
KB
2403 int result_limit,
2404 int *done,
2bc416ba 2405 int *result_count,
23860348 2406 threadref *threadlist);
cce74817 2407
23860348 2408typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2409
a14ed312
KB
2410static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2411 void *context, int looplimit);
cce74817 2412
23860348 2413static int remote_newthread_step (threadref *ref, void *context);
cce74817 2414
82f73884
PA
2415
2416/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2417 buffer we're allowed to write to. Returns
2418 BUF+CHARACTERS_WRITTEN. */
2419
2420static char *
2421write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2422{
2423 int pid, tid;
2424 struct remote_state *rs = get_remote_state ();
2425
2426 if (remote_multi_process_p (rs))
2427 {
2428 pid = ptid_get_pid (ptid);
2429 if (pid < 0)
2430 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2431 else
2432 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2433 }
ba348170 2434 tid = ptid_get_lwp (ptid);
82f73884
PA
2435 if (tid < 0)
2436 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2437 else
2438 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2439
2440 return buf;
2441}
2442
2443/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2444 passed the last parsed char. Returns null_ptid on error. */
2445
2446static ptid_t
2447read_ptid (char *buf, char **obuf)
2448{
2449 char *p = buf;
2450 char *pp;
2451 ULONGEST pid = 0, tid = 0;
82f73884
PA
2452
2453 if (*p == 'p')
2454 {
2455 /* Multi-process ptid. */
2456 pp = unpack_varlen_hex (p + 1, &pid);
2457 if (*pp != '.')
b37520b6 2458 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2459
2460 p = pp;
2461 pp = unpack_varlen_hex (p + 1, &tid);
2462 if (obuf)
2463 *obuf = pp;
ba348170 2464 return ptid_build (pid, tid, 0);
82f73884
PA
2465 }
2466
2467 /* No multi-process. Just a tid. */
2468 pp = unpack_varlen_hex (p, &tid);
2469
c9f35b34
KB
2470 /* Return null_ptid when no thread id is found. */
2471 if (p == pp)
2472 {
2473 if (obuf)
2474 *obuf = pp;
2475 return null_ptid;
2476 }
2477
82f73884 2478 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2479 what's in inferior_ptid, unless it's null at this point. If so,
2480 then since there's no way to know the pid of the reported
2481 threads, use the magic number. */
2482 if (ptid_equal (inferior_ptid, null_ptid))
2483 pid = ptid_get_pid (magic_null_ptid);
2484 else
2485 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2486
2487 if (obuf)
2488 *obuf = pp;
ba348170 2489 return ptid_build (pid, tid, 0);
82f73884
PA
2490}
2491
c906108c 2492static int
fba45db2 2493stubhex (int ch)
c906108c
SS
2494{
2495 if (ch >= 'a' && ch <= 'f')
2496 return ch - 'a' + 10;
2497 if (ch >= '0' && ch <= '9')
2498 return ch - '0';
2499 if (ch >= 'A' && ch <= 'F')
2500 return ch - 'A' + 10;
2501 return -1;
2502}
2503
2504static int
fba45db2 2505stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2506{
2507 int nibble;
2508 int retval = 0;
2509
2510 while (fieldlength)
2511 {
2512 nibble = stubhex (*buff++);
2513 retval |= nibble;
2514 fieldlength--;
2515 if (fieldlength)
2516 retval = retval << 4;
2517 }
2518 return retval;
2519}
2520
c906108c 2521static char *
fba45db2 2522unpack_nibble (char *buf, int *val)
c906108c 2523{
b7589f7d 2524 *val = fromhex (*buf++);
c906108c
SS
2525 return buf;
2526}
2527
c906108c 2528static char *
fba45db2 2529unpack_byte (char *buf, int *value)
c906108c
SS
2530{
2531 *value = stub_unpack_int (buf, 2);
2532 return buf + 2;
2533}
2534
2535static char *
fba45db2 2536pack_int (char *buf, int value)
c906108c
SS
2537{
2538 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2539 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2540 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2541 buf = pack_hex_byte (buf, (value & 0xff));
2542 return buf;
2543}
2544
2545static char *
fba45db2 2546unpack_int (char *buf, int *value)
c906108c
SS
2547{
2548 *value = stub_unpack_int (buf, 8);
2549 return buf + 8;
2550}
2551
23860348 2552#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2553static char *pack_string (char *pkt, char *string);
c906108c
SS
2554
2555static char *
fba45db2 2556pack_string (char *pkt, char *string)
c906108c
SS
2557{
2558 char ch;
2559 int len;
2560
2561 len = strlen (string);
2562 if (len > 200)
23860348 2563 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2564 pkt = pack_hex_byte (pkt, len);
2565 while (len-- > 0)
2566 {
2567 ch = *string++;
2568 if ((ch == '\0') || (ch == '#'))
23860348 2569 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2570 *pkt++ = ch;
2571 }
2572 return pkt;
2573}
2574#endif /* 0 (unused) */
2575
2576static char *
fba45db2 2577unpack_string (char *src, char *dest, int length)
c906108c
SS
2578{
2579 while (length--)
2580 *dest++ = *src++;
2581 *dest = '\0';
2582 return src;
2583}
2584
2585static char *
fba45db2 2586pack_threadid (char *pkt, threadref *id)
c906108c
SS
2587{
2588 char *limit;
2589 unsigned char *altid;
2590
2591 altid = (unsigned char *) id;
2592 limit = pkt + BUF_THREAD_ID_SIZE;
2593 while (pkt < limit)
2594 pkt = pack_hex_byte (pkt, *altid++);
2595 return pkt;
2596}
2597
2598
2599static char *
fba45db2 2600unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2601{
2602 char *altref;
2603 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2604 int x, y;
2605
2606 altref = (char *) id;
2607
2608 while (inbuf < limit)
2609 {
2610 x = stubhex (*inbuf++);
2611 y = stubhex (*inbuf++);
2612 *altref++ = (x << 4) | y;
2613 }
2614 return inbuf;
2615}
2616
2617/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2618 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2619 to use 64bit thread references internally. This is an adapter
2620 function. */
2621
2622void
fba45db2 2623int_to_threadref (threadref *id, int value)
c906108c
SS
2624{
2625 unsigned char *scan;
2626
2627 scan = (unsigned char *) id;
2628 {
2629 int i = 4;
2630 while (i--)
2631 *scan++ = 0;
2632 }
2633 *scan++ = (value >> 24) & 0xff;
2634 *scan++ = (value >> 16) & 0xff;
2635 *scan++ = (value >> 8) & 0xff;
2636 *scan++ = (value & 0xff);
2637}
2638
2639static int
fba45db2 2640threadref_to_int (threadref *ref)
c906108c
SS
2641{
2642 int i, value = 0;
2643 unsigned char *scan;
2644
cfd77fa1 2645 scan = *ref;
c906108c
SS
2646 scan += 4;
2647 i = 4;
2648 while (i-- > 0)
2649 value = (value << 8) | ((*scan++) & 0xff);
2650 return value;
2651}
2652
2653static void
fba45db2 2654copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2655{
2656 int i;
2657 unsigned char *csrc, *cdest;
2658
2659 csrc = (unsigned char *) src;
2660 cdest = (unsigned char *) dest;
2661 i = 8;
2662 while (i--)
2663 *cdest++ = *csrc++;
2664}
2665
2666static int
fba45db2 2667threadmatch (threadref *dest, threadref *src)
c906108c 2668{
23860348 2669 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2670#if 0
2671 unsigned char *srcp, *destp;
2672 int i, result;
2673 srcp = (char *) src;
2674 destp = (char *) dest;
2675
2676 result = 1;
2677 while (i-- > 0)
2678 result &= (*srcp++ == *destp++) ? 1 : 0;
2679 return result;
2680#endif
2681 return 1;
2682}
2683
2684/*
c5aa993b
JM
2685 threadid:1, # always request threadid
2686 context_exists:2,
2687 display:4,
2688 unique_name:8,
2689 more_display:16
2690 */
c906108c
SS
2691
2692/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2693
2694static char *
fba45db2 2695pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2696{
23860348
MS
2697 *pkt++ = 'q'; /* Info Query */
2698 *pkt++ = 'P'; /* process or thread info */
2699 pkt = pack_int (pkt, mode); /* mode */
c906108c 2700 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2701 *pkt = '\0'; /* terminate */
c906108c
SS
2702 return pkt;
2703}
2704
23860348 2705/* These values tag the fields in a thread info response packet. */
c906108c 2706/* Tagging the fields allows us to request specific fields and to
23860348 2707 add more fields as time goes by. */
c906108c 2708
23860348 2709#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2710#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2711 fetch registers and its stack? */
c5aa993b 2712#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2713#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2714#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2715 the process. */
c906108c
SS
2716
2717static int
fba45db2
KB
2718remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2719 struct gdb_ext_thread_info *info)
c906108c 2720{
d01949b6 2721 struct remote_state *rs = get_remote_state ();
c906108c 2722 int mask, length;
cfd77fa1 2723 int tag;
c906108c 2724 threadref ref;
6d820c5c 2725 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2726 int retval = 1;
2727
23860348 2728 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2729 info->active = 0;
2730 info->display[0] = '\0';
2731 info->shortname[0] = '\0';
2732 info->more_display[0] = '\0';
2733
23860348
MS
2734 /* Assume the characters indicating the packet type have been
2735 stripped. */
c906108c
SS
2736 pkt = unpack_int (pkt, &mask); /* arg mask */
2737 pkt = unpack_threadid (pkt, &ref);
2738
2739 if (mask == 0)
8a3fe4f8 2740 warning (_("Incomplete response to threadinfo request."));
c906108c 2741 if (!threadmatch (&ref, expectedref))
23860348 2742 { /* This is an answer to a different request. */
8a3fe4f8 2743 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2744 return 0;
2745 }
2746 copy_threadref (&info->threadid, &ref);
2747
23860348 2748 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2749
23860348
MS
2750 /* Packets are terminated with nulls. */
2751 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2752 {
2753 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2754 pkt = unpack_byte (pkt, &length); /* length */
2755 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2756 {
8a3fe4f8 2757 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2758 retval = 0;
2759 break;
2760 }
2761 if (tag == TAG_THREADID)
2762 {
2763 if (length != 16)
2764 {
8a3fe4f8 2765 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2766 retval = 0;
2767 break;
2768 }
2769 pkt = unpack_threadid (pkt, &ref);
2770 mask = mask & ~TAG_THREADID;
2771 continue;
2772 }
2773 if (tag == TAG_EXISTS)
2774 {
2775 info->active = stub_unpack_int (pkt, length);
2776 pkt += length;
2777 mask = mask & ~(TAG_EXISTS);
2778 if (length > 8)
2779 {
8a3fe4f8 2780 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2781 retval = 0;
2782 break;
2783 }
2784 continue;
2785 }
2786 if (tag == TAG_THREADNAME)
2787 {
2788 pkt = unpack_string (pkt, &info->shortname[0], length);
2789 mask = mask & ~TAG_THREADNAME;
2790 continue;
2791 }
2792 if (tag == TAG_DISPLAY)
2793 {
2794 pkt = unpack_string (pkt, &info->display[0], length);
2795 mask = mask & ~TAG_DISPLAY;
2796 continue;
2797 }
2798 if (tag == TAG_MOREDISPLAY)
2799 {
2800 pkt = unpack_string (pkt, &info->more_display[0], length);
2801 mask = mask & ~TAG_MOREDISPLAY;
2802 continue;
2803 }
8a3fe4f8 2804 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2805 break; /* Not a tag we know about. */
c906108c
SS
2806 }
2807 return retval;
2808}
2809
2810static int
fba45db2
KB
2811remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2812 struct gdb_ext_thread_info *info)
c906108c 2813{
d01949b6 2814 struct remote_state *rs = get_remote_state ();
c906108c 2815 int result;
c906108c 2816
2e9f7625
DJ
2817 pack_threadinfo_request (rs->buf, fieldset, threadid);
2818 putpkt (rs->buf);
6d820c5c 2819 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2820
2821 if (rs->buf[0] == '\0')
2822 return 0;
2823
2e9f7625 2824 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2825 threadid, info);
c906108c
SS
2826 return result;
2827}
2828
c906108c
SS
2829/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2830
2831static char *
fba45db2
KB
2832pack_threadlist_request (char *pkt, int startflag, int threadcount,
2833 threadref *nextthread)
c906108c
SS
2834{
2835 *pkt++ = 'q'; /* info query packet */
2836 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2837 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2838 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2839 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2840 *pkt = '\0';
2841 return pkt;
2842}
2843
2844/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2845
2846static int
fba45db2
KB
2847parse_threadlist_response (char *pkt, int result_limit,
2848 threadref *original_echo, threadref *resultlist,
2849 int *doneflag)
c906108c 2850{
d01949b6 2851 struct remote_state *rs = get_remote_state ();
c906108c
SS
2852 char *limit;
2853 int count, resultcount, done;
2854
2855 resultcount = 0;
2856 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2857 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2858 /* done parse past here */
c906108c
SS
2859 pkt = unpack_byte (pkt, &count); /* count field */
2860 pkt = unpack_nibble (pkt, &done);
2861 /* The first threadid is the argument threadid. */
2862 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2863 while ((count-- > 0) && (pkt < limit))
2864 {
2865 pkt = unpack_threadid (pkt, resultlist++);
2866 if (resultcount++ >= result_limit)
2867 break;
2868 }
2869 if (doneflag)
2870 *doneflag = done;
2871 return resultcount;
2872}
2873
6dc54d91
PA
2874/* Fetch the next batch of threads from the remote. Returns -1 if the
2875 qL packet is not supported, 0 on error and 1 on success. */
2876
c906108c 2877static int
fba45db2
KB
2878remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2879 int *done, int *result_count, threadref *threadlist)
c906108c 2880{
d01949b6 2881 struct remote_state *rs = get_remote_state ();
c906108c
SS
2882 int result = 1;
2883
23860348 2884 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2885 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2886 >= get_remote_packet_size ())
ea9c271d 2887 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2888
6d820c5c
DJ
2889 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2890 putpkt (rs->buf);
2891 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2892 if (*rs->buf == '\0')
6dc54d91
PA
2893 {
2894 /* Packet not supported. */
2895 return -1;
2896 }
2897
2898 *result_count =
2899 parse_threadlist_response (rs->buf + 2, result_limit,
2900 &rs->echo_nextthread, threadlist, done);
c906108c 2901
0d031856 2902 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2903 {
23860348
MS
2904 /* FIXME: This is a good reason to drop the packet. */
2905 /* Possably, there is a duplicate response. */
c906108c
SS
2906 /* Possabilities :
2907 retransmit immediatly - race conditions
2908 retransmit after timeout - yes
2909 exit
2910 wait for packet, then exit
2911 */
8a3fe4f8 2912 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2913 return 0; /* I choose simply exiting. */
c906108c
SS
2914 }
2915 if (*result_count <= 0)
2916 {
2917 if (*done != 1)
2918 {
8a3fe4f8 2919 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2920 result = 0;
2921 }
2922 return result; /* break; */
2923 }
2924 if (*result_count > result_limit)
2925 {
2926 *result_count = 0;
8a3fe4f8 2927 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2928 return 0;
2929 }
2930 return result;
2931}
2932
6dc54d91
PA
2933/* Fetch the list of remote threads, with the qL packet, and call
2934 STEPFUNCTION for each thread found. Stops iterating and returns 1
2935 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2936 STEPFUNCTION returns false. If the packet is not supported,
2937 returns -1. */
c906108c 2938
c906108c 2939static int
fba45db2
KB
2940remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2941 int looplimit)
c906108c 2942{
0d031856 2943 struct remote_state *rs = get_remote_state ();
c906108c
SS
2944 int done, i, result_count;
2945 int startflag = 1;
2946 int result = 1;
2947 int loopcount = 0;
c906108c
SS
2948
2949 done = 0;
2950 while (!done)
2951 {
2952 if (loopcount++ > looplimit)
2953 {
2954 result = 0;
8a3fe4f8 2955 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2956 break;
2957 }
6dc54d91
PA
2958 result = remote_get_threadlist (startflag, &rs->nextthread,
2959 MAXTHREADLISTRESULTS,
2960 &done, &result_count,
2961 rs->resultthreadlist);
2962 if (result <= 0)
2963 break;
23860348 2964 /* Clear for later iterations. */
c906108c
SS
2965 startflag = 0;
2966 /* Setup to resume next batch of thread references, set nextthread. */
2967 if (result_count >= 1)
0d031856
TT
2968 copy_threadref (&rs->nextthread,
2969 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2970 i = 0;
2971 while (result_count--)
6dc54d91
PA
2972 {
2973 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2974 {
2975 result = 0;
2976 break;
2977 }
2978 }
c906108c
SS
2979 }
2980 return result;
2981}
2982
6dc54d91
PA
2983/* A thread found on the remote target. */
2984
2985typedef struct thread_item
2986{
2987 /* The thread's PTID. */
2988 ptid_t ptid;
2989
2990 /* The thread's extra info. May be NULL. */
2991 char *extra;
2992
79efa585
SM
2993 /* The thread's name. May be NULL. */
2994 char *name;
2995
6dc54d91
PA
2996 /* The core the thread was running on. -1 if not known. */
2997 int core;
2998} thread_item_t;
2999DEF_VEC_O(thread_item_t);
3000
3001/* Context passed around to the various methods listing remote
3002 threads. As new threads are found, they're added to the ITEMS
3003 vector. */
3004
3005struct threads_listing_context
3006{
3007 /* The threads found on the remote target. */
3008 VEC (thread_item_t) *items;
3009};
3010
80134cf5
PA
3011/* Discard the contents of the constructed thread listing context. */
3012
3013static void
3014clear_threads_listing_context (void *p)
3015{
19ba03f4
SM
3016 struct threads_listing_context *context
3017 = (struct threads_listing_context *) p;
80134cf5
PA
3018 int i;
3019 struct thread_item *item;
3020
3021 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
3022 {
3023 xfree (item->extra);
3024 xfree (item->name);
3025 }
80134cf5
PA
3026
3027 VEC_free (thread_item_t, context->items);
3028}
3029
cbb8991c
DB
3030/* Remove the thread specified as the related_pid field of WS
3031 from the CONTEXT list. */
3032
3033static void
3034threads_listing_context_remove (struct target_waitstatus *ws,
3035 struct threads_listing_context *context)
3036{
3037 struct thread_item *item;
3038 int i;
3039 ptid_t child_ptid = ws->value.related_pid;
3040
3041 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3042 {
3043 if (ptid_equal (item->ptid, child_ptid))
3044 {
3045 VEC_ordered_remove (thread_item_t, context->items, i);
3046 break;
3047 }
3048 }
3049}
3050
c906108c 3051static int
6dc54d91 3052remote_newthread_step (threadref *ref, void *data)
c906108c 3053{
19ba03f4
SM
3054 struct threads_listing_context *context
3055 = (struct threads_listing_context *) data;
6dc54d91 3056 struct thread_item item;
79d7f229 3057 int pid = ptid_get_pid (inferior_ptid);
39f77062 3058
6dc54d91
PA
3059 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3060 item.core = -1;
2e3b657e 3061 item.name = NULL;
6dc54d91
PA
3062 item.extra = NULL;
3063
3064 VEC_safe_push (thread_item_t, context->items, &item);
3065
c906108c
SS
3066 return 1; /* continue iterator */
3067}
3068
3069#define CRAZY_MAX_THREADS 1000
3070
39f77062
KB
3071static ptid_t
3072remote_current_thread (ptid_t oldpid)
c906108c 3073{
d01949b6 3074 struct remote_state *rs = get_remote_state ();
c906108c
SS
3075
3076 putpkt ("qC");
6d820c5c 3077 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3078 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
3079 {
3080 char *obuf;
3081 ptid_t result;
3082
3083 result = read_ptid (&rs->buf[2], &obuf);
3084 if (*obuf != '\0' && remote_debug)
3085 fprintf_unfiltered (gdb_stdlog,
3086 "warning: garbage in qC reply\n");
3087
3088 return result;
3089 }
c906108c
SS
3090 else
3091 return oldpid;
3092}
3093
6dc54d91 3094/* List remote threads using the deprecated qL packet. */
cce74817 3095
6dc54d91
PA
3096static int
3097remote_get_threads_with_ql (struct target_ops *ops,
3098 struct threads_listing_context *context)
c906108c 3099{
6dc54d91
PA
3100 if (remote_threadlist_iterator (remote_newthread_step, context,
3101 CRAZY_MAX_THREADS) >= 0)
3102 return 1;
3103
3104 return 0;
c906108c
SS
3105}
3106
dc146f7c
VP
3107#if defined(HAVE_LIBEXPAT)
3108
dc146f7c
VP
3109static void
3110start_thread (struct gdb_xml_parser *parser,
3111 const struct gdb_xml_element *element,
3112 void *user_data, VEC(gdb_xml_value_s) *attributes)
3113{
19ba03f4
SM
3114 struct threads_listing_context *data
3115 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3116
3117 struct thread_item item;
3118 char *id;
3d2c1d41 3119 struct gdb_xml_value *attr;
dc146f7c 3120
19ba03f4 3121 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
3122 item.ptid = read_ptid (id, NULL);
3123
3d2c1d41
PA
3124 attr = xml_find_attribute (attributes, "core");
3125 if (attr != NULL)
3126 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
3127 else
3128 item.core = -1;
3129
79efa585 3130 attr = xml_find_attribute (attributes, "name");
e1961661 3131 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 3132
dc146f7c
VP
3133 item.extra = 0;
3134
3135 VEC_safe_push (thread_item_t, data->items, &item);
3136}
3137
3138static void
3139end_thread (struct gdb_xml_parser *parser,
3140 const struct gdb_xml_element *element,
3141 void *user_data, const char *body_text)
3142{
19ba03f4
SM
3143 struct threads_listing_context *data
3144 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3145
3146 if (body_text && *body_text)
2ae2a0b7 3147 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3148}
3149
3150const struct gdb_xml_attribute thread_attributes[] = {
3151 { "id", GDB_XML_AF_NONE, NULL, NULL },
3152 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3153 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3154 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3155};
3156
3157const struct gdb_xml_element thread_children[] = {
3158 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3159};
3160
3161const struct gdb_xml_element threads_children[] = {
3162 { "thread", thread_attributes, thread_children,
3163 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3164 start_thread, end_thread },
3165 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3166};
3167
3168const struct gdb_xml_element threads_elements[] = {
3169 { "threads", NULL, threads_children,
3170 GDB_XML_EF_NONE, NULL, NULL },
3171 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3172};
3173
3174#endif
3175
6dc54d91 3176/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3177
6dc54d91
PA
3178static int
3179remote_get_threads_with_qxfer (struct target_ops *ops,
3180 struct threads_listing_context *context)
0f71a2f6 3181{
dc146f7c 3182#if defined(HAVE_LIBEXPAT)
4082afcc 3183 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3184 {
6dc54d91 3185 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3186 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3187
6dc54d91 3188 if (xml != NULL && *xml != '\0')
dc146f7c 3189 {
6dc54d91
PA
3190 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3191 threads_elements, xml, context);
dc146f7c
VP
3192 }
3193
3194 do_cleanups (back_to);
6dc54d91 3195 return 1;
dc146f7c
VP
3196 }
3197#endif
3198
6dc54d91
PA
3199 return 0;
3200}
3201
3202/* List remote threads using qfThreadInfo/qsThreadInfo. */
3203
3204static int
3205remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3206 struct threads_listing_context *context)
3207{
3208 struct remote_state *rs = get_remote_state ();
3209
b80fafe3 3210 if (rs->use_threadinfo_query)
9d1f7ab2 3211 {
6dc54d91
PA
3212 char *bufp;
3213
9d1f7ab2 3214 putpkt ("qfThreadInfo");
6d820c5c 3215 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3216 bufp = rs->buf;
9d1f7ab2 3217 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3218 {
9d1f7ab2
MS
3219 while (*bufp++ == 'm') /* reply contains one or more TID */
3220 {
3221 do
3222 {
6dc54d91
PA
3223 struct thread_item item;
3224
3225 item.ptid = read_ptid (bufp, &bufp);
3226 item.core = -1;
2e3b657e 3227 item.name = NULL;
6dc54d91
PA
3228 item.extra = NULL;
3229
3230 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3231 }
3232 while (*bufp++ == ','); /* comma-separated list */
3233 putpkt ("qsThreadInfo");
6d820c5c 3234 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3235 bufp = rs->buf;
9d1f7ab2 3236 }
6dc54d91
PA
3237 return 1;
3238 }
3239 else
3240 {
3241 /* Packet not recognized. */
3242 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3243 }
3244 }
3245
6dc54d91
PA
3246 return 0;
3247}
3248
e8032dde 3249/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3250 targets. */
3251
3252static void
e8032dde 3253remote_update_thread_list (struct target_ops *ops)
6dc54d91 3254{
6dc54d91
PA
3255 struct threads_listing_context context;
3256 struct cleanup *old_chain;
ab970af1 3257 int got_list = 0;
e8032dde 3258
6dc54d91
PA
3259 context.items = NULL;
3260 old_chain = make_cleanup (clear_threads_listing_context, &context);
3261
3262 /* We have a few different mechanisms to fetch the thread list. Try
3263 them all, starting with the most preferred one first, falling
3264 back to older methods. */
3265 if (remote_get_threads_with_qxfer (ops, &context)
3266 || remote_get_threads_with_qthreadinfo (ops, &context)
3267 || remote_get_threads_with_ql (ops, &context))
3268 {
3269 int i;
3270 struct thread_item *item;
ab970af1
PA
3271 struct thread_info *tp, *tmp;
3272
3273 got_list = 1;
3274
7d1a114c
PA
3275 if (VEC_empty (thread_item_t, context.items)
3276 && remote_thread_always_alive (ops, inferior_ptid))
3277 {
3278 /* Some targets don't really support threads, but still
3279 reply an (empty) thread list in response to the thread
3280 listing packets, instead of replying "packet not
3281 supported". Exit early so we don't delete the main
3282 thread. */
3283 do_cleanups (old_chain);
3284 return;
3285 }
3286
ab970af1
PA
3287 /* CONTEXT now holds the current thread list on the remote
3288 target end. Delete GDB-side threads no longer found on the
3289 target. */
8a06aea7 3290 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3291 {
ab970af1
PA
3292 for (i = 0;
3293 VEC_iterate (thread_item_t, context.items, i, item);
3294 ++i)
3295 {
3296 if (ptid_equal (item->ptid, tp->ptid))
3297 break;
3298 }
3299
3300 if (i == VEC_length (thread_item_t, context.items))
3301 {
3302 /* Not found. */
3303 delete_thread (tp->ptid);
3304 }
cbb8991c
DB
3305 }
3306
3307 /* Remove any unreported fork child threads from CONTEXT so
3308 that we don't interfere with follow fork, which is where
3309 creation of such threads is handled. */
3310 remove_new_fork_children (&context);
74531fed 3311
ab970af1 3312 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3313 for (i = 0;
3314 VEC_iterate (thread_item_t, context.items, i, item);
3315 ++i)
3316 {
3317 if (!ptid_equal (item->ptid, null_ptid))
3318 {
3319 struct private_thread_info *info;
3320 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3321 executing until proven otherwise with a stop reply.
3322 In all-stop, we can only get here if all threads are
6dc54d91 3323 stopped. */
0d5b594f 3324 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3325
0d5b594f 3326 remote_notice_new_inferior (item->ptid, executing);
6dc54d91 3327
85ad3aaf 3328 info = get_private_info_ptid (item->ptid);
6dc54d91
PA
3329 info->core = item->core;
3330 info->extra = item->extra;
3331 item->extra = NULL;
79efa585
SM
3332 info->name = item->name;
3333 item->name = NULL;
6dc54d91
PA
3334 }
3335 }
3336 }
3337
ab970af1
PA
3338 if (!got_list)
3339 {
3340 /* If no thread listing method is supported, then query whether
3341 each known thread is alive, one by one, with the T packet.
3342 If the target doesn't support threads at all, then this is a
3343 no-op. See remote_thread_alive. */
3344 prune_threads ();
3345 }
3346
6dc54d91 3347 do_cleanups (old_chain);
9d1f7ab2
MS
3348}
3349
802188a7 3350/*
9d1f7ab2
MS
3351 * Collect a descriptive string about the given thread.
3352 * The target may say anything it wants to about the thread
3353 * (typically info about its blocked / runnable state, name, etc.).
3354 * This string will appear in the info threads display.
802188a7 3355 *
9d1f7ab2
MS
3356 * Optional: targets are not required to implement this function.
3357 */
3358
7a114964 3359static const char *
c15906d8 3360remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3361{
d01949b6 3362 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3363 int result;
3364 int set;
3365 threadref id;
3366 struct gdb_ext_thread_info threadinfo;
23860348 3367 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3368 int n = 0; /* position in display_buf */
3369
5d93a237 3370 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3371 internal_error (__FILE__, __LINE__,
e2e0b3e5 3372 _("remote_threads_extra_info"));
9d1f7ab2 3373
60e569b9 3374 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3375 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3376 /* This is the main thread which was added by GDB. The remote
3377 server doesn't know about it. */
3378 return NULL;
3379
4082afcc 3380 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3381 {
3382 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3383
fe978cb0
PA
3384 if (info && info->priv)
3385 return info->priv->extra;
dc146f7c
VP
3386 else
3387 return NULL;
3388 }
3389
b80fafe3 3390 if (rs->use_threadextra_query)
9d1f7ab2 3391 {
82f73884
PA
3392 char *b = rs->buf;
3393 char *endb = rs->buf + get_remote_packet_size ();
3394
3395 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3396 b += strlen (b);
3397 write_ptid (b, endb, tp->ptid);
3398
2e9f7625 3399 putpkt (rs->buf);
6d820c5c 3400 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3401 if (rs->buf[0] != 0)
9d1f7ab2 3402 {
325fac50 3403 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
2e9f7625 3404 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3405 display_buf [result] = '\0';
9d1f7ab2
MS
3406 return display_buf;
3407 }
0f71a2f6 3408 }
9d1f7ab2
MS
3409
3410 /* If the above query fails, fall back to the old method. */
b80fafe3 3411 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3412 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3413 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3414 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3415 if (remote_get_threadinfo (&id, set, &threadinfo))
3416 if (threadinfo.active)
0f71a2f6 3417 {
9d1f7ab2 3418 if (*threadinfo.shortname)
2bc416ba 3419 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3420 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3421 if (*threadinfo.display)
2bc416ba 3422 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3423 " State: %s,", threadinfo.display);
9d1f7ab2 3424 if (*threadinfo.more_display)
2bc416ba 3425 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3426 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3427
3428 if (n > 0)
c5aa993b 3429 {
23860348 3430 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3431 if (',' == display_buf[n-1])
3432 display_buf[n-1] = ' ';
3433 return display_buf;
c5aa993b 3434 }
0f71a2f6 3435 }
9d1f7ab2 3436 return NULL;
0f71a2f6 3437}
c906108c 3438\f
c5aa993b 3439
0fb4aa4b 3440static int
61fc905d 3441remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3442 struct static_tracepoint_marker *marker)
3443{
3444 struct remote_state *rs = get_remote_state ();
3445 char *p = rs->buf;
3446
bba74b36 3447 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3448 p += strlen (p);
3449 p += hexnumstr (p, addr);
3450 putpkt (rs->buf);
3451 getpkt (&rs->buf, &rs->buf_size, 0);
3452 p = rs->buf;
3453
3454 if (*p == 'E')
3455 error (_("Remote failure reply: %s"), p);
3456
3457 if (*p++ == 'm')
3458 {
3459 parse_static_tracepoint_marker_definition (p, &p, marker);
3460 return 1;
3461 }
3462
3463 return 0;
3464}
3465
0fb4aa4b 3466static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3467remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3468 const char *strid)
0fb4aa4b
PA
3469{
3470 struct remote_state *rs = get_remote_state ();
3471 VEC(static_tracepoint_marker_p) *markers = NULL;
3472 struct static_tracepoint_marker *marker = NULL;
3473 struct cleanup *old_chain;
3474 char *p;
3475
3476 /* Ask for a first packet of static tracepoint marker
3477 definition. */
3478 putpkt ("qTfSTM");
3479 getpkt (&rs->buf, &rs->buf_size, 0);
3480 p = rs->buf;
3481 if (*p == 'E')
3482 error (_("Remote failure reply: %s"), p);
3483
3484 old_chain = make_cleanup (free_current_marker, &marker);
3485
3486 while (*p++ == 'm')
3487 {
3488 if (marker == NULL)
3489 marker = XCNEW (struct static_tracepoint_marker);
3490
3491 do
3492 {
3493 parse_static_tracepoint_marker_definition (p, &p, marker);
3494
3495 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3496 {
3497 VEC_safe_push (static_tracepoint_marker_p,
3498 markers, marker);
3499 marker = NULL;
3500 }
3501 else
3502 {
3503 release_static_tracepoint_marker (marker);
3504 memset (marker, 0, sizeof (*marker));
3505 }
3506 }
3507 while (*p++ == ','); /* comma-separated list */
3508 /* Ask for another packet of static tracepoint definition. */
3509 putpkt ("qTsSTM");
3510 getpkt (&rs->buf, &rs->buf_size, 0);
3511 p = rs->buf;
3512 }
3513
3514 do_cleanups (old_chain);
3515 return markers;
3516}
3517
3518\f
10760264
JB
3519/* Implement the to_get_ada_task_ptid function for the remote targets. */
3520
3521static ptid_t
1e6b91a4 3522remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3523{
ba348170 3524 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3525}
3526\f
3527
24b06219 3528/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3529
3530static void
fba45db2 3531extended_remote_restart (void)
c906108c 3532{
d01949b6 3533 struct remote_state *rs = get_remote_state ();
c906108c
SS
3534
3535 /* Send the restart command; for reasons I don't understand the
3536 remote side really expects a number after the "R". */
ea9c271d 3537 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3538 putpkt (rs->buf);
c906108c 3539
ad9a8f3f 3540 remote_fileio_reset ();
c906108c
SS
3541}
3542\f
3543/* Clean up connection to a remote debugger. */
3544
c906108c 3545static void
de90e03d 3546remote_close (struct target_ops *self)
c906108c 3547{
5d93a237
TT
3548 struct remote_state *rs = get_remote_state ();
3549
3550 if (rs->remote_desc == NULL)
d3fd5342
PA
3551 return; /* already closed */
3552
048094ac 3553 /* Make sure we leave stdin registered in the event loop. */
e3594fd1 3554 remote_terminal_ours (self);
ce5ce7ed 3555
5d93a237
TT
3556 serial_close (rs->remote_desc);
3557 rs->remote_desc = NULL;
ce5ce7ed
PA
3558
3559 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3560 of all the inferiors and their threads we were controlling.
3561 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3562 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3563 inferior_ptid = null_ptid;
f67fd822 3564 discard_all_inferiors ();
ce5ce7ed 3565
f48ff2a7
YQ
3566 /* We are closing the remote target, so we should discard
3567 everything of this target. */
bcc75809 3568 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3569
3570 if (remote_async_inferior_event_token)
3571 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3572
5965e028 3573 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3574
3575 trace_reset_local_state ();
c906108c
SS
3576}
3577
23860348 3578/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3579
3580static void
fba45db2 3581get_offsets (void)
c906108c 3582{
d01949b6 3583 struct remote_state *rs = get_remote_state ();
2e9f7625 3584 char *buf;
085dd6e6 3585 char *ptr;
31d99776
DJ
3586 int lose, num_segments = 0, do_sections, do_segments;
3587 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3588 struct section_offsets *offs;
31d99776
DJ
3589 struct symfile_segment_data *data;
3590
3591 if (symfile_objfile == NULL)
3592 return;
c906108c
SS
3593
3594 putpkt ("qOffsets");
6d820c5c 3595 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3596 buf = rs->buf;
c906108c
SS
3597
3598 if (buf[0] == '\000')
3599 return; /* Return silently. Stub doesn't support
23860348 3600 this command. */
c906108c
SS
3601 if (buf[0] == 'E')
3602 {
8a3fe4f8 3603 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3604 return;
3605 }
3606
3607 /* Pick up each field in turn. This used to be done with scanf, but
3608 scanf will make trouble if CORE_ADDR size doesn't match
3609 conversion directives correctly. The following code will work
3610 with any size of CORE_ADDR. */
3611 text_addr = data_addr = bss_addr = 0;
3612 ptr = buf;
3613 lose = 0;
3614
61012eef 3615 if (startswith (ptr, "Text="))
c906108c
SS
3616 {
3617 ptr += 5;
3618 /* Don't use strtol, could lose on big values. */
3619 while (*ptr && *ptr != ';')
3620 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3621
61012eef 3622 if (startswith (ptr, ";Data="))
31d99776
DJ
3623 {
3624 ptr += 6;
3625 while (*ptr && *ptr != ';')
3626 data_addr = (data_addr << 4) + fromhex (*ptr++);
3627 }
3628 else
3629 lose = 1;
3630
61012eef 3631 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3632 {
3633 ptr += 5;
3634 while (*ptr && *ptr != ';')
3635 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3636
31d99776
DJ
3637 if (bss_addr != data_addr)
3638 warning (_("Target reported unsupported offsets: %s"), buf);
3639 }
3640 else
3641 lose = 1;
3642 }
61012eef 3643 else if (startswith (ptr, "TextSeg="))
c906108c 3644 {
31d99776
DJ
3645 ptr += 8;
3646 /* Don't use strtol, could lose on big values. */
c906108c 3647 while (*ptr && *ptr != ';')
31d99776
DJ
3648 text_addr = (text_addr << 4) + fromhex (*ptr++);
3649 num_segments = 1;
3650
61012eef 3651 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3652 {
3653 ptr += 9;
3654 while (*ptr && *ptr != ';')
3655 data_addr = (data_addr << 4) + fromhex (*ptr++);
3656 num_segments++;
3657 }
c906108c
SS
3658 }
3659 else
3660 lose = 1;
3661
3662 if (lose)
8a3fe4f8 3663 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3664 else if (*ptr != '\0')
3665 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3666
802188a7 3667 offs = ((struct section_offsets *)
a39a16c4 3668 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3669 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3670 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3671
31d99776
DJ
3672 data = get_symfile_segment_data (symfile_objfile->obfd);
3673 do_segments = (data != NULL);
3674 do_sections = num_segments == 0;
c906108c 3675
28c32713 3676 if (num_segments > 0)
31d99776 3677 {
31d99776
DJ
3678 segments[0] = text_addr;
3679 segments[1] = data_addr;
3680 }
28c32713
JB
3681 /* If we have two segments, we can still try to relocate everything
3682 by assuming that the .text and .data offsets apply to the whole
3683 text and data segments. Convert the offsets given in the packet
3684 to base addresses for symfile_map_offsets_to_segments. */
3685 else if (data && data->num_segments == 2)
3686 {
3687 segments[0] = data->segment_bases[0] + text_addr;
3688 segments[1] = data->segment_bases[1] + data_addr;
3689 num_segments = 2;
3690 }
8d385431
DJ
3691 /* If the object file has only one segment, assume that it is text
3692 rather than data; main programs with no writable data are rare,
3693 but programs with no code are useless. Of course the code might
3694 have ended up in the data segment... to detect that we would need
3695 the permissions here. */
3696 else if (data && data->num_segments == 1)
3697 {
3698 segments[0] = data->segment_bases[0] + text_addr;
3699 num_segments = 1;
3700 }
28c32713
JB
3701 /* There's no way to relocate by segment. */
3702 else
3703 do_segments = 0;
31d99776
DJ
3704
3705 if (do_segments)
3706 {
3707 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3708 offs, num_segments, segments);
3709
3710 if (ret == 0 && !do_sections)
3e43a32a
MS
3711 error (_("Can not handle qOffsets TextSeg "
3712 "response with this symbol file"));
31d99776
DJ
3713
3714 if (ret > 0)
3715 do_sections = 0;
3716 }
c906108c 3717
9ef895d6
DJ
3718 if (data)
3719 free_symfile_segment_data (data);
31d99776
DJ
3720
3721 if (do_sections)
3722 {
3723 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3724
3e43a32a
MS
3725 /* This is a temporary kludge to force data and bss to use the
3726 same offsets because that's what nlmconv does now. The real
3727 solution requires changes to the stub and remote.c that I
3728 don't have time to do right now. */
31d99776
DJ
3729
3730 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3731 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3732 }
c906108c
SS
3733
3734 objfile_relocate (symfile_objfile, offs);
3735}
3736
9a7071a8
JB
3737/* Send interrupt_sequence to remote target. */
3738static void
eeae04df 3739send_interrupt_sequence (void)
9a7071a8 3740{
5d93a237
TT
3741 struct remote_state *rs = get_remote_state ();
3742
9a7071a8 3743 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3744 remote_serial_write ("\x03", 1);
9a7071a8 3745 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3746 serial_send_break (rs->remote_desc);
9a7071a8
JB
3747 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3748 {
5d93a237 3749 serial_send_break (rs->remote_desc);
c33e31fd 3750 remote_serial_write ("g", 1);
9a7071a8
JB
3751 }
3752 else
3753 internal_error (__FILE__, __LINE__,
3754 _("Invalid value for interrupt_sequence_mode: %s."),
3755 interrupt_sequence_mode);
3756}
3757
3405876a
PA
3758
3759/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3760 and extract the PTID. Returns NULL_PTID if not found. */
3761
3762static ptid_t
3763stop_reply_extract_thread (char *stop_reply)
3764{
3765 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3766 {
3767 char *p;
3768
3769 /* Txx r:val ; r:val (...) */
3770 p = &stop_reply[3];
3771
3772 /* Look for "register" named "thread". */
3773 while (*p != '\0')
3774 {
3775 char *p1;
3776
3777 p1 = strchr (p, ':');
3778 if (p1 == NULL)
3779 return null_ptid;
3780
3781 if (strncmp (p, "thread", p1 - p) == 0)
3782 return read_ptid (++p1, &p);
3783
3784 p1 = strchr (p, ';');
3785 if (p1 == NULL)
3786 return null_ptid;
3787 p1++;
3788
3789 p = p1;
3790 }
3791 }
3792
3793 return null_ptid;
3794}
3795
b7ea362b
PA
3796/* Determine the remote side's current thread. If we have a stop
3797 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3798 "thread" register we can extract the current thread from. If not,
3799 ask the remote which is the current thread with qC. The former
3800 method avoids a roundtrip. */
3801
3802static ptid_t
3803get_current_thread (char *wait_status)
3804{
6a49a997 3805 ptid_t ptid = null_ptid;
b7ea362b
PA
3806
3807 /* Note we don't use remote_parse_stop_reply as that makes use of
3808 the target architecture, which we haven't yet fully determined at
3809 this point. */
3810 if (wait_status != NULL)
3811 ptid = stop_reply_extract_thread (wait_status);
3812 if (ptid_equal (ptid, null_ptid))
3813 ptid = remote_current_thread (inferior_ptid);
3814
3815 return ptid;
3816}
3817
49c62f2e
PA
3818/* Query the remote target for which is the current thread/process,
3819 add it to our tables, and update INFERIOR_PTID. The caller is
3820 responsible for setting the state such that the remote end is ready
3405876a
PA
3821 to return the current thread.
3822
3823 This function is called after handling the '?' or 'vRun' packets,
3824 whose response is a stop reply from which we can also try
3825 extracting the thread. If the target doesn't support the explicit
3826 qC query, we infer the current thread from that stop reply, passed
3827 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3828
3829static void
3405876a 3830add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3831{
3832 struct remote_state *rs = get_remote_state ();
3833 int fake_pid_p = 0;
6a49a997 3834 ptid_t ptid;
49c62f2e
PA
3835
3836 inferior_ptid = null_ptid;
3837
b7ea362b
PA
3838 /* Now, if we have thread information, update inferior_ptid. */
3839 ptid = get_current_thread (wait_status);
3405876a 3840
49c62f2e
PA
3841 if (!ptid_equal (ptid, null_ptid))
3842 {
3843 if (!remote_multi_process_p (rs))
3844 fake_pid_p = 1;
3845
3846 inferior_ptid = ptid;
3847 }
3848 else
3849 {
3850 /* Without this, some commands which require an active target
3851 (such as kill) won't work. This variable serves (at least)
3852 double duty as both the pid of the target process (if it has
3853 such), and as a flag indicating that a target is active. */
3854 inferior_ptid = magic_null_ptid;
3855 fake_pid_p = 1;
3856 }
3857
1b6e6f5c 3858 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3859
3860 /* Add the main thread. */
3861 add_thread_silent (inferior_ptid);
3862}
3863
6efcd9a8
PA
3864/* Print info about a thread that was found already stopped on
3865 connection. */
3866
3867static void
3868print_one_stopped_thread (struct thread_info *thread)
3869{
3870 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3871
3872 switch_to_thread (thread->ptid);
3873 stop_pc = get_frame_pc (get_current_frame ());
3874 set_current_sal_from_frame (get_current_frame ());
3875
3876 thread->suspend.waitstatus_pending_p = 0;
3877
3878 if (ws->kind == TARGET_WAITKIND_STOPPED)
3879 {
3880 enum gdb_signal sig = ws->value.sig;
3881
3882 if (signal_print_state (sig))
3883 observer_notify_signal_received (sig);
3884 }
3885 observer_notify_normal_stop (NULL, 1);
3886}
3887
221e1a37
PA
3888/* Process all initial stop replies the remote side sent in response
3889 to the ? packet. These indicate threads that were already stopped
3890 on initial connection. We mark these threads as stopped and print
3891 their current frame before giving the user the prompt. */
3892
3893static void
6efcd9a8 3894process_initial_stop_replies (int from_tty)
221e1a37
PA
3895{
3896 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3897 struct inferior *inf;
3898 struct thread_info *thread;
3899 struct thread_info *selected = NULL;
3900 struct thread_info *lowest_stopped = NULL;
3901 struct thread_info *first = NULL;
221e1a37
PA
3902
3903 /* Consume the initial pending events. */
3904 while (pending_stop_replies-- > 0)
3905 {
3906 ptid_t waiton_ptid = minus_one_ptid;
3907 ptid_t event_ptid;
3908 struct target_waitstatus ws;
3909 int ignore_event = 0;
6efcd9a8 3910 struct thread_info *thread;
221e1a37
PA
3911
3912 memset (&ws, 0, sizeof (ws));
3913 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3914 if (remote_debug)
3915 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3916
3917 switch (ws.kind)
3918 {
3919 case TARGET_WAITKIND_IGNORE:
3920 case TARGET_WAITKIND_NO_RESUMED:
3921 case TARGET_WAITKIND_SIGNALLED:
3922 case TARGET_WAITKIND_EXITED:
3923 /* We shouldn't see these, but if we do, just ignore. */
3924 if (remote_debug)
3925 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3926 ignore_event = 1;
3927 break;
3928
3929 case TARGET_WAITKIND_EXECD:
3930 xfree (ws.value.execd_pathname);
3931 break;
3932 default:
3933 break;
3934 }
3935
3936 if (ignore_event)
3937 continue;
3938
6efcd9a8 3939 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3940
3941 if (ws.kind == TARGET_WAITKIND_STOPPED)
3942 {
3943 enum gdb_signal sig = ws.value.sig;
3944
3945 /* Stubs traditionally report SIGTRAP as initial signal,
3946 instead of signal 0. Suppress it. */
3947 if (sig == GDB_SIGNAL_TRAP)
3948 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3949 thread->suspend.stop_signal = sig;
3950 ws.value.sig = sig;
3951 }
221e1a37 3952
6efcd9a8
PA
3953 thread->suspend.waitstatus = ws;
3954
3955 if (ws.kind != TARGET_WAITKIND_STOPPED
3956 || ws.value.sig != GDB_SIGNAL_0)
3957 thread->suspend.waitstatus_pending_p = 1;
3958
3959 set_executing (event_ptid, 0);
3960 set_running (event_ptid, 0);
85ad3aaf 3961 thread->priv->vcont_resumed = 0;
6efcd9a8
PA
3962 }
3963
3964 /* "Notice" the new inferiors before anything related to
3965 registers/memory. */
3966 ALL_INFERIORS (inf)
3967 {
3968 if (inf->pid == 0)
3969 continue;
3970
3971 inf->needs_setup = 1;
3972
3973 if (non_stop)
3974 {
3975 thread = any_live_thread_of_process (inf->pid);
3976 notice_new_inferior (thread->ptid,
3977 thread->state == THREAD_RUNNING,
3978 from_tty);
3979 }
3980 }
3981
3982 /* If all-stop on top of non-stop, pause all threads. Note this
3983 records the threads' stop pc, so must be done after "noticing"
3984 the inferiors. */
3985 if (!non_stop)
3986 {
3987 stop_all_threads ();
3988
3989 /* If all threads of an inferior were already stopped, we
3990 haven't setup the inferior yet. */
3991 ALL_INFERIORS (inf)
3992 {
3993 if (inf->pid == 0)
3994 continue;
221e1a37 3995
6efcd9a8
PA
3996 if (inf->needs_setup)
3997 {
3998 thread = any_live_thread_of_process (inf->pid);
3999 switch_to_thread_no_regs (thread);
4000 setup_inferior (0);
4001 }
4002 }
221e1a37 4003 }
6efcd9a8
PA
4004
4005 /* Now go over all threads that are stopped, and print their current
4006 frame. If all-stop, then if there's a signalled thread, pick
4007 that as current. */
4008 ALL_NON_EXITED_THREADS (thread)
4009 {
6efcd9a8
PA
4010 if (first == NULL)
4011 first = thread;
4012
4013 if (!non_stop)
4014 set_running (thread->ptid, 0);
4015 else if (thread->state != THREAD_STOPPED)
4016 continue;
4017
6efcd9a8
PA
4018 if (selected == NULL
4019 && thread->suspend.waitstatus_pending_p)
4020 selected = thread;
4021
5d5658a1
PA
4022 if (lowest_stopped == NULL
4023 || thread->inf->num < lowest_stopped->inf->num
4024 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4025 lowest_stopped = thread;
4026
4027 if (non_stop)
4028 print_one_stopped_thread (thread);
4029 }
4030
4031 /* In all-stop, we only print the status of one thread, and leave
4032 others with their status pending. */
4033 if (!non_stop)
4034 {
4035 thread = selected;
4036 if (thread == NULL)
4037 thread = lowest_stopped;
4038 if (thread == NULL)
4039 thread = first;
4040
4041 print_one_stopped_thread (thread);
4042 }
4043
4044 /* For "info program". */
4045 thread = inferior_thread ();
4046 if (thread->state == THREAD_STOPPED)
4047 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4048}
4049
048094ac
PA
4050/* Start the remote connection and sync state. */
4051
9cbc821d 4052static void
04bd08de 4053remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 4054{
c8d104ad
PA
4055 struct remote_state *rs = get_remote_state ();
4056 struct packet_config *noack_config;
2d717e4f 4057 char *wait_status = NULL;
8621d6a9 4058
048094ac
PA
4059 /* Signal other parts that we're going through the initial setup,
4060 and so things may not be stable yet. E.g., we don't try to
4061 install tracepoints until we've relocated symbols. Also, a
4062 Ctrl-C before we're connected and synced up can't interrupt the
4063 target. Instead, it offers to drop the (potentially wedged)
4064 connection. */
4065 rs->starting_up = 1;
4066
522002f9 4067 QUIT;
c906108c 4068
9a7071a8
JB
4069 if (interrupt_on_connect)
4070 send_interrupt_sequence ();
4071
57e12211 4072 /* Ack any packet which the remote side has already sent. */
048094ac 4073 remote_serial_write ("+", 1);
1e51243a 4074
c8d104ad
PA
4075 /* The first packet we send to the target is the optional "supported
4076 packets" request. If the target can answer this, it will tell us
4077 which later probes to skip. */
4078 remote_query_supported ();
4079
d914c394 4080 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4081 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 4082 remote_set_permissions (target);
d914c394 4083
57809e5e
JK
4084 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4085 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4086 as a reply to known packet. For packet "vFile:setfs:" it is an
4087 invalid reply and GDB would return error in
4088 remote_hostio_set_filesystem, making remote files access impossible.
4089 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4090 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4091 {
4092 const char v_mustreplyempty[] = "vMustReplyEmpty";
4093
4094 putpkt (v_mustreplyempty);
4095 getpkt (&rs->buf, &rs->buf_size, 0);
4096 if (strcmp (rs->buf, "OK") == 0)
4097 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4098 else if (strcmp (rs->buf, "") != 0)
4099 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4100 rs->buf);
4101 }
4102
c8d104ad
PA
4103 /* Next, we possibly activate noack mode.
4104
4105 If the QStartNoAckMode packet configuration is set to AUTO,
4106 enable noack mode if the stub reported a wish for it with
4107 qSupported.
4108
4109 If set to TRUE, then enable noack mode even if the stub didn't
4110 report it in qSupported. If the stub doesn't reply OK, the
4111 session ends with an error.
4112
4113 If FALSE, then don't activate noack mode, regardless of what the
4114 stub claimed should be the default with qSupported. */
4115
4116 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4117 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4118 {
4119 putpkt ("QStartNoAckMode");
4120 getpkt (&rs->buf, &rs->buf_size, 0);
4121 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4122 rs->noack_mode = 1;
4123 }
4124
04bd08de 4125 if (extended_p)
5fe04517
PA
4126 {
4127 /* Tell the remote that we are using the extended protocol. */
4128 putpkt ("!");
4129 getpkt (&rs->buf, &rs->buf_size, 0);
4130 }
4131
9b224c5e
PA
4132 /* Let the target know which signals it is allowed to pass down to
4133 the program. */
4134 update_signals_program_target ();
4135
d962ef82
DJ
4136 /* Next, if the target can specify a description, read it. We do
4137 this before anything involving memory or registers. */
4138 target_find_description ();
4139
6c95b8df
PA
4140 /* Next, now that we know something about the target, update the
4141 address spaces in the program spaces. */
4142 update_address_spaces ();
4143
50c71eaf
PA
4144 /* On OSs where the list of libraries is global to all
4145 processes, we fetch them early. */
f5656ead 4146 if (gdbarch_has_global_solist (target_gdbarch ()))
e696b3ad 4147 solib_add (NULL, from_tty, auto_solib_add);
50c71eaf 4148
6efcd9a8 4149 if (target_is_non_stop_p ())
74531fed 4150 {
4082afcc 4151 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4152 error (_("Non-stop mode requested, but remote "
4153 "does not support non-stop"));
74531fed
PA
4154
4155 putpkt ("QNonStop:1");
4156 getpkt (&rs->buf, &rs->buf_size, 0);
4157
4158 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4159 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4160
4161 /* Find about threads and processes the stub is already
4162 controlling. We default to adding them in the running state.
4163 The '?' query below will then tell us about which threads are
4164 stopped. */
e8032dde 4165 remote_update_thread_list (target);
74531fed 4166 }
4082afcc 4167 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4168 {
4169 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4170 Request it explicitly. */
74531fed
PA
4171 putpkt ("QNonStop:0");
4172 getpkt (&rs->buf, &rs->buf_size, 0);
4173
4174 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4175 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4176 }
4177
a0743c90
YQ
4178 /* Upload TSVs regardless of whether the target is running or not. The
4179 remote stub, such as GDBserver, may have some predefined or builtin
4180 TSVs, even if the target is not running. */
8bd200f1 4181 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4182 {
4183 struct uploaded_tsv *uploaded_tsvs = NULL;
4184
181e3713 4185 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4186 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4187 }
4188
2d717e4f
DJ
4189 /* Check whether the target is running now. */
4190 putpkt ("?");
4191 getpkt (&rs->buf, &rs->buf_size, 0);
4192
6efcd9a8 4193 if (!target_is_non_stop_p ())
2d717e4f 4194 {
74531fed 4195 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4196 {
04bd08de 4197 if (!extended_p)
74531fed 4198 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4199
4200 /* We're connected, but not running. Drop out before we
4201 call start_remote. */
e278ad5b 4202 rs->starting_up = 0;
c35b1492 4203 return;
2d717e4f
DJ
4204 }
4205 else
74531fed 4206 {
74531fed 4207 /* Save the reply for later. */
224c3ddb 4208 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4209 strcpy (wait_status, rs->buf);
4210 }
4211
b7ea362b 4212 /* Fetch thread list. */
e8032dde 4213 target_update_thread_list ();
b7ea362b 4214
74531fed
PA
4215 /* Let the stub know that we want it to return the thread. */
4216 set_continue_thread (minus_one_ptid);
4217
b7ea362b
PA
4218 if (thread_count () == 0)
4219 {
4220 /* Target has no concept of threads at all. GDB treats
4221 non-threaded target as single-threaded; add a main
4222 thread. */
4223 add_current_inferior_and_thread (wait_status);
4224 }
4225 else
4226 {
4227 /* We have thread information; select the thread the target
4228 says should be current. If we're reconnecting to a
4229 multi-threaded program, this will ideally be the thread
4230 that last reported an event before GDB disconnected. */
4231 inferior_ptid = get_current_thread (wait_status);
4232 if (ptid_equal (inferior_ptid, null_ptid))
4233 {
4234 /* Odd... The target was able to list threads, but not
4235 tell us which thread was current (no "thread"
4236 register in T stop reply?). Just pick the first
4237 thread in the thread list then. */
c9f35b34
KB
4238
4239 if (remote_debug)
4240 fprintf_unfiltered (gdb_stdlog,
4241 "warning: couldn't determine remote "
4242 "current thread; picking first in list.\n");
4243
b7ea362b
PA
4244 inferior_ptid = thread_list->ptid;
4245 }
4246 }
74531fed 4247
6e586cc5
YQ
4248 /* init_wait_for_inferior should be called before get_offsets in order
4249 to manage `inserted' flag in bp loc in a correct state.
4250 breakpoint_init_inferior, called from init_wait_for_inferior, set
4251 `inserted' flag to 0, while before breakpoint_re_set, called from
4252 start_remote, set `inserted' flag to 1. In the initialization of
4253 inferior, breakpoint_init_inferior should be called first, and then
4254 breakpoint_re_set can be called. If this order is broken, state of
4255 `inserted' flag is wrong, and cause some problems on breakpoint
4256 manipulation. */
4257 init_wait_for_inferior ();
4258
74531fed
PA
4259 get_offsets (); /* Get text, data & bss offsets. */
4260
d962ef82
DJ
4261 /* If we could not find a description using qXfer, and we know
4262 how to do it some other way, try again. This is not
4263 supported for non-stop; it could be, but it is tricky if
4264 there are no stopped threads when we connect. */
04bd08de 4265 if (remote_read_description_p (target)
f5656ead 4266 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4267 {
4268 target_clear_description ();
4269 target_find_description ();
4270 }
4271
74531fed
PA
4272 /* Use the previously fetched status. */
4273 gdb_assert (wait_status != NULL);
4274 strcpy (rs->buf, wait_status);
4275 rs->cached_wait_status = 1;
4276
04bd08de 4277 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4278 }
4279 else
4280 {
68c97600
PA
4281 /* Clear WFI global state. Do this before finding about new
4282 threads and inferiors, and setting the current inferior.
4283 Otherwise we would clear the proceed status of the current
4284 inferior when we want its stop_soon state to be preserved
4285 (see notice_new_inferior). */
4286 init_wait_for_inferior ();
4287
74531fed
PA
4288 /* In non-stop, we will either get an "OK", meaning that there
4289 are no stopped threads at this time; or, a regular stop
4290 reply. In the latter case, there may be more than one thread
4291 stopped --- we pull them all out using the vStopped
4292 mechanism. */
4293 if (strcmp (rs->buf, "OK") != 0)
4294 {
722247f1 4295 struct notif_client *notif = &notif_client_stop;
2d717e4f 4296
722247f1
YQ
4297 /* remote_notif_get_pending_replies acks this one, and gets
4298 the rest out. */
f48ff2a7 4299 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4300 = remote_notif_parse (notif, rs->buf);
4301 remote_notif_get_pending_events (notif);
74531fed 4302 }
2d717e4f 4303
74531fed
PA
4304 if (thread_count () == 0)
4305 {
04bd08de 4306 if (!extended_p)
74531fed 4307 error (_("The target is not running (try extended-remote?)"));
82f73884 4308
c35b1492
PA
4309 /* We're connected, but not running. Drop out before we
4310 call start_remote. */
e278ad5b 4311 rs->starting_up = 0;
c35b1492
PA
4312 return;
4313 }
74531fed 4314
74531fed
PA
4315 /* In non-stop mode, any cached wait status will be stored in
4316 the stop reply queue. */
4317 gdb_assert (wait_status == NULL);
f0223081 4318
2455069d 4319 /* Report all signals during attach/startup. */
94bedb42 4320 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4321
4322 /* If there are already stopped threads, mark them stopped and
4323 report their stops before giving the prompt to the user. */
6efcd9a8 4324 process_initial_stop_replies (from_tty);
221e1a37
PA
4325
4326 if (target_can_async_p ())
4327 target_async (1);
74531fed 4328 }
c8d104ad 4329
c8d104ad
PA
4330 /* If we connected to a live target, do some additional setup. */
4331 if (target_has_execution)
4332 {
f4ccffad 4333 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4334 remote_check_symbols ();
c8d104ad 4335 }
50c71eaf 4336
d5551862
SS
4337 /* Possibly the target has been engaged in a trace run started
4338 previously; find out where things are at. */
8bd200f1 4339 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4340 {
00bf0b85 4341 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4342
00bf0b85
SS
4343 if (current_trace_status ()->running)
4344 printf_filtered (_("Trace is already running on the target.\n"));
4345
ab6617cc 4346 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4347
4348 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4349 }
4350
c0272db5
TW
4351 /* Possibly the target has been engaged in a btrace record started
4352 previously; find out where things are at. */
4353 remote_btrace_maybe_reopen ();
4354
1e51243a
PA
4355 /* The thread and inferior lists are now synchronized with the
4356 target, our symbols have been relocated, and we're merged the
4357 target's tracepoints with ours. We're done with basic start
4358 up. */
4359 rs->starting_up = 0;
4360
a25a5a45
PA
4361 /* Maybe breakpoints are global and need to be inserted now. */
4362 if (breakpoints_should_be_inserted_now ())
50c71eaf 4363 insert_breakpoints ();
c906108c
SS
4364}
4365
4366/* Open a connection to a remote debugger.
4367 NAME is the filename used for communication. */
4368
4369static void
014f9477 4370remote_open (const char *name, int from_tty)
c906108c 4371{
75c99385 4372 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4373}
4374
c906108c
SS
4375/* Open a connection to a remote debugger using the extended
4376 remote gdb protocol. NAME is the filename used for communication. */
4377
4378static void
014f9477 4379extended_remote_open (const char *name, int from_tty)
c906108c 4380{
75c99385 4381 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4382}
4383
ca4f7f8b
PA
4384/* Reset all packets back to "unknown support". Called when opening a
4385 new connection to a remote target. */
c906108c 4386
d471ea57 4387static void
ca4f7f8b 4388reset_all_packet_configs_support (void)
d471ea57
AC
4389{
4390 int i;
a744cf53 4391
444abaca 4392 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4393 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4394}
4395
ca4f7f8b
PA
4396/* Initialize all packet configs. */
4397
4398static void
4399init_all_packet_configs (void)
4400{
4401 int i;
4402
4403 for (i = 0; i < PACKET_MAX; i++)
4404 {
4405 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4406 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4407 }
4408}
4409
23860348 4410/* Symbol look-up. */
dc8acb97
MS
4411
4412static void
36d25514 4413remote_check_symbols (void)
dc8acb97 4414{
d01949b6 4415 struct remote_state *rs = get_remote_state ();
dc8acb97 4416 char *msg, *reply, *tmp;
dc8acb97 4417 int end;
28170b88 4418 long reply_size;
a5c0808e 4419 struct cleanup *old_chain;
dc8acb97 4420
63154eca
PA
4421 /* The remote side has no concept of inferiors that aren't running
4422 yet, it only knows about running processes. If we're connected
4423 but our current inferior is not running, we should not invite the
4424 remote target to request symbol lookups related to its
4425 (unrelated) current process. */
4426 if (!target_has_execution)
4427 return;
4428
4082afcc 4429 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4430 return;
4431
63154eca
PA
4432 /* Make sure the remote is pointing at the right process. Note
4433 there's no way to select "no process". */
3c9c4b83
PA
4434 set_general_process ();
4435
6d820c5c
DJ
4436 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4437 because we need both at the same time. */
224c3ddb 4438 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4439 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4440 reply = (char *) xmalloc (get_remote_packet_size ());
4441 make_cleanup (free_current_contents, &reply);
4442 reply_size = get_remote_packet_size ();
6d820c5c 4443
23860348 4444 /* Invite target to request symbol lookups. */
dc8acb97
MS
4445
4446 putpkt ("qSymbol::");
28170b88
MK
4447 getpkt (&reply, &reply_size, 0);
4448 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4449
61012eef 4450 while (startswith (reply, "qSymbol:"))
dc8acb97 4451 {
77e371c0
TT
4452 struct bound_minimal_symbol sym;
4453
dc8acb97 4454 tmp = &reply[8];
cfd77fa1 4455 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4456 msg[end] = '\0';
4457 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4458 if (sym.minsym == NULL)
ea9c271d 4459 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4460 else
2bbe3cc1 4461 {
f5656ead 4462 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4463 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4464
4465 /* If this is a function address, return the start of code
4466 instead of any data function descriptor. */
f5656ead 4467 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4468 sym_addr,
4469 &current_target);
4470
4471 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4472 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4473 }
4474
dc8acb97 4475 putpkt (msg);
28170b88 4476 getpkt (&reply, &reply_size, 0);
dc8acb97 4477 }
a5c0808e
PA
4478
4479 do_cleanups (old_chain);
dc8acb97
MS
4480}
4481
9db8d71f 4482static struct serial *
baa336ce 4483remote_serial_open (const char *name)
9db8d71f
DJ
4484{
4485 static int udp_warning = 0;
4486
4487 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4488 of in ser-tcp.c, because it is the remote protocol assuming that the
4489 serial connection is reliable and not the serial connection promising
4490 to be. */
61012eef 4491 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4492 {
3e43a32a
MS
4493 warning (_("The remote protocol may be unreliable over UDP.\n"
4494 "Some events may be lost, rendering further debugging "
4495 "impossible."));
9db8d71f
DJ
4496 udp_warning = 1;
4497 }
4498
4499 return serial_open (name);
4500}
4501
d914c394
SS
4502/* Inform the target of our permission settings. The permission flags
4503 work without this, but if the target knows the settings, it can do
4504 a couple things. First, it can add its own check, to catch cases
4505 that somehow manage to get by the permissions checks in target
4506 methods. Second, if the target is wired to disallow particular
4507 settings (for instance, a system in the field that is not set up to
4508 be able to stop at a breakpoint), it can object to any unavailable
4509 permissions. */
4510
4511void
c378d69d 4512remote_set_permissions (struct target_ops *self)
d914c394
SS
4513{
4514 struct remote_state *rs = get_remote_state ();
4515
bba74b36
YQ
4516 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4517 "WriteReg:%x;WriteMem:%x;"
4518 "InsertBreak:%x;InsertTrace:%x;"
4519 "InsertFastTrace:%x;Stop:%x",
4520 may_write_registers, may_write_memory,
4521 may_insert_breakpoints, may_insert_tracepoints,
4522 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4523 putpkt (rs->buf);
4524 getpkt (&rs->buf, &rs->buf_size, 0);
4525
4526 /* If the target didn't like the packet, warn the user. Do not try
4527 to undo the user's settings, that would just be maddening. */
4528 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4529 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4530}
4531
be2a5f71
DJ
4532/* This type describes each known response to the qSupported
4533 packet. */
4534struct protocol_feature
4535{
4536 /* The name of this protocol feature. */
4537 const char *name;
4538
4539 /* The default for this protocol feature. */
4540 enum packet_support default_support;
4541
4542 /* The function to call when this feature is reported, or after
4543 qSupported processing if the feature is not supported.
4544 The first argument points to this structure. The second
4545 argument indicates whether the packet requested support be
4546 enabled, disabled, or probed (or the default, if this function
4547 is being called at the end of processing and this feature was
4548 not reported). The third argument may be NULL; if not NULL, it
4549 is a NUL-terminated string taken from the packet following
4550 this feature's name and an equals sign. */
4551 void (*func) (const struct protocol_feature *, enum packet_support,
4552 const char *);
4553
4554 /* The corresponding packet for this feature. Only used if
4555 FUNC is remote_supported_packet. */
4556 int packet;
4557};
4558
be2a5f71
DJ
4559static void
4560remote_supported_packet (const struct protocol_feature *feature,
4561 enum packet_support support,
4562 const char *argument)
4563{
4564 if (argument)
4565 {
4566 warning (_("Remote qSupported response supplied an unexpected value for"
4567 " \"%s\"."), feature->name);
4568 return;
4569 }
4570
4082afcc 4571 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4572}
be2a5f71
DJ
4573
4574static void
4575remote_packet_size (const struct protocol_feature *feature,
4576 enum packet_support support, const char *value)
4577{
4578 struct remote_state *rs = get_remote_state ();
4579
4580 int packet_size;
4581 char *value_end;
4582
4583 if (support != PACKET_ENABLE)
4584 return;
4585
4586 if (value == NULL || *value == '\0')
4587 {
4588 warning (_("Remote target reported \"%s\" without a size."),
4589 feature->name);
4590 return;
4591 }
4592
4593 errno = 0;
4594 packet_size = strtol (value, &value_end, 16);
4595 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4596 {
4597 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4598 feature->name, value);
4599 return;
4600 }
4601
be2a5f71
DJ
4602 /* Record the new maximum packet size. */
4603 rs->explicit_packet_size = packet_size;
4604}
4605
dc473cfb 4606static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4607 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4608 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4609 PACKET_qXfer_auxv },
c78fa86a
GB
4610 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4611 PACKET_qXfer_exec_file },
23181151
DJ
4612 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4613 PACKET_qXfer_features },
cfa9d6d9
DJ
4614 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4615 PACKET_qXfer_libraries },
2268b414
JK
4616 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4617 PACKET_qXfer_libraries_svr4 },
ced63ec0 4618 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4619 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4620 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4621 PACKET_qXfer_memory_map },
4de6483e
UW
4622 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4623 PACKET_qXfer_spu_read },
4624 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4625 PACKET_qXfer_spu_write },
07e059b5
VP
4626 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4627 PACKET_qXfer_osdata },
dc146f7c
VP
4628 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4629 PACKET_qXfer_threads },
b3b9301e
PA
4630 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4631 PACKET_qXfer_traceframe_info },
89be2091
DJ
4632 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4633 PACKET_QPassSignals },
82075af2
JS
4634 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4635 PACKET_QCatchSyscalls },
9b224c5e
PA
4636 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4637 PACKET_QProgramSignals },
aefd8b33
SDJ
4638 { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4639 PACKET_QStartupWithShell },
a6f3e723
SL
4640 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4641 PACKET_QStartNoAckMode },
4082afcc
PA
4642 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4643 PACKET_multiprocess_feature },
4644 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4645 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4646 PACKET_qXfer_siginfo_read },
4647 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4648 PACKET_qXfer_siginfo_write },
4082afcc 4649 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4650 PACKET_ConditionalTracepoints },
4082afcc 4651 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4652 PACKET_ConditionalBreakpoints },
4082afcc 4653 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4654 PACKET_BreakpointCommands },
4082afcc 4655 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4656 PACKET_FastTracepoints },
4082afcc 4657 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4658 PACKET_StaticTracepoints },
4082afcc 4659 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4660 PACKET_InstallInTrace},
4082afcc
PA
4661 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4662 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4663 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4664 PACKET_bc },
4665 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4666 PACKET_bs },
409873ef
SS
4667 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4668 PACKET_TracepointSource },
d914c394
SS
4669 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4670 PACKET_QAllow },
4082afcc
PA
4671 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4672 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4673 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4674 PACKET_qXfer_fdpic },
169081d0
TG
4675 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4676 PACKET_qXfer_uib },
03583c20
UW
4677 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4678 PACKET_QDisableRandomization },
d1feda86 4679 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4680 { "QTBuffer:size", PACKET_DISABLE,
4681 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4682 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4683 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4684 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4685 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4686 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4687 PACKET_qXfer_btrace },
4688 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4689 PACKET_qXfer_btrace_conf },
4690 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4691 PACKET_Qbtrace_conf_bts_size },
4692 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4693 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4694 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4695 PACKET_fork_event_feature },
4696 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4697 PACKET_vfork_event_feature },
94585166
DB
4698 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4699 PACKET_exec_event_feature },
b20a6524 4700 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4701 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4702 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4703 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4704 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4705};
4706
c8d5aac9
L
4707static char *remote_support_xml;
4708
4709/* Register string appended to "xmlRegisters=" in qSupported query. */
4710
4711void
6e39997a 4712register_remote_support_xml (const char *xml)
c8d5aac9
L
4713{
4714#if defined(HAVE_LIBEXPAT)
4715 if (remote_support_xml == NULL)
c4f7c687 4716 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4717 else
4718 {
4719 char *copy = xstrdup (remote_support_xml + 13);
4720 char *p = strtok (copy, ",");
4721
4722 do
4723 {
4724 if (strcmp (p, xml) == 0)
4725 {
4726 /* already there */
4727 xfree (copy);
4728 return;
4729 }
4730 }
4731 while ((p = strtok (NULL, ",")) != NULL);
4732 xfree (copy);
4733
94b0dee1
PA
4734 remote_support_xml = reconcat (remote_support_xml,
4735 remote_support_xml, ",", xml,
4736 (char *) NULL);
c8d5aac9
L
4737 }
4738#endif
4739}
4740
4741static char *
4742remote_query_supported_append (char *msg, const char *append)
4743{
4744 if (msg)
94b0dee1 4745 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4746 else
4747 return xstrdup (append);
4748}
4749
be2a5f71
DJ
4750static void
4751remote_query_supported (void)
4752{
4753 struct remote_state *rs = get_remote_state ();
4754 char *next;
4755 int i;
4756 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4757
4758 /* The packet support flags are handled differently for this packet
4759 than for most others. We treat an error, a disabled packet, and
4760 an empty response identically: any features which must be reported
4761 to be used will be automatically disabled. An empty buffer
4762 accomplishes this, since that is also the representation for a list
4763 containing no features. */
4764
4765 rs->buf[0] = 0;
4082afcc 4766 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4767 {
c8d5aac9 4768 char *q = NULL;
94b0dee1 4769 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4770
73b8c1fd
PA
4771 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4772 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4773
f7e6eed5
PA
4774 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4775 q = remote_query_supported_append (q, "swbreak+");
4776 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4777 q = remote_query_supported_append (q, "hwbreak+");
4778
dde08ee1
PA
4779 q = remote_query_supported_append (q, "qRelocInsn+");
4780
8020350c
DB
4781 if (packet_set_cmd_state (PACKET_fork_event_feature)
4782 != AUTO_BOOLEAN_FALSE)
4783 q = remote_query_supported_append (q, "fork-events+");
4784 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4785 != AUTO_BOOLEAN_FALSE)
4786 q = remote_query_supported_append (q, "vfork-events+");
4787 if (packet_set_cmd_state (PACKET_exec_event_feature)
4788 != AUTO_BOOLEAN_FALSE)
4789 q = remote_query_supported_append (q, "exec-events+");
89245bc0 4790
750ce8d1
YQ
4791 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4792 q = remote_query_supported_append (q, "vContSupported+");
4793
65706a29
PA
4794 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4795 q = remote_query_supported_append (q, "QThreadEvents+");
4796
f2faf941
PA
4797 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4798 q = remote_query_supported_append (q, "no-resumed+");
4799
b35d5edb
PA
4800 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4801 the qSupported:xmlRegisters=i386 handling. */
4802 if (remote_support_xml != NULL)
4803 q = remote_query_supported_append (q, remote_support_xml);
4804
dde08ee1
PA
4805 q = reconcat (q, "qSupported:", q, (char *) NULL);
4806 putpkt (q);
82f73884 4807
94b0dee1
PA
4808 do_cleanups (old_chain);
4809
be2a5f71
DJ
4810 getpkt (&rs->buf, &rs->buf_size, 0);
4811
4812 /* If an error occured, warn, but do not return - just reset the
4813 buffer to empty and go on to disable features. */
4814 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4815 == PACKET_ERROR)
4816 {
4817 warning (_("Remote failure reply: %s"), rs->buf);
4818 rs->buf[0] = 0;
4819 }
4820 }
4821
4822 memset (seen, 0, sizeof (seen));
4823
4824 next = rs->buf;
4825 while (*next)
4826 {
4827 enum packet_support is_supported;
4828 char *p, *end, *name_end, *value;
4829
4830 /* First separate out this item from the rest of the packet. If
4831 there's another item after this, we overwrite the separator
4832 (terminated strings are much easier to work with). */
4833 p = next;
4834 end = strchr (p, ';');
4835 if (end == NULL)
4836 {
4837 end = p + strlen (p);
4838 next = end;
4839 }
4840 else
4841 {
89be2091
DJ
4842 *end = '\0';
4843 next = end + 1;
4844
be2a5f71
DJ
4845 if (end == p)
4846 {
4847 warning (_("empty item in \"qSupported\" response"));
4848 continue;
4849 }
be2a5f71
DJ
4850 }
4851
4852 name_end = strchr (p, '=');
4853 if (name_end)
4854 {
4855 /* This is a name=value entry. */
4856 is_supported = PACKET_ENABLE;
4857 value = name_end + 1;
4858 *name_end = '\0';
4859 }
4860 else
4861 {
4862 value = NULL;
4863 switch (end[-1])
4864 {
4865 case '+':
4866 is_supported = PACKET_ENABLE;
4867 break;
4868
4869 case '-':
4870 is_supported = PACKET_DISABLE;
4871 break;
4872
4873 case '?':
4874 is_supported = PACKET_SUPPORT_UNKNOWN;
4875 break;
4876
4877 default:
3e43a32a
MS
4878 warning (_("unrecognized item \"%s\" "
4879 "in \"qSupported\" response"), p);
be2a5f71
DJ
4880 continue;
4881 }
4882 end[-1] = '\0';
4883 }
4884
4885 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4886 if (strcmp (remote_protocol_features[i].name, p) == 0)
4887 {
4888 const struct protocol_feature *feature;
4889
4890 seen[i] = 1;
4891 feature = &remote_protocol_features[i];
4892 feature->func (feature, is_supported, value);
4893 break;
4894 }
4895 }
4896
4897 /* If we increased the packet size, make sure to increase the global
4898 buffer size also. We delay this until after parsing the entire
4899 qSupported packet, because this is the same buffer we were
4900 parsing. */
4901 if (rs->buf_size < rs->explicit_packet_size)
4902 {
4903 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4904 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4905 }
4906
4907 /* Handle the defaults for unmentioned features. */
4908 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4909 if (!seen[i])
4910 {
4911 const struct protocol_feature *feature;
4912
4913 feature = &remote_protocol_features[i];
4914 feature->func (feature, feature->default_support, NULL);
4915 }
4916}
4917
048094ac
PA
4918/* Serial QUIT handler for the remote serial descriptor.
4919
4920 Defers handling a Ctrl-C until we're done with the current
4921 command/response packet sequence, unless:
4922
4923 - We're setting up the connection. Don't send a remote interrupt
4924 request, as we're not fully synced yet. Quit immediately
4925 instead.
4926
4927 - The target has been resumed in the foreground
4928 (target_terminal_is_ours is false) with a synchronous resume
4929 packet, and we're blocked waiting for the stop reply, thus a
4930 Ctrl-C should be immediately sent to the target.
4931
4932 - We get a second Ctrl-C while still within the same serial read or
4933 write. In that case the serial is seemingly wedged --- offer to
4934 quit/disconnect.
4935
4936 - We see a second Ctrl-C without target response, after having
4937 previously interrupted the target. In that case the target/stub
4938 is probably wedged --- offer to quit/disconnect.
4939*/
4940
4941static void
4942remote_serial_quit_handler (void)
4943{
4944 struct remote_state *rs = get_remote_state ();
4945
4946 if (check_quit_flag ())
4947 {
4948 /* If we're starting up, we're not fully synced yet. Quit
4949 immediately. */
4950 if (rs->starting_up)
4951 quit ();
4952 else if (rs->got_ctrlc_during_io)
4953 {
4954 if (query (_("The target is not responding to GDB commands.\n"
4955 "Stop debugging it? ")))
4956 remote_unpush_and_throw ();
4957 }
4958 /* If ^C has already been sent once, offer to disconnect. */
4959 else if (!target_terminal_is_ours () && rs->ctrlc_pending_p)
4960 interrupt_query ();
4961 /* All-stop protocol, and blocked waiting for stop reply. Send
4962 an interrupt request. */
4963 else if (!target_terminal_is_ours () && rs->waiting_for_stop_reply)
4964 target_interrupt (inferior_ptid);
4965 else
4966 rs->got_ctrlc_during_io = 1;
4967 }
4968}
4969
78a095c3
JK
4970/* Remove any of the remote.c targets from target stack. Upper targets depend
4971 on it so remove them first. */
4972
4973static void
4974remote_unpush_target (void)
4975{
915ef8b1 4976 pop_all_targets_at_and_above (process_stratum);
78a095c3 4977}
be2a5f71 4978
048094ac
PA
4979static void
4980remote_unpush_and_throw (void)
4981{
4982 remote_unpush_target ();
4983 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
4984}
4985
c906108c 4986static void
014f9477 4987remote_open_1 (const char *name, int from_tty,
3e43a32a 4988 struct target_ops *target, int extended_p)
c906108c 4989{
d01949b6 4990 struct remote_state *rs = get_remote_state ();
a6f3e723 4991
c906108c 4992 if (name == 0)
8a3fe4f8 4993 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4994 "serial device is attached to the remote system\n"
8a3fe4f8 4995 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4996
23860348 4997 /* See FIXME above. */
c6ebd6cf 4998 if (!target_async_permitted)
92d1e331 4999 wait_forever_enabled_p = 1;
6426a772 5000
2d717e4f 5001 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
5002 Ask this question first, before target_preopen has a chance to kill
5003 anything. */
5d93a237 5004 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 5005 {
78a095c3
JK
5006 if (from_tty
5007 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
5008 error (_("Still connected."));
5009 }
5010
78a095c3 5011 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5012 target_preopen (from_tty);
5013
89be2091 5014 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
5015 xfree (rs->last_pass_packet);
5016 rs->last_pass_packet = NULL;
89be2091 5017
9b224c5e
PA
5018 /* Make sure we send the program signals list the next time we
5019 resume. */
5e4a05c4
TT
5020 xfree (rs->last_program_signals_packet);
5021 rs->last_program_signals_packet = NULL;
9b224c5e 5022
ad9a8f3f 5023 remote_fileio_reset ();
1dd41f16
NS
5024 reopen_exec_file ();
5025 reread_symbols ();
5026
5d93a237
TT
5027 rs->remote_desc = remote_serial_open (name);
5028 if (!rs->remote_desc)
c906108c
SS
5029 perror_with_name (name);
5030
5031 if (baud_rate != -1)
5032 {
5d93a237 5033 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5034 {
9b74d5d3
KB
5035 /* The requested speed could not be set. Error out to
5036 top level after closing remote_desc. Take care to
5037 set remote_desc to NULL to avoid closing remote_desc
5038 more than once. */
5d93a237
TT
5039 serial_close (rs->remote_desc);
5040 rs->remote_desc = NULL;
c906108c
SS
5041 perror_with_name (name);
5042 }
5043 }
5044
236af5e3 5045 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5046 serial_raw (rs->remote_desc);
c906108c
SS
5047
5048 /* If there is something sitting in the buffer we might take it as a
5049 response to a command, which would be bad. */
5d93a237 5050 serial_flush_input (rs->remote_desc);
c906108c
SS
5051
5052 if (from_tty)
5053 {
5054 puts_filtered ("Remote debugging using ");
5055 puts_filtered (name);
5056 puts_filtered ("\n");
5057 }
23860348 5058 push_target (target); /* Switch to using remote target now. */
c906108c 5059
74531fed
PA
5060 /* Register extra event sources in the event loop. */
5061 remote_async_inferior_event_token
5062 = create_async_event_handler (remote_async_inferior_event_handler,
5063 NULL);
5965e028 5064 rs->notif_state = remote_notif_state_allocate ();
74531fed 5065
be2a5f71
DJ
5066 /* Reset the target state; these things will be queried either by
5067 remote_query_supported or as they are needed. */
ca4f7f8b 5068 reset_all_packet_configs_support ();
74531fed 5069 rs->cached_wait_status = 0;
be2a5f71 5070 rs->explicit_packet_size = 0;
a6f3e723 5071 rs->noack_mode = 0;
82f73884 5072 rs->extended = extended_p;
e24a49d8 5073 rs->waiting_for_stop_reply = 0;
3a29589a 5074 rs->ctrlc_pending_p = 0;
048094ac 5075 rs->got_ctrlc_during_io = 0;
802188a7 5076
47f8a51d
TT
5077 rs->general_thread = not_sent_ptid;
5078 rs->continue_thread = not_sent_ptid;
262e1174 5079 rs->remote_traceframe_number = -1;
c906108c 5080
3a00c802
PA
5081 rs->last_resume_exec_dir = EXEC_FORWARD;
5082
9d1f7ab2 5083 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5084 rs->use_threadinfo_query = 1;
5085 rs->use_threadextra_query = 1;
9d1f7ab2 5086
80152258
PA
5087 readahead_cache_invalidate ();
5088
048094ac
PA
5089 /* Start out by owning the terminal. */
5090 remote_async_terminal_ours_p = 1;
5091
c6ebd6cf 5092 if (target_async_permitted)
92d1e331 5093 {
92d1e331
DJ
5094 /* FIXME: cagney/1999-09-23: During the initial connection it is
5095 assumed that the target is already ready and able to respond to
0df8b418 5096 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5097 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5098 around this. Eventually a mechanism that allows
92d1e331 5099 wait_for_inferior() to expect/get timeouts will be
23860348 5100 implemented. */
92d1e331
DJ
5101 wait_forever_enabled_p = 0;
5102 }
5103
23860348 5104 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5105 no_shared_libraries (NULL, 0);
f78f6cf1 5106
74531fed
PA
5107 /* Start afresh. */
5108 init_thread_list ();
5109
36918e70 5110 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5111 target (we'd otherwise be in an inconsistent state) and then
5112 propogate the error on up the exception chain. This ensures that
5113 the caller doesn't stumble along blindly assuming that the
5114 function succeeded. The CLI doesn't have this problem but other
5115 UI's, such as MI do.
36918e70
AC
5116
5117 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5118 this function should return an error indication letting the
ce2826aa 5119 caller restore the previous state. Unfortunately the command
36918e70
AC
5120 ``target remote'' is directly wired to this function making that
5121 impossible. On a positive note, the CLI side of this problem has
5122 been fixed - the function set_cmd_context() makes it possible for
5123 all the ``target ....'' commands to share a common callback
5124 function. See cli-dump.c. */
109c3e39 5125 {
2d717e4f 5126
492d29ea 5127 TRY
04bd08de
TT
5128 {
5129 remote_start_remote (from_tty, target, extended_p);
5130 }
492d29ea 5131 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5132 {
c8d104ad
PA
5133 /* Pop the partially set up target - unless something else did
5134 already before throwing the exception. */
5d93a237 5135 if (rs->remote_desc != NULL)
78a095c3 5136 remote_unpush_target ();
c6ebd6cf 5137 if (target_async_permitted)
109c3e39
AC
5138 wait_forever_enabled_p = 1;
5139 throw_exception (ex);
5140 }
492d29ea 5141 END_CATCH
109c3e39 5142 }
c906108c 5143
f4abbc16
MM
5144 remote_btrace_reset ();
5145
c6ebd6cf 5146 if (target_async_permitted)
92d1e331 5147 wait_forever_enabled_p = 1;
43ff13b4
JM
5148}
5149
de0d863e
DB
5150/* Detach the specified process. */
5151
5152static void
5153remote_detach_pid (int pid)
5154{
5155 struct remote_state *rs = get_remote_state ();
5156
5157 if (remote_multi_process_p (rs))
5158 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5159 else
5160 strcpy (rs->buf, "D");
5161
5162 putpkt (rs->buf);
5163 getpkt (&rs->buf, &rs->buf_size, 0);
5164
5165 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5166 ;
5167 else if (rs->buf[0] == '\0')
5168 error (_("Remote doesn't know how to detach"));
5169 else
5170 error (_("Can't detach process."));
5171}
5172
5173/* This detaches a program to which we previously attached, using
5174 inferior_ptid to identify the process. After this is done, GDB
5175 can be used to debug some other program. We better not have left
5176 any breakpoints in the target program or it'll die when it hits
5177 one. */
c906108c
SS
5178
5179static void
de0d863e 5180remote_detach_1 (const char *args, int from_tty)
c906108c 5181{
82f73884 5182 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5183 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5184 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5185 int is_fork_parent;
c906108c
SS
5186
5187 if (args)
8a3fe4f8 5188 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 5189
2d717e4f
DJ
5190 if (!target_has_execution)
5191 error (_("No process to detach from."));
5192
0f48b757 5193 target_announce_detach (from_tty);
7cee1e54 5194
c906108c 5195 /* Tell the remote target to detach. */
de0d863e 5196 remote_detach_pid (pid);
82f73884 5197
8020350c
DB
5198 /* Exit only if this is the only active inferior. */
5199 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5200 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5201
de0d863e
DB
5202 /* Check to see if we are detaching a fork parent. Note that if we
5203 are detaching a fork child, tp == NULL. */
5204 is_fork_parent = (tp != NULL
5205 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5206
5207 /* If doing detach-on-fork, we don't mourn, because that will delete
5208 breakpoints that should be available for the followed inferior. */
5209 if (!is_fork_parent)
bc1e6c81 5210 target_mourn_inferior (inferior_ptid);
de0d863e
DB
5211 else
5212 {
5213 inferior_ptid = null_ptid;
5214 detach_inferior (pid);
5215 }
2d717e4f
DJ
5216}
5217
5218static void
52554a0e 5219remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5220{
de0d863e 5221 remote_detach_1 (args, from_tty);
2d717e4f
DJ
5222}
5223
5224static void
52554a0e 5225extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5226{
de0d863e
DB
5227 remote_detach_1 (args, from_tty);
5228}
5229
5230/* Target follow-fork function for remote targets. On entry, and
5231 at return, the current inferior is the fork parent.
5232
5233 Note that although this is currently only used for extended-remote,
5234 it is named remote_follow_fork in anticipation of using it for the
5235 remote target as well. */
5236
5237static int
5238remote_follow_fork (struct target_ops *ops, int follow_child,
5239 int detach_fork)
5240{
5241 struct remote_state *rs = get_remote_state ();
c269dbdb 5242 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5243
c269dbdb
DB
5244 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5245 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5246 {
5247 /* When following the parent and detaching the child, we detach
5248 the child here. For the case of following the child and
5249 detaching the parent, the detach is done in the target-
5250 independent follow fork code in infrun.c. We can't use
5251 target_detach when detaching an unfollowed child because
5252 the client side doesn't know anything about the child. */
5253 if (detach_fork && !follow_child)
5254 {
5255 /* Detach the fork child. */
5256 ptid_t child_ptid;
5257 pid_t child_pid;
5258
5259 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5260 child_pid = ptid_get_pid (child_ptid);
5261
5262 remote_detach_pid (child_pid);
5263 detach_inferior (child_pid);
5264 }
5265 }
5266 return 0;
c906108c
SS
5267}
5268
94585166
DB
5269/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5270 in the program space of the new inferior. On entry and at return the
5271 current inferior is the exec'ing inferior. INF is the new exec'd
5272 inferior, which may be the same as the exec'ing inferior unless
5273 follow-exec-mode is "new". */
5274
5275static void
5276remote_follow_exec (struct target_ops *ops,
5277 struct inferior *inf, char *execd_pathname)
5278{
5279 /* We know that this is a target file name, so if it has the "target:"
5280 prefix we strip it off before saving it in the program space. */
5281 if (is_target_filename (execd_pathname))
5282 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5283
5284 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5285}
5286
6ad8ae5c
DJ
5287/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5288
43ff13b4 5289static void
fee354ee 5290remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5291{
43ff13b4 5292 if (args)
2d717e4f 5293 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5294
8020350c
DB
5295 /* Make sure we unpush even the extended remote targets. Calling
5296 target_mourn_inferior won't unpush, and remote_mourn won't
5297 unpush if there is more than one inferior left. */
5298 unpush_target (target);
5299 generic_mourn_inferior ();
2d717e4f 5300
43ff13b4
JM
5301 if (from_tty)
5302 puts_filtered ("Ending remote debugging.\n");
5303}
5304
2d717e4f
DJ
5305/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5306 be chatty about it. */
5307
5308static void
20f796c9
GB
5309extended_remote_attach (struct target_ops *target, const char *args,
5310 int from_tty)
2d717e4f
DJ
5311{
5312 struct remote_state *rs = get_remote_state ();
be86555c 5313 int pid;
96ef3384 5314 char *wait_status = NULL;
2d717e4f 5315
74164c56 5316 pid = parse_pid_to_attach (args);
2d717e4f 5317
74164c56
JK
5318 /* Remote PID can be freely equal to getpid, do not check it here the same
5319 way as in other targets. */
2d717e4f 5320
4082afcc 5321 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5322 error (_("This target does not support attaching to a process"));
5323
7cee1e54
PA
5324 if (from_tty)
5325 {
5326 char *exec_file = get_exec_file (0);
5327
5328 if (exec_file)
5329 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5330 target_pid_to_str (pid_to_ptid (pid)));
5331 else
5332 printf_unfiltered (_("Attaching to %s\n"),
5333 target_pid_to_str (pid_to_ptid (pid)));
5334
5335 gdb_flush (gdb_stdout);
5336 }
5337
bba74b36 5338 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5339 putpkt (rs->buf);
5340 getpkt (&rs->buf, &rs->buf_size, 0);
5341
4082afcc
PA
5342 switch (packet_ok (rs->buf,
5343 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5344 {
4082afcc 5345 case PACKET_OK:
6efcd9a8 5346 if (!target_is_non_stop_p ())
74531fed
PA
5347 {
5348 /* Save the reply for later. */
224c3ddb 5349 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5350 strcpy (wait_status, rs->buf);
5351 }
5352 else if (strcmp (rs->buf, "OK") != 0)
5353 error (_("Attaching to %s failed with: %s"),
5354 target_pid_to_str (pid_to_ptid (pid)),
5355 rs->buf);
4082afcc
PA
5356 break;
5357 case PACKET_UNKNOWN:
5358 error (_("This target does not support attaching to a process"));
5359 default:
5360 error (_("Attaching to %s failed"),
5361 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5362 }
2d717e4f 5363
1b6e6f5c 5364 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5365
2d717e4f 5366 inferior_ptid = pid_to_ptid (pid);
79d7f229 5367
6efcd9a8 5368 if (target_is_non_stop_p ())
bad34192
PA
5369 {
5370 struct thread_info *thread;
79d7f229 5371
bad34192 5372 /* Get list of threads. */
e8032dde 5373 remote_update_thread_list (target);
82f73884 5374
bad34192
PA
5375 thread = first_thread_of_process (pid);
5376 if (thread)
5377 inferior_ptid = thread->ptid;
5378 else
5379 inferior_ptid = pid_to_ptid (pid);
5380
5381 /* Invalidate our notion of the remote current thread. */
47f8a51d 5382 record_currthread (rs, minus_one_ptid);
bad34192 5383 }
74531fed 5384 else
bad34192
PA
5385 {
5386 /* Now, if we have thread information, update inferior_ptid. */
5387 inferior_ptid = remote_current_thread (inferior_ptid);
5388
5389 /* Add the main thread to the thread list. */
5390 add_thread_silent (inferior_ptid);
5391 }
c0a2216e 5392
96ef3384
UW
5393 /* Next, if the target can specify a description, read it. We do
5394 this before anything involving memory or registers. */
5395 target_find_description ();
5396
6efcd9a8 5397 if (!target_is_non_stop_p ())
74531fed
PA
5398 {
5399 /* Use the previously fetched status. */
5400 gdb_assert (wait_status != NULL);
5401
5402 if (target_can_async_p ())
5403 {
722247f1
YQ
5404 struct notif_event *reply
5405 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5406
722247f1 5407 push_stop_reply ((struct stop_reply *) reply);
74531fed 5408
6a3753b3 5409 target_async (1);
74531fed
PA
5410 }
5411 else
5412 {
5413 gdb_assert (wait_status != NULL);
5414 strcpy (rs->buf, wait_status);
5415 rs->cached_wait_status = 1;
5416 }
5417 }
5418 else
5419 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5420}
5421
b9c1d481
AS
5422/* Implementation of the to_post_attach method. */
5423
5424static void
5425extended_remote_post_attach (struct target_ops *ops, int pid)
5426{
6efcd9a8
PA
5427 /* Get text, data & bss offsets. */
5428 get_offsets ();
5429
b9c1d481
AS
5430 /* In certain cases GDB might not have had the chance to start
5431 symbol lookup up until now. This could happen if the debugged
5432 binary is not using shared libraries, the vsyscall page is not
5433 present (on Linux) and the binary itself hadn't changed since the
5434 debugging process was started. */
5435 if (symfile_objfile != NULL)
5436 remote_check_symbols();
5437}
5438
c906108c 5439\f
506fb367
DJ
5440/* Check for the availability of vCont. This function should also check
5441 the response. */
c906108c
SS
5442
5443static void
6d820c5c 5444remote_vcont_probe (struct remote_state *rs)
c906108c 5445{
2e9f7625 5446 char *buf;
6d820c5c 5447
2e9f7625
DJ
5448 strcpy (rs->buf, "vCont?");
5449 putpkt (rs->buf);
6d820c5c 5450 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5451 buf = rs->buf;
c906108c 5452
506fb367 5453 /* Make sure that the features we assume are supported. */
61012eef 5454 if (startswith (buf, "vCont"))
506fb367
DJ
5455 {
5456 char *p = &buf[5];
750ce8d1 5457 int support_c, support_C;
506fb367 5458
750ce8d1
YQ
5459 rs->supports_vCont.s = 0;
5460 rs->supports_vCont.S = 0;
506fb367
DJ
5461 support_c = 0;
5462 support_C = 0;
d458bd84 5463 rs->supports_vCont.t = 0;
c1e36e3e 5464 rs->supports_vCont.r = 0;
506fb367
DJ
5465 while (p && *p == ';')
5466 {
5467 p++;
5468 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5469 rs->supports_vCont.s = 1;
506fb367 5470 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5471 rs->supports_vCont.S = 1;
506fb367
DJ
5472 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5473 support_c = 1;
5474 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5475 support_C = 1;
74531fed 5476 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5477 rs->supports_vCont.t = 1;
c1e36e3e
PA
5478 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5479 rs->supports_vCont.r = 1;
506fb367
DJ
5480
5481 p = strchr (p, ';');
5482 }
c906108c 5483
750ce8d1
YQ
5484 /* If c, and C are not all supported, we can't use vCont. Clearing
5485 BUF will make packet_ok disable the packet. */
5486 if (!support_c || !support_C)
506fb367
DJ
5487 buf[0] = 0;
5488 }
c906108c 5489
444abaca 5490 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5491}
c906108c 5492
0d8f58ca
PA
5493/* Helper function for building "vCont" resumptions. Write a
5494 resumption to P. ENDP points to one-passed-the-end of the buffer
5495 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5496 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5497 resumed thread should be single-stepped and/or signalled. If PTID
5498 equals minus_one_ptid, then all threads are resumed; if PTID
5499 represents a process, then all threads of the process are resumed;
5500 the thread to be stepped and/or signalled is given in the global
5501 INFERIOR_PTID. */
5502
5503static char *
5504append_resumption (char *p, char *endp,
2ea28649 5505 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5506{
5507 struct remote_state *rs = get_remote_state ();
5508
a493e3e2 5509 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5510 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5511 else if (step
5512 /* GDB is willing to range step. */
5513 && use_range_stepping
5514 /* Target supports range stepping. */
5515 && rs->supports_vCont.r
5516 /* We don't currently support range stepping multiple
5517 threads with a wildcard (though the protocol allows it,
5518 so stubs shouldn't make an active effort to forbid
5519 it). */
5520 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5521 {
5522 struct thread_info *tp;
5523
5524 if (ptid_equal (ptid, minus_one_ptid))
5525 {
5526 /* If we don't know about the target thread's tid, then
5527 we're resuming magic_null_ptid (see caller). */
5528 tp = find_thread_ptid (magic_null_ptid);
5529 }
5530 else
5531 tp = find_thread_ptid (ptid);
5532 gdb_assert (tp != NULL);
5533
5534 if (tp->control.may_range_step)
5535 {
5536 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5537
5538 p += xsnprintf (p, endp - p, ";r%s,%s",
5539 phex_nz (tp->control.step_range_start,
5540 addr_size),
5541 phex_nz (tp->control.step_range_end,
5542 addr_size));
5543 }
5544 else
5545 p += xsnprintf (p, endp - p, ";s");
5546 }
0d8f58ca
PA
5547 else if (step)
5548 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5549 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5550 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5551 else
5552 p += xsnprintf (p, endp - p, ";c");
5553
5554 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5555 {
5556 ptid_t nptid;
5557
5558 /* All (-1) threads of process. */
ba348170 5559 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5560
5561 p += xsnprintf (p, endp - p, ":");
5562 p = write_ptid (p, endp, nptid);
5563 }
5564 else if (!ptid_equal (ptid, minus_one_ptid))
5565 {
5566 p += xsnprintf (p, endp - p, ":");
5567 p = write_ptid (p, endp, ptid);
5568 }
5569
5570 return p;
5571}
5572
799a2abe
PA
5573/* Clear the thread's private info on resume. */
5574
5575static void
5576resume_clear_thread_private_info (struct thread_info *thread)
5577{
5578 if (thread->priv != NULL)
5579 {
5580 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5581 thread->priv->watch_data_address = 0;
5582 }
5583}
5584
e5ef252a
PA
5585/* Append a vCont continue-with-signal action for threads that have a
5586 non-zero stop signal. */
5587
5588static char *
5589append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5590{
5591 struct thread_info *thread;
5592
034f788c 5593 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5594 if (ptid_match (thread->ptid, ptid)
5595 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5596 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5597 {
5598 p = append_resumption (p, endp, thread->ptid,
5599 0, thread->suspend.stop_signal);
5600 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5601 resume_clear_thread_private_info (thread);
e5ef252a
PA
5602 }
5603
5604 return p;
5605}
5606
7b68ffbb
PA
5607/* Set the target running, using the packets that use Hc
5608 (c/s/C/S). */
5609
5610static void
5611remote_resume_with_hc (struct target_ops *ops,
5612 ptid_t ptid, int step, enum gdb_signal siggnal)
5613{
5614 struct remote_state *rs = get_remote_state ();
5615 struct thread_info *thread;
5616 char *buf;
5617
5618 rs->last_sent_signal = siggnal;
5619 rs->last_sent_step = step;
5620
5621 /* The c/s/C/S resume packets use Hc, so set the continue
5622 thread. */
5623 if (ptid_equal (ptid, minus_one_ptid))
5624 set_continue_thread (any_thread_ptid);
5625 else
5626 set_continue_thread (ptid);
5627
5628 ALL_NON_EXITED_THREADS (thread)
5629 resume_clear_thread_private_info (thread);
5630
5631 buf = rs->buf;
5632 if (execution_direction == EXEC_REVERSE)
5633 {
5634 /* We don't pass signals to the target in reverse exec mode. */
5635 if (info_verbose && siggnal != GDB_SIGNAL_0)
5636 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5637 siggnal);
5638
5639 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5640 error (_("Remote reverse-step not supported."));
5641 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5642 error (_("Remote reverse-continue not supported."));
5643
5644 strcpy (buf, step ? "bs" : "bc");
5645 }
5646 else if (siggnal != GDB_SIGNAL_0)
5647 {
5648 buf[0] = step ? 'S' : 'C';
5649 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5650 buf[2] = tohex (((int) siggnal) & 0xf);
5651 buf[3] = '\0';
5652 }
5653 else
5654 strcpy (buf, step ? "s" : "c");
5655
5656 putpkt (buf);
5657}
5658
506fb367
DJ
5659/* Resume the remote inferior by using a "vCont" packet. The thread
5660 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5661 resumed thread should be single-stepped and/or signalled. If PTID
5662 equals minus_one_ptid, then all threads are resumed; the thread to
5663 be stepped and/or signalled is given in the global INFERIOR_PTID.
5664 This function returns non-zero iff it resumes the inferior.
44eaed12 5665
7b68ffbb
PA
5666 This function issues a strict subset of all possible vCont commands
5667 at the moment. */
44eaed12 5668
506fb367 5669static int
7b68ffbb 5670remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5671{
5672 struct remote_state *rs = get_remote_state ();
82f73884
PA
5673 char *p;
5674 char *endp;
44eaed12 5675
7b68ffbb
PA
5676 /* No reverse execution actions defined for vCont. */
5677 if (execution_direction == EXEC_REVERSE)
5678 return 0;
5679
4082afcc 5680 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5681 remote_vcont_probe (rs);
44eaed12 5682
4082afcc 5683 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5684 return 0;
44eaed12 5685
82f73884
PA
5686 p = rs->buf;
5687 endp = rs->buf + get_remote_packet_size ();
5688
506fb367
DJ
5689 /* If we could generate a wider range of packets, we'd have to worry
5690 about overflowing BUF. Should there be a generic
5691 "multi-part-packet" packet? */
5692
0d8f58ca
PA
5693 p += xsnprintf (p, endp - p, "vCont");
5694
79d7f229 5695 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5696 {
79d7f229
PA
5697 /* MAGIC_NULL_PTID means that we don't have any active threads,
5698 so we don't have any TID numbers the inferior will
5699 understand. Make sure to only send forms that do not specify
5700 a TID. */
a9cbf802 5701 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5702 }
0d8f58ca 5703 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5704 {
0d8f58ca
PA
5705 /* Resume all threads (of all processes, or of a single
5706 process), with preference for INFERIOR_PTID. This assumes
5707 inferior_ptid belongs to the set of all threads we are about
5708 to resume. */
a493e3e2 5709 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5710 {
0d8f58ca
PA
5711 /* Step inferior_ptid, with or without signal. */
5712 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5713 }
0d8f58ca 5714
e5ef252a
PA
5715 /* Also pass down any pending signaled resumption for other
5716 threads not the current. */
5717 p = append_pending_thread_resumptions (p, endp, ptid);
5718
0d8f58ca 5719 /* And continue others without a signal. */
a493e3e2 5720 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5721 }
5722 else
506fb367
DJ
5723 {
5724 /* Scheduler locking; resume only PTID. */
a9cbf802 5725 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5726 }
c906108c 5727
82f73884
PA
5728 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5729 putpkt (rs->buf);
506fb367 5730
6efcd9a8 5731 if (target_is_non_stop_p ())
74531fed
PA
5732 {
5733 /* In non-stop, the stub replies to vCont with "OK". The stop
5734 reply will be reported asynchronously by means of a `%Stop'
5735 notification. */
5736 getpkt (&rs->buf, &rs->buf_size, 0);
5737 if (strcmp (rs->buf, "OK") != 0)
5738 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5739 }
5740
506fb367 5741 return 1;
c906108c 5742}
43ff13b4 5743
506fb367
DJ
5744/* Tell the remote machine to resume. */
5745
43ff13b4 5746static void
28439f5e 5747remote_resume (struct target_ops *ops,
2ea28649 5748 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5749{
d01949b6 5750 struct remote_state *rs = get_remote_state ();
43ff13b4 5751
85ad3aaf
PA
5752 /* When connected in non-stop mode, the core resumes threads
5753 individually. Resuming remote threads directly in target_resume
5754 would thus result in sending one packet per thread. Instead, to
5755 minimize roundtrip latency, here we just store the resume
5756 request; the actual remote resumption will be done in
5757 target_commit_resume / remote_commit_resume, where we'll be able
5758 to do vCont action coalescing. */
5759 if (target_is_non_stop_p () && execution_direction != EXEC_REVERSE)
5760 {
5761 struct private_thread_info *remote_thr;
5762
5763 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5764 remote_thr = get_private_info_ptid (inferior_ptid);
5765 else
5766 remote_thr = get_private_info_ptid (ptid);
5767 remote_thr->last_resume_step = step;
5768 remote_thr->last_resume_sig = siggnal;
5769 return;
5770 }
5771
722247f1
YQ
5772 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5773 (explained in remote-notif.c:handle_notification) so
5774 remote_notif_process is not called. We need find a place where
5775 it is safe to start a 'vNotif' sequence. It is good to do it
5776 before resuming inferior, because inferior was stopped and no RSP
5777 traffic at that moment. */
6efcd9a8 5778 if (!target_is_non_stop_p ())
5965e028 5779 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5780
3a00c802
PA
5781 rs->last_resume_exec_dir = execution_direction;
5782
7b68ffbb
PA
5783 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
5784 if (!remote_resume_with_vcont (ptid, step, siggnal))
5785 remote_resume_with_hc (ops, ptid, step, siggnal);
43ff13b4 5786
2acceee2 5787 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5788 with the event loop. NOTE: this is the one place where all the
5789 execution commands end up. We could alternatively do this in each
23860348 5790 of the execution commands in infcmd.c. */
2acceee2
JM
5791 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5792 into infcmd.c in order to allow inferior function calls to work
23860348 5793 NOT asynchronously. */
362646f5 5794 if (target_can_async_p ())
6a3753b3 5795 target_async (1);
e24a49d8
PA
5796
5797 /* We've just told the target to resume. The remote server will
5798 wait for the inferior to stop, and then send a stop reply. In
5799 the mean time, we can't start another command/query ourselves
74531fed
PA
5800 because the stub wouldn't be ready to process it. This applies
5801 only to the base all-stop protocol, however. In non-stop (which
5802 only supports vCont), the stub replies with an "OK", and is
5803 immediate able to process further serial input. */
6efcd9a8 5804 if (!target_is_non_stop_p ())
74531fed 5805 rs->waiting_for_stop_reply = 1;
43ff13b4 5806}
85ad3aaf
PA
5807
5808static void check_pending_events_prevent_wildcard_vcont
5809 (int *may_global_wildcard_vcont);
5810static int is_pending_fork_parent_thread (struct thread_info *thread);
5811
5812/* Private per-inferior info for target remote processes. */
5813
5814struct private_inferior
5815{
5816 /* Whether we can send a wildcard vCont for this process. */
5817 int may_wildcard_vcont;
5818};
5819
5820/* Structure used to track the construction of a vCont packet in the
5821 outgoing packet buffer. This is used to send multiple vCont
5822 packets if we have more actions than would fit a single packet. */
5823
5824struct vcont_builder
5825{
5826 /* Pointer to the first action. P points here if no action has been
5827 appended yet. */
5828 char *first_action;
5829
5830 /* Where the next action will be appended. */
5831 char *p;
5832
5833 /* The end of the buffer. Must never write past this. */
5834 char *endp;
5835};
5836
5837/* Prepare the outgoing buffer for a new vCont packet. */
5838
5839static void
5840vcont_builder_restart (struct vcont_builder *builder)
5841{
5842 struct remote_state *rs = get_remote_state ();
5843
5844 builder->p = rs->buf;
5845 builder->endp = rs->buf + get_remote_packet_size ();
5846 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
5847 builder->first_action = builder->p;
5848}
5849
5850/* If the vCont packet being built has any action, send it to the
5851 remote end. */
5852
5853static void
5854vcont_builder_flush (struct vcont_builder *builder)
5855{
5856 struct remote_state *rs;
5857
5858 if (builder->p == builder->first_action)
5859 return;
5860
5861 rs = get_remote_state ();
5862 putpkt (rs->buf);
5863 getpkt (&rs->buf, &rs->buf_size, 0);
5864 if (strcmp (rs->buf, "OK") != 0)
5865 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5866}
5867
5868/* The largest action is range-stepping, with its two addresses. This
5869 is more than sufficient. If a new, bigger action is created, it'll
5870 quickly trigger a failed assertion in append_resumption (and we'll
5871 just bump this). */
5872#define MAX_ACTION_SIZE 200
5873
5874/* Append a new vCont action in the outgoing packet being built. If
5875 the action doesn't fit the packet along with previous actions, push
5876 what we've got so far to the remote end and start over a new vCont
5877 packet (with the new action). */
5878
5879static void
5880vcont_builder_push_action (struct vcont_builder *builder,
5881 ptid_t ptid, int step, enum gdb_signal siggnal)
5882{
5883 char buf[MAX_ACTION_SIZE + 1];
5884 char *endp;
5885 size_t rsize;
5886
5887 endp = append_resumption (buf, buf + sizeof (buf),
5888 ptid, step, siggnal);
5889
5890 /* Check whether this new action would fit in the vCont packet along
5891 with previous actions. If not, send what we've got so far and
5892 start a new vCont packet. */
5893 rsize = endp - buf;
5894 if (rsize > builder->endp - builder->p)
5895 {
5896 vcont_builder_flush (builder);
5897 vcont_builder_restart (builder);
5898
5899 /* Should now fit. */
5900 gdb_assert (rsize <= builder->endp - builder->p);
5901 }
5902
5903 memcpy (builder->p, buf, rsize);
5904 builder->p += rsize;
5905 *builder->p = '\0';
5906}
5907
5908/* to_commit_resume implementation. */
5909
5910static void
5911remote_commit_resume (struct target_ops *ops)
5912{
5913 struct remote_state *rs = get_remote_state ();
5914 struct inferior *inf;
5915 struct thread_info *tp;
5916 int any_process_wildcard;
5917 int may_global_wildcard_vcont;
5918 struct vcont_builder vcont_builder;
5919
5920 /* If connected in all-stop mode, we'd send the remote resume
5921 request directly from remote_resume. Likewise if
5922 reverse-debugging, as there are no defined vCont actions for
5923 reverse execution. */
5924 if (!target_is_non_stop_p () || execution_direction == EXEC_REVERSE)
5925 return;
5926
5927 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
5928 instead of resuming all threads of each process individually.
5929 However, if any thread of a process must remain halted, we can't
5930 send wildcard resumes and must send one action per thread.
5931
5932 Care must be taken to not resume threads/processes the server
5933 side already told us are stopped, but the core doesn't know about
5934 yet, because the events are still in the vStopped notification
5935 queue. For example:
5936
5937 #1 => vCont s:p1.1;c
5938 #2 <= OK
5939 #3 <= %Stopped T05 p1.1
5940 #4 => vStopped
5941 #5 <= T05 p1.2
5942 #6 => vStopped
5943 #7 <= OK
5944 #8 (infrun handles the stop for p1.1 and continues stepping)
5945 #9 => vCont s:p1.1;c
5946
5947 The last vCont above would resume thread p1.2 by mistake, because
5948 the server has no idea that the event for p1.2 had not been
5949 handled yet.
5950
5951 The server side must similarly ignore resume actions for the
5952 thread that has a pending %Stopped notification (and any other
5953 threads with events pending), until GDB acks the notification
5954 with vStopped. Otherwise, e.g., the following case is
5955 mishandled:
5956
5957 #1 => g (or any other packet)
5958 #2 <= [registers]
5959 #3 <= %Stopped T05 p1.2
5960 #4 => vCont s:p1.1;c
5961 #5 <= OK
5962
5963 Above, the server must not resume thread p1.2. GDB can't know
5964 that p1.2 stopped until it acks the %Stopped notification, and
5965 since from GDB's perspective all threads should be running, it
5966 sends a "c" action.
5967
5968 Finally, special care must also be given to handling fork/vfork
5969 events. A (v)fork event actually tells us that two processes
5970 stopped -- the parent and the child. Until we follow the fork,
5971 we must not resume the child. Therefore, if we have a pending
5972 fork follow, we must not send a global wildcard resume action
5973 (vCont;c). We can still send process-wide wildcards though. */
5974
5975 /* Start by assuming a global wildcard (vCont;c) is possible. */
5976 may_global_wildcard_vcont = 1;
5977
5978 /* And assume every process is individually wildcard-able too. */
5979 ALL_NON_EXITED_INFERIORS (inf)
5980 {
5981 if (inf->priv == NULL)
5982 inf->priv = XNEW (struct private_inferior);
5983 inf->priv->may_wildcard_vcont = 1;
5984 }
5985
5986 /* Check for any pending events (not reported or processed yet) and
5987 disable process and global wildcard resumes appropriately. */
5988 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
5989
5990 ALL_NON_EXITED_THREADS (tp)
5991 {
5992 /* If a thread of a process is not meant to be resumed, then we
5993 can't wildcard that process. */
5994 if (!tp->executing)
5995 {
5996 tp->inf->priv->may_wildcard_vcont = 0;
5997
5998 /* And if we can't wildcard a process, we can't wildcard
5999 everything either. */
6000 may_global_wildcard_vcont = 0;
6001 continue;
6002 }
6003
6004 /* If a thread is the parent of an unfollowed fork, then we
6005 can't do a global wildcard, as that would resume the fork
6006 child. */
6007 if (is_pending_fork_parent_thread (tp))
6008 may_global_wildcard_vcont = 0;
6009 }
6010
6011 /* Now let's build the vCont packet(s). Actions must be appended
6012 from narrower to wider scopes (thread -> process -> global). If
6013 we end up with too many actions for a single packet vcont_builder
6014 flushes the current vCont packet to the remote side and starts a
6015 new one. */
6016 vcont_builder_restart (&vcont_builder);
6017
6018 /* Threads first. */
6019 ALL_NON_EXITED_THREADS (tp)
6020 {
6021 struct private_thread_info *remote_thr = tp->priv;
6022
6023 if (!tp->executing || remote_thr->vcont_resumed)
6024 continue;
6025
6026 gdb_assert (!thread_is_in_step_over_chain (tp));
6027
6028 if (!remote_thr->last_resume_step
6029 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6030 && tp->inf->priv->may_wildcard_vcont)
6031 {
6032 /* We'll send a wildcard resume instead. */
6033 remote_thr->vcont_resumed = 1;
6034 continue;
6035 }
6036
6037 vcont_builder_push_action (&vcont_builder, tp->ptid,
6038 remote_thr->last_resume_step,
6039 remote_thr->last_resume_sig);
6040 remote_thr->vcont_resumed = 1;
6041 }
6042
6043 /* Now check whether we can send any process-wide wildcard. This is
6044 to avoid sending a global wildcard in the case nothing is
6045 supposed to be resumed. */
6046 any_process_wildcard = 0;
6047
6048 ALL_NON_EXITED_INFERIORS (inf)
6049 {
6050 if (inf->priv->may_wildcard_vcont)
6051 {
6052 any_process_wildcard = 1;
6053 break;
6054 }
6055 }
6056
6057 if (any_process_wildcard)
6058 {
6059 /* If all processes are wildcard-able, then send a single "c"
6060 action, otherwise, send an "all (-1) threads of process"
6061 continue action for each running process, if any. */
6062 if (may_global_wildcard_vcont)
6063 {
6064 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6065 0, GDB_SIGNAL_0);
6066 }
6067 else
6068 {
6069 ALL_NON_EXITED_INFERIORS (inf)
6070 {
6071 if (inf->priv->may_wildcard_vcont)
6072 {
6073 vcont_builder_push_action (&vcont_builder,
6074 pid_to_ptid (inf->pid),
6075 0, GDB_SIGNAL_0);
6076 }
6077 }
6078 }
6079 }
6080
6081 vcont_builder_flush (&vcont_builder);
6082}
6083
c906108c 6084\f
43ff13b4 6085
74531fed
PA
6086/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6087 thread, all threads of a remote process, or all threads of all
6088 processes. */
6089
6090static void
6091remote_stop_ns (ptid_t ptid)
6092{
6093 struct remote_state *rs = get_remote_state ();
6094 char *p = rs->buf;
6095 char *endp = rs->buf + get_remote_packet_size ();
74531fed 6096
4082afcc 6097 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
6098 remote_vcont_probe (rs);
6099
d458bd84 6100 if (!rs->supports_vCont.t)
74531fed
PA
6101 error (_("Remote server does not support stopping threads"));
6102
f91d3df5
PA
6103 if (ptid_equal (ptid, minus_one_ptid)
6104 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
6105 p += xsnprintf (p, endp - p, "vCont;t");
6106 else
6107 {
6108 ptid_t nptid;
6109
74531fed
PA
6110 p += xsnprintf (p, endp - p, "vCont;t:");
6111
6112 if (ptid_is_pid (ptid))
6113 /* All (-1) threads of process. */
ba348170 6114 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
6115 else
6116 {
6117 /* Small optimization: if we already have a stop reply for
6118 this thread, no use in telling the stub we want this
6119 stopped. */
6120 if (peek_stop_reply (ptid))
6121 return;
6122
6123 nptid = ptid;
6124 }
6125
a9cbf802 6126 write_ptid (p, endp, nptid);
74531fed
PA
6127 }
6128
6129 /* In non-stop, we get an immediate OK reply. The stop reply will
6130 come in asynchronously by notification. */
6131 putpkt (rs->buf);
6132 getpkt (&rs->buf, &rs->buf_size, 0);
6133 if (strcmp (rs->buf, "OK") != 0)
6134 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6135}
6136
bfedc46a
PA
6137/* All-stop version of target_interrupt. Sends a break or a ^C to
6138 interrupt the remote target. It is undefined which thread of which
6139 process reports the interrupt. */
74531fed
PA
6140
6141static void
de979965 6142remote_interrupt_as (void)
74531fed
PA
6143{
6144 struct remote_state *rs = get_remote_state ();
6145
3a29589a
DJ
6146 rs->ctrlc_pending_p = 1;
6147
74531fed
PA
6148 /* If the inferior is stopped already, but the core didn't know
6149 about it yet, just ignore the request. The cached wait status
6150 will be collected in remote_wait. */
6151 if (rs->cached_wait_status)
6152 return;
6153
9a7071a8
JB
6154 /* Send interrupt_sequence to remote target. */
6155 send_interrupt_sequence ();
74531fed
PA
6156}
6157
de979965
PA
6158/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6159 the remote target. It is undefined which thread of which process
e42de8c7
PA
6160 reports the interrupt. Throws an error if the packet is not
6161 supported by the server. */
de979965 6162
e42de8c7 6163static void
de979965
PA
6164remote_interrupt_ns (void)
6165{
6166 struct remote_state *rs = get_remote_state ();
6167 char *p = rs->buf;
6168 char *endp = rs->buf + get_remote_packet_size ();
6169
6170 xsnprintf (p, endp - p, "vCtrlC");
6171
6172 /* In non-stop, we get an immediate OK reply. The stop reply will
6173 come in asynchronously by notification. */
6174 putpkt (rs->buf);
6175 getpkt (&rs->buf, &rs->buf_size, 0);
6176
6177 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6178 {
6179 case PACKET_OK:
6180 break;
6181 case PACKET_UNKNOWN:
e42de8c7 6182 error (_("No support for interrupting the remote target."));
de979965
PA
6183 case PACKET_ERROR:
6184 error (_("Interrupting target failed: %s"), rs->buf);
6185 }
de979965
PA
6186}
6187
bfedc46a 6188/* Implement the to_stop function for the remote targets. */
74531fed 6189
c906108c 6190static void
1eab8a48 6191remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 6192{
7a292a7a 6193 if (remote_debug)
0f71a2f6 6194 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6195
6efcd9a8 6196 if (target_is_non_stop_p ())
74531fed 6197 remote_stop_ns (ptid);
c906108c 6198 else
bfedc46a
PA
6199 {
6200 /* We don't currently have a way to transparently pause the
6201 remote target in all-stop mode. Interrupt it instead. */
de979965 6202 remote_interrupt_as ();
bfedc46a
PA
6203 }
6204}
6205
6206/* Implement the to_interrupt function for the remote targets. */
6207
6208static void
6209remote_interrupt (struct target_ops *self, ptid_t ptid)
6210{
e42de8c7
PA
6211 struct remote_state *rs = get_remote_state ();
6212
bfedc46a
PA
6213 if (remote_debug)
6214 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6215
e42de8c7
PA
6216 if (target_is_non_stop_p ())
6217 remote_interrupt_ns ();
bfedc46a 6218 else
e42de8c7 6219 remote_interrupt_as ();
c906108c
SS
6220}
6221
93692b58
PA
6222/* Implement the to_pass_ctrlc function for the remote targets. */
6223
6224static void
6225remote_pass_ctrlc (struct target_ops *self)
6226{
6227 struct remote_state *rs = get_remote_state ();
6228
6229 if (remote_debug)
6230 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6231
6232 /* If we're starting up, we're not fully synced yet. Quit
6233 immediately. */
6234 if (rs->starting_up)
6235 quit ();
6236 /* If ^C has already been sent once, offer to disconnect. */
6237 else if (rs->ctrlc_pending_p)
6238 interrupt_query ();
6239 else
6240 target_interrupt (inferior_ptid);
6241}
6242
c906108c
SS
6243/* Ask the user what to do when an interrupt is received. */
6244
6245static void
fba45db2 6246interrupt_query (void)
c906108c 6247{
abc56d60 6248 struct remote_state *rs = get_remote_state ();
c906108c 6249
abc56d60 6250 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6251 {
abc56d60
PA
6252 if (query (_("The target is not responding to interrupt requests.\n"
6253 "Stop debugging it? ")))
74531fed 6254 {
78a095c3 6255 remote_unpush_target ();
abc56d60 6256 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6257 }
6258 }
abc56d60
PA
6259 else
6260 {
6261 if (query (_("Interrupted while waiting for the program.\n"
6262 "Give up waiting? ")))
6263 quit ();
6264 }
c906108c
SS
6265}
6266
6426a772
JM
6267/* Enable/disable target terminal ownership. Most targets can use
6268 terminal groups to control terminal ownership. Remote targets are
6269 different in that explicit transfer of ownership to/from GDB/target
23860348 6270 is required. */
6426a772
JM
6271
6272static void
d2f640d4 6273remote_terminal_inferior (struct target_ops *self)
6426a772 6274{
d9d2d8b6
PA
6275 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
6276 idempotent. The event-loop GDB talking to an asynchronous target
6277 with a synchronous command calls this function from both
6278 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
6279 transfer the terminal to the target when it shouldn't this guard
6280 can go away. */
6426a772
JM
6281 if (!remote_async_terminal_ours_p)
6282 return;
6426a772 6283 remote_async_terminal_ours_p = 0;
6426a772
JM
6284 /* NOTE: At this point we could also register our selves as the
6285 recipient of all input. Any characters typed could then be
23860348 6286 passed on down to the target. */
6426a772
JM
6287}
6288
6289static void
e3594fd1 6290remote_terminal_ours (struct target_ops *self)
6426a772 6291{
75c99385 6292 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
6293 if (remote_async_terminal_ours_p)
6294 return;
6426a772
JM
6295 remote_async_terminal_ours_p = 1;
6296}
6297
176a6961 6298static void
917317f4 6299remote_console_output (char *msg)
c906108c
SS
6300{
6301 char *p;
6302
c5aa993b 6303 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6304 {
6305 char tb[2];
6306 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6307
c906108c
SS
6308 tb[0] = c;
6309 tb[1] = 0;
43ff13b4 6310 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6311 }
00db5b94
PA
6312 gdb_flush (gdb_stdtarg);
6313}
74531fed 6314
74531fed
PA
6315DEF_VEC_O(cached_reg_t);
6316
722247f1 6317typedef struct stop_reply
74531fed 6318{
722247f1 6319 struct notif_event base;
74531fed 6320
722247f1 6321 /* The identifier of the thread about this event */
74531fed
PA
6322 ptid_t ptid;
6323
340e3c99 6324 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6325 connection, represented by a remote_state object, is closed,
6326 all the associated stop_reply events should be released. */
6327 struct remote_state *rs;
6328
74531fed
PA
6329 struct target_waitstatus ws;
6330
15148d6a
PA
6331 /* Expedited registers. This makes remote debugging a bit more
6332 efficient for those targets that provide critical registers as
6333 part of their normal status mechanism (as another roundtrip to
6334 fetch them is avoided). */
74531fed
PA
6335 VEC(cached_reg_t) *regcache;
6336
f7e6eed5
PA
6337 enum target_stop_reason stop_reason;
6338
74531fed
PA
6339 CORE_ADDR watch_data_address;
6340
dc146f7c 6341 int core;
722247f1 6342} *stop_reply_p;
a744cf53 6343
722247f1
YQ
6344DECLARE_QUEUE_P (stop_reply_p);
6345DEFINE_QUEUE_P (stop_reply_p);
6346/* The list of already fetched and acknowledged stop events. This
6347 queue is used for notification Stop, and other notifications
6348 don't need queue for their events, because the notification events
6349 of Stop can't be consumed immediately, so that events should be
6350 queued first, and be consumed by remote_wait_{ns,as} one per
6351 time. Other notifications can consume their events immediately,
6352 so queue is not needed for them. */
6353static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
6354
6355static void
6356stop_reply_xfree (struct stop_reply *r)
6357{
f48ff2a7 6358 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6359}
6360
221e1a37
PA
6361/* Return the length of the stop reply queue. */
6362
6363static int
6364stop_reply_queue_length (void)
6365{
6366 return QUEUE_length (stop_reply_p, stop_reply_queue);
6367}
6368
722247f1
YQ
6369static void
6370remote_notif_stop_parse (struct notif_client *self, char *buf,
6371 struct notif_event *event)
6372{
6373 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6374}
6375
6376static void
6377remote_notif_stop_ack (struct notif_client *self, char *buf,
6378 struct notif_event *event)
6379{
6380 struct stop_reply *stop_reply = (struct stop_reply *) event;
6381
6382 /* acknowledge */
f5c4fcd9 6383 putpkt (self->ack_command);
722247f1
YQ
6384
6385 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6386 /* We got an unknown stop reply. */
6387 error (_("Unknown stop reply"));
6388
6389 push_stop_reply (stop_reply);
6390}
6391
6392static int
6393remote_notif_stop_can_get_pending_events (struct notif_client *self)
6394{
6395 /* We can't get pending events in remote_notif_process for
6396 notification stop, and we have to do this in remote_wait_ns
6397 instead. If we fetch all queued events from stub, remote stub
6398 may exit and we have no chance to process them back in
6399 remote_wait_ns. */
6400 mark_async_event_handler (remote_async_inferior_event_token);
6401 return 0;
6402}
6403
6404static void
6405stop_reply_dtr (struct notif_event *event)
6406{
6407 struct stop_reply *r = (struct stop_reply *) event;
d1dff226
AH
6408 cached_reg_t *reg;
6409 int ix;
6410
6411 for (ix = 0;
6412 VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6413 ix++)
6414 xfree (reg->data);
722247f1
YQ
6415
6416 VEC_free (cached_reg_t, r->regcache);
6417}
6418
6419static struct notif_event *
6420remote_notif_stop_alloc_reply (void)
6421{
8d749320
SM
6422 /* We cast to a pointer to the "base class". */
6423 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6424
6425 r->dtr = stop_reply_dtr;
6426
6427 return r;
6428}
6429
6430/* A client of notification Stop. */
6431
6432struct notif_client notif_client_stop =
6433{
6434 "Stop",
6435 "vStopped",
6436 remote_notif_stop_parse,
6437 remote_notif_stop_ack,
6438 remote_notif_stop_can_get_pending_events,
6439 remote_notif_stop_alloc_reply,
f48ff2a7 6440 REMOTE_NOTIF_STOP,
722247f1
YQ
6441};
6442
6443/* A parameter to pass data in and out. */
6444
6445struct queue_iter_param
6446{
6447 void *input;
6448 struct stop_reply *output;
6449};
6450
85ad3aaf 6451/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6452 the pid of the process that owns the threads we want to check, or
6453 -1 if we want to check all threads. */
6454
6455static int
6456is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6457 ptid_t thread_ptid)
6458{
6459 if (ws->kind == TARGET_WAITKIND_FORKED
6460 || ws->kind == TARGET_WAITKIND_VFORKED)
6461 {
6462 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6463 return 1;
6464 }
6465
6466 return 0;
6467}
6468
85ad3aaf
PA
6469/* Return the thread's pending status used to determine whether the
6470 thread is a fork parent stopped at a fork event. */
6471
6472static struct target_waitstatus *
6473thread_pending_fork_status (struct thread_info *thread)
6474{
6475 if (thread->suspend.waitstatus_pending_p)
6476 return &thread->suspend.waitstatus;
6477 else
6478 return &thread->pending_follow;
6479}
6480
6481/* Determine if THREAD is a pending fork parent thread. */
6482
6483static int
6484is_pending_fork_parent_thread (struct thread_info *thread)
6485{
6486 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6487 int pid = -1;
6488
6489 return is_pending_fork_parent (ws, pid, thread->ptid);
6490}
6491
cbb8991c
DB
6492/* Check whether EVENT is a fork event, and if it is, remove the
6493 fork child from the context list passed in DATA. */
6494
6495static int
6496remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6497 QUEUE_ITER (stop_reply_p) *iter,
6498 stop_reply_p event,
6499 void *data)
6500{
19ba03f4
SM
6501 struct queue_iter_param *param = (struct queue_iter_param *) data;
6502 struct threads_listing_context *context
6503 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6504
6505 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6506 || event->ws.kind == TARGET_WAITKIND_VFORKED
6507 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6508 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6509
6510 return 1;
6511}
6512
6513/* If CONTEXT contains any fork child threads that have not been
6514 reported yet, remove them from the CONTEXT list. If such a
6515 thread exists it is because we are stopped at a fork catchpoint
6516 and have not yet called follow_fork, which will set up the
6517 host-side data structures for the new process. */
6518
6519static void
6520remove_new_fork_children (struct threads_listing_context *context)
6521{
6522 struct thread_info * thread;
6523 int pid = -1;
6524 struct notif_client *notif = &notif_client_stop;
6525 struct queue_iter_param param;
6526
6527 /* For any threads stopped at a fork event, remove the corresponding
6528 fork child threads from the CONTEXT list. */
6529 ALL_NON_EXITED_THREADS (thread)
6530 {
85ad3aaf 6531 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
6532
6533 if (is_pending_fork_parent (ws, pid, thread->ptid))
6534 {
6535 threads_listing_context_remove (ws, context);
6536 }
6537 }
6538
6539 /* Check for any pending fork events (not reported or processed yet)
6540 in process PID and remove those fork child threads from the
6541 CONTEXT list as well. */
6542 remote_notif_get_pending_events (notif);
6543 param.input = context;
6544 param.output = NULL;
6545 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6546 remove_child_of_pending_fork, &param);
6547}
6548
85ad3aaf
PA
6549/* Check whether EVENT would prevent a global or process wildcard
6550 vCont action. */
6551
6552static int
6553check_pending_event_prevents_wildcard_vcont_callback
6554 (QUEUE (stop_reply_p) *q,
6555 QUEUE_ITER (stop_reply_p) *iter,
6556 stop_reply_p event,
6557 void *data)
6558{
6559 struct inferior *inf;
6560 int *may_global_wildcard_vcont = (int *) data;
6561
6562 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6563 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6564 return 1;
6565
6566 if (event->ws.kind == TARGET_WAITKIND_FORKED
6567 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6568 *may_global_wildcard_vcont = 0;
6569
6570 inf = find_inferior_ptid (event->ptid);
6571
6572 /* This may be the first time we heard about this process.
6573 Regardless, we must not do a global wildcard resume, otherwise
6574 we'd resume this process too. */
6575 *may_global_wildcard_vcont = 0;
6576 if (inf != NULL)
6577 inf->priv->may_wildcard_vcont = 0;
6578
6579 return 1;
6580}
6581
6582/* Check whether any event pending in the vStopped queue would prevent
6583 a global or process wildcard vCont action. Clear
6584 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6585 and clear the event inferior's may_wildcard_vcont flag if we can't
6586 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6587
6588static void
6589check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6590{
6591 struct notif_client *notif = &notif_client_stop;
6592
6593 remote_notif_get_pending_events (notif);
6594 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6595 check_pending_event_prevents_wildcard_vcont_callback,
6596 may_global_wildcard);
6597}
6598
f48ff2a7
YQ
6599/* Remove stop replies in the queue if its pid is equal to the given
6600 inferior's pid. */
722247f1
YQ
6601
6602static int
f48ff2a7
YQ
6603remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6604 QUEUE_ITER (stop_reply_p) *iter,
6605 stop_reply_p event,
6606 void *data)
722247f1 6607{
19ba03f4
SM
6608 struct queue_iter_param *param = (struct queue_iter_param *) data;
6609 struct inferior *inf = (struct inferior *) param->input;
722247f1 6610
f48ff2a7 6611 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6612 {
6613 stop_reply_xfree (event);
6614 QUEUE_remove_elem (stop_reply_p, q, iter);
6615 }
6616
6617 return 1;
6618}
6619
f48ff2a7 6620/* Discard all pending stop replies of inferior INF. */
c906108c 6621
74531fed 6622static void
5f4cf0bb 6623discard_pending_stop_replies (struct inferior *inf)
c906108c 6624{
722247f1 6625 struct queue_iter_param param;
f48ff2a7
YQ
6626 struct stop_reply *reply;
6627 struct remote_state *rs = get_remote_state ();
6628 struct remote_notif_state *rns = rs->notif_state;
6629
6630 /* This function can be notified when an inferior exists. When the
6631 target is not remote, the notification state is NULL. */
6632 if (rs->remote_desc == NULL)
6633 return;
6634
6635 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6636
74531fed 6637 /* Discard the in-flight notification. */
f48ff2a7 6638 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6639 {
722247f1 6640 stop_reply_xfree (reply);
f48ff2a7 6641 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6642 }
c906108c 6643
722247f1
YQ
6644 param.input = inf;
6645 param.output = NULL;
74531fed
PA
6646 /* Discard the stop replies we have already pulled with
6647 vStopped. */
722247f1 6648 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6649 remove_stop_reply_for_inferior, &param);
6650}
6651
bcc75809
YQ
6652/* If its remote state is equal to the given remote state,
6653 remove EVENT from the stop reply queue. */
6654
6655static int
6656remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6657 QUEUE_ITER (stop_reply_p) *iter,
6658 stop_reply_p event,
6659 void *data)
6660{
19ba03f4
SM
6661 struct queue_iter_param *param = (struct queue_iter_param *) data;
6662 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6663
6664 if (event->rs == rs)
6665 {
6666 stop_reply_xfree (event);
6667 QUEUE_remove_elem (stop_reply_p, q, iter);
6668 }
6669
6670 return 1;
6671}
6672
6673/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6674
6675static void
bcc75809 6676discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6677{
6678 struct queue_iter_param param;
6679
bcc75809 6680 param.input = rs;
f48ff2a7
YQ
6681 param.output = NULL;
6682 /* Discard the stop replies we have already pulled with
6683 vStopped. */
6684 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6685 remove_stop_reply_of_remote_state, &param);
722247f1 6686}
74531fed 6687
722247f1
YQ
6688/* A parameter to pass data in and out. */
6689
6690static int
6691remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6692 QUEUE_ITER (stop_reply_p) *iter,
6693 stop_reply_p event,
6694 void *data)
6695{
19ba03f4
SM
6696 struct queue_iter_param *param = (struct queue_iter_param *) data;
6697 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6698
6699 if (ptid_match (event->ptid, *ptid))
6700 {
6701 param->output = event;
6702 QUEUE_remove_elem (stop_reply_p, q, iter);
6703 return 0;
c8e38a49 6704 }
722247f1
YQ
6705
6706 return 1;
74531fed 6707}
43ff13b4 6708
722247f1
YQ
6709/* Remove the first reply in 'stop_reply_queue' which matches
6710 PTID. */
2e9f7625 6711
722247f1
YQ
6712static struct stop_reply *
6713remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6714{
722247f1
YQ
6715 struct queue_iter_param param;
6716
6717 param.input = &ptid;
6718 param.output = NULL;
6719
6720 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6721 remote_notif_remove_once_on_match, &param);
6722 if (notif_debug)
6723 fprintf_unfiltered (gdb_stdlog,
6724 "notif: discard queued event: 'Stop' in %s\n",
6725 target_pid_to_str (ptid));
a744cf53 6726
722247f1 6727 return param.output;
74531fed 6728}
75c99385 6729
74531fed
PA
6730/* Look for a queued stop reply belonging to PTID. If one is found,
6731 remove it from the queue, and return it. Returns NULL if none is
6732 found. If there are still queued events left to process, tell the
6733 event loop to get back to target_wait soon. */
e24a49d8 6734
74531fed
PA
6735static struct stop_reply *
6736queued_stop_reply (ptid_t ptid)
6737{
722247f1 6738 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6739
722247f1 6740 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6741 /* There's still at least an event left. */
6742 mark_async_event_handler (remote_async_inferior_event_token);
6743
722247f1 6744 return r;
74531fed
PA
6745}
6746
6747/* Push a fully parsed stop reply in the stop reply queue. Since we
6748 know that we now have at least one queued event left to pass to the
6749 core side, tell the event loop to get back to target_wait soon. */
6750
6751static void
6752push_stop_reply (struct stop_reply *new_event)
6753{
722247f1 6754 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6755
722247f1
YQ
6756 if (notif_debug)
6757 fprintf_unfiltered (gdb_stdlog,
6758 "notif: push 'Stop' %s to queue %d\n",
6759 target_pid_to_str (new_event->ptid),
6760 QUEUE_length (stop_reply_p,
6761 stop_reply_queue));
74531fed
PA
6762
6763 mark_async_event_handler (remote_async_inferior_event_token);
6764}
6765
722247f1
YQ
6766static int
6767stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6768 QUEUE_ITER (stop_reply_p) *iter,
6769 struct stop_reply *event,
6770 void *data)
6771{
19ba03f4 6772 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6773
6774 return !(ptid_equal (*ptid, event->ptid)
6775 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6776}
6777
74531fed
PA
6778/* Returns true if we have a stop reply for PTID. */
6779
6780static int
6781peek_stop_reply (ptid_t ptid)
6782{
722247f1
YQ
6783 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6784 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6785}
6786
26d56a93
SL
6787/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6788 starting with P and ending with PEND matches PREFIX. */
6789
6790static int
6791strprefix (const char *p, const char *pend, const char *prefix)
6792{
6793 for ( ; p < pend; p++, prefix++)
6794 if (*p != *prefix)
6795 return 0;
6796 return *prefix == '\0';
6797}
6798
74531fed
PA
6799/* Parse the stop reply in BUF. Either the function succeeds, and the
6800 result is stored in EVENT, or throws an error. */
6801
6802static void
6803remote_parse_stop_reply (char *buf, struct stop_reply *event)
6804{
6805 struct remote_arch_state *rsa = get_remote_arch_state ();
6806 ULONGEST addr;
6807 char *p;
94585166 6808 int skipregs = 0;
74531fed
PA
6809
6810 event->ptid = null_ptid;
bcc75809 6811 event->rs = get_remote_state ();
74531fed
PA
6812 event->ws.kind = TARGET_WAITKIND_IGNORE;
6813 event->ws.value.integer = 0;
f7e6eed5 6814 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6815 event->regcache = NULL;
dc146f7c 6816 event->core = -1;
74531fed
PA
6817
6818 switch (buf[0])
6819 {
6820 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6821 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6822 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6823 ss = signal number
6824 n... = register number
6825 r... = register contents
6826 */
6827
6828 p = &buf[3]; /* after Txx */
6829 while (*p)
6830 {
6831 char *p1;
cea39f65 6832 int fieldsize;
43ff13b4 6833
1f10ba14
PA
6834 p1 = strchr (p, ':');
6835 if (p1 == NULL)
6836 error (_("Malformed packet(a) (missing colon): %s\n\
6837Packet: '%s'\n"),
6838 p, buf);
6839 if (p == p1)
6840 error (_("Malformed packet(a) (missing register number): %s\n\
6841Packet: '%s'\n"),
6842 p, buf);
3c3bea1c 6843
1f10ba14
PA
6844 /* Some "registers" are actually extended stop information.
6845 Note if you're adding a new entry here: GDB 7.9 and
6846 earlier assume that all register "numbers" that start
6847 with an hex digit are real register numbers. Make sure
6848 the server only sends such a packet if it knows the
6849 client understands it. */
c8e38a49 6850
26d56a93 6851 if (strprefix (p, p1, "thread"))
1f10ba14 6852 event->ptid = read_ptid (++p1, &p);
82075af2
JS
6853 else if (strprefix (p, p1, "syscall_entry"))
6854 {
6855 ULONGEST sysno;
6856
6857 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6858 p = unpack_varlen_hex (++p1, &sysno);
6859 event->ws.value.syscall_number = (int) sysno;
6860 }
6861 else if (strprefix (p, p1, "syscall_return"))
6862 {
6863 ULONGEST sysno;
6864
6865 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6866 p = unpack_varlen_hex (++p1, &sysno);
6867 event->ws.value.syscall_number = (int) sysno;
6868 }
26d56a93
SL
6869 else if (strprefix (p, p1, "watch")
6870 || strprefix (p, p1, "rwatch")
6871 || strprefix (p, p1, "awatch"))
cea39f65 6872 {
f7e6eed5 6873 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6874 p = unpack_varlen_hex (++p1, &addr);
6875 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6876 }
26d56a93 6877 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6878 {
6879 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6880
6881 /* Make sure the stub doesn't forget to indicate support
6882 with qSupported. */
6883 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6884 error (_("Unexpected swbreak stop reason"));
6885
6886 /* The value part is documented as "must be empty",
6887 though we ignore it, in case we ever decide to make
6888 use of it in a backward compatible way. */
8424cc97 6889 p = strchrnul (p1 + 1, ';');
f7e6eed5 6890 }
26d56a93 6891 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6892 {
6893 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6894
6895 /* Make sure the stub doesn't forget to indicate support
6896 with qSupported. */
6897 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6898 error (_("Unexpected hwbreak stop reason"));
6899
6900 /* See above. */
8424cc97 6901 p = strchrnul (p1 + 1, ';');
f7e6eed5 6902 }
26d56a93 6903 else if (strprefix (p, p1, "library"))
cea39f65 6904 {
1f10ba14 6905 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 6906 p = strchrnul (p1 + 1, ';');
1f10ba14 6907 }
26d56a93 6908 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6909 {
6910 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6911 /* p1 will indicate "begin" or "end", but it makes
6912 no difference for now, so ignore it. */
8424cc97 6913 p = strchrnul (p1 + 1, ';');
1f10ba14 6914 }
26d56a93 6915 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6916 {
6917 ULONGEST c;
a744cf53 6918
1f10ba14
PA
6919 p = unpack_varlen_hex (++p1, &c);
6920 event->core = c;
cea39f65 6921 }
26d56a93 6922 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6923 {
6924 event->ws.value.related_pid = read_ptid (++p1, &p);
6925 event->ws.kind = TARGET_WAITKIND_FORKED;
6926 }
26d56a93 6927 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6928 {
6929 event->ws.value.related_pid = read_ptid (++p1, &p);
6930 event->ws.kind = TARGET_WAITKIND_VFORKED;
6931 }
26d56a93 6932 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6933 {
6934 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 6935 p = strchrnul (p1 + 1, ';');
c269dbdb 6936 }
6ab24463 6937 else if (strprefix (p, p1, "exec"))
94585166
DB
6938 {
6939 ULONGEST ignored;
6940 char pathname[PATH_MAX];
6941 int pathlen;
6942
6943 /* Determine the length of the execd pathname. */
6944 p = unpack_varlen_hex (++p1, &ignored);
6945 pathlen = (p - p1) / 2;
6946
6947 /* Save the pathname for event reporting and for
6948 the next run command. */
6949 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6950 pathname[pathlen] = '\0';
6951
6952 /* This is freed during event handling. */
6953 event->ws.value.execd_pathname = xstrdup (pathname);
6954 event->ws.kind = TARGET_WAITKIND_EXECD;
6955
6956 /* Skip the registers included in this packet, since
6957 they may be for an architecture different from the
6958 one used by the original program. */
6959 skipregs = 1;
6960 }
65706a29
PA
6961 else if (strprefix (p, p1, "create"))
6962 {
6963 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 6964 p = strchrnul (p1 + 1, ';');
65706a29 6965 }
cea39f65
MS
6966 else
6967 {
1f10ba14
PA
6968 ULONGEST pnum;
6969 char *p_temp;
6970
94585166
DB
6971 if (skipregs)
6972 {
8424cc97 6973 p = strchrnul (p1 + 1, ';');
94585166
DB
6974 p++;
6975 continue;
6976 }
6977
1f10ba14
PA
6978 /* Maybe a real ``P'' register number. */
6979 p_temp = unpack_varlen_hex (p, &pnum);
6980 /* If the first invalid character is the colon, we got a
6981 register number. Otherwise, it's an unknown stop
6982 reason. */
6983 if (p_temp == p1)
6984 {
6985 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6986 cached_reg_t cached_reg;
d1dff226 6987 struct gdbarch *gdbarch = target_gdbarch ();
43ff13b4 6988
1f10ba14
PA
6989 if (reg == NULL)
6990 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6991Packet: '%s'\n"),
1f10ba14 6992 hex_string (pnum), p, buf);
c8e38a49 6993
1f10ba14 6994 cached_reg.num = reg->regnum;
d1dff226
AH
6995 cached_reg.data = (gdb_byte *)
6996 xmalloc (register_size (gdbarch, reg->regnum));
4100683b 6997
1f10ba14
PA
6998 p = p1 + 1;
6999 fieldsize = hex2bin (p, cached_reg.data,
d1dff226 7000 register_size (gdbarch, reg->regnum));
1f10ba14 7001 p += 2 * fieldsize;
d1dff226 7002 if (fieldsize < register_size (gdbarch, reg->regnum))
1f10ba14 7003 warning (_("Remote reply is too short: %s"), buf);
74531fed 7004
1f10ba14
PA
7005 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7006 }
7007 else
7008 {
7009 /* Not a number. Silently skip unknown optional
7010 info. */
8424cc97 7011 p = strchrnul (p1 + 1, ';');
1f10ba14 7012 }
cea39f65 7013 }
c8e38a49 7014
cea39f65
MS
7015 if (*p != ';')
7016 error (_("Remote register badly formatted: %s\nhere: %s"),
7017 buf, p);
7018 ++p;
7019 }
5b5596ff
PA
7020
7021 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7022 break;
7023
c8e38a49
PA
7024 /* fall through */
7025 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7026 {
7027 int sig;
7028
7029 event->ws.kind = TARGET_WAITKIND_STOPPED;
7030 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7031 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7032 event->ws.value.sig = (enum gdb_signal) sig;
7033 else
7034 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7035 }
c8e38a49 7036 break;
65706a29
PA
7037 case 'w': /* Thread exited. */
7038 {
7039 char *p;
7040 ULONGEST value;
7041
7042 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7043 p = unpack_varlen_hex (&buf[1], &value);
7044 event->ws.value.integer = value;
7045 if (*p != ';')
7046 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7047 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7048 break;
7049 }
c8e38a49
PA
7050 case 'W': /* Target exited. */
7051 case 'X':
7052 {
7053 char *p;
7054 int pid;
7055 ULONGEST value;
82f73884 7056
c8e38a49
PA
7057 /* GDB used to accept only 2 hex chars here. Stubs should
7058 only send more if they detect GDB supports multi-process
7059 support. */
7060 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7061
c8e38a49
PA
7062 if (buf[0] == 'W')
7063 {
7064 /* The remote process exited. */
74531fed
PA
7065 event->ws.kind = TARGET_WAITKIND_EXITED;
7066 event->ws.value.integer = value;
c8e38a49
PA
7067 }
7068 else
7069 {
7070 /* The remote process exited with a signal. */
74531fed 7071 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7072 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7073 event->ws.value.sig = (enum gdb_signal) value;
7074 else
7075 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7076 }
82f73884 7077
c8e38a49
PA
7078 /* If no process is specified, assume inferior_ptid. */
7079 pid = ptid_get_pid (inferior_ptid);
7080 if (*p == '\0')
7081 ;
7082 else if (*p == ';')
7083 {
7084 p++;
7085
0b24eb2d 7086 if (*p == '\0')
82f73884 7087 ;
61012eef 7088 else if (startswith (p, "process:"))
82f73884 7089 {
c8e38a49 7090 ULONGEST upid;
a744cf53 7091
c8e38a49
PA
7092 p += sizeof ("process:") - 1;
7093 unpack_varlen_hex (p, &upid);
7094 pid = upid;
82f73884
PA
7095 }
7096 else
7097 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7098 }
c8e38a49
PA
7099 else
7100 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
7101 event->ptid = pid_to_ptid (pid);
7102 }
7103 break;
f2faf941
PA
7104 case 'N':
7105 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7106 event->ptid = minus_one_ptid;
7107 break;
74531fed
PA
7108 }
7109
6efcd9a8 7110 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
7111 error (_("No process or thread specified in stop reply: %s"), buf);
7112}
7113
722247f1
YQ
7114/* When the stub wants to tell GDB about a new notification reply, it
7115 sends a notification (%Stop, for example). Those can come it at
7116 any time, hence, we have to make sure that any pending
7117 putpkt/getpkt sequence we're making is finished, before querying
7118 the stub for more events with the corresponding ack command
7119 (vStopped, for example). E.g., if we started a vStopped sequence
7120 immediately upon receiving the notification, something like this
7121 could happen:
74531fed
PA
7122
7123 1.1) --> Hg 1
7124 1.2) <-- OK
7125 1.3) --> g
7126 1.4) <-- %Stop
7127 1.5) --> vStopped
7128 1.6) <-- (registers reply to step #1.3)
7129
7130 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7131 query.
7132
796cb314 7133 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7134 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7135 doing whatever we were doing:
7136
7137 2.1) --> Hg 1
7138 2.2) <-- OK
7139 2.3) --> g
7140 2.4) <-- %Stop
7141 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7142 2.5) <-- (registers reply to step #2.3)
7143
7144 Eventualy after step #2.5, we return to the event loop, which
7145 notices there's an event on the
7146 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7147 associated callback --- the function below. At this point, we're
7148 always safe to start a vStopped sequence. :
7149
7150 2.6) --> vStopped
7151 2.7) <-- T05 thread:2
7152 2.8) --> vStopped
7153 2.9) --> OK
7154*/
7155
722247f1
YQ
7156void
7157remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
7158{
7159 struct remote_state *rs = get_remote_state ();
74531fed 7160
f48ff2a7 7161 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7162 {
722247f1
YQ
7163 if (notif_debug)
7164 fprintf_unfiltered (gdb_stdlog,
7165 "notif: process: '%s' ack pending event\n",
7166 nc->name);
74531fed 7167
722247f1 7168 /* acknowledge */
f48ff2a7
YQ
7169 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7170 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7171
7172 while (1)
7173 {
7174 getpkt (&rs->buf, &rs->buf_size, 0);
7175 if (strcmp (rs->buf, "OK") == 0)
7176 break;
7177 else
722247f1 7178 remote_notif_ack (nc, rs->buf);
74531fed
PA
7179 }
7180 }
722247f1
YQ
7181 else
7182 {
7183 if (notif_debug)
7184 fprintf_unfiltered (gdb_stdlog,
7185 "notif: process: '%s' no pending reply\n",
7186 nc->name);
7187 }
74531fed
PA
7188}
7189
74531fed
PA
7190/* Called when it is decided that STOP_REPLY holds the info of the
7191 event that is to be returned to the core. This function always
7192 destroys STOP_REPLY. */
7193
7194static ptid_t
7195process_stop_reply (struct stop_reply *stop_reply,
7196 struct target_waitstatus *status)
7197{
7198 ptid_t ptid;
7199
7200 *status = stop_reply->ws;
7201 ptid = stop_reply->ptid;
7202
7203 /* If no thread/process was reported by the stub, assume the current
7204 inferior. */
7205 if (ptid_equal (ptid, null_ptid))
7206 ptid = inferior_ptid;
7207
5f3563ea 7208 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7209 && status->kind != TARGET_WAITKIND_SIGNALLED
7210 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7211 {
799a2abe 7212 struct private_thread_info *remote_thr;
ee154bee 7213
5f3563ea
PA
7214 /* Expedited registers. */
7215 if (stop_reply->regcache)
7216 {
217f1f79 7217 struct regcache *regcache
f5656ead 7218 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
7219 cached_reg_t *reg;
7220 int ix;
7221
7222 for (ix = 0;
d1dff226 7223 VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
5f3563ea 7224 ix++)
d1dff226 7225 {
217f1f79 7226 regcache_raw_supply (regcache, reg->num, reg->data);
d1dff226
AH
7227 xfree (reg->data);
7228 }
7229
5f3563ea
PA
7230 VEC_free (cached_reg_t, stop_reply->regcache);
7231 }
74531fed 7232
1941c569 7233 remote_notice_new_inferior (ptid, 0);
85ad3aaf 7234 remote_thr = get_private_info_ptid (ptid);
799a2abe
PA
7235 remote_thr->core = stop_reply->core;
7236 remote_thr->stop_reason = stop_reply->stop_reason;
7237 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7238 remote_thr->vcont_resumed = 0;
74531fed
PA
7239 }
7240
74531fed
PA
7241 stop_reply_xfree (stop_reply);
7242 return ptid;
7243}
7244
7245/* The non-stop mode version of target_wait. */
7246
7247static ptid_t
47608cb1 7248remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7249{
7250 struct remote_state *rs = get_remote_state ();
74531fed
PA
7251 struct stop_reply *stop_reply;
7252 int ret;
fee9eda9 7253 int is_notif = 0;
74531fed
PA
7254
7255 /* If in non-stop mode, get out of getpkt even if a
7256 notification is received. */
7257
7258 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7259 0 /* forever */, &is_notif);
74531fed
PA
7260 while (1)
7261 {
fee9eda9 7262 if (ret != -1 && !is_notif)
74531fed
PA
7263 switch (rs->buf[0])
7264 {
7265 case 'E': /* Error of some sort. */
7266 /* We're out of sync with the target now. Did it continue
7267 or not? We can't tell which thread it was in non-stop,
7268 so just ignore this. */
7269 warning (_("Remote failure reply: %s"), rs->buf);
7270 break;
7271 case 'O': /* Console output. */
7272 remote_console_output (rs->buf + 1);
7273 break;
7274 default:
7275 warning (_("Invalid remote reply: %s"), rs->buf);
7276 break;
7277 }
7278
7279 /* Acknowledge a pending stop reply that may have arrived in the
7280 mean time. */
f48ff2a7 7281 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7282 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7283
7284 /* If indeed we noticed a stop reply, we're done. */
7285 stop_reply = queued_stop_reply (ptid);
7286 if (stop_reply != NULL)
7287 return process_stop_reply (stop_reply, status);
7288
47608cb1 7289 /* Still no event. If we're just polling for an event, then
74531fed 7290 return to the event loop. */
47608cb1 7291 if (options & TARGET_WNOHANG)
74531fed
PA
7292 {
7293 status->kind = TARGET_WAITKIND_IGNORE;
7294 return minus_one_ptid;
7295 }
7296
47608cb1 7297 /* Otherwise do a blocking wait. */
74531fed 7298 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7299 1 /* forever */, &is_notif);
74531fed
PA
7300 }
7301}
7302
7303/* Wait until the remote machine stops, then return, storing status in
7304 STATUS just as `wait' would. */
7305
7306static ptid_t
47608cb1 7307remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7308{
7309 struct remote_state *rs = get_remote_state ();
74531fed 7310 ptid_t event_ptid = null_ptid;
cea39f65 7311 char *buf;
74531fed
PA
7312 struct stop_reply *stop_reply;
7313
47608cb1
PA
7314 again:
7315
74531fed
PA
7316 status->kind = TARGET_WAITKIND_IGNORE;
7317 status->value.integer = 0;
7318
7319 stop_reply = queued_stop_reply (ptid);
7320 if (stop_reply != NULL)
7321 return process_stop_reply (stop_reply, status);
7322
7323 if (rs->cached_wait_status)
7324 /* Use the cached wait status, but only once. */
7325 rs->cached_wait_status = 0;
7326 else
7327 {
7328 int ret;
722247f1 7329 int is_notif;
567420d1
PA
7330 int forever = ((options & TARGET_WNOHANG) == 0
7331 && wait_forever_enabled_p);
7332
7333 if (!rs->waiting_for_stop_reply)
7334 {
7335 status->kind = TARGET_WAITKIND_NO_RESUMED;
7336 return minus_one_ptid;
7337 }
74531fed 7338
74531fed
PA
7339 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7340 _never_ wait for ever -> test on target_is_async_p().
7341 However, before we do that we need to ensure that the caller
7342 knows how to take the target into/out of async mode. */
722247f1 7343 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 7344 forever, &is_notif);
722247f1
YQ
7345
7346 /* GDB gets a notification. Return to core as this event is
7347 not interesting. */
7348 if (ret != -1 && is_notif)
7349 return minus_one_ptid;
567420d1
PA
7350
7351 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7352 return minus_one_ptid;
74531fed
PA
7353 }
7354
7355 buf = rs->buf;
7356
3a29589a
DJ
7357 /* Assume that the target has acknowledged Ctrl-C unless we receive
7358 an 'F' or 'O' packet. */
7359 if (buf[0] != 'F' && buf[0] != 'O')
7360 rs->ctrlc_pending_p = 0;
7361
74531fed
PA
7362 switch (buf[0])
7363 {
7364 case 'E': /* Error of some sort. */
7365 /* We're out of sync with the target now. Did it continue or
7366 not? Not is more likely, so report a stop. */
29090fb6
LM
7367 rs->waiting_for_stop_reply = 0;
7368
74531fed
PA
7369 warning (_("Remote failure reply: %s"), buf);
7370 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7371 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7372 break;
7373 case 'F': /* File-I/O request. */
e42e5352
YQ
7374 /* GDB may access the inferior memory while handling the File-I/O
7375 request, but we don't want GDB accessing memory while waiting
7376 for a stop reply. See the comments in putpkt_binary. Set
7377 waiting_for_stop_reply to 0 temporarily. */
7378 rs->waiting_for_stop_reply = 0;
3a29589a
DJ
7379 remote_fileio_request (buf, rs->ctrlc_pending_p);
7380 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7381 /* GDB handled the File-I/O request, and the target is running
7382 again. Keep waiting for events. */
7383 rs->waiting_for_stop_reply = 1;
74531fed 7384 break;
f2faf941 7385 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7386 {
29090fb6
LM
7387 struct stop_reply *stop_reply;
7388
7389 /* There is a stop reply to handle. */
7390 rs->waiting_for_stop_reply = 0;
7391
7392 stop_reply
722247f1
YQ
7393 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7394 rs->buf);
74531fed 7395
74531fed 7396 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7397 break;
7398 }
7399 case 'O': /* Console output. */
7400 remote_console_output (buf + 1);
c8e38a49
PA
7401 break;
7402 case '\0':
b73be471 7403 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7404 {
7405 /* Zero length reply means that we tried 'S' or 'C' and the
7406 remote system doesn't support it. */
7407 target_terminal_ours_for_output ();
7408 printf_filtered
7409 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7410 gdb_signal_to_name (rs->last_sent_signal));
7411 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
7412 target_terminal_inferior ();
7413
f5c4fcd9
TT
7414 strcpy (buf, rs->last_sent_step ? "s" : "c");
7415 putpkt (buf);
c8e38a49 7416 break;
43ff13b4 7417 }
c8e38a49
PA
7418 /* else fallthrough */
7419 default:
7420 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7421 break;
43ff13b4 7422 }
c8e38a49 7423
f2faf941
PA
7424 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7425 return minus_one_ptid;
7426 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7427 {
7428 /* Nothing interesting happened. If we're doing a non-blocking
7429 poll, we're done. Otherwise, go back to waiting. */
7430 if (options & TARGET_WNOHANG)
7431 return minus_one_ptid;
7432 else
7433 goto again;
7434 }
74531fed
PA
7435 else if (status->kind != TARGET_WAITKIND_EXITED
7436 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7437 {
7438 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7439 record_currthread (rs, event_ptid);
82f73884
PA
7440 else
7441 event_ptid = inferior_ptid;
43ff13b4 7442 }
74531fed
PA
7443 else
7444 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7445 record_currthread (rs, minus_one_ptid);
79d7f229 7446
82f73884 7447 return event_ptid;
43ff13b4
JM
7448}
7449
74531fed
PA
7450/* Wait until the remote machine stops, then return, storing status in
7451 STATUS just as `wait' would. */
7452
c8e38a49 7453static ptid_t
117de6a9 7454remote_wait (struct target_ops *ops,
47608cb1 7455 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7456{
7457 ptid_t event_ptid;
7458
6efcd9a8 7459 if (target_is_non_stop_p ())
47608cb1 7460 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7461 else
47608cb1 7462 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7463
d9d41e78 7464 if (target_is_async_p ())
c8e38a49 7465 {
74531fed
PA
7466 /* If there are are events left in the queue tell the event loop
7467 to return here. */
722247f1 7468 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7469 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7470 }
c8e38a49
PA
7471
7472 return event_ptid;
7473}
7474
74ca34ce 7475/* Fetch a single register using a 'p' packet. */
c906108c 7476
b96ec7ac 7477static int
56be3814 7478fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac 7479{
9890e433 7480 struct gdbarch *gdbarch = get_regcache_arch (regcache);
b96ec7ac 7481 struct remote_state *rs = get_remote_state ();
2e9f7625 7482 char *buf, *p;
9890e433 7483 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
b96ec7ac
AC
7484 int i;
7485
4082afcc 7486 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7487 return 0;
7488
7489 if (reg->pnum == -1)
7490 return 0;
7491
2e9f7625 7492 p = rs->buf;
fcad0fa4 7493 *p++ = 'p';
74ca34ce 7494 p += hexnumstr (p, reg->pnum);
fcad0fa4 7495 *p++ = '\0';
1f4437a4
MS
7496 putpkt (rs->buf);
7497 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7498
2e9f7625
DJ
7499 buf = rs->buf;
7500
74ca34ce
DJ
7501 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7502 {
7503 case PACKET_OK:
7504 break;
7505 case PACKET_UNKNOWN:
7506 return 0;
7507 case PACKET_ERROR:
27a9c0bf
MS
7508 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7509 gdbarch_register_name (get_regcache_arch (regcache),
7510 reg->regnum),
7511 buf);
74ca34ce 7512 }
3f9a994c
JB
7513
7514 /* If this register is unfetchable, tell the regcache. */
7515 if (buf[0] == 'x')
8480adf2 7516 {
56be3814 7517 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7518 return 1;
b96ec7ac 7519 }
b96ec7ac 7520
3f9a994c
JB
7521 /* Otherwise, parse and supply the value. */
7522 p = buf;
7523 i = 0;
7524 while (p[0] != 0)
7525 {
7526 if (p[1] == 0)
74ca34ce 7527 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7528
7529 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7530 p += 2;
7531 }
56be3814 7532 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7533 return 1;
b96ec7ac
AC
7534}
7535
74ca34ce
DJ
7536/* Fetch the registers included in the target's 'g' packet. */
7537
29709017
DJ
7538static int
7539send_g_packet (void)
c906108c 7540{
d01949b6 7541 struct remote_state *rs = get_remote_state ();
cea39f65 7542 int buf_len;
c906108c 7543
bba74b36 7544 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7545 remote_send (&rs->buf, &rs->buf_size);
c906108c 7546
29709017
DJ
7547 /* We can get out of synch in various cases. If the first character
7548 in the buffer is not a hex character, assume that has happened
7549 and try to fetch another packet to read. */
7550 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7551 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7552 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7553 && rs->buf[0] != 'x') /* New: unavailable register value. */
7554 {
7555 if (remote_debug)
7556 fprintf_unfiltered (gdb_stdlog,
7557 "Bad register packet; fetching a new packet\n");
7558 getpkt (&rs->buf, &rs->buf_size, 0);
7559 }
7560
74ca34ce
DJ
7561 buf_len = strlen (rs->buf);
7562
7563 /* Sanity check the received packet. */
7564 if (buf_len % 2 != 0)
7565 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7566
7567 return buf_len / 2;
7568}
7569
7570static void
56be3814 7571process_g_packet (struct regcache *regcache)
29709017 7572{
4a22f64d 7573 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7574 struct remote_state *rs = get_remote_state ();
7575 struct remote_arch_state *rsa = get_remote_arch_state ();
7576 int i, buf_len;
7577 char *p;
7578 char *regs;
7579
7580 buf_len = strlen (rs->buf);
7581
7582 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7583 if (buf_len > 2 * rsa->sizeof_g_packet)
7584 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7585
7586 /* Save the size of the packet sent to us by the target. It is used
7587 as a heuristic when determining the max size of packets that the
7588 target can safely receive. */
7589 if (rsa->actual_register_packet_size == 0)
7590 rsa->actual_register_packet_size = buf_len;
7591
7592 /* If this is smaller than we guessed the 'g' packet would be,
7593 update our records. A 'g' reply that doesn't include a register's
7594 value implies either that the register is not available, or that
7595 the 'p' packet must be used. */
7596 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7597 {
9dc193c3 7598 long sizeof_g_packet = buf_len / 2;
74ca34ce 7599
4a22f64d 7600 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7601 {
9dc193c3
LF
7602 long offset = rsa->regs[i].offset;
7603 long reg_size = register_size (gdbarch, i);
7604
74ca34ce
DJ
7605 if (rsa->regs[i].pnum == -1)
7606 continue;
7607
9dc193c3 7608 if (offset >= sizeof_g_packet)
74ca34ce 7609 rsa->regs[i].in_g_packet = 0;
9dc193c3
LF
7610 else if (offset + reg_size > sizeof_g_packet)
7611 error (_("Truncated register %d in remote 'g' packet"), i);
b96ec7ac 7612 else
74ca34ce 7613 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7614 }
9dc193c3
LF
7615
7616 /* Looks valid enough, we can assume this is the correct length
7617 for a 'g' packet. It's important not to adjust
7618 rsa->sizeof_g_packet if we have truncated registers otherwise
7619 this "if" won't be run the next time the method is called
7620 with a packet of the same size and one of the internal errors
7621 below will trigger instead. */
7622 rsa->sizeof_g_packet = sizeof_g_packet;
74ca34ce 7623 }
b323314b 7624
224c3ddb 7625 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7626
7627 /* Unimplemented registers read as all bits zero. */
ea9c271d 7628 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7629
c906108c
SS
7630 /* Reply describes registers byte by byte, each byte encoded as two
7631 hex characters. Suck them all up, then supply them to the
7632 register cacheing/storage mechanism. */
7633
74ca34ce 7634 p = rs->buf;
ea9c271d 7635 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7636 {
74ca34ce
DJ
7637 if (p[0] == 0 || p[1] == 0)
7638 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7639 internal_error (__FILE__, __LINE__,
9b20d036 7640 _("unexpected end of 'g' packet reply"));
74ca34ce 7641
c906108c 7642 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7643 regs[i] = 0; /* 'x' */
c906108c
SS
7644 else
7645 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7646 p += 2;
7647 }
7648
a744cf53
MS
7649 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7650 {
7651 struct packet_reg *r = &rsa->regs[i];
9dc193c3 7652 long reg_size = register_size (gdbarch, i);
a744cf53
MS
7653
7654 if (r->in_g_packet)
7655 {
9dc193c3 7656 if ((r->offset + reg_size) * 2 > strlen (rs->buf))
a744cf53
MS
7657 /* This shouldn't happen - we adjusted in_g_packet above. */
7658 internal_error (__FILE__, __LINE__,
9b20d036 7659 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7660 else if (rs->buf[r->offset * 2] == 'x')
7661 {
7662 gdb_assert (r->offset * 2 < strlen (rs->buf));
7663 /* The register isn't available, mark it as such (at
7664 the same time setting the value to zero). */
7665 regcache_raw_supply (regcache, r->regnum, NULL);
7666 }
7667 else
7668 regcache_raw_supply (regcache, r->regnum,
7669 regs + r->offset);
7670 }
7671 }
c906108c
SS
7672}
7673
29709017 7674static void
56be3814 7675fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7676{
7677 send_g_packet ();
56be3814 7678 process_g_packet (regcache);
29709017
DJ
7679}
7680
e6e4e701
PA
7681/* Make the remote selected traceframe match GDB's selected
7682 traceframe. */
7683
7684static void
7685set_remote_traceframe (void)
7686{
7687 int newnum;
262e1174 7688 struct remote_state *rs = get_remote_state ();
e6e4e701 7689
262e1174 7690 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7691 return;
7692
7693 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7694 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7695
7696 newnum = target_trace_find (tfind_number,
7697 get_traceframe_number (), 0, 0, NULL);
7698
7699 /* Should not happen. If it does, all bets are off. */
7700 if (newnum != get_traceframe_number ())
7701 warning (_("could not set remote traceframe"));
7702}
7703
74ca34ce 7704static void
28439f5e
PA
7705remote_fetch_registers (struct target_ops *ops,
7706 struct regcache *regcache, int regnum)
74ca34ce 7707{
74ca34ce
DJ
7708 struct remote_arch_state *rsa = get_remote_arch_state ();
7709 int i;
7710
e6e4e701 7711 set_remote_traceframe ();
bcc0c096 7712 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
7713
7714 if (regnum >= 0)
7715 {
7716 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7717
74ca34ce
DJ
7718 gdb_assert (reg != NULL);
7719
7720 /* If this register might be in the 'g' packet, try that first -
7721 we are likely to read more than one register. If this is the
7722 first 'g' packet, we might be overly optimistic about its
7723 contents, so fall back to 'p'. */
7724 if (reg->in_g_packet)
7725 {
56be3814 7726 fetch_registers_using_g (regcache);
74ca34ce
DJ
7727 if (reg->in_g_packet)
7728 return;
7729 }
7730
56be3814 7731 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7732 return;
7733
7734 /* This register is not available. */
56be3814 7735 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7736
7737 return;
7738 }
7739
56be3814 7740 fetch_registers_using_g (regcache);
74ca34ce 7741
4a22f64d 7742 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7743 if (!rsa->regs[i].in_g_packet)
56be3814 7744 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7745 {
7746 /* This register is not available. */
56be3814 7747 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7748 }
7749}
7750
c906108c
SS
7751/* Prepare to store registers. Since we may send them all (using a
7752 'G' request), we have to read out the ones we don't want to change
7753 first. */
7754
c5aa993b 7755static void
f32dbf8c 7756remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7757{
ea9c271d 7758 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7759 int i;
cf0e1e0d 7760
c906108c 7761 /* Make sure the entire registers array is valid. */
4082afcc 7762 switch (packet_support (PACKET_P))
5a2468f5
JM
7763 {
7764 case PACKET_DISABLE:
7765 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7766 /* Make sure all the necessary registers are cached. */
4a22f64d 7767 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7768 if (rsa->regs[i].in_g_packet)
8e368124 7769 regcache_raw_update (regcache, rsa->regs[i].regnum);
5a2468f5
JM
7770 break;
7771 case PACKET_ENABLE:
7772 break;
7773 }
7774}
7775
ad10f812 7776/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7777 packet was not recognized. */
5a2468f5
JM
7778
7779static int
1f4437a4
MS
7780store_register_using_P (const struct regcache *regcache,
7781 struct packet_reg *reg)
5a2468f5 7782{
4a22f64d 7783 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7784 struct remote_state *rs = get_remote_state ();
5a2468f5 7785 /* Try storing a single register. */
6d820c5c 7786 char *buf = rs->buf;
9890e433 7787 gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
5a2468f5 7788 char *p;
5a2468f5 7789
4082afcc 7790 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7791 return 0;
7792
7793 if (reg->pnum == -1)
7794 return 0;
7795
ea9c271d 7796 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7797 p = buf + strlen (buf);
56be3814 7798 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7799 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7800 putpkt (rs->buf);
7801 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7802
74ca34ce
DJ
7803 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7804 {
7805 case PACKET_OK:
7806 return 1;
7807 case PACKET_ERROR:
27a9c0bf
MS
7808 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7809 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7810 case PACKET_UNKNOWN:
7811 return 0;
7812 default:
7813 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7814 }
c906108c
SS
7815}
7816
23860348
MS
7817/* Store register REGNUM, or all registers if REGNUM == -1, from the
7818 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7819
7820static void
56be3814 7821store_registers_using_G (const struct regcache *regcache)
c906108c 7822{
d01949b6 7823 struct remote_state *rs = get_remote_state ();
ea9c271d 7824 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7825 gdb_byte *regs;
c906108c
SS
7826 char *p;
7827
193cb69f
AC
7828 /* Extract all the registers in the regcache copying them into a
7829 local buffer. */
7830 {
b323314b 7831 int i;
a744cf53 7832
224c3ddb 7833 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7834 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7835 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7836 {
ea9c271d 7837 struct packet_reg *r = &rsa->regs[i];
a744cf53 7838
b323314b 7839 if (r->in_g_packet)
56be3814 7840 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7841 }
7842 }
c906108c
SS
7843
7844 /* Command describes registers byte by byte,
7845 each byte encoded as two hex characters. */
6d820c5c 7846 p = rs->buf;
193cb69f 7847 *p++ = 'G';
74ca34ce 7848 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7849 putpkt (rs->buf);
7850 getpkt (&rs->buf, &rs->buf_size, 0);
7851 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7852 error (_("Could not write registers; remote failure reply '%s'"),
7853 rs->buf);
c906108c 7854}
74ca34ce
DJ
7855
7856/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7857 of the register cache buffer. FIXME: ignores errors. */
7858
7859static void
28439f5e
PA
7860remote_store_registers (struct target_ops *ops,
7861 struct regcache *regcache, int regnum)
74ca34ce 7862{
74ca34ce
DJ
7863 struct remote_arch_state *rsa = get_remote_arch_state ();
7864 int i;
7865
e6e4e701 7866 set_remote_traceframe ();
bcc0c096 7867 set_general_thread (regcache_get_ptid (regcache));
74ca34ce
DJ
7868
7869 if (regnum >= 0)
7870 {
7871 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7872
74ca34ce
DJ
7873 gdb_assert (reg != NULL);
7874
7875 /* Always prefer to store registers using the 'P' packet if
7876 possible; we often change only a small number of registers.
7877 Sometimes we change a larger number; we'd need help from a
7878 higher layer to know to use 'G'. */
56be3814 7879 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7880 return;
7881
7882 /* For now, don't complain if we have no way to write the
7883 register. GDB loses track of unavailable registers too
7884 easily. Some day, this may be an error. We don't have
0df8b418 7885 any way to read the register, either... */
74ca34ce
DJ
7886 if (!reg->in_g_packet)
7887 return;
7888
56be3814 7889 store_registers_using_G (regcache);
74ca34ce
DJ
7890 return;
7891 }
7892
56be3814 7893 store_registers_using_G (regcache);
74ca34ce 7894
4a22f64d 7895 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7896 if (!rsa->regs[i].in_g_packet)
56be3814 7897 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7898 /* See above for why we do not issue an error here. */
7899 continue;
7900}
c906108c
SS
7901\f
7902
7903/* Return the number of hex digits in num. */
7904
7905static int
fba45db2 7906hexnumlen (ULONGEST num)
c906108c
SS
7907{
7908 int i;
7909
7910 for (i = 0; num != 0; i++)
7911 num >>= 4;
7912
325fac50 7913 return std::max (i, 1);
c906108c
SS
7914}
7915
2df3850c 7916/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7917
7918static int
fba45db2 7919hexnumstr (char *buf, ULONGEST num)
c906108c 7920{
c906108c 7921 int len = hexnumlen (num);
a744cf53 7922
2df3850c
JM
7923 return hexnumnstr (buf, num, len);
7924}
7925
c906108c 7926
2df3850c 7927/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7928
2df3850c 7929static int
fba45db2 7930hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7931{
7932 int i;
7933
7934 buf[width] = '\0';
7935
7936 for (i = width - 1; i >= 0; i--)
c906108c 7937 {
c5aa993b 7938 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7939 num >>= 4;
7940 }
7941
2df3850c 7942 return width;
c906108c
SS
7943}
7944
23860348 7945/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7946
7947static CORE_ADDR
fba45db2 7948remote_address_masked (CORE_ADDR addr)
c906108c 7949{
883b9c6c 7950 unsigned int address_size = remote_address_size;
a744cf53 7951
911c95a5
UW
7952 /* If "remoteaddresssize" was not set, default to target address size. */
7953 if (!address_size)
f5656ead 7954 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7955
7956 if (address_size > 0
7957 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7958 {
7959 /* Only create a mask when that mask can safely be constructed
23860348 7960 in a ULONGEST variable. */
c906108c 7961 ULONGEST mask = 1;
a744cf53 7962
911c95a5 7963 mask = (mask << address_size) - 1;
c906108c
SS
7964 addr &= mask;
7965 }
7966 return addr;
7967}
7968
7969/* Determine whether the remote target supports binary downloading.
7970 This is accomplished by sending a no-op memory write of zero length
7971 to the target at the specified address. It does not suffice to send
23860348
MS
7972 the whole packet, since many stubs strip the eighth bit and
7973 subsequently compute a wrong checksum, which causes real havoc with
7974 remote_write_bytes.
7a292a7a 7975
96baa820 7976 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7977 clean. In cases like this, the user should clear "remote
23860348 7978 X-packet". */
96baa820 7979
c906108c 7980static void
fba45db2 7981check_binary_download (CORE_ADDR addr)
c906108c 7982{
d01949b6 7983 struct remote_state *rs = get_remote_state ();
24b06219 7984
4082afcc 7985 switch (packet_support (PACKET_X))
c906108c 7986 {
96baa820
JM
7987 case PACKET_DISABLE:
7988 break;
7989 case PACKET_ENABLE:
7990 break;
7991 case PACKET_SUPPORT_UNKNOWN:
7992 {
96baa820 7993 char *p;
802188a7 7994
2e9f7625 7995 p = rs->buf;
96baa820
JM
7996 *p++ = 'X';
7997 p += hexnumstr (p, (ULONGEST) addr);
7998 *p++ = ',';
7999 p += hexnumstr (p, (ULONGEST) 0);
8000 *p++ = ':';
8001 *p = '\0';
802188a7 8002
2e9f7625 8003 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8004 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 8005
2e9f7625 8006 if (rs->buf[0] == '\0')
96baa820
JM
8007 {
8008 if (remote_debug)
8009 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8010 "binary downloading NOT "
8011 "supported by target\n");
444abaca 8012 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
8013 }
8014 else
8015 {
8016 if (remote_debug)
8017 fprintf_unfiltered (gdb_stdlog,
64b9b334 8018 "binary downloading supported by target\n");
444abaca 8019 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
8020 }
8021 break;
8022 }
c906108c
SS
8023 }
8024}
8025
124e13d9
SM
8026/* Helper function to resize the payload in order to try to get a good
8027 alignment. We try to write an amount of data such that the next write will
8028 start on an address aligned on REMOTE_ALIGN_WRITES. */
8029
8030static int
8031align_for_efficient_write (int todo, CORE_ADDR memaddr)
8032{
8033 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8034}
8035
c906108c
SS
8036/* Write memory data directly to the remote machine.
8037 This does not inform the data cache; the data cache uses this.
a76d924d 8038 HEADER is the starting part of the packet.
c906108c
SS
8039 MEMADDR is the address in the remote memory space.
8040 MYADDR is the address of the buffer in our space.
124e13d9
SM
8041 LEN_UNITS is the number of addressable units to write.
8042 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8043 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8044 should send data as binary ('X'), or hex-encoded ('M').
8045
8046 The function creates packet of the form
8047 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8048
124e13d9 8049 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8050
8051 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8052 are omitted.
8053
9b409511 8054 Return the transferred status, error or OK (an
124e13d9
SM
8055 'enum target_xfer_status' value). Save the number of addressable units
8056 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8057
8058 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8059 exchange between gdb and the stub could look like (?? in place of the
8060 checksum):
8061
8062 -> $m1000,4#??
8063 <- aaaabbbbccccdddd
8064
8065 -> $M1000,3:eeeeffffeeee#??
8066 <- OK
8067
8068 -> $m1000,4#??
8069 <- eeeeffffeeeedddd */
c906108c 8070
9b409511 8071static enum target_xfer_status
a76d924d 8072remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
8073 const gdb_byte *myaddr, ULONGEST len_units,
8074 int unit_size, ULONGEST *xfered_len_units,
8075 char packet_format, int use_length)
c906108c 8076{
6d820c5c 8077 struct remote_state *rs = get_remote_state ();
cfd77fa1 8078 char *p;
a76d924d
DJ
8079 char *plen = NULL;
8080 int plenlen = 0;
124e13d9
SM
8081 int todo_units;
8082 int units_written;
8083 int payload_capacity_bytes;
8084 int payload_length_bytes;
a76d924d
DJ
8085
8086 if (packet_format != 'X' && packet_format != 'M')
8087 internal_error (__FILE__, __LINE__,
9b20d036 8088 _("remote_write_bytes_aux: bad packet format"));
c906108c 8089
124e13d9 8090 if (len_units == 0)
9b409511 8091 return TARGET_XFER_EOF;
b2182ed2 8092
124e13d9 8093 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8094
6d820c5c
DJ
8095 /* The packet buffer will be large enough for the payload;
8096 get_memory_packet_size ensures this. */
a76d924d 8097 rs->buf[0] = '\0';
c906108c 8098
a257b5bb 8099 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8100 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8101
124e13d9 8102 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8103 if (!use_length)
0df8b418 8104 /* The comma won't be used. */
124e13d9
SM
8105 payload_capacity_bytes += 1;
8106 payload_capacity_bytes -= strlen (header);
8107 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8108
a76d924d 8109 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8110
a76d924d
DJ
8111 strcat (rs->buf, header);
8112 p = rs->buf + strlen (header);
8113
8114 /* Compute a best guess of the number of bytes actually transfered. */
8115 if (packet_format == 'X')
c906108c 8116 {
23860348 8117 /* Best guess at number of bytes that will fit. */
325fac50
PA
8118 todo_units = std::min (len_units,
8119 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8120 if (use_length)
124e13d9 8121 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8122 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8123 }
8124 else
8125 {
124e13d9 8126 /* Number of bytes that will fit. */
325fac50
PA
8127 todo_units
8128 = std::min (len_units,
8129 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8130 if (use_length)
124e13d9 8131 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8132 todo_units = std::min (todo_units,
8133 (payload_capacity_bytes / unit_size) / 2);
917317f4 8134 }
a76d924d 8135
124e13d9 8136 if (todo_units <= 0)
3de11b2e 8137 internal_error (__FILE__, __LINE__,
405f8e94 8138 _("minimum packet size too small to write data"));
802188a7 8139
6765f3e5
DJ
8140 /* If we already need another packet, then try to align the end
8141 of this packet to a useful boundary. */
124e13d9
SM
8142 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8143 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8144
a257b5bb 8145 /* Append "<memaddr>". */
917317f4
JM
8146 memaddr = remote_address_masked (memaddr);
8147 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8148
a76d924d
DJ
8149 if (use_length)
8150 {
8151 /* Append ",". */
8152 *p++ = ',';
802188a7 8153
124e13d9
SM
8154 /* Append the length and retain its location and size. It may need to be
8155 adjusted once the packet body has been created. */
a76d924d 8156 plen = p;
124e13d9 8157 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8158 p += plenlen;
8159 }
a257b5bb
AC
8160
8161 /* Append ":". */
917317f4
JM
8162 *p++ = ':';
8163 *p = '\0';
802188a7 8164
a257b5bb 8165 /* Append the packet body. */
a76d924d 8166 if (packet_format == 'X')
917317f4 8167 {
917317f4
JM
8168 /* Binary mode. Send target system values byte by byte, in
8169 increasing byte addresses. Only escape certain critical
8170 characters. */
124e13d9
SM
8171 payload_length_bytes =
8172 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8173 &units_written, payload_capacity_bytes);
6765f3e5 8174
124e13d9 8175 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8176 a second try to keep the end of the packet aligned. Don't do
8177 this if the packet is tiny. */
124e13d9 8178 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8179 {
124e13d9
SM
8180 int new_todo_units;
8181
8182 new_todo_units = align_for_efficient_write (units_written, memaddr);
8183
8184 if (new_todo_units != units_written)
8185 payload_length_bytes =
8186 remote_escape_output (myaddr, new_todo_units, unit_size,
8187 (gdb_byte *) p, &units_written,
8188 payload_capacity_bytes);
6765f3e5
DJ
8189 }
8190
124e13d9
SM
8191 p += payload_length_bytes;
8192 if (use_length && units_written < todo_units)
c906108c 8193 {
802188a7 8194 /* Escape chars have filled up the buffer prematurely,
124e13d9 8195 and we have actually sent fewer units than planned.
917317f4
JM
8196 Fix-up the length field of the packet. Use the same
8197 number of characters as before. */
124e13d9
SM
8198 plen += hexnumnstr (plen, (ULONGEST) units_written,
8199 plenlen);
917317f4 8200 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8201 }
a76d924d
DJ
8202 }
8203 else
8204 {
917317f4
JM
8205 /* Normal mode: Send target system values byte by byte, in
8206 increasing byte addresses. Each byte is encoded as a two hex
8207 value. */
124e13d9
SM
8208 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8209 units_written = todo_units;
c906108c 8210 }
802188a7 8211
2e9f7625 8212 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8213 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8214
2e9f7625 8215 if (rs->buf[0] == 'E')
00d84524 8216 return TARGET_XFER_E_IO;
802188a7 8217
124e13d9
SM
8218 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8219 send fewer units than we'd planned. */
8220 *xfered_len_units = (ULONGEST) units_written;
9b409511 8221 return TARGET_XFER_OK;
c906108c
SS
8222}
8223
a76d924d
DJ
8224/* Write memory data directly to the remote machine.
8225 This does not inform the data cache; the data cache uses this.
8226 MEMADDR is the address in the remote memory space.
8227 MYADDR is the address of the buffer in our space.
8228 LEN is the number of bytes.
8229
9b409511
YQ
8230 Return the transferred status, error or OK (an
8231 'enum target_xfer_status' value). Save the number of bytes
8232 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8233
9b409511
YQ
8234static enum target_xfer_status
8235remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 8236 int unit_size, ULONGEST *xfered_len)
a76d924d 8237{
a121b7c1 8238 const char *packet_format = NULL;
a76d924d
DJ
8239
8240 /* Check whether the target supports binary download. */
8241 check_binary_download (memaddr);
8242
4082afcc 8243 switch (packet_support (PACKET_X))
a76d924d
DJ
8244 {
8245 case PACKET_ENABLE:
8246 packet_format = "X";
8247 break;
8248 case PACKET_DISABLE:
8249 packet_format = "M";
8250 break;
8251 case PACKET_SUPPORT_UNKNOWN:
8252 internal_error (__FILE__, __LINE__,
8253 _("remote_write_bytes: bad internal state"));
8254 default:
8255 internal_error (__FILE__, __LINE__, _("bad switch"));
8256 }
8257
8258 return remote_write_bytes_aux (packet_format,
124e13d9 8259 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8260 packet_format[0], 1);
a76d924d
DJ
8261}
8262
9217e74e
YQ
8263/* Read memory data directly from the remote machine.
8264 This does not use the data cache; the data cache uses this.
8265 MEMADDR is the address in the remote memory space.
8266 MYADDR is the address of the buffer in our space.
124e13d9
SM
8267 LEN_UNITS is the number of addressable memory units to read..
8268 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8269
8270 Return the transferred status, error or OK (an
8271 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8272 transferred in *XFERED_LEN_UNITS.
8273
8274 See the comment of remote_write_bytes_aux for an example of
8275 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
8276
8277static enum target_xfer_status
124e13d9
SM
8278remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8279 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8280{
8281 struct remote_state *rs = get_remote_state ();
124e13d9 8282 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8283 char *p;
124e13d9
SM
8284 int todo_units;
8285 int decoded_bytes;
9217e74e 8286
124e13d9 8287 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8288 /* The packet buffer will be large enough for the payload;
8289 get_memory_packet_size ensures this. */
8290
124e13d9 8291 /* Number of units that will fit. */
325fac50
PA
8292 todo_units = std::min (len_units,
8293 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8294
8295 /* Construct "m"<memaddr>","<len>". */
8296 memaddr = remote_address_masked (memaddr);
8297 p = rs->buf;
8298 *p++ = 'm';
8299 p += hexnumstr (p, (ULONGEST) memaddr);
8300 *p++ = ',';
124e13d9 8301 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8302 *p = '\0';
8303 putpkt (rs->buf);
8304 getpkt (&rs->buf, &rs->buf_size, 0);
8305 if (rs->buf[0] == 'E'
8306 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8307 && rs->buf[3] == '\0')
8308 return TARGET_XFER_E_IO;
8309 /* Reply describes memory byte by byte, each byte encoded as two hex
8310 characters. */
8311 p = rs->buf;
124e13d9 8312 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8313 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8314 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
8315 return TARGET_XFER_OK;
8316}
8317
b55fbac4
YQ
8318/* Using the set of read-only target sections of remote, read live
8319 read-only memory.
8acf9577
YQ
8320
8321 For interface/parameters/return description see target.h,
8322 to_xfer_partial. */
8323
8324static enum target_xfer_status
b55fbac4
YQ
8325remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8326 ULONGEST memaddr, ULONGEST len,
124e13d9 8327 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
8328{
8329 struct target_section *secp;
8330 struct target_section_table *table;
8331
8332 secp = target_section_by_addr (ops, memaddr);
8333 if (secp != NULL
8334 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8335 secp->the_bfd_section)
8336 & SEC_READONLY))
8337 {
8338 struct target_section *p;
8339 ULONGEST memend = memaddr + len;
8340
8341 table = target_get_section_table (ops);
8342
8343 for (p = table->sections; p < table->sections_end; p++)
8344 {
8345 if (memaddr >= p->addr)
8346 {
8347 if (memend <= p->endaddr)
8348 {
8349 /* Entire transfer is within this section. */
124e13d9 8350 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8351 xfered_len);
8acf9577
YQ
8352 }
8353 else if (memaddr >= p->endaddr)
8354 {
8355 /* This section ends before the transfer starts. */
8356 continue;
8357 }
8358 else
8359 {
8360 /* This section overlaps the transfer. Just do half. */
8361 len = p->endaddr - memaddr;
124e13d9 8362 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8363 xfered_len);
8acf9577
YQ
8364 }
8365 }
8366 }
8367 }
8368
8369 return TARGET_XFER_EOF;
8370}
8371
9217e74e
YQ
8372/* Similar to remote_read_bytes_1, but it reads from the remote stub
8373 first if the requested memory is unavailable in traceframe.
8374 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8375
9b409511 8376static enum target_xfer_status
8acf9577 8377remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
8378 gdb_byte *myaddr, ULONGEST len, int unit_size,
8379 ULONGEST *xfered_len)
c906108c 8380{
6b6aa828 8381 if (len == 0)
96c4f946 8382 return TARGET_XFER_EOF;
b2182ed2 8383
8acf9577
YQ
8384 if (get_traceframe_number () != -1)
8385 {
8386 VEC(mem_range_s) *available;
8387
8388 /* If we fail to get the set of available memory, then the
8389 target does not support querying traceframe info, and so we
8390 attempt reading from the traceframe anyway (assuming the
8391 target implements the old QTro packet then). */
8392 if (traceframe_available_memory (&available, memaddr, len))
8393 {
8394 struct cleanup *old_chain;
8395
8396 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
8397
8398 if (VEC_empty (mem_range_s, available)
8399 || VEC_index (mem_range_s, available, 0)->start != memaddr)
8400 {
8401 enum target_xfer_status res;
8402
8403 /* Don't read into the traceframe's available
8404 memory. */
8405 if (!VEC_empty (mem_range_s, available))
8406 {
8407 LONGEST oldlen = len;
8408
8409 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8410 gdb_assert (len <= oldlen);
8411 }
8412
8413 do_cleanups (old_chain);
8414
8415 /* This goes through the topmost target again. */
b55fbac4 8416 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 8417 len, unit_size, xfered_len);
8acf9577
YQ
8418 if (res == TARGET_XFER_OK)
8419 return TARGET_XFER_OK;
8420 else
8421 {
8422 /* No use trying further, we know some memory starting
8423 at MEMADDR isn't available. */
8424 *xfered_len = len;
8425 return TARGET_XFER_UNAVAILABLE;
8426 }
8427 }
8428
8429 /* Don't try to read more than how much is available, in
8430 case the target implements the deprecated QTro packet to
8431 cater for older GDBs (the target's knowledge of read-only
8432 sections may be outdated by now). */
8433 len = VEC_index (mem_range_s, available, 0)->length;
8434
8435 do_cleanups (old_chain);
8436 }
8437 }
8438
124e13d9 8439 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8440}
74531fed 8441
c906108c 8442\f
c906108c 8443
a76d924d
DJ
8444/* Sends a packet with content determined by the printf format string
8445 FORMAT and the remaining arguments, then gets the reply. Returns
8446 whether the packet was a success, a failure, or unknown. */
8447
77b64a49
PA
8448static enum packet_result remote_send_printf (const char *format, ...)
8449 ATTRIBUTE_PRINTF (1, 2);
8450
2c0b251b 8451static enum packet_result
a76d924d
DJ
8452remote_send_printf (const char *format, ...)
8453{
8454 struct remote_state *rs = get_remote_state ();
8455 int max_size = get_remote_packet_size ();
a76d924d 8456 va_list ap;
a744cf53 8457
a76d924d
DJ
8458 va_start (ap, format);
8459
8460 rs->buf[0] = '\0';
8461 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8462 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8463
8464 if (putpkt (rs->buf) < 0)
8465 error (_("Communication problem with target."));
8466
8467 rs->buf[0] = '\0';
8468 getpkt (&rs->buf, &rs->buf_size, 0);
8469
8470 return packet_check_result (rs->buf);
8471}
8472
a76d924d
DJ
8473/* Flash writing can take quite some time. We'll set
8474 effectively infinite timeout for flash operations.
8475 In future, we'll need to decide on a better approach. */
8476static const int remote_flash_timeout = 1000;
8477
8478static void
8479remote_flash_erase (struct target_ops *ops,
8480 ULONGEST address, LONGEST length)
8481{
f5656ead 8482 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d 8483 enum packet_result ret;
2ec845e7
TT
8484 scoped_restore restore_timeout
8485 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
a76d924d
DJ
8486
8487 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8488 phex (address, addr_size),
a76d924d
DJ
8489 phex (length, 4));
8490 switch (ret)
8491 {
8492 case PACKET_UNKNOWN:
8493 error (_("Remote target does not support flash erase"));
8494 case PACKET_ERROR:
8495 error (_("Error erasing flash with vFlashErase packet"));
8496 default:
8497 break;
8498 }
a76d924d
DJ
8499}
8500
9b409511
YQ
8501static enum target_xfer_status
8502remote_flash_write (struct target_ops *ops, ULONGEST address,
8503 ULONGEST length, ULONGEST *xfered_len,
8504 const gdb_byte *data)
a76d924d 8505{
2ec845e7
TT
8506 scoped_restore restore_timeout
8507 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8508 return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8509 xfered_len,'X', 0);
a76d924d
DJ
8510}
8511
8512static void
8513remote_flash_done (struct target_ops *ops)
8514{
a76d924d 8515 int ret;
a76d924d 8516
2ec845e7
TT
8517 scoped_restore restore_timeout
8518 = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8519
a76d924d 8520 ret = remote_send_printf ("vFlashDone");
a76d924d
DJ
8521
8522 switch (ret)
8523 {
8524 case PACKET_UNKNOWN:
8525 error (_("Remote target does not support vFlashDone"));
8526 case PACKET_ERROR:
8527 error (_("Error finishing flash operation"));
8528 default:
8529 break;
8530 }
8531}
8532
c906108c 8533static void
fba45db2 8534remote_files_info (struct target_ops *ignore)
c906108c
SS
8535{
8536 puts_filtered ("Debugging a target over a serial line.\n");
8537}
8538\f
8539/* Stuff for dealing with the packets which are part of this protocol.
8540 See comment at top of file for details. */
8541
1927e618
PA
8542/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8543 error to higher layers. Called when a serial error is detected.
8544 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8545 the system error message for errno at function entry and final dot
8546 for output compatibility with throw_perror_with_name. */
1927e618
PA
8547
8548static void
8549unpush_and_perror (const char *string)
8550{
d6cb50a2 8551 int saved_errno = errno;
1927e618
PA
8552
8553 remote_unpush_target ();
d6cb50a2
JK
8554 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8555 safe_strerror (saved_errno));
1927e618
PA
8556}
8557
048094ac
PA
8558/* Read a single character from the remote end. The current quit
8559 handler is overridden to avoid quitting in the middle of packet
8560 sequence, as that would break communication with the remote server.
8561 See remote_serial_quit_handler for more detail. */
c906108c
SS
8562
8563static int
fba45db2 8564readchar (int timeout)
c906108c
SS
8565{
8566 int ch;
5d93a237 8567 struct remote_state *rs = get_remote_state ();
048094ac 8568
2ec845e7
TT
8569 {
8570 scoped_restore restore_quit
8571 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
c906108c 8572
2ec845e7 8573 rs->got_ctrlc_during_io = 0;
c906108c 8574
2ec845e7 8575 ch = serial_readchar (rs->remote_desc, timeout);
048094ac 8576
2ec845e7
TT
8577 if (rs->got_ctrlc_during_io)
8578 set_quit_flag ();
8579 }
048094ac 8580
2acceee2 8581 if (ch >= 0)
0876f84a 8582 return ch;
2acceee2
JM
8583
8584 switch ((enum serial_rc) ch)
c906108c
SS
8585 {
8586 case SERIAL_EOF:
78a095c3 8587 remote_unpush_target ();
598d3636 8588 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8589 /* no return */
c906108c 8590 case SERIAL_ERROR:
1927e618
PA
8591 unpush_and_perror (_("Remote communication error. "
8592 "Target disconnected."));
2acceee2 8593 /* no return */
c906108c 8594 case SERIAL_TIMEOUT:
2acceee2 8595 break;
c906108c 8596 }
2acceee2 8597 return ch;
c906108c
SS
8598}
8599
c33e31fd 8600/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
8601 writing fails. The current quit handler is overridden to avoid
8602 quitting in the middle of packet sequence, as that would break
8603 communication with the remote server. See
8604 remote_serial_quit_handler for more detail. */
c33e31fd
PA
8605
8606static void
8607remote_serial_write (const char *str, int len)
8608{
5d93a237 8609 struct remote_state *rs = get_remote_state ();
048094ac 8610
2ec845e7
TT
8611 scoped_restore restore_quit
8612 = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
048094ac
PA
8613
8614 rs->got_ctrlc_during_io = 0;
5d93a237
TT
8615
8616 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8617 {
1927e618
PA
8618 unpush_and_perror (_("Remote communication error. "
8619 "Target disconnected."));
c33e31fd 8620 }
048094ac
PA
8621
8622 if (rs->got_ctrlc_during_io)
8623 set_quit_flag ();
c33e31fd
PA
8624}
8625
6d820c5c
DJ
8626/* Send the command in *BUF to the remote machine, and read the reply
8627 into *BUF. Report an error if we get an error reply. Resize
8628 *BUF using xrealloc if necessary to hold the result, and update
8629 *SIZEOF_BUF. */
c906108c
SS
8630
8631static void
6d820c5c
DJ
8632remote_send (char **buf,
8633 long *sizeof_buf)
c906108c 8634{
6d820c5c 8635 putpkt (*buf);
c2d11a7d 8636 getpkt (buf, sizeof_buf, 0);
c906108c 8637
6d820c5c
DJ
8638 if ((*buf)[0] == 'E')
8639 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8640}
8641
b3ced9ba
PA
8642/* Return a string representing an escaped version of BUF, of len N.
8643 E.g. \n is converted to \\n, \t to \\t, etc. */
6e5abd65 8644
b3ced9ba 8645static std::string
6e5abd65
PA
8646escape_buffer (const char *buf, int n)
8647{
d7e74731 8648 string_file stb;
6e5abd65 8649
d7e74731
PA
8650 stb.putstrn (buf, n, '\\');
8651 return std::move (stb.string ());
6e5abd65
PA
8652}
8653
c906108c
SS
8654/* Display a null-terminated packet on stdout, for debugging, using C
8655 string notation. */
8656
8657static void
baa336ce 8658print_packet (const char *buf)
c906108c
SS
8659{
8660 puts_filtered ("\"");
43e526b9 8661 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8662 puts_filtered ("\"");
8663}
8664
8665int
baa336ce 8666putpkt (const char *buf)
c906108c
SS
8667{
8668 return putpkt_binary (buf, strlen (buf));
8669}
8670
8671/* Send a packet to the remote machine, with error checking. The data
23860348 8672 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8673 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8674 and for a possible /0 if we are debugging (remote_debug) and want
8675 to print the sent packet as a string. */
c906108c
SS
8676
8677static int
baa336ce 8678putpkt_binary (const char *buf, int cnt)
c906108c 8679{
2d717e4f 8680 struct remote_state *rs = get_remote_state ();
c906108c
SS
8681 int i;
8682 unsigned char csum = 0;
224c3ddb 8683 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8684 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8685
c906108c
SS
8686 int ch;
8687 int tcount = 0;
8688 char *p;
8689
e24a49d8
PA
8690 /* Catch cases like trying to read memory or listing threads while
8691 we're waiting for a stop reply. The remote server wouldn't be
8692 ready to handle this request, so we'd hang and timeout. We don't
8693 have to worry about this in synchronous mode, because in that
8694 case it's not possible to issue a command while the target is
74531fed
PA
8695 running. This is not a problem in non-stop mode, because in that
8696 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8697 if (!target_is_non_stop_p ()
8698 && target_is_async_p ()
8699 && rs->waiting_for_stop_reply)
9597b22a
DE
8700 {
8701 error (_("Cannot execute this command while the target is running.\n"
8702 "Use the \"interrupt\" command to stop the target\n"
8703 "and then try again."));
8704 }
e24a49d8 8705
2d717e4f
DJ
8706 /* We're sending out a new packet. Make sure we don't look at a
8707 stale cached response. */
8708 rs->cached_wait_status = 0;
8709
c906108c
SS
8710 /* Copy the packet into buffer BUF2, encapsulating it
8711 and giving it a checksum. */
8712
c906108c
SS
8713 p = buf2;
8714 *p++ = '$';
8715
8716 for (i = 0; i < cnt; i++)
8717 {
8718 csum += buf[i];
8719 *p++ = buf[i];
8720 }
8721 *p++ = '#';
8722 *p++ = tohex ((csum >> 4) & 0xf);
8723 *p++ = tohex (csum & 0xf);
8724
8725 /* Send it over and over until we get a positive ack. */
8726
8727 while (1)
8728 {
8729 int started_error_output = 0;
8730
8731 if (remote_debug)
8732 {
8733 *p = '\0';
b3ced9ba 8734
6f8976bf
YQ
8735 int len = (int) (p - buf2);
8736
8737 std::string str
8738 = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8739
8740 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8741
8742 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
8743 {
8744 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
8745 str.length () - REMOTE_DEBUG_MAX_CHAR);
8746 }
8747
8748 fprintf_unfiltered (gdb_stdlog, "...");
b3ced9ba 8749
0f71a2f6 8750 gdb_flush (gdb_stdlog);
c906108c 8751 }
c33e31fd 8752 remote_serial_write (buf2, p - buf2);
c906108c 8753
a6f3e723
SL
8754 /* If this is a no acks version of the remote protocol, send the
8755 packet and move on. */
8756 if (rs->noack_mode)
8757 break;
8758
74531fed
PA
8759 /* Read until either a timeout occurs (-2) or '+' is read.
8760 Handle any notification that arrives in the mean time. */
c906108c
SS
8761 while (1)
8762 {
8763 ch = readchar (remote_timeout);
8764
c5aa993b 8765 if (remote_debug)
c906108c
SS
8766 {
8767 switch (ch)
8768 {
8769 case '+':
1216fa2c 8770 case '-':
c906108c
SS
8771 case SERIAL_TIMEOUT:
8772 case '$':
74531fed 8773 case '%':
c906108c
SS
8774 if (started_error_output)
8775 {
8776 putchar_unfiltered ('\n');
8777 started_error_output = 0;
8778 }
8779 }
8780 }
8781
8782 switch (ch)
8783 {
8784 case '+':
8785 if (remote_debug)
0f71a2f6 8786 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8787 do_cleanups (old_chain);
c906108c 8788 return 1;
1216fa2c
AC
8789 case '-':
8790 if (remote_debug)
8791 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8792 /* FALLTHROUGH */
c906108c 8793 case SERIAL_TIMEOUT:
c5aa993b 8794 tcount++;
c906108c 8795 if (tcount > 3)
a5c0808e
PA
8796 {
8797 do_cleanups (old_chain);
8798 return 0;
8799 }
23860348 8800 break; /* Retransmit buffer. */
c906108c
SS
8801 case '$':
8802 {
40e3f985 8803 if (remote_debug)
2bc416ba 8804 fprintf_unfiltered (gdb_stdlog,
23860348 8805 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8806 /* It's probably an old response sent because an ACK
8807 was lost. Gobble up the packet and ack it so it
8808 doesn't get retransmitted when we resend this
8809 packet. */
6d820c5c 8810 skip_frame ();
c33e31fd 8811 remote_serial_write ("+", 1);
23860348 8812 continue; /* Now, go look for +. */
c906108c 8813 }
74531fed
PA
8814
8815 case '%':
8816 {
8817 int val;
8818
8819 /* If we got a notification, handle it, and go back to looking
8820 for an ack. */
8821 /* We've found the start of a notification. Now
8822 collect the data. */
8823 val = read_frame (&rs->buf, &rs->buf_size);
8824 if (val >= 0)
8825 {
8826 if (remote_debug)
8827 {
b3ced9ba 8828 std::string str = escape_buffer (rs->buf, val);
6e5abd65 8829
6e5abd65
PA
8830 fprintf_unfiltered (gdb_stdlog,
8831 " Notification received: %s\n",
b3ced9ba 8832 str.c_str ());
74531fed 8833 }
5965e028 8834 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8835 /* We're in sync now, rewait for the ack. */
8836 tcount = 0;
8837 }
8838 else
8839 {
8840 if (remote_debug)
8841 {
8842 if (!started_error_output)
8843 {
8844 started_error_output = 1;
8845 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8846 }
8847 fputc_unfiltered (ch & 0177, gdb_stdlog);
8848 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8849 }
8850 }
8851 continue;
8852 }
8853 /* fall-through */
c906108c
SS
8854 default:
8855 if (remote_debug)
8856 {
8857 if (!started_error_output)
8858 {
8859 started_error_output = 1;
0f71a2f6 8860 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8861 }
0f71a2f6 8862 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8863 }
8864 continue;
8865 }
23860348 8866 break; /* Here to retransmit. */
c906108c
SS
8867 }
8868
8869#if 0
8870 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8871 able to get out next time we call QUIT, without anything as
8872 violent as interrupt_query. If we want to provide a way out of
8873 here without getting to the next QUIT, it should be based on
8874 hitting ^C twice as in remote_wait. */
c906108c
SS
8875 if (quit_flag)
8876 {
8877 quit_flag = 0;
8878 interrupt_query ();
8879 }
8880#endif
8881 }
a5c0808e
PA
8882
8883 do_cleanups (old_chain);
a6f3e723 8884 return 0;
c906108c
SS
8885}
8886
6d820c5c
DJ
8887/* Come here after finding the start of a frame when we expected an
8888 ack. Do our best to discard the rest of this packet. */
8889
8890static void
8891skip_frame (void)
8892{
8893 int c;
8894
8895 while (1)
8896 {
8897 c = readchar (remote_timeout);
8898 switch (c)
8899 {
8900 case SERIAL_TIMEOUT:
8901 /* Nothing we can do. */
8902 return;
8903 case '#':
8904 /* Discard the two bytes of checksum and stop. */
8905 c = readchar (remote_timeout);
8906 if (c >= 0)
8907 c = readchar (remote_timeout);
8908
8909 return;
8910 case '*': /* Run length encoding. */
8911 /* Discard the repeat count. */
8912 c = readchar (remote_timeout);
8913 if (c < 0)
8914 return;
8915 break;
8916 default:
8917 /* A regular character. */
8918 break;
8919 }
8920 }
8921}
8922
c906108c 8923/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8924 into *BUF, verifying the checksum, length, and handling run-length
8925 compression. NUL terminate the buffer. If there is not enough room,
8926 expand *BUF using xrealloc.
c906108c 8927
c2d11a7d
JM
8928 Returns -1 on error, number of characters in buffer (ignoring the
8929 trailing NULL) on success. (could be extended to return one of the
23860348 8930 SERIAL status indications). */
c2d11a7d
JM
8931
8932static long
6d820c5c
DJ
8933read_frame (char **buf_p,
8934 long *sizeof_buf)
c906108c
SS
8935{
8936 unsigned char csum;
c2d11a7d 8937 long bc;
c906108c 8938 int c;
6d820c5c 8939 char *buf = *buf_p;
a6f3e723 8940 struct remote_state *rs = get_remote_state ();
c906108c
SS
8941
8942 csum = 0;
c2d11a7d 8943 bc = 0;
c906108c
SS
8944
8945 while (1)
8946 {
8947 c = readchar (remote_timeout);
c906108c
SS
8948 switch (c)
8949 {
8950 case SERIAL_TIMEOUT:
8951 if (remote_debug)
0f71a2f6 8952 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8953 return -1;
c906108c
SS
8954 case '$':
8955 if (remote_debug)
0f71a2f6
JM
8956 fputs_filtered ("Saw new packet start in middle of old one\n",
8957 gdb_stdlog);
23860348 8958 return -1; /* Start a new packet, count retries. */
c906108c
SS
8959 case '#':
8960 {
8961 unsigned char pktcsum;
e1b09194
AC
8962 int check_0 = 0;
8963 int check_1 = 0;
c906108c 8964
c2d11a7d 8965 buf[bc] = '\0';
c906108c 8966
e1b09194
AC
8967 check_0 = readchar (remote_timeout);
8968 if (check_0 >= 0)
8969 check_1 = readchar (remote_timeout);
802188a7 8970
e1b09194
AC
8971 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8972 {
8973 if (remote_debug)
2bc416ba 8974 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8975 gdb_stdlog);
e1b09194
AC
8976 return -1;
8977 }
8978 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8979 {
8980 if (remote_debug)
2bc416ba 8981 fputs_filtered ("Communication error in checksum\n",
23860348 8982 gdb_stdlog);
40e3f985
FN
8983 return -1;
8984 }
c906108c 8985
a6f3e723
SL
8986 /* Don't recompute the checksum; with no ack packets we
8987 don't have any way to indicate a packet retransmission
8988 is necessary. */
8989 if (rs->noack_mode)
8990 return bc;
8991
e1b09194 8992 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8993 if (csum == pktcsum)
c2d11a7d 8994 return bc;
c906108c 8995
c5aa993b 8996 if (remote_debug)
c906108c 8997 {
b3ced9ba 8998 std::string str = escape_buffer (buf, bc);
6e5abd65 8999
6e5abd65 9000 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9001 "Bad checksum, sentsum=0x%x, "
9002 "csum=0x%x, buf=%s\n",
b3ced9ba 9003 pktcsum, csum, str.c_str ());
c906108c 9004 }
c2d11a7d 9005 /* Number of characters in buffer ignoring trailing
23860348 9006 NULL. */
c2d11a7d 9007 return -1;
c906108c 9008 }
23860348 9009 case '*': /* Run length encoding. */
c2c6d25f
JM
9010 {
9011 int repeat;
c906108c 9012
a744cf53 9013 csum += c;
b4501125
AC
9014 c = readchar (remote_timeout);
9015 csum += c;
23860348 9016 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9017
23860348 9018 /* The character before ``*'' is repeated. */
c2d11a7d 9019
6d820c5c 9020 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9021 {
6d820c5c
DJ
9022 if (bc + repeat - 1 >= *sizeof_buf - 1)
9023 {
9024 /* Make some more room in the buffer. */
9025 *sizeof_buf += repeat;
224c3ddb 9026 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
9027 buf = *buf_p;
9028 }
9029
c2d11a7d
JM
9030 memset (&buf[bc], buf[bc - 1], repeat);
9031 bc += repeat;
c2c6d25f
JM
9032 continue;
9033 }
9034
c2d11a7d 9035 buf[bc] = '\0';
6d820c5c 9036 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9037 return -1;
c2c6d25f 9038 }
c906108c 9039 default:
6d820c5c 9040 if (bc >= *sizeof_buf - 1)
c906108c 9041 {
6d820c5c
DJ
9042 /* Make some more room in the buffer. */
9043 *sizeof_buf *= 2;
224c3ddb 9044 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 9045 buf = *buf_p;
c906108c
SS
9046 }
9047
6d820c5c
DJ
9048 buf[bc++] = c;
9049 csum += c;
9050 continue;
c906108c
SS
9051 }
9052 }
9053}
9054
9055/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9056 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9057 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9058 rather than timing out; this is used (in synchronous mode) to wait
9059 for a target that is is executing user code to stop. */
d9fcf2fb
JM
9060/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9061 don't have to change all the calls to getpkt to deal with the
9062 return value, because at the moment I don't know what the right
23860348 9063 thing to do it for those. */
c906108c 9064void
6d820c5c
DJ
9065getpkt (char **buf,
9066 long *sizeof_buf,
c2d11a7d 9067 int forever)
d9fcf2fb 9068{
54887903 9069 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
9070}
9071
9072
9073/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9074 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9075 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9076 rather than timing out; this is used (in synchronous mode) to wait
9077 for a target that is is executing user code to stop. If FOREVER ==
9078 0, this function is allowed to time out gracefully and return an
74531fed
PA
9079 indication of this to the caller. Otherwise return the number of
9080 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
9081 enough reason to return to the caller. *IS_NOTIF is an output
9082 boolean that indicates whether *BUF holds a notification or not
9083 (a regular packet). */
74531fed 9084
3172dc30 9085static int
74531fed 9086getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 9087 int expecting_notif, int *is_notif)
c906108c 9088{
2d717e4f 9089 struct remote_state *rs = get_remote_state ();
c906108c
SS
9090 int c;
9091 int tries;
9092 int timeout;
df4b58fe 9093 int val = -1;
c906108c 9094
2d717e4f
DJ
9095 /* We're reading a new response. Make sure we don't look at a
9096 previously cached response. */
9097 rs->cached_wait_status = 0;
9098
6d820c5c 9099 strcpy (*buf, "timeout");
c906108c
SS
9100
9101 if (forever)
74531fed
PA
9102 timeout = watchdog > 0 ? watchdog : -1;
9103 else if (expecting_notif)
9104 timeout = 0; /* There should already be a char in the buffer. If
9105 not, bail out. */
c906108c
SS
9106 else
9107 timeout = remote_timeout;
9108
9109#define MAX_TRIES 3
9110
74531fed
PA
9111 /* Process any number of notifications, and then return when
9112 we get a packet. */
9113 for (;;)
c906108c 9114 {
d9c43928 9115 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9116 times. */
9117 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9118 {
74531fed
PA
9119 /* This can loop forever if the remote side sends us
9120 characters continuously, but if it pauses, we'll get
9121 SERIAL_TIMEOUT from readchar because of timeout. Then
9122 we'll count that as a retry.
9123
9124 Note that even when forever is set, we will only wait
9125 forever prior to the start of a packet. After that, we
9126 expect characters to arrive at a brisk pace. They should
9127 show up within remote_timeout intervals. */
9128 do
9129 c = readchar (timeout);
9130 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9131
9132 if (c == SERIAL_TIMEOUT)
9133 {
74531fed
PA
9134 if (expecting_notif)
9135 return -1; /* Don't complain, it's normal to not get
9136 anything in this case. */
9137
23860348 9138 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9139 {
78a095c3 9140 remote_unpush_target ();
598d3636
JK
9141 throw_error (TARGET_CLOSE_ERROR,
9142 _("Watchdog timeout has expired. "
9143 "Target detached."));
c906108c 9144 }
c906108c 9145 if (remote_debug)
0f71a2f6 9146 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9147 }
74531fed
PA
9148 else
9149 {
9150 /* We've found the start of a packet or notification.
9151 Now collect the data. */
9152 val = read_frame (buf, sizeof_buf);
9153 if (val >= 0)
9154 break;
9155 }
9156
c33e31fd 9157 remote_serial_write ("-", 1);
c906108c 9158 }
c906108c 9159
74531fed
PA
9160 if (tries > MAX_TRIES)
9161 {
9162 /* We have tried hard enough, and just can't receive the
9163 packet/notification. Give up. */
9164 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9165
74531fed
PA
9166 /* Skip the ack char if we're in no-ack mode. */
9167 if (!rs->noack_mode)
c33e31fd 9168 remote_serial_write ("+", 1);
74531fed
PA
9169 return -1;
9170 }
c906108c 9171
74531fed
PA
9172 /* If we got an ordinary packet, return that to our caller. */
9173 if (c == '$')
c906108c
SS
9174 {
9175 if (remote_debug)
43e526b9 9176 {
6f8976bf
YQ
9177 std::string str
9178 = escape_buffer (*buf,
9179 std::min (val, REMOTE_DEBUG_MAX_CHAR));
9180
9181 fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9182 str.c_str ());
9183
9184 if (str.length () > REMOTE_DEBUG_MAX_CHAR)
9185 {
9186 fprintf_unfiltered (gdb_stdlog, "[%zu bytes omitted]",
9187 str.length () - REMOTE_DEBUG_MAX_CHAR);
9188 }
6e5abd65 9189
6f8976bf 9190 fprintf_unfiltered (gdb_stdlog, "\n");
43e526b9 9191 }
a6f3e723
SL
9192
9193 /* Skip the ack char if we're in no-ack mode. */
9194 if (!rs->noack_mode)
c33e31fd 9195 remote_serial_write ("+", 1);
fee9eda9
YQ
9196 if (is_notif != NULL)
9197 *is_notif = 0;
0876f84a 9198 return val;
c906108c
SS
9199 }
9200
74531fed
PA
9201 /* If we got a notification, handle it, and go back to looking
9202 for a packet. */
9203 else
9204 {
9205 gdb_assert (c == '%');
9206
9207 if (remote_debug)
9208 {
b3ced9ba 9209 std::string str = escape_buffer (*buf, val);
6e5abd65 9210
6e5abd65
PA
9211 fprintf_unfiltered (gdb_stdlog,
9212 " Notification received: %s\n",
b3ced9ba 9213 str.c_str ());
74531fed 9214 }
fee9eda9
YQ
9215 if (is_notif != NULL)
9216 *is_notif = 1;
c906108c 9217
5965e028 9218 handle_notification (rs->notif_state, *buf);
c906108c 9219
74531fed 9220 /* Notifications require no acknowledgement. */
a6f3e723 9221
74531fed 9222 if (expecting_notif)
fee9eda9 9223 return val;
74531fed
PA
9224 }
9225 }
9226}
9227
9228static int
9229getpkt_sane (char **buf, long *sizeof_buf, int forever)
9230{
fee9eda9 9231 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
9232}
9233
9234static int
fee9eda9
YQ
9235getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9236 int *is_notif)
74531fed 9237{
fee9eda9
YQ
9238 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9239 is_notif);
c906108c 9240}
74531fed 9241
cbb8991c
DB
9242/* Check whether EVENT is a fork event for the process specified
9243 by the pid passed in DATA, and if it is, kill the fork child. */
9244
9245static int
9246kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9247 QUEUE_ITER (stop_reply_p) *iter,
9248 stop_reply_p event,
9249 void *data)
9250{
19ba03f4 9251 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
9252 int parent_pid = *(int *) param->input;
9253
9254 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9255 {
9256 struct remote_state *rs = get_remote_state ();
9257 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9258 int res;
9259
9260 res = remote_vkill (child_pid, rs);
9261 if (res != 0)
9262 error (_("Can't kill fork child process %d"), child_pid);
9263 }
9264
9265 return 1;
9266}
9267
9268/* Kill any new fork children of process PID that haven't been
9269 processed by follow_fork. */
9270
9271static void
9272kill_new_fork_children (int pid, struct remote_state *rs)
9273{
9274 struct thread_info *thread;
9275 struct notif_client *notif = &notif_client_stop;
9276 struct queue_iter_param param;
9277
9278 /* Kill the fork child threads of any threads in process PID
9279 that are stopped at a fork event. */
9280 ALL_NON_EXITED_THREADS (thread)
9281 {
9282 struct target_waitstatus *ws = &thread->pending_follow;
9283
9284 if (is_pending_fork_parent (ws, pid, thread->ptid))
9285 {
9286 struct remote_state *rs = get_remote_state ();
9287 int child_pid = ptid_get_pid (ws->value.related_pid);
9288 int res;
9289
9290 res = remote_vkill (child_pid, rs);
9291 if (res != 0)
9292 error (_("Can't kill fork child process %d"), child_pid);
9293 }
9294 }
9295
9296 /* Check for any pending fork events (not reported or processed yet)
9297 in process PID and kill those fork child threads as well. */
9298 remote_notif_get_pending_events (notif);
9299 param.input = &pid;
9300 param.output = NULL;
9301 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9302 kill_child_of_pending_fork, &param);
9303}
9304
c906108c 9305\f
8020350c
DB
9306/* Target hook to kill the current inferior. */
9307
c906108c 9308static void
7d85a9c0 9309remote_kill (struct target_ops *ops)
43ff13b4 9310{
8020350c
DB
9311 int res = -1;
9312 int pid = ptid_get_pid (inferior_ptid);
9313 struct remote_state *rs = get_remote_state ();
0fdf84ca 9314
8020350c 9315 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9316 {
8020350c
DB
9317 /* If we're stopped while forking and we haven't followed yet,
9318 kill the child task. We need to do this before killing the
9319 parent task because if this is a vfork then the parent will
9320 be sleeping. */
9321 kill_new_fork_children (pid, rs);
9322
9323 res = remote_vkill (pid, rs);
9324 if (res == 0)
0fdf84ca 9325 {
bc1e6c81 9326 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9327 return;
9328 }
8020350c 9329 }
0fdf84ca 9330
8020350c
DB
9331 /* If we are in 'target remote' mode and we are killing the only
9332 inferior, then we will tell gdbserver to exit and unpush the
9333 target. */
9334 if (res == -1 && !remote_multi_process_p (rs)
9335 && number_of_live_inferiors () == 1)
9336 {
9337 remote_kill_k ();
9338
9339 /* We've killed the remote end, we get to mourn it. If we are
9340 not in extended mode, mourning the inferior also unpushes
9341 remote_ops from the target stack, which closes the remote
9342 connection. */
bc1e6c81 9343 target_mourn_inferior (inferior_ptid);
8020350c
DB
9344
9345 return;
0fdf84ca 9346 }
43ff13b4 9347
8020350c 9348 error (_("Can't kill process"));
43ff13b4
JM
9349}
9350
8020350c
DB
9351/* Send a kill request to the target using the 'vKill' packet. */
9352
82f73884
PA
9353static int
9354remote_vkill (int pid, struct remote_state *rs)
9355{
4082afcc 9356 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9357 return -1;
9358
9359 /* Tell the remote target to detach. */
bba74b36 9360 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
9361 putpkt (rs->buf);
9362 getpkt (&rs->buf, &rs->buf_size, 0);
9363
4082afcc
PA
9364 switch (packet_ok (rs->buf,
9365 &remote_protocol_packets[PACKET_vKill]))
9366 {
9367 case PACKET_OK:
9368 return 0;
9369 case PACKET_ERROR:
9370 return 1;
9371 case PACKET_UNKNOWN:
9372 return -1;
9373 default:
9374 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9375 }
82f73884
PA
9376}
9377
8020350c
DB
9378/* Send a kill request to the target using the 'k' packet. */
9379
82f73884 9380static void
8020350c 9381remote_kill_k (void)
82f73884 9382{
8020350c
DB
9383 /* Catch errors so the user can quit from gdb even when we
9384 aren't on speaking terms with the remote system. */
9385 TRY
82f73884 9386 {
82f73884 9387 putpkt ("k");
82f73884 9388 }
8020350c
DB
9389 CATCH (ex, RETURN_MASK_ERROR)
9390 {
9391 if (ex.error == TARGET_CLOSE_ERROR)
9392 {
9393 /* If we got an (EOF) error that caused the target
9394 to go away, then we're done, that's what we wanted.
9395 "k" is susceptible to cause a premature EOF, given
9396 that the remote server isn't actually required to
9397 reply to "k", and it can happen that it doesn't
9398 even get to reply ACK to the "k". */
9399 return;
9400 }
82f73884 9401
8020350c
DB
9402 /* Otherwise, something went wrong. We didn't actually kill
9403 the target. Just propagate the exception, and let the
9404 user or higher layers decide what to do. */
9405 throw_exception (ex);
9406 }
9407 END_CATCH
82f73884
PA
9408}
9409
c906108c 9410static void
20f796c9 9411remote_mourn (struct target_ops *target)
c906108c 9412{
8020350c 9413 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9414
8020350c
DB
9415 /* In 'target remote' mode with one inferior, we close the connection. */
9416 if (!rs->extended && number_of_live_inferiors () <= 1)
9417 {
9418 unpush_target (target);
c906108c 9419
8020350c
DB
9420 /* remote_close takes care of doing most of the clean up. */
9421 generic_mourn_inferior ();
9422 return;
9423 }
c906108c 9424
e24a49d8
PA
9425 /* In case we got here due to an error, but we're going to stay
9426 connected. */
9427 rs->waiting_for_stop_reply = 0;
9428
dc1981d7
PA
9429 /* If the current general thread belonged to the process we just
9430 detached from or has exited, the remote side current general
9431 thread becomes undefined. Considering a case like this:
9432
9433 - We just got here due to a detach.
9434 - The process that we're detaching from happens to immediately
9435 report a global breakpoint being hit in non-stop mode, in the
9436 same thread we had selected before.
9437 - GDB attaches to this process again.
9438 - This event happens to be the next event we handle.
9439
9440 GDB would consider that the current general thread didn't need to
9441 be set on the stub side (with Hg), since for all it knew,
9442 GENERAL_THREAD hadn't changed.
9443
9444 Notice that although in all-stop mode, the remote server always
9445 sets the current thread to the thread reporting the stop event,
9446 that doesn't happen in non-stop mode; in non-stop, the stub *must
9447 not* change the current thread when reporting a breakpoint hit,
9448 due to the decoupling of event reporting and event handling.
9449
9450 To keep things simple, we always invalidate our notion of the
9451 current thread. */
47f8a51d 9452 record_currthread (rs, minus_one_ptid);
dc1981d7 9453
8020350c 9454 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9455 generic_mourn_inferior ();
9456
d729566a 9457 if (!have_inferiors ())
2d717e4f 9458 {
82f73884
PA
9459 if (!remote_multi_process_p (rs))
9460 {
9461 /* Check whether the target is running now - some remote stubs
9462 automatically restart after kill. */
9463 putpkt ("?");
9464 getpkt (&rs->buf, &rs->buf_size, 0);
9465
9466 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9467 {
3e43a32a
MS
9468 /* Assume that the target has been restarted. Set
9469 inferior_ptid so that bits of core GDB realizes
9470 there's something here, e.g., so that the user can
9471 say "kill" again. */
82f73884
PA
9472 inferior_ptid = magic_null_ptid;
9473 }
82f73884 9474 }
2d717e4f
DJ
9475 }
9476}
c906108c 9477
03583c20 9478static int
2bfc0540 9479extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 9480{
4082afcc 9481 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9482}
9483
9484static void
9485extended_remote_disable_randomization (int val)
9486{
9487 struct remote_state *rs = get_remote_state ();
9488 char *reply;
9489
bba74b36
YQ
9490 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9491 val);
03583c20
UW
9492 putpkt (rs->buf);
9493 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9494 if (*reply == '\0')
9495 error (_("Target does not support QDisableRandomization."));
9496 if (strcmp (reply, "OK") != 0)
9497 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9498}
9499
2d717e4f 9500static int
7c5ded6a 9501extended_remote_run (const std::string &args)
2d717e4f
DJ
9502{
9503 struct remote_state *rs = get_remote_state ();
2d717e4f 9504 int len;
94585166 9505 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9506
2d717e4f
DJ
9507 /* If the user has disabled vRun support, or we have detected that
9508 support is not available, do not try it. */
4082afcc 9509 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9510 return -1;
424163ea 9511
2d717e4f
DJ
9512 strcpy (rs->buf, "vRun;");
9513 len = strlen (rs->buf);
c906108c 9514
2d717e4f
DJ
9515 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9516 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9517 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9518 strlen (remote_exec_file));
2d717e4f 9519
7c5ded6a 9520 if (!args.empty ())
2d717e4f 9521 {
2d717e4f 9522 int i;
2d717e4f 9523
773a1edc 9524 gdb_argv argv (args.c_str ());
2d717e4f
DJ
9525 for (i = 0; argv[i] != NULL; i++)
9526 {
9527 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9528 error (_("Argument list too long for run packet"));
9529 rs->buf[len++] = ';';
9f1b45b0
TT
9530 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9531 strlen (argv[i]));
2d717e4f 9532 }
2d717e4f
DJ
9533 }
9534
9535 rs->buf[len++] = '\0';
9536
9537 putpkt (rs->buf);
9538 getpkt (&rs->buf, &rs->buf_size, 0);
9539
4082afcc 9540 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9541 {
4082afcc 9542 case PACKET_OK:
3405876a 9543 /* We have a wait response. All is well. */
2d717e4f 9544 return 0;
4082afcc
PA
9545 case PACKET_UNKNOWN:
9546 return -1;
9547 case PACKET_ERROR:
2d717e4f
DJ
9548 if (remote_exec_file[0] == '\0')
9549 error (_("Running the default executable on the remote target failed; "
9550 "try \"set remote exec-file\"?"));
9551 else
9552 error (_("Running \"%s\" on the remote target failed"),
9553 remote_exec_file);
4082afcc
PA
9554 default:
9555 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9556 }
c906108c
SS
9557}
9558
2d717e4f
DJ
9559/* In the extended protocol we want to be able to do things like
9560 "run" and have them basically work as expected. So we need
9561 a special create_inferior function. We support changing the
9562 executable file and the command line arguments, but not the
9563 environment. */
9564
43ff13b4 9565static void
77a19445 9566extended_remote_create_inferior (struct target_ops *ops,
7c5ded6a
SDJ
9567 const char *exec_file,
9568 const std::string &args,
77a19445 9569 char **env, int from_tty)
43ff13b4 9570{
3405876a
PA
9571 int run_worked;
9572 char *stop_reply;
9573 struct remote_state *rs = get_remote_state ();
94585166 9574 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9575
43ff13b4 9576 /* If running asynchronously, register the target file descriptor
23860348 9577 with the event loop. */
75c99385 9578 if (target_can_async_p ())
6a3753b3 9579 target_async (1);
43ff13b4 9580
03583c20 9581 /* Disable address space randomization if requested (and supported). */
2bfc0540 9582 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9583 extended_remote_disable_randomization (disable_randomization);
9584
aefd8b33
SDJ
9585 /* If startup-with-shell is on, we inform gdbserver to start the
9586 remote inferior using a shell. */
9587 if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9588 {
9589 xsnprintf (rs->buf, get_remote_packet_size (),
9590 "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9591 putpkt (rs->buf);
9592 getpkt (&rs->buf, &rs->buf_size, 0);
9593 if (strcmp (rs->buf, "OK") != 0)
9594 error (_("\
9595Remote replied unexpectedly while setting startup-with-shell: %s"),
9596 rs->buf);
9597 }
9598
43ff13b4 9599 /* Now restart the remote server. */
3405876a
PA
9600 run_worked = extended_remote_run (args) != -1;
9601 if (!run_worked)
2d717e4f
DJ
9602 {
9603 /* vRun was not supported. Fail if we need it to do what the
9604 user requested. */
9605 if (remote_exec_file[0])
9606 error (_("Remote target does not support \"set remote exec-file\""));
7c5ded6a 9607 if (!args.empty ())
2d717e4f 9608 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9609
2d717e4f
DJ
9610 /* Fall back to "R". */
9611 extended_remote_restart ();
9612 }
424163ea 9613
6c95b8df
PA
9614 if (!have_inferiors ())
9615 {
9616 /* Clean up from the last time we ran, before we mark the target
9617 running again. This will mark breakpoints uninserted, and
9618 get_offsets may insert breakpoints. */
9619 init_thread_list ();
9620 init_wait_for_inferior ();
9621 }
45280a52 9622
3405876a
PA
9623 /* vRun's success return is a stop reply. */
9624 stop_reply = run_worked ? rs->buf : NULL;
9625 add_current_inferior_and_thread (stop_reply);
c0a2216e 9626
2d717e4f
DJ
9627 /* Get updated offsets, if the stub uses qOffsets. */
9628 get_offsets ();
2d717e4f 9629}
c906108c 9630\f
c5aa993b 9631
b775012e
LM
9632/* Given a location's target info BP_TGT and the packet buffer BUF, output
9633 the list of conditions (in agent expression bytecode format), if any, the
9634 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9635 started from BUF and ended at BUF_END. */
b775012e
LM
9636
9637static int
9638remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9639 struct bp_target_info *bp_tgt, char *buf,
9640 char *buf_end)
b775012e 9641{
3cde5c42 9642 if (bp_tgt->conditions.empty ())
b775012e
LM
9643 return 0;
9644
9645 buf += strlen (buf);
bba74b36 9646 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9647 buf++;
9648
83621223 9649 /* Send conditions to the target. */
d538e36d 9650 for (agent_expr *aexpr : bp_tgt->conditions)
b775012e 9651 {
bba74b36 9652 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e 9653 buf += strlen (buf);
3cde5c42 9654 for (int i = 0; i < aexpr->len; ++i)
b775012e
LM
9655 buf = pack_hex_byte (buf, aexpr->buf[i]);
9656 *buf = '\0';
9657 }
b775012e
LM
9658 return 0;
9659}
9660
d3ce09f5
SS
9661static void
9662remote_add_target_side_commands (struct gdbarch *gdbarch,
9663 struct bp_target_info *bp_tgt, char *buf)
9664{
3cde5c42 9665 if (bp_tgt->tcommands.empty ())
d3ce09f5
SS
9666 return;
9667
9668 buf += strlen (buf);
9669
9670 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9671 buf += strlen (buf);
9672
9673 /* Concatenate all the agent expressions that are commands into the
9674 cmds parameter. */
df97be55 9675 for (agent_expr *aexpr : bp_tgt->tcommands)
d3ce09f5
SS
9676 {
9677 sprintf (buf, "X%x,", aexpr->len);
9678 buf += strlen (buf);
3cde5c42 9679 for (int i = 0; i < aexpr->len; ++i)
d3ce09f5
SS
9680 buf = pack_hex_byte (buf, aexpr->buf[i]);
9681 *buf = '\0';
9682 }
d3ce09f5
SS
9683}
9684
8181d85f
DJ
9685/* Insert a breakpoint. On targets that have software breakpoint
9686 support, we ask the remote target to do the work; on targets
9687 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9688
9689static int
3db08215
MM
9690remote_insert_breakpoint (struct target_ops *ops,
9691 struct gdbarch *gdbarch,
a6d9a66e 9692 struct bp_target_info *bp_tgt)
c906108c 9693{
d471ea57
AC
9694 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9695 If it succeeds, then set the support to PACKET_ENABLE. If it
9696 fails, and the user has explicitly requested the Z support then
23860348 9697 report an error, otherwise, mark it disabled and go on. */
802188a7 9698
4082afcc 9699 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9700 {
0d5ed153 9701 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9702 struct remote_state *rs;
bba74b36 9703 char *p, *endbuf;
7c0f6dcc 9704 int bpsize;
4fff2411 9705
28439a30
PA
9706 /* Make sure the remote is pointing at the right process, if
9707 necessary. */
9708 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9709 set_general_process ();
9710
4fff2411
JZ
9711 rs = get_remote_state ();
9712 p = rs->buf;
bba74b36 9713 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9714
96baa820
JM
9715 *(p++) = 'Z';
9716 *(p++) = '0';
9717 *(p++) = ',';
7c0f6dcc 9718 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9719 p += hexnumstr (p, addr);
579c6ad9 9720 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 9721
efcc2da7 9722 if (remote_supports_cond_breakpoints (ops))
bba74b36 9723 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9724
78eff0ec 9725 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9726 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9727
6d820c5c
DJ
9728 putpkt (rs->buf);
9729 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9730
6d820c5c 9731 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9732 {
d471ea57
AC
9733 case PACKET_ERROR:
9734 return -1;
9735 case PACKET_OK:
9736 return 0;
9737 case PACKET_UNKNOWN:
9738 break;
96baa820
JM
9739 }
9740 }
c906108c 9741
0000e5cc
PA
9742 /* If this breakpoint has target-side commands but this stub doesn't
9743 support Z0 packets, throw error. */
3cde5c42 9744 if (!bp_tgt->tcommands.empty ())
0000e5cc
PA
9745 throw_error (NOT_SUPPORTED_ERROR, _("\
9746Target doesn't support breakpoints that have target side commands."));
9747
3db08215 9748 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9749}
9750
9751static int
3db08215
MM
9752remote_remove_breakpoint (struct target_ops *ops,
9753 struct gdbarch *gdbarch,
73971819
PA
9754 struct bp_target_info *bp_tgt,
9755 enum remove_bp_reason reason)
c906108c 9756{
8181d85f 9757 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9758 struct remote_state *rs = get_remote_state ();
96baa820 9759
4082afcc 9760 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9761 {
6d820c5c 9762 char *p = rs->buf;
bba74b36 9763 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9764
28439a30
PA
9765 /* Make sure the remote is pointing at the right process, if
9766 necessary. */
9767 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9768 set_general_process ();
9769
96baa820
JM
9770 *(p++) = 'z';
9771 *(p++) = '0';
9772 *(p++) = ',';
9773
8181d85f
DJ
9774 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9775 p += hexnumstr (p, addr);
579c6ad9 9776 xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
802188a7 9777
6d820c5c
DJ
9778 putpkt (rs->buf);
9779 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9780
6d820c5c 9781 return (rs->buf[0] == 'E');
96baa820
JM
9782 }
9783
73971819 9784 return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
c906108c
SS
9785}
9786
f486487f 9787static enum Z_packet_type
d471ea57
AC
9788watchpoint_to_Z_packet (int type)
9789{
9790 switch (type)
9791 {
9792 case hw_write:
bb858e6a 9793 return Z_PACKET_WRITE_WP;
d471ea57
AC
9794 break;
9795 case hw_read:
bb858e6a 9796 return Z_PACKET_READ_WP;
d471ea57
AC
9797 break;
9798 case hw_access:
bb858e6a 9799 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9800 break;
9801 default:
8e65ff28 9802 internal_error (__FILE__, __LINE__,
e2e0b3e5 9803 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9804 }
9805}
9806
3c3bea1c 9807static int
f486487f
SM
9808remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9809 enum target_hw_bp_type type, struct expression *cond)
96baa820 9810{
d01949b6 9811 struct remote_state *rs = get_remote_state ();
bba74b36 9812 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9813 char *p;
d471ea57 9814 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9815
4082afcc 9816 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9817 return 1;
802188a7 9818
28439a30
PA
9819 /* Make sure the remote is pointing at the right process, if
9820 necessary. */
9821 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9822 set_general_process ();
9823
bba74b36 9824 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9825 p = strchr (rs->buf, '\0');
96baa820
JM
9826 addr = remote_address_masked (addr);
9827 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9828 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9829
6d820c5c
DJ
9830 putpkt (rs->buf);
9831 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9832
6d820c5c 9833 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9834 {
9835 case PACKET_ERROR:
d471ea57 9836 return -1;
85d721b8
PA
9837 case PACKET_UNKNOWN:
9838 return 1;
d471ea57
AC
9839 case PACKET_OK:
9840 return 0;
9841 }
8e65ff28 9842 internal_error (__FILE__, __LINE__,
e2e0b3e5 9843 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9844}
9845
283002cf
MR
9846static int
9847remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9848 CORE_ADDR start, int length)
9849{
9850 CORE_ADDR diff = remote_address_masked (addr - start);
9851
9852 return diff < length;
9853}
9854
d471ea57 9855
3c3bea1c 9856static int
f486487f
SM
9857remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9858 enum target_hw_bp_type type, struct expression *cond)
96baa820 9859{
d01949b6 9860 struct remote_state *rs = get_remote_state ();
bba74b36 9861 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9862 char *p;
d471ea57
AC
9863 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9864
4082afcc 9865 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9866 return -1;
802188a7 9867
28439a30
PA
9868 /* Make sure the remote is pointing at the right process, if
9869 necessary. */
9870 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9871 set_general_process ();
9872
bba74b36 9873 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9874 p = strchr (rs->buf, '\0');
96baa820
JM
9875 addr = remote_address_masked (addr);
9876 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9877 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9878 putpkt (rs->buf);
9879 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9880
6d820c5c 9881 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9882 {
9883 case PACKET_ERROR:
9884 case PACKET_UNKNOWN:
9885 return -1;
9886 case PACKET_OK:
9887 return 0;
9888 }
8e65ff28 9889 internal_error (__FILE__, __LINE__,
e2e0b3e5 9890 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9891}
9892
3c3bea1c 9893
501eef12 9894int remote_hw_watchpoint_limit = -1;
480a3f21 9895int remote_hw_watchpoint_length_limit = -1;
501eef12 9896int remote_hw_breakpoint_limit = -1;
d471ea57 9897
480a3f21 9898static int
31568a15
TT
9899remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9900 CORE_ADDR addr, int len)
480a3f21
PW
9901{
9902 if (remote_hw_watchpoint_length_limit == 0)
9903 return 0;
9904 else if (remote_hw_watchpoint_length_limit < 0)
9905 return 1;
9906 else if (len <= remote_hw_watchpoint_length_limit)
9907 return 1;
9908 else
9909 return 0;
9910}
9911
b9362cc7 9912static int
5461485a 9913remote_check_watch_resources (struct target_ops *self,
f486487f 9914 enum bptype type, int cnt, int ot)
96baa820 9915{
3c3bea1c
GS
9916 if (type == bp_hardware_breakpoint)
9917 {
9918 if (remote_hw_breakpoint_limit == 0)
9919 return 0;
501eef12
AC
9920 else if (remote_hw_breakpoint_limit < 0)
9921 return 1;
3c3bea1c
GS
9922 else if (cnt <= remote_hw_breakpoint_limit)
9923 return 1;
9924 }
9925 else
9926 {
9927 if (remote_hw_watchpoint_limit == 0)
9928 return 0;
501eef12
AC
9929 else if (remote_hw_watchpoint_limit < 0)
9930 return 1;
3c3bea1c
GS
9931 else if (ot)
9932 return -1;
9933 else if (cnt <= remote_hw_watchpoint_limit)
9934 return 1;
9935 }
9936 return -1;
9937}
9938
f7e6eed5
PA
9939/* The to_stopped_by_sw_breakpoint method of target remote. */
9940
9941static int
9942remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9943{
799a2abe 9944 struct thread_info *thread = inferior_thread ();
f7e6eed5 9945
799a2abe
PA
9946 return (thread->priv != NULL
9947 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9948}
9949
9950/* The to_supports_stopped_by_sw_breakpoint method of target
9951 remote. */
9952
9953static int
9954remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9955{
f7e6eed5
PA
9956 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9957}
9958
9959/* The to_stopped_by_hw_breakpoint method of target remote. */
9960
9961static int
9962remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9963{
799a2abe 9964 struct thread_info *thread = inferior_thread ();
f7e6eed5 9965
799a2abe
PA
9966 return (thread->priv != NULL
9967 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9968}
9969
9970/* The to_supports_stopped_by_hw_breakpoint method of target
9971 remote. */
9972
9973static int
9974remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9975{
f7e6eed5
PA
9976 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9977}
9978
b9362cc7 9979static int
6a109b6b 9980remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9981{
799a2abe 9982 struct thread_info *thread = inferior_thread ();
ee154bee 9983
799a2abe
PA
9984 return (thread->priv != NULL
9985 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9986}
9987
4aa7a7f5
JJ
9988static int
9989remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9990{
799a2abe 9991 struct thread_info *thread = inferior_thread ();
a744cf53 9992
799a2abe
PA
9993 if (thread->priv != NULL
9994 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9995 {
799a2abe
PA
9996 *addr_p = thread->priv->watch_data_address;
9997 return 1;
4aa7a7f5
JJ
9998 }
9999
799a2abe 10000 return 0;
3c3bea1c
GS
10001}
10002
10003
10004static int
23a26771 10005remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 10006 struct bp_target_info *bp_tgt)
3c3bea1c 10007{
0d5ed153 10008 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10009 struct remote_state *rs;
bba74b36 10010 char *p, *endbuf;
dd61ec5c 10011 char *message;
3c3bea1c 10012
4082afcc 10013 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10014 return -1;
2bc416ba 10015
28439a30
PA
10016 /* Make sure the remote is pointing at the right process, if
10017 necessary. */
10018 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10019 set_general_process ();
10020
4fff2411
JZ
10021 rs = get_remote_state ();
10022 p = rs->buf;
bba74b36 10023 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 10024
96baa820
JM
10025 *(p++) = 'Z';
10026 *(p++) = '1';
10027 *(p++) = ',';
802188a7 10028
0d5ed153 10029 addr = remote_address_masked (addr);
96baa820 10030 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10031 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10032
efcc2da7 10033 if (remote_supports_cond_breakpoints (self))
bba74b36 10034 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10035
78eff0ec 10036 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
10037 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10038
6d820c5c
DJ
10039 putpkt (rs->buf);
10040 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10041
6d820c5c 10042 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10043 {
10044 case PACKET_ERROR:
dd61ec5c
MW
10045 if (rs->buf[1] == '.')
10046 {
10047 message = strchr (rs->buf + 2, '.');
10048 if (message)
0316657e 10049 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10050 }
10051 return -1;
d471ea57
AC
10052 case PACKET_UNKNOWN:
10053 return -1;
10054 case PACKET_OK:
10055 return 0;
10056 }
8e65ff28 10057 internal_error (__FILE__, __LINE__,
e2e0b3e5 10058 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10059}
10060
d471ea57 10061
802188a7 10062static int
a64dc96c 10063remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 10064 struct bp_target_info *bp_tgt)
96baa820 10065{
8181d85f 10066 CORE_ADDR addr;
d01949b6 10067 struct remote_state *rs = get_remote_state ();
6d820c5c 10068 char *p = rs->buf;
bba74b36 10069 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 10070
4082afcc 10071 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10072 return -1;
802188a7 10073
28439a30
PA
10074 /* Make sure the remote is pointing at the right process, if
10075 necessary. */
10076 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10077 set_general_process ();
10078
96baa820
JM
10079 *(p++) = 'z';
10080 *(p++) = '1';
10081 *(p++) = ',';
802188a7 10082
8181d85f 10083 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10084 p += hexnumstr (p, (ULONGEST) addr);
579c6ad9 10085 xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
96baa820 10086
6d820c5c
DJ
10087 putpkt (rs->buf);
10088 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 10089
6d820c5c 10090 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10091 {
10092 case PACKET_ERROR:
10093 case PACKET_UNKNOWN:
10094 return -1;
10095 case PACKET_OK:
10096 return 0;
10097 }
8e65ff28 10098 internal_error (__FILE__, __LINE__,
e2e0b3e5 10099 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10100}
96baa820 10101
4a5e7a5b
PA
10102/* Verify memory using the "qCRC:" request. */
10103
10104static int
10105remote_verify_memory (struct target_ops *ops,
10106 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10107{
10108 struct remote_state *rs = get_remote_state ();
10109 unsigned long host_crc, target_crc;
10110 char *tmp;
10111
936d2992
PA
10112 /* It doesn't make sense to use qCRC if the remote target is
10113 connected but not running. */
10114 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10115 {
10116 enum packet_result result;
28439a30 10117
936d2992
PA
10118 /* Make sure the remote is pointing at the right process. */
10119 set_general_process ();
4a5e7a5b 10120
936d2992
PA
10121 /* FIXME: assumes lma can fit into long. */
10122 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10123 (long) lma, (long) size);
10124 putpkt (rs->buf);
4a5e7a5b 10125
936d2992
PA
10126 /* Be clever; compute the host_crc before waiting for target
10127 reply. */
10128 host_crc = xcrc32 (data, size, 0xffffffff);
10129
10130 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 10131
936d2992
PA
10132 result = packet_ok (rs->buf,
10133 &remote_protocol_packets[PACKET_qCRC]);
10134 if (result == PACKET_ERROR)
10135 return -1;
10136 else if (result == PACKET_OK)
10137 {
10138 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10139 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10140
936d2992
PA
10141 return (host_crc == target_crc);
10142 }
10143 }
4a5e7a5b 10144
936d2992 10145 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
10146}
10147
c906108c
SS
10148/* compare-sections command
10149
10150 With no arguments, compares each loadable section in the exec bfd
10151 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10152 Useful for verifying the image on the target against the exec file. */
e514a9d6 10153
c906108c 10154static void
fba45db2 10155compare_sections_command (char *args, int from_tty)
c906108c
SS
10156{
10157 asection *s;
c906108c 10158 struct cleanup *old_chain;
948f8e3d 10159 gdb_byte *sectdata;
ce359b09 10160 const char *sectname;
c906108c
SS
10161 bfd_size_type size;
10162 bfd_vma lma;
10163 int matched = 0;
10164 int mismatched = 0;
4a5e7a5b 10165 int res;
95cf3b38 10166 int read_only = 0;
c906108c
SS
10167
10168 if (!exec_bfd)
8a3fe4f8 10169 error (_("command cannot be used without an exec file"));
c906108c 10170
28439a30
PA
10171 /* Make sure the remote is pointing at the right process. */
10172 set_general_process ();
10173
95cf3b38
DT
10174 if (args != NULL && strcmp (args, "-r") == 0)
10175 {
10176 read_only = 1;
10177 args = NULL;
10178 }
10179
c5aa993b 10180 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10181 {
10182 if (!(s->flags & SEC_LOAD))
0df8b418 10183 continue; /* Skip non-loadable section. */
c906108c 10184
95cf3b38
DT
10185 if (read_only && (s->flags & SEC_READONLY) == 0)
10186 continue; /* Skip writeable sections */
10187
2c500098 10188 size = bfd_get_section_size (s);
c906108c 10189 if (size == 0)
0df8b418 10190 continue; /* Skip zero-length section. */
c906108c 10191
ce359b09 10192 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10193 if (args && strcmp (args, sectname) != 0)
0df8b418 10194 continue; /* Not the section selected by user. */
c906108c 10195
0df8b418 10196 matched = 1; /* Do this section. */
c906108c 10197 lma = s->lma;
c906108c 10198
224c3ddb 10199 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 10200 old_chain = make_cleanup (xfree, sectdata);
c906108c 10201 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 10202
4a5e7a5b
PA
10203 res = target_verify_memory (sectdata, lma, size);
10204
10205 if (res == -1)
5af949e3 10206 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10207 paddress (target_gdbarch (), lma),
10208 paddress (target_gdbarch (), lma + size));
c906108c 10209
5af949e3 10210 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10211 paddress (target_gdbarch (), lma),
10212 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10213 if (res)
c906108c
SS
10214 printf_filtered ("matched.\n");
10215 else
c5aa993b
JM
10216 {
10217 printf_filtered ("MIS-MATCHED!\n");
10218 mismatched++;
10219 }
c906108c
SS
10220
10221 do_cleanups (old_chain);
10222 }
10223 if (mismatched > 0)
936d2992 10224 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10225the loaded file\n"));
c906108c 10226 if (args && !matched)
a3f17187 10227 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10228}
10229
0e7f50da
UW
10230/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10231 into remote target. The number of bytes written to the remote
10232 target is returned, or -1 for error. */
10233
9b409511 10234static enum target_xfer_status
0e7f50da
UW
10235remote_write_qxfer (struct target_ops *ops, const char *object_name,
10236 const char *annex, const gdb_byte *writebuf,
9b409511 10237 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
10238 struct packet_config *packet)
10239{
10240 int i, buf_len;
10241 ULONGEST n;
0e7f50da
UW
10242 struct remote_state *rs = get_remote_state ();
10243 int max_size = get_memory_write_packet_size ();
10244
10245 if (packet->support == PACKET_DISABLE)
2ed4b548 10246 return TARGET_XFER_E_IO;
0e7f50da
UW
10247
10248 /* Insert header. */
10249 i = snprintf (rs->buf, max_size,
10250 "qXfer:%s:write:%s:%s:",
10251 object_name, annex ? annex : "",
10252 phex_nz (offset, sizeof offset));
10253 max_size -= (i + 1);
10254
10255 /* Escape as much data as fits into rs->buf. */
10256 buf_len = remote_escape_output
124e13d9 10257 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
10258
10259 if (putpkt_binary (rs->buf, i + buf_len) < 0
10260 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10261 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10262 return TARGET_XFER_E_IO;
0e7f50da
UW
10263
10264 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
10265
10266 *xfered_len = n;
10267 return TARGET_XFER_OK;
0e7f50da
UW
10268}
10269
0876f84a
DJ
10270/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10271 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10272 number of bytes read is returned, or 0 for EOF, or -1 for error.
10273 The number of bytes read may be less than LEN without indicating an
10274 EOF. PACKET is checked and updated to indicate whether the remote
10275 target supports this object. */
10276
9b409511 10277static enum target_xfer_status
0876f84a
DJ
10278remote_read_qxfer (struct target_ops *ops, const char *object_name,
10279 const char *annex,
10280 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 10281 ULONGEST *xfered_len,
0876f84a
DJ
10282 struct packet_config *packet)
10283{
0876f84a 10284 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10285 LONGEST i, n, packet_len;
10286
10287 if (packet->support == PACKET_DISABLE)
2ed4b548 10288 return TARGET_XFER_E_IO;
0876f84a
DJ
10289
10290 /* Check whether we've cached an end-of-object packet that matches
10291 this request. */
8e88304f 10292 if (rs->finished_object)
0876f84a 10293 {
8e88304f
TT
10294 if (strcmp (object_name, rs->finished_object) == 0
10295 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10296 && offset == rs->finished_offset)
9b409511
YQ
10297 return TARGET_XFER_EOF;
10298
0876f84a
DJ
10299
10300 /* Otherwise, we're now reading something different. Discard
10301 the cache. */
8e88304f
TT
10302 xfree (rs->finished_object);
10303 xfree (rs->finished_annex);
10304 rs->finished_object = NULL;
10305 rs->finished_annex = NULL;
0876f84a
DJ
10306 }
10307
10308 /* Request only enough to fit in a single packet. The actual data
10309 may not, since we don't know how much of it will need to be escaped;
10310 the target is free to respond with slightly less data. We subtract
10311 five to account for the response type and the protocol frame. */
768adc05 10312 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
0876f84a
DJ
10313 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10314 object_name, annex ? annex : "",
10315 phex_nz (offset, sizeof offset),
10316 phex_nz (n, sizeof n));
10317 i = putpkt (rs->buf);
10318 if (i < 0)
2ed4b548 10319 return TARGET_XFER_E_IO;
0876f84a
DJ
10320
10321 rs->buf[0] = '\0';
10322 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10323 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10324 return TARGET_XFER_E_IO;
0876f84a
DJ
10325
10326 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10327 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10328
10329 /* 'm' means there is (or at least might be) more data after this
10330 batch. That does not make sense unless there's at least one byte
10331 of data in this reply. */
10332 if (rs->buf[0] == 'm' && packet_len == 1)
10333 error (_("Remote qXfer reply contained no data."));
10334
10335 /* Got some data. */
bc20a4af
PA
10336 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10337 packet_len - 1, readbuf, n);
0876f84a
DJ
10338
10339 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10340 or possibly empty. If we have the final block of a non-empty
10341 object, record this fact to bypass a subsequent partial read. */
10342 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10343 {
8e88304f
TT
10344 rs->finished_object = xstrdup (object_name);
10345 rs->finished_annex = xstrdup (annex ? annex : "");
10346 rs->finished_offset = offset + i;
0876f84a
DJ
10347 }
10348
9b409511
YQ
10349 if (i == 0)
10350 return TARGET_XFER_EOF;
10351 else
10352 {
10353 *xfered_len = i;
10354 return TARGET_XFER_OK;
10355 }
0876f84a
DJ
10356}
10357
9b409511 10358static enum target_xfer_status
4b8a223f 10359remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 10360 const char *annex, gdb_byte *readbuf,
9b409511
YQ
10361 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10362 ULONGEST *xfered_len)
c906108c 10363{
82f73884 10364 struct remote_state *rs;
c906108c 10365 int i;
6d820c5c 10366 char *p2;
1e3ff5ad 10367 char query_type;
124e13d9 10368 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 10369
e6e4e701 10370 set_remote_traceframe ();
82f73884
PA
10371 set_general_thread (inferior_ptid);
10372
10373 rs = get_remote_state ();
10374
b2182ed2 10375 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
10376 if (object == TARGET_OBJECT_MEMORY)
10377 {
2d717e4f
DJ
10378 /* If the remote target is connected but not running, we should
10379 pass this request down to a lower stratum (e.g. the executable
10380 file). */
10381 if (!target_has_execution)
9b409511 10382 return TARGET_XFER_EOF;
2d717e4f 10383
21e3b9b9 10384 if (writebuf != NULL)
124e13d9
SM
10385 return remote_write_bytes (offset, writebuf, len, unit_size,
10386 xfered_len);
21e3b9b9 10387 else
124e13d9
SM
10388 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10389 xfered_len);
21e3b9b9
DJ
10390 }
10391
0df8b418 10392 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10393 if (object == TARGET_OBJECT_SPU)
10394 {
10395 if (readbuf)
10396 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
10397 xfered_len, &remote_protocol_packets
10398 [PACKET_qXfer_spu_read]);
0e7f50da
UW
10399 else
10400 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
10401 xfered_len, &remote_protocol_packets
10402 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10403 }
10404
4aa995e1
PA
10405 /* Handle extra signal info using qxfer packets. */
10406 if (object == TARGET_OBJECT_SIGNAL_INFO)
10407 {
10408 if (readbuf)
10409 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 10410 xfered_len, &remote_protocol_packets
4aa995e1
PA
10411 [PACKET_qXfer_siginfo_read]);
10412 else
3e43a32a 10413 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 10414 writebuf, offset, len, xfered_len,
4aa995e1
PA
10415 &remote_protocol_packets
10416 [PACKET_qXfer_siginfo_write]);
10417 }
10418
0fb4aa4b
PA
10419 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10420 {
10421 if (readbuf)
3e43a32a 10422 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 10423 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10424 &remote_protocol_packets
10425 [PACKET_qXfer_statictrace_read]);
10426 else
2ed4b548 10427 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10428 }
10429
a76d924d
DJ
10430 /* Only handle flash writes. */
10431 if (writebuf != NULL)
10432 {
a76d924d
DJ
10433 switch (object)
10434 {
10435 case TARGET_OBJECT_FLASH:
9b409511
YQ
10436 return remote_flash_write (ops, offset, len, xfered_len,
10437 writebuf);
a76d924d
DJ
10438
10439 default:
2ed4b548 10440 return TARGET_XFER_E_IO;
a76d924d
DJ
10441 }
10442 }
4b8a223f 10443
1e3ff5ad
AC
10444 /* Map pre-existing objects onto letters. DO NOT do this for new
10445 objects!!! Instead specify new query packets. */
10446 switch (object)
c906108c 10447 {
1e3ff5ad
AC
10448 case TARGET_OBJECT_AVR:
10449 query_type = 'R';
10450 break;
802188a7
RM
10451
10452 case TARGET_OBJECT_AUXV:
0876f84a
DJ
10453 gdb_assert (annex == NULL);
10454 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 10455 xfered_len,
0876f84a 10456 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10457
23181151
DJ
10458 case TARGET_OBJECT_AVAILABLE_FEATURES:
10459 return remote_read_qxfer
9b409511 10460 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10461 &remote_protocol_packets[PACKET_qXfer_features]);
10462
cfa9d6d9
DJ
10463 case TARGET_OBJECT_LIBRARIES:
10464 return remote_read_qxfer
9b409511 10465 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10466 &remote_protocol_packets[PACKET_qXfer_libraries]);
10467
2268b414
JK
10468 case TARGET_OBJECT_LIBRARIES_SVR4:
10469 return remote_read_qxfer
9b409511 10470 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10471 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10472
fd79ecee
DJ
10473 case TARGET_OBJECT_MEMORY_MAP:
10474 gdb_assert (annex == NULL);
10475 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 10476 xfered_len,
fd79ecee
DJ
10477 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10478
07e059b5
VP
10479 case TARGET_OBJECT_OSDATA:
10480 /* Should only get here if we're connected. */
5d93a237 10481 gdb_assert (rs->remote_desc);
07e059b5 10482 return remote_read_qxfer
9b409511 10483 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10484 &remote_protocol_packets[PACKET_qXfer_osdata]);
10485
dc146f7c
VP
10486 case TARGET_OBJECT_THREADS:
10487 gdb_assert (annex == NULL);
10488 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10489 xfered_len,
dc146f7c
VP
10490 &remote_protocol_packets[PACKET_qXfer_threads]);
10491
b3b9301e
PA
10492 case TARGET_OBJECT_TRACEFRAME_INFO:
10493 gdb_assert (annex == NULL);
10494 return remote_read_qxfer
9b409511 10495 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10496 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10497
10498 case TARGET_OBJECT_FDPIC:
10499 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10500 xfered_len,
78d85199 10501 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10502
10503 case TARGET_OBJECT_OPENVMS_UIB:
10504 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10505 xfered_len,
169081d0
TG
10506 &remote_protocol_packets[PACKET_qXfer_uib]);
10507
9accd112
MM
10508 case TARGET_OBJECT_BTRACE:
10509 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10510 xfered_len,
9accd112
MM
10511 &remote_protocol_packets[PACKET_qXfer_btrace]);
10512
f4abbc16
MM
10513 case TARGET_OBJECT_BTRACE_CONF:
10514 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10515 len, xfered_len,
10516 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10517
c78fa86a
GB
10518 case TARGET_OBJECT_EXEC_FILE:
10519 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10520 len, xfered_len,
10521 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10522
1e3ff5ad 10523 default:
2ed4b548 10524 return TARGET_XFER_E_IO;
c906108c
SS
10525 }
10526
0df8b418 10527 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10528 large enough let the caller deal with it. */
ea9c271d 10529 if (len < get_remote_packet_size ())
2ed4b548 10530 return TARGET_XFER_E_IO;
ea9c271d 10531 len = get_remote_packet_size ();
1e3ff5ad 10532
23860348 10533 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10534 if (!rs->remote_desc)
8a3fe4f8 10535 error (_("remote query is only available after target open"));
c906108c 10536
1e3ff5ad 10537 gdb_assert (annex != NULL);
4b8a223f 10538 gdb_assert (readbuf != NULL);
c906108c 10539
6d820c5c 10540 p2 = rs->buf;
c906108c
SS
10541 *p2++ = 'q';
10542 *p2++ = query_type;
10543
23860348
MS
10544 /* We used one buffer char for the remote protocol q command and
10545 another for the query type. As the remote protocol encapsulation
10546 uses 4 chars plus one extra in case we are debugging
10547 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10548 string. */
c906108c 10549 i = 0;
ea9c271d 10550 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10551 {
1e3ff5ad
AC
10552 /* Bad caller may have sent forbidden characters. */
10553 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10554 *p2++ = annex[i];
c906108c
SS
10555 i++;
10556 }
1e3ff5ad
AC
10557 *p2 = '\0';
10558 gdb_assert (annex[i] == '\0');
c906108c 10559
6d820c5c 10560 i = putpkt (rs->buf);
c5aa993b 10561 if (i < 0)
2ed4b548 10562 return TARGET_XFER_E_IO;
c906108c 10563
6d820c5c
DJ
10564 getpkt (&rs->buf, &rs->buf_size, 0);
10565 strcpy ((char *) readbuf, rs->buf);
c906108c 10566
9b409511
YQ
10567 *xfered_len = strlen ((char *) readbuf);
10568 return TARGET_XFER_OK;
c906108c
SS
10569}
10570
09c98b44
DB
10571/* Implementation of to_get_memory_xfer_limit. */
10572
10573static ULONGEST
10574remote_get_memory_xfer_limit (struct target_ops *ops)
10575{
10576 return get_memory_write_packet_size ();
10577}
10578
08388c79
DE
10579static int
10580remote_search_memory (struct target_ops* ops,
10581 CORE_ADDR start_addr, ULONGEST search_space_len,
10582 const gdb_byte *pattern, ULONGEST pattern_len,
10583 CORE_ADDR *found_addrp)
10584{
f5656ead 10585 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10586 struct remote_state *rs = get_remote_state ();
10587 int max_size = get_memory_write_packet_size ();
10588 struct packet_config *packet =
10589 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10590 /* Number of packet bytes used to encode the pattern;
10591 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10592 int escaped_pattern_len;
0df8b418 10593 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10594 int used_pattern_len;
10595 int i;
10596 int found;
10597 ULONGEST found_addr;
10598
10599 /* Don't go to the target if we don't have to.
10600 This is done before checking packet->support to avoid the possibility that
10601 a success for this edge case means the facility works in general. */
10602 if (pattern_len > search_space_len)
10603 return 0;
10604 if (pattern_len == 0)
10605 {
10606 *found_addrp = start_addr;
10607 return 1;
10608 }
10609
10610 /* If we already know the packet isn't supported, fall back to the simple
10611 way of searching memory. */
10612
4082afcc 10613 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10614 {
10615 /* Target doesn't provided special support, fall back and use the
10616 standard support (copy memory and do the search here). */
10617 return simple_search_memory (ops, start_addr, search_space_len,
10618 pattern, pattern_len, found_addrp);
10619 }
10620
28439a30
PA
10621 /* Make sure the remote is pointing at the right process. */
10622 set_general_process ();
10623
08388c79
DE
10624 /* Insert header. */
10625 i = snprintf (rs->buf, max_size,
10626 "qSearch:memory:%s;%s;",
5af949e3 10627 phex_nz (start_addr, addr_size),
08388c79
DE
10628 phex_nz (search_space_len, sizeof (search_space_len)));
10629 max_size -= (i + 1);
10630
10631 /* Escape as much data as fits into rs->buf. */
10632 escaped_pattern_len =
124e13d9 10633 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10634 &used_pattern_len, max_size);
10635
10636 /* Bail if the pattern is too large. */
10637 if (used_pattern_len != pattern_len)
9b20d036 10638 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10639
10640 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10641 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10642 || packet_ok (rs->buf, packet) != PACKET_OK)
10643 {
10644 /* The request may not have worked because the command is not
10645 supported. If so, fall back to the simple way. */
10646 if (packet->support == PACKET_DISABLE)
10647 {
10648 return simple_search_memory (ops, start_addr, search_space_len,
10649 pattern, pattern_len, found_addrp);
10650 }
10651 return -1;
10652 }
10653
10654 if (rs->buf[0] == '0')
10655 found = 0;
10656 else if (rs->buf[0] == '1')
10657 {
10658 found = 1;
10659 if (rs->buf[1] != ',')
10e0fa18 10660 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10661 unpack_varlen_hex (rs->buf + 2, &found_addr);
10662 *found_addrp = found_addr;
10663 }
10664 else
10e0fa18 10665 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10666
10667 return found;
10668}
10669
96baa820 10670static void
a30bf1f1 10671remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10672 struct ui_file *outbuf)
96baa820 10673{
d01949b6 10674 struct remote_state *rs = get_remote_state ();
2e9f7625 10675 char *p = rs->buf;
96baa820 10676
5d93a237 10677 if (!rs->remote_desc)
8a3fe4f8 10678 error (_("remote rcmd is only available after target open"));
96baa820 10679
23860348 10680 /* Send a NULL command across as an empty command. */
7be570e7
JM
10681 if (command == NULL)
10682 command = "";
10683
23860348 10684 /* The query prefix. */
2e9f7625
DJ
10685 strcpy (rs->buf, "qRcmd,");
10686 p = strchr (rs->buf, '\0');
96baa820 10687
3e43a32a
MS
10688 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10689 > get_remote_packet_size ())
8a3fe4f8 10690 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10691
23860348 10692 /* Encode the actual command. */
a30bf1f1 10693 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10694
6d820c5c 10695 if (putpkt (rs->buf) < 0)
8a3fe4f8 10696 error (_("Communication problem with target."));
96baa820
JM
10697
10698 /* get/display the response */
10699 while (1)
10700 {
2e9f7625
DJ
10701 char *buf;
10702
00bf0b85 10703 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10704 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10705 rs->buf[0] = '\0';
5b37825d
PW
10706 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10707 {
10708 /* Timeout. Continue to (try to) read responses.
10709 This is better than stopping with an error, assuming the stub
10710 is still executing the (long) monitor command.
10711 If needed, the user can interrupt gdb using C-c, obtaining
10712 an effect similar to stop on timeout. */
10713 continue;
10714 }
2e9f7625 10715 buf = rs->buf;
96baa820 10716 if (buf[0] == '\0')
8a3fe4f8 10717 error (_("Target does not support this command."));
96baa820
JM
10718 if (buf[0] == 'O' && buf[1] != 'K')
10719 {
23860348 10720 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10721 continue;
10722 }
10723 if (strcmp (buf, "OK") == 0)
10724 break;
7be570e7
JM
10725 if (strlen (buf) == 3 && buf[0] == 'E'
10726 && isdigit (buf[1]) && isdigit (buf[2]))
10727 {
8a3fe4f8 10728 error (_("Protocol error with Rcmd"));
7be570e7 10729 }
96baa820
JM
10730 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10731 {
10732 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10733
96baa820
JM
10734 fputc_unfiltered (c, outbuf);
10735 }
10736 break;
10737 }
10738}
10739
fd79ecee
DJ
10740static VEC(mem_region_s) *
10741remote_memory_map (struct target_ops *ops)
10742{
10743 VEC(mem_region_s) *result = NULL;
10744 char *text = target_read_stralloc (&current_target,
10745 TARGET_OBJECT_MEMORY_MAP, NULL);
10746
10747 if (text)
10748 {
10749 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10750
fd79ecee
DJ
10751 result = parse_memory_map (text);
10752 do_cleanups (back_to);
10753 }
10754
10755 return result;
10756}
10757
c906108c 10758static void
fba45db2 10759packet_command (char *args, int from_tty)
c906108c 10760{
d01949b6 10761 struct remote_state *rs = get_remote_state ();
c906108c 10762
5d93a237 10763 if (!rs->remote_desc)
8a3fe4f8 10764 error (_("command can only be used with remote target"));
c906108c 10765
c5aa993b 10766 if (!args)
8a3fe4f8 10767 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10768
10769 puts_filtered ("sending: ");
10770 print_packet (args);
10771 puts_filtered ("\n");
10772 putpkt (args);
10773
6d820c5c 10774 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10775 puts_filtered ("received: ");
6d820c5c 10776 print_packet (rs->buf);
c906108c
SS
10777 puts_filtered ("\n");
10778}
10779
10780#if 0
23860348 10781/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10782
a14ed312 10783static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10784
a14ed312 10785static void threadset_test_cmd (char *cmd, int tty);
c906108c 10786
a14ed312 10787static void threadalive_test (char *cmd, int tty);
c906108c 10788
a14ed312 10789static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10790
23860348 10791int get_and_display_threadinfo (threadref *ref);
c906108c 10792
a14ed312 10793static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10794
23860348 10795static int thread_display_step (threadref *ref, void *context);
c906108c 10796
a14ed312 10797static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10798
a14ed312 10799static void init_remote_threadtests (void);
c906108c 10800
23860348 10801#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10802
10803static void
fba45db2 10804threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10805{
10806 int sample_thread = SAMPLE_THREAD;
10807
a3f17187 10808 printf_filtered (_("Remote threadset test\n"));
79d7f229 10809 set_general_thread (sample_thread);
c906108c
SS
10810}
10811
10812
10813static void
fba45db2 10814threadalive_test (char *cmd, int tty)
c906108c
SS
10815{
10816 int sample_thread = SAMPLE_THREAD;
79d7f229 10817 int pid = ptid_get_pid (inferior_ptid);
ba348170 10818 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10819
79d7f229 10820 if (remote_thread_alive (ptid))
c906108c
SS
10821 printf_filtered ("PASS: Thread alive test\n");
10822 else
10823 printf_filtered ("FAIL: Thread alive test\n");
10824}
10825
23860348 10826void output_threadid (char *title, threadref *ref);
c906108c
SS
10827
10828void
fba45db2 10829output_threadid (char *title, threadref *ref)
c906108c
SS
10830{
10831 char hexid[20];
10832
23860348 10833 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10834 hexid[16] = 0;
10835 printf_filtered ("%s %s\n", title, (&hexid[0]));
10836}
10837
10838static void
fba45db2 10839threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10840{
10841 int startflag = 1;
10842 threadref nextthread;
10843 int done, result_count;
10844 threadref threadlist[3];
10845
10846 printf_filtered ("Remote Threadlist test\n");
10847 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10848 &result_count, &threadlist[0]))
10849 printf_filtered ("FAIL: threadlist test\n");
10850 else
10851 {
10852 threadref *scan = threadlist;
10853 threadref *limit = scan + result_count;
10854
10855 while (scan < limit)
10856 output_threadid (" thread ", scan++);
10857 }
10858}
10859
10860void
fba45db2 10861display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10862{
10863 output_threadid ("Threadid: ", &info->threadid);
10864 printf_filtered ("Name: %s\n ", info->shortname);
10865 printf_filtered ("State: %s\n", info->display);
10866 printf_filtered ("other: %s\n\n", info->more_display);
10867}
10868
10869int
fba45db2 10870get_and_display_threadinfo (threadref *ref)
c906108c
SS
10871{
10872 int result;
10873 int set;
10874 struct gdb_ext_thread_info threadinfo;
10875
10876 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10877 | TAG_MOREDISPLAY | TAG_DISPLAY;
10878 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10879 display_thread_info (&threadinfo);
10880 return result;
10881}
10882
10883static void
fba45db2 10884threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10885{
10886 int athread = SAMPLE_THREAD;
10887 threadref thread;
10888 int set;
10889
10890 int_to_threadref (&thread, athread);
10891 printf_filtered ("Remote Threadinfo test\n");
10892 if (!get_and_display_threadinfo (&thread))
10893 printf_filtered ("FAIL cannot get thread info\n");
10894}
10895
10896static int
fba45db2 10897thread_display_step (threadref *ref, void *context)
c906108c
SS
10898{
10899 /* output_threadid(" threadstep ",ref); *//* simple test */
10900 return get_and_display_threadinfo (ref);
10901}
10902
10903static void
fba45db2 10904threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10905{
10906 printf_filtered ("Remote Threadlist update test\n");
10907 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10908}
10909
10910static void
10911init_remote_threadtests (void)
10912{
3e43a32a
MS
10913 add_com ("tlist", class_obscure, threadlist_test_cmd,
10914 _("Fetch and print the remote list of "
10915 "thread identifiers, one pkt only"));
c906108c 10916 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10917 _("Fetch and display info about one thread"));
c906108c 10918 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10919 _("Test setting to a different thread"));
c906108c 10920 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10921 _("Iterate through updating all remote thread info"));
c906108c 10922 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10923 _(" Remote thread alive test "));
c906108c
SS
10924}
10925
10926#endif /* 0 */
10927
f3fb8c85
MS
10928/* Convert a thread ID to a string. Returns the string in a static
10929 buffer. */
10930
7a114964 10931static const char *
117de6a9 10932remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10933{
79d7f229 10934 static char buf[64];
82f73884 10935 struct remote_state *rs = get_remote_state ();
f3fb8c85 10936
7cee1e54
PA
10937 if (ptid_equal (ptid, null_ptid))
10938 return normal_pid_to_str (ptid);
10939 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10940 {
10941 /* Printing an inferior target id. */
10942
10943 /* When multi-process extensions are off, there's no way in the
10944 remote protocol to know the remote process id, if there's any
10945 at all. There's one exception --- when we're connected with
10946 target extended-remote, and we manually attached to a process
10947 with "attach PID". We don't record anywhere a flag that
10948 allows us to distinguish that case from the case of
10949 connecting with extended-remote and the stub already being
10950 attached to a process, and reporting yes to qAttached, hence
10951 no smart special casing here. */
10952 if (!remote_multi_process_p (rs))
10953 {
10954 xsnprintf (buf, sizeof buf, "Remote target");
10955 return buf;
10956 }
10957
10958 return normal_pid_to_str (ptid);
82f73884 10959 }
ecd0ada5 10960 else
79d7f229 10961 {
ecd0ada5
PA
10962 if (ptid_equal (magic_null_ptid, ptid))
10963 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 10964 else if (remote_multi_process_p (rs))
de0d863e
DB
10965 if (ptid_get_lwp (ptid) == 0)
10966 return normal_pid_to_str (ptid);
10967 else
10968 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10969 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10970 else
10971 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10972 ptid_get_lwp (ptid));
79d7f229
PA
10973 return buf;
10974 }
f3fb8c85
MS
10975}
10976
38691318
KB
10977/* Get the address of the thread local variable in OBJFILE which is
10978 stored at OFFSET within the thread local storage for thread PTID. */
10979
10980static CORE_ADDR
117de6a9
PA
10981remote_get_thread_local_address (struct target_ops *ops,
10982 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10983{
4082afcc 10984 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10985 {
10986 struct remote_state *rs = get_remote_state ();
6d820c5c 10987 char *p = rs->buf;
82f73884 10988 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10989 enum packet_result result;
38691318
KB
10990
10991 strcpy (p, "qGetTLSAddr:");
10992 p += strlen (p);
82f73884 10993 p = write_ptid (p, endp, ptid);
38691318
KB
10994 *p++ = ',';
10995 p += hexnumstr (p, offset);
10996 *p++ = ',';
10997 p += hexnumstr (p, lm);
10998 *p++ = '\0';
10999
6d820c5c
DJ
11000 putpkt (rs->buf);
11001 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
11002 result = packet_ok (rs->buf,
11003 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11004 if (result == PACKET_OK)
38691318
KB
11005 {
11006 ULONGEST result;
11007
6d820c5c 11008 unpack_varlen_hex (rs->buf, &result);
38691318
KB
11009 return result;
11010 }
571dd617 11011 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11012 throw_error (TLS_GENERIC_ERROR,
11013 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11014 else
109c3e39
AC
11015 throw_error (TLS_GENERIC_ERROR,
11016 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11017 }
11018 else
109c3e39
AC
11019 throw_error (TLS_GENERIC_ERROR,
11020 _("TLS not supported or disabled on this target"));
38691318
KB
11021 /* Not reached. */
11022 return 0;
11023}
11024
711e434b
PM
11025/* Provide thread local base, i.e. Thread Information Block address.
11026 Returns 1 if ptid is found and thread_local_base is non zero. */
11027
70221824 11028static int
bd7ae0f5 11029remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 11030{
4082afcc 11031 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11032 {
11033 struct remote_state *rs = get_remote_state ();
11034 char *p = rs->buf;
11035 char *endp = rs->buf + get_remote_packet_size ();
11036 enum packet_result result;
11037
11038 strcpy (p, "qGetTIBAddr:");
11039 p += strlen (p);
11040 p = write_ptid (p, endp, ptid);
11041 *p++ = '\0';
11042
11043 putpkt (rs->buf);
11044 getpkt (&rs->buf, &rs->buf_size, 0);
11045 result = packet_ok (rs->buf,
11046 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11047 if (result == PACKET_OK)
11048 {
11049 ULONGEST result;
11050
11051 unpack_varlen_hex (rs->buf, &result);
11052 if (addr)
11053 *addr = (CORE_ADDR) result;
11054 return 1;
11055 }
11056 else if (result == PACKET_UNKNOWN)
11057 error (_("Remote target doesn't support qGetTIBAddr packet"));
11058 else
11059 error (_("Remote target failed to process qGetTIBAddr request"));
11060 }
11061 else
11062 error (_("qGetTIBAddr not supported or disabled on this target"));
11063 /* Not reached. */
11064 return 0;
11065}
11066
29709017
DJ
11067/* Support for inferring a target description based on the current
11068 architecture and the size of a 'g' packet. While the 'g' packet
11069 can have any size (since optional registers can be left off the
11070 end), some sizes are easily recognizable given knowledge of the
11071 approximate architecture. */
11072
11073struct remote_g_packet_guess
11074{
11075 int bytes;
11076 const struct target_desc *tdesc;
11077};
11078typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11079DEF_VEC_O(remote_g_packet_guess_s);
11080
11081struct remote_g_packet_data
11082{
11083 VEC(remote_g_packet_guess_s) *guesses;
11084};
11085
11086static struct gdbarch_data *remote_g_packet_data_handle;
11087
11088static void *
11089remote_g_packet_data_init (struct obstack *obstack)
11090{
11091 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11092}
11093
11094void
11095register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11096 const struct target_desc *tdesc)
11097{
11098 struct remote_g_packet_data *data
19ba03f4
SM
11099 = ((struct remote_g_packet_data *)
11100 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11101 struct remote_g_packet_guess new_guess, *guess;
11102 int ix;
11103
11104 gdb_assert (tdesc != NULL);
11105
11106 for (ix = 0;
11107 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11108 ix++)
11109 if (guess->bytes == bytes)
11110 internal_error (__FILE__, __LINE__,
9b20d036 11111 _("Duplicate g packet description added for size %d"),
29709017
DJ
11112 bytes);
11113
11114 new_guess.bytes = bytes;
11115 new_guess.tdesc = tdesc;
11116 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11117}
11118
d962ef82
DJ
11119/* Return 1 if remote_read_description would do anything on this target
11120 and architecture, 0 otherwise. */
11121
11122static int
11123remote_read_description_p (struct target_ops *target)
11124{
11125 struct remote_g_packet_data *data
19ba03f4
SM
11126 = ((struct remote_g_packet_data *)
11127 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
11128
11129 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11130 return 1;
11131
11132 return 0;
11133}
11134
29709017
DJ
11135static const struct target_desc *
11136remote_read_description (struct target_ops *target)
11137{
11138 struct remote_g_packet_data *data
19ba03f4
SM
11139 = ((struct remote_g_packet_data *)
11140 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11141
d962ef82
DJ
11142 /* Do not try this during initial connection, when we do not know
11143 whether there is a running but stopped thread. */
11144 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 11145 return target->beneath->to_read_description (target->beneath);
d962ef82 11146
29709017
DJ
11147 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11148 {
11149 struct remote_g_packet_guess *guess;
11150 int ix;
11151 int bytes = send_g_packet ();
11152
11153 for (ix = 0;
11154 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11155 ix++)
11156 if (guess->bytes == bytes)
11157 return guess->tdesc;
11158
11159 /* We discard the g packet. A minor optimization would be to
11160 hold on to it, and fill the register cache once we have selected
11161 an architecture, but it's too tricky to do safely. */
11162 }
11163
2117c711 11164 return target->beneath->to_read_description (target->beneath);
29709017
DJ
11165}
11166
a6b151f1
DJ
11167/* Remote file transfer support. This is host-initiated I/O, not
11168 target-initiated; for target-initiated, see remote-fileio.c. */
11169
11170/* If *LEFT is at least the length of STRING, copy STRING to
11171 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11172 decrease *LEFT. Otherwise raise an error. */
11173
11174static void
a121b7c1 11175remote_buffer_add_string (char **buffer, int *left, const char *string)
a6b151f1
DJ
11176{
11177 int len = strlen (string);
11178
11179 if (len > *left)
11180 error (_("Packet too long for target."));
11181
11182 memcpy (*buffer, string, len);
11183 *buffer += len;
11184 *left -= len;
11185
11186 /* NUL-terminate the buffer as a convenience, if there is
11187 room. */
11188 if (*left)
11189 **buffer = '\0';
11190}
11191
11192/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11193 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11194 decrease *LEFT. Otherwise raise an error. */
11195
11196static void
11197remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11198 int len)
11199{
11200 if (2 * len > *left)
11201 error (_("Packet too long for target."));
11202
11203 bin2hex (bytes, *buffer, len);
11204 *buffer += 2 * len;
11205 *left -= 2 * len;
11206
11207 /* NUL-terminate the buffer as a convenience, if there is
11208 room. */
11209 if (*left)
11210 **buffer = '\0';
11211}
11212
11213/* If *LEFT is large enough, convert VALUE to hex and add it to
11214 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11215 decrease *LEFT. Otherwise raise an error. */
11216
11217static void
11218remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11219{
11220 int len = hexnumlen (value);
11221
11222 if (len > *left)
11223 error (_("Packet too long for target."));
11224
11225 hexnumstr (*buffer, value);
11226 *buffer += len;
11227 *left -= len;
11228
11229 /* NUL-terminate the buffer as a convenience, if there is
11230 room. */
11231 if (*left)
11232 **buffer = '\0';
11233}
11234
11235/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11236 value, *REMOTE_ERRNO to the remote error number or zero if none
11237 was included, and *ATTACHMENT to point to the start of the annex
11238 if any. The length of the packet isn't needed here; there may
11239 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11240
11241 Return 0 if the packet could be parsed, -1 if it could not. If
11242 -1 is returned, the other variables may not be initialized. */
11243
11244static int
11245remote_hostio_parse_result (char *buffer, int *retcode,
11246 int *remote_errno, char **attachment)
11247{
11248 char *p, *p2;
11249
11250 *remote_errno = 0;
11251 *attachment = NULL;
11252
11253 if (buffer[0] != 'F')
11254 return -1;
11255
11256 errno = 0;
11257 *retcode = strtol (&buffer[1], &p, 16);
11258 if (errno != 0 || p == &buffer[1])
11259 return -1;
11260
11261 /* Check for ",errno". */
11262 if (*p == ',')
11263 {
11264 errno = 0;
11265 *remote_errno = strtol (p + 1, &p2, 16);
11266 if (errno != 0 || p + 1 == p2)
11267 return -1;
11268 p = p2;
11269 }
11270
11271 /* Check for ";attachment". If there is no attachment, the
11272 packet should end here. */
11273 if (*p == ';')
11274 {
11275 *attachment = p + 1;
11276 return 0;
11277 }
11278 else if (*p == '\0')
11279 return 0;
11280 else
11281 return -1;
11282}
11283
11284/* Send a prepared I/O packet to the target and read its response.
11285 The prepared packet is in the global RS->BUF before this function
11286 is called, and the answer is there when we return.
11287
11288 COMMAND_BYTES is the length of the request to send, which may include
11289 binary data. WHICH_PACKET is the packet configuration to check
11290 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11291 is set to the error number and -1 is returned. Otherwise the value
11292 returned by the function is returned.
11293
11294 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11295 attachment is expected; an error will be reported if there's a
11296 mismatch. If one is found, *ATTACHMENT will be set to point into
11297 the packet buffer and *ATTACHMENT_LEN will be set to the
11298 attachment's length. */
11299
11300static int
11301remote_hostio_send_command (int command_bytes, int which_packet,
11302 int *remote_errno, char **attachment,
11303 int *attachment_len)
11304{
11305 struct remote_state *rs = get_remote_state ();
11306 int ret, bytes_read;
11307 char *attachment_tmp;
11308
5d93a237 11309 if (!rs->remote_desc
4082afcc 11310 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11311 {
11312 *remote_errno = FILEIO_ENOSYS;
11313 return -1;
11314 }
11315
11316 putpkt_binary (rs->buf, command_bytes);
11317 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11318
11319 /* If it timed out, something is wrong. Don't try to parse the
11320 buffer. */
11321 if (bytes_read < 0)
11322 {
11323 *remote_errno = FILEIO_EINVAL;
11324 return -1;
11325 }
11326
11327 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11328 {
11329 case PACKET_ERROR:
11330 *remote_errno = FILEIO_EINVAL;
11331 return -1;
11332 case PACKET_UNKNOWN:
11333 *remote_errno = FILEIO_ENOSYS;
11334 return -1;
11335 case PACKET_OK:
11336 break;
11337 }
11338
11339 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11340 &attachment_tmp))
11341 {
11342 *remote_errno = FILEIO_EINVAL;
11343 return -1;
11344 }
11345
11346 /* Make sure we saw an attachment if and only if we expected one. */
11347 if ((attachment_tmp == NULL && attachment != NULL)
11348 || (attachment_tmp != NULL && attachment == NULL))
11349 {
11350 *remote_errno = FILEIO_EINVAL;
11351 return -1;
11352 }
11353
11354 /* If an attachment was found, it must point into the packet buffer;
11355 work out how many bytes there were. */
11356 if (attachment_tmp != NULL)
11357 {
11358 *attachment = attachment_tmp;
11359 *attachment_len = bytes_read - (*attachment - rs->buf);
11360 }
11361
11362 return ret;
11363}
11364
80152258
PA
11365/* Invalidate the readahead cache. */
11366
11367static void
11368readahead_cache_invalidate (void)
11369{
11370 struct remote_state *rs = get_remote_state ();
11371
11372 rs->readahead_cache.fd = -1;
11373}
11374
11375/* Invalidate the readahead cache if it is holding data for FD. */
11376
11377static void
11378readahead_cache_invalidate_fd (int fd)
11379{
11380 struct remote_state *rs = get_remote_state ();
11381
11382 if (rs->readahead_cache.fd == fd)
11383 rs->readahead_cache.fd = -1;
11384}
11385
15a201c8
GB
11386/* Set the filesystem remote_hostio functions that take FILENAME
11387 arguments will use. Return 0 on success, or -1 if an error
11388 occurs (and set *REMOTE_ERRNO). */
11389
11390static int
11391remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11392{
11393 struct remote_state *rs = get_remote_state ();
11394 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11395 char *p = rs->buf;
11396 int left = get_remote_packet_size () - 1;
11397 char arg[9];
11398 int ret;
11399
11400 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11401 return 0;
11402
11403 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11404 return 0;
11405
11406 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11407
11408 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11409 remote_buffer_add_string (&p, &left, arg);
11410
11411 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11412 remote_errno, NULL, NULL);
11413
11414 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11415 return 0;
11416
11417 if (ret == 0)
11418 rs->fs_pid = required_pid;
11419
11420 return ret;
11421}
11422
12e2a5fd 11423/* Implementation of to_fileio_open. */
a6b151f1
DJ
11424
11425static int
cd897586 11426remote_hostio_open (struct target_ops *self,
07c138c8 11427 struct inferior *inf, const char *filename,
4313b8c0
GB
11428 int flags, int mode, int warn_if_slow,
11429 int *remote_errno)
a6b151f1
DJ
11430{
11431 struct remote_state *rs = get_remote_state ();
11432 char *p = rs->buf;
11433 int left = get_remote_packet_size () - 1;
11434
4313b8c0
GB
11435 if (warn_if_slow)
11436 {
11437 static int warning_issued = 0;
11438
11439 printf_unfiltered (_("Reading %s from remote target...\n"),
11440 filename);
11441
11442 if (!warning_issued)
11443 {
11444 warning (_("File transfers from remote targets can be slow."
11445 " Use \"set sysroot\" to access files locally"
11446 " instead."));
11447 warning_issued = 1;
11448 }
11449 }
11450
15a201c8
GB
11451 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11452 return -1;
11453
a6b151f1
DJ
11454 remote_buffer_add_string (&p, &left, "vFile:open:");
11455
11456 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11457 strlen (filename));
11458 remote_buffer_add_string (&p, &left, ",");
11459
11460 remote_buffer_add_int (&p, &left, flags);
11461 remote_buffer_add_string (&p, &left, ",");
11462
11463 remote_buffer_add_int (&p, &left, mode);
11464
11465 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11466 remote_errno, NULL, NULL);
11467}
11468
12e2a5fd 11469/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11470
11471static int
0d866f62
TT
11472remote_hostio_pwrite (struct target_ops *self,
11473 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11474 ULONGEST offset, int *remote_errno)
11475{
11476 struct remote_state *rs = get_remote_state ();
11477 char *p = rs->buf;
11478 int left = get_remote_packet_size ();
11479 int out_len;
11480
80152258
PA
11481 readahead_cache_invalidate_fd (fd);
11482
a6b151f1
DJ
11483 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11484
11485 remote_buffer_add_int (&p, &left, fd);
11486 remote_buffer_add_string (&p, &left, ",");
11487
11488 remote_buffer_add_int (&p, &left, offset);
11489 remote_buffer_add_string (&p, &left, ",");
11490
124e13d9 11491 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11492 get_remote_packet_size () - (p - rs->buf));
11493
11494 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11495 remote_errno, NULL, NULL);
11496}
11497
80152258
PA
11498/* Helper for the implementation of to_fileio_pread. Read the file
11499 from the remote side with vFile:pread. */
a6b151f1
DJ
11500
11501static int
80152258
PA
11502remote_hostio_pread_vFile (struct target_ops *self,
11503 int fd, gdb_byte *read_buf, int len,
11504 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11505{
11506 struct remote_state *rs = get_remote_state ();
11507 char *p = rs->buf;
11508 char *attachment;
11509 int left = get_remote_packet_size ();
11510 int ret, attachment_len;
11511 int read_len;
11512
11513 remote_buffer_add_string (&p, &left, "vFile:pread:");
11514
11515 remote_buffer_add_int (&p, &left, fd);
11516 remote_buffer_add_string (&p, &left, ",");
11517
11518 remote_buffer_add_int (&p, &left, len);
11519 remote_buffer_add_string (&p, &left, ",");
11520
11521 remote_buffer_add_int (&p, &left, offset);
11522
11523 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11524 remote_errno, &attachment,
11525 &attachment_len);
11526
11527 if (ret < 0)
11528 return ret;
11529
bc20a4af 11530 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11531 read_buf, len);
11532 if (read_len != ret)
11533 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11534
11535 return ret;
11536}
11537
80152258
PA
11538/* Serve pread from the readahead cache. Returns number of bytes
11539 read, or 0 if the request can't be served from the cache. */
11540
11541static int
11542remote_hostio_pread_from_cache (struct remote_state *rs,
11543 int fd, gdb_byte *read_buf, size_t len,
11544 ULONGEST offset)
11545{
11546 struct readahead_cache *cache = &rs->readahead_cache;
11547
11548 if (cache->fd == fd
11549 && cache->offset <= offset
11550 && offset < cache->offset + cache->bufsize)
11551 {
11552 ULONGEST max = cache->offset + cache->bufsize;
11553
11554 if (offset + len > max)
11555 len = max - offset;
11556
11557 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11558 return len;
11559 }
11560
11561 return 0;
11562}
11563
11564/* Implementation of to_fileio_pread. */
11565
11566static int
11567remote_hostio_pread (struct target_ops *self,
11568 int fd, gdb_byte *read_buf, int len,
11569 ULONGEST offset, int *remote_errno)
11570{
11571 int ret;
11572 struct remote_state *rs = get_remote_state ();
11573 struct readahead_cache *cache = &rs->readahead_cache;
11574
11575 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11576 if (ret > 0)
11577 {
11578 cache->hit_count++;
11579
11580 if (remote_debug)
11581 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11582 pulongest (cache->hit_count));
11583 return ret;
11584 }
11585
11586 cache->miss_count++;
11587 if (remote_debug)
11588 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11589 pulongest (cache->miss_count));
11590
11591 cache->fd = fd;
11592 cache->offset = offset;
11593 cache->bufsize = get_remote_packet_size ();
224c3ddb 11594 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11595
11596 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11597 cache->offset, remote_errno);
11598 if (ret <= 0)
11599 {
11600 readahead_cache_invalidate_fd (fd);
11601 return ret;
11602 }
11603
11604 cache->bufsize = ret;
11605 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11606}
11607
12e2a5fd 11608/* Implementation of to_fileio_close. */
a6b151f1
DJ
11609
11610static int
df39ea25 11611remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11612{
11613 struct remote_state *rs = get_remote_state ();
11614 char *p = rs->buf;
11615 int left = get_remote_packet_size () - 1;
11616
80152258
PA
11617 readahead_cache_invalidate_fd (fd);
11618
a6b151f1
DJ
11619 remote_buffer_add_string (&p, &left, "vFile:close:");
11620
11621 remote_buffer_add_int (&p, &left, fd);
11622
11623 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11624 remote_errno, NULL, NULL);
11625}
11626
12e2a5fd 11627/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11628
11629static int
dbbca37d 11630remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11631 struct inferior *inf, const char *filename,
11632 int *remote_errno)
a6b151f1
DJ
11633{
11634 struct remote_state *rs = get_remote_state ();
11635 char *p = rs->buf;
11636 int left = get_remote_packet_size () - 1;
11637
15a201c8
GB
11638 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11639 return -1;
11640
a6b151f1
DJ
11641 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11642
11643 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11644 strlen (filename));
11645
11646 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11647 remote_errno, NULL, NULL);
11648}
11649
12e2a5fd 11650/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11651
11652static char *
fab5aa7c 11653remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11654 struct inferior *inf, const char *filename,
11655 int *remote_errno)
b9e7b9c3
UW
11656{
11657 struct remote_state *rs = get_remote_state ();
11658 char *p = rs->buf;
11659 char *attachment;
11660 int left = get_remote_packet_size ();
11661 int len, attachment_len;
11662 int read_len;
11663 char *ret;
11664
15a201c8
GB
11665 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11666 return NULL;
11667
b9e7b9c3
UW
11668 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11669
11670 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11671 strlen (filename));
11672
11673 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11674 remote_errno, &attachment,
11675 &attachment_len);
11676
11677 if (len < 0)
11678 return NULL;
11679
224c3ddb 11680 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11681
bc20a4af
PA
11682 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11683 (gdb_byte *) ret, len);
b9e7b9c3
UW
11684 if (read_len != len)
11685 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11686
11687 ret[len] = '\0';
11688 return ret;
11689}
11690
12e2a5fd 11691/* Implementation of to_fileio_fstat. */
0a93529c
GB
11692
11693static int
11694remote_hostio_fstat (struct target_ops *self,
11695 int fd, struct stat *st,
11696 int *remote_errno)
11697{
11698 struct remote_state *rs = get_remote_state ();
11699 char *p = rs->buf;
11700 int left = get_remote_packet_size ();
11701 int attachment_len, ret;
11702 char *attachment;
11703 struct fio_stat fst;
11704 int read_len;
11705
464b0089
GB
11706 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11707
11708 remote_buffer_add_int (&p, &left, fd);
11709
11710 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11711 remote_errno, &attachment,
11712 &attachment_len);
11713 if (ret < 0)
0a93529c 11714 {
464b0089
GB
11715 if (*remote_errno != FILEIO_ENOSYS)
11716 return ret;
11717
0a93529c
GB
11718 /* Strictly we should return -1, ENOSYS here, but when
11719 "set sysroot remote:" was implemented in August 2008
11720 BFD's need for a stat function was sidestepped with
11721 this hack. This was not remedied until March 2015
11722 so we retain the previous behavior to avoid breaking
11723 compatibility.
11724
11725 Note that the memset is a March 2015 addition; older
11726 GDBs set st_size *and nothing else* so the structure
11727 would have garbage in all other fields. This might
11728 break something but retaining the previous behavior
11729 here would be just too wrong. */
11730
11731 memset (st, 0, sizeof (struct stat));
11732 st->st_size = INT_MAX;
11733 return 0;
11734 }
11735
0a93529c
GB
11736 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11737 (gdb_byte *) &fst, sizeof (fst));
11738
11739 if (read_len != ret)
11740 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11741
11742 if (read_len != sizeof (fst))
11743 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11744 read_len, (int) sizeof (fst));
11745
11746 remote_fileio_to_host_stat (&fst, st);
11747
11748 return 0;
11749}
11750
12e2a5fd 11751/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11752
11753static int
11754remote_filesystem_is_local (struct target_ops *self)
11755{
11756 /* Valgrind GDB presents itself as a remote target but works
11757 on the local filesystem: it does not implement remote get
11758 and users are not expected to set a sysroot. To handle
11759 this case we treat the remote filesystem as local if the
11760 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11761 does not support vFile:open. */
a3be80c3 11762 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11763 {
11764 enum packet_support ps = packet_support (PACKET_vFile_open);
11765
11766 if (ps == PACKET_SUPPORT_UNKNOWN)
11767 {
11768 int fd, remote_errno;
11769
11770 /* Try opening a file to probe support. The supplied
11771 filename is irrelevant, we only care about whether
11772 the stub recognizes the packet or not. */
07c138c8 11773 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11774 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11775 &remote_errno);
11776
11777 if (fd >= 0)
11778 remote_hostio_close (self, fd, &remote_errno);
11779
11780 ps = packet_support (PACKET_vFile_open);
11781 }
11782
11783 if (ps == PACKET_DISABLE)
11784 {
11785 static int warning_issued = 0;
11786
11787 if (!warning_issued)
11788 {
11789 warning (_("remote target does not support file"
11790 " transfer, attempting to access files"
11791 " from local filesystem."));
11792 warning_issued = 1;
11793 }
11794
11795 return 1;
11796 }
11797 }
11798
11799 return 0;
11800}
11801
a6b151f1
DJ
11802static int
11803remote_fileio_errno_to_host (int errnum)
11804{
11805 switch (errnum)
11806 {
11807 case FILEIO_EPERM:
11808 return EPERM;
11809 case FILEIO_ENOENT:
11810 return ENOENT;
11811 case FILEIO_EINTR:
11812 return EINTR;
11813 case FILEIO_EIO:
11814 return EIO;
11815 case FILEIO_EBADF:
11816 return EBADF;
11817 case FILEIO_EACCES:
11818 return EACCES;
11819 case FILEIO_EFAULT:
11820 return EFAULT;
11821 case FILEIO_EBUSY:
11822 return EBUSY;
11823 case FILEIO_EEXIST:
11824 return EEXIST;
11825 case FILEIO_ENODEV:
11826 return ENODEV;
11827 case FILEIO_ENOTDIR:
11828 return ENOTDIR;
11829 case FILEIO_EISDIR:
11830 return EISDIR;
11831 case FILEIO_EINVAL:
11832 return EINVAL;
11833 case FILEIO_ENFILE:
11834 return ENFILE;
11835 case FILEIO_EMFILE:
11836 return EMFILE;
11837 case FILEIO_EFBIG:
11838 return EFBIG;
11839 case FILEIO_ENOSPC:
11840 return ENOSPC;
11841 case FILEIO_ESPIPE:
11842 return ESPIPE;
11843 case FILEIO_EROFS:
11844 return EROFS;
11845 case FILEIO_ENOSYS:
11846 return ENOSYS;
11847 case FILEIO_ENAMETOOLONG:
11848 return ENAMETOOLONG;
11849 }
11850 return -1;
11851}
11852
11853static char *
11854remote_hostio_error (int errnum)
11855{
11856 int host_error = remote_fileio_errno_to_host (errnum);
11857
11858 if (host_error == -1)
11859 error (_("Unknown remote I/O error %d"), errnum);
11860 else
11861 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11862}
11863
a6b151f1
DJ
11864static void
11865remote_hostio_close_cleanup (void *opaque)
11866{
11867 int fd = *(int *) opaque;
11868 int remote_errno;
11869
df39ea25 11870 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11871}
11872
11873void
11874remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11875{
11876 struct cleanup *back_to, *close_cleanup;
11877 int retcode, fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11878 gdb_byte *buffer;
11879 int bytes_in_buffer;
11880 int saw_eof;
11881 ULONGEST offset;
5d93a237 11882 struct remote_state *rs = get_remote_state ();
a6b151f1 11883
5d93a237 11884 if (!rs->remote_desc)
a6b151f1
DJ
11885 error (_("command can only be used with remote target"));
11886
d419f42d 11887 gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11888 if (file == NULL)
11889 perror_with_name (local_file);
a6b151f1 11890
07c138c8 11891 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11892 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11893 | FILEIO_O_TRUNC),
4313b8c0 11894 0700, 0, &remote_errno);
a6b151f1
DJ
11895 if (fd == -1)
11896 remote_hostio_error (remote_errno);
11897
11898 /* Send up to this many bytes at once. They won't all fit in the
11899 remote packet limit, so we'll transfer slightly fewer. */
11900 io_size = get_remote_packet_size ();
224c3ddb 11901 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 11902 back_to = make_cleanup (xfree, buffer);
a6b151f1
DJ
11903
11904 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11905
11906 bytes_in_buffer = 0;
11907 saw_eof = 0;
11908 offset = 0;
11909 while (bytes_in_buffer || !saw_eof)
11910 {
11911 if (!saw_eof)
11912 {
3e43a32a
MS
11913 bytes = fread (buffer + bytes_in_buffer, 1,
11914 io_size - bytes_in_buffer,
d419f42d 11915 file.get ());
a6b151f1
DJ
11916 if (bytes == 0)
11917 {
d419f42d 11918 if (ferror (file.get ()))
a6b151f1
DJ
11919 error (_("Error reading %s."), local_file);
11920 else
11921 {
11922 /* EOF. Unless there is something still in the
11923 buffer from the last iteration, we are done. */
11924 saw_eof = 1;
11925 if (bytes_in_buffer == 0)
11926 break;
11927 }
11928 }
11929 }
11930 else
11931 bytes = 0;
11932
11933 bytes += bytes_in_buffer;
11934 bytes_in_buffer = 0;
11935
0d866f62
TT
11936 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11937 fd, buffer, bytes,
3e43a32a 11938 offset, &remote_errno);
a6b151f1
DJ
11939
11940 if (retcode < 0)
11941 remote_hostio_error (remote_errno);
11942 else if (retcode == 0)
11943 error (_("Remote write of %d bytes returned 0!"), bytes);
11944 else if (retcode < bytes)
11945 {
11946 /* Short write. Save the rest of the read data for the next
11947 write. */
11948 bytes_in_buffer = bytes - retcode;
11949 memmove (buffer, buffer + retcode, bytes_in_buffer);
11950 }
11951
11952 offset += retcode;
11953 }
11954
11955 discard_cleanups (close_cleanup);
df39ea25 11956 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11957 remote_hostio_error (remote_errno);
11958
11959 if (from_tty)
11960 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11961 do_cleanups (back_to);
11962}
11963
11964void
11965remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11966{
11967 struct cleanup *back_to, *close_cleanup;
cea39f65 11968 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11969 gdb_byte *buffer;
11970 ULONGEST offset;
5d93a237 11971 struct remote_state *rs = get_remote_state ();
a6b151f1 11972
5d93a237 11973 if (!rs->remote_desc)
a6b151f1
DJ
11974 error (_("command can only be used with remote target"));
11975
07c138c8 11976 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11977 remote_file, FILEIO_O_RDONLY, 0, 0,
11978 &remote_errno);
a6b151f1
DJ
11979 if (fd == -1)
11980 remote_hostio_error (remote_errno);
11981
d419f42d 11982 gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11983 if (file == NULL)
11984 perror_with_name (local_file);
a6b151f1
DJ
11985
11986 /* Send up to this many bytes at once. They won't all fit in the
11987 remote packet limit, so we'll transfer slightly fewer. */
11988 io_size = get_remote_packet_size ();
224c3ddb 11989 buffer = (gdb_byte *) xmalloc (io_size);
d419f42d 11990 back_to = make_cleanup (xfree, buffer);
a6b151f1
DJ
11991
11992 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11993
11994 offset = 0;
11995 while (1)
11996 {
a3be983c
TT
11997 bytes = remote_hostio_pread (find_target_at (process_stratum),
11998 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11999 if (bytes == 0)
12000 /* Success, but no bytes, means end-of-file. */
12001 break;
12002 if (bytes == -1)
12003 remote_hostio_error (remote_errno);
12004
12005 offset += bytes;
12006
d419f42d 12007 bytes = fwrite (buffer, 1, bytes, file.get ());
a6b151f1
DJ
12008 if (bytes == 0)
12009 perror_with_name (local_file);
12010 }
12011
12012 discard_cleanups (close_cleanup);
df39ea25 12013 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
12014 remote_hostio_error (remote_errno);
12015
12016 if (from_tty)
12017 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12018 do_cleanups (back_to);
12019}
12020
12021void
12022remote_file_delete (const char *remote_file, int from_tty)
12023{
12024 int retcode, remote_errno;
5d93a237 12025 struct remote_state *rs = get_remote_state ();
a6b151f1 12026
5d93a237 12027 if (!rs->remote_desc)
a6b151f1
DJ
12028 error (_("command can only be used with remote target"));
12029
dbbca37d 12030 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 12031 NULL, remote_file, &remote_errno);
a6b151f1
DJ
12032 if (retcode == -1)
12033 remote_hostio_error (remote_errno);
12034
12035 if (from_tty)
12036 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12037}
12038
12039static void
12040remote_put_command (char *args, int from_tty)
12041{
d1a41061
PP
12042 if (args == NULL)
12043 error_no_arg (_("file to put"));
12044
773a1edc 12045 gdb_argv argv (args);
a6b151f1
DJ
12046 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12047 error (_("Invalid parameters to remote put"));
12048
12049 remote_file_put (argv[0], argv[1], from_tty);
a6b151f1
DJ
12050}
12051
12052static void
12053remote_get_command (char *args, int from_tty)
12054{
d1a41061
PP
12055 if (args == NULL)
12056 error_no_arg (_("file to get"));
12057
773a1edc 12058 gdb_argv argv (args);
a6b151f1
DJ
12059 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12060 error (_("Invalid parameters to remote get"));
12061
12062 remote_file_get (argv[0], argv[1], from_tty);
a6b151f1
DJ
12063}
12064
12065static void
12066remote_delete_command (char *args, int from_tty)
12067{
d1a41061
PP
12068 if (args == NULL)
12069 error_no_arg (_("file to delete"));
12070
773a1edc 12071 gdb_argv argv (args);
a6b151f1
DJ
12072 if (argv[0] == NULL || argv[1] != NULL)
12073 error (_("Invalid parameters to remote delete"));
12074
12075 remote_file_delete (argv[0], from_tty);
a6b151f1
DJ
12076}
12077
12078static void
12079remote_command (char *args, int from_tty)
12080{
635c7e8a 12081 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12082}
12083
b2175913 12084static int
19db3e69 12085remote_can_execute_reverse (struct target_ops *self)
b2175913 12086{
4082afcc
PA
12087 if (packet_support (PACKET_bs) == PACKET_ENABLE
12088 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
12089 return 1;
12090 else
12091 return 0;
b2175913
MS
12092}
12093
74531fed 12094static int
2a9a2795 12095remote_supports_non_stop (struct target_ops *self)
74531fed
PA
12096{
12097 return 1;
12098}
12099
03583c20 12100static int
2bfc0540 12101remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
12102{
12103 /* Only supported in extended mode. */
12104 return 0;
12105}
12106
8a305172 12107static int
86ce2668 12108remote_supports_multi_process (struct target_ops *self)
8a305172
PA
12109{
12110 struct remote_state *rs = get_remote_state ();
a744cf53 12111
8020350c 12112 return remote_multi_process_p (rs);
8a305172
PA
12113}
12114
70221824 12115static int
782b2b07
SS
12116remote_supports_cond_tracepoints (void)
12117{
4082afcc 12118 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12119}
12120
3788aec7 12121static int
efcc2da7 12122remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 12123{
4082afcc 12124 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12125}
12126
70221824 12127static int
7a697b8d
SS
12128remote_supports_fast_tracepoints (void)
12129{
4082afcc 12130 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12131}
12132
0fb4aa4b
PA
12133static int
12134remote_supports_static_tracepoints (void)
12135{
4082afcc 12136 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12137}
12138
1e4d1764
YQ
12139static int
12140remote_supports_install_in_trace (void)
12141{
4082afcc 12142 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12143}
12144
d248b706 12145static int
7d178d6a 12146remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 12147{
4082afcc
PA
12148 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12149 == PACKET_ENABLE);
d248b706
KY
12150}
12151
3065dfb6 12152static int
6de37a3a 12153remote_supports_string_tracing (struct target_ops *self)
3065dfb6 12154{
4082afcc 12155 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12156}
12157
d3ce09f5 12158static int
78eff0ec 12159remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 12160{
4082afcc 12161 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12162}
12163
35b1e5cc 12164static void
ecae04e1 12165remote_trace_init (struct target_ops *self)
35b1e5cc
SS
12166{
12167 putpkt ("QTinit");
12168 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 12169 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12170 error (_("Target does not support this command."));
12171}
12172
12173static void free_actions_list (char **actions_list);
12174static void free_actions_list_cleanup_wrapper (void *);
12175static void
12176free_actions_list_cleanup_wrapper (void *al)
12177{
19ba03f4 12178 free_actions_list ((char **) al);
35b1e5cc
SS
12179}
12180
12181static void
12182free_actions_list (char **actions_list)
12183{
12184 int ndx;
12185
12186 if (actions_list == 0)
12187 return;
12188
12189 for (ndx = 0; actions_list[ndx]; ndx++)
12190 xfree (actions_list[ndx]);
12191
12192 xfree (actions_list);
12193}
12194
409873ef
SS
12195/* Recursive routine to walk through command list including loops, and
12196 download packets for each command. */
12197
12198static void
12199remote_download_command_source (int num, ULONGEST addr,
12200 struct command_line *cmds)
12201{
12202 struct remote_state *rs = get_remote_state ();
12203 struct command_line *cmd;
12204
12205 for (cmd = cmds; cmd; cmd = cmd->next)
12206 {
0df8b418 12207 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12208 strcpy (rs->buf, "QTDPsrc:");
12209 encode_source_string (num, addr, "cmd", cmd->line,
12210 rs->buf + strlen (rs->buf),
12211 rs->buf_size - strlen (rs->buf));
12212 putpkt (rs->buf);
12213 remote_get_noisy_reply (&target_buf, &target_buf_size);
12214 if (strcmp (target_buf, "OK"))
12215 warning (_("Target does not support source download."));
12216
12217 if (cmd->control_type == while_control
12218 || cmd->control_type == while_stepping_control)
12219 {
12220 remote_download_command_source (num, addr, *cmd->body_list);
12221
0df8b418 12222 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12223 strcpy (rs->buf, "QTDPsrc:");
12224 encode_source_string (num, addr, "cmd", "end",
12225 rs->buf + strlen (rs->buf),
12226 rs->buf_size - strlen (rs->buf));
12227 putpkt (rs->buf);
12228 remote_get_noisy_reply (&target_buf, &target_buf_size);
12229 if (strcmp (target_buf, "OK"))
12230 warning (_("Target does not support source download."));
12231 }
12232 }
12233}
12234
35b1e5cc 12235static void
548f7808 12236remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 12237{
bba74b36 12238#define BUF_SIZE 2048
e8ba3115 12239
35b1e5cc 12240 CORE_ADDR tpaddr;
409873ef 12241 char addrbuf[40];
bba74b36 12242 char buf[BUF_SIZE];
35b1e5cc
SS
12243 char **tdp_actions;
12244 char **stepping_actions;
12245 int ndx;
12246 struct cleanup *old_chain = NULL;
35b1e5cc 12247 char *pkt;
e8ba3115 12248 struct breakpoint *b = loc->owner;
d9b3f62e 12249 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 12250
dc673c81 12251 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12252 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
12253 tdp_actions);
12254 (void) make_cleanup (free_actions_list_cleanup_wrapper,
12255 stepping_actions);
12256
12257 tpaddr = loc->address;
12258 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
12259 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12260 addrbuf, /* address */
12261 (b->enable_state == bp_enabled ? 'E' : 'D'),
12262 t->step_count, t->pass_count);
e8ba3115
YQ
12263 /* Fast tracepoints are mostly handled by the target, but we can
12264 tell the target how big of an instruction block should be moved
12265 around. */
12266 if (b->type == bp_fast_tracepoint)
12267 {
12268 /* Only test for support at download time; we may not know
12269 target capabilities at definition time. */
12270 if (remote_supports_fast_tracepoints ())
35b1e5cc 12271 {
6b940e6a
PL
12272 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12273 NULL))
bba74b36 12274 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 12275 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 12276 else
e8ba3115
YQ
12277 /* If it passed validation at definition but fails now,
12278 something is very wrong. */
12279 internal_error (__FILE__, __LINE__,
12280 _("Fast tracepoint not "
12281 "valid during download"));
35b1e5cc 12282 }
e8ba3115
YQ
12283 else
12284 /* Fast tracepoints are functionally identical to regular
12285 tracepoints, so don't take lack of support as a reason to
12286 give up on the trace run. */
12287 warning (_("Target does not support fast tracepoints, "
12288 "downloading %d as regular tracepoint"), b->number);
12289 }
12290 else if (b->type == bp_static_tracepoint)
12291 {
12292 /* Only test for support at download time; we may not know
12293 target capabilities at definition time. */
12294 if (remote_supports_static_tracepoints ())
0fb4aa4b 12295 {
e8ba3115 12296 struct static_tracepoint_marker marker;
0fb4aa4b 12297
e8ba3115
YQ
12298 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12299 strcat (buf, ":S");
0fb4aa4b 12300 else
e8ba3115 12301 error (_("Static tracepoint not valid during download"));
0fb4aa4b 12302 }
e8ba3115
YQ
12303 else
12304 /* Fast tracepoints are functionally identical to regular
12305 tracepoints, so don't take lack of support as a reason
12306 to give up on the trace run. */
12307 error (_("Target does not support static tracepoints"));
12308 }
12309 /* If the tracepoint has a conditional, make it into an agent
12310 expression and append to the definition. */
12311 if (loc->cond)
12312 {
12313 /* Only test support at download time, we may not know target
12314 capabilities at definition time. */
12315 if (remote_supports_cond_tracepoints ())
35b1e5cc 12316 {
833177a4 12317 agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
bba74b36
YQ
12318 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12319 aexpr->len);
e8ba3115
YQ
12320 pkt = buf + strlen (buf);
12321 for (ndx = 0; ndx < aexpr->len; ++ndx)
12322 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12323 *pkt = '\0';
35b1e5cc 12324 }
e8ba3115
YQ
12325 else
12326 warning (_("Target does not support conditional tracepoints, "
12327 "ignoring tp %d cond"), b->number);
12328 }
35b1e5cc 12329
d9b3f62e 12330 if (b->commands || *default_collect)
e8ba3115
YQ
12331 strcat (buf, "-");
12332 putpkt (buf);
12333 remote_get_noisy_reply (&target_buf, &target_buf_size);
12334 if (strcmp (target_buf, "OK"))
12335 error (_("Target does not support tracepoints."));
35b1e5cc 12336
e8ba3115
YQ
12337 /* do_single_steps (t); */
12338 if (tdp_actions)
12339 {
12340 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 12341 {
e8ba3115 12342 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
12343 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12344 b->number, addrbuf, /* address */
12345 tdp_actions[ndx],
12346 ((tdp_actions[ndx + 1] || stepping_actions)
12347 ? '-' : 0));
e8ba3115
YQ
12348 putpkt (buf);
12349 remote_get_noisy_reply (&target_buf,
12350 &target_buf_size);
12351 if (strcmp (target_buf, "OK"))
12352 error (_("Error on target while setting tracepoints."));
35b1e5cc 12353 }
e8ba3115
YQ
12354 }
12355 if (stepping_actions)
12356 {
12357 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 12358 {
e8ba3115 12359 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
12360 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12361 b->number, addrbuf, /* address */
12362 ((ndx == 0) ? "S" : ""),
12363 stepping_actions[ndx],
12364 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
12365 putpkt (buf);
12366 remote_get_noisy_reply (&target_buf,
12367 &target_buf_size);
12368 if (strcmp (target_buf, "OK"))
12369 error (_("Error on target while setting tracepoints."));
35b1e5cc 12370 }
e8ba3115 12371 }
409873ef 12372
4082afcc 12373 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 12374 {
f00aae0f 12375 if (b->location != NULL)
409873ef 12376 {
e8ba3115 12377 strcpy (buf, "QTDPsrc:");
f00aae0f 12378 encode_source_string (b->number, loc->address, "at",
d28cd78a 12379 event_location_to_string (b->location.get ()),
f00aae0f 12380 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
12381 putpkt (buf);
12382 remote_get_noisy_reply (&target_buf, &target_buf_size);
12383 if (strcmp (target_buf, "OK"))
12384 warning (_("Target does not support source download."));
409873ef 12385 }
e8ba3115
YQ
12386 if (b->cond_string)
12387 {
12388 strcpy (buf, "QTDPsrc:");
12389 encode_source_string (b->number, loc->address,
12390 "cond", b->cond_string, buf + strlen (buf),
12391 2048 - strlen (buf));
12392 putpkt (buf);
12393 remote_get_noisy_reply (&target_buf, &target_buf_size);
12394 if (strcmp (target_buf, "OK"))
12395 warning (_("Target does not support source download."));
12396 }
12397 remote_download_command_source (b->number, loc->address,
12398 breakpoint_commands (b));
35b1e5cc 12399 }
e8ba3115
YQ
12400
12401 do_cleanups (old_chain);
35b1e5cc
SS
12402}
12403
1e4d1764 12404static int
a52a8357 12405remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 12406{
1e51243a
PA
12407 struct remote_state *rs = get_remote_state ();
12408 struct trace_status *ts;
12409 int status;
12410
12411 /* Don't try to install tracepoints until we've relocated our
12412 symbols, and fetched and merged the target's tracepoint list with
12413 ours. */
12414 if (rs->starting_up)
12415 return 0;
12416
12417 ts = current_trace_status ();
8bd200f1 12418 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
12419
12420 if (status == -1 || !ts->running_known || !ts->running)
12421 return 0;
12422
12423 /* If we are in a tracing experiment, but remote stub doesn't support
12424 installing tracepoint in trace, we have to return. */
12425 if (!remote_supports_install_in_trace ())
12426 return 0;
12427
12428 return 1;
12429}
12430
12431
35b1e5cc 12432static void
559d2b81
TT
12433remote_download_trace_state_variable (struct target_ops *self,
12434 struct trace_state_variable *tsv)
35b1e5cc
SS
12435{
12436 struct remote_state *rs = get_remote_state ();
00bf0b85 12437 char *p;
35b1e5cc 12438
bba74b36
YQ
12439 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12440 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12441 tsv->builtin);
00bf0b85
SS
12442 p = rs->buf + strlen (rs->buf);
12443 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12444 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 12445 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 12446 *p++ = '\0';
35b1e5cc
SS
12447 putpkt (rs->buf);
12448 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12449 if (*target_buf == '\0')
12450 error (_("Target does not support this command."));
12451 if (strcmp (target_buf, "OK") != 0)
12452 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12453}
12454
d248b706 12455static void
46670d57
TT
12456remote_enable_tracepoint (struct target_ops *self,
12457 struct bp_location *location)
d248b706
KY
12458{
12459 struct remote_state *rs = get_remote_state ();
12460 char addr_buf[40];
12461
12462 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12463 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12464 location->owner->number, addr_buf);
d248b706
KY
12465 putpkt (rs->buf);
12466 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12467 if (*rs->buf == '\0')
12468 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12469 if (strcmp (rs->buf, "OK") != 0)
12470 error (_("Error on target while enabling tracepoint."));
12471}
12472
12473static void
780b049c
TT
12474remote_disable_tracepoint (struct target_ops *self,
12475 struct bp_location *location)
d248b706
KY
12476{
12477 struct remote_state *rs = get_remote_state ();
12478 char addr_buf[40];
12479
12480 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12481 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12482 location->owner->number, addr_buf);
d248b706
KY
12483 putpkt (rs->buf);
12484 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12485 if (*rs->buf == '\0')
12486 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12487 if (strcmp (rs->buf, "OK") != 0)
12488 error (_("Error on target while disabling tracepoint."));
12489}
12490
35b1e5cc 12491static void
583f9a86 12492remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12493{
12494 asection *s;
81b9b86e 12495 bfd *abfd = NULL;
35b1e5cc 12496 bfd_size_type size;
608bcef2 12497 bfd_vma vma;
35b1e5cc 12498 int anysecs = 0;
c2fa21f1 12499 int offset = 0;
35b1e5cc
SS
12500
12501 if (!exec_bfd)
12502 return; /* No information to give. */
12503
12504 strcpy (target_buf, "QTro");
9779ab84 12505 offset = strlen (target_buf);
35b1e5cc
SS
12506 for (s = exec_bfd->sections; s; s = s->next)
12507 {
12508 char tmp1[40], tmp2[40];
c2fa21f1 12509 int sec_length;
35b1e5cc
SS
12510
12511 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12512 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12513 (s->flags & SEC_READONLY) == 0)
12514 continue;
12515
12516 anysecs = 1;
81b9b86e 12517 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12518 size = bfd_get_section_size (s);
608bcef2
HZ
12519 sprintf_vma (tmp1, vma);
12520 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12521 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12522 if (offset + sec_length + 1 > target_buf_size)
12523 {
4082afcc 12524 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12525 warning (_("\
c2fa21f1
HZ
12526Too many sections for read-only sections definition packet."));
12527 break;
12528 }
bba74b36
YQ
12529 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12530 tmp1, tmp2);
c2fa21f1 12531 offset += sec_length;
35b1e5cc
SS
12532 }
12533 if (anysecs)
12534 {
12535 putpkt (target_buf);
12536 getpkt (&target_buf, &target_buf_size, 0);
12537 }
12538}
12539
12540static void
e2d1aae3 12541remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12542{
12543 putpkt ("QTStart");
12544 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12545 if (*target_buf == '\0')
12546 error (_("Target does not support this command."));
12547 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12548 error (_("Bogus reply from target: %s"), target_buf);
12549}
12550
12551static int
8bd200f1 12552remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12553{
953b98d1 12554 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12555 char *p = NULL;
0df8b418 12556 /* FIXME we need to get register block size some other way. */
00bf0b85 12557 extern int trace_regblock_size;
bd3eecc3
PA
12558 enum packet_result result;
12559
4082afcc 12560 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12561 return -1;
a744cf53 12562
00bf0b85
SS
12563 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12564
049dc89b
JK
12565 putpkt ("qTStatus");
12566
492d29ea 12567 TRY
67f41397
JK
12568 {
12569 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12570 }
492d29ea 12571 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12572 {
598d3636
JK
12573 if (ex.error != TARGET_CLOSE_ERROR)
12574 {
12575 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12576 return -1;
12577 }
12578 throw_exception (ex);
67f41397 12579 }
492d29ea 12580 END_CATCH
00bf0b85 12581
bd3eecc3
PA
12582 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12583
00bf0b85 12584 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12585 if (result == PACKET_UNKNOWN)
00bf0b85 12586 return -1;
35b1e5cc 12587
00bf0b85 12588 /* We're working with a live target. */
f5911ea1 12589 ts->filename = NULL;
00bf0b85 12590
00bf0b85 12591 if (*p++ != 'T')
35b1e5cc
SS
12592 error (_("Bogus trace status reply from target: %s"), target_buf);
12593
84cebc4a
YQ
12594 /* Function 'parse_trace_status' sets default value of each field of
12595 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12596 parse_trace_status (p, ts);
12597
12598 return ts->running;
35b1e5cc
SS
12599}
12600
70221824 12601static void
db90e85c 12602remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12603 struct uploaded_tp *utp)
12604{
12605 struct remote_state *rs = get_remote_state ();
f196051f
SS
12606 char *reply;
12607 struct bp_location *loc;
12608 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12609 size_t size = get_remote_packet_size ();
f196051f
SS
12610
12611 if (tp)
12612 {
c1fc2657 12613 tp->hit_count = 0;
f196051f 12614 tp->traceframe_usage = 0;
c1fc2657 12615 for (loc = tp->loc; loc; loc = loc->next)
f196051f
SS
12616 {
12617 /* If the tracepoint was never downloaded, don't go asking for
12618 any status. */
12619 if (tp->number_on_target == 0)
12620 continue;
bba74b36
YQ
12621 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12622 phex_nz (loc->address, 0));
f196051f
SS
12623 putpkt (rs->buf);
12624 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12625 if (reply && *reply)
12626 {
12627 if (*reply == 'V')
12628 parse_tracepoint_status (reply + 1, bp, utp);
12629 }
12630 }
12631 }
12632 else if (utp)
12633 {
12634 utp->hit_count = 0;
12635 utp->traceframe_usage = 0;
bba74b36
YQ
12636 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12637 phex_nz (utp->addr, 0));
f196051f
SS
12638 putpkt (rs->buf);
12639 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12640 if (reply && *reply)
12641 {
12642 if (*reply == 'V')
12643 parse_tracepoint_status (reply + 1, bp, utp);
12644 }
12645 }
12646}
12647
35b1e5cc 12648static void
74499f1b 12649remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12650{
12651 putpkt ("QTStop");
12652 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12653 if (*target_buf == '\0')
12654 error (_("Target does not support this command."));
12655 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12656 error (_("Bogus reply from target: %s"), target_buf);
12657}
12658
12659static int
bd4c6793
TT
12660remote_trace_find (struct target_ops *self,
12661 enum trace_find_type type, int num,
cc5925ad 12662 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12663 int *tpp)
12664{
12665 struct remote_state *rs = get_remote_state ();
bba74b36 12666 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12667 char *p, *reply;
12668 int target_frameno = -1, target_tracept = -1;
12669
e6e4e701
PA
12670 /* Lookups other than by absolute frame number depend on the current
12671 trace selected, so make sure it is correct on the remote end
12672 first. */
12673 if (type != tfind_number)
12674 set_remote_traceframe ();
12675
35b1e5cc
SS
12676 p = rs->buf;
12677 strcpy (p, "QTFrame:");
12678 p = strchr (p, '\0');
12679 switch (type)
12680 {
12681 case tfind_number:
bba74b36 12682 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12683 break;
12684 case tfind_pc:
bba74b36 12685 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12686 break;
12687 case tfind_tp:
bba74b36 12688 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12689 break;
12690 case tfind_range:
bba74b36
YQ
12691 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12692 phex_nz (addr2, 0));
35b1e5cc
SS
12693 break;
12694 case tfind_outside:
bba74b36
YQ
12695 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12696 phex_nz (addr2, 0));
35b1e5cc
SS
12697 break;
12698 default:
9b20d036 12699 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12700 }
12701
12702 putpkt (rs->buf);
2f65bcb7 12703 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12704 if (*reply == '\0')
12705 error (_("Target does not support this command."));
35b1e5cc
SS
12706
12707 while (reply && *reply)
12708 switch (*reply)
12709 {
12710 case 'F':
f197e0f1
VP
12711 p = ++reply;
12712 target_frameno = (int) strtol (p, &reply, 16);
12713 if (reply == p)
12714 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12715 /* Don't update our remote traceframe number cache on failure
12716 to select a remote traceframe. */
f197e0f1
VP
12717 if (target_frameno == -1)
12718 return -1;
35b1e5cc
SS
12719 break;
12720 case 'T':
f197e0f1
VP
12721 p = ++reply;
12722 target_tracept = (int) strtol (p, &reply, 16);
12723 if (reply == p)
12724 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12725 break;
12726 case 'O': /* "OK"? */
12727 if (reply[1] == 'K' && reply[2] == '\0')
12728 reply += 2;
12729 else
12730 error (_("Bogus reply from target: %s"), reply);
12731 break;
12732 default:
12733 error (_("Bogus reply from target: %s"), reply);
12734 }
12735 if (tpp)
12736 *tpp = target_tracept;
e6e4e701 12737
262e1174 12738 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12739 return target_frameno;
12740}
12741
12742static int
4011015b
TT
12743remote_get_trace_state_variable_value (struct target_ops *self,
12744 int tsvnum, LONGEST *val)
35b1e5cc
SS
12745{
12746 struct remote_state *rs = get_remote_state ();
12747 char *reply;
12748 ULONGEST uval;
12749
e6e4e701
PA
12750 set_remote_traceframe ();
12751
bba74b36 12752 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12753 putpkt (rs->buf);
12754 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12755 if (reply && *reply)
12756 {
12757 if (*reply == 'V')
12758 {
12759 unpack_varlen_hex (reply + 1, &uval);
12760 *val = (LONGEST) uval;
12761 return 1;
12762 }
12763 }
12764 return 0;
12765}
12766
00bf0b85 12767static int
dc3decaf 12768remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12769{
12770 struct remote_state *rs = get_remote_state ();
12771 char *p, *reply;
12772
12773 p = rs->buf;
12774 strcpy (p, "QTSave:");
12775 p += strlen (p);
12776 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12777 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12778 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12779 *p++ = '\0';
12780 putpkt (rs->buf);
ad91cd99 12781 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12782 if (*reply == '\0')
ad91cd99
PA
12783 error (_("Target does not support this command."));
12784 if (strcmp (reply, "OK") != 0)
12785 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12786 return 0;
12787}
12788
12789/* This is basically a memory transfer, but needs to be its own packet
12790 because we don't know how the target actually organizes its trace
12791 memory, plus we want to be able to ask for as much as possible, but
12792 not be unhappy if we don't get as much as we ask for. */
12793
12794static LONGEST
88ee6f45
TT
12795remote_get_raw_trace_data (struct target_ops *self,
12796 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12797{
12798 struct remote_state *rs = get_remote_state ();
12799 char *reply;
12800 char *p;
12801 int rslt;
12802
12803 p = rs->buf;
12804 strcpy (p, "qTBuffer:");
12805 p += strlen (p);
12806 p += hexnumstr (p, offset);
12807 *p++ = ',';
12808 p += hexnumstr (p, len);
12809 *p++ = '\0';
12810
12811 putpkt (rs->buf);
12812 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12813 if (reply && *reply)
12814 {
12815 /* 'l' by itself means we're at the end of the buffer and
12816 there is nothing more to get. */
12817 if (*reply == 'l')
12818 return 0;
12819
12820 /* Convert the reply into binary. Limit the number of bytes to
12821 convert according to our passed-in buffer size, rather than
12822 what was returned in the packet; if the target is
12823 unexpectedly generous and gives us a bigger reply than we
12824 asked for, we don't want to crash. */
12825 rslt = hex2bin (target_buf, buf, len);
12826 return rslt;
12827 }
12828
12829 /* Something went wrong, flag as an error. */
12830 return -1;
12831}
12832
35b1e5cc 12833static void
37b25738 12834remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12835{
12836 struct remote_state *rs = get_remote_state ();
12837
4082afcc 12838 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12839 {
ad91cd99
PA
12840 char *reply;
12841
bba74b36 12842 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12843 putpkt (rs->buf);
ad91cd99
PA
12844 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12845 if (*reply == '\0')
33da3f1c 12846 error (_("Target does not support this command."));
ad91cd99
PA
12847 if (strcmp (reply, "OK") != 0)
12848 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12849 }
12850 else if (val)
12851 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12852}
12853
dc146f7c
VP
12854static int
12855remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12856{
12857 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12858
fe978cb0
PA
12859 if (info && info->priv)
12860 return info->priv->core;
dc146f7c
VP
12861 return -1;
12862}
12863
4daf5ac0 12864static void
736d5b1f 12865remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12866{
12867 struct remote_state *rs = get_remote_state ();
ad91cd99 12868 char *reply;
4daf5ac0 12869
bba74b36 12870 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12871 putpkt (rs->buf);
ad91cd99
PA
12872 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12873 if (*reply == '\0')
4daf5ac0 12874 error (_("Target does not support this command."));
ad91cd99
PA
12875 if (strcmp (reply, "OK") != 0)
12876 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12877}
12878
b3b9301e 12879static struct traceframe_info *
a893e81f 12880remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12881{
12882 char *text;
12883
12884 text = target_read_stralloc (&current_target,
12885 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12886 if (text != NULL)
12887 {
12888 struct traceframe_info *info;
12889 struct cleanup *back_to = make_cleanup (xfree, text);
12890
12891 info = parse_traceframe_info (text);
12892 do_cleanups (back_to);
12893 return info;
12894 }
12895
12896 return NULL;
12897}
12898
405f8e94
SS
12899/* Handle the qTMinFTPILen packet. Returns the minimum length of
12900 instruction on which a fast tracepoint may be placed. Returns -1
12901 if the packet is not supported, and 0 if the minimum instruction
12902 length is unknown. */
12903
12904static int
0e67620a 12905remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12906{
12907 struct remote_state *rs = get_remote_state ();
12908 char *reply;
12909
e886a173
PA
12910 /* If we're not debugging a process yet, the IPA can't be
12911 loaded. */
12912 if (!target_has_execution)
12913 return 0;
12914
12915 /* Make sure the remote is pointing at the right process. */
12916 set_general_process ();
12917
bba74b36 12918 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12919 putpkt (rs->buf);
12920 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12921 if (*reply == '\0')
12922 return -1;
12923 else
12924 {
12925 ULONGEST min_insn_len;
12926
12927 unpack_varlen_hex (reply, &min_insn_len);
12928
12929 return (int) min_insn_len;
12930 }
12931}
12932
f6f899bf 12933static void
4da384be 12934remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12935{
4082afcc 12936 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12937 {
12938 struct remote_state *rs = get_remote_state ();
12939 char *buf = rs->buf;
12940 char *endbuf = rs->buf + get_remote_packet_size ();
12941 enum packet_result result;
12942
12943 gdb_assert (val >= 0 || val == -1);
12944 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12945 /* Send -1 as literal "-1" to avoid host size dependency. */
12946 if (val < 0)
12947 {
12948 *buf++ = '-';
12949 buf += hexnumstr (buf, (ULONGEST) -val);
12950 }
12951 else
12952 buf += hexnumstr (buf, (ULONGEST) val);
12953
12954 putpkt (rs->buf);
12955 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12956 result = packet_ok (rs->buf,
12957 &remote_protocol_packets[PACKET_QTBuffer_size]);
12958
12959 if (result != PACKET_OK)
12960 warning (_("Bogus reply from target: %s"), rs->buf);
12961 }
12962}
12963
f196051f 12964static int
d9e68a2c
TT
12965remote_set_trace_notes (struct target_ops *self,
12966 const char *user, const char *notes,
ca623f82 12967 const char *stop_notes)
f196051f
SS
12968{
12969 struct remote_state *rs = get_remote_state ();
12970 char *reply;
12971 char *buf = rs->buf;
12972 char *endbuf = rs->buf + get_remote_packet_size ();
12973 int nbytes;
12974
12975 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12976 if (user)
12977 {
12978 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12979 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12980 buf += 2 * nbytes;
12981 *buf++ = ';';
12982 }
12983 if (notes)
12984 {
12985 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12986 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12987 buf += 2 * nbytes;
12988 *buf++ = ';';
12989 }
12990 if (stop_notes)
12991 {
12992 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12993 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12994 buf += 2 * nbytes;
12995 *buf++ = ';';
12996 }
12997 /* Ensure the buffer is terminated. */
12998 *buf = '\0';
12999
13000 putpkt (rs->buf);
13001 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
13002 if (*reply == '\0')
13003 return 0;
13004
13005 if (strcmp (reply, "OK") != 0)
13006 error (_("Bogus reply from target: %s"), reply);
13007
13008 return 1;
13009}
13010
d1feda86 13011static int
2c152180 13012remote_use_agent (struct target_ops *self, int use)
d1feda86 13013{
4082afcc 13014 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13015 {
13016 struct remote_state *rs = get_remote_state ();
13017
13018 /* If the stub supports QAgent. */
bba74b36 13019 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
13020 putpkt (rs->buf);
13021 getpkt (&rs->buf, &rs->buf_size, 0);
13022
13023 if (strcmp (rs->buf, "OK") == 0)
13024 {
13025 use_agent = use;
13026 return 1;
13027 }
13028 }
13029
13030 return 0;
13031}
13032
13033static int
fe38f897 13034remote_can_use_agent (struct target_ops *self)
d1feda86 13035{
4082afcc 13036 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13037}
13038
9accd112
MM
13039struct btrace_target_info
13040{
13041 /* The ptid of the traced thread. */
13042 ptid_t ptid;
f4abbc16
MM
13043
13044 /* The obtained branch trace configuration. */
13045 struct btrace_config conf;
9accd112
MM
13046};
13047
f4abbc16
MM
13048/* Reset our idea of our target's btrace configuration. */
13049
13050static void
13051remote_btrace_reset (void)
13052{
13053 struct remote_state *rs = get_remote_state ();
13054
13055 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13056}
13057
9accd112
MM
13058/* Check whether the target supports branch tracing. */
13059
13060static int
043c3577 13061remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 13062{
4082afcc 13063 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 13064 return 0;
4082afcc 13065 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
13066 return 0;
13067
043c3577
MM
13068 switch (format)
13069 {
13070 case BTRACE_FORMAT_NONE:
13071 return 0;
13072
13073 case BTRACE_FORMAT_BTS:
13074 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
13075
13076 case BTRACE_FORMAT_PT:
13077 /* The trace is decoded on the host. Even if our target supports it,
13078 we still need to have libipt to decode the trace. */
13079#if defined (HAVE_LIBIPT)
13080 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
13081#else /* !defined (HAVE_LIBIPT) */
13082 return 0;
13083#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
13084 }
13085
13086 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
13087}
13088
f4abbc16
MM
13089/* Synchronize the configuration with the target. */
13090
13091static void
13092btrace_sync_conf (const struct btrace_config *conf)
13093{
d33501a5
MM
13094 struct packet_config *packet;
13095 struct remote_state *rs;
13096 char *buf, *pos, *endbuf;
13097
13098 rs = get_remote_state ();
13099 buf = rs->buf;
13100 endbuf = buf + get_remote_packet_size ();
13101
13102 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13103 if (packet_config_support (packet) == PACKET_ENABLE
13104 && conf->bts.size != rs->btrace_config.bts.size)
13105 {
13106 pos = buf;
13107 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13108 conf->bts.size);
13109
13110 putpkt (buf);
13111 getpkt (&buf, &rs->buf_size, 0);
13112
13113 if (packet_ok (buf, packet) == PACKET_ERROR)
13114 {
13115 if (buf[0] == 'E' && buf[1] == '.')
13116 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13117 else
13118 error (_("Failed to configure the BTS buffer size."));
13119 }
13120
13121 rs->btrace_config.bts.size = conf->bts.size;
13122 }
b20a6524
MM
13123
13124 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13125 if (packet_config_support (packet) == PACKET_ENABLE
13126 && conf->pt.size != rs->btrace_config.pt.size)
13127 {
13128 pos = buf;
13129 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13130 conf->pt.size);
13131
13132 putpkt (buf);
13133 getpkt (&buf, &rs->buf_size, 0);
13134
13135 if (packet_ok (buf, packet) == PACKET_ERROR)
13136 {
13137 if (buf[0] == 'E' && buf[1] == '.')
13138 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13139 else
13140 error (_("Failed to configure the trace buffer size."));
13141 }
13142
13143 rs->btrace_config.pt.size = conf->pt.size;
13144 }
f4abbc16
MM
13145}
13146
13147/* Read the current thread's btrace configuration from the target and
13148 store it into CONF. */
13149
13150static void
13151btrace_read_config (struct btrace_config *conf)
13152{
13153 char *xml;
13154
13155 xml = target_read_stralloc (&current_target,
b20a6524 13156 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
13157 if (xml != NULL)
13158 {
13159 struct cleanup *cleanup;
13160
13161 cleanup = make_cleanup (xfree, xml);
13162 parse_xml_btrace_conf (conf, xml);
13163 do_cleanups (cleanup);
13164 }
13165}
13166
c0272db5
TW
13167/* Maybe reopen target btrace. */
13168
13169static void
13170remote_btrace_maybe_reopen (void)
13171{
13172 struct remote_state *rs = get_remote_state ();
c0272db5
TW
13173 struct thread_info *tp;
13174 int btrace_target_pushed = 0;
13175 int warned = 0;
13176
5ed8105e
PA
13177 scoped_restore_current_thread restore_thread;
13178
c0272db5
TW
13179 ALL_NON_EXITED_THREADS (tp)
13180 {
13181 set_general_thread (tp->ptid);
13182
13183 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13184 btrace_read_config (&rs->btrace_config);
13185
13186 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13187 continue;
13188
13189#if !defined (HAVE_LIBIPT)
13190 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13191 {
13192 if (!warned)
13193 {
13194 warned = 1;
13195 warning (_("GDB does not support Intel Processor Trace. "
13196 "\"record\" will not work in this session."));
13197 }
13198
13199 continue;
13200 }
13201#endif /* !defined (HAVE_LIBIPT) */
13202
13203 /* Push target, once, but before anything else happens. This way our
13204 changes to the threads will be cleaned up by unpushing the target
13205 in case btrace_read_config () throws. */
13206 if (!btrace_target_pushed)
13207 {
13208 btrace_target_pushed = 1;
13209 record_btrace_push_target ();
13210 printf_filtered (_("Target is recording using %s.\n"),
13211 btrace_format_string (rs->btrace_config.format));
13212 }
13213
13214 tp->btrace.target = XCNEW (struct btrace_target_info);
13215 tp->btrace.target->ptid = tp->ptid;
13216 tp->btrace.target->conf = rs->btrace_config;
13217 }
c0272db5
TW
13218}
13219
9accd112
MM
13220/* Enable branch tracing. */
13221
13222static struct btrace_target_info *
f4abbc16
MM
13223remote_enable_btrace (struct target_ops *self, ptid_t ptid,
13224 const struct btrace_config *conf)
9accd112
MM
13225{
13226 struct btrace_target_info *tinfo = NULL;
b20a6524 13227 struct packet_config *packet = NULL;
9accd112
MM
13228 struct remote_state *rs = get_remote_state ();
13229 char *buf = rs->buf;
13230 char *endbuf = rs->buf + get_remote_packet_size ();
13231
b20a6524
MM
13232 switch (conf->format)
13233 {
13234 case BTRACE_FORMAT_BTS:
13235 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13236 break;
13237
13238 case BTRACE_FORMAT_PT:
13239 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13240 break;
13241 }
13242
13243 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13244 error (_("Target does not support branch tracing."));
13245
f4abbc16
MM
13246 btrace_sync_conf (conf);
13247
9accd112
MM
13248 set_general_thread (ptid);
13249
13250 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13251 putpkt (rs->buf);
13252 getpkt (&rs->buf, &rs->buf_size, 0);
13253
13254 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13255 {
13256 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13257 error (_("Could not enable branch tracing for %s: %s"),
13258 target_pid_to_str (ptid), rs->buf + 2);
13259 else
13260 error (_("Could not enable branch tracing for %s."),
13261 target_pid_to_str (ptid));
13262 }
13263
8d749320 13264 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13265 tinfo->ptid = ptid;
13266
f4abbc16
MM
13267 /* If we fail to read the configuration, we lose some information, but the
13268 tracing itself is not impacted. */
492d29ea
PA
13269 TRY
13270 {
13271 btrace_read_config (&tinfo->conf);
13272 }
13273 CATCH (err, RETURN_MASK_ERROR)
13274 {
13275 if (err.message != NULL)
13276 warning ("%s", err.message);
13277 }
13278 END_CATCH
f4abbc16 13279
9accd112
MM
13280 return tinfo;
13281}
13282
13283/* Disable branch tracing. */
13284
13285static void
25e95349
TT
13286remote_disable_btrace (struct target_ops *self,
13287 struct btrace_target_info *tinfo)
9accd112
MM
13288{
13289 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13290 struct remote_state *rs = get_remote_state ();
13291 char *buf = rs->buf;
13292 char *endbuf = rs->buf + get_remote_packet_size ();
13293
4082afcc 13294 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13295 error (_("Target does not support branch tracing."));
13296
13297 set_general_thread (tinfo->ptid);
13298
13299 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13300 putpkt (rs->buf);
13301 getpkt (&rs->buf, &rs->buf_size, 0);
13302
13303 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13304 {
13305 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13306 error (_("Could not disable branch tracing for %s: %s"),
13307 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13308 else
13309 error (_("Could not disable branch tracing for %s."),
13310 target_pid_to_str (tinfo->ptid));
13311 }
13312
13313 xfree (tinfo);
13314}
13315
13316/* Teardown branch tracing. */
13317
13318static void
1777056d
TT
13319remote_teardown_btrace (struct target_ops *self,
13320 struct btrace_target_info *tinfo)
9accd112
MM
13321{
13322 /* We must not talk to the target during teardown. */
13323 xfree (tinfo);
13324}
13325
13326/* Read the branch trace. */
13327
969c39fb 13328static enum btrace_error
39c49f83 13329remote_read_btrace (struct target_ops *self,
734b0e4b 13330 struct btrace_data *btrace,
969c39fb 13331 struct btrace_target_info *tinfo,
9accd112
MM
13332 enum btrace_read_type type)
13333{
13334 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
969c39fb 13335 struct cleanup *cleanup;
9accd112
MM
13336 const char *annex;
13337 char *xml;
13338
4082afcc 13339 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13340 error (_("Target does not support branch tracing."));
13341
13342#if !defined(HAVE_LIBEXPAT)
13343 error (_("Cannot process branch tracing result. XML parsing not supported."));
13344#endif
13345
13346 switch (type)
13347 {
864089d2 13348 case BTRACE_READ_ALL:
9accd112
MM
13349 annex = "all";
13350 break;
864089d2 13351 case BTRACE_READ_NEW:
9accd112
MM
13352 annex = "new";
13353 break;
969c39fb
MM
13354 case BTRACE_READ_DELTA:
13355 annex = "delta";
13356 break;
9accd112
MM
13357 default:
13358 internal_error (__FILE__, __LINE__,
13359 _("Bad branch tracing read type: %u."),
13360 (unsigned int) type);
13361 }
13362
13363 xml = target_read_stralloc (&current_target,
b20a6524 13364 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
13365 if (xml == NULL)
13366 return BTRACE_ERR_UNKNOWN;
9accd112 13367
969c39fb 13368 cleanup = make_cleanup (xfree, xml);
734b0e4b 13369 parse_xml_btrace (btrace, xml);
969c39fb 13370 do_cleanups (cleanup);
9accd112 13371
969c39fb 13372 return BTRACE_ERR_NONE;
9accd112
MM
13373}
13374
f4abbc16
MM
13375static const struct btrace_config *
13376remote_btrace_conf (struct target_ops *self,
13377 const struct btrace_target_info *tinfo)
13378{
13379 return &tinfo->conf;
13380}
13381
ced63ec0 13382static int
5436ff03 13383remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 13384{
4082afcc
PA
13385 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13386 == PACKET_ENABLE);
ced63ec0
GB
13387}
13388
9dd130a0
TT
13389/* Implementation of to_load. */
13390
13391static void
9cbe5fff 13392remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
13393{
13394 generic_load (name, from_tty);
13395}
13396
c78fa86a
GB
13397/* Accepts an integer PID; returns a string representing a file that
13398 can be opened on the remote side to get the symbols for the child
13399 process. Returns NULL if the operation is not supported. */
13400
13401static char *
13402remote_pid_to_exec_file (struct target_ops *self, int pid)
13403{
13404 static char *filename = NULL;
835205d0
GB
13405 struct inferior *inf;
13406 char *annex = NULL;
c78fa86a
GB
13407
13408 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13409 return NULL;
13410
13411 if (filename != NULL)
13412 xfree (filename);
13413
835205d0
GB
13414 inf = find_inferior_pid (pid);
13415 if (inf == NULL)
13416 internal_error (__FILE__, __LINE__,
13417 _("not currently attached to process %d"), pid);
13418
13419 if (!inf->fake_pid_p)
13420 {
13421 const int annex_size = 9;
13422
224c3ddb 13423 annex = (char *) alloca (annex_size);
835205d0
GB
13424 xsnprintf (annex, annex_size, "%x", pid);
13425 }
13426
c78fa86a
GB
13427 filename = target_read_stralloc (&current_target,
13428 TARGET_OBJECT_EXEC_FILE, annex);
13429
13430 return filename;
13431}
13432
750ce8d1
YQ
13433/* Implement the to_can_do_single_step target_ops method. */
13434
13435static int
13436remote_can_do_single_step (struct target_ops *ops)
13437{
13438 /* We can only tell whether target supports single step or not by
13439 supported s and S vCont actions if the stub supports vContSupported
13440 feature. If the stub doesn't support vContSupported feature,
13441 we have conservatively to think target doesn't supports single
13442 step. */
13443 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13444 {
13445 struct remote_state *rs = get_remote_state ();
13446
13447 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13448 remote_vcont_probe (rs);
13449
13450 return rs->supports_vCont.s && rs->supports_vCont.S;
13451 }
13452 else
13453 return 0;
13454}
13455
3a00c802
PA
13456/* Implementation of the to_execution_direction method for the remote
13457 target. */
13458
13459static enum exec_direction_kind
13460remote_execution_direction (struct target_ops *self)
13461{
13462 struct remote_state *rs = get_remote_state ();
13463
13464 return rs->last_resume_exec_dir;
13465}
13466
c906108c 13467static void
fba45db2 13468init_remote_ops (void)
c906108c 13469{
c5aa993b 13470 remote_ops.to_shortname = "remote";
c906108c 13471 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 13472 remote_ops.to_doc =
c906108c 13473 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
13474Specify the serial device it is connected to\n\
13475(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
13476 remote_ops.to_open = remote_open;
13477 remote_ops.to_close = remote_close;
c906108c 13478 remote_ops.to_detach = remote_detach;
6ad8ae5c 13479 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 13480 remote_ops.to_resume = remote_resume;
85ad3aaf 13481 remote_ops.to_commit_resume = remote_commit_resume;
c906108c
SS
13482 remote_ops.to_wait = remote_wait;
13483 remote_ops.to_fetch_registers = remote_fetch_registers;
13484 remote_ops.to_store_registers = remote_store_registers;
13485 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 13486 remote_ops.to_files_info = remote_files_info;
c906108c
SS
13487 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13488 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
13489 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13490 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13491 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13492 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
13493 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13494 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
13495 remote_ops.to_watchpoint_addr_within_range =
13496 remote_watchpoint_addr_within_range;
3c3bea1c
GS
13497 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13498 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13499 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
13500 remote_ops.to_region_ok_for_hw_watchpoint
13501 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
13502 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13503 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 13504 remote_ops.to_kill = remote_kill;
9dd130a0 13505 remote_ops.to_load = remote_load;
c906108c 13506 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 13507 remote_ops.to_pass_signals = remote_pass_signals;
82075af2 13508 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
9b224c5e 13509 remote_ops.to_program_signals = remote_program_signals;
c906108c 13510 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 13511 remote_ops.to_thread_name = remote_thread_name;
e8032dde 13512 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 13513 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 13514 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 13515 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 13516 remote_ops.to_stop = remote_stop;
bfedc46a 13517 remote_ops.to_interrupt = remote_interrupt;
93692b58 13518 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
4b8a223f 13519 remote_ops.to_xfer_partial = remote_xfer_partial;
09c98b44 13520 remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
96baa820 13521 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 13522 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 13523 remote_ops.to_log_command = serial_log_command;
38691318 13524 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 13525 remote_ops.to_stratum = process_stratum;
c35b1492
PA
13526 remote_ops.to_has_all_memory = default_child_has_all_memory;
13527 remote_ops.to_has_memory = default_child_has_memory;
13528 remote_ops.to_has_stack = default_child_has_stack;
13529 remote_ops.to_has_registers = default_child_has_registers;
13530 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 13531 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13532 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13533 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13534 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13535 remote_ops.to_flash_erase = remote_flash_erase;
13536 remote_ops.to_flash_done = remote_flash_done;
29709017 13537 remote_ops.to_read_description = remote_read_description;
08388c79 13538 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13539 remote_ops.to_can_async_p = remote_can_async_p;
13540 remote_ops.to_is_async_p = remote_is_async_p;
13541 remote_ops.to_async = remote_async;
65706a29 13542 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13543 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13544 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13545 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13546 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13547 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13548 remote_ops.to_supports_disable_randomization
13549 = remote_supports_disable_randomization;
4bd7dc42 13550 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13551 remote_ops.to_fileio_open = remote_hostio_open;
13552 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13553 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13554 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13555 remote_ops.to_fileio_close = remote_hostio_close;
13556 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13557 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13558 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13559 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13560 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13561 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13562 remote_ops.to_trace_init = remote_trace_init;
13563 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13564 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13565 remote_ops.to_download_trace_state_variable
13566 = remote_download_trace_state_variable;
d248b706
KY
13567 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13568 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13569 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13570 remote_ops.to_trace_start = remote_trace_start;
13571 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13572 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13573 remote_ops.to_trace_stop = remote_trace_stop;
13574 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13575 remote_ops.to_get_trace_state_variable_value
13576 = remote_get_trace_state_variable_value;
00bf0b85
SS
13577 remote_ops.to_save_trace_data = remote_save_trace_data;
13578 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13579 remote_ops.to_upload_trace_state_variables
13580 = remote_upload_trace_state_variables;
00bf0b85 13581 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13582 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13583 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13584 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13585 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13586 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13587 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13588 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13589 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13590 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13591 remote_ops.to_static_tracepoint_marker_at
13592 = remote_static_tracepoint_marker_at;
13593 remote_ops.to_static_tracepoint_markers_by_strid
13594 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13595 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13596 remote_ops.to_use_agent = remote_use_agent;
13597 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13598 remote_ops.to_supports_btrace = remote_supports_btrace;
13599 remote_ops.to_enable_btrace = remote_enable_btrace;
13600 remote_ops.to_disable_btrace = remote_disable_btrace;
13601 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13602 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13603 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13604 remote_ops.to_augmented_libraries_svr4_read =
13605 remote_augmented_libraries_svr4_read;
8020350c
DB
13606 remote_ops.to_follow_fork = remote_follow_fork;
13607 remote_ops.to_follow_exec = remote_follow_exec;
13608 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13609 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13610 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13611 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13612 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13613 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
3a00c802 13614 remote_ops.to_execution_direction = remote_execution_direction;
c906108c
SS
13615}
13616
13617/* Set up the extended remote vector by making a copy of the standard
13618 remote vector and adding to it. */
13619
13620static void
fba45db2 13621init_extended_remote_ops (void)
c906108c
SS
13622{
13623 extended_remote_ops = remote_ops;
13624
0f71a2f6 13625 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13626 extended_remote_ops.to_longname =
c906108c 13627 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13628 extended_remote_ops.to_doc =
c906108c 13629 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13630Specify the serial device it is connected to (e.g. /dev/ttya).";
13631 extended_remote_ops.to_open = extended_remote_open;
c906108c 13632 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
2d717e4f
DJ
13633 extended_remote_ops.to_detach = extended_remote_detach;
13634 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13635 extended_remote_ops.to_post_attach = extended_remote_post_attach;
03583c20
UW
13636 extended_remote_ops.to_supports_disable_randomization
13637 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
13638}
13639
6426a772 13640static int
6a109b6b 13641remote_can_async_p (struct target_ops *ops)
6426a772 13642{
5d93a237
TT
13643 struct remote_state *rs = get_remote_state ();
13644
3015c064
SM
13645 /* We don't go async if the user has explicitly prevented it with the
13646 "maint set target-async" command. */
c6ebd6cf 13647 if (!target_async_permitted)
75c99385
PA
13648 return 0;
13649
23860348 13650 /* We're async whenever the serial device is. */
5d93a237 13651 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13652}
13653
13654static int
6a109b6b 13655remote_is_async_p (struct target_ops *ops)
6426a772 13656{
5d93a237
TT
13657 struct remote_state *rs = get_remote_state ();
13658
c6ebd6cf 13659 if (!target_async_permitted)
75c99385
PA
13660 /* We only enable async when the user specifically asks for it. */
13661 return 0;
13662
23860348 13663 /* We're async whenever the serial device is. */
5d93a237 13664 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13665}
13666
2acceee2
JM
13667/* Pass the SERIAL event on and up to the client. One day this code
13668 will be able to delay notifying the client of an event until the
23860348 13669 point where an entire packet has been received. */
2acceee2 13670
2acceee2
JM
13671static serial_event_ftype remote_async_serial_handler;
13672
6426a772 13673static void
819cc324 13674remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13675{
2acceee2
JM
13676 /* Don't propogate error information up to the client. Instead let
13677 the client find out about the error by querying the target. */
6a3753b3 13678 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13679}
13680
74531fed
PA
13681static void
13682remote_async_inferior_event_handler (gdb_client_data data)
13683{
13684 inferior_event_handler (INF_REG_EVENT, NULL);
13685}
13686
2acceee2 13687static void
6a3753b3 13688remote_async (struct target_ops *ops, int enable)
2acceee2 13689{
5d93a237
TT
13690 struct remote_state *rs = get_remote_state ();
13691
6a3753b3 13692 if (enable)
2acceee2 13693 {
88b496c3 13694 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13695
13696 /* If there are pending events in the stop reply queue tell the
13697 event loop to process them. */
13698 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13699 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13700 /* For simplicity, below we clear the pending events token
13701 without remembering whether it is marked, so here we always
13702 mark it. If there's actually no pending notification to
13703 process, this ends up being a no-op (other than a spurious
13704 event-loop wakeup). */
13705 if (target_is_non_stop_p ())
13706 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13707 }
13708 else
b7d2e916
PA
13709 {
13710 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13711 /* If the core is disabling async, it doesn't want to be
13712 disturbed with target events. Clear all async event sources
13713 too. */
b7d2e916 13714 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13715 if (target_is_non_stop_p ())
13716 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13717 }
6426a772
JM
13718}
13719
65706a29
PA
13720/* Implementation of the to_thread_events method. */
13721
13722static void
13723remote_thread_events (struct target_ops *ops, int enable)
13724{
13725 struct remote_state *rs = get_remote_state ();
13726 size_t size = get_remote_packet_size ();
65706a29
PA
13727
13728 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13729 return;
13730
13731 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13732 putpkt (rs->buf);
13733 getpkt (&rs->buf, &rs->buf_size, 0);
13734
13735 switch (packet_ok (rs->buf,
13736 &remote_protocol_packets[PACKET_QThreadEvents]))
13737 {
13738 case PACKET_OK:
13739 if (strcmp (rs->buf, "OK") != 0)
13740 error (_("Remote refused setting thread events: %s"), rs->buf);
13741 break;
13742 case PACKET_ERROR:
13743 warning (_("Remote failure reply: %s"), rs->buf);
13744 break;
13745 case PACKET_UNKNOWN:
13746 break;
13747 }
13748}
13749
5a2468f5 13750static void
c2d11a7d 13751set_remote_cmd (char *args, int from_tty)
5a2468f5 13752{
635c7e8a 13753 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13754}
13755
d471ea57
AC
13756static void
13757show_remote_cmd (char *args, int from_tty)
13758{
37a105a1 13759 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13760 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1 13761 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13762 struct ui_out *uiout = current_uiout;
37a105a1 13763
2e783024 13764 ui_out_emit_tuple tuple_emitter (uiout, "showlist");
37a105a1
DJ
13765 for (; list != NULL; list = list->next)
13766 if (strcmp (list->name, "Z-packet") == 0)
13767 continue;
427c3a89
DJ
13768 else if (list->type == not_set_cmd)
13769 /* Alias commands are exactly like the original, except they
13770 don't have the normal type. */
13771 continue;
13772 else
37a105a1 13773 {
2e783024 13774 ui_out_emit_tuple option_emitter (uiout, "option");
a744cf53 13775
112e8700
SM
13776 uiout->field_string ("name", list->name);
13777 uiout->text (": ");
427c3a89 13778 if (list->type == show_cmd)
f5c4fcd9 13779 do_show_command (NULL, from_tty, list);
427c3a89
DJ
13780 else
13781 cmd_func (list, NULL, from_tty);
37a105a1 13782 }
d471ea57 13783}
5a2468f5 13784
0f71a2f6 13785
23860348 13786/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13787static void
13788remote_new_objfile (struct objfile *objfile)
13789{
5d93a237
TT
13790 struct remote_state *rs = get_remote_state ();
13791
13792 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13793 remote_check_symbols ();
dc8acb97
MS
13794}
13795
00bf0b85
SS
13796/* Pull all the tracepoints defined on the target and create local
13797 data structures representing them. We don't want to create real
13798 tracepoints yet, we don't want to mess up the user's existing
13799 collection. */
13800
13801static int
ab6617cc 13802remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13803{
00bf0b85
SS
13804 struct remote_state *rs = get_remote_state ();
13805 char *p;
d5551862 13806
00bf0b85
SS
13807 /* Ask for a first packet of tracepoint definition. */
13808 putpkt ("qTfP");
13809 getpkt (&rs->buf, &rs->buf_size, 0);
13810 p = rs->buf;
13811 while (*p && *p != 'l')
d5551862 13812 {
00bf0b85
SS
13813 parse_tracepoint_definition (p, utpp);
13814 /* Ask for another packet of tracepoint definition. */
13815 putpkt ("qTsP");
13816 getpkt (&rs->buf, &rs->buf_size, 0);
13817 p = rs->buf;
d5551862 13818 }
00bf0b85 13819 return 0;
d5551862
SS
13820}
13821
00bf0b85 13822static int
181e3713
TT
13823remote_upload_trace_state_variables (struct target_ops *self,
13824 struct uploaded_tsv **utsvp)
d5551862 13825{
00bf0b85 13826 struct remote_state *rs = get_remote_state ();
d5551862 13827 char *p;
d5551862 13828
00bf0b85
SS
13829 /* Ask for a first packet of variable definition. */
13830 putpkt ("qTfV");
d5551862
SS
13831 getpkt (&rs->buf, &rs->buf_size, 0);
13832 p = rs->buf;
00bf0b85 13833 while (*p && *p != 'l')
d5551862 13834 {
00bf0b85
SS
13835 parse_tsv_definition (p, utsvp);
13836 /* Ask for another packet of variable definition. */
13837 putpkt ("qTsV");
d5551862
SS
13838 getpkt (&rs->buf, &rs->buf_size, 0);
13839 p = rs->buf;
13840 }
00bf0b85 13841 return 0;
d5551862
SS
13842}
13843
c1e36e3e
PA
13844/* The "set/show range-stepping" show hook. */
13845
13846static void
13847show_range_stepping (struct ui_file *file, int from_tty,
13848 struct cmd_list_element *c,
13849 const char *value)
13850{
13851 fprintf_filtered (file,
13852 _("Debugger's willingness to use range stepping "
13853 "is %s.\n"), value);
13854}
13855
13856/* The "set/show range-stepping" set hook. */
13857
13858static void
13859set_range_stepping (char *ignore_args, int from_tty,
13860 struct cmd_list_element *c)
13861{
5d93a237
TT
13862 struct remote_state *rs = get_remote_state ();
13863
c1e36e3e
PA
13864 /* Whene enabling, check whether range stepping is actually
13865 supported by the target, and warn if not. */
13866 if (use_range_stepping)
13867 {
5d93a237 13868 if (rs->remote_desc != NULL)
c1e36e3e 13869 {
4082afcc 13870 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13871 remote_vcont_probe (rs);
13872
4082afcc 13873 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13874 && rs->supports_vCont.r)
13875 return;
13876 }
13877
13878 warning (_("Range stepping is not supported by the current target"));
13879 }
13880}
13881
c906108c 13882void
fba45db2 13883_initialize_remote (void)
c906108c 13884{
9a7071a8 13885 struct cmd_list_element *cmd;
6f937416 13886 const char *cmd_name;
ea9c271d 13887
0f71a2f6 13888 /* architecture specific data */
2bc416ba 13889 remote_gdbarch_data_handle =
23860348 13890 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13891 remote_g_packet_data_handle =
13892 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13893
94585166
DB
13894 remote_pspace_data
13895 = register_program_space_data_with_cleanup (NULL,
13896 remote_pspace_data_cleanup);
13897
ea9c271d
DJ
13898 /* Initialize the per-target state. At the moment there is only one
13899 of these, not one per target. Only one target is active at a
cf792862
TT
13900 time. */
13901 remote_state = new_remote_state ();
ea9c271d 13902
c906108c
SS
13903 init_remote_ops ();
13904 add_target (&remote_ops);
13905
13906 init_extended_remote_ops ();
13907 add_target (&extended_remote_ops);
cce74817 13908
dc8acb97 13909 /* Hook into new objfile notification. */
06d3b283 13910 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13911 /* We're no longer interested in notification events of an inferior
13912 when it exits. */
13913 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13914
c906108c
SS
13915#if 0
13916 init_remote_threadtests ();
13917#endif
13918
722247f1 13919 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13920 /* set/show remote ... */
d471ea57 13921
1bedd215 13922 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13923Remote protocol specific variables\n\
13924Configure various remote-protocol specific variables such as\n\
1bedd215 13925the packets being used"),
cff3e48b 13926 &remote_set_cmdlist, "set remote ",
23860348 13927 0 /* allow-unknown */, &setlist);
1bedd215 13928 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13929Remote protocol specific variables\n\
13930Configure various remote-protocol specific variables such as\n\
1bedd215 13931the packets being used"),
cff3e48b 13932 &remote_show_cmdlist, "show remote ",
23860348 13933 0 /* allow-unknown */, &showlist);
5a2468f5 13934
1a966eab
AC
13935 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13936Compare section data on target to the exec file.\n\
95cf3b38
DT
13937Argument is a single section name (default: all loaded sections).\n\
13938To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13939 &cmdlist);
13940
1a966eab
AC
13941 add_cmd ("packet", class_maintenance, packet_command, _("\
13942Send an arbitrary packet to a remote target.\n\
c906108c
SS
13943 maintenance packet TEXT\n\
13944If GDB is talking to an inferior via the GDB serial protocol, then\n\
13945this command sends the string TEXT to the inferior, and displays the\n\
13946response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13947terminating `#' character and checksum."),
c906108c
SS
13948 &maintenancelist);
13949
7915a72c
AC
13950 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13951Set whether to send break if interrupted."), _("\
13952Show whether to send break if interrupted."), _("\
13953If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13954 set_remotebreak, show_remotebreak,
e707bbc2 13955 &setlist, &showlist);
9a7071a8
JB
13956 cmd_name = "remotebreak";
13957 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13958 deprecate_cmd (cmd, "set remote interrupt-sequence");
13959 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13960 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13961 deprecate_cmd (cmd, "show remote interrupt-sequence");
13962
13963 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13964 interrupt_sequence_modes, &interrupt_sequence_mode,
13965 _("\
9a7071a8
JB
13966Set interrupt sequence to remote target."), _("\
13967Show interrupt sequence to remote target."), _("\
13968Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13969 NULL, show_interrupt_sequence,
13970 &remote_set_cmdlist,
13971 &remote_show_cmdlist);
13972
13973 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13974 &interrupt_on_connect, _("\
13975Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13976Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13977If set, interrupt sequence is sent to remote target."),
13978 NULL, NULL,
13979 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13980
23860348 13981 /* Install commands for configuring memory read/write packets. */
11cf8741 13982
1a966eab
AC
13983 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13984Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13985 &setlist);
1a966eab
AC
13986 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13987Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13988 &showlist);
13989 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13990 set_memory_write_packet_size, _("\
13991Set the maximum number of bytes per memory-write packet.\n\
13992Specify the number of bytes in a packet or 0 (zero) for the\n\
13993default packet size. The actual limit is further reduced\n\
13994dependent on the target. Specify ``fixed'' to disable the\n\
13995further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13996 &remote_set_cmdlist);
13997 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13998 set_memory_read_packet_size, _("\
13999Set the maximum number of bytes per memory-read packet.\n\
14000Specify the number of bytes in a packet or 0 (zero) for the\n\
14001default packet size. The actual limit is further reduced\n\
14002dependent on the target. Specify ``fixed'' to disable the\n\
14003further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14004 &remote_set_cmdlist);
14005 add_cmd ("memory-write-packet-size", no_class,
14006 show_memory_write_packet_size,
1a966eab 14007 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14008 &remote_show_cmdlist);
14009 add_cmd ("memory-read-packet-size", no_class,
14010 show_memory_read_packet_size,
1a966eab 14011 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14012 &remote_show_cmdlist);
c906108c 14013
b3f42336 14014 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14015 &remote_hw_watchpoint_limit, _("\
14016Set the maximum number of target hardware watchpoints."), _("\
14017Show the maximum number of target hardware watchpoints."), _("\
14018Specify a negative limit for unlimited."),
3e43a32a
MS
14019 NULL, NULL, /* FIXME: i18n: The maximum
14020 number of target hardware
14021 watchpoints is %s. */
b3f42336 14022 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
14023 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14024 &remote_hw_watchpoint_length_limit, _("\
14025Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14026Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14027Specify a negative limit for unlimited."),
14028 NULL, NULL, /* FIXME: i18n: The maximum
14029 length (in bytes) of a target
14030 hardware watchpoint is %s. */
14031 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 14032 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14033 &remote_hw_breakpoint_limit, _("\
14034Set the maximum number of target hardware breakpoints."), _("\
14035Show the maximum number of target hardware breakpoints."), _("\
14036Specify a negative limit for unlimited."),
3e43a32a
MS
14037 NULL, NULL, /* FIXME: i18n: The maximum
14038 number of target hardware
14039 breakpoints is %s. */
b3f42336 14040 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14041
1b493192
PA
14042 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14043 &remote_address_size, _("\
4d28ad1e
AC
14044Set the maximum size of the address (in bits) in a memory packet."), _("\
14045Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14046 NULL,
14047 NULL, /* FIXME: i18n: */
14048 &setlist, &showlist);
c906108c 14049
ca4f7f8b
PA
14050 init_all_packet_configs ();
14051
444abaca 14052 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14053 "X", "binary-download", 1);
0f71a2f6 14054
444abaca 14055 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14056 "vCont", "verbose-resume", 0);
506fb367 14057
89be2091
DJ
14058 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14059 "QPassSignals", "pass-signals", 0);
14060
82075af2
JS
14061 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14062 "QCatchSyscalls", "catch-syscalls", 0);
14063
9b224c5e
PA
14064 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14065 "QProgramSignals", "program-signals", 0);
14066
aefd8b33
SDJ
14067 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14068 "QStartupWithShell", "startup-with-shell", 0);
14069
444abaca 14070 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14071 "qSymbol", "symbol-lookup", 0);
dc8acb97 14072
444abaca 14073 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14074 "P", "set-register", 1);
d471ea57 14075
444abaca 14076 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14077 "p", "fetch-register", 1);
b96ec7ac 14078
444abaca 14079 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14080 "Z0", "software-breakpoint", 0);
d471ea57 14081
444abaca 14082 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14083 "Z1", "hardware-breakpoint", 0);
d471ea57 14084
444abaca 14085 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14086 "Z2", "write-watchpoint", 0);
d471ea57 14087
444abaca 14088 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14089 "Z3", "read-watchpoint", 0);
d471ea57 14090
444abaca 14091 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14092 "Z4", "access-watchpoint", 0);
d471ea57 14093
0876f84a
DJ
14094 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14095 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14096
c78fa86a
GB
14097 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14098 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14099
23181151
DJ
14100 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14101 "qXfer:features:read", "target-features", 0);
14102
cfa9d6d9
DJ
14103 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14104 "qXfer:libraries:read", "library-info", 0);
14105
2268b414
JK
14106 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14107 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14108
fd79ecee
DJ
14109 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14110 "qXfer:memory-map:read", "memory-map", 0);
14111
0e7f50da
UW
14112 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14113 "qXfer:spu:read", "read-spu-object", 0);
14114
14115 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14116 "qXfer:spu:write", "write-spu-object", 0);
14117
07e059b5
VP
14118 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14119 "qXfer:osdata:read", "osdata", 0);
14120
dc146f7c
VP
14121 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14122 "qXfer:threads:read", "threads", 0);
14123
4aa995e1
PA
14124 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14125 "qXfer:siginfo:read", "read-siginfo-object", 0);
14126
14127 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14128 "qXfer:siginfo:write", "write-siginfo-object", 0);
14129
b3b9301e
PA
14130 add_packet_config_cmd
14131 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14132 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14133
169081d0
TG
14134 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14135 "qXfer:uib:read", "unwind-info-block", 0);
14136
444abaca 14137 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14138 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14139 0);
14140
711e434b
PM
14141 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14142 "qGetTIBAddr", "get-thread-information-block-address",
14143 0);
14144
40ab02ce
MS
14145 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14146 "bc", "reverse-continue", 0);
14147
14148 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14149 "bs", "reverse-step", 0);
14150
be2a5f71
DJ
14151 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14152 "qSupported", "supported-packets", 0);
14153
08388c79
DE
14154 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14155 "qSearch:memory", "search-memory", 0);
14156
bd3eecc3
PA
14157 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14158 "qTStatus", "trace-status", 0);
14159
15a201c8
GB
14160 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14161 "vFile:setfs", "hostio-setfs", 0);
14162
a6b151f1
DJ
14163 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14164 "vFile:open", "hostio-open", 0);
14165
14166 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14167 "vFile:pread", "hostio-pread", 0);
14168
14169 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14170 "vFile:pwrite", "hostio-pwrite", 0);
14171
14172 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14173 "vFile:close", "hostio-close", 0);
14174
14175 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14176 "vFile:unlink", "hostio-unlink", 0);
14177
b9e7b9c3
UW
14178 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14179 "vFile:readlink", "hostio-readlink", 0);
14180
0a93529c
GB
14181 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14182 "vFile:fstat", "hostio-fstat", 0);
14183
2d717e4f
DJ
14184 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14185 "vAttach", "attach", 0);
14186
14187 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14188 "vRun", "run", 0);
14189
a6f3e723
SL
14190 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14191 "QStartNoAckMode", "noack", 0);
14192
82f73884
PA
14193 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14194 "vKill", "kill", 0);
14195
0b16c5cf
PA
14196 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14197 "qAttached", "query-attached", 0);
14198
782b2b07 14199 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14200 "ConditionalTracepoints",
14201 "conditional-tracepoints", 0);
3788aec7
LM
14202
14203 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14204 "ConditionalBreakpoints",
14205 "conditional-breakpoints", 0);
14206
d3ce09f5
SS
14207 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14208 "BreakpointCommands",
14209 "breakpoint-commands", 0);
14210
7a697b8d
SS
14211 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14212 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14213
409873ef
SS
14214 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14215 "TracepointSource", "TracepointSource", 0);
14216
d914c394
SS
14217 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14218 "QAllow", "allow", 0);
14219
0fb4aa4b
PA
14220 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14221 "StaticTracepoints", "static-tracepoints", 0);
14222
1e4d1764
YQ
14223 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14224 "InstallInTrace", "install-in-trace", 0);
14225
0fb4aa4b
PA
14226 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14227 "qXfer:statictrace:read", "read-sdata-object", 0);
14228
78d85199
YQ
14229 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14230 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14231
03583c20
UW
14232 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14233 "QDisableRandomization", "disable-randomization", 0);
14234
d1feda86
YQ
14235 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14236 "QAgent", "agent", 0);
14237
f6f899bf
HAQ
14238 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14239 "QTBuffer:size", "trace-buffer-size", 0);
14240
9accd112
MM
14241 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14242 "Qbtrace:off", "disable-btrace", 0);
14243
14244 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14245 "Qbtrace:bts", "enable-btrace-bts", 0);
14246
14247 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14248 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14249
14250 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14251 "qXfer:btrace", "read-btrace", 0);
14252
f4abbc16
MM
14253 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14254 "qXfer:btrace-conf", "read-btrace-conf", 0);
14255
d33501a5
MM
14256 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14257 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14258
73b8c1fd
PA
14259 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14260 "multiprocess-feature", "multiprocess-feature", 0);
14261
f7e6eed5
PA
14262 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14263 "swbreak-feature", "swbreak-feature", 0);
14264
14265 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14266 "hwbreak-feature", "hwbreak-feature", 0);
14267
89245bc0
DB
14268 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14269 "fork-event-feature", "fork-event-feature", 0);
14270
14271 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14272 "vfork-event-feature", "vfork-event-feature", 0);
14273
b20a6524
MM
14274 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14275 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14276
750ce8d1
YQ
14277 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14278 "vContSupported", "verbose-resume-supported", 0);
14279
94585166
DB
14280 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14281 "exec-event-feature", "exec-event-feature", 0);
14282
de979965
PA
14283 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14284 "vCtrlC", "ctrl-c", 0);
14285
65706a29
PA
14286 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14287 "QThreadEvents", "thread-events", 0);
14288
f2faf941
PA
14289 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14290 "N stop reply", "no-resumed-stop-reply", 0);
14291
0b736949
DB
14292 /* Assert that we've registered "set remote foo-packet" commands
14293 for all packet configs. */
ca4f7f8b
PA
14294 {
14295 int i;
14296
14297 for (i = 0; i < PACKET_MAX; i++)
14298 {
14299 /* Ideally all configs would have a command associated. Some
14300 still don't though. */
14301 int excepted;
14302
14303 switch (i)
14304 {
14305 case PACKET_QNonStop:
ca4f7f8b
PA
14306 case PACKET_EnableDisableTracepoints_feature:
14307 case PACKET_tracenz_feature:
14308 case PACKET_DisconnectedTracing_feature:
14309 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14310 case PACKET_qCRC:
14311 /* Additions to this list need to be well justified:
14312 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14313 excepted = 1;
14314 break;
14315 default:
14316 excepted = 0;
14317 break;
14318 }
14319
14320 /* This catches both forgetting to add a config command, and
14321 forgetting to remove a packet from the exception list. */
14322 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14323 }
14324 }
14325
37a105a1
DJ
14326 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14327 Z sub-packet has its own set and show commands, but users may
14328 have sets to this variable in their .gdbinit files (or in their
14329 documentation). */
e9e68a56 14330 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14331 &remote_Z_packet_detect, _("\
14332Set use of remote protocol `Z' packets"), _("\
14333Show use of remote protocol `Z' packets "), _("\
3b64bf98 14334When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14335packets."),
e9e68a56 14336 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14337 show_remote_protocol_Z_packet_cmd,
14338 /* FIXME: i18n: Use of remote protocol
14339 `Z' packets is %s. */
e9e68a56 14340 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14341
a6b151f1
DJ
14342 add_prefix_cmd ("remote", class_files, remote_command, _("\
14343Manipulate files on the remote system\n\
14344Transfer files to and from the remote target system."),
14345 &remote_cmdlist, "remote ",
14346 0 /* allow-unknown */, &cmdlist);
14347
14348 add_cmd ("put", class_files, remote_put_command,
14349 _("Copy a local file to the remote system."),
14350 &remote_cmdlist);
14351
14352 add_cmd ("get", class_files, remote_get_command,
14353 _("Copy a remote file to the local system."),
14354 &remote_cmdlist);
14355
14356 add_cmd ("delete", class_files, remote_delete_command,
14357 _("Delete a remote file."),
14358 &remote_cmdlist);
14359
2d717e4f 14360 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14361 &remote_exec_file_var, _("\
2d717e4f 14362Set the remote pathname for \"run\""), _("\
94585166
DB
14363Show the remote pathname for \"run\""), NULL,
14364 set_remote_exec_file,
14365 show_remote_exec_file,
14366 &remote_set_cmdlist,
14367 &remote_show_cmdlist);
2d717e4f 14368
c1e36e3e
PA
14369 add_setshow_boolean_cmd ("range-stepping", class_run,
14370 &use_range_stepping, _("\
14371Enable or disable range stepping."), _("\
14372Show whether target-assisted range stepping is enabled."), _("\
14373If on, and the target supports it, when stepping a source line, GDB\n\
14374tells the target to step the corresponding range of addresses itself instead\n\
14375of issuing multiple single-steps. This speeds up source level\n\
14376stepping. If off, GDB always issues single-steps, even if range\n\
14377stepping is supported by the target. The default is on."),
14378 set_range_stepping,
14379 show_range_stepping,
14380 &setlist,
14381 &showlist);
14382
449092f6
CV
14383 /* Eventually initialize fileio. See fileio.c */
14384 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14385
ba348170 14386 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14387 special ptids with it set to != 0. */
ba348170
PA
14388 magic_null_ptid = ptid_build (42000, -1, 1);
14389 not_sent_ptid = ptid_build (42000, -2, 1);
14390 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
14391
14392 target_buf_size = 2048;
224c3ddb 14393 target_buf = (char *) xmalloc (target_buf_size);
c906108c 14394}
10760264 14395
This page took 3.208595 seconds and 4 git commands to generate.