Fix dwarf_expr_context method regressions
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
618f726f 3 Copyright (C) 1988-2016 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>
35b1e5cc 75
0df8b418 76/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
77static char *target_buf;
78static long target_buf_size;
35b1e5cc 79
94585166
DB
80/* Per-program-space data key. */
81static const struct program_space_data *remote_pspace_data;
82
83/* The variable registered as the control variable used by the
84 remote exec-file commands. While the remote exec-file setting is
85 per-program-space, the set/show machinery uses this as the
86 location of the remote exec-file value. */
87static char *remote_exec_file_var;
88
6765f3e5
DJ
89/* The size to align memory write packets, when practical. The protocol
90 does not guarantee any alignment, and gdb will generate short
91 writes and unaligned writes, but even as a best-effort attempt this
92 can improve bulk transfers. For instance, if a write is misaligned
93 relative to the target's data bus, the stub may need to make an extra
94 round trip fetching data from the target. This doesn't make a
95 huge difference, but it's easy to do, so we try to be helpful.
96
97 The alignment chosen is arbitrary; usually data bus width is
98 important here, not the possibly larger cache line size. */
99enum { REMOTE_ALIGN_WRITES = 16 };
100
23860348 101/* Prototypes for local functions. */
6d820c5c 102static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 103static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 104 int forever, int *is_notif);
6426a772 105
a14ed312 106static void remote_files_info (struct target_ops *ignore);
c906108c 107
f32dbf8c
MM
108static void remote_prepare_to_store (struct target_ops *self,
109 struct regcache *regcache);
c906108c 110
014f9477
TT
111static void remote_open_1 (const char *, int, struct target_ops *,
112 int extended_p);
c906108c 113
de90e03d 114static void remote_close (struct target_ops *self);
c906108c 115
cbb8991c
DB
116struct remote_state;
117
118static int remote_vkill (int pid, struct remote_state *rs);
119
8020350c
DB
120static void remote_kill_k (void);
121
136d6dae 122static void remote_mourn (struct target_ops *ops);
c906108c 123
a14ed312 124static void extended_remote_restart (void);
c906108c 125
6d820c5c 126static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 127
a14ed312 128static int readchar (int timeout);
c906108c 129
c33e31fd
PA
130static void remote_serial_write (const char *str, int len);
131
7d85a9c0 132static void remote_kill (struct target_ops *ops);
c906108c 133
6a109b6b 134static int remote_can_async_p (struct target_ops *);
75c99385 135
6a109b6b 136static int remote_is_async_p (struct target_ops *);
75c99385 137
6a3753b3 138static void remote_async (struct target_ops *ops, int enable);
75c99385 139
65706a29
PA
140static void remote_thread_events (struct target_ops *ops, int enable);
141
a14ed312 142static void interrupt_query (void);
c906108c 143
79d7f229
PA
144static void set_general_thread (struct ptid ptid);
145static void set_continue_thread (struct ptid ptid);
c906108c 146
a14ed312 147static void get_offsets (void);
c906108c 148
6d820c5c
DJ
149static void skip_frame (void);
150
151static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 152
a14ed312 153static int hexnumlen (ULONGEST num);
c906108c 154
a14ed312 155static void init_remote_ops (void);
c906108c 156
a14ed312 157static void init_extended_remote_ops (void);
c906108c 158
1eab8a48 159static void remote_stop (struct target_ops *self, ptid_t);
c906108c 160
a14ed312 161static int stubhex (int ch);
c906108c 162
a14ed312 163static int hexnumstr (char *, ULONGEST);
c906108c 164
a14ed312 165static int hexnumnstr (char *, ULONGEST, int);
2df3850c 166
a14ed312 167static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 168
baa336ce 169static void print_packet (const char *);
c906108c 170
a14ed312 171static void compare_sections_command (char *, int);
c906108c 172
a14ed312 173static void packet_command (char *, int);
c906108c 174
a14ed312 175static int stub_unpack_int (char *buff, int fieldlength);
c906108c 176
39f77062 177static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 178
baa336ce 179static int putpkt_binary (const char *buf, int cnt);
c906108c 180
a14ed312 181static void check_binary_download (CORE_ADDR addr);
c906108c 182
5a2468f5 183struct packet_config;
5a2468f5 184
a14ed312 185static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 186
bb572ddd
DJ
187static void show_remote_protocol_packet_cmd (struct ui_file *file,
188 int from_tty,
189 struct cmd_list_element *c,
190 const char *value);
191
82f73884
PA
192static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
193static ptid_t read_ptid (char *buf, char **obuf);
194
c378d69d 195static void remote_set_permissions (struct target_ops *self);
d914c394 196
8bd200f1
TT
197static int remote_get_trace_status (struct target_ops *self,
198 struct trace_status *ts);
d5551862 199
ab6617cc
TT
200static int remote_upload_tracepoints (struct target_ops *self,
201 struct uploaded_tp **utpp);
00bf0b85 202
181e3713
TT
203static int remote_upload_trace_state_variables (struct target_ops *self,
204 struct uploaded_tsv **utsvp);
00bf0b85 205
c8d104ad
PA
206static void remote_query_supported (void);
207
36d25514 208static void remote_check_symbols (void);
c8d104ad 209
a14ed312 210void _initialize_remote (void);
c906108c 211
74531fed 212struct stop_reply;
74531fed 213static void stop_reply_xfree (struct stop_reply *);
722247f1 214static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 215static void push_stop_reply (struct stop_reply *);
bcc75809 216static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
217static int peek_stop_reply (ptid_t ptid);
218
cbb8991c
DB
219struct threads_listing_context;
220static void remove_new_fork_children (struct threads_listing_context *);
221
74531fed 222static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 223
e3594fd1 224static void remote_terminal_ours (struct target_ops *self);
d3fd5342 225
d962ef82
DJ
226static int remote_read_description_p (struct target_ops *target);
227
176a6961 228static void remote_console_output (char *msg);
dde08ee1 229
efcc2da7 230static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 231
78eff0ec 232static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 233
f4abbc16
MM
234static void remote_btrace_reset (void);
235
c0272db5
TW
236static void remote_btrace_maybe_reopen (void);
237
221e1a37
PA
238static int stop_reply_queue_length (void);
239
80152258
PA
240static void readahead_cache_invalidate (void);
241
048094ac
PA
242static void remote_unpush_and_throw (void);
243
a6b151f1
DJ
244/* For "remote". */
245
246static struct cmd_list_element *remote_cmdlist;
247
bb572ddd
DJ
248/* For "set remote" and "show remote". */
249
250static struct cmd_list_element *remote_set_cmdlist;
251static struct cmd_list_element *remote_show_cmdlist;
252
d458bd84
PA
253/* Stub vCont actions support.
254
255 Each field is a boolean flag indicating whether the stub reports
256 support for the corresponding action. */
257
258struct vCont_action_support
259{
260 /* vCont;t */
261 int t;
c1e36e3e
PA
262
263 /* vCont;r */
264 int r;
750ce8d1
YQ
265
266 /* vCont;s */
267 int s;
268
269 /* vCont;S */
270 int S;
d458bd84
PA
271};
272
c1e36e3e
PA
273/* Controls whether GDB is willing to use range stepping. */
274
275static int use_range_stepping = 1;
276
0d031856
TT
277#define OPAQUETHREADBYTES 8
278
279/* a 64 bit opaque identifier */
280typedef unsigned char threadref[OPAQUETHREADBYTES];
281
282/* About this many threadisds fit in a packet. */
283
284#define MAXTHREADLISTRESULTS 32
285
80152258
PA
286/* Data for the vFile:pread readahead cache. */
287
288struct readahead_cache
289{
290 /* The file descriptor for the file that is being cached. -1 if the
291 cache is invalid. */
292 int fd;
293
294 /* The offset into the file that the cache buffer corresponds
295 to. */
296 ULONGEST offset;
297
298 /* The buffer holding the cache contents. */
299 gdb_byte *buf;
300 /* The buffer's size. We try to read as much as fits into a packet
301 at a time. */
302 size_t bufsize;
303
304 /* Cache hit and miss counters. */
305 ULONGEST hit_count;
306 ULONGEST miss_count;
307};
308
ea9c271d
DJ
309/* Description of the remote protocol state for the currently
310 connected target. This is per-target state, and independent of the
311 selected architecture. */
312
313struct remote_state
314{
315 /* A buffer to use for incoming packets, and its current size. The
316 buffer is grown dynamically for larger incoming packets.
317 Outgoing packets may also be constructed in this buffer.
318 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
320 packets. */
321 char *buf;
322 long buf_size;
be2a5f71 323
1e51243a
PA
324 /* True if we're going through initial connection setup (finding out
325 about the remote side's threads, relocating symbols, etc.). */
326 int starting_up;
327
be2a5f71
DJ
328 /* If we negotiated packet size explicitly (and thus can bypass
329 heuristics for the largest packet size that will not overflow
330 a buffer in the stub), this will be set to that packet size.
331 Otherwise zero, meaning to use the guessed size. */
332 long explicit_packet_size;
2d717e4f
DJ
333
334 /* remote_wait is normally called when the target is running and
335 waits for a stop reply packet. But sometimes we need to call it
336 when the target is already stopped. We can send a "?" packet
337 and have remote_wait read the response. Or, if we already have
338 the response, we can stash it in BUF and tell remote_wait to
339 skip calling getpkt. This flag is set when BUF contains a
340 stop reply packet and the target is not waiting. */
341 int cached_wait_status;
a6f3e723
SL
342
343 /* True, if in no ack mode. That is, neither GDB nor the stub will
344 expect acks from each other. The connection is assumed to be
345 reliable. */
346 int noack_mode;
82f73884
PA
347
348 /* True if we're connected in extended remote mode. */
349 int extended;
350
e24a49d8
PA
351 /* True if we resumed the target and we're waiting for the target to
352 stop. In the mean time, we can't start another command/query.
353 The remote server wouldn't be ready to process it, so we'd
354 timeout waiting for a reply that would never come and eventually
355 we'd close the connection. This can happen in asynchronous mode
356 because we allow GDB commands while the target is running. */
357 int waiting_for_stop_reply;
74531fed 358
d458bd84
PA
359 /* The status of the stub support for the various vCont actions. */
360 struct vCont_action_support supports_vCont;
782b2b07 361
3a29589a
DJ
362 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363 responded to that. */
364 int ctrlc_pending_p;
5d93a237 365
048094ac
PA
366 /* True if we saw a Ctrl-C while reading or writing from/to the
367 remote descriptor. At that point it is not safe to send a remote
368 interrupt packet, so we instead remember we saw the Ctrl-C and
369 process it once we're done with sending/receiving the current
370 packet, which should be shortly. If however that takes too long,
371 and the user presses Ctrl-C again, we offer to disconnect. */
372 int got_ctrlc_during_io;
373
5d93a237
TT
374 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
375 remote_open knows that we don't have a file open when the program
376 starts. */
377 struct serial *remote_desc;
47f8a51d
TT
378
379 /* These are the threads which we last sent to the remote system. The
380 TID member will be -1 for all or -2 for not sent yet. */
381 ptid_t general_thread;
382 ptid_t continue_thread;
262e1174
TT
383
384 /* This is the traceframe which we last selected on the remote system.
385 It will be -1 if no traceframe is selected. */
386 int remote_traceframe_number;
747dc59d
TT
387
388 char *last_pass_packet;
5e4a05c4
TT
389
390 /* The last QProgramSignals packet sent to the target. We bypass
391 sending a new program signals list down to the target if the new
392 packet is exactly the same as the last we sent. IOW, we only let
393 the target know about program signals list changes. */
394 char *last_program_signals_packet;
b73be471
TT
395
396 enum gdb_signal last_sent_signal;
280ceea3
TT
397
398 int last_sent_step;
8e88304f 399
3a00c802
PA
400 /* The execution direction of the last resume we got. */
401 enum exec_direction_kind last_resume_exec_dir;
402
8e88304f
TT
403 char *finished_object;
404 char *finished_annex;
405 ULONGEST finished_offset;
b80fafe3
TT
406
407 /* Should we try the 'ThreadInfo' query packet?
408
409 This variable (NOT available to the user: auto-detect only!)
410 determines whether GDB will use the new, simpler "ThreadInfo"
411 query or the older, more complex syntax for thread queries.
412 This is an auto-detect variable (set to true at each connect,
413 and set to false when the target fails to recognize it). */
414 int use_threadinfo_query;
415 int use_threadextra_query;
88b496c3 416
0d031856
TT
417 threadref echo_nextthread;
418 threadref nextthread;
419 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
420
421 /* The state of remote notification. */
422 struct remote_notif_state *notif_state;
f4abbc16
MM
423
424 /* The branch trace configuration. */
425 struct btrace_config btrace_config;
15a201c8
GB
426
427 /* The argument to the last "vFile:setfs:" packet we sent, used
428 to avoid sending repeated unnecessary "vFile:setfs:" packets.
429 Initialized to -1 to indicate that no "vFile:setfs:" packet
430 has yet been sent. */
431 int fs_pid;
80152258
PA
432
433 /* A readahead cache for vFile:pread. Often, reading a binary
434 involves a sequence of small reads. E.g., when parsing an ELF
435 file. A readahead cache helps mostly the case of remote
436 debugging on a connection with higher latency, due to the
437 request/reply nature of the RSP. We only cache data for a single
438 file descriptor at a time. */
439 struct readahead_cache readahead_cache;
ea9c271d
DJ
440};
441
dc146f7c
VP
442/* Private data that we'll store in (struct thread_info)->private. */
443struct private_thread_info
444{
445 char *extra;
79efa585 446 char *name;
dc146f7c 447 int core;
799a2abe
PA
448
449 /* Whether the target stopped for a breakpoint/watchpoint. */
450 enum target_stop_reason stop_reason;
451
452 /* This is set to the data address of the access causing the target
453 to stop for a watchpoint. */
454 CORE_ADDR watch_data_address;
85ad3aaf
PA
455
456 /* Fields used by the vCont action coalescing implemented in
457 remote_resume / remote_commit_resume. remote_resume stores each
458 thread's last resume request in these fields, so that a later
459 remote_commit_resume knows which is the proper action for this
460 thread to include in the vCont packet. */
461
462 /* True if the last target_resume call for this thread was a step
463 request, false if a continue request. */
464 int last_resume_step;
465
466 /* The signal specified in the last target_resume call for this
467 thread. */
468 enum gdb_signal last_resume_sig;
469
470 /* Whether this thread was already vCont-resumed on the remote
471 side. */
472 int vcont_resumed;
dc146f7c
VP
473};
474
475static void
476free_private_thread_info (struct private_thread_info *info)
477{
478 xfree (info->extra);
79efa585 479 xfree (info->name);
dc146f7c
VP
480 xfree (info);
481}
482
ea9c271d
DJ
483/* This data could be associated with a target, but we do not always
484 have access to the current target when we need it, so for now it is
485 static. This will be fine for as long as only one target is in use
486 at a time. */
cf792862 487static struct remote_state *remote_state;
ea9c271d
DJ
488
489static struct remote_state *
0b83947e 490get_remote_state_raw (void)
ea9c271d 491{
cf792862
TT
492 return remote_state;
493}
494
495/* Allocate a new struct remote_state with xmalloc, initialize it, and
496 return it. */
497
498static struct remote_state *
499new_remote_state (void)
500{
501 struct remote_state *result = XCNEW (struct remote_state);
502
503 /* The default buffer size is unimportant; it will be expanded
504 whenever a larger buffer is needed. */
505 result->buf_size = 400;
224c3ddb 506 result->buf = (char *) xmalloc (result->buf_size);
262e1174 507 result->remote_traceframe_number = -1;
b73be471 508 result->last_sent_signal = GDB_SIGNAL_0;
3a00c802 509 result->last_resume_exec_dir = EXEC_FORWARD;
15a201c8 510 result->fs_pid = -1;
cf792862
TT
511
512 return result;
ea9c271d
DJ
513}
514
515/* Description of the remote protocol for a given architecture. */
d01949b6 516
ad10f812
AC
517struct packet_reg
518{
519 long offset; /* Offset into G packet. */
520 long regnum; /* GDB's internal register number. */
521 LONGEST pnum; /* Remote protocol register number. */
b323314b 522 int in_g_packet; /* Always part of G packet. */
f5656ead 523 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 524 at present. */
f5656ead 525 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 526 at present. */
ad10f812
AC
527};
528
ea9c271d 529struct remote_arch_state
d01949b6 530{
ad10f812
AC
531 /* Description of the remote protocol registers. */
532 long sizeof_g_packet;
b323314b
AC
533
534 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 535 (making an array gdbarch_num_regs in size). */
b323314b 536 struct packet_reg *regs;
ad10f812 537
d01949b6
AC
538 /* This is the size (in chars) of the first response to the ``g''
539 packet. It is used as a heuristic when determining the maximum
540 size of memory-read and memory-write packets. A target will
541 typically only reserve a buffer large enough to hold the ``g''
542 packet. The size does not include packet overhead (headers and
23860348 543 trailers). */
d01949b6
AC
544 long actual_register_packet_size;
545
546 /* This is the maximum size (in chars) of a non read/write packet.
23860348 547 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
548 long remote_packet_size;
549};
550
35b1e5cc
SS
551/* Utility: generate error from an incoming stub packet. */
552static void
553trace_error (char *buf)
554{
555 if (*buf++ != 'E')
556 return; /* not an error msg */
557 switch (*buf)
558 {
559 case '1': /* malformed packet error */
560 if (*++buf == '0') /* general case: */
561 error (_("remote.c: error in outgoing packet."));
562 else
563 error (_("remote.c: error in outgoing packet at field #%ld."),
564 strtol (buf, NULL, 16));
35b1e5cc
SS
565 default:
566 error (_("Target returns error code '%s'."), buf);
567 }
568}
569
570/* Utility: wait for reply from stub, while accepting "O" packets. */
571static char *
572remote_get_noisy_reply (char **buf_p,
573 long *sizeof_buf)
574{
575 do /* Loop on reply from remote stub. */
576 {
577 char *buf;
a744cf53 578
0df8b418 579 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
580 getpkt (buf_p, sizeof_buf, 0);
581 buf = *buf_p;
ad91cd99 582 if (buf[0] == 'E')
35b1e5cc 583 trace_error (buf);
61012eef 584 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
585 {
586 ULONGEST ul;
587 CORE_ADDR from, to, org_to;
588 char *p, *pp;
589 int adjusted_size = 0;
7556d4a4 590 int relocated = 0;
dde08ee1
PA
591
592 p = buf + strlen ("qRelocInsn:");
593 pp = unpack_varlen_hex (p, &ul);
594 if (*pp != ';')
cb91c06a 595 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
596 from = ul;
597
598 p = pp + 1;
a9cbf802 599 unpack_varlen_hex (p, &ul);
dde08ee1
PA
600 to = ul;
601
602 org_to = to;
603
492d29ea 604 TRY
dde08ee1 605 {
f5656ead 606 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 607 relocated = 1;
dde08ee1 608 }
492d29ea 609 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
610 {
611 if (ex.error == MEMORY_ERROR)
612 {
613 /* Propagate memory errors silently back to the
614 target. The stub may have limited the range of
615 addresses we can write to, for example. */
616 }
617 else
618 {
619 /* Something unexpectedly bad happened. Be verbose
620 so we can tell what, and propagate the error back
621 to the stub, so it doesn't get stuck waiting for
622 a response. */
623 exception_fprintf (gdb_stderr, ex,
624 _("warning: relocating instruction: "));
625 }
626 putpkt ("E01");
627 }
492d29ea 628 END_CATCH
7556d4a4
PA
629
630 if (relocated)
dde08ee1
PA
631 {
632 adjusted_size = to - org_to;
633
bba74b36 634 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
635 putpkt (buf);
636 }
dde08ee1 637 }
ad91cd99 638 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
639 remote_console_output (buf + 1); /* 'O' message from stub */
640 else
0df8b418 641 return buf; /* Here's the actual reply. */
35b1e5cc
SS
642 }
643 while (1);
644}
3c3bea1c 645
d01949b6
AC
646/* Handle for retreving the remote protocol data from gdbarch. */
647static struct gdbarch_data *remote_gdbarch_data_handle;
648
ea9c271d
DJ
649static struct remote_arch_state *
650get_remote_arch_state (void)
d01949b6 651{
17d8546e 652 gdb_assert (target_gdbarch () != NULL);
19ba03f4
SM
653 return ((struct remote_arch_state *)
654 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
d01949b6
AC
655}
656
0b83947e
DJ
657/* Fetch the global remote target state. */
658
659static struct remote_state *
660get_remote_state (void)
661{
662 /* Make sure that the remote architecture state has been
663 initialized, because doing so might reallocate rs->buf. Any
664 function which calls getpkt also needs to be mindful of changes
665 to rs->buf, but this call limits the number of places which run
666 into trouble. */
667 get_remote_arch_state ();
668
669 return get_remote_state_raw ();
670}
671
94585166
DB
672/* Cleanup routine for the remote module's pspace data. */
673
674static void
675remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
676{
19ba03f4 677 char *remote_exec_file = (char *) arg;
94585166
DB
678
679 xfree (remote_exec_file);
680}
681
682/* Fetch the remote exec-file from the current program space. */
683
684static const char *
685get_remote_exec_file (void)
686{
687 char *remote_exec_file;
688
19ba03f4
SM
689 remote_exec_file
690 = (char *) program_space_data (current_program_space,
691 remote_pspace_data);
94585166
DB
692 if (remote_exec_file == NULL)
693 return "";
694
695 return remote_exec_file;
696}
697
698/* Set the remote exec file for PSPACE. */
699
700static void
701set_pspace_remote_exec_file (struct program_space *pspace,
702 char *remote_exec_file)
703{
19ba03f4 704 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
705
706 xfree (old_file);
707 set_program_space_data (pspace, remote_pspace_data,
708 xstrdup (remote_exec_file));
709}
710
711/* The "set/show remote exec-file" set command hook. */
712
713static void
714set_remote_exec_file (char *ignored, int from_tty,
715 struct cmd_list_element *c)
716{
717 gdb_assert (remote_exec_file_var != NULL);
718 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
719}
720
721/* The "set/show remote exec-file" show command hook. */
722
723static void
724show_remote_exec_file (struct ui_file *file, int from_tty,
725 struct cmd_list_element *cmd, const char *value)
726{
727 fprintf_filtered (file, "%s\n", remote_exec_file_var);
728}
729
74ca34ce
DJ
730static int
731compare_pnums (const void *lhs_, const void *rhs_)
732{
19ba03f4
SM
733 const struct packet_reg * const *lhs
734 = (const struct packet_reg * const *) lhs_;
735 const struct packet_reg * const *rhs
736 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
737
738 if ((*lhs)->pnum < (*rhs)->pnum)
739 return -1;
740 else if ((*lhs)->pnum == (*rhs)->pnum)
741 return 0;
742 else
743 return 1;
744}
745
c21236dc
PA
746static int
747map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 748{
74ca34ce 749 int regnum, num_remote_regs, offset;
74ca34ce 750 struct packet_reg **remote_regs;
ea9c271d 751
4a22f64d 752 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 753 {
c21236dc 754 struct packet_reg *r = &regs[regnum];
baef701f 755
4a22f64d 756 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
757 /* Do not try to fetch zero-sized (placeholder) registers. */
758 r->pnum = -1;
759 else
760 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
761
b323314b 762 r->regnum = regnum;
74ca34ce
DJ
763 }
764
765 /* Define the g/G packet format as the contents of each register
766 with a remote protocol number, in order of ascending protocol
767 number. */
768
224c3ddb 769 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 770 for (num_remote_regs = 0, regnum = 0;
4a22f64d 771 regnum < gdbarch_num_regs (gdbarch);
f57d151a 772 regnum++)
c21236dc
PA
773 if (regs[regnum].pnum != -1)
774 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 775
74ca34ce
DJ
776 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
777 compare_pnums);
778
779 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
780 {
781 remote_regs[regnum]->in_g_packet = 1;
782 remote_regs[regnum]->offset = offset;
4a22f64d 783 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
784 }
785
c21236dc
PA
786 return offset;
787}
788
789/* Given the architecture described by GDBARCH, return the remote
790 protocol register's number and the register's offset in the g/G
791 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
792 If the target does not have a mapping for REGNUM, return false,
793 otherwise, return true. */
794
795int
796remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
797 int *pnum, int *poffset)
798{
c21236dc
PA
799 struct packet_reg *regs;
800 struct cleanup *old_chain;
801
802 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
803
224c3ddb 804 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
c21236dc
PA
805 old_chain = make_cleanup (xfree, regs);
806
54887903 807 map_regcache_remote_table (gdbarch, regs);
c21236dc
PA
808
809 *pnum = regs[regnum].pnum;
810 *poffset = regs[regnum].offset;
811
812 do_cleanups (old_chain);
813
814 return *pnum != -1;
815}
816
817static void *
818init_remote_state (struct gdbarch *gdbarch)
819{
820 struct remote_state *rs = get_remote_state_raw ();
821 struct remote_arch_state *rsa;
822
823 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
824
825 /* Use the architecture to build a regnum<->pnum table, which will be
826 1:1 unless a feature set specifies otherwise. */
827 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
828 gdbarch_num_regs (gdbarch),
829 struct packet_reg);
830
74ca34ce
DJ
831 /* Record the maximum possible size of the g packet - it may turn out
832 to be smaller. */
c21236dc 833 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 834
0df8b418 835 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
836 remote stubs have a hardwired buffer size of 400 bytes
837 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
838 as the maximum packet-size to ensure that the packet and an extra
839 NUL character can always fit in the buffer. This stops GDB
840 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
841 already a full buffer (As of 1999-12-04 that was most stubs). */
842 rsa->remote_packet_size = 400 - 1;
d01949b6 843
ea9c271d
DJ
844 /* This one is filled in when a ``g'' packet is received. */
845 rsa->actual_register_packet_size = 0;
846
847 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
848 default, adjust the size accordingly. Remember that each byte is
849 encoded as two characters. 32 is the overhead for the packet
850 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 851 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 852 little. */
ea9c271d
DJ
853 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
854 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 855
ea9c271d
DJ
856 /* Make sure that the packet buffer is plenty big enough for
857 this architecture. */
858 if (rs->buf_size < rsa->remote_packet_size)
859 {
860 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 861 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 862 }
6d820c5c 863
ea9c271d
DJ
864 return rsa;
865}
866
867/* Return the current allowed size of a remote packet. This is
868 inferred from the current architecture, and should be used to
869 limit the length of outgoing packets. */
870static long
871get_remote_packet_size (void)
872{
be2a5f71 873 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
874 struct remote_arch_state *rsa = get_remote_arch_state ();
875
be2a5f71
DJ
876 if (rs->explicit_packet_size)
877 return rs->explicit_packet_size;
878
ea9c271d 879 return rsa->remote_packet_size;
d01949b6
AC
880}
881
ad10f812 882static struct packet_reg *
ea9c271d 883packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 884{
f5656ead 885 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
886 return NULL;
887 else
ad10f812 888 {
ea9c271d 889 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 890
b323314b
AC
891 gdb_assert (r->regnum == regnum);
892 return r;
ad10f812 893 }
ad10f812
AC
894}
895
896static struct packet_reg *
ea9c271d 897packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 898{
b323314b 899 int i;
a744cf53 900
f5656ead 901 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 902 {
ea9c271d 903 struct packet_reg *r = &rsa->regs[i];
a744cf53 904
b323314b
AC
905 if (r->pnum == pnum)
906 return r;
ad10f812
AC
907 }
908 return NULL;
d01949b6
AC
909}
910
c906108c
SS
911static struct target_ops remote_ops;
912
913static struct target_ops extended_remote_ops;
914
6426a772
JM
915/* FIXME: cagney/1999-09-23: Even though getpkt was called with
916 ``forever'' still use the normal timeout mechanism. This is
917 currently used by the ASYNC code to guarentee that target reads
918 during the initial connect always time-out. Once getpkt has been
919 modified to return a timeout indication and, in turn
920 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 921 this can go away. */
6426a772
JM
922static int wait_forever_enabled_p = 1;
923
9a7071a8
JB
924/* Allow the user to specify what sequence to send to the remote
925 when he requests a program interruption: Although ^C is usually
926 what remote systems expect (this is the default, here), it is
927 sometimes preferable to send a break. On other systems such
928 as the Linux kernel, a break followed by g, which is Magic SysRq g
929 is required in order to interrupt the execution. */
930const char interrupt_sequence_control_c[] = "Ctrl-C";
931const char interrupt_sequence_break[] = "BREAK";
932const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 933static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
934 {
935 interrupt_sequence_control_c,
936 interrupt_sequence_break,
937 interrupt_sequence_break_g,
938 NULL
939 };
940static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
941
942static void
943show_interrupt_sequence (struct ui_file *file, int from_tty,
944 struct cmd_list_element *c,
945 const char *value)
946{
947 if (interrupt_sequence_mode == interrupt_sequence_control_c)
948 fprintf_filtered (file,
949 _("Send the ASCII ETX character (Ctrl-c) "
950 "to the remote target to interrupt the "
951 "execution of the program.\n"));
952 else if (interrupt_sequence_mode == interrupt_sequence_break)
953 fprintf_filtered (file,
954 _("send a break signal to the remote target "
955 "to interrupt the execution of the program.\n"));
956 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
957 fprintf_filtered (file,
958 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
959 "the remote target to interrupt the execution "
960 "of Linux kernel.\n"));
961 else
962 internal_error (__FILE__, __LINE__,
963 _("Invalid value for interrupt_sequence_mode: %s."),
964 interrupt_sequence_mode);
965}
6426a772 966
9a7071a8
JB
967/* This boolean variable specifies whether interrupt_sequence is sent
968 to the remote target when gdb connects to it.
969 This is mostly needed when you debug the Linux kernel: The Linux kernel
970 expects BREAK g which is Magic SysRq g for connecting gdb. */
971static int interrupt_on_connect = 0;
c906108c 972
9a7071a8
JB
973/* This variable is used to implement the "set/show remotebreak" commands.
974 Since these commands are now deprecated in favor of "set/show remote
975 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
976static int remote_break;
977
9a7071a8
JB
978static void
979set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
980{
981 if (remote_break)
982 interrupt_sequence_mode = interrupt_sequence_break;
983 else
984 interrupt_sequence_mode = interrupt_sequence_control_c;
985}
986
987static void
988show_remotebreak (struct ui_file *file, int from_tty,
989 struct cmd_list_element *c,
990 const char *value)
991{
992}
993
c906108c
SS
994/* This variable sets the number of bits in an address that are to be
995 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 996 leading zeros, the entire address would be sent. This variable
c906108c
SS
997 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
998 initial implementation of remote.c restricted the address sent in
999 memory packets to ``host::sizeof long'' bytes - (typically 32
1000 bits). Consequently, for 64 bit targets, the upper 32 bits of an
1001 address was never sent. Since fixing this bug may cause a break in
1002 some remote targets this variable is principly provided to
23860348 1003 facilitate backward compatibility. */
c906108c 1004
883b9c6c 1005static unsigned int remote_address_size;
c906108c 1006
75c99385
PA
1007/* Temporary to track who currently owns the terminal. See
1008 remote_terminal_* for more details. */
6426a772
JM
1009
1010static int remote_async_terminal_ours_p;
1011
11cf8741 1012\f
11cf8741 1013/* User configurable variables for the number of characters in a
ea9c271d
DJ
1014 memory read/write packet. MIN (rsa->remote_packet_size,
1015 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 1016 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
1017 (speed up transfers). The variables ``preferred_*'' (the user
1018 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 1019 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
1020
1021struct memory_packet_config
1022{
1023 char *name;
1024 long size;
1025 int fixed_p;
1026};
1027
a5c0808e
PA
1028/* The default max memory-write-packet-size. The 16k is historical.
1029 (It came from older GDB's using alloca for buffers and the
1030 knowledge (folklore?) that some hosts don't cope very well with
1031 large alloca calls.) */
1032#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1033
1034/* The minimum remote packet size for memory transfers. Ensures we
1035 can write at least one byte. */
1036#define MIN_MEMORY_PACKET_SIZE 20
1037
11cf8741
JM
1038/* Compute the current size of a read/write packet. Since this makes
1039 use of ``actual_register_packet_size'' the computation is dynamic. */
1040
1041static long
1042get_memory_packet_size (struct memory_packet_config *config)
1043{
d01949b6 1044 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
1045 struct remote_arch_state *rsa = get_remote_arch_state ();
1046
11cf8741
JM
1047 long what_they_get;
1048 if (config->fixed_p)
1049 {
1050 if (config->size <= 0)
a5c0808e 1051 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1052 else
1053 what_they_get = config->size;
1054 }
1055 else
1056 {
ea9c271d 1057 what_they_get = get_remote_packet_size ();
23860348 1058 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1059 if (config->size > 0
1060 && what_they_get > config->size)
1061 what_they_get = config->size;
be2a5f71
DJ
1062
1063 /* Limit it to the size of the targets ``g'' response unless we have
1064 permission from the stub to use a larger packet size. */
1065 if (rs->explicit_packet_size == 0
1066 && rsa->actual_register_packet_size > 0
1067 && what_they_get > rsa->actual_register_packet_size)
1068 what_they_get = rsa->actual_register_packet_size;
11cf8741 1069 }
a5c0808e
PA
1070 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1071 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1072
1073 /* Make sure there is room in the global buffer for this packet
1074 (including its trailing NUL byte). */
1075 if (rs->buf_size < what_they_get + 1)
1076 {
1077 rs->buf_size = 2 * what_they_get;
224c3ddb 1078 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1079 }
1080
11cf8741
JM
1081 return what_they_get;
1082}
1083
0df8b418 1084/* Update the size of a read/write packet. If they user wants
23860348 1085 something really big then do a sanity check. */
11cf8741
JM
1086
1087static void
1088set_memory_packet_size (char *args, struct memory_packet_config *config)
1089{
1090 int fixed_p = config->fixed_p;
1091 long size = config->size;
a744cf53 1092
11cf8741 1093 if (args == NULL)
8a3fe4f8 1094 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1095 else if (strcmp (args, "hard") == 0
1096 || strcmp (args, "fixed") == 0)
1097 fixed_p = 1;
1098 else if (strcmp (args, "soft") == 0
1099 || strcmp (args, "limit") == 0)
1100 fixed_p = 0;
1101 else
1102 {
1103 char *end;
a744cf53 1104
11cf8741
JM
1105 size = strtoul (args, &end, 0);
1106 if (args == end)
8a3fe4f8 1107 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1108
1109 /* Instead of explicitly capping the size of a packet to or
1110 disallowing it, the user is allowed to set the size to
1111 something arbitrarily large. */
11cf8741 1112 }
a5c0808e
PA
1113
1114 /* So that the query shows the correct value. */
1115 if (size <= 0)
1116 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1117
23860348 1118 /* Extra checks? */
11cf8741
JM
1119 if (fixed_p && !config->fixed_p)
1120 {
e2e0b3e5
AC
1121 if (! query (_("The target may not be able to correctly handle a %s\n"
1122 "of %ld bytes. Change the packet size? "),
11cf8741 1123 config->name, size))
8a3fe4f8 1124 error (_("Packet size not changed."));
11cf8741 1125 }
23860348 1126 /* Update the config. */
11cf8741
JM
1127 config->fixed_p = fixed_p;
1128 config->size = size;
1129}
1130
1131static void
1132show_memory_packet_size (struct memory_packet_config *config)
1133{
a3f17187 1134 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1135 if (config->fixed_p)
a3f17187 1136 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1137 get_memory_packet_size (config));
1138 else
a3f17187 1139 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1140 get_memory_packet_size (config));
1141}
1142
1143static struct memory_packet_config memory_write_packet_config =
1144{
1145 "memory-write-packet-size",
1146};
1147
1148static void
1149set_memory_write_packet_size (char *args, int from_tty)
1150{
1151 set_memory_packet_size (args, &memory_write_packet_config);
1152}
1153
1154static void
1155show_memory_write_packet_size (char *args, int from_tty)
1156{
1157 show_memory_packet_size (&memory_write_packet_config);
1158}
1159
1160static long
1161get_memory_write_packet_size (void)
1162{
1163 return get_memory_packet_size (&memory_write_packet_config);
1164}
1165
1166static struct memory_packet_config memory_read_packet_config =
1167{
1168 "memory-read-packet-size",
1169};
1170
1171static void
1172set_memory_read_packet_size (char *args, int from_tty)
1173{
1174 set_memory_packet_size (args, &memory_read_packet_config);
1175}
1176
1177static void
1178show_memory_read_packet_size (char *args, int from_tty)
1179{
1180 show_memory_packet_size (&memory_read_packet_config);
1181}
1182
1183static long
1184get_memory_read_packet_size (void)
1185{
1186 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1187
11cf8741
JM
1188 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1189 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1190 increased beyond this. */
1191 if (size > get_remote_packet_size ())
1192 size = get_remote_packet_size ();
11cf8741
JM
1193 return size;
1194}
1195
11cf8741 1196\f
5a2468f5 1197/* Generic configuration support for packets the stub optionally
0df8b418 1198 supports. Allows the user to specify the use of the packet as well
23860348 1199 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1200
1201enum packet_support
1202 {
1203 PACKET_SUPPORT_UNKNOWN = 0,
1204 PACKET_ENABLE,
1205 PACKET_DISABLE
1206 };
1207
5a2468f5
JM
1208struct packet_config
1209 {
bb572ddd
DJ
1210 const char *name;
1211 const char *title;
4082afcc
PA
1212
1213 /* If auto, GDB auto-detects support for this packet or feature,
1214 either through qSupported, or by trying the packet and looking
1215 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1216 packet. If false, the packet is disabled. Configs that don't
1217 have an associated command always have this set to auto. */
7f19b9a2 1218 enum auto_boolean detect;
4082afcc
PA
1219
1220 /* Does the target support this packet? */
5a2468f5
JM
1221 enum packet_support support;
1222 };
1223
d471ea57 1224/* Analyze a packet's return value and update the packet config
23860348 1225 accordingly. */
d471ea57
AC
1226
1227enum packet_result
1228{
1229 PACKET_ERROR,
1230 PACKET_OK,
1231 PACKET_UNKNOWN
1232};
1233
4082afcc
PA
1234static enum packet_support packet_config_support (struct packet_config *config);
1235static enum packet_support packet_support (int packet);
5a2468f5
JM
1236
1237static void
fba45db2 1238show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1239{
1240 char *support = "internal-error";
a744cf53 1241
4082afcc 1242 switch (packet_config_support (config))
5a2468f5
JM
1243 {
1244 case PACKET_ENABLE:
1245 support = "enabled";
1246 break;
1247 case PACKET_DISABLE:
1248 support = "disabled";
1249 break;
1250 case PACKET_SUPPORT_UNKNOWN:
1251 support = "unknown";
1252 break;
1253 }
1254 switch (config->detect)
1255 {
7f19b9a2 1256 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1257 printf_filtered (_("Support for the `%s' packet "
1258 "is auto-detected, currently %s.\n"),
37a105a1 1259 config->name, support);
5a2468f5 1260 break;
7f19b9a2
AC
1261 case AUTO_BOOLEAN_TRUE:
1262 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1263 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1264 config->name, support);
8e248173 1265 break;
5a2468f5
JM
1266 }
1267}
1268
1269static void
bb572ddd
DJ
1270add_packet_config_cmd (struct packet_config *config, const char *name,
1271 const char *title, int legacy)
d471ea57 1272{
5a2468f5
JM
1273 char *set_doc;
1274 char *show_doc;
d471ea57 1275 char *cmd_name;
3ed07be4 1276
5a2468f5
JM
1277 config->name = name;
1278 config->title = title;
b435e160
AC
1279 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1280 name, title);
3e43a32a
MS
1281 show_doc = xstrprintf ("Show current use of remote "
1282 "protocol `%s' (%s) packet",
b435e160 1283 name, title);
d471ea57 1284 /* set/show TITLE-packet {auto,on,off} */
b435e160 1285 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1286 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1287 &config->detect, set_doc,
1288 show_doc, NULL, /* help_doc */
4082afcc 1289 NULL,
bb572ddd
DJ
1290 show_remote_protocol_packet_cmd,
1291 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1292 /* The command code copies the documentation strings. */
1293 xfree (set_doc);
1294 xfree (show_doc);
23860348 1295 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1296 if (legacy)
1297 {
1298 char *legacy_name;
a744cf53 1299
b435e160 1300 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1301 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1302 &remote_set_cmdlist);
d471ea57 1303 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1304 &remote_show_cmdlist);
d471ea57 1305 }
5a2468f5
JM
1306}
1307
d471ea57 1308static enum packet_result
a76d924d 1309packet_check_result (const char *buf)
5a2468f5 1310{
d471ea57 1311 if (buf[0] != '\0')
5a2468f5 1312 {
d471ea57 1313 /* The stub recognized the packet request. Check that the
23860348 1314 operation succeeded. */
a76d924d
DJ
1315 if (buf[0] == 'E'
1316 && isxdigit (buf[1]) && isxdigit (buf[2])
1317 && buf[3] == '\0')
1318 /* "Enn" - definitly an error. */
1319 return PACKET_ERROR;
1320
1321 /* Always treat "E." as an error. This will be used for
1322 more verbose error messages, such as E.memtypes. */
1323 if (buf[0] == 'E' && buf[1] == '.')
1324 return PACKET_ERROR;
1325
1326 /* The packet may or may not be OK. Just assume it is. */
1327 return PACKET_OK;
1328 }
1329 else
1330 /* The stub does not support the packet. */
1331 return PACKET_UNKNOWN;
1332}
1333
1334static enum packet_result
1335packet_ok (const char *buf, struct packet_config *config)
1336{
1337 enum packet_result result;
1338
4082afcc
PA
1339 if (config->detect != AUTO_BOOLEAN_TRUE
1340 && config->support == PACKET_DISABLE)
1341 internal_error (__FILE__, __LINE__,
1342 _("packet_ok: attempt to use a disabled packet"));
1343
a76d924d
DJ
1344 result = packet_check_result (buf);
1345 switch (result)
1346 {
1347 case PACKET_OK:
1348 case PACKET_ERROR:
1349 /* The stub recognized the packet request. */
4082afcc 1350 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1351 {
d471ea57
AC
1352 if (remote_debug)
1353 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1354 "Packet %s (%s) is supported\n",
1355 config->name, config->title);
d471ea57 1356 config->support = PACKET_ENABLE;
d471ea57 1357 }
a76d924d
DJ
1358 break;
1359 case PACKET_UNKNOWN:
23860348 1360 /* The stub does not support the packet. */
4082afcc
PA
1361 if (config->detect == AUTO_BOOLEAN_AUTO
1362 && config->support == PACKET_ENABLE)
d471ea57 1363 {
4082afcc
PA
1364 /* If the stub previously indicated that the packet was
1365 supported then there is a protocol error. */
1366 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1367 config->name, config->title);
1368 }
1369 else if (config->detect == AUTO_BOOLEAN_TRUE)
1370 {
1371 /* The user set it wrong. */
1372 error (_("Enabled packet %s (%s) not recognized by stub"),
1373 config->name, config->title);
d471ea57 1374 }
4082afcc
PA
1375
1376 if (remote_debug)
1377 fprintf_unfiltered (gdb_stdlog,
1378 "Packet %s (%s) is NOT supported\n",
1379 config->name, config->title);
1380 config->support = PACKET_DISABLE;
a76d924d 1381 break;
5a2468f5 1382 }
a76d924d
DJ
1383
1384 return result;
5a2468f5
JM
1385}
1386
444abaca
DJ
1387enum {
1388 PACKET_vCont = 0,
1389 PACKET_X,
1390 PACKET_qSymbol,
1391 PACKET_P,
1392 PACKET_p,
1393 PACKET_Z0,
1394 PACKET_Z1,
1395 PACKET_Z2,
1396 PACKET_Z3,
1397 PACKET_Z4,
15a201c8 1398 PACKET_vFile_setfs,
a6b151f1
DJ
1399 PACKET_vFile_open,
1400 PACKET_vFile_pread,
1401 PACKET_vFile_pwrite,
1402 PACKET_vFile_close,
1403 PACKET_vFile_unlink,
b9e7b9c3 1404 PACKET_vFile_readlink,
0a93529c 1405 PACKET_vFile_fstat,
0876f84a 1406 PACKET_qXfer_auxv,
23181151 1407 PACKET_qXfer_features,
c78fa86a 1408 PACKET_qXfer_exec_file,
cfa9d6d9 1409 PACKET_qXfer_libraries,
2268b414 1410 PACKET_qXfer_libraries_svr4,
fd79ecee 1411 PACKET_qXfer_memory_map,
0e7f50da
UW
1412 PACKET_qXfer_spu_read,
1413 PACKET_qXfer_spu_write,
07e059b5 1414 PACKET_qXfer_osdata,
dc146f7c 1415 PACKET_qXfer_threads,
0fb4aa4b 1416 PACKET_qXfer_statictrace_read,
b3b9301e 1417 PACKET_qXfer_traceframe_info,
169081d0 1418 PACKET_qXfer_uib,
711e434b 1419 PACKET_qGetTIBAddr,
444abaca 1420 PACKET_qGetTLSAddr,
be2a5f71 1421 PACKET_qSupported,
bd3eecc3 1422 PACKET_qTStatus,
89be2091 1423 PACKET_QPassSignals,
82075af2 1424 PACKET_QCatchSyscalls,
9b224c5e 1425 PACKET_QProgramSignals,
936d2992 1426 PACKET_qCRC,
08388c79 1427 PACKET_qSearch_memory,
2d717e4f
DJ
1428 PACKET_vAttach,
1429 PACKET_vRun,
a6f3e723 1430 PACKET_QStartNoAckMode,
82f73884 1431 PACKET_vKill,
4aa995e1
PA
1432 PACKET_qXfer_siginfo_read,
1433 PACKET_qXfer_siginfo_write,
0b16c5cf 1434 PACKET_qAttached,
4082afcc
PA
1435
1436 /* Support for conditional tracepoints. */
782b2b07 1437 PACKET_ConditionalTracepoints,
4082afcc
PA
1438
1439 /* Support for target-side breakpoint conditions. */
3788aec7 1440 PACKET_ConditionalBreakpoints,
4082afcc
PA
1441
1442 /* Support for target-side breakpoint commands. */
d3ce09f5 1443 PACKET_BreakpointCommands,
4082afcc
PA
1444
1445 /* Support for fast tracepoints. */
7a697b8d 1446 PACKET_FastTracepoints,
4082afcc
PA
1447
1448 /* Support for static tracepoints. */
0fb4aa4b 1449 PACKET_StaticTracepoints,
4082afcc
PA
1450
1451 /* Support for installing tracepoints while a trace experiment is
1452 running. */
1e4d1764 1453 PACKET_InstallInTrace,
4082afcc 1454
40ab02ce
MS
1455 PACKET_bc,
1456 PACKET_bs,
409873ef 1457 PACKET_TracepointSource,
d914c394 1458 PACKET_QAllow,
78d85199 1459 PACKET_qXfer_fdpic,
03583c20 1460 PACKET_QDisableRandomization,
d1feda86 1461 PACKET_QAgent,
f6f899bf 1462 PACKET_QTBuffer_size,
9accd112
MM
1463 PACKET_Qbtrace_off,
1464 PACKET_Qbtrace_bts,
b20a6524 1465 PACKET_Qbtrace_pt,
9accd112 1466 PACKET_qXfer_btrace,
4082afcc
PA
1467
1468 /* Support for the QNonStop packet. */
1469 PACKET_QNonStop,
1470
65706a29
PA
1471 /* Support for the QThreadEvents packet. */
1472 PACKET_QThreadEvents,
1473
4082afcc
PA
1474 /* Support for multi-process extensions. */
1475 PACKET_multiprocess_feature,
1476
1477 /* Support for enabling and disabling tracepoints while a trace
1478 experiment is running. */
1479 PACKET_EnableDisableTracepoints_feature,
1480
1481 /* Support for collecting strings using the tracenz bytecode. */
1482 PACKET_tracenz_feature,
1483
1484 /* Support for continuing to run a trace experiment while GDB is
1485 disconnected. */
1486 PACKET_DisconnectedTracing_feature,
1487
1488 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1489 PACKET_augmented_libraries_svr4_read_feature,
1490
f4abbc16
MM
1491 /* Support for the qXfer:btrace-conf:read packet. */
1492 PACKET_qXfer_btrace_conf,
1493
d33501a5
MM
1494 /* Support for the Qbtrace-conf:bts:size packet. */
1495 PACKET_Qbtrace_conf_bts_size,
1496
f7e6eed5
PA
1497 /* Support for swbreak+ feature. */
1498 PACKET_swbreak_feature,
1499
1500 /* Support for hwbreak+ feature. */
1501 PACKET_hwbreak_feature,
1502
89245bc0
DB
1503 /* Support for fork events. */
1504 PACKET_fork_event_feature,
1505
1506 /* Support for vfork events. */
1507 PACKET_vfork_event_feature,
1508
b20a6524
MM
1509 /* Support for the Qbtrace-conf:pt:size packet. */
1510 PACKET_Qbtrace_conf_pt_size,
1511
94585166
DB
1512 /* Support for exec events. */
1513 PACKET_exec_event_feature,
1514
750ce8d1
YQ
1515 /* Support for query supported vCont actions. */
1516 PACKET_vContSupported,
1517
de979965
PA
1518 /* Support remote CTRL-C. */
1519 PACKET_vCtrlC,
1520
f2faf941
PA
1521 /* Support TARGET_WAITKIND_NO_RESUMED. */
1522 PACKET_no_resumed,
1523
444abaca
DJ
1524 PACKET_MAX
1525};
506fb367 1526
444abaca 1527static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1528
f7e6eed5
PA
1529/* Returns the packet's corresponding "set remote foo-packet" command
1530 state. See struct packet_config for more details. */
1531
1532static enum auto_boolean
1533packet_set_cmd_state (int packet)
1534{
1535 return remote_protocol_packets[packet].detect;
1536}
1537
4082afcc
PA
1538/* Returns whether a given packet or feature is supported. This takes
1539 into account the state of the corresponding "set remote foo-packet"
1540 command, which may be used to bypass auto-detection. */
dc8acb97 1541
4082afcc
PA
1542static enum packet_support
1543packet_config_support (struct packet_config *config)
1544{
1545 switch (config->detect)
444abaca 1546 {
4082afcc
PA
1547 case AUTO_BOOLEAN_TRUE:
1548 return PACKET_ENABLE;
1549 case AUTO_BOOLEAN_FALSE:
1550 return PACKET_DISABLE;
1551 case AUTO_BOOLEAN_AUTO:
1552 return config->support;
1553 default:
1554 gdb_assert_not_reached (_("bad switch"));
444abaca 1555 }
4082afcc
PA
1556}
1557
1558/* Same as packet_config_support, but takes the packet's enum value as
1559 argument. */
1560
1561static enum packet_support
1562packet_support (int packet)
1563{
1564 struct packet_config *config = &remote_protocol_packets[packet];
1565
1566 return packet_config_support (config);
dc8acb97
MS
1567}
1568
5a2468f5 1569static void
444abaca
DJ
1570show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1571 struct cmd_list_element *c,
1572 const char *value)
5a2468f5 1573{
444abaca 1574 struct packet_config *packet;
5a2468f5 1575
444abaca
DJ
1576 for (packet = remote_protocol_packets;
1577 packet < &remote_protocol_packets[PACKET_MAX];
1578 packet++)
1579 {
1580 if (&packet->detect == c->var)
1581 {
1582 show_packet_config_cmd (packet);
1583 return;
1584 }
1585 }
9b20d036 1586 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1587 c->name);
5a2468f5
JM
1588}
1589
d471ea57
AC
1590/* Should we try one of the 'Z' requests? */
1591
1592enum Z_packet_type
1593{
1594 Z_PACKET_SOFTWARE_BP,
1595 Z_PACKET_HARDWARE_BP,
1596 Z_PACKET_WRITE_WP,
1597 Z_PACKET_READ_WP,
1598 Z_PACKET_ACCESS_WP,
1599 NR_Z_PACKET_TYPES
1600};
96baa820 1601
d471ea57 1602/* For compatibility with older distributions. Provide a ``set remote
23860348 1603 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1604
7f19b9a2 1605static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1606
1607static void
fba45db2
KB
1608set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1609 struct cmd_list_element *c)
96baa820 1610{
d471ea57 1611 int i;
a744cf53 1612
d471ea57 1613 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1614 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1615}
1616
1617static void
08546159
AC
1618show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1619 struct cmd_list_element *c,
1620 const char *value)
96baa820 1621{
d471ea57 1622 int i;
a744cf53 1623
d471ea57
AC
1624 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1625 {
444abaca 1626 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1627 }
96baa820
JM
1628}
1629
4082afcc
PA
1630/* Returns true if the multi-process extensions are in effect. */
1631
1632static int
1633remote_multi_process_p (struct remote_state *rs)
1634{
1635 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1636}
1637
de0d863e
DB
1638/* Returns true if fork events are supported. */
1639
1640static int
1641remote_fork_event_p (struct remote_state *rs)
1642{
1643 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1644}
1645
c269dbdb
DB
1646/* Returns true if vfork events are supported. */
1647
1648static int
1649remote_vfork_event_p (struct remote_state *rs)
1650{
1651 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1652}
1653
d46addbb
DB
1654/* Returns true if exec events are supported. */
1655
1656static int
1657remote_exec_event_p (struct remote_state *rs)
1658{
1659 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1660}
1661
cbb8991c
DB
1662/* Insert fork catchpoint target routine. If fork events are enabled
1663 then return success, nothing more to do. */
1664
1665static int
1666remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1667{
1668 struct remote_state *rs = get_remote_state ();
1669
1670 return !remote_fork_event_p (rs);
1671}
1672
1673/* Remove fork catchpoint target routine. Nothing to do, just
1674 return success. */
1675
1676static int
1677remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1678{
1679 return 0;
1680}
1681
1682/* Insert vfork catchpoint target routine. If vfork events are enabled
1683 then return success, nothing more to do. */
1684
1685static int
1686remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1687{
1688 struct remote_state *rs = get_remote_state ();
1689
1690 return !remote_vfork_event_p (rs);
1691}
1692
1693/* Remove vfork catchpoint target routine. Nothing to do, just
1694 return success. */
1695
1696static int
1697remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1698{
1699 return 0;
1700}
1701
d46addbb
DB
1702/* Insert exec catchpoint target routine. If exec events are
1703 enabled, just return success. */
1704
1705static int
1706remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1707{
1708 struct remote_state *rs = get_remote_state ();
1709
1710 return !remote_exec_event_p (rs);
1711}
1712
1713/* Remove exec catchpoint target routine. Nothing to do, just
1714 return success. */
1715
1716static int
1717remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1718{
1719 return 0;
1720}
1721
74531fed
PA
1722\f
1723/* Asynchronous signal handle registered as event loop source for
1724 when we have pending events ready to be passed to the core. */
1725
1726static struct async_event_handler *remote_async_inferior_event_token;
1727
c906108c
SS
1728\f
1729
79d7f229
PA
1730static ptid_t magic_null_ptid;
1731static ptid_t not_sent_ptid;
1732static ptid_t any_thread_ptid;
1733
0b16c5cf
PA
1734/* Find out if the stub attached to PID (and hence GDB should offer to
1735 detach instead of killing it when bailing out). */
1736
1737static int
1738remote_query_attached (int pid)
1739{
1740 struct remote_state *rs = get_remote_state ();
bba74b36 1741 size_t size = get_remote_packet_size ();
0b16c5cf 1742
4082afcc 1743 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1744 return 0;
1745
1746 if (remote_multi_process_p (rs))
bba74b36 1747 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1748 else
bba74b36 1749 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1750
1751 putpkt (rs->buf);
1752 getpkt (&rs->buf, &rs->buf_size, 0);
1753
1754 switch (packet_ok (rs->buf,
1554e9be 1755 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1756 {
1757 case PACKET_OK:
1758 if (strcmp (rs->buf, "1") == 0)
1759 return 1;
1760 break;
1761 case PACKET_ERROR:
1762 warning (_("Remote failure reply: %s"), rs->buf);
1763 break;
1764 case PACKET_UNKNOWN:
1765 break;
1766 }
1767
1768 return 0;
1769}
1770
49c62f2e
PA
1771/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1772 has been invented by GDB, instead of reported by the target. Since
1773 we can be connected to a remote system before before knowing about
1774 any inferior, mark the target with execution when we find the first
1775 inferior. If ATTACHED is 1, then we had just attached to this
1776 inferior. If it is 0, then we just created this inferior. If it
1777 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1778 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1779 attempt to open this inferior's executable as the main executable
1780 if no main executable is open already. */
1941c569
PA
1781
1782static struct inferior *
1b6e6f5c
GB
1783remote_add_inferior (int fake_pid_p, int pid, int attached,
1784 int try_open_exec)
1941c569 1785{
1941c569
PA
1786 struct inferior *inf;
1787
0b16c5cf
PA
1788 /* Check whether this process we're learning about is to be
1789 considered attached, or if is to be considered to have been
1790 spawned by the stub. */
1791 if (attached == -1)
1792 attached = remote_query_attached (pid);
1793
f5656ead 1794 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1795 {
1796 /* If the target shares code across all inferiors, then every
1797 attach adds a new inferior. */
1798 inf = add_inferior (pid);
1799
1800 /* ... and every inferior is bound to the same program space.
1801 However, each inferior may still have its own address
1802 space. */
1803 inf->aspace = maybe_new_address_space ();
1804 inf->pspace = current_program_space;
1805 }
1806 else
1807 {
1808 /* In the traditional debugging scenario, there's a 1-1 match
1809 between program/address spaces. We simply bind the inferior
1810 to the program space's address space. */
1811 inf = current_inferior ();
1812 inferior_appeared (inf, pid);
1813 }
1941c569 1814
0b16c5cf 1815 inf->attach_flag = attached;
49c62f2e 1816 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1817
1b6e6f5c
GB
1818 /* If no main executable is currently open then attempt to
1819 open the file that was executed to create this inferior. */
835205d0 1820 if (try_open_exec && get_exec_file (0) == NULL)
bb805577 1821 exec_file_locate_attach (pid, 0, 1);
1b6e6f5c 1822
1941c569
PA
1823 return inf;
1824}
1825
85ad3aaf
PA
1826static struct private_thread_info *
1827 get_private_info_thread (struct thread_info *info);
1828
1941c569
PA
1829/* Add thread PTID to GDB's thread list. Tag it as executing/running
1830 according to RUNNING. */
1831
c906108c 1832static void
0d5b594f 1833remote_add_thread (ptid_t ptid, int running, int executing)
c906108c 1834{
b7ea362b 1835 struct remote_state *rs = get_remote_state ();
85ad3aaf 1836 struct thread_info *thread;
b7ea362b
PA
1837
1838 /* GDB historically didn't pull threads in the initial connection
1839 setup. If the remote target doesn't even have a concept of
1840 threads (e.g., a bare-metal target), even if internally we
1841 consider that a single-threaded target, mentioning a new thread
1842 might be confusing to the user. Be silent then, preserving the
1843 age old behavior. */
1844 if (rs->starting_up)
85ad3aaf 1845 thread = add_thread_silent (ptid);
b7ea362b 1846 else
85ad3aaf 1847 thread = add_thread (ptid);
1941c569 1848
85ad3aaf 1849 get_private_info_thread (thread)->vcont_resumed = executing;
0d5b594f 1850 set_executing (ptid, executing);
1941c569
PA
1851 set_running (ptid, running);
1852}
1853
1854/* Come here when we learn about a thread id from the remote target.
1855 It may be the first time we hear about such thread, so take the
1856 opportunity to add it to GDB's thread list. In case this is the
1857 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
1858 GDB's inferior list as well. EXECUTING indicates whether the
1859 thread is (internally) executing or stopped. */
1941c569
PA
1860
1861static void
0d5b594f 1862remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 1863{
0d5b594f
PA
1864 /* In non-stop mode, we assume new found threads are (externally)
1865 running until proven otherwise with a stop reply. In all-stop,
1866 we can only get here if all threads are stopped. */
1867 int running = target_is_non_stop_p () ? 1 : 0;
1868
c906108c
SS
1869 /* If this is a new thread, add it to GDB's thread list.
1870 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1871
1872 if (in_thread_list (currthread) && is_exited (currthread))
1873 {
1874 /* We're seeing an event on a thread id we knew had exited.
1875 This has to be a new thread reusing the old id. Add it. */
0d5b594f 1876 remote_add_thread (currthread, running, executing);
82f73884
PA
1877 return;
1878 }
1879
79d7f229 1880 if (!in_thread_list (currthread))
c0a2216e 1881 {
1941c569 1882 struct inferior *inf = NULL;
bad34192 1883 int pid = ptid_get_pid (currthread);
1941c569 1884
bad34192
PA
1885 if (ptid_is_pid (inferior_ptid)
1886 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1887 {
1888 /* inferior_ptid has no thread member yet. This can happen
1889 with the vAttach -> remote_wait,"TAAthread:" path if the
1890 stub doesn't support qC. This is the first stop reported
1891 after an attach, so this is the main thread. Update the
1892 ptid in the thread list. */
bad34192
PA
1893 if (in_thread_list (pid_to_ptid (pid)))
1894 thread_change_ptid (inferior_ptid, currthread);
1895 else
1896 {
0d5b594f 1897 remote_add_thread (currthread, running, executing);
bad34192
PA
1898 inferior_ptid = currthread;
1899 }
dc146f7c 1900 return;
c0a2216e 1901 }
82f73884
PA
1902
1903 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1904 {
1905 /* inferior_ptid is not set yet. This can happen with the
1906 vRun -> remote_wait,"TAAthread:" path if the stub
1907 doesn't support qC. This is the first stop reported
1908 after an attach, so this is the main thread. Update the
1909 ptid in the thread list. */
dc146f7c 1910 thread_change_ptid (inferior_ptid, currthread);
82f73884 1911 return;
c0a2216e 1912 }
82f73884 1913
29c87f7f
PA
1914 /* When connecting to a target remote, or to a target
1915 extended-remote which already was debugging an inferior, we
1916 may not know about it yet. Add it before adding its child
1917 thread, so notifications are emitted in a sensible order. */
1918 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1919 {
1920 struct remote_state *rs = get_remote_state ();
1921 int fake_pid_p = !remote_multi_process_p (rs);
1922
1923 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1924 ptid_get_pid (currthread), -1, 1);
49c62f2e 1925 }
29c87f7f 1926
82f73884 1927 /* This is really a new thread. Add it. */
0d5b594f 1928 remote_add_thread (currthread, running, executing);
1941c569
PA
1929
1930 /* If we found a new inferior, let the common code do whatever
1931 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1932 breakpoints), unless we're just setting up an all-stop
1933 connection. */
1941c569 1934 if (inf != NULL)
b7ea362b
PA
1935 {
1936 struct remote_state *rs = get_remote_state ();
1937
6efcd9a8 1938 if (!rs->starting_up)
0d5b594f 1939 notice_new_inferior (currthread, executing, 0);
b7ea362b 1940 }
c0a2216e 1941 }
c906108c
SS
1942}
1943
85ad3aaf 1944/* Return THREAD's private thread data, creating it if necessary. */
dc146f7c 1945
70221824 1946static struct private_thread_info *
85ad3aaf 1947get_private_info_thread (struct thread_info *thread)
dc146f7c 1948{
85ad3aaf 1949 gdb_assert (thread != NULL);
dc146f7c 1950
85ad3aaf 1951 if (thread->priv == NULL)
dc146f7c 1952 {
85ad3aaf
PA
1953 struct private_thread_info *priv = XNEW (struct private_thread_info);
1954
1955 thread->private_dtor = free_private_thread_info;
1956 thread->priv = priv;
1957
1958 priv->core = -1;
1959 priv->extra = NULL;
1960 priv->name = NULL;
1961 priv->name = NULL;
1962 priv->last_resume_step = 0;
1963 priv->last_resume_sig = GDB_SIGNAL_0;
1964 priv->vcont_resumed = 0;
dc146f7c
VP
1965 }
1966
85ad3aaf
PA
1967 return thread->priv;
1968}
1969
1970/* Return PTID's private thread data, creating it if necessary. */
1971
1972static struct private_thread_info *
1973get_private_info_ptid (ptid_t ptid)
1974{
1975 struct thread_info *info = find_thread_ptid (ptid);
1976
1977 return get_private_info_thread (info);
dc146f7c
VP
1978}
1979
74531fed
PA
1980/* Call this function as a result of
1981 1) A halt indication (T packet) containing a thread id
1982 2) A direct query of currthread
0df8b418 1983 3) Successful execution of set thread */
74531fed
PA
1984
1985static void
47f8a51d 1986record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1987{
47f8a51d 1988 rs->general_thread = currthread;
74531fed
PA
1989}
1990
89be2091
DJ
1991/* If 'QPassSignals' is supported, tell the remote stub what signals
1992 it can simply pass through to the inferior without reporting. */
1993
1994static void
94bedb42
TT
1995remote_pass_signals (struct target_ops *self,
1996 int numsigs, unsigned char *pass_signals)
89be2091 1997{
4082afcc 1998 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1999 {
2000 char *pass_packet, *p;
89be2091 2001 int count = 0, i;
747dc59d 2002 struct remote_state *rs = get_remote_state ();
89be2091
DJ
2003
2004 gdb_assert (numsigs < 256);
2005 for (i = 0; i < numsigs; i++)
2006 {
2455069d 2007 if (pass_signals[i])
89be2091
DJ
2008 count++;
2009 }
224c3ddb 2010 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
2011 strcpy (pass_packet, "QPassSignals:");
2012 p = pass_packet + strlen (pass_packet);
2013 for (i = 0; i < numsigs; i++)
2014 {
2455069d 2015 if (pass_signals[i])
89be2091
DJ
2016 {
2017 if (i >= 16)
2018 *p++ = tohex (i >> 4);
2019 *p++ = tohex (i & 15);
2020 if (count)
2021 *p++ = ';';
2022 else
2023 break;
2024 count--;
2025 }
2026 }
2027 *p = 0;
747dc59d 2028 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 2029 {
89be2091
DJ
2030 putpkt (pass_packet);
2031 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2032 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
2033 if (rs->last_pass_packet)
2034 xfree (rs->last_pass_packet);
2035 rs->last_pass_packet = pass_packet;
89be2091
DJ
2036 }
2037 else
2038 xfree (pass_packet);
2039 }
2040}
2041
82075af2
JS
2042/* If 'QCatchSyscalls' is supported, tell the remote stub
2043 to report syscalls to GDB. */
2044
2045static int
2046remote_set_syscall_catchpoint (struct target_ops *self,
2047 int pid, int needed, int any_count,
2048 int table_size, int *table)
2049{
2050 char *catch_packet;
2051 enum packet_result result;
2052 int n_sysno = 0;
2053
2054 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2055 {
2056 /* Not supported. */
2057 return 1;
2058 }
2059
2060 if (needed && !any_count)
2061 {
2062 int i;
2063
2064 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2065 for (i = 0; i < table_size; i++)
2066 {
2067 if (table[i] != 0)
2068 n_sysno++;
2069 }
2070 }
2071
2072 if (remote_debug)
2073 {
2074 fprintf_unfiltered (gdb_stdlog,
2075 "remote_set_syscall_catchpoint "
2076 "pid %d needed %d any_count %d n_sysno %d\n",
2077 pid, needed, any_count, n_sysno);
2078 }
2079
2080 if (needed)
2081 {
2082 /* Prepare a packet with the sysno list, assuming max 8+1
2083 characters for a sysno. If the resulting packet size is too
2084 big, fallback on the non-selective packet. */
2085 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2086
c0518081 2087 catch_packet = (char *) xmalloc (maxpktsz);
82075af2
JS
2088 strcpy (catch_packet, "QCatchSyscalls:1");
2089 if (!any_count)
2090 {
2091 int i;
2092 char *p;
2093
2094 p = catch_packet;
2095 p += strlen (p);
2096
2097 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2098 for (i = 0; i < table_size; i++)
2099 {
2100 if (table[i] != 0)
2101 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2102 }
2103 }
2104 if (strlen (catch_packet) > get_remote_packet_size ())
2105 {
2106 /* catch_packet too big. Fallback to less efficient
2107 non selective mode, with GDB doing the filtering. */
2108 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2109 }
2110 }
2111 else
2112 catch_packet = xstrdup ("QCatchSyscalls:0");
2113
2114 {
2115 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2116 struct remote_state *rs = get_remote_state ();
2117
2118 putpkt (catch_packet);
2119 getpkt (&rs->buf, &rs->buf_size, 0);
2120 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2121 do_cleanups (old_chain);
2122 if (result == PACKET_OK)
2123 return 0;
2124 else
2125 return -1;
2126 }
2127}
2128
9b224c5e
PA
2129/* If 'QProgramSignals' is supported, tell the remote stub what
2130 signals it should pass through to the inferior when detaching. */
2131
2132static void
daf5e9b6
TT
2133remote_program_signals (struct target_ops *self,
2134 int numsigs, unsigned char *signals)
9b224c5e 2135{
4082afcc 2136 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2137 {
2138 char *packet, *p;
2139 int count = 0, i;
5e4a05c4 2140 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2141
2142 gdb_assert (numsigs < 256);
2143 for (i = 0; i < numsigs; i++)
2144 {
2145 if (signals[i])
2146 count++;
2147 }
224c3ddb 2148 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2149 strcpy (packet, "QProgramSignals:");
2150 p = packet + strlen (packet);
2151 for (i = 0; i < numsigs; i++)
2152 {
2153 if (signal_pass_state (i))
2154 {
2155 if (i >= 16)
2156 *p++ = tohex (i >> 4);
2157 *p++ = tohex (i & 15);
2158 if (count)
2159 *p++ = ';';
2160 else
2161 break;
2162 count--;
2163 }
2164 }
2165 *p = 0;
5e4a05c4
TT
2166 if (!rs->last_program_signals_packet
2167 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2168 {
9b224c5e
PA
2169 putpkt (packet);
2170 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2171 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2172 xfree (rs->last_program_signals_packet);
2173 rs->last_program_signals_packet = packet;
9b224c5e
PA
2174 }
2175 else
2176 xfree (packet);
2177 }
2178}
2179
79d7f229
PA
2180/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2181 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2182 thread. If GEN is set, set the general thread, if not, then set
2183 the step/continue thread. */
c906108c 2184static void
79d7f229 2185set_thread (struct ptid ptid, int gen)
c906108c 2186{
d01949b6 2187 struct remote_state *rs = get_remote_state ();
47f8a51d 2188 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2189 char *buf = rs->buf;
79d7f229 2190 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2191
79d7f229 2192 if (ptid_equal (state, ptid))
c906108c
SS
2193 return;
2194
79d7f229
PA
2195 *buf++ = 'H';
2196 *buf++ = gen ? 'g' : 'c';
2197 if (ptid_equal (ptid, magic_null_ptid))
2198 xsnprintf (buf, endbuf - buf, "0");
2199 else if (ptid_equal (ptid, any_thread_ptid))
2200 xsnprintf (buf, endbuf - buf, "0");
2201 else if (ptid_equal (ptid, minus_one_ptid))
2202 xsnprintf (buf, endbuf - buf, "-1");
2203 else
82f73884 2204 write_ptid (buf, endbuf, ptid);
79d7f229 2205 putpkt (rs->buf);
6d820c5c 2206 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2207 if (gen)
47f8a51d 2208 rs->general_thread = ptid;
c906108c 2209 else
47f8a51d 2210 rs->continue_thread = ptid;
c906108c 2211}
79d7f229
PA
2212
2213static void
2214set_general_thread (struct ptid ptid)
2215{
2216 set_thread (ptid, 1);
2217}
2218
2219static void
2220set_continue_thread (struct ptid ptid)
2221{
2222 set_thread (ptid, 0);
2223}
2224
3c9c4b83
PA
2225/* Change the remote current process. Which thread within the process
2226 ends up selected isn't important, as long as it is the same process
2227 as what INFERIOR_PTID points to.
2228
2229 This comes from that fact that there is no explicit notion of
2230 "selected process" in the protocol. The selected process for
2231 general operations is the process the selected general thread
2232 belongs to. */
2233
2234static void
2235set_general_process (void)
2236{
2237 struct remote_state *rs = get_remote_state ();
2238
2239 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2240 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2241 return;
2242
2243 /* We only need to change the remote current thread if it's pointing
2244 at some other process. */
47f8a51d 2245 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2246 set_general_thread (inferior_ptid);
2247}
2248
c906108c 2249\f
7d1a114c
PA
2250/* Return nonzero if this is the main thread that we made up ourselves
2251 to model non-threaded targets as single-threaded. */
c906108c
SS
2252
2253static int
7d1a114c 2254remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2255{
c0a2216e
PA
2256 if (ptid_equal (ptid, magic_null_ptid))
2257 /* The main thread is always alive. */
2258 return 1;
2259
ba348170 2260 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2261 /* The main thread is always alive. This can happen after a
2262 vAttach, if the remote side doesn't support
2263 multi-threading. */
2264 return 1;
2265
7d1a114c
PA
2266 return 0;
2267}
2268
2269/* Return nonzero if the thread PTID is still alive on the remote
2270 system. */
2271
2272static int
2273remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2274{
2275 struct remote_state *rs = get_remote_state ();
2276 char *p, *endp;
2277
2278 /* Check if this is a thread that we made up ourselves to model
2279 non-threaded targets as single-threaded. */
2280 if (remote_thread_always_alive (ops, ptid))
2281 return 1;
2282
82f73884
PA
2283 p = rs->buf;
2284 endp = rs->buf + get_remote_packet_size ();
2285
2286 *p++ = 'T';
2287 write_ptid (p, endp, ptid);
2288
2e9f7625 2289 putpkt (rs->buf);
6d820c5c 2290 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2291 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2292}
2293
79efa585
SM
2294/* Return a pointer to a thread name if we know it and NULL otherwise.
2295 The thread_info object owns the memory for the name. */
2296
2297static const char *
2298remote_thread_name (struct target_ops *ops, struct thread_info *info)
2299{
2300 if (info->priv != NULL)
2301 return info->priv->name;
2302
2303 return NULL;
2304}
2305
c906108c
SS
2306/* About these extended threadlist and threadinfo packets. They are
2307 variable length packets but, the fields within them are often fixed
2308 length. They are redundent enough to send over UDP as is the
2309 remote protocol in general. There is a matching unit test module
2310 in libstub. */
2311
23860348 2312/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2313 libstub protocol encoding, and remote.c. It is not particularly
23860348 2314 changable. */
cce74817
JM
2315
2316/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2317 Plan to fix this. */
cce74817 2318
23860348 2319typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2320
9d1f7ab2 2321/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2322 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2323
2324struct gdb_ext_thread_info
c5aa993b 2325 {
23860348 2326 threadref threadid; /* External form of thread reference. */
2bc416ba 2327 int active; /* Has state interesting to GDB?
23860348 2328 regs, stack. */
2bc416ba 2329 char display[256]; /* Brief state display, name,
cedea757 2330 blocked/suspended. */
23860348 2331 char shortname[32]; /* To be used to name threads. */
2bc416ba 2332 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2333 whatever. */
c5aa993b 2334 };
cce74817
JM
2335
2336/* The volume of remote transfers can be limited by submitting
2337 a mask containing bits specifying the desired information.
2338 Use a union of these values as the 'selection' parameter to
0df8b418 2339 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2340
2341#define TAG_THREADID 1
2342#define TAG_EXISTS 2
2343#define TAG_DISPLAY 4
2344#define TAG_THREADNAME 8
c5aa993b 2345#define TAG_MOREDISPLAY 16
cce74817 2346
23860348 2347#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2348
a14ed312 2349static char *unpack_nibble (char *buf, int *val);
cce74817 2350
a14ed312 2351static char *unpack_byte (char *buf, int *value);
cce74817 2352
a14ed312 2353static char *pack_int (char *buf, int value);
cce74817 2354
a14ed312 2355static char *unpack_int (char *buf, int *value);
cce74817 2356
a14ed312 2357static char *unpack_string (char *src, char *dest, int length);
cce74817 2358
23860348 2359static char *pack_threadid (char *pkt, threadref *id);
cce74817 2360
23860348 2361static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2362
23860348 2363void int_to_threadref (threadref *id, int value);
cce74817 2364
23860348 2365static int threadref_to_int (threadref *ref);
cce74817 2366
23860348 2367static void copy_threadref (threadref *dest, threadref *src);
cce74817 2368
23860348 2369static int threadmatch (threadref *dest, threadref *src);
cce74817 2370
2bc416ba 2371static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2372 threadref *id);
cce74817 2373
a14ed312 2374static int remote_unpack_thread_info_response (char *pkt,
23860348 2375 threadref *expectedref,
a14ed312
KB
2376 struct gdb_ext_thread_info
2377 *info);
cce74817
JM
2378
2379
2bc416ba 2380static int remote_get_threadinfo (threadref *threadid,
23860348 2381 int fieldset, /*TAG mask */
a14ed312 2382 struct gdb_ext_thread_info *info);
cce74817 2383
a14ed312
KB
2384static char *pack_threadlist_request (char *pkt, int startflag,
2385 int threadcount,
23860348 2386 threadref *nextthread);
cce74817 2387
a14ed312
KB
2388static int parse_threadlist_response (char *pkt,
2389 int result_limit,
23860348 2390 threadref *original_echo,
2bc416ba 2391 threadref *resultlist,
23860348 2392 int *doneflag);
cce74817 2393
a14ed312 2394static int remote_get_threadlist (int startflag,
23860348 2395 threadref *nextthread,
a14ed312
KB
2396 int result_limit,
2397 int *done,
2bc416ba 2398 int *result_count,
23860348 2399 threadref *threadlist);
cce74817 2400
23860348 2401typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2402
a14ed312
KB
2403static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2404 void *context, int looplimit);
cce74817 2405
23860348 2406static int remote_newthread_step (threadref *ref, void *context);
cce74817 2407
82f73884
PA
2408
2409/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2410 buffer we're allowed to write to. Returns
2411 BUF+CHARACTERS_WRITTEN. */
2412
2413static char *
2414write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2415{
2416 int pid, tid;
2417 struct remote_state *rs = get_remote_state ();
2418
2419 if (remote_multi_process_p (rs))
2420 {
2421 pid = ptid_get_pid (ptid);
2422 if (pid < 0)
2423 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2424 else
2425 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2426 }
ba348170 2427 tid = ptid_get_lwp (ptid);
82f73884
PA
2428 if (tid < 0)
2429 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2430 else
2431 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2432
2433 return buf;
2434}
2435
2436/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2437 passed the last parsed char. Returns null_ptid on error. */
2438
2439static ptid_t
2440read_ptid (char *buf, char **obuf)
2441{
2442 char *p = buf;
2443 char *pp;
2444 ULONGEST pid = 0, tid = 0;
82f73884
PA
2445
2446 if (*p == 'p')
2447 {
2448 /* Multi-process ptid. */
2449 pp = unpack_varlen_hex (p + 1, &pid);
2450 if (*pp != '.')
b37520b6 2451 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2452
2453 p = pp;
2454 pp = unpack_varlen_hex (p + 1, &tid);
2455 if (obuf)
2456 *obuf = pp;
ba348170 2457 return ptid_build (pid, tid, 0);
82f73884
PA
2458 }
2459
2460 /* No multi-process. Just a tid. */
2461 pp = unpack_varlen_hex (p, &tid);
2462
c9f35b34
KB
2463 /* Return null_ptid when no thread id is found. */
2464 if (p == pp)
2465 {
2466 if (obuf)
2467 *obuf = pp;
2468 return null_ptid;
2469 }
2470
82f73884 2471 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2472 what's in inferior_ptid, unless it's null at this point. If so,
2473 then since there's no way to know the pid of the reported
2474 threads, use the magic number. */
2475 if (ptid_equal (inferior_ptid, null_ptid))
2476 pid = ptid_get_pid (magic_null_ptid);
2477 else
2478 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2479
2480 if (obuf)
2481 *obuf = pp;
ba348170 2482 return ptid_build (pid, tid, 0);
82f73884
PA
2483}
2484
c906108c 2485static int
fba45db2 2486stubhex (int ch)
c906108c
SS
2487{
2488 if (ch >= 'a' && ch <= 'f')
2489 return ch - 'a' + 10;
2490 if (ch >= '0' && ch <= '9')
2491 return ch - '0';
2492 if (ch >= 'A' && ch <= 'F')
2493 return ch - 'A' + 10;
2494 return -1;
2495}
2496
2497static int
fba45db2 2498stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2499{
2500 int nibble;
2501 int retval = 0;
2502
2503 while (fieldlength)
2504 {
2505 nibble = stubhex (*buff++);
2506 retval |= nibble;
2507 fieldlength--;
2508 if (fieldlength)
2509 retval = retval << 4;
2510 }
2511 return retval;
2512}
2513
c906108c 2514static char *
fba45db2 2515unpack_nibble (char *buf, int *val)
c906108c 2516{
b7589f7d 2517 *val = fromhex (*buf++);
c906108c
SS
2518 return buf;
2519}
2520
c906108c 2521static char *
fba45db2 2522unpack_byte (char *buf, int *value)
c906108c
SS
2523{
2524 *value = stub_unpack_int (buf, 2);
2525 return buf + 2;
2526}
2527
2528static char *
fba45db2 2529pack_int (char *buf, int value)
c906108c
SS
2530{
2531 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2532 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2533 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2534 buf = pack_hex_byte (buf, (value & 0xff));
2535 return buf;
2536}
2537
2538static char *
fba45db2 2539unpack_int (char *buf, int *value)
c906108c
SS
2540{
2541 *value = stub_unpack_int (buf, 8);
2542 return buf + 8;
2543}
2544
23860348 2545#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2546static char *pack_string (char *pkt, char *string);
c906108c
SS
2547
2548static char *
fba45db2 2549pack_string (char *pkt, char *string)
c906108c
SS
2550{
2551 char ch;
2552 int len;
2553
2554 len = strlen (string);
2555 if (len > 200)
23860348 2556 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2557 pkt = pack_hex_byte (pkt, len);
2558 while (len-- > 0)
2559 {
2560 ch = *string++;
2561 if ((ch == '\0') || (ch == '#'))
23860348 2562 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2563 *pkt++ = ch;
2564 }
2565 return pkt;
2566}
2567#endif /* 0 (unused) */
2568
2569static char *
fba45db2 2570unpack_string (char *src, char *dest, int length)
c906108c
SS
2571{
2572 while (length--)
2573 *dest++ = *src++;
2574 *dest = '\0';
2575 return src;
2576}
2577
2578static char *
fba45db2 2579pack_threadid (char *pkt, threadref *id)
c906108c
SS
2580{
2581 char *limit;
2582 unsigned char *altid;
2583
2584 altid = (unsigned char *) id;
2585 limit = pkt + BUF_THREAD_ID_SIZE;
2586 while (pkt < limit)
2587 pkt = pack_hex_byte (pkt, *altid++);
2588 return pkt;
2589}
2590
2591
2592static char *
fba45db2 2593unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2594{
2595 char *altref;
2596 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2597 int x, y;
2598
2599 altref = (char *) id;
2600
2601 while (inbuf < limit)
2602 {
2603 x = stubhex (*inbuf++);
2604 y = stubhex (*inbuf++);
2605 *altref++ = (x << 4) | y;
2606 }
2607 return inbuf;
2608}
2609
2610/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2611 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2612 to use 64bit thread references internally. This is an adapter
2613 function. */
2614
2615void
fba45db2 2616int_to_threadref (threadref *id, int value)
c906108c
SS
2617{
2618 unsigned char *scan;
2619
2620 scan = (unsigned char *) id;
2621 {
2622 int i = 4;
2623 while (i--)
2624 *scan++ = 0;
2625 }
2626 *scan++ = (value >> 24) & 0xff;
2627 *scan++ = (value >> 16) & 0xff;
2628 *scan++ = (value >> 8) & 0xff;
2629 *scan++ = (value & 0xff);
2630}
2631
2632static int
fba45db2 2633threadref_to_int (threadref *ref)
c906108c
SS
2634{
2635 int i, value = 0;
2636 unsigned char *scan;
2637
cfd77fa1 2638 scan = *ref;
c906108c
SS
2639 scan += 4;
2640 i = 4;
2641 while (i-- > 0)
2642 value = (value << 8) | ((*scan++) & 0xff);
2643 return value;
2644}
2645
2646static void
fba45db2 2647copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2648{
2649 int i;
2650 unsigned char *csrc, *cdest;
2651
2652 csrc = (unsigned char *) src;
2653 cdest = (unsigned char *) dest;
2654 i = 8;
2655 while (i--)
2656 *cdest++ = *csrc++;
2657}
2658
2659static int
fba45db2 2660threadmatch (threadref *dest, threadref *src)
c906108c 2661{
23860348 2662 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2663#if 0
2664 unsigned char *srcp, *destp;
2665 int i, result;
2666 srcp = (char *) src;
2667 destp = (char *) dest;
2668
2669 result = 1;
2670 while (i-- > 0)
2671 result &= (*srcp++ == *destp++) ? 1 : 0;
2672 return result;
2673#endif
2674 return 1;
2675}
2676
2677/*
c5aa993b
JM
2678 threadid:1, # always request threadid
2679 context_exists:2,
2680 display:4,
2681 unique_name:8,
2682 more_display:16
2683 */
c906108c
SS
2684
2685/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2686
2687static char *
fba45db2 2688pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2689{
23860348
MS
2690 *pkt++ = 'q'; /* Info Query */
2691 *pkt++ = 'P'; /* process or thread info */
2692 pkt = pack_int (pkt, mode); /* mode */
c906108c 2693 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2694 *pkt = '\0'; /* terminate */
c906108c
SS
2695 return pkt;
2696}
2697
23860348 2698/* These values tag the fields in a thread info response packet. */
c906108c 2699/* Tagging the fields allows us to request specific fields and to
23860348 2700 add more fields as time goes by. */
c906108c 2701
23860348 2702#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2703#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2704 fetch registers and its stack? */
c5aa993b 2705#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2706#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2707#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2708 the process. */
c906108c
SS
2709
2710static int
fba45db2
KB
2711remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2712 struct gdb_ext_thread_info *info)
c906108c 2713{
d01949b6 2714 struct remote_state *rs = get_remote_state ();
c906108c 2715 int mask, length;
cfd77fa1 2716 int tag;
c906108c 2717 threadref ref;
6d820c5c 2718 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2719 int retval = 1;
2720
23860348 2721 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2722 info->active = 0;
2723 info->display[0] = '\0';
2724 info->shortname[0] = '\0';
2725 info->more_display[0] = '\0';
2726
23860348
MS
2727 /* Assume the characters indicating the packet type have been
2728 stripped. */
c906108c
SS
2729 pkt = unpack_int (pkt, &mask); /* arg mask */
2730 pkt = unpack_threadid (pkt, &ref);
2731
2732 if (mask == 0)
8a3fe4f8 2733 warning (_("Incomplete response to threadinfo request."));
c906108c 2734 if (!threadmatch (&ref, expectedref))
23860348 2735 { /* This is an answer to a different request. */
8a3fe4f8 2736 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2737 return 0;
2738 }
2739 copy_threadref (&info->threadid, &ref);
2740
23860348 2741 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2742
23860348
MS
2743 /* Packets are terminated with nulls. */
2744 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2745 {
2746 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2747 pkt = unpack_byte (pkt, &length); /* length */
2748 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2749 {
8a3fe4f8 2750 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2751 retval = 0;
2752 break;
2753 }
2754 if (tag == TAG_THREADID)
2755 {
2756 if (length != 16)
2757 {
8a3fe4f8 2758 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2759 retval = 0;
2760 break;
2761 }
2762 pkt = unpack_threadid (pkt, &ref);
2763 mask = mask & ~TAG_THREADID;
2764 continue;
2765 }
2766 if (tag == TAG_EXISTS)
2767 {
2768 info->active = stub_unpack_int (pkt, length);
2769 pkt += length;
2770 mask = mask & ~(TAG_EXISTS);
2771 if (length > 8)
2772 {
8a3fe4f8 2773 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2774 retval = 0;
2775 break;
2776 }
2777 continue;
2778 }
2779 if (tag == TAG_THREADNAME)
2780 {
2781 pkt = unpack_string (pkt, &info->shortname[0], length);
2782 mask = mask & ~TAG_THREADNAME;
2783 continue;
2784 }
2785 if (tag == TAG_DISPLAY)
2786 {
2787 pkt = unpack_string (pkt, &info->display[0], length);
2788 mask = mask & ~TAG_DISPLAY;
2789 continue;
2790 }
2791 if (tag == TAG_MOREDISPLAY)
2792 {
2793 pkt = unpack_string (pkt, &info->more_display[0], length);
2794 mask = mask & ~TAG_MOREDISPLAY;
2795 continue;
2796 }
8a3fe4f8 2797 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2798 break; /* Not a tag we know about. */
c906108c
SS
2799 }
2800 return retval;
2801}
2802
2803static int
fba45db2
KB
2804remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2805 struct gdb_ext_thread_info *info)
c906108c 2806{
d01949b6 2807 struct remote_state *rs = get_remote_state ();
c906108c 2808 int result;
c906108c 2809
2e9f7625
DJ
2810 pack_threadinfo_request (rs->buf, fieldset, threadid);
2811 putpkt (rs->buf);
6d820c5c 2812 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2813
2814 if (rs->buf[0] == '\0')
2815 return 0;
2816
2e9f7625 2817 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2818 threadid, info);
c906108c
SS
2819 return result;
2820}
2821
c906108c
SS
2822/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2823
2824static char *
fba45db2
KB
2825pack_threadlist_request (char *pkt, int startflag, int threadcount,
2826 threadref *nextthread)
c906108c
SS
2827{
2828 *pkt++ = 'q'; /* info query packet */
2829 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2830 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2831 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2832 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2833 *pkt = '\0';
2834 return pkt;
2835}
2836
2837/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2838
2839static int
fba45db2
KB
2840parse_threadlist_response (char *pkt, int result_limit,
2841 threadref *original_echo, threadref *resultlist,
2842 int *doneflag)
c906108c 2843{
d01949b6 2844 struct remote_state *rs = get_remote_state ();
c906108c
SS
2845 char *limit;
2846 int count, resultcount, done;
2847
2848 resultcount = 0;
2849 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2850 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2851 /* done parse past here */
c906108c
SS
2852 pkt = unpack_byte (pkt, &count); /* count field */
2853 pkt = unpack_nibble (pkt, &done);
2854 /* The first threadid is the argument threadid. */
2855 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2856 while ((count-- > 0) && (pkt < limit))
2857 {
2858 pkt = unpack_threadid (pkt, resultlist++);
2859 if (resultcount++ >= result_limit)
2860 break;
2861 }
2862 if (doneflag)
2863 *doneflag = done;
2864 return resultcount;
2865}
2866
6dc54d91
PA
2867/* Fetch the next batch of threads from the remote. Returns -1 if the
2868 qL packet is not supported, 0 on error and 1 on success. */
2869
c906108c 2870static int
fba45db2
KB
2871remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2872 int *done, int *result_count, threadref *threadlist)
c906108c 2873{
d01949b6 2874 struct remote_state *rs = get_remote_state ();
c906108c
SS
2875 int result = 1;
2876
23860348 2877 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2878 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2879 >= get_remote_packet_size ())
ea9c271d 2880 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2881
6d820c5c
DJ
2882 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2883 putpkt (rs->buf);
2884 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2885 if (*rs->buf == '\0')
6dc54d91
PA
2886 {
2887 /* Packet not supported. */
2888 return -1;
2889 }
2890
2891 *result_count =
2892 parse_threadlist_response (rs->buf + 2, result_limit,
2893 &rs->echo_nextthread, threadlist, done);
c906108c 2894
0d031856 2895 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2896 {
23860348
MS
2897 /* FIXME: This is a good reason to drop the packet. */
2898 /* Possably, there is a duplicate response. */
c906108c
SS
2899 /* Possabilities :
2900 retransmit immediatly - race conditions
2901 retransmit after timeout - yes
2902 exit
2903 wait for packet, then exit
2904 */
8a3fe4f8 2905 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2906 return 0; /* I choose simply exiting. */
c906108c
SS
2907 }
2908 if (*result_count <= 0)
2909 {
2910 if (*done != 1)
2911 {
8a3fe4f8 2912 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2913 result = 0;
2914 }
2915 return result; /* break; */
2916 }
2917 if (*result_count > result_limit)
2918 {
2919 *result_count = 0;
8a3fe4f8 2920 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2921 return 0;
2922 }
2923 return result;
2924}
2925
6dc54d91
PA
2926/* Fetch the list of remote threads, with the qL packet, and call
2927 STEPFUNCTION for each thread found. Stops iterating and returns 1
2928 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2929 STEPFUNCTION returns false. If the packet is not supported,
2930 returns -1. */
c906108c 2931
c906108c 2932static int
fba45db2
KB
2933remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2934 int looplimit)
c906108c 2935{
0d031856 2936 struct remote_state *rs = get_remote_state ();
c906108c
SS
2937 int done, i, result_count;
2938 int startflag = 1;
2939 int result = 1;
2940 int loopcount = 0;
c906108c
SS
2941
2942 done = 0;
2943 while (!done)
2944 {
2945 if (loopcount++ > looplimit)
2946 {
2947 result = 0;
8a3fe4f8 2948 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2949 break;
2950 }
6dc54d91
PA
2951 result = remote_get_threadlist (startflag, &rs->nextthread,
2952 MAXTHREADLISTRESULTS,
2953 &done, &result_count,
2954 rs->resultthreadlist);
2955 if (result <= 0)
2956 break;
23860348 2957 /* Clear for later iterations. */
c906108c
SS
2958 startflag = 0;
2959 /* Setup to resume next batch of thread references, set nextthread. */
2960 if (result_count >= 1)
0d031856
TT
2961 copy_threadref (&rs->nextthread,
2962 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2963 i = 0;
2964 while (result_count--)
6dc54d91
PA
2965 {
2966 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2967 {
2968 result = 0;
2969 break;
2970 }
2971 }
c906108c
SS
2972 }
2973 return result;
2974}
2975
6dc54d91
PA
2976/* A thread found on the remote target. */
2977
2978typedef struct thread_item
2979{
2980 /* The thread's PTID. */
2981 ptid_t ptid;
2982
2983 /* The thread's extra info. May be NULL. */
2984 char *extra;
2985
79efa585
SM
2986 /* The thread's name. May be NULL. */
2987 char *name;
2988
6dc54d91
PA
2989 /* The core the thread was running on. -1 if not known. */
2990 int core;
2991} thread_item_t;
2992DEF_VEC_O(thread_item_t);
2993
2994/* Context passed around to the various methods listing remote
2995 threads. As new threads are found, they're added to the ITEMS
2996 vector. */
2997
2998struct threads_listing_context
2999{
3000 /* The threads found on the remote target. */
3001 VEC (thread_item_t) *items;
3002};
3003
80134cf5
PA
3004/* Discard the contents of the constructed thread listing context. */
3005
3006static void
3007clear_threads_listing_context (void *p)
3008{
19ba03f4
SM
3009 struct threads_listing_context *context
3010 = (struct threads_listing_context *) p;
80134cf5
PA
3011 int i;
3012 struct thread_item *item;
3013
3014 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
3015 {
3016 xfree (item->extra);
3017 xfree (item->name);
3018 }
80134cf5
PA
3019
3020 VEC_free (thread_item_t, context->items);
3021}
3022
cbb8991c
DB
3023/* Remove the thread specified as the related_pid field of WS
3024 from the CONTEXT list. */
3025
3026static void
3027threads_listing_context_remove (struct target_waitstatus *ws,
3028 struct threads_listing_context *context)
3029{
3030 struct thread_item *item;
3031 int i;
3032 ptid_t child_ptid = ws->value.related_pid;
3033
3034 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3035 {
3036 if (ptid_equal (item->ptid, child_ptid))
3037 {
3038 VEC_ordered_remove (thread_item_t, context->items, i);
3039 break;
3040 }
3041 }
3042}
3043
c906108c 3044static int
6dc54d91 3045remote_newthread_step (threadref *ref, void *data)
c906108c 3046{
19ba03f4
SM
3047 struct threads_listing_context *context
3048 = (struct threads_listing_context *) data;
6dc54d91 3049 struct thread_item item;
79d7f229 3050 int pid = ptid_get_pid (inferior_ptid);
39f77062 3051
6dc54d91
PA
3052 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3053 item.core = -1;
2e3b657e 3054 item.name = NULL;
6dc54d91
PA
3055 item.extra = NULL;
3056
3057 VEC_safe_push (thread_item_t, context->items, &item);
3058
c906108c
SS
3059 return 1; /* continue iterator */
3060}
3061
3062#define CRAZY_MAX_THREADS 1000
3063
39f77062
KB
3064static ptid_t
3065remote_current_thread (ptid_t oldpid)
c906108c 3066{
d01949b6 3067 struct remote_state *rs = get_remote_state ();
c906108c
SS
3068
3069 putpkt ("qC");
6d820c5c 3070 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3071 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
3072 {
3073 char *obuf;
3074 ptid_t result;
3075
3076 result = read_ptid (&rs->buf[2], &obuf);
3077 if (*obuf != '\0' && remote_debug)
3078 fprintf_unfiltered (gdb_stdlog,
3079 "warning: garbage in qC reply\n");
3080
3081 return result;
3082 }
c906108c
SS
3083 else
3084 return oldpid;
3085}
3086
6dc54d91 3087/* List remote threads using the deprecated qL packet. */
cce74817 3088
6dc54d91
PA
3089static int
3090remote_get_threads_with_ql (struct target_ops *ops,
3091 struct threads_listing_context *context)
c906108c 3092{
6dc54d91
PA
3093 if (remote_threadlist_iterator (remote_newthread_step, context,
3094 CRAZY_MAX_THREADS) >= 0)
3095 return 1;
3096
3097 return 0;
c906108c
SS
3098}
3099
dc146f7c
VP
3100#if defined(HAVE_LIBEXPAT)
3101
dc146f7c
VP
3102static void
3103start_thread (struct gdb_xml_parser *parser,
3104 const struct gdb_xml_element *element,
3105 void *user_data, VEC(gdb_xml_value_s) *attributes)
3106{
19ba03f4
SM
3107 struct threads_listing_context *data
3108 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3109
3110 struct thread_item item;
3111 char *id;
3d2c1d41 3112 struct gdb_xml_value *attr;
dc146f7c 3113
19ba03f4 3114 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
3115 item.ptid = read_ptid (id, NULL);
3116
3d2c1d41
PA
3117 attr = xml_find_attribute (attributes, "core");
3118 if (attr != NULL)
3119 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
3120 else
3121 item.core = -1;
3122
79efa585 3123 attr = xml_find_attribute (attributes, "name");
e1961661 3124 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 3125
dc146f7c
VP
3126 item.extra = 0;
3127
3128 VEC_safe_push (thread_item_t, data->items, &item);
3129}
3130
3131static void
3132end_thread (struct gdb_xml_parser *parser,
3133 const struct gdb_xml_element *element,
3134 void *user_data, const char *body_text)
3135{
19ba03f4
SM
3136 struct threads_listing_context *data
3137 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3138
3139 if (body_text && *body_text)
2ae2a0b7 3140 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3141}
3142
3143const struct gdb_xml_attribute thread_attributes[] = {
3144 { "id", GDB_XML_AF_NONE, NULL, NULL },
3145 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3146 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3147 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3148};
3149
3150const struct gdb_xml_element thread_children[] = {
3151 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3152};
3153
3154const struct gdb_xml_element threads_children[] = {
3155 { "thread", thread_attributes, thread_children,
3156 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3157 start_thread, end_thread },
3158 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3159};
3160
3161const struct gdb_xml_element threads_elements[] = {
3162 { "threads", NULL, threads_children,
3163 GDB_XML_EF_NONE, NULL, NULL },
3164 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3165};
3166
3167#endif
3168
6dc54d91 3169/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3170
6dc54d91
PA
3171static int
3172remote_get_threads_with_qxfer (struct target_ops *ops,
3173 struct threads_listing_context *context)
0f71a2f6 3174{
dc146f7c 3175#if defined(HAVE_LIBEXPAT)
4082afcc 3176 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3177 {
6dc54d91 3178 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3179 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3180
6dc54d91 3181 if (xml != NULL && *xml != '\0')
dc146f7c 3182 {
6dc54d91
PA
3183 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3184 threads_elements, xml, context);
dc146f7c
VP
3185 }
3186
3187 do_cleanups (back_to);
6dc54d91 3188 return 1;
dc146f7c
VP
3189 }
3190#endif
3191
6dc54d91
PA
3192 return 0;
3193}
3194
3195/* List remote threads using qfThreadInfo/qsThreadInfo. */
3196
3197static int
3198remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3199 struct threads_listing_context *context)
3200{
3201 struct remote_state *rs = get_remote_state ();
3202
b80fafe3 3203 if (rs->use_threadinfo_query)
9d1f7ab2 3204 {
6dc54d91
PA
3205 char *bufp;
3206
9d1f7ab2 3207 putpkt ("qfThreadInfo");
6d820c5c 3208 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3209 bufp = rs->buf;
9d1f7ab2 3210 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3211 {
9d1f7ab2
MS
3212 while (*bufp++ == 'm') /* reply contains one or more TID */
3213 {
3214 do
3215 {
6dc54d91
PA
3216 struct thread_item item;
3217
3218 item.ptid = read_ptid (bufp, &bufp);
3219 item.core = -1;
2e3b657e 3220 item.name = NULL;
6dc54d91
PA
3221 item.extra = NULL;
3222
3223 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3224 }
3225 while (*bufp++ == ','); /* comma-separated list */
3226 putpkt ("qsThreadInfo");
6d820c5c 3227 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3228 bufp = rs->buf;
9d1f7ab2 3229 }
6dc54d91
PA
3230 return 1;
3231 }
3232 else
3233 {
3234 /* Packet not recognized. */
3235 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3236 }
3237 }
3238
6dc54d91
PA
3239 return 0;
3240}
3241
e8032dde 3242/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3243 targets. */
3244
3245static void
e8032dde 3246remote_update_thread_list (struct target_ops *ops)
6dc54d91 3247{
6dc54d91
PA
3248 struct threads_listing_context context;
3249 struct cleanup *old_chain;
ab970af1 3250 int got_list = 0;
e8032dde 3251
6dc54d91
PA
3252 context.items = NULL;
3253 old_chain = make_cleanup (clear_threads_listing_context, &context);
3254
3255 /* We have a few different mechanisms to fetch the thread list. Try
3256 them all, starting with the most preferred one first, falling
3257 back to older methods. */
3258 if (remote_get_threads_with_qxfer (ops, &context)
3259 || remote_get_threads_with_qthreadinfo (ops, &context)
3260 || remote_get_threads_with_ql (ops, &context))
3261 {
3262 int i;
3263 struct thread_item *item;
ab970af1
PA
3264 struct thread_info *tp, *tmp;
3265
3266 got_list = 1;
3267
7d1a114c
PA
3268 if (VEC_empty (thread_item_t, context.items)
3269 && remote_thread_always_alive (ops, inferior_ptid))
3270 {
3271 /* Some targets don't really support threads, but still
3272 reply an (empty) thread list in response to the thread
3273 listing packets, instead of replying "packet not
3274 supported". Exit early so we don't delete the main
3275 thread. */
3276 do_cleanups (old_chain);
3277 return;
3278 }
3279
ab970af1
PA
3280 /* CONTEXT now holds the current thread list on the remote
3281 target end. Delete GDB-side threads no longer found on the
3282 target. */
8a06aea7 3283 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3284 {
ab970af1
PA
3285 for (i = 0;
3286 VEC_iterate (thread_item_t, context.items, i, item);
3287 ++i)
3288 {
3289 if (ptid_equal (item->ptid, tp->ptid))
3290 break;
3291 }
3292
3293 if (i == VEC_length (thread_item_t, context.items))
3294 {
3295 /* Not found. */
3296 delete_thread (tp->ptid);
3297 }
cbb8991c
DB
3298 }
3299
3300 /* Remove any unreported fork child threads from CONTEXT so
3301 that we don't interfere with follow fork, which is where
3302 creation of such threads is handled. */
3303 remove_new_fork_children (&context);
74531fed 3304
ab970af1 3305 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3306 for (i = 0;
3307 VEC_iterate (thread_item_t, context.items, i, item);
3308 ++i)
3309 {
3310 if (!ptid_equal (item->ptid, null_ptid))
3311 {
3312 struct private_thread_info *info;
3313 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3314 executing until proven otherwise with a stop reply.
3315 In all-stop, we can only get here if all threads are
6dc54d91 3316 stopped. */
0d5b594f 3317 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3318
0d5b594f 3319 remote_notice_new_inferior (item->ptid, executing);
6dc54d91 3320
85ad3aaf 3321 info = get_private_info_ptid (item->ptid);
6dc54d91
PA
3322 info->core = item->core;
3323 info->extra = item->extra;
3324 item->extra = NULL;
79efa585
SM
3325 info->name = item->name;
3326 item->name = NULL;
6dc54d91
PA
3327 }
3328 }
3329 }
3330
ab970af1
PA
3331 if (!got_list)
3332 {
3333 /* If no thread listing method is supported, then query whether
3334 each known thread is alive, one by one, with the T packet.
3335 If the target doesn't support threads at all, then this is a
3336 no-op. See remote_thread_alive. */
3337 prune_threads ();
3338 }
3339
6dc54d91 3340 do_cleanups (old_chain);
9d1f7ab2
MS
3341}
3342
802188a7 3343/*
9d1f7ab2
MS
3344 * Collect a descriptive string about the given thread.
3345 * The target may say anything it wants to about the thread
3346 * (typically info about its blocked / runnable state, name, etc.).
3347 * This string will appear in the info threads display.
802188a7 3348 *
9d1f7ab2
MS
3349 * Optional: targets are not required to implement this function.
3350 */
3351
3352static char *
c15906d8 3353remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3354{
d01949b6 3355 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3356 int result;
3357 int set;
3358 threadref id;
3359 struct gdb_ext_thread_info threadinfo;
23860348 3360 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3361 int n = 0; /* position in display_buf */
3362
5d93a237 3363 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3364 internal_error (__FILE__, __LINE__,
e2e0b3e5 3365 _("remote_threads_extra_info"));
9d1f7ab2 3366
60e569b9 3367 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3368 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3369 /* This is the main thread which was added by GDB. The remote
3370 server doesn't know about it. */
3371 return NULL;
3372
4082afcc 3373 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3374 {
3375 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3376
fe978cb0
PA
3377 if (info && info->priv)
3378 return info->priv->extra;
dc146f7c
VP
3379 else
3380 return NULL;
3381 }
3382
b80fafe3 3383 if (rs->use_threadextra_query)
9d1f7ab2 3384 {
82f73884
PA
3385 char *b = rs->buf;
3386 char *endb = rs->buf + get_remote_packet_size ();
3387
3388 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3389 b += strlen (b);
3390 write_ptid (b, endb, tp->ptid);
3391
2e9f7625 3392 putpkt (rs->buf);
6d820c5c 3393 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3394 if (rs->buf[0] != 0)
9d1f7ab2 3395 {
325fac50 3396 n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
2e9f7625 3397 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3398 display_buf [result] = '\0';
9d1f7ab2
MS
3399 return display_buf;
3400 }
0f71a2f6 3401 }
9d1f7ab2
MS
3402
3403 /* If the above query fails, fall back to the old method. */
b80fafe3 3404 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3405 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3406 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3407 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3408 if (remote_get_threadinfo (&id, set, &threadinfo))
3409 if (threadinfo.active)
0f71a2f6 3410 {
9d1f7ab2 3411 if (*threadinfo.shortname)
2bc416ba 3412 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3413 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3414 if (*threadinfo.display)
2bc416ba 3415 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3416 " State: %s,", threadinfo.display);
9d1f7ab2 3417 if (*threadinfo.more_display)
2bc416ba 3418 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3419 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3420
3421 if (n > 0)
c5aa993b 3422 {
23860348 3423 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3424 if (',' == display_buf[n-1])
3425 display_buf[n-1] = ' ';
3426 return display_buf;
c5aa993b 3427 }
0f71a2f6 3428 }
9d1f7ab2 3429 return NULL;
0f71a2f6 3430}
c906108c 3431\f
c5aa993b 3432
0fb4aa4b 3433static int
61fc905d 3434remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3435 struct static_tracepoint_marker *marker)
3436{
3437 struct remote_state *rs = get_remote_state ();
3438 char *p = rs->buf;
3439
bba74b36 3440 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3441 p += strlen (p);
3442 p += hexnumstr (p, addr);
3443 putpkt (rs->buf);
3444 getpkt (&rs->buf, &rs->buf_size, 0);
3445 p = rs->buf;
3446
3447 if (*p == 'E')
3448 error (_("Remote failure reply: %s"), p);
3449
3450 if (*p++ == 'm')
3451 {
3452 parse_static_tracepoint_marker_definition (p, &p, marker);
3453 return 1;
3454 }
3455
3456 return 0;
3457}
3458
0fb4aa4b 3459static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3460remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3461 const char *strid)
0fb4aa4b
PA
3462{
3463 struct remote_state *rs = get_remote_state ();
3464 VEC(static_tracepoint_marker_p) *markers = NULL;
3465 struct static_tracepoint_marker *marker = NULL;
3466 struct cleanup *old_chain;
3467 char *p;
3468
3469 /* Ask for a first packet of static tracepoint marker
3470 definition. */
3471 putpkt ("qTfSTM");
3472 getpkt (&rs->buf, &rs->buf_size, 0);
3473 p = rs->buf;
3474 if (*p == 'E')
3475 error (_("Remote failure reply: %s"), p);
3476
3477 old_chain = make_cleanup (free_current_marker, &marker);
3478
3479 while (*p++ == 'm')
3480 {
3481 if (marker == NULL)
3482 marker = XCNEW (struct static_tracepoint_marker);
3483
3484 do
3485 {
3486 parse_static_tracepoint_marker_definition (p, &p, marker);
3487
3488 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3489 {
3490 VEC_safe_push (static_tracepoint_marker_p,
3491 markers, marker);
3492 marker = NULL;
3493 }
3494 else
3495 {
3496 release_static_tracepoint_marker (marker);
3497 memset (marker, 0, sizeof (*marker));
3498 }
3499 }
3500 while (*p++ == ','); /* comma-separated list */
3501 /* Ask for another packet of static tracepoint definition. */
3502 putpkt ("qTsSTM");
3503 getpkt (&rs->buf, &rs->buf_size, 0);
3504 p = rs->buf;
3505 }
3506
3507 do_cleanups (old_chain);
3508 return markers;
3509}
3510
3511\f
10760264
JB
3512/* Implement the to_get_ada_task_ptid function for the remote targets. */
3513
3514static ptid_t
1e6b91a4 3515remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3516{
ba348170 3517 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3518}
3519\f
3520
24b06219 3521/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3522
3523static void
fba45db2 3524extended_remote_restart (void)
c906108c 3525{
d01949b6 3526 struct remote_state *rs = get_remote_state ();
c906108c
SS
3527
3528 /* Send the restart command; for reasons I don't understand the
3529 remote side really expects a number after the "R". */
ea9c271d 3530 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3531 putpkt (rs->buf);
c906108c 3532
ad9a8f3f 3533 remote_fileio_reset ();
c906108c
SS
3534}
3535\f
3536/* Clean up connection to a remote debugger. */
3537
c906108c 3538static void
de90e03d 3539remote_close (struct target_ops *self)
c906108c 3540{
5d93a237
TT
3541 struct remote_state *rs = get_remote_state ();
3542
3543 if (rs->remote_desc == NULL)
d3fd5342
PA
3544 return; /* already closed */
3545
048094ac 3546 /* Make sure we leave stdin registered in the event loop. */
e3594fd1 3547 remote_terminal_ours (self);
ce5ce7ed 3548
5d93a237
TT
3549 serial_close (rs->remote_desc);
3550 rs->remote_desc = NULL;
ce5ce7ed
PA
3551
3552 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3553 of all the inferiors and their threads we were controlling.
3554 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3555 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3556 inferior_ptid = null_ptid;
f67fd822 3557 discard_all_inferiors ();
ce5ce7ed 3558
f48ff2a7
YQ
3559 /* We are closing the remote target, so we should discard
3560 everything of this target. */
bcc75809 3561 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3562
3563 if (remote_async_inferior_event_token)
3564 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3565
5965e028 3566 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3567
3568 trace_reset_local_state ();
c906108c
SS
3569}
3570
23860348 3571/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3572
3573static void
fba45db2 3574get_offsets (void)
c906108c 3575{
d01949b6 3576 struct remote_state *rs = get_remote_state ();
2e9f7625 3577 char *buf;
085dd6e6 3578 char *ptr;
31d99776
DJ
3579 int lose, num_segments = 0, do_sections, do_segments;
3580 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3581 struct section_offsets *offs;
31d99776
DJ
3582 struct symfile_segment_data *data;
3583
3584 if (symfile_objfile == NULL)
3585 return;
c906108c
SS
3586
3587 putpkt ("qOffsets");
6d820c5c 3588 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3589 buf = rs->buf;
c906108c
SS
3590
3591 if (buf[0] == '\000')
3592 return; /* Return silently. Stub doesn't support
23860348 3593 this command. */
c906108c
SS
3594 if (buf[0] == 'E')
3595 {
8a3fe4f8 3596 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3597 return;
3598 }
3599
3600 /* Pick up each field in turn. This used to be done with scanf, but
3601 scanf will make trouble if CORE_ADDR size doesn't match
3602 conversion directives correctly. The following code will work
3603 with any size of CORE_ADDR. */
3604 text_addr = data_addr = bss_addr = 0;
3605 ptr = buf;
3606 lose = 0;
3607
61012eef 3608 if (startswith (ptr, "Text="))
c906108c
SS
3609 {
3610 ptr += 5;
3611 /* Don't use strtol, could lose on big values. */
3612 while (*ptr && *ptr != ';')
3613 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3614
61012eef 3615 if (startswith (ptr, ";Data="))
31d99776
DJ
3616 {
3617 ptr += 6;
3618 while (*ptr && *ptr != ';')
3619 data_addr = (data_addr << 4) + fromhex (*ptr++);
3620 }
3621 else
3622 lose = 1;
3623
61012eef 3624 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3625 {
3626 ptr += 5;
3627 while (*ptr && *ptr != ';')
3628 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3629
31d99776
DJ
3630 if (bss_addr != data_addr)
3631 warning (_("Target reported unsupported offsets: %s"), buf);
3632 }
3633 else
3634 lose = 1;
3635 }
61012eef 3636 else if (startswith (ptr, "TextSeg="))
c906108c 3637 {
31d99776
DJ
3638 ptr += 8;
3639 /* Don't use strtol, could lose on big values. */
c906108c 3640 while (*ptr && *ptr != ';')
31d99776
DJ
3641 text_addr = (text_addr << 4) + fromhex (*ptr++);
3642 num_segments = 1;
3643
61012eef 3644 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3645 {
3646 ptr += 9;
3647 while (*ptr && *ptr != ';')
3648 data_addr = (data_addr << 4) + fromhex (*ptr++);
3649 num_segments++;
3650 }
c906108c
SS
3651 }
3652 else
3653 lose = 1;
3654
3655 if (lose)
8a3fe4f8 3656 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3657 else if (*ptr != '\0')
3658 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3659
802188a7 3660 offs = ((struct section_offsets *)
a39a16c4 3661 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3662 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3663 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3664
31d99776
DJ
3665 data = get_symfile_segment_data (symfile_objfile->obfd);
3666 do_segments = (data != NULL);
3667 do_sections = num_segments == 0;
c906108c 3668
28c32713 3669 if (num_segments > 0)
31d99776 3670 {
31d99776
DJ
3671 segments[0] = text_addr;
3672 segments[1] = data_addr;
3673 }
28c32713
JB
3674 /* If we have two segments, we can still try to relocate everything
3675 by assuming that the .text and .data offsets apply to the whole
3676 text and data segments. Convert the offsets given in the packet
3677 to base addresses for symfile_map_offsets_to_segments. */
3678 else if (data && data->num_segments == 2)
3679 {
3680 segments[0] = data->segment_bases[0] + text_addr;
3681 segments[1] = data->segment_bases[1] + data_addr;
3682 num_segments = 2;
3683 }
8d385431
DJ
3684 /* If the object file has only one segment, assume that it is text
3685 rather than data; main programs with no writable data are rare,
3686 but programs with no code are useless. Of course the code might
3687 have ended up in the data segment... to detect that we would need
3688 the permissions here. */
3689 else if (data && data->num_segments == 1)
3690 {
3691 segments[0] = data->segment_bases[0] + text_addr;
3692 num_segments = 1;
3693 }
28c32713
JB
3694 /* There's no way to relocate by segment. */
3695 else
3696 do_segments = 0;
31d99776
DJ
3697
3698 if (do_segments)
3699 {
3700 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3701 offs, num_segments, segments);
3702
3703 if (ret == 0 && !do_sections)
3e43a32a
MS
3704 error (_("Can not handle qOffsets TextSeg "
3705 "response with this symbol file"));
31d99776
DJ
3706
3707 if (ret > 0)
3708 do_sections = 0;
3709 }
c906108c 3710
9ef895d6
DJ
3711 if (data)
3712 free_symfile_segment_data (data);
31d99776
DJ
3713
3714 if (do_sections)
3715 {
3716 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3717
3e43a32a
MS
3718 /* This is a temporary kludge to force data and bss to use the
3719 same offsets because that's what nlmconv does now. The real
3720 solution requires changes to the stub and remote.c that I
3721 don't have time to do right now. */
31d99776
DJ
3722
3723 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3724 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3725 }
c906108c
SS
3726
3727 objfile_relocate (symfile_objfile, offs);
3728}
3729
9a7071a8
JB
3730/* Send interrupt_sequence to remote target. */
3731static void
eeae04df 3732send_interrupt_sequence (void)
9a7071a8 3733{
5d93a237
TT
3734 struct remote_state *rs = get_remote_state ();
3735
9a7071a8 3736 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3737 remote_serial_write ("\x03", 1);
9a7071a8 3738 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3739 serial_send_break (rs->remote_desc);
9a7071a8
JB
3740 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3741 {
5d93a237 3742 serial_send_break (rs->remote_desc);
c33e31fd 3743 remote_serial_write ("g", 1);
9a7071a8
JB
3744 }
3745 else
3746 internal_error (__FILE__, __LINE__,
3747 _("Invalid value for interrupt_sequence_mode: %s."),
3748 interrupt_sequence_mode);
3749}
3750
3405876a
PA
3751
3752/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3753 and extract the PTID. Returns NULL_PTID if not found. */
3754
3755static ptid_t
3756stop_reply_extract_thread (char *stop_reply)
3757{
3758 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3759 {
3760 char *p;
3761
3762 /* Txx r:val ; r:val (...) */
3763 p = &stop_reply[3];
3764
3765 /* Look for "register" named "thread". */
3766 while (*p != '\0')
3767 {
3768 char *p1;
3769
3770 p1 = strchr (p, ':');
3771 if (p1 == NULL)
3772 return null_ptid;
3773
3774 if (strncmp (p, "thread", p1 - p) == 0)
3775 return read_ptid (++p1, &p);
3776
3777 p1 = strchr (p, ';');
3778 if (p1 == NULL)
3779 return null_ptid;
3780 p1++;
3781
3782 p = p1;
3783 }
3784 }
3785
3786 return null_ptid;
3787}
3788
b7ea362b
PA
3789/* Determine the remote side's current thread. If we have a stop
3790 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3791 "thread" register we can extract the current thread from. If not,
3792 ask the remote which is the current thread with qC. The former
3793 method avoids a roundtrip. */
3794
3795static ptid_t
3796get_current_thread (char *wait_status)
3797{
6a49a997 3798 ptid_t ptid = null_ptid;
b7ea362b
PA
3799
3800 /* Note we don't use remote_parse_stop_reply as that makes use of
3801 the target architecture, which we haven't yet fully determined at
3802 this point. */
3803 if (wait_status != NULL)
3804 ptid = stop_reply_extract_thread (wait_status);
3805 if (ptid_equal (ptid, null_ptid))
3806 ptid = remote_current_thread (inferior_ptid);
3807
3808 return ptid;
3809}
3810
49c62f2e
PA
3811/* Query the remote target for which is the current thread/process,
3812 add it to our tables, and update INFERIOR_PTID. The caller is
3813 responsible for setting the state such that the remote end is ready
3405876a
PA
3814 to return the current thread.
3815
3816 This function is called after handling the '?' or 'vRun' packets,
3817 whose response is a stop reply from which we can also try
3818 extracting the thread. If the target doesn't support the explicit
3819 qC query, we infer the current thread from that stop reply, passed
3820 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3821
3822static void
3405876a 3823add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3824{
3825 struct remote_state *rs = get_remote_state ();
3826 int fake_pid_p = 0;
6a49a997 3827 ptid_t ptid;
49c62f2e
PA
3828
3829 inferior_ptid = null_ptid;
3830
b7ea362b
PA
3831 /* Now, if we have thread information, update inferior_ptid. */
3832 ptid = get_current_thread (wait_status);
3405876a 3833
49c62f2e
PA
3834 if (!ptid_equal (ptid, null_ptid))
3835 {
3836 if (!remote_multi_process_p (rs))
3837 fake_pid_p = 1;
3838
3839 inferior_ptid = ptid;
3840 }
3841 else
3842 {
3843 /* Without this, some commands which require an active target
3844 (such as kill) won't work. This variable serves (at least)
3845 double duty as both the pid of the target process (if it has
3846 such), and as a flag indicating that a target is active. */
3847 inferior_ptid = magic_null_ptid;
3848 fake_pid_p = 1;
3849 }
3850
1b6e6f5c 3851 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3852
3853 /* Add the main thread. */
3854 add_thread_silent (inferior_ptid);
3855}
3856
6efcd9a8
PA
3857/* Print info about a thread that was found already stopped on
3858 connection. */
3859
3860static void
3861print_one_stopped_thread (struct thread_info *thread)
3862{
3863 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3864
3865 switch_to_thread (thread->ptid);
3866 stop_pc = get_frame_pc (get_current_frame ());
3867 set_current_sal_from_frame (get_current_frame ());
3868
3869 thread->suspend.waitstatus_pending_p = 0;
3870
3871 if (ws->kind == TARGET_WAITKIND_STOPPED)
3872 {
3873 enum gdb_signal sig = ws->value.sig;
3874
3875 if (signal_print_state (sig))
3876 observer_notify_signal_received (sig);
3877 }
3878 observer_notify_normal_stop (NULL, 1);
3879}
3880
221e1a37
PA
3881/* Process all initial stop replies the remote side sent in response
3882 to the ? packet. These indicate threads that were already stopped
3883 on initial connection. We mark these threads as stopped and print
3884 their current frame before giving the user the prompt. */
3885
3886static void
6efcd9a8 3887process_initial_stop_replies (int from_tty)
221e1a37
PA
3888{
3889 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3890 struct inferior *inf;
3891 struct thread_info *thread;
3892 struct thread_info *selected = NULL;
3893 struct thread_info *lowest_stopped = NULL;
3894 struct thread_info *first = NULL;
221e1a37
PA
3895
3896 /* Consume the initial pending events. */
3897 while (pending_stop_replies-- > 0)
3898 {
3899 ptid_t waiton_ptid = minus_one_ptid;
3900 ptid_t event_ptid;
3901 struct target_waitstatus ws;
3902 int ignore_event = 0;
6efcd9a8 3903 struct thread_info *thread;
221e1a37
PA
3904
3905 memset (&ws, 0, sizeof (ws));
3906 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3907 if (remote_debug)
3908 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3909
3910 switch (ws.kind)
3911 {
3912 case TARGET_WAITKIND_IGNORE:
3913 case TARGET_WAITKIND_NO_RESUMED:
3914 case TARGET_WAITKIND_SIGNALLED:
3915 case TARGET_WAITKIND_EXITED:
3916 /* We shouldn't see these, but if we do, just ignore. */
3917 if (remote_debug)
3918 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3919 ignore_event = 1;
3920 break;
3921
3922 case TARGET_WAITKIND_EXECD:
3923 xfree (ws.value.execd_pathname);
3924 break;
3925 default:
3926 break;
3927 }
3928
3929 if (ignore_event)
3930 continue;
3931
6efcd9a8 3932 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3933
3934 if (ws.kind == TARGET_WAITKIND_STOPPED)
3935 {
3936 enum gdb_signal sig = ws.value.sig;
3937
3938 /* Stubs traditionally report SIGTRAP as initial signal,
3939 instead of signal 0. Suppress it. */
3940 if (sig == GDB_SIGNAL_TRAP)
3941 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3942 thread->suspend.stop_signal = sig;
3943 ws.value.sig = sig;
3944 }
221e1a37 3945
6efcd9a8
PA
3946 thread->suspend.waitstatus = ws;
3947
3948 if (ws.kind != TARGET_WAITKIND_STOPPED
3949 || ws.value.sig != GDB_SIGNAL_0)
3950 thread->suspend.waitstatus_pending_p = 1;
3951
3952 set_executing (event_ptid, 0);
3953 set_running (event_ptid, 0);
85ad3aaf 3954 thread->priv->vcont_resumed = 0;
6efcd9a8
PA
3955 }
3956
3957 /* "Notice" the new inferiors before anything related to
3958 registers/memory. */
3959 ALL_INFERIORS (inf)
3960 {
3961 if (inf->pid == 0)
3962 continue;
3963
3964 inf->needs_setup = 1;
3965
3966 if (non_stop)
3967 {
3968 thread = any_live_thread_of_process (inf->pid);
3969 notice_new_inferior (thread->ptid,
3970 thread->state == THREAD_RUNNING,
3971 from_tty);
3972 }
3973 }
3974
3975 /* If all-stop on top of non-stop, pause all threads. Note this
3976 records the threads' stop pc, so must be done after "noticing"
3977 the inferiors. */
3978 if (!non_stop)
3979 {
3980 stop_all_threads ();
3981
3982 /* If all threads of an inferior were already stopped, we
3983 haven't setup the inferior yet. */
3984 ALL_INFERIORS (inf)
3985 {
3986 if (inf->pid == 0)
3987 continue;
221e1a37 3988
6efcd9a8
PA
3989 if (inf->needs_setup)
3990 {
3991 thread = any_live_thread_of_process (inf->pid);
3992 switch_to_thread_no_regs (thread);
3993 setup_inferior (0);
3994 }
3995 }
221e1a37 3996 }
6efcd9a8
PA
3997
3998 /* Now go over all threads that are stopped, and print their current
3999 frame. If all-stop, then if there's a signalled thread, pick
4000 that as current. */
4001 ALL_NON_EXITED_THREADS (thread)
4002 {
6efcd9a8
PA
4003 if (first == NULL)
4004 first = thread;
4005
4006 if (!non_stop)
4007 set_running (thread->ptid, 0);
4008 else if (thread->state != THREAD_STOPPED)
4009 continue;
4010
6efcd9a8
PA
4011 if (selected == NULL
4012 && thread->suspend.waitstatus_pending_p)
4013 selected = thread;
4014
5d5658a1
PA
4015 if (lowest_stopped == NULL
4016 || thread->inf->num < lowest_stopped->inf->num
4017 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
4018 lowest_stopped = thread;
4019
4020 if (non_stop)
4021 print_one_stopped_thread (thread);
4022 }
4023
4024 /* In all-stop, we only print the status of one thread, and leave
4025 others with their status pending. */
4026 if (!non_stop)
4027 {
4028 thread = selected;
4029 if (thread == NULL)
4030 thread = lowest_stopped;
4031 if (thread == NULL)
4032 thread = first;
4033
4034 print_one_stopped_thread (thread);
4035 }
4036
4037 /* For "info program". */
4038 thread = inferior_thread ();
4039 if (thread->state == THREAD_STOPPED)
4040 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4041}
4042
048094ac
PA
4043/* Start the remote connection and sync state. */
4044
9cbc821d 4045static void
04bd08de 4046remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 4047{
c8d104ad
PA
4048 struct remote_state *rs = get_remote_state ();
4049 struct packet_config *noack_config;
2d717e4f 4050 char *wait_status = NULL;
8621d6a9 4051
048094ac
PA
4052 /* Signal other parts that we're going through the initial setup,
4053 and so things may not be stable yet. E.g., we don't try to
4054 install tracepoints until we've relocated symbols. Also, a
4055 Ctrl-C before we're connected and synced up can't interrupt the
4056 target. Instead, it offers to drop the (potentially wedged)
4057 connection. */
4058 rs->starting_up = 1;
4059
522002f9 4060 QUIT;
c906108c 4061
9a7071a8
JB
4062 if (interrupt_on_connect)
4063 send_interrupt_sequence ();
4064
57e12211 4065 /* Ack any packet which the remote side has already sent. */
048094ac 4066 remote_serial_write ("+", 1);
1e51243a 4067
c8d104ad
PA
4068 /* The first packet we send to the target is the optional "supported
4069 packets" request. If the target can answer this, it will tell us
4070 which later probes to skip. */
4071 remote_query_supported ();
4072
d914c394 4073 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4074 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 4075 remote_set_permissions (target);
d914c394 4076
57809e5e
JK
4077 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4078 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4079 as a reply to known packet. For packet "vFile:setfs:" it is an
4080 invalid reply and GDB would return error in
4081 remote_hostio_set_filesystem, making remote files access impossible.
4082 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4083 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4084 {
4085 const char v_mustreplyempty[] = "vMustReplyEmpty";
4086
4087 putpkt (v_mustreplyempty);
4088 getpkt (&rs->buf, &rs->buf_size, 0);
4089 if (strcmp (rs->buf, "OK") == 0)
4090 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4091 else if (strcmp (rs->buf, "") != 0)
4092 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4093 rs->buf);
4094 }
4095
c8d104ad
PA
4096 /* Next, we possibly activate noack mode.
4097
4098 If the QStartNoAckMode packet configuration is set to AUTO,
4099 enable noack mode if the stub reported a wish for it with
4100 qSupported.
4101
4102 If set to TRUE, then enable noack mode even if the stub didn't
4103 report it in qSupported. If the stub doesn't reply OK, the
4104 session ends with an error.
4105
4106 If FALSE, then don't activate noack mode, regardless of what the
4107 stub claimed should be the default with qSupported. */
4108
4109 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4110 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4111 {
4112 putpkt ("QStartNoAckMode");
4113 getpkt (&rs->buf, &rs->buf_size, 0);
4114 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4115 rs->noack_mode = 1;
4116 }
4117
04bd08de 4118 if (extended_p)
5fe04517
PA
4119 {
4120 /* Tell the remote that we are using the extended protocol. */
4121 putpkt ("!");
4122 getpkt (&rs->buf, &rs->buf_size, 0);
4123 }
4124
9b224c5e
PA
4125 /* Let the target know which signals it is allowed to pass down to
4126 the program. */
4127 update_signals_program_target ();
4128
d962ef82
DJ
4129 /* Next, if the target can specify a description, read it. We do
4130 this before anything involving memory or registers. */
4131 target_find_description ();
4132
6c95b8df
PA
4133 /* Next, now that we know something about the target, update the
4134 address spaces in the program spaces. */
4135 update_address_spaces ();
4136
50c71eaf
PA
4137 /* On OSs where the list of libraries is global to all
4138 processes, we fetch them early. */
f5656ead 4139 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 4140 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 4141
6efcd9a8 4142 if (target_is_non_stop_p ())
74531fed 4143 {
4082afcc 4144 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4145 error (_("Non-stop mode requested, but remote "
4146 "does not support non-stop"));
74531fed
PA
4147
4148 putpkt ("QNonStop:1");
4149 getpkt (&rs->buf, &rs->buf_size, 0);
4150
4151 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4152 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4153
4154 /* Find about threads and processes the stub is already
4155 controlling. We default to adding them in the running state.
4156 The '?' query below will then tell us about which threads are
4157 stopped. */
e8032dde 4158 remote_update_thread_list (target);
74531fed 4159 }
4082afcc 4160 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4161 {
4162 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4163 Request it explicitly. */
74531fed
PA
4164 putpkt ("QNonStop:0");
4165 getpkt (&rs->buf, &rs->buf_size, 0);
4166
4167 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4168 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4169 }
4170
a0743c90
YQ
4171 /* Upload TSVs regardless of whether the target is running or not. The
4172 remote stub, such as GDBserver, may have some predefined or builtin
4173 TSVs, even if the target is not running. */
8bd200f1 4174 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4175 {
4176 struct uploaded_tsv *uploaded_tsvs = NULL;
4177
181e3713 4178 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4179 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4180 }
4181
2d717e4f
DJ
4182 /* Check whether the target is running now. */
4183 putpkt ("?");
4184 getpkt (&rs->buf, &rs->buf_size, 0);
4185
6efcd9a8 4186 if (!target_is_non_stop_p ())
2d717e4f 4187 {
74531fed 4188 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4189 {
04bd08de 4190 if (!extended_p)
74531fed 4191 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4192
4193 /* We're connected, but not running. Drop out before we
4194 call start_remote. */
e278ad5b 4195 rs->starting_up = 0;
c35b1492 4196 return;
2d717e4f
DJ
4197 }
4198 else
74531fed 4199 {
74531fed 4200 /* Save the reply for later. */
224c3ddb 4201 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4202 strcpy (wait_status, rs->buf);
4203 }
4204
b7ea362b 4205 /* Fetch thread list. */
e8032dde 4206 target_update_thread_list ();
b7ea362b 4207
74531fed
PA
4208 /* Let the stub know that we want it to return the thread. */
4209 set_continue_thread (minus_one_ptid);
4210
b7ea362b
PA
4211 if (thread_count () == 0)
4212 {
4213 /* Target has no concept of threads at all. GDB treats
4214 non-threaded target as single-threaded; add a main
4215 thread. */
4216 add_current_inferior_and_thread (wait_status);
4217 }
4218 else
4219 {
4220 /* We have thread information; select the thread the target
4221 says should be current. If we're reconnecting to a
4222 multi-threaded program, this will ideally be the thread
4223 that last reported an event before GDB disconnected. */
4224 inferior_ptid = get_current_thread (wait_status);
4225 if (ptid_equal (inferior_ptid, null_ptid))
4226 {
4227 /* Odd... The target was able to list threads, but not
4228 tell us which thread was current (no "thread"
4229 register in T stop reply?). Just pick the first
4230 thread in the thread list then. */
c9f35b34
KB
4231
4232 if (remote_debug)
4233 fprintf_unfiltered (gdb_stdlog,
4234 "warning: couldn't determine remote "
4235 "current thread; picking first in list.\n");
4236
b7ea362b
PA
4237 inferior_ptid = thread_list->ptid;
4238 }
4239 }
74531fed 4240
6e586cc5
YQ
4241 /* init_wait_for_inferior should be called before get_offsets in order
4242 to manage `inserted' flag in bp loc in a correct state.
4243 breakpoint_init_inferior, called from init_wait_for_inferior, set
4244 `inserted' flag to 0, while before breakpoint_re_set, called from
4245 start_remote, set `inserted' flag to 1. In the initialization of
4246 inferior, breakpoint_init_inferior should be called first, and then
4247 breakpoint_re_set can be called. If this order is broken, state of
4248 `inserted' flag is wrong, and cause some problems on breakpoint
4249 manipulation. */
4250 init_wait_for_inferior ();
4251
74531fed
PA
4252 get_offsets (); /* Get text, data & bss offsets. */
4253
d962ef82
DJ
4254 /* If we could not find a description using qXfer, and we know
4255 how to do it some other way, try again. This is not
4256 supported for non-stop; it could be, but it is tricky if
4257 there are no stopped threads when we connect. */
04bd08de 4258 if (remote_read_description_p (target)
f5656ead 4259 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4260 {
4261 target_clear_description ();
4262 target_find_description ();
4263 }
4264
74531fed
PA
4265 /* Use the previously fetched status. */
4266 gdb_assert (wait_status != NULL);
4267 strcpy (rs->buf, wait_status);
4268 rs->cached_wait_status = 1;
4269
04bd08de 4270 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4271 }
4272 else
4273 {
68c97600
PA
4274 /* Clear WFI global state. Do this before finding about new
4275 threads and inferiors, and setting the current inferior.
4276 Otherwise we would clear the proceed status of the current
4277 inferior when we want its stop_soon state to be preserved
4278 (see notice_new_inferior). */
4279 init_wait_for_inferior ();
4280
74531fed
PA
4281 /* In non-stop, we will either get an "OK", meaning that there
4282 are no stopped threads at this time; or, a regular stop
4283 reply. In the latter case, there may be more than one thread
4284 stopped --- we pull them all out using the vStopped
4285 mechanism. */
4286 if (strcmp (rs->buf, "OK") != 0)
4287 {
722247f1 4288 struct notif_client *notif = &notif_client_stop;
2d717e4f 4289
722247f1
YQ
4290 /* remote_notif_get_pending_replies acks this one, and gets
4291 the rest out. */
f48ff2a7 4292 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4293 = remote_notif_parse (notif, rs->buf);
4294 remote_notif_get_pending_events (notif);
74531fed 4295 }
2d717e4f 4296
74531fed
PA
4297 if (thread_count () == 0)
4298 {
04bd08de 4299 if (!extended_p)
74531fed 4300 error (_("The target is not running (try extended-remote?)"));
82f73884 4301
c35b1492
PA
4302 /* We're connected, but not running. Drop out before we
4303 call start_remote. */
e278ad5b 4304 rs->starting_up = 0;
c35b1492
PA
4305 return;
4306 }
74531fed 4307
74531fed
PA
4308 /* In non-stop mode, any cached wait status will be stored in
4309 the stop reply queue. */
4310 gdb_assert (wait_status == NULL);
f0223081 4311
2455069d 4312 /* Report all signals during attach/startup. */
94bedb42 4313 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4314
4315 /* If there are already stopped threads, mark them stopped and
4316 report their stops before giving the prompt to the user. */
6efcd9a8 4317 process_initial_stop_replies (from_tty);
221e1a37
PA
4318
4319 if (target_can_async_p ())
4320 target_async (1);
74531fed 4321 }
c8d104ad 4322
c8d104ad
PA
4323 /* If we connected to a live target, do some additional setup. */
4324 if (target_has_execution)
4325 {
f4ccffad 4326 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4327 remote_check_symbols ();
c8d104ad 4328 }
50c71eaf 4329
d5551862
SS
4330 /* Possibly the target has been engaged in a trace run started
4331 previously; find out where things are at. */
8bd200f1 4332 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4333 {
00bf0b85 4334 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4335
00bf0b85
SS
4336 if (current_trace_status ()->running)
4337 printf_filtered (_("Trace is already running on the target.\n"));
4338
ab6617cc 4339 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4340
4341 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4342 }
4343
c0272db5
TW
4344 /* Possibly the target has been engaged in a btrace record started
4345 previously; find out where things are at. */
4346 remote_btrace_maybe_reopen ();
4347
1e51243a
PA
4348 /* The thread and inferior lists are now synchronized with the
4349 target, our symbols have been relocated, and we're merged the
4350 target's tracepoints with ours. We're done with basic start
4351 up. */
4352 rs->starting_up = 0;
4353
a25a5a45
PA
4354 /* Maybe breakpoints are global and need to be inserted now. */
4355 if (breakpoints_should_be_inserted_now ())
50c71eaf 4356 insert_breakpoints ();
c906108c
SS
4357}
4358
4359/* Open a connection to a remote debugger.
4360 NAME is the filename used for communication. */
4361
4362static void
014f9477 4363remote_open (const char *name, int from_tty)
c906108c 4364{
75c99385 4365 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4366}
4367
c906108c
SS
4368/* Open a connection to a remote debugger using the extended
4369 remote gdb protocol. NAME is the filename used for communication. */
4370
4371static void
014f9477 4372extended_remote_open (const char *name, int from_tty)
c906108c 4373{
75c99385 4374 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4375}
4376
ca4f7f8b
PA
4377/* Reset all packets back to "unknown support". Called when opening a
4378 new connection to a remote target. */
c906108c 4379
d471ea57 4380static void
ca4f7f8b 4381reset_all_packet_configs_support (void)
d471ea57
AC
4382{
4383 int i;
a744cf53 4384
444abaca 4385 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4386 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4387}
4388
ca4f7f8b
PA
4389/* Initialize all packet configs. */
4390
4391static void
4392init_all_packet_configs (void)
4393{
4394 int i;
4395
4396 for (i = 0; i < PACKET_MAX; i++)
4397 {
4398 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4399 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4400 }
4401}
4402
23860348 4403/* Symbol look-up. */
dc8acb97
MS
4404
4405static void
36d25514 4406remote_check_symbols (void)
dc8acb97 4407{
d01949b6 4408 struct remote_state *rs = get_remote_state ();
dc8acb97 4409 char *msg, *reply, *tmp;
dc8acb97 4410 int end;
28170b88 4411 long reply_size;
a5c0808e 4412 struct cleanup *old_chain;
dc8acb97 4413
63154eca
PA
4414 /* The remote side has no concept of inferiors that aren't running
4415 yet, it only knows about running processes. If we're connected
4416 but our current inferior is not running, we should not invite the
4417 remote target to request symbol lookups related to its
4418 (unrelated) current process. */
4419 if (!target_has_execution)
4420 return;
4421
4082afcc 4422 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4423 return;
4424
63154eca
PA
4425 /* Make sure the remote is pointing at the right process. Note
4426 there's no way to select "no process". */
3c9c4b83
PA
4427 set_general_process ();
4428
6d820c5c
DJ
4429 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4430 because we need both at the same time. */
224c3ddb 4431 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4432 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4433 reply = (char *) xmalloc (get_remote_packet_size ());
4434 make_cleanup (free_current_contents, &reply);
4435 reply_size = get_remote_packet_size ();
6d820c5c 4436
23860348 4437 /* Invite target to request symbol lookups. */
dc8acb97
MS
4438
4439 putpkt ("qSymbol::");
28170b88
MK
4440 getpkt (&reply, &reply_size, 0);
4441 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4442
61012eef 4443 while (startswith (reply, "qSymbol:"))
dc8acb97 4444 {
77e371c0
TT
4445 struct bound_minimal_symbol sym;
4446
dc8acb97 4447 tmp = &reply[8];
cfd77fa1 4448 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4449 msg[end] = '\0';
4450 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4451 if (sym.minsym == NULL)
ea9c271d 4452 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4453 else
2bbe3cc1 4454 {
f5656ead 4455 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4456 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4457
4458 /* If this is a function address, return the start of code
4459 instead of any data function descriptor. */
f5656ead 4460 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4461 sym_addr,
4462 &current_target);
4463
4464 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4465 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4466 }
4467
dc8acb97 4468 putpkt (msg);
28170b88 4469 getpkt (&reply, &reply_size, 0);
dc8acb97 4470 }
a5c0808e
PA
4471
4472 do_cleanups (old_chain);
dc8acb97
MS
4473}
4474
9db8d71f 4475static struct serial *
baa336ce 4476remote_serial_open (const char *name)
9db8d71f
DJ
4477{
4478 static int udp_warning = 0;
4479
4480 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4481 of in ser-tcp.c, because it is the remote protocol assuming that the
4482 serial connection is reliable and not the serial connection promising
4483 to be. */
61012eef 4484 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4485 {
3e43a32a
MS
4486 warning (_("The remote protocol may be unreliable over UDP.\n"
4487 "Some events may be lost, rendering further debugging "
4488 "impossible."));
9db8d71f
DJ
4489 udp_warning = 1;
4490 }
4491
4492 return serial_open (name);
4493}
4494
d914c394
SS
4495/* Inform the target of our permission settings. The permission flags
4496 work without this, but if the target knows the settings, it can do
4497 a couple things. First, it can add its own check, to catch cases
4498 that somehow manage to get by the permissions checks in target
4499 methods. Second, if the target is wired to disallow particular
4500 settings (for instance, a system in the field that is not set up to
4501 be able to stop at a breakpoint), it can object to any unavailable
4502 permissions. */
4503
4504void
c378d69d 4505remote_set_permissions (struct target_ops *self)
d914c394
SS
4506{
4507 struct remote_state *rs = get_remote_state ();
4508
bba74b36
YQ
4509 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4510 "WriteReg:%x;WriteMem:%x;"
4511 "InsertBreak:%x;InsertTrace:%x;"
4512 "InsertFastTrace:%x;Stop:%x",
4513 may_write_registers, may_write_memory,
4514 may_insert_breakpoints, may_insert_tracepoints,
4515 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4516 putpkt (rs->buf);
4517 getpkt (&rs->buf, &rs->buf_size, 0);
4518
4519 /* If the target didn't like the packet, warn the user. Do not try
4520 to undo the user's settings, that would just be maddening. */
4521 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4522 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4523}
4524
be2a5f71
DJ
4525/* This type describes each known response to the qSupported
4526 packet. */
4527struct protocol_feature
4528{
4529 /* The name of this protocol feature. */
4530 const char *name;
4531
4532 /* The default for this protocol feature. */
4533 enum packet_support default_support;
4534
4535 /* The function to call when this feature is reported, or after
4536 qSupported processing if the feature is not supported.
4537 The first argument points to this structure. The second
4538 argument indicates whether the packet requested support be
4539 enabled, disabled, or probed (or the default, if this function
4540 is being called at the end of processing and this feature was
4541 not reported). The third argument may be NULL; if not NULL, it
4542 is a NUL-terminated string taken from the packet following
4543 this feature's name and an equals sign. */
4544 void (*func) (const struct protocol_feature *, enum packet_support,
4545 const char *);
4546
4547 /* The corresponding packet for this feature. Only used if
4548 FUNC is remote_supported_packet. */
4549 int packet;
4550};
4551
be2a5f71
DJ
4552static void
4553remote_supported_packet (const struct protocol_feature *feature,
4554 enum packet_support support,
4555 const char *argument)
4556{
4557 if (argument)
4558 {
4559 warning (_("Remote qSupported response supplied an unexpected value for"
4560 " \"%s\"."), feature->name);
4561 return;
4562 }
4563
4082afcc 4564 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4565}
be2a5f71
DJ
4566
4567static void
4568remote_packet_size (const struct protocol_feature *feature,
4569 enum packet_support support, const char *value)
4570{
4571 struct remote_state *rs = get_remote_state ();
4572
4573 int packet_size;
4574 char *value_end;
4575
4576 if (support != PACKET_ENABLE)
4577 return;
4578
4579 if (value == NULL || *value == '\0')
4580 {
4581 warning (_("Remote target reported \"%s\" without a size."),
4582 feature->name);
4583 return;
4584 }
4585
4586 errno = 0;
4587 packet_size = strtol (value, &value_end, 16);
4588 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4589 {
4590 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4591 feature->name, value);
4592 return;
4593 }
4594
be2a5f71
DJ
4595 /* Record the new maximum packet size. */
4596 rs->explicit_packet_size = packet_size;
4597}
4598
dc473cfb 4599static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4600 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4601 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4602 PACKET_qXfer_auxv },
c78fa86a
GB
4603 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4604 PACKET_qXfer_exec_file },
23181151
DJ
4605 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4606 PACKET_qXfer_features },
cfa9d6d9
DJ
4607 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4608 PACKET_qXfer_libraries },
2268b414
JK
4609 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4610 PACKET_qXfer_libraries_svr4 },
ced63ec0 4611 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4612 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4613 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4614 PACKET_qXfer_memory_map },
4de6483e
UW
4615 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4616 PACKET_qXfer_spu_read },
4617 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4618 PACKET_qXfer_spu_write },
07e059b5
VP
4619 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4620 PACKET_qXfer_osdata },
dc146f7c
VP
4621 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4622 PACKET_qXfer_threads },
b3b9301e
PA
4623 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4624 PACKET_qXfer_traceframe_info },
89be2091
DJ
4625 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4626 PACKET_QPassSignals },
82075af2
JS
4627 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4628 PACKET_QCatchSyscalls },
9b224c5e
PA
4629 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4630 PACKET_QProgramSignals },
a6f3e723
SL
4631 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4632 PACKET_QStartNoAckMode },
4082afcc
PA
4633 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4634 PACKET_multiprocess_feature },
4635 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4636 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4637 PACKET_qXfer_siginfo_read },
4638 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4639 PACKET_qXfer_siginfo_write },
4082afcc 4640 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4641 PACKET_ConditionalTracepoints },
4082afcc 4642 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4643 PACKET_ConditionalBreakpoints },
4082afcc 4644 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4645 PACKET_BreakpointCommands },
4082afcc 4646 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4647 PACKET_FastTracepoints },
4082afcc 4648 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4649 PACKET_StaticTracepoints },
4082afcc 4650 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4651 PACKET_InstallInTrace},
4082afcc
PA
4652 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4653 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4654 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4655 PACKET_bc },
4656 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4657 PACKET_bs },
409873ef
SS
4658 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4659 PACKET_TracepointSource },
d914c394
SS
4660 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4661 PACKET_QAllow },
4082afcc
PA
4662 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4663 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4664 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4665 PACKET_qXfer_fdpic },
169081d0
TG
4666 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4667 PACKET_qXfer_uib },
03583c20
UW
4668 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4669 PACKET_QDisableRandomization },
d1feda86 4670 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4671 { "QTBuffer:size", PACKET_DISABLE,
4672 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4673 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4674 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4675 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4676 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4677 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4678 PACKET_qXfer_btrace },
4679 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4680 PACKET_qXfer_btrace_conf },
4681 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4682 PACKET_Qbtrace_conf_bts_size },
4683 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4684 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4685 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4686 PACKET_fork_event_feature },
4687 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4688 PACKET_vfork_event_feature },
94585166
DB
4689 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4690 PACKET_exec_event_feature },
b20a6524 4691 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4692 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4693 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4694 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4695 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4696};
4697
c8d5aac9
L
4698static char *remote_support_xml;
4699
4700/* Register string appended to "xmlRegisters=" in qSupported query. */
4701
4702void
6e39997a 4703register_remote_support_xml (const char *xml)
c8d5aac9
L
4704{
4705#if defined(HAVE_LIBEXPAT)
4706 if (remote_support_xml == NULL)
c4f7c687 4707 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4708 else
4709 {
4710 char *copy = xstrdup (remote_support_xml + 13);
4711 char *p = strtok (copy, ",");
4712
4713 do
4714 {
4715 if (strcmp (p, xml) == 0)
4716 {
4717 /* already there */
4718 xfree (copy);
4719 return;
4720 }
4721 }
4722 while ((p = strtok (NULL, ",")) != NULL);
4723 xfree (copy);
4724
94b0dee1
PA
4725 remote_support_xml = reconcat (remote_support_xml,
4726 remote_support_xml, ",", xml,
4727 (char *) NULL);
c8d5aac9
L
4728 }
4729#endif
4730}
4731
4732static char *
4733remote_query_supported_append (char *msg, const char *append)
4734{
4735 if (msg)
94b0dee1 4736 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4737 else
4738 return xstrdup (append);
4739}
4740
be2a5f71
DJ
4741static void
4742remote_query_supported (void)
4743{
4744 struct remote_state *rs = get_remote_state ();
4745 char *next;
4746 int i;
4747 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4748
4749 /* The packet support flags are handled differently for this packet
4750 than for most others. We treat an error, a disabled packet, and
4751 an empty response identically: any features which must be reported
4752 to be used will be automatically disabled. An empty buffer
4753 accomplishes this, since that is also the representation for a list
4754 containing no features. */
4755
4756 rs->buf[0] = 0;
4082afcc 4757 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4758 {
c8d5aac9 4759 char *q = NULL;
94b0dee1 4760 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4761
73b8c1fd
PA
4762 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4763 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4764
f7e6eed5
PA
4765 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4766 q = remote_query_supported_append (q, "swbreak+");
4767 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4768 q = remote_query_supported_append (q, "hwbreak+");
4769
dde08ee1
PA
4770 q = remote_query_supported_append (q, "qRelocInsn+");
4771
8020350c
DB
4772 if (packet_set_cmd_state (PACKET_fork_event_feature)
4773 != AUTO_BOOLEAN_FALSE)
4774 q = remote_query_supported_append (q, "fork-events+");
4775 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4776 != AUTO_BOOLEAN_FALSE)
4777 q = remote_query_supported_append (q, "vfork-events+");
4778 if (packet_set_cmd_state (PACKET_exec_event_feature)
4779 != AUTO_BOOLEAN_FALSE)
4780 q = remote_query_supported_append (q, "exec-events+");
89245bc0 4781
750ce8d1
YQ
4782 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4783 q = remote_query_supported_append (q, "vContSupported+");
4784
65706a29
PA
4785 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4786 q = remote_query_supported_append (q, "QThreadEvents+");
4787
f2faf941
PA
4788 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4789 q = remote_query_supported_append (q, "no-resumed+");
4790
b35d5edb
PA
4791 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4792 the qSupported:xmlRegisters=i386 handling. */
4793 if (remote_support_xml != NULL)
4794 q = remote_query_supported_append (q, remote_support_xml);
4795
dde08ee1
PA
4796 q = reconcat (q, "qSupported:", q, (char *) NULL);
4797 putpkt (q);
82f73884 4798
94b0dee1
PA
4799 do_cleanups (old_chain);
4800
be2a5f71
DJ
4801 getpkt (&rs->buf, &rs->buf_size, 0);
4802
4803 /* If an error occured, warn, but do not return - just reset the
4804 buffer to empty and go on to disable features. */
4805 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4806 == PACKET_ERROR)
4807 {
4808 warning (_("Remote failure reply: %s"), rs->buf);
4809 rs->buf[0] = 0;
4810 }
4811 }
4812
4813 memset (seen, 0, sizeof (seen));
4814
4815 next = rs->buf;
4816 while (*next)
4817 {
4818 enum packet_support is_supported;
4819 char *p, *end, *name_end, *value;
4820
4821 /* First separate out this item from the rest of the packet. If
4822 there's another item after this, we overwrite the separator
4823 (terminated strings are much easier to work with). */
4824 p = next;
4825 end = strchr (p, ';');
4826 if (end == NULL)
4827 {
4828 end = p + strlen (p);
4829 next = end;
4830 }
4831 else
4832 {
89be2091
DJ
4833 *end = '\0';
4834 next = end + 1;
4835
be2a5f71
DJ
4836 if (end == p)
4837 {
4838 warning (_("empty item in \"qSupported\" response"));
4839 continue;
4840 }
be2a5f71
DJ
4841 }
4842
4843 name_end = strchr (p, '=');
4844 if (name_end)
4845 {
4846 /* This is a name=value entry. */
4847 is_supported = PACKET_ENABLE;
4848 value = name_end + 1;
4849 *name_end = '\0';
4850 }
4851 else
4852 {
4853 value = NULL;
4854 switch (end[-1])
4855 {
4856 case '+':
4857 is_supported = PACKET_ENABLE;
4858 break;
4859
4860 case '-':
4861 is_supported = PACKET_DISABLE;
4862 break;
4863
4864 case '?':
4865 is_supported = PACKET_SUPPORT_UNKNOWN;
4866 break;
4867
4868 default:
3e43a32a
MS
4869 warning (_("unrecognized item \"%s\" "
4870 "in \"qSupported\" response"), p);
be2a5f71
DJ
4871 continue;
4872 }
4873 end[-1] = '\0';
4874 }
4875
4876 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4877 if (strcmp (remote_protocol_features[i].name, p) == 0)
4878 {
4879 const struct protocol_feature *feature;
4880
4881 seen[i] = 1;
4882 feature = &remote_protocol_features[i];
4883 feature->func (feature, is_supported, value);
4884 break;
4885 }
4886 }
4887
4888 /* If we increased the packet size, make sure to increase the global
4889 buffer size also. We delay this until after parsing the entire
4890 qSupported packet, because this is the same buffer we were
4891 parsing. */
4892 if (rs->buf_size < rs->explicit_packet_size)
4893 {
4894 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4895 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4896 }
4897
4898 /* Handle the defaults for unmentioned features. */
4899 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4900 if (!seen[i])
4901 {
4902 const struct protocol_feature *feature;
4903
4904 feature = &remote_protocol_features[i];
4905 feature->func (feature, feature->default_support, NULL);
4906 }
4907}
4908
048094ac
PA
4909/* Serial QUIT handler for the remote serial descriptor.
4910
4911 Defers handling a Ctrl-C until we're done with the current
4912 command/response packet sequence, unless:
4913
4914 - We're setting up the connection. Don't send a remote interrupt
4915 request, as we're not fully synced yet. Quit immediately
4916 instead.
4917
4918 - The target has been resumed in the foreground
4919 (target_terminal_is_ours is false) with a synchronous resume
4920 packet, and we're blocked waiting for the stop reply, thus a
4921 Ctrl-C should be immediately sent to the target.
4922
4923 - We get a second Ctrl-C while still within the same serial read or
4924 write. In that case the serial is seemingly wedged --- offer to
4925 quit/disconnect.
4926
4927 - We see a second Ctrl-C without target response, after having
4928 previously interrupted the target. In that case the target/stub
4929 is probably wedged --- offer to quit/disconnect.
4930*/
4931
4932static void
4933remote_serial_quit_handler (void)
4934{
4935 struct remote_state *rs = get_remote_state ();
4936
4937 if (check_quit_flag ())
4938 {
4939 /* If we're starting up, we're not fully synced yet. Quit
4940 immediately. */
4941 if (rs->starting_up)
4942 quit ();
4943 else if (rs->got_ctrlc_during_io)
4944 {
4945 if (query (_("The target is not responding to GDB commands.\n"
4946 "Stop debugging it? ")))
4947 remote_unpush_and_throw ();
4948 }
4949 /* If ^C has already been sent once, offer to disconnect. */
4950 else if (!target_terminal_is_ours () && rs->ctrlc_pending_p)
4951 interrupt_query ();
4952 /* All-stop protocol, and blocked waiting for stop reply. Send
4953 an interrupt request. */
4954 else if (!target_terminal_is_ours () && rs->waiting_for_stop_reply)
4955 target_interrupt (inferior_ptid);
4956 else
4957 rs->got_ctrlc_during_io = 1;
4958 }
4959}
4960
78a095c3
JK
4961/* Remove any of the remote.c targets from target stack. Upper targets depend
4962 on it so remove them first. */
4963
4964static void
4965remote_unpush_target (void)
4966{
915ef8b1 4967 pop_all_targets_at_and_above (process_stratum);
78a095c3 4968}
be2a5f71 4969
048094ac
PA
4970static void
4971remote_unpush_and_throw (void)
4972{
4973 remote_unpush_target ();
4974 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
4975}
4976
c906108c 4977static void
014f9477 4978remote_open_1 (const char *name, int from_tty,
3e43a32a 4979 struct target_ops *target, int extended_p)
c906108c 4980{
d01949b6 4981 struct remote_state *rs = get_remote_state ();
a6f3e723 4982
c906108c 4983 if (name == 0)
8a3fe4f8 4984 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4985 "serial device is attached to the remote system\n"
8a3fe4f8 4986 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4987
23860348 4988 /* See FIXME above. */
c6ebd6cf 4989 if (!target_async_permitted)
92d1e331 4990 wait_forever_enabled_p = 1;
6426a772 4991
2d717e4f 4992 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4993 Ask this question first, before target_preopen has a chance to kill
4994 anything. */
5d93a237 4995 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4996 {
78a095c3
JK
4997 if (from_tty
4998 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4999 error (_("Still connected."));
5000 }
5001
78a095c3 5002 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
5003 target_preopen (from_tty);
5004
89be2091 5005 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
5006 xfree (rs->last_pass_packet);
5007 rs->last_pass_packet = NULL;
89be2091 5008
9b224c5e
PA
5009 /* Make sure we send the program signals list the next time we
5010 resume. */
5e4a05c4
TT
5011 xfree (rs->last_program_signals_packet);
5012 rs->last_program_signals_packet = NULL;
9b224c5e 5013
ad9a8f3f 5014 remote_fileio_reset ();
1dd41f16
NS
5015 reopen_exec_file ();
5016 reread_symbols ();
5017
5d93a237
TT
5018 rs->remote_desc = remote_serial_open (name);
5019 if (!rs->remote_desc)
c906108c
SS
5020 perror_with_name (name);
5021
5022 if (baud_rate != -1)
5023 {
5d93a237 5024 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 5025 {
9b74d5d3
KB
5026 /* The requested speed could not be set. Error out to
5027 top level after closing remote_desc. Take care to
5028 set remote_desc to NULL to avoid closing remote_desc
5029 more than once. */
5d93a237
TT
5030 serial_close (rs->remote_desc);
5031 rs->remote_desc = NULL;
c906108c
SS
5032 perror_with_name (name);
5033 }
5034 }
5035
236af5e3 5036 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 5037 serial_raw (rs->remote_desc);
c906108c
SS
5038
5039 /* If there is something sitting in the buffer we might take it as a
5040 response to a command, which would be bad. */
5d93a237 5041 serial_flush_input (rs->remote_desc);
c906108c
SS
5042
5043 if (from_tty)
5044 {
5045 puts_filtered ("Remote debugging using ");
5046 puts_filtered (name);
5047 puts_filtered ("\n");
5048 }
23860348 5049 push_target (target); /* Switch to using remote target now. */
c906108c 5050
74531fed
PA
5051 /* Register extra event sources in the event loop. */
5052 remote_async_inferior_event_token
5053 = create_async_event_handler (remote_async_inferior_event_handler,
5054 NULL);
5965e028 5055 rs->notif_state = remote_notif_state_allocate ();
74531fed 5056
be2a5f71
DJ
5057 /* Reset the target state; these things will be queried either by
5058 remote_query_supported or as they are needed. */
ca4f7f8b 5059 reset_all_packet_configs_support ();
74531fed 5060 rs->cached_wait_status = 0;
be2a5f71 5061 rs->explicit_packet_size = 0;
a6f3e723 5062 rs->noack_mode = 0;
82f73884 5063 rs->extended = extended_p;
e24a49d8 5064 rs->waiting_for_stop_reply = 0;
3a29589a 5065 rs->ctrlc_pending_p = 0;
048094ac 5066 rs->got_ctrlc_during_io = 0;
802188a7 5067
47f8a51d
TT
5068 rs->general_thread = not_sent_ptid;
5069 rs->continue_thread = not_sent_ptid;
262e1174 5070 rs->remote_traceframe_number = -1;
c906108c 5071
3a00c802
PA
5072 rs->last_resume_exec_dir = EXEC_FORWARD;
5073
9d1f7ab2 5074 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5075 rs->use_threadinfo_query = 1;
5076 rs->use_threadextra_query = 1;
9d1f7ab2 5077
80152258
PA
5078 readahead_cache_invalidate ();
5079
048094ac
PA
5080 /* Start out by owning the terminal. */
5081 remote_async_terminal_ours_p = 1;
5082
c6ebd6cf 5083 if (target_async_permitted)
92d1e331 5084 {
92d1e331
DJ
5085 /* FIXME: cagney/1999-09-23: During the initial connection it is
5086 assumed that the target is already ready and able to respond to
0df8b418 5087 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5088 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5089 around this. Eventually a mechanism that allows
92d1e331 5090 wait_for_inferior() to expect/get timeouts will be
23860348 5091 implemented. */
92d1e331
DJ
5092 wait_forever_enabled_p = 0;
5093 }
5094
23860348 5095 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5096 no_shared_libraries (NULL, 0);
f78f6cf1 5097
74531fed
PA
5098 /* Start afresh. */
5099 init_thread_list ();
5100
36918e70 5101 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5102 target (we'd otherwise be in an inconsistent state) and then
5103 propogate the error on up the exception chain. This ensures that
5104 the caller doesn't stumble along blindly assuming that the
5105 function succeeded. The CLI doesn't have this problem but other
5106 UI's, such as MI do.
36918e70
AC
5107
5108 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5109 this function should return an error indication letting the
ce2826aa 5110 caller restore the previous state. Unfortunately the command
36918e70
AC
5111 ``target remote'' is directly wired to this function making that
5112 impossible. On a positive note, the CLI side of this problem has
5113 been fixed - the function set_cmd_context() makes it possible for
5114 all the ``target ....'' commands to share a common callback
5115 function. See cli-dump.c. */
109c3e39 5116 {
2d717e4f 5117
492d29ea 5118 TRY
04bd08de
TT
5119 {
5120 remote_start_remote (from_tty, target, extended_p);
5121 }
492d29ea 5122 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5123 {
c8d104ad
PA
5124 /* Pop the partially set up target - unless something else did
5125 already before throwing the exception. */
5d93a237 5126 if (rs->remote_desc != NULL)
78a095c3 5127 remote_unpush_target ();
c6ebd6cf 5128 if (target_async_permitted)
109c3e39
AC
5129 wait_forever_enabled_p = 1;
5130 throw_exception (ex);
5131 }
492d29ea 5132 END_CATCH
109c3e39 5133 }
c906108c 5134
f4abbc16
MM
5135 remote_btrace_reset ();
5136
c6ebd6cf 5137 if (target_async_permitted)
92d1e331 5138 wait_forever_enabled_p = 1;
43ff13b4
JM
5139}
5140
de0d863e
DB
5141/* Detach the specified process. */
5142
5143static void
5144remote_detach_pid (int pid)
5145{
5146 struct remote_state *rs = get_remote_state ();
5147
5148 if (remote_multi_process_p (rs))
5149 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5150 else
5151 strcpy (rs->buf, "D");
5152
5153 putpkt (rs->buf);
5154 getpkt (&rs->buf, &rs->buf_size, 0);
5155
5156 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5157 ;
5158 else if (rs->buf[0] == '\0')
5159 error (_("Remote doesn't know how to detach"));
5160 else
5161 error (_("Can't detach process."));
5162}
5163
5164/* This detaches a program to which we previously attached, using
5165 inferior_ptid to identify the process. After this is done, GDB
5166 can be used to debug some other program. We better not have left
5167 any breakpoints in the target program or it'll die when it hits
5168 one. */
c906108c
SS
5169
5170static void
de0d863e 5171remote_detach_1 (const char *args, int from_tty)
c906108c 5172{
82f73884 5173 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5174 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5175 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5176 int is_fork_parent;
c906108c
SS
5177
5178 if (args)
8a3fe4f8 5179 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 5180
2d717e4f
DJ
5181 if (!target_has_execution)
5182 error (_("No process to detach from."));
5183
0f48b757 5184 target_announce_detach (from_tty);
7cee1e54 5185
c906108c 5186 /* Tell the remote target to detach. */
de0d863e 5187 remote_detach_pid (pid);
82f73884 5188
8020350c
DB
5189 /* Exit only if this is the only active inferior. */
5190 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5191 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5192
de0d863e
DB
5193 /* Check to see if we are detaching a fork parent. Note that if we
5194 are detaching a fork child, tp == NULL. */
5195 is_fork_parent = (tp != NULL
5196 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5197
5198 /* If doing detach-on-fork, we don't mourn, because that will delete
5199 breakpoints that should be available for the followed inferior. */
5200 if (!is_fork_parent)
bc1e6c81 5201 target_mourn_inferior (inferior_ptid);
de0d863e
DB
5202 else
5203 {
5204 inferior_ptid = null_ptid;
5205 detach_inferior (pid);
5206 }
2d717e4f
DJ
5207}
5208
5209static void
52554a0e 5210remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5211{
de0d863e 5212 remote_detach_1 (args, from_tty);
2d717e4f
DJ
5213}
5214
5215static void
52554a0e 5216extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5217{
de0d863e
DB
5218 remote_detach_1 (args, from_tty);
5219}
5220
5221/* Target follow-fork function for remote targets. On entry, and
5222 at return, the current inferior is the fork parent.
5223
5224 Note that although this is currently only used for extended-remote,
5225 it is named remote_follow_fork in anticipation of using it for the
5226 remote target as well. */
5227
5228static int
5229remote_follow_fork (struct target_ops *ops, int follow_child,
5230 int detach_fork)
5231{
5232 struct remote_state *rs = get_remote_state ();
c269dbdb 5233 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5234
c269dbdb
DB
5235 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5236 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5237 {
5238 /* When following the parent and detaching the child, we detach
5239 the child here. For the case of following the child and
5240 detaching the parent, the detach is done in the target-
5241 independent follow fork code in infrun.c. We can't use
5242 target_detach when detaching an unfollowed child because
5243 the client side doesn't know anything about the child. */
5244 if (detach_fork && !follow_child)
5245 {
5246 /* Detach the fork child. */
5247 ptid_t child_ptid;
5248 pid_t child_pid;
5249
5250 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5251 child_pid = ptid_get_pid (child_ptid);
5252
5253 remote_detach_pid (child_pid);
5254 detach_inferior (child_pid);
5255 }
5256 }
5257 return 0;
c906108c
SS
5258}
5259
94585166
DB
5260/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5261 in the program space of the new inferior. On entry and at return the
5262 current inferior is the exec'ing inferior. INF is the new exec'd
5263 inferior, which may be the same as the exec'ing inferior unless
5264 follow-exec-mode is "new". */
5265
5266static void
5267remote_follow_exec (struct target_ops *ops,
5268 struct inferior *inf, char *execd_pathname)
5269{
5270 /* We know that this is a target file name, so if it has the "target:"
5271 prefix we strip it off before saving it in the program space. */
5272 if (is_target_filename (execd_pathname))
5273 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5274
5275 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5276}
5277
6ad8ae5c
DJ
5278/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5279
43ff13b4 5280static void
fee354ee 5281remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5282{
43ff13b4 5283 if (args)
2d717e4f 5284 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5285
8020350c
DB
5286 /* Make sure we unpush even the extended remote targets. Calling
5287 target_mourn_inferior won't unpush, and remote_mourn won't
5288 unpush if there is more than one inferior left. */
5289 unpush_target (target);
5290 generic_mourn_inferior ();
2d717e4f 5291
43ff13b4
JM
5292 if (from_tty)
5293 puts_filtered ("Ending remote debugging.\n");
5294}
5295
2d717e4f
DJ
5296/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5297 be chatty about it. */
5298
5299static void
20f796c9
GB
5300extended_remote_attach (struct target_ops *target, const char *args,
5301 int from_tty)
2d717e4f
DJ
5302{
5303 struct remote_state *rs = get_remote_state ();
be86555c 5304 int pid;
96ef3384 5305 char *wait_status = NULL;
2d717e4f 5306
74164c56 5307 pid = parse_pid_to_attach (args);
2d717e4f 5308
74164c56
JK
5309 /* Remote PID can be freely equal to getpid, do not check it here the same
5310 way as in other targets. */
2d717e4f 5311
4082afcc 5312 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5313 error (_("This target does not support attaching to a process"));
5314
7cee1e54
PA
5315 if (from_tty)
5316 {
5317 char *exec_file = get_exec_file (0);
5318
5319 if (exec_file)
5320 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5321 target_pid_to_str (pid_to_ptid (pid)));
5322 else
5323 printf_unfiltered (_("Attaching to %s\n"),
5324 target_pid_to_str (pid_to_ptid (pid)));
5325
5326 gdb_flush (gdb_stdout);
5327 }
5328
bba74b36 5329 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5330 putpkt (rs->buf);
5331 getpkt (&rs->buf, &rs->buf_size, 0);
5332
4082afcc
PA
5333 switch (packet_ok (rs->buf,
5334 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5335 {
4082afcc 5336 case PACKET_OK:
6efcd9a8 5337 if (!target_is_non_stop_p ())
74531fed
PA
5338 {
5339 /* Save the reply for later. */
224c3ddb 5340 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5341 strcpy (wait_status, rs->buf);
5342 }
5343 else if (strcmp (rs->buf, "OK") != 0)
5344 error (_("Attaching to %s failed with: %s"),
5345 target_pid_to_str (pid_to_ptid (pid)),
5346 rs->buf);
4082afcc
PA
5347 break;
5348 case PACKET_UNKNOWN:
5349 error (_("This target does not support attaching to a process"));
5350 default:
5351 error (_("Attaching to %s failed"),
5352 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5353 }
2d717e4f 5354
1b6e6f5c 5355 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5356
2d717e4f 5357 inferior_ptid = pid_to_ptid (pid);
79d7f229 5358
6efcd9a8 5359 if (target_is_non_stop_p ())
bad34192
PA
5360 {
5361 struct thread_info *thread;
79d7f229 5362
bad34192 5363 /* Get list of threads. */
e8032dde 5364 remote_update_thread_list (target);
82f73884 5365
bad34192
PA
5366 thread = first_thread_of_process (pid);
5367 if (thread)
5368 inferior_ptid = thread->ptid;
5369 else
5370 inferior_ptid = pid_to_ptid (pid);
5371
5372 /* Invalidate our notion of the remote current thread. */
47f8a51d 5373 record_currthread (rs, minus_one_ptid);
bad34192 5374 }
74531fed 5375 else
bad34192
PA
5376 {
5377 /* Now, if we have thread information, update inferior_ptid. */
5378 inferior_ptid = remote_current_thread (inferior_ptid);
5379
5380 /* Add the main thread to the thread list. */
5381 add_thread_silent (inferior_ptid);
5382 }
c0a2216e 5383
96ef3384
UW
5384 /* Next, if the target can specify a description, read it. We do
5385 this before anything involving memory or registers. */
5386 target_find_description ();
5387
6efcd9a8 5388 if (!target_is_non_stop_p ())
74531fed
PA
5389 {
5390 /* Use the previously fetched status. */
5391 gdb_assert (wait_status != NULL);
5392
5393 if (target_can_async_p ())
5394 {
722247f1
YQ
5395 struct notif_event *reply
5396 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5397
722247f1 5398 push_stop_reply ((struct stop_reply *) reply);
74531fed 5399
6a3753b3 5400 target_async (1);
74531fed
PA
5401 }
5402 else
5403 {
5404 gdb_assert (wait_status != NULL);
5405 strcpy (rs->buf, wait_status);
5406 rs->cached_wait_status = 1;
5407 }
5408 }
5409 else
5410 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5411}
5412
b9c1d481
AS
5413/* Implementation of the to_post_attach method. */
5414
5415static void
5416extended_remote_post_attach (struct target_ops *ops, int pid)
5417{
6efcd9a8
PA
5418 /* Get text, data & bss offsets. */
5419 get_offsets ();
5420
b9c1d481
AS
5421 /* In certain cases GDB might not have had the chance to start
5422 symbol lookup up until now. This could happen if the debugged
5423 binary is not using shared libraries, the vsyscall page is not
5424 present (on Linux) and the binary itself hadn't changed since the
5425 debugging process was started. */
5426 if (symfile_objfile != NULL)
5427 remote_check_symbols();
5428}
5429
c906108c 5430\f
506fb367
DJ
5431/* Check for the availability of vCont. This function should also check
5432 the response. */
c906108c
SS
5433
5434static void
6d820c5c 5435remote_vcont_probe (struct remote_state *rs)
c906108c 5436{
2e9f7625 5437 char *buf;
6d820c5c 5438
2e9f7625
DJ
5439 strcpy (rs->buf, "vCont?");
5440 putpkt (rs->buf);
6d820c5c 5441 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5442 buf = rs->buf;
c906108c 5443
506fb367 5444 /* Make sure that the features we assume are supported. */
61012eef 5445 if (startswith (buf, "vCont"))
506fb367
DJ
5446 {
5447 char *p = &buf[5];
750ce8d1 5448 int support_c, support_C;
506fb367 5449
750ce8d1
YQ
5450 rs->supports_vCont.s = 0;
5451 rs->supports_vCont.S = 0;
506fb367
DJ
5452 support_c = 0;
5453 support_C = 0;
d458bd84 5454 rs->supports_vCont.t = 0;
c1e36e3e 5455 rs->supports_vCont.r = 0;
506fb367
DJ
5456 while (p && *p == ';')
5457 {
5458 p++;
5459 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5460 rs->supports_vCont.s = 1;
506fb367 5461 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5462 rs->supports_vCont.S = 1;
506fb367
DJ
5463 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5464 support_c = 1;
5465 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5466 support_C = 1;
74531fed 5467 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5468 rs->supports_vCont.t = 1;
c1e36e3e
PA
5469 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5470 rs->supports_vCont.r = 1;
506fb367
DJ
5471
5472 p = strchr (p, ';');
5473 }
c906108c 5474
750ce8d1
YQ
5475 /* If c, and C are not all supported, we can't use vCont. Clearing
5476 BUF will make packet_ok disable the packet. */
5477 if (!support_c || !support_C)
506fb367
DJ
5478 buf[0] = 0;
5479 }
c906108c 5480
444abaca 5481 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5482}
c906108c 5483
0d8f58ca
PA
5484/* Helper function for building "vCont" resumptions. Write a
5485 resumption to P. ENDP points to one-passed-the-end of the buffer
5486 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5487 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5488 resumed thread should be single-stepped and/or signalled. If PTID
5489 equals minus_one_ptid, then all threads are resumed; if PTID
5490 represents a process, then all threads of the process are resumed;
5491 the thread to be stepped and/or signalled is given in the global
5492 INFERIOR_PTID. */
5493
5494static char *
5495append_resumption (char *p, char *endp,
2ea28649 5496 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5497{
5498 struct remote_state *rs = get_remote_state ();
5499
a493e3e2 5500 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5501 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5502 else if (step
5503 /* GDB is willing to range step. */
5504 && use_range_stepping
5505 /* Target supports range stepping. */
5506 && rs->supports_vCont.r
5507 /* We don't currently support range stepping multiple
5508 threads with a wildcard (though the protocol allows it,
5509 so stubs shouldn't make an active effort to forbid
5510 it). */
5511 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5512 {
5513 struct thread_info *tp;
5514
5515 if (ptid_equal (ptid, minus_one_ptid))
5516 {
5517 /* If we don't know about the target thread's tid, then
5518 we're resuming magic_null_ptid (see caller). */
5519 tp = find_thread_ptid (magic_null_ptid);
5520 }
5521 else
5522 tp = find_thread_ptid (ptid);
5523 gdb_assert (tp != NULL);
5524
5525 if (tp->control.may_range_step)
5526 {
5527 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5528
5529 p += xsnprintf (p, endp - p, ";r%s,%s",
5530 phex_nz (tp->control.step_range_start,
5531 addr_size),
5532 phex_nz (tp->control.step_range_end,
5533 addr_size));
5534 }
5535 else
5536 p += xsnprintf (p, endp - p, ";s");
5537 }
0d8f58ca
PA
5538 else if (step)
5539 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5540 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5541 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5542 else
5543 p += xsnprintf (p, endp - p, ";c");
5544
5545 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5546 {
5547 ptid_t nptid;
5548
5549 /* All (-1) threads of process. */
ba348170 5550 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5551
5552 p += xsnprintf (p, endp - p, ":");
5553 p = write_ptid (p, endp, nptid);
5554 }
5555 else if (!ptid_equal (ptid, minus_one_ptid))
5556 {
5557 p += xsnprintf (p, endp - p, ":");
5558 p = write_ptid (p, endp, ptid);
5559 }
5560
5561 return p;
5562}
5563
799a2abe
PA
5564/* Clear the thread's private info on resume. */
5565
5566static void
5567resume_clear_thread_private_info (struct thread_info *thread)
5568{
5569 if (thread->priv != NULL)
5570 {
5571 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5572 thread->priv->watch_data_address = 0;
5573 }
5574}
5575
e5ef252a
PA
5576/* Append a vCont continue-with-signal action for threads that have a
5577 non-zero stop signal. */
5578
5579static char *
5580append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5581{
5582 struct thread_info *thread;
5583
034f788c 5584 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5585 if (ptid_match (thread->ptid, ptid)
5586 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5587 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5588 {
5589 p = append_resumption (p, endp, thread->ptid,
5590 0, thread->suspend.stop_signal);
5591 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5592 resume_clear_thread_private_info (thread);
e5ef252a
PA
5593 }
5594
5595 return p;
5596}
5597
7b68ffbb
PA
5598/* Set the target running, using the packets that use Hc
5599 (c/s/C/S). */
5600
5601static void
5602remote_resume_with_hc (struct target_ops *ops,
5603 ptid_t ptid, int step, enum gdb_signal siggnal)
5604{
5605 struct remote_state *rs = get_remote_state ();
5606 struct thread_info *thread;
5607 char *buf;
5608
5609 rs->last_sent_signal = siggnal;
5610 rs->last_sent_step = step;
5611
5612 /* The c/s/C/S resume packets use Hc, so set the continue
5613 thread. */
5614 if (ptid_equal (ptid, minus_one_ptid))
5615 set_continue_thread (any_thread_ptid);
5616 else
5617 set_continue_thread (ptid);
5618
5619 ALL_NON_EXITED_THREADS (thread)
5620 resume_clear_thread_private_info (thread);
5621
5622 buf = rs->buf;
5623 if (execution_direction == EXEC_REVERSE)
5624 {
5625 /* We don't pass signals to the target in reverse exec mode. */
5626 if (info_verbose && siggnal != GDB_SIGNAL_0)
5627 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5628 siggnal);
5629
5630 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5631 error (_("Remote reverse-step not supported."));
5632 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5633 error (_("Remote reverse-continue not supported."));
5634
5635 strcpy (buf, step ? "bs" : "bc");
5636 }
5637 else if (siggnal != GDB_SIGNAL_0)
5638 {
5639 buf[0] = step ? 'S' : 'C';
5640 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5641 buf[2] = tohex (((int) siggnal) & 0xf);
5642 buf[3] = '\0';
5643 }
5644 else
5645 strcpy (buf, step ? "s" : "c");
5646
5647 putpkt (buf);
5648}
5649
506fb367
DJ
5650/* Resume the remote inferior by using a "vCont" packet. The thread
5651 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5652 resumed thread should be single-stepped and/or signalled. If PTID
5653 equals minus_one_ptid, then all threads are resumed; the thread to
5654 be stepped and/or signalled is given in the global INFERIOR_PTID.
5655 This function returns non-zero iff it resumes the inferior.
44eaed12 5656
7b68ffbb
PA
5657 This function issues a strict subset of all possible vCont commands
5658 at the moment. */
44eaed12 5659
506fb367 5660static int
7b68ffbb 5661remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5662{
5663 struct remote_state *rs = get_remote_state ();
82f73884
PA
5664 char *p;
5665 char *endp;
44eaed12 5666
7b68ffbb
PA
5667 /* No reverse execution actions defined for vCont. */
5668 if (execution_direction == EXEC_REVERSE)
5669 return 0;
5670
4082afcc 5671 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5672 remote_vcont_probe (rs);
44eaed12 5673
4082afcc 5674 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5675 return 0;
44eaed12 5676
82f73884
PA
5677 p = rs->buf;
5678 endp = rs->buf + get_remote_packet_size ();
5679
506fb367
DJ
5680 /* If we could generate a wider range of packets, we'd have to worry
5681 about overflowing BUF. Should there be a generic
5682 "multi-part-packet" packet? */
5683
0d8f58ca
PA
5684 p += xsnprintf (p, endp - p, "vCont");
5685
79d7f229 5686 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5687 {
79d7f229
PA
5688 /* MAGIC_NULL_PTID means that we don't have any active threads,
5689 so we don't have any TID numbers the inferior will
5690 understand. Make sure to only send forms that do not specify
5691 a TID. */
a9cbf802 5692 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5693 }
0d8f58ca 5694 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5695 {
0d8f58ca
PA
5696 /* Resume all threads (of all processes, or of a single
5697 process), with preference for INFERIOR_PTID. This assumes
5698 inferior_ptid belongs to the set of all threads we are about
5699 to resume. */
a493e3e2 5700 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5701 {
0d8f58ca
PA
5702 /* Step inferior_ptid, with or without signal. */
5703 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5704 }
0d8f58ca 5705
e5ef252a
PA
5706 /* Also pass down any pending signaled resumption for other
5707 threads not the current. */
5708 p = append_pending_thread_resumptions (p, endp, ptid);
5709
0d8f58ca 5710 /* And continue others without a signal. */
a493e3e2 5711 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5712 }
5713 else
506fb367
DJ
5714 {
5715 /* Scheduler locking; resume only PTID. */
a9cbf802 5716 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5717 }
c906108c 5718
82f73884
PA
5719 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5720 putpkt (rs->buf);
506fb367 5721
6efcd9a8 5722 if (target_is_non_stop_p ())
74531fed
PA
5723 {
5724 /* In non-stop, the stub replies to vCont with "OK". The stop
5725 reply will be reported asynchronously by means of a `%Stop'
5726 notification. */
5727 getpkt (&rs->buf, &rs->buf_size, 0);
5728 if (strcmp (rs->buf, "OK") != 0)
5729 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5730 }
5731
506fb367 5732 return 1;
c906108c 5733}
43ff13b4 5734
506fb367
DJ
5735/* Tell the remote machine to resume. */
5736
43ff13b4 5737static void
28439f5e 5738remote_resume (struct target_ops *ops,
2ea28649 5739 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5740{
d01949b6 5741 struct remote_state *rs = get_remote_state ();
43ff13b4 5742
85ad3aaf
PA
5743 /* When connected in non-stop mode, the core resumes threads
5744 individually. Resuming remote threads directly in target_resume
5745 would thus result in sending one packet per thread. Instead, to
5746 minimize roundtrip latency, here we just store the resume
5747 request; the actual remote resumption will be done in
5748 target_commit_resume / remote_commit_resume, where we'll be able
5749 to do vCont action coalescing. */
5750 if (target_is_non_stop_p () && execution_direction != EXEC_REVERSE)
5751 {
5752 struct private_thread_info *remote_thr;
5753
5754 if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5755 remote_thr = get_private_info_ptid (inferior_ptid);
5756 else
5757 remote_thr = get_private_info_ptid (ptid);
5758 remote_thr->last_resume_step = step;
5759 remote_thr->last_resume_sig = siggnal;
5760 return;
5761 }
5762
722247f1
YQ
5763 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5764 (explained in remote-notif.c:handle_notification) so
5765 remote_notif_process is not called. We need find a place where
5766 it is safe to start a 'vNotif' sequence. It is good to do it
5767 before resuming inferior, because inferior was stopped and no RSP
5768 traffic at that moment. */
6efcd9a8 5769 if (!target_is_non_stop_p ())
5965e028 5770 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5771
3a00c802
PA
5772 rs->last_resume_exec_dir = execution_direction;
5773
7b68ffbb
PA
5774 /* Prefer vCont, and fallback to s/c/S/C, which use Hc. */
5775 if (!remote_resume_with_vcont (ptid, step, siggnal))
5776 remote_resume_with_hc (ops, ptid, step, siggnal);
43ff13b4 5777
2acceee2 5778 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5779 with the event loop. NOTE: this is the one place where all the
5780 execution commands end up. We could alternatively do this in each
23860348 5781 of the execution commands in infcmd.c. */
2acceee2
JM
5782 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5783 into infcmd.c in order to allow inferior function calls to work
23860348 5784 NOT asynchronously. */
362646f5 5785 if (target_can_async_p ())
6a3753b3 5786 target_async (1);
e24a49d8
PA
5787
5788 /* We've just told the target to resume. The remote server will
5789 wait for the inferior to stop, and then send a stop reply. In
5790 the mean time, we can't start another command/query ourselves
74531fed
PA
5791 because the stub wouldn't be ready to process it. This applies
5792 only to the base all-stop protocol, however. In non-stop (which
5793 only supports vCont), the stub replies with an "OK", and is
5794 immediate able to process further serial input. */
6efcd9a8 5795 if (!target_is_non_stop_p ())
74531fed 5796 rs->waiting_for_stop_reply = 1;
43ff13b4 5797}
85ad3aaf
PA
5798
5799static void check_pending_events_prevent_wildcard_vcont
5800 (int *may_global_wildcard_vcont);
5801static int is_pending_fork_parent_thread (struct thread_info *thread);
5802
5803/* Private per-inferior info for target remote processes. */
5804
5805struct private_inferior
5806{
5807 /* Whether we can send a wildcard vCont for this process. */
5808 int may_wildcard_vcont;
5809};
5810
5811/* Structure used to track the construction of a vCont packet in the
5812 outgoing packet buffer. This is used to send multiple vCont
5813 packets if we have more actions than would fit a single packet. */
5814
5815struct vcont_builder
5816{
5817 /* Pointer to the first action. P points here if no action has been
5818 appended yet. */
5819 char *first_action;
5820
5821 /* Where the next action will be appended. */
5822 char *p;
5823
5824 /* The end of the buffer. Must never write past this. */
5825 char *endp;
5826};
5827
5828/* Prepare the outgoing buffer for a new vCont packet. */
5829
5830static void
5831vcont_builder_restart (struct vcont_builder *builder)
5832{
5833 struct remote_state *rs = get_remote_state ();
5834
5835 builder->p = rs->buf;
5836 builder->endp = rs->buf + get_remote_packet_size ();
5837 builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
5838 builder->first_action = builder->p;
5839}
5840
5841/* If the vCont packet being built has any action, send it to the
5842 remote end. */
5843
5844static void
5845vcont_builder_flush (struct vcont_builder *builder)
5846{
5847 struct remote_state *rs;
5848
5849 if (builder->p == builder->first_action)
5850 return;
5851
5852 rs = get_remote_state ();
5853 putpkt (rs->buf);
5854 getpkt (&rs->buf, &rs->buf_size, 0);
5855 if (strcmp (rs->buf, "OK") != 0)
5856 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5857}
5858
5859/* The largest action is range-stepping, with its two addresses. This
5860 is more than sufficient. If a new, bigger action is created, it'll
5861 quickly trigger a failed assertion in append_resumption (and we'll
5862 just bump this). */
5863#define MAX_ACTION_SIZE 200
5864
5865/* Append a new vCont action in the outgoing packet being built. If
5866 the action doesn't fit the packet along with previous actions, push
5867 what we've got so far to the remote end and start over a new vCont
5868 packet (with the new action). */
5869
5870static void
5871vcont_builder_push_action (struct vcont_builder *builder,
5872 ptid_t ptid, int step, enum gdb_signal siggnal)
5873{
5874 char buf[MAX_ACTION_SIZE + 1];
5875 char *endp;
5876 size_t rsize;
5877
5878 endp = append_resumption (buf, buf + sizeof (buf),
5879 ptid, step, siggnal);
5880
5881 /* Check whether this new action would fit in the vCont packet along
5882 with previous actions. If not, send what we've got so far and
5883 start a new vCont packet. */
5884 rsize = endp - buf;
5885 if (rsize > builder->endp - builder->p)
5886 {
5887 vcont_builder_flush (builder);
5888 vcont_builder_restart (builder);
5889
5890 /* Should now fit. */
5891 gdb_assert (rsize <= builder->endp - builder->p);
5892 }
5893
5894 memcpy (builder->p, buf, rsize);
5895 builder->p += rsize;
5896 *builder->p = '\0';
5897}
5898
5899/* to_commit_resume implementation. */
5900
5901static void
5902remote_commit_resume (struct target_ops *ops)
5903{
5904 struct remote_state *rs = get_remote_state ();
5905 struct inferior *inf;
5906 struct thread_info *tp;
5907 int any_process_wildcard;
5908 int may_global_wildcard_vcont;
5909 struct vcont_builder vcont_builder;
5910
5911 /* If connected in all-stop mode, we'd send the remote resume
5912 request directly from remote_resume. Likewise if
5913 reverse-debugging, as there are no defined vCont actions for
5914 reverse execution. */
5915 if (!target_is_non_stop_p () || execution_direction == EXEC_REVERSE)
5916 return;
5917
5918 /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
5919 instead of resuming all threads of each process individually.
5920 However, if any thread of a process must remain halted, we can't
5921 send wildcard resumes and must send one action per thread.
5922
5923 Care must be taken to not resume threads/processes the server
5924 side already told us are stopped, but the core doesn't know about
5925 yet, because the events are still in the vStopped notification
5926 queue. For example:
5927
5928 #1 => vCont s:p1.1;c
5929 #2 <= OK
5930 #3 <= %Stopped T05 p1.1
5931 #4 => vStopped
5932 #5 <= T05 p1.2
5933 #6 => vStopped
5934 #7 <= OK
5935 #8 (infrun handles the stop for p1.1 and continues stepping)
5936 #9 => vCont s:p1.1;c
5937
5938 The last vCont above would resume thread p1.2 by mistake, because
5939 the server has no idea that the event for p1.2 had not been
5940 handled yet.
5941
5942 The server side must similarly ignore resume actions for the
5943 thread that has a pending %Stopped notification (and any other
5944 threads with events pending), until GDB acks the notification
5945 with vStopped. Otherwise, e.g., the following case is
5946 mishandled:
5947
5948 #1 => g (or any other packet)
5949 #2 <= [registers]
5950 #3 <= %Stopped T05 p1.2
5951 #4 => vCont s:p1.1;c
5952 #5 <= OK
5953
5954 Above, the server must not resume thread p1.2. GDB can't know
5955 that p1.2 stopped until it acks the %Stopped notification, and
5956 since from GDB's perspective all threads should be running, it
5957 sends a "c" action.
5958
5959 Finally, special care must also be given to handling fork/vfork
5960 events. A (v)fork event actually tells us that two processes
5961 stopped -- the parent and the child. Until we follow the fork,
5962 we must not resume the child. Therefore, if we have a pending
5963 fork follow, we must not send a global wildcard resume action
5964 (vCont;c). We can still send process-wide wildcards though. */
5965
5966 /* Start by assuming a global wildcard (vCont;c) is possible. */
5967 may_global_wildcard_vcont = 1;
5968
5969 /* And assume every process is individually wildcard-able too. */
5970 ALL_NON_EXITED_INFERIORS (inf)
5971 {
5972 if (inf->priv == NULL)
5973 inf->priv = XNEW (struct private_inferior);
5974 inf->priv->may_wildcard_vcont = 1;
5975 }
5976
5977 /* Check for any pending events (not reported or processed yet) and
5978 disable process and global wildcard resumes appropriately. */
5979 check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
5980
5981 ALL_NON_EXITED_THREADS (tp)
5982 {
5983 /* If a thread of a process is not meant to be resumed, then we
5984 can't wildcard that process. */
5985 if (!tp->executing)
5986 {
5987 tp->inf->priv->may_wildcard_vcont = 0;
5988
5989 /* And if we can't wildcard a process, we can't wildcard
5990 everything either. */
5991 may_global_wildcard_vcont = 0;
5992 continue;
5993 }
5994
5995 /* If a thread is the parent of an unfollowed fork, then we
5996 can't do a global wildcard, as that would resume the fork
5997 child. */
5998 if (is_pending_fork_parent_thread (tp))
5999 may_global_wildcard_vcont = 0;
6000 }
6001
6002 /* Now let's build the vCont packet(s). Actions must be appended
6003 from narrower to wider scopes (thread -> process -> global). If
6004 we end up with too many actions for a single packet vcont_builder
6005 flushes the current vCont packet to the remote side and starts a
6006 new one. */
6007 vcont_builder_restart (&vcont_builder);
6008
6009 /* Threads first. */
6010 ALL_NON_EXITED_THREADS (tp)
6011 {
6012 struct private_thread_info *remote_thr = tp->priv;
6013
6014 if (!tp->executing || remote_thr->vcont_resumed)
6015 continue;
6016
6017 gdb_assert (!thread_is_in_step_over_chain (tp));
6018
6019 if (!remote_thr->last_resume_step
6020 && remote_thr->last_resume_sig == GDB_SIGNAL_0
6021 && tp->inf->priv->may_wildcard_vcont)
6022 {
6023 /* We'll send a wildcard resume instead. */
6024 remote_thr->vcont_resumed = 1;
6025 continue;
6026 }
6027
6028 vcont_builder_push_action (&vcont_builder, tp->ptid,
6029 remote_thr->last_resume_step,
6030 remote_thr->last_resume_sig);
6031 remote_thr->vcont_resumed = 1;
6032 }
6033
6034 /* Now check whether we can send any process-wide wildcard. This is
6035 to avoid sending a global wildcard in the case nothing is
6036 supposed to be resumed. */
6037 any_process_wildcard = 0;
6038
6039 ALL_NON_EXITED_INFERIORS (inf)
6040 {
6041 if (inf->priv->may_wildcard_vcont)
6042 {
6043 any_process_wildcard = 1;
6044 break;
6045 }
6046 }
6047
6048 if (any_process_wildcard)
6049 {
6050 /* If all processes are wildcard-able, then send a single "c"
6051 action, otherwise, send an "all (-1) threads of process"
6052 continue action for each running process, if any. */
6053 if (may_global_wildcard_vcont)
6054 {
6055 vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6056 0, GDB_SIGNAL_0);
6057 }
6058 else
6059 {
6060 ALL_NON_EXITED_INFERIORS (inf)
6061 {
6062 if (inf->priv->may_wildcard_vcont)
6063 {
6064 vcont_builder_push_action (&vcont_builder,
6065 pid_to_ptid (inf->pid),
6066 0, GDB_SIGNAL_0);
6067 }
6068 }
6069 }
6070 }
6071
6072 vcont_builder_flush (&vcont_builder);
6073}
6074
c906108c 6075\f
43ff13b4 6076
74531fed
PA
6077/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
6078 thread, all threads of a remote process, or all threads of all
6079 processes. */
6080
6081static void
6082remote_stop_ns (ptid_t ptid)
6083{
6084 struct remote_state *rs = get_remote_state ();
6085 char *p = rs->buf;
6086 char *endp = rs->buf + get_remote_packet_size ();
74531fed 6087
4082afcc 6088 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
6089 remote_vcont_probe (rs);
6090
d458bd84 6091 if (!rs->supports_vCont.t)
74531fed
PA
6092 error (_("Remote server does not support stopping threads"));
6093
f91d3df5
PA
6094 if (ptid_equal (ptid, minus_one_ptid)
6095 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
6096 p += xsnprintf (p, endp - p, "vCont;t");
6097 else
6098 {
6099 ptid_t nptid;
6100
74531fed
PA
6101 p += xsnprintf (p, endp - p, "vCont;t:");
6102
6103 if (ptid_is_pid (ptid))
6104 /* All (-1) threads of process. */
ba348170 6105 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
6106 else
6107 {
6108 /* Small optimization: if we already have a stop reply for
6109 this thread, no use in telling the stub we want this
6110 stopped. */
6111 if (peek_stop_reply (ptid))
6112 return;
6113
6114 nptid = ptid;
6115 }
6116
a9cbf802 6117 write_ptid (p, endp, nptid);
74531fed
PA
6118 }
6119
6120 /* In non-stop, we get an immediate OK reply. The stop reply will
6121 come in asynchronously by notification. */
6122 putpkt (rs->buf);
6123 getpkt (&rs->buf, &rs->buf_size, 0);
6124 if (strcmp (rs->buf, "OK") != 0)
6125 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6126}
6127
bfedc46a
PA
6128/* All-stop version of target_interrupt. Sends a break or a ^C to
6129 interrupt the remote target. It is undefined which thread of which
6130 process reports the interrupt. */
74531fed
PA
6131
6132static void
de979965 6133remote_interrupt_as (void)
74531fed
PA
6134{
6135 struct remote_state *rs = get_remote_state ();
6136
3a29589a
DJ
6137 rs->ctrlc_pending_p = 1;
6138
74531fed
PA
6139 /* If the inferior is stopped already, but the core didn't know
6140 about it yet, just ignore the request. The cached wait status
6141 will be collected in remote_wait. */
6142 if (rs->cached_wait_status)
6143 return;
6144
9a7071a8
JB
6145 /* Send interrupt_sequence to remote target. */
6146 send_interrupt_sequence ();
74531fed
PA
6147}
6148
de979965
PA
6149/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
6150 the remote target. It is undefined which thread of which process
e42de8c7
PA
6151 reports the interrupt. Throws an error if the packet is not
6152 supported by the server. */
de979965 6153
e42de8c7 6154static void
de979965
PA
6155remote_interrupt_ns (void)
6156{
6157 struct remote_state *rs = get_remote_state ();
6158 char *p = rs->buf;
6159 char *endp = rs->buf + get_remote_packet_size ();
6160
6161 xsnprintf (p, endp - p, "vCtrlC");
6162
6163 /* In non-stop, we get an immediate OK reply. The stop reply will
6164 come in asynchronously by notification. */
6165 putpkt (rs->buf);
6166 getpkt (&rs->buf, &rs->buf_size, 0);
6167
6168 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6169 {
6170 case PACKET_OK:
6171 break;
6172 case PACKET_UNKNOWN:
e42de8c7 6173 error (_("No support for interrupting the remote target."));
de979965
PA
6174 case PACKET_ERROR:
6175 error (_("Interrupting target failed: %s"), rs->buf);
6176 }
de979965
PA
6177}
6178
bfedc46a 6179/* Implement the to_stop function for the remote targets. */
74531fed 6180
c906108c 6181static void
1eab8a48 6182remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 6183{
7a292a7a 6184 if (remote_debug)
0f71a2f6 6185 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 6186
6efcd9a8 6187 if (target_is_non_stop_p ())
74531fed 6188 remote_stop_ns (ptid);
c906108c 6189 else
bfedc46a
PA
6190 {
6191 /* We don't currently have a way to transparently pause the
6192 remote target in all-stop mode. Interrupt it instead. */
de979965 6193 remote_interrupt_as ();
bfedc46a
PA
6194 }
6195}
6196
6197/* Implement the to_interrupt function for the remote targets. */
6198
6199static void
6200remote_interrupt (struct target_ops *self, ptid_t ptid)
6201{
e42de8c7
PA
6202 struct remote_state *rs = get_remote_state ();
6203
bfedc46a
PA
6204 if (remote_debug)
6205 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6206
e42de8c7
PA
6207 if (target_is_non_stop_p ())
6208 remote_interrupt_ns ();
bfedc46a 6209 else
e42de8c7 6210 remote_interrupt_as ();
c906108c
SS
6211}
6212
93692b58
PA
6213/* Implement the to_pass_ctrlc function for the remote targets. */
6214
6215static void
6216remote_pass_ctrlc (struct target_ops *self)
6217{
6218 struct remote_state *rs = get_remote_state ();
6219
6220 if (remote_debug)
6221 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6222
6223 /* If we're starting up, we're not fully synced yet. Quit
6224 immediately. */
6225 if (rs->starting_up)
6226 quit ();
6227 /* If ^C has already been sent once, offer to disconnect. */
6228 else if (rs->ctrlc_pending_p)
6229 interrupt_query ();
6230 else
6231 target_interrupt (inferior_ptid);
6232}
6233
c906108c
SS
6234/* Ask the user what to do when an interrupt is received. */
6235
6236static void
fba45db2 6237interrupt_query (void)
c906108c 6238{
abc56d60 6239 struct remote_state *rs = get_remote_state ();
c906108c 6240
abc56d60 6241 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 6242 {
abc56d60
PA
6243 if (query (_("The target is not responding to interrupt requests.\n"
6244 "Stop debugging it? ")))
74531fed 6245 {
78a095c3 6246 remote_unpush_target ();
abc56d60 6247 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
6248 }
6249 }
abc56d60
PA
6250 else
6251 {
6252 if (query (_("Interrupted while waiting for the program.\n"
6253 "Give up waiting? ")))
6254 quit ();
6255 }
c906108c
SS
6256}
6257
6426a772
JM
6258/* Enable/disable target terminal ownership. Most targets can use
6259 terminal groups to control terminal ownership. Remote targets are
6260 different in that explicit transfer of ownership to/from GDB/target
23860348 6261 is required. */
6426a772
JM
6262
6263static void
d2f640d4 6264remote_terminal_inferior (struct target_ops *self)
6426a772 6265{
d9d2d8b6
PA
6266 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
6267 idempotent. The event-loop GDB talking to an asynchronous target
6268 with a synchronous command calls this function from both
6269 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
6270 transfer the terminal to the target when it shouldn't this guard
6271 can go away. */
6426a772
JM
6272 if (!remote_async_terminal_ours_p)
6273 return;
6426a772 6274 remote_async_terminal_ours_p = 0;
6426a772
JM
6275 /* NOTE: At this point we could also register our selves as the
6276 recipient of all input. Any characters typed could then be
23860348 6277 passed on down to the target. */
6426a772
JM
6278}
6279
6280static void
e3594fd1 6281remote_terminal_ours (struct target_ops *self)
6426a772 6282{
75c99385 6283 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
6284 if (remote_async_terminal_ours_p)
6285 return;
6426a772
JM
6286 remote_async_terminal_ours_p = 1;
6287}
6288
176a6961 6289static void
917317f4 6290remote_console_output (char *msg)
c906108c
SS
6291{
6292 char *p;
6293
c5aa993b 6294 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6295 {
6296 char tb[2];
6297 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6298
c906108c
SS
6299 tb[0] = c;
6300 tb[1] = 0;
43ff13b4 6301 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6302 }
00db5b94
PA
6303 gdb_flush (gdb_stdtarg);
6304}
74531fed
PA
6305
6306typedef struct cached_reg
6307{
6308 int num;
6309 gdb_byte data[MAX_REGISTER_SIZE];
6310} cached_reg_t;
6311
6312DEF_VEC_O(cached_reg_t);
6313
722247f1 6314typedef struct stop_reply
74531fed 6315{
722247f1 6316 struct notif_event base;
74531fed 6317
722247f1 6318 /* The identifier of the thread about this event */
74531fed
PA
6319 ptid_t ptid;
6320
340e3c99 6321 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6322 connection, represented by a remote_state object, is closed,
6323 all the associated stop_reply events should be released. */
6324 struct remote_state *rs;
6325
74531fed
PA
6326 struct target_waitstatus ws;
6327
15148d6a
PA
6328 /* Expedited registers. This makes remote debugging a bit more
6329 efficient for those targets that provide critical registers as
6330 part of their normal status mechanism (as another roundtrip to
6331 fetch them is avoided). */
74531fed
PA
6332 VEC(cached_reg_t) *regcache;
6333
f7e6eed5
PA
6334 enum target_stop_reason stop_reason;
6335
74531fed
PA
6336 CORE_ADDR watch_data_address;
6337
dc146f7c 6338 int core;
722247f1 6339} *stop_reply_p;
a744cf53 6340
722247f1
YQ
6341DECLARE_QUEUE_P (stop_reply_p);
6342DEFINE_QUEUE_P (stop_reply_p);
6343/* The list of already fetched and acknowledged stop events. This
6344 queue is used for notification Stop, and other notifications
6345 don't need queue for their events, because the notification events
6346 of Stop can't be consumed immediately, so that events should be
6347 queued first, and be consumed by remote_wait_{ns,as} one per
6348 time. Other notifications can consume their events immediately,
6349 so queue is not needed for them. */
6350static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
6351
6352static void
6353stop_reply_xfree (struct stop_reply *r)
6354{
f48ff2a7 6355 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6356}
6357
221e1a37
PA
6358/* Return the length of the stop reply queue. */
6359
6360static int
6361stop_reply_queue_length (void)
6362{
6363 return QUEUE_length (stop_reply_p, stop_reply_queue);
6364}
6365
722247f1
YQ
6366static void
6367remote_notif_stop_parse (struct notif_client *self, char *buf,
6368 struct notif_event *event)
6369{
6370 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6371}
6372
6373static void
6374remote_notif_stop_ack (struct notif_client *self, char *buf,
6375 struct notif_event *event)
6376{
6377 struct stop_reply *stop_reply = (struct stop_reply *) event;
6378
6379 /* acknowledge */
f5c4fcd9 6380 putpkt (self->ack_command);
722247f1
YQ
6381
6382 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6383 /* We got an unknown stop reply. */
6384 error (_("Unknown stop reply"));
6385
6386 push_stop_reply (stop_reply);
6387}
6388
6389static int
6390remote_notif_stop_can_get_pending_events (struct notif_client *self)
6391{
6392 /* We can't get pending events in remote_notif_process for
6393 notification stop, and we have to do this in remote_wait_ns
6394 instead. If we fetch all queued events from stub, remote stub
6395 may exit and we have no chance to process them back in
6396 remote_wait_ns. */
6397 mark_async_event_handler (remote_async_inferior_event_token);
6398 return 0;
6399}
6400
6401static void
6402stop_reply_dtr (struct notif_event *event)
6403{
6404 struct stop_reply *r = (struct stop_reply *) event;
6405
6406 VEC_free (cached_reg_t, r->regcache);
6407}
6408
6409static struct notif_event *
6410remote_notif_stop_alloc_reply (void)
6411{
8d749320
SM
6412 /* We cast to a pointer to the "base class". */
6413 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6414
6415 r->dtr = stop_reply_dtr;
6416
6417 return r;
6418}
6419
6420/* A client of notification Stop. */
6421
6422struct notif_client notif_client_stop =
6423{
6424 "Stop",
6425 "vStopped",
6426 remote_notif_stop_parse,
6427 remote_notif_stop_ack,
6428 remote_notif_stop_can_get_pending_events,
6429 remote_notif_stop_alloc_reply,
f48ff2a7 6430 REMOTE_NOTIF_STOP,
722247f1
YQ
6431};
6432
6433/* A parameter to pass data in and out. */
6434
6435struct queue_iter_param
6436{
6437 void *input;
6438 struct stop_reply *output;
6439};
6440
85ad3aaf 6441/* Determine if THREAD_PTID is a pending fork parent thread. ARG contains
cbb8991c
DB
6442 the pid of the process that owns the threads we want to check, or
6443 -1 if we want to check all threads. */
6444
6445static int
6446is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6447 ptid_t thread_ptid)
6448{
6449 if (ws->kind == TARGET_WAITKIND_FORKED
6450 || ws->kind == TARGET_WAITKIND_VFORKED)
6451 {
6452 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6453 return 1;
6454 }
6455
6456 return 0;
6457}
6458
85ad3aaf
PA
6459/* Return the thread's pending status used to determine whether the
6460 thread is a fork parent stopped at a fork event. */
6461
6462static struct target_waitstatus *
6463thread_pending_fork_status (struct thread_info *thread)
6464{
6465 if (thread->suspend.waitstatus_pending_p)
6466 return &thread->suspend.waitstatus;
6467 else
6468 return &thread->pending_follow;
6469}
6470
6471/* Determine if THREAD is a pending fork parent thread. */
6472
6473static int
6474is_pending_fork_parent_thread (struct thread_info *thread)
6475{
6476 struct target_waitstatus *ws = thread_pending_fork_status (thread);
6477 int pid = -1;
6478
6479 return is_pending_fork_parent (ws, pid, thread->ptid);
6480}
6481
cbb8991c
DB
6482/* Check whether EVENT is a fork event, and if it is, remove the
6483 fork child from the context list passed in DATA. */
6484
6485static int
6486remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6487 QUEUE_ITER (stop_reply_p) *iter,
6488 stop_reply_p event,
6489 void *data)
6490{
19ba03f4
SM
6491 struct queue_iter_param *param = (struct queue_iter_param *) data;
6492 struct threads_listing_context *context
6493 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6494
6495 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6496 || event->ws.kind == TARGET_WAITKIND_VFORKED
6497 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6498 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6499
6500 return 1;
6501}
6502
6503/* If CONTEXT contains any fork child threads that have not been
6504 reported yet, remove them from the CONTEXT list. If such a
6505 thread exists it is because we are stopped at a fork catchpoint
6506 and have not yet called follow_fork, which will set up the
6507 host-side data structures for the new process. */
6508
6509static void
6510remove_new_fork_children (struct threads_listing_context *context)
6511{
6512 struct thread_info * thread;
6513 int pid = -1;
6514 struct notif_client *notif = &notif_client_stop;
6515 struct queue_iter_param param;
6516
6517 /* For any threads stopped at a fork event, remove the corresponding
6518 fork child threads from the CONTEXT list. */
6519 ALL_NON_EXITED_THREADS (thread)
6520 {
85ad3aaf 6521 struct target_waitstatus *ws = thread_pending_fork_status (thread);
cbb8991c
DB
6522
6523 if (is_pending_fork_parent (ws, pid, thread->ptid))
6524 {
6525 threads_listing_context_remove (ws, context);
6526 }
6527 }
6528
6529 /* Check for any pending fork events (not reported or processed yet)
6530 in process PID and remove those fork child threads from the
6531 CONTEXT list as well. */
6532 remote_notif_get_pending_events (notif);
6533 param.input = context;
6534 param.output = NULL;
6535 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6536 remove_child_of_pending_fork, &param);
6537}
6538
85ad3aaf
PA
6539/* Check whether EVENT would prevent a global or process wildcard
6540 vCont action. */
6541
6542static int
6543check_pending_event_prevents_wildcard_vcont_callback
6544 (QUEUE (stop_reply_p) *q,
6545 QUEUE_ITER (stop_reply_p) *iter,
6546 stop_reply_p event,
6547 void *data)
6548{
6549 struct inferior *inf;
6550 int *may_global_wildcard_vcont = (int *) data;
6551
6552 if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6553 || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6554 return 1;
6555
6556 if (event->ws.kind == TARGET_WAITKIND_FORKED
6557 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6558 *may_global_wildcard_vcont = 0;
6559
6560 inf = find_inferior_ptid (event->ptid);
6561
6562 /* This may be the first time we heard about this process.
6563 Regardless, we must not do a global wildcard resume, otherwise
6564 we'd resume this process too. */
6565 *may_global_wildcard_vcont = 0;
6566 if (inf != NULL)
6567 inf->priv->may_wildcard_vcont = 0;
6568
6569 return 1;
6570}
6571
6572/* Check whether any event pending in the vStopped queue would prevent
6573 a global or process wildcard vCont action. Clear
6574 *may_global_wildcard if we can't do a global wildcard (vCont;c),
6575 and clear the event inferior's may_wildcard_vcont flag if we can't
6576 do a process-wide wildcard resume (vCont;c:pPID.-1). */
6577
6578static void
6579check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6580{
6581 struct notif_client *notif = &notif_client_stop;
6582
6583 remote_notif_get_pending_events (notif);
6584 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6585 check_pending_event_prevents_wildcard_vcont_callback,
6586 may_global_wildcard);
6587}
6588
f48ff2a7
YQ
6589/* Remove stop replies in the queue if its pid is equal to the given
6590 inferior's pid. */
722247f1
YQ
6591
6592static int
f48ff2a7
YQ
6593remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6594 QUEUE_ITER (stop_reply_p) *iter,
6595 stop_reply_p event,
6596 void *data)
722247f1 6597{
19ba03f4
SM
6598 struct queue_iter_param *param = (struct queue_iter_param *) data;
6599 struct inferior *inf = (struct inferior *) param->input;
722247f1 6600
f48ff2a7 6601 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6602 {
6603 stop_reply_xfree (event);
6604 QUEUE_remove_elem (stop_reply_p, q, iter);
6605 }
6606
6607 return 1;
6608}
6609
f48ff2a7 6610/* Discard all pending stop replies of inferior INF. */
c906108c 6611
74531fed 6612static void
5f4cf0bb 6613discard_pending_stop_replies (struct inferior *inf)
c906108c 6614{
722247f1 6615 struct queue_iter_param param;
f48ff2a7
YQ
6616 struct stop_reply *reply;
6617 struct remote_state *rs = get_remote_state ();
6618 struct remote_notif_state *rns = rs->notif_state;
6619
6620 /* This function can be notified when an inferior exists. When the
6621 target is not remote, the notification state is NULL. */
6622 if (rs->remote_desc == NULL)
6623 return;
6624
6625 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6626
74531fed 6627 /* Discard the in-flight notification. */
f48ff2a7 6628 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6629 {
722247f1 6630 stop_reply_xfree (reply);
f48ff2a7 6631 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6632 }
c906108c 6633
722247f1
YQ
6634 param.input = inf;
6635 param.output = NULL;
74531fed
PA
6636 /* Discard the stop replies we have already pulled with
6637 vStopped. */
722247f1 6638 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6639 remove_stop_reply_for_inferior, &param);
6640}
6641
bcc75809
YQ
6642/* If its remote state is equal to the given remote state,
6643 remove EVENT from the stop reply queue. */
6644
6645static int
6646remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6647 QUEUE_ITER (stop_reply_p) *iter,
6648 stop_reply_p event,
6649 void *data)
6650{
19ba03f4
SM
6651 struct queue_iter_param *param = (struct queue_iter_param *) data;
6652 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6653
6654 if (event->rs == rs)
6655 {
6656 stop_reply_xfree (event);
6657 QUEUE_remove_elem (stop_reply_p, q, iter);
6658 }
6659
6660 return 1;
6661}
6662
6663/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6664
6665static void
bcc75809 6666discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6667{
6668 struct queue_iter_param param;
6669
bcc75809 6670 param.input = rs;
f48ff2a7
YQ
6671 param.output = NULL;
6672 /* Discard the stop replies we have already pulled with
6673 vStopped. */
6674 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6675 remove_stop_reply_of_remote_state, &param);
722247f1 6676}
74531fed 6677
722247f1
YQ
6678/* A parameter to pass data in and out. */
6679
6680static int
6681remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6682 QUEUE_ITER (stop_reply_p) *iter,
6683 stop_reply_p event,
6684 void *data)
6685{
19ba03f4
SM
6686 struct queue_iter_param *param = (struct queue_iter_param *) data;
6687 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6688
6689 if (ptid_match (event->ptid, *ptid))
6690 {
6691 param->output = event;
6692 QUEUE_remove_elem (stop_reply_p, q, iter);
6693 return 0;
c8e38a49 6694 }
722247f1
YQ
6695
6696 return 1;
74531fed 6697}
43ff13b4 6698
722247f1
YQ
6699/* Remove the first reply in 'stop_reply_queue' which matches
6700 PTID. */
2e9f7625 6701
722247f1
YQ
6702static struct stop_reply *
6703remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6704{
722247f1
YQ
6705 struct queue_iter_param param;
6706
6707 param.input = &ptid;
6708 param.output = NULL;
6709
6710 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6711 remote_notif_remove_once_on_match, &param);
6712 if (notif_debug)
6713 fprintf_unfiltered (gdb_stdlog,
6714 "notif: discard queued event: 'Stop' in %s\n",
6715 target_pid_to_str (ptid));
a744cf53 6716
722247f1 6717 return param.output;
74531fed 6718}
75c99385 6719
74531fed
PA
6720/* Look for a queued stop reply belonging to PTID. If one is found,
6721 remove it from the queue, and return it. Returns NULL if none is
6722 found. If there are still queued events left to process, tell the
6723 event loop to get back to target_wait soon. */
e24a49d8 6724
74531fed
PA
6725static struct stop_reply *
6726queued_stop_reply (ptid_t ptid)
6727{
722247f1 6728 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6729
722247f1 6730 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6731 /* There's still at least an event left. */
6732 mark_async_event_handler (remote_async_inferior_event_token);
6733
722247f1 6734 return r;
74531fed
PA
6735}
6736
6737/* Push a fully parsed stop reply in the stop reply queue. Since we
6738 know that we now have at least one queued event left to pass to the
6739 core side, tell the event loop to get back to target_wait soon. */
6740
6741static void
6742push_stop_reply (struct stop_reply *new_event)
6743{
722247f1 6744 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6745
722247f1
YQ
6746 if (notif_debug)
6747 fprintf_unfiltered (gdb_stdlog,
6748 "notif: push 'Stop' %s to queue %d\n",
6749 target_pid_to_str (new_event->ptid),
6750 QUEUE_length (stop_reply_p,
6751 stop_reply_queue));
74531fed
PA
6752
6753 mark_async_event_handler (remote_async_inferior_event_token);
6754}
6755
722247f1
YQ
6756static int
6757stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6758 QUEUE_ITER (stop_reply_p) *iter,
6759 struct stop_reply *event,
6760 void *data)
6761{
19ba03f4 6762 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6763
6764 return !(ptid_equal (*ptid, event->ptid)
6765 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6766}
6767
74531fed
PA
6768/* Returns true if we have a stop reply for PTID. */
6769
6770static int
6771peek_stop_reply (ptid_t ptid)
6772{
722247f1
YQ
6773 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6774 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6775}
6776
26d56a93
SL
6777/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6778 starting with P and ending with PEND matches PREFIX. */
6779
6780static int
6781strprefix (const char *p, const char *pend, const char *prefix)
6782{
6783 for ( ; p < pend; p++, prefix++)
6784 if (*p != *prefix)
6785 return 0;
6786 return *prefix == '\0';
6787}
6788
74531fed
PA
6789/* Parse the stop reply in BUF. Either the function succeeds, and the
6790 result is stored in EVENT, or throws an error. */
6791
6792static void
6793remote_parse_stop_reply (char *buf, struct stop_reply *event)
6794{
6795 struct remote_arch_state *rsa = get_remote_arch_state ();
6796 ULONGEST addr;
6797 char *p;
94585166 6798 int skipregs = 0;
74531fed
PA
6799
6800 event->ptid = null_ptid;
bcc75809 6801 event->rs = get_remote_state ();
74531fed
PA
6802 event->ws.kind = TARGET_WAITKIND_IGNORE;
6803 event->ws.value.integer = 0;
f7e6eed5 6804 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6805 event->regcache = NULL;
dc146f7c 6806 event->core = -1;
74531fed
PA
6807
6808 switch (buf[0])
6809 {
6810 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6811 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6812 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6813 ss = signal number
6814 n... = register number
6815 r... = register contents
6816 */
6817
6818 p = &buf[3]; /* after Txx */
6819 while (*p)
6820 {
6821 char *p1;
cea39f65 6822 int fieldsize;
43ff13b4 6823
1f10ba14
PA
6824 p1 = strchr (p, ':');
6825 if (p1 == NULL)
6826 error (_("Malformed packet(a) (missing colon): %s\n\
6827Packet: '%s'\n"),
6828 p, buf);
6829 if (p == p1)
6830 error (_("Malformed packet(a) (missing register number): %s\n\
6831Packet: '%s'\n"),
6832 p, buf);
3c3bea1c 6833
1f10ba14
PA
6834 /* Some "registers" are actually extended stop information.
6835 Note if you're adding a new entry here: GDB 7.9 and
6836 earlier assume that all register "numbers" that start
6837 with an hex digit are real register numbers. Make sure
6838 the server only sends such a packet if it knows the
6839 client understands it. */
c8e38a49 6840
26d56a93 6841 if (strprefix (p, p1, "thread"))
1f10ba14 6842 event->ptid = read_ptid (++p1, &p);
82075af2
JS
6843 else if (strprefix (p, p1, "syscall_entry"))
6844 {
6845 ULONGEST sysno;
6846
6847 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6848 p = unpack_varlen_hex (++p1, &sysno);
6849 event->ws.value.syscall_number = (int) sysno;
6850 }
6851 else if (strprefix (p, p1, "syscall_return"))
6852 {
6853 ULONGEST sysno;
6854
6855 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6856 p = unpack_varlen_hex (++p1, &sysno);
6857 event->ws.value.syscall_number = (int) sysno;
6858 }
26d56a93
SL
6859 else if (strprefix (p, p1, "watch")
6860 || strprefix (p, p1, "rwatch")
6861 || strprefix (p, p1, "awatch"))
cea39f65 6862 {
f7e6eed5 6863 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6864 p = unpack_varlen_hex (++p1, &addr);
6865 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6866 }
26d56a93 6867 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6868 {
6869 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6870
6871 /* Make sure the stub doesn't forget to indicate support
6872 with qSupported. */
6873 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6874 error (_("Unexpected swbreak stop reason"));
6875
6876 /* The value part is documented as "must be empty",
6877 though we ignore it, in case we ever decide to make
6878 use of it in a backward compatible way. */
8424cc97 6879 p = strchrnul (p1 + 1, ';');
f7e6eed5 6880 }
26d56a93 6881 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6882 {
6883 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6884
6885 /* Make sure the stub doesn't forget to indicate support
6886 with qSupported. */
6887 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6888 error (_("Unexpected hwbreak stop reason"));
6889
6890 /* See above. */
8424cc97 6891 p = strchrnul (p1 + 1, ';');
f7e6eed5 6892 }
26d56a93 6893 else if (strprefix (p, p1, "library"))
cea39f65 6894 {
1f10ba14 6895 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 6896 p = strchrnul (p1 + 1, ';');
1f10ba14 6897 }
26d56a93 6898 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6899 {
6900 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6901 /* p1 will indicate "begin" or "end", but it makes
6902 no difference for now, so ignore it. */
8424cc97 6903 p = strchrnul (p1 + 1, ';');
1f10ba14 6904 }
26d56a93 6905 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6906 {
6907 ULONGEST c;
a744cf53 6908
1f10ba14
PA
6909 p = unpack_varlen_hex (++p1, &c);
6910 event->core = c;
cea39f65 6911 }
26d56a93 6912 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6913 {
6914 event->ws.value.related_pid = read_ptid (++p1, &p);
6915 event->ws.kind = TARGET_WAITKIND_FORKED;
6916 }
26d56a93 6917 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6918 {
6919 event->ws.value.related_pid = read_ptid (++p1, &p);
6920 event->ws.kind = TARGET_WAITKIND_VFORKED;
6921 }
26d56a93 6922 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6923 {
6924 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 6925 p = strchrnul (p1 + 1, ';');
c269dbdb 6926 }
6ab24463 6927 else if (strprefix (p, p1, "exec"))
94585166
DB
6928 {
6929 ULONGEST ignored;
6930 char pathname[PATH_MAX];
6931 int pathlen;
6932
6933 /* Determine the length of the execd pathname. */
6934 p = unpack_varlen_hex (++p1, &ignored);
6935 pathlen = (p - p1) / 2;
6936
6937 /* Save the pathname for event reporting and for
6938 the next run command. */
6939 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6940 pathname[pathlen] = '\0';
6941
6942 /* This is freed during event handling. */
6943 event->ws.value.execd_pathname = xstrdup (pathname);
6944 event->ws.kind = TARGET_WAITKIND_EXECD;
6945
6946 /* Skip the registers included in this packet, since
6947 they may be for an architecture different from the
6948 one used by the original program. */
6949 skipregs = 1;
6950 }
65706a29
PA
6951 else if (strprefix (p, p1, "create"))
6952 {
6953 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 6954 p = strchrnul (p1 + 1, ';');
65706a29 6955 }
cea39f65
MS
6956 else
6957 {
1f10ba14
PA
6958 ULONGEST pnum;
6959 char *p_temp;
6960
94585166
DB
6961 if (skipregs)
6962 {
8424cc97 6963 p = strchrnul (p1 + 1, ';');
94585166
DB
6964 p++;
6965 continue;
6966 }
6967
1f10ba14
PA
6968 /* Maybe a real ``P'' register number. */
6969 p_temp = unpack_varlen_hex (p, &pnum);
6970 /* If the first invalid character is the colon, we got a
6971 register number. Otherwise, it's an unknown stop
6972 reason. */
6973 if (p_temp == p1)
6974 {
6975 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6976 cached_reg_t cached_reg;
43ff13b4 6977
1f10ba14
PA
6978 if (reg == NULL)
6979 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6980Packet: '%s'\n"),
1f10ba14 6981 hex_string (pnum), p, buf);
c8e38a49 6982
1f10ba14 6983 cached_reg.num = reg->regnum;
4100683b 6984
1f10ba14
PA
6985 p = p1 + 1;
6986 fieldsize = hex2bin (p, cached_reg.data,
6987 register_size (target_gdbarch (),
6988 reg->regnum));
6989 p += 2 * fieldsize;
6990 if (fieldsize < register_size (target_gdbarch (),
6991 reg->regnum))
6992 warning (_("Remote reply is too short: %s"), buf);
74531fed 6993
1f10ba14
PA
6994 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6995 }
6996 else
6997 {
6998 /* Not a number. Silently skip unknown optional
6999 info. */
8424cc97 7000 p = strchrnul (p1 + 1, ';');
1f10ba14 7001 }
cea39f65 7002 }
c8e38a49 7003
cea39f65
MS
7004 if (*p != ';')
7005 error (_("Remote register badly formatted: %s\nhere: %s"),
7006 buf, p);
7007 ++p;
7008 }
5b5596ff
PA
7009
7010 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7011 break;
7012
c8e38a49
PA
7013 /* fall through */
7014 case 'S': /* Old style status, just signal only. */
3a09da41
PA
7015 {
7016 int sig;
7017
7018 event->ws.kind = TARGET_WAITKIND_STOPPED;
7019 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7020 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7021 event->ws.value.sig = (enum gdb_signal) sig;
7022 else
7023 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7024 }
c8e38a49 7025 break;
65706a29
PA
7026 case 'w': /* Thread exited. */
7027 {
7028 char *p;
7029 ULONGEST value;
7030
7031 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7032 p = unpack_varlen_hex (&buf[1], &value);
7033 event->ws.value.integer = value;
7034 if (*p != ';')
7035 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 7036 event->ptid = read_ptid (++p, NULL);
65706a29
PA
7037 break;
7038 }
c8e38a49
PA
7039 case 'W': /* Target exited. */
7040 case 'X':
7041 {
7042 char *p;
7043 int pid;
7044 ULONGEST value;
82f73884 7045
c8e38a49
PA
7046 /* GDB used to accept only 2 hex chars here. Stubs should
7047 only send more if they detect GDB supports multi-process
7048 support. */
7049 p = unpack_varlen_hex (&buf[1], &value);
82f73884 7050
c8e38a49
PA
7051 if (buf[0] == 'W')
7052 {
7053 /* The remote process exited. */
74531fed
PA
7054 event->ws.kind = TARGET_WAITKIND_EXITED;
7055 event->ws.value.integer = value;
c8e38a49
PA
7056 }
7057 else
7058 {
7059 /* The remote process exited with a signal. */
74531fed 7060 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
7061 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7062 event->ws.value.sig = (enum gdb_signal) value;
7063 else
7064 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 7065 }
82f73884 7066
c8e38a49
PA
7067 /* If no process is specified, assume inferior_ptid. */
7068 pid = ptid_get_pid (inferior_ptid);
7069 if (*p == '\0')
7070 ;
7071 else if (*p == ';')
7072 {
7073 p++;
7074
0b24eb2d 7075 if (*p == '\0')
82f73884 7076 ;
61012eef 7077 else if (startswith (p, "process:"))
82f73884 7078 {
c8e38a49 7079 ULONGEST upid;
a744cf53 7080
c8e38a49
PA
7081 p += sizeof ("process:") - 1;
7082 unpack_varlen_hex (p, &upid);
7083 pid = upid;
82f73884
PA
7084 }
7085 else
7086 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 7087 }
c8e38a49
PA
7088 else
7089 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
7090 event->ptid = pid_to_ptid (pid);
7091 }
7092 break;
f2faf941
PA
7093 case 'N':
7094 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7095 event->ptid = minus_one_ptid;
7096 break;
74531fed
PA
7097 }
7098
6efcd9a8 7099 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
7100 error (_("No process or thread specified in stop reply: %s"), buf);
7101}
7102
722247f1
YQ
7103/* When the stub wants to tell GDB about a new notification reply, it
7104 sends a notification (%Stop, for example). Those can come it at
7105 any time, hence, we have to make sure that any pending
7106 putpkt/getpkt sequence we're making is finished, before querying
7107 the stub for more events with the corresponding ack command
7108 (vStopped, for example). E.g., if we started a vStopped sequence
7109 immediately upon receiving the notification, something like this
7110 could happen:
74531fed
PA
7111
7112 1.1) --> Hg 1
7113 1.2) <-- OK
7114 1.3) --> g
7115 1.4) <-- %Stop
7116 1.5) --> vStopped
7117 1.6) <-- (registers reply to step #1.3)
7118
7119 Obviously, the reply in step #1.6 would be unexpected to a vStopped
7120 query.
7121
796cb314 7122 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
7123 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7124 doing whatever we were doing:
7125
7126 2.1) --> Hg 1
7127 2.2) <-- OK
7128 2.3) --> g
7129 2.4) <-- %Stop
7130 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7131 2.5) <-- (registers reply to step #2.3)
7132
7133 Eventualy after step #2.5, we return to the event loop, which
7134 notices there's an event on the
7135 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7136 associated callback --- the function below. At this point, we're
7137 always safe to start a vStopped sequence. :
7138
7139 2.6) --> vStopped
7140 2.7) <-- T05 thread:2
7141 2.8) --> vStopped
7142 2.9) --> OK
7143*/
7144
722247f1
YQ
7145void
7146remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
7147{
7148 struct remote_state *rs = get_remote_state ();
74531fed 7149
f48ff2a7 7150 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 7151 {
722247f1
YQ
7152 if (notif_debug)
7153 fprintf_unfiltered (gdb_stdlog,
7154 "notif: process: '%s' ack pending event\n",
7155 nc->name);
74531fed 7156
722247f1 7157 /* acknowledge */
f48ff2a7
YQ
7158 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7159 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
7160
7161 while (1)
7162 {
7163 getpkt (&rs->buf, &rs->buf_size, 0);
7164 if (strcmp (rs->buf, "OK") == 0)
7165 break;
7166 else
722247f1 7167 remote_notif_ack (nc, rs->buf);
74531fed
PA
7168 }
7169 }
722247f1
YQ
7170 else
7171 {
7172 if (notif_debug)
7173 fprintf_unfiltered (gdb_stdlog,
7174 "notif: process: '%s' no pending reply\n",
7175 nc->name);
7176 }
74531fed
PA
7177}
7178
74531fed
PA
7179/* Called when it is decided that STOP_REPLY holds the info of the
7180 event that is to be returned to the core. This function always
7181 destroys STOP_REPLY. */
7182
7183static ptid_t
7184process_stop_reply (struct stop_reply *stop_reply,
7185 struct target_waitstatus *status)
7186{
7187 ptid_t ptid;
7188
7189 *status = stop_reply->ws;
7190 ptid = stop_reply->ptid;
7191
7192 /* If no thread/process was reported by the stub, assume the current
7193 inferior. */
7194 if (ptid_equal (ptid, null_ptid))
7195 ptid = inferior_ptid;
7196
5f3563ea 7197 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
7198 && status->kind != TARGET_WAITKIND_SIGNALLED
7199 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 7200 {
799a2abe 7201 struct private_thread_info *remote_thr;
ee154bee 7202
5f3563ea
PA
7203 /* Expedited registers. */
7204 if (stop_reply->regcache)
7205 {
217f1f79 7206 struct regcache *regcache
f5656ead 7207 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
7208 cached_reg_t *reg;
7209 int ix;
7210
7211 for (ix = 0;
7212 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
7213 ix++)
217f1f79 7214 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
7215 VEC_free (cached_reg_t, stop_reply->regcache);
7216 }
74531fed 7217
1941c569 7218 remote_notice_new_inferior (ptid, 0);
85ad3aaf 7219 remote_thr = get_private_info_ptid (ptid);
799a2abe
PA
7220 remote_thr->core = stop_reply->core;
7221 remote_thr->stop_reason = stop_reply->stop_reason;
7222 remote_thr->watch_data_address = stop_reply->watch_data_address;
85ad3aaf 7223 remote_thr->vcont_resumed = 0;
74531fed
PA
7224 }
7225
74531fed
PA
7226 stop_reply_xfree (stop_reply);
7227 return ptid;
7228}
7229
7230/* The non-stop mode version of target_wait. */
7231
7232static ptid_t
47608cb1 7233remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7234{
7235 struct remote_state *rs = get_remote_state ();
74531fed
PA
7236 struct stop_reply *stop_reply;
7237 int ret;
fee9eda9 7238 int is_notif = 0;
74531fed
PA
7239
7240 /* If in non-stop mode, get out of getpkt even if a
7241 notification is received. */
7242
7243 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7244 0 /* forever */, &is_notif);
74531fed
PA
7245 while (1)
7246 {
fee9eda9 7247 if (ret != -1 && !is_notif)
74531fed
PA
7248 switch (rs->buf[0])
7249 {
7250 case 'E': /* Error of some sort. */
7251 /* We're out of sync with the target now. Did it continue
7252 or not? We can't tell which thread it was in non-stop,
7253 so just ignore this. */
7254 warning (_("Remote failure reply: %s"), rs->buf);
7255 break;
7256 case 'O': /* Console output. */
7257 remote_console_output (rs->buf + 1);
7258 break;
7259 default:
7260 warning (_("Invalid remote reply: %s"), rs->buf);
7261 break;
7262 }
7263
7264 /* Acknowledge a pending stop reply that may have arrived in the
7265 mean time. */
f48ff2a7 7266 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 7267 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
7268
7269 /* If indeed we noticed a stop reply, we're done. */
7270 stop_reply = queued_stop_reply (ptid);
7271 if (stop_reply != NULL)
7272 return process_stop_reply (stop_reply, status);
7273
47608cb1 7274 /* Still no event. If we're just polling for an event, then
74531fed 7275 return to the event loop. */
47608cb1 7276 if (options & TARGET_WNOHANG)
74531fed
PA
7277 {
7278 status->kind = TARGET_WAITKIND_IGNORE;
7279 return minus_one_ptid;
7280 }
7281
47608cb1 7282 /* Otherwise do a blocking wait. */
74531fed 7283 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 7284 1 /* forever */, &is_notif);
74531fed
PA
7285 }
7286}
7287
7288/* Wait until the remote machine stops, then return, storing status in
7289 STATUS just as `wait' would. */
7290
7291static ptid_t
47608cb1 7292remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
7293{
7294 struct remote_state *rs = get_remote_state ();
74531fed 7295 ptid_t event_ptid = null_ptid;
cea39f65 7296 char *buf;
74531fed
PA
7297 struct stop_reply *stop_reply;
7298
47608cb1
PA
7299 again:
7300
74531fed
PA
7301 status->kind = TARGET_WAITKIND_IGNORE;
7302 status->value.integer = 0;
7303
7304 stop_reply = queued_stop_reply (ptid);
7305 if (stop_reply != NULL)
7306 return process_stop_reply (stop_reply, status);
7307
7308 if (rs->cached_wait_status)
7309 /* Use the cached wait status, but only once. */
7310 rs->cached_wait_status = 0;
7311 else
7312 {
7313 int ret;
722247f1 7314 int is_notif;
567420d1
PA
7315 int forever = ((options & TARGET_WNOHANG) == 0
7316 && wait_forever_enabled_p);
7317
7318 if (!rs->waiting_for_stop_reply)
7319 {
7320 status->kind = TARGET_WAITKIND_NO_RESUMED;
7321 return minus_one_ptid;
7322 }
74531fed 7323
74531fed
PA
7324 /* FIXME: cagney/1999-09-27: If we're in async mode we should
7325 _never_ wait for ever -> test on target_is_async_p().
7326 However, before we do that we need to ensure that the caller
7327 knows how to take the target into/out of async mode. */
722247f1 7328 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 7329 forever, &is_notif);
722247f1
YQ
7330
7331 /* GDB gets a notification. Return to core as this event is
7332 not interesting. */
7333 if (ret != -1 && is_notif)
7334 return minus_one_ptid;
567420d1
PA
7335
7336 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7337 return minus_one_ptid;
74531fed
PA
7338 }
7339
7340 buf = rs->buf;
7341
3a29589a
DJ
7342 /* Assume that the target has acknowledged Ctrl-C unless we receive
7343 an 'F' or 'O' packet. */
7344 if (buf[0] != 'F' && buf[0] != 'O')
7345 rs->ctrlc_pending_p = 0;
7346
74531fed
PA
7347 switch (buf[0])
7348 {
7349 case 'E': /* Error of some sort. */
7350 /* We're out of sync with the target now. Did it continue or
7351 not? Not is more likely, so report a stop. */
29090fb6
LM
7352 rs->waiting_for_stop_reply = 0;
7353
74531fed
PA
7354 warning (_("Remote failure reply: %s"), buf);
7355 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7356 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7357 break;
7358 case 'F': /* File-I/O request. */
e42e5352
YQ
7359 /* GDB may access the inferior memory while handling the File-I/O
7360 request, but we don't want GDB accessing memory while waiting
7361 for a stop reply. See the comments in putpkt_binary. Set
7362 waiting_for_stop_reply to 0 temporarily. */
7363 rs->waiting_for_stop_reply = 0;
3a29589a
DJ
7364 remote_fileio_request (buf, rs->ctrlc_pending_p);
7365 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7366 /* GDB handled the File-I/O request, and the target is running
7367 again. Keep waiting for events. */
7368 rs->waiting_for_stop_reply = 1;
74531fed 7369 break;
f2faf941 7370 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7371 {
29090fb6
LM
7372 struct stop_reply *stop_reply;
7373
7374 /* There is a stop reply to handle. */
7375 rs->waiting_for_stop_reply = 0;
7376
7377 stop_reply
722247f1
YQ
7378 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7379 rs->buf);
74531fed 7380
74531fed 7381 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7382 break;
7383 }
7384 case 'O': /* Console output. */
7385 remote_console_output (buf + 1);
c8e38a49
PA
7386 break;
7387 case '\0':
b73be471 7388 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7389 {
7390 /* Zero length reply means that we tried 'S' or 'C' and the
7391 remote system doesn't support it. */
7392 target_terminal_ours_for_output ();
7393 printf_filtered
7394 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7395 gdb_signal_to_name (rs->last_sent_signal));
7396 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
7397 target_terminal_inferior ();
7398
f5c4fcd9
TT
7399 strcpy (buf, rs->last_sent_step ? "s" : "c");
7400 putpkt (buf);
c8e38a49 7401 break;
43ff13b4 7402 }
c8e38a49
PA
7403 /* else fallthrough */
7404 default:
7405 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7406 break;
43ff13b4 7407 }
c8e38a49 7408
f2faf941
PA
7409 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7410 return minus_one_ptid;
7411 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7412 {
7413 /* Nothing interesting happened. If we're doing a non-blocking
7414 poll, we're done. Otherwise, go back to waiting. */
7415 if (options & TARGET_WNOHANG)
7416 return minus_one_ptid;
7417 else
7418 goto again;
7419 }
74531fed
PA
7420 else if (status->kind != TARGET_WAITKIND_EXITED
7421 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7422 {
7423 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7424 record_currthread (rs, event_ptid);
82f73884
PA
7425 else
7426 event_ptid = inferior_ptid;
43ff13b4 7427 }
74531fed
PA
7428 else
7429 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7430 record_currthread (rs, minus_one_ptid);
79d7f229 7431
82f73884 7432 return event_ptid;
43ff13b4
JM
7433}
7434
74531fed
PA
7435/* Wait until the remote machine stops, then return, storing status in
7436 STATUS just as `wait' would. */
7437
c8e38a49 7438static ptid_t
117de6a9 7439remote_wait (struct target_ops *ops,
47608cb1 7440 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7441{
7442 ptid_t event_ptid;
7443
6efcd9a8 7444 if (target_is_non_stop_p ())
47608cb1 7445 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7446 else
47608cb1 7447 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7448
d9d41e78 7449 if (target_is_async_p ())
c8e38a49 7450 {
74531fed
PA
7451 /* If there are are events left in the queue tell the event loop
7452 to return here. */
722247f1 7453 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7454 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7455 }
c8e38a49
PA
7456
7457 return event_ptid;
7458}
7459
74ca34ce 7460/* Fetch a single register using a 'p' packet. */
c906108c 7461
b96ec7ac 7462static int
56be3814 7463fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
7464{
7465 struct remote_state *rs = get_remote_state ();
2e9f7625 7466 char *buf, *p;
b96ec7ac
AC
7467 char regp[MAX_REGISTER_SIZE];
7468 int i;
7469
4082afcc 7470 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7471 return 0;
7472
7473 if (reg->pnum == -1)
7474 return 0;
7475
2e9f7625 7476 p = rs->buf;
fcad0fa4 7477 *p++ = 'p';
74ca34ce 7478 p += hexnumstr (p, reg->pnum);
fcad0fa4 7479 *p++ = '\0';
1f4437a4
MS
7480 putpkt (rs->buf);
7481 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7482
2e9f7625
DJ
7483 buf = rs->buf;
7484
74ca34ce
DJ
7485 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7486 {
7487 case PACKET_OK:
7488 break;
7489 case PACKET_UNKNOWN:
7490 return 0;
7491 case PACKET_ERROR:
27a9c0bf
MS
7492 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7493 gdbarch_register_name (get_regcache_arch (regcache),
7494 reg->regnum),
7495 buf);
74ca34ce 7496 }
3f9a994c
JB
7497
7498 /* If this register is unfetchable, tell the regcache. */
7499 if (buf[0] == 'x')
8480adf2 7500 {
56be3814 7501 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7502 return 1;
b96ec7ac 7503 }
b96ec7ac 7504
3f9a994c
JB
7505 /* Otherwise, parse and supply the value. */
7506 p = buf;
7507 i = 0;
7508 while (p[0] != 0)
7509 {
7510 if (p[1] == 0)
74ca34ce 7511 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7512
7513 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7514 p += 2;
7515 }
56be3814 7516 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7517 return 1;
b96ec7ac
AC
7518}
7519
74ca34ce
DJ
7520/* Fetch the registers included in the target's 'g' packet. */
7521
29709017
DJ
7522static int
7523send_g_packet (void)
c906108c 7524{
d01949b6 7525 struct remote_state *rs = get_remote_state ();
cea39f65 7526 int buf_len;
c906108c 7527
bba74b36 7528 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7529 remote_send (&rs->buf, &rs->buf_size);
c906108c 7530
29709017
DJ
7531 /* We can get out of synch in various cases. If the first character
7532 in the buffer is not a hex character, assume that has happened
7533 and try to fetch another packet to read. */
7534 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7535 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7536 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7537 && rs->buf[0] != 'x') /* New: unavailable register value. */
7538 {
7539 if (remote_debug)
7540 fprintf_unfiltered (gdb_stdlog,
7541 "Bad register packet; fetching a new packet\n");
7542 getpkt (&rs->buf, &rs->buf_size, 0);
7543 }
7544
74ca34ce
DJ
7545 buf_len = strlen (rs->buf);
7546
7547 /* Sanity check the received packet. */
7548 if (buf_len % 2 != 0)
7549 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7550
7551 return buf_len / 2;
7552}
7553
7554static void
56be3814 7555process_g_packet (struct regcache *regcache)
29709017 7556{
4a22f64d 7557 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7558 struct remote_state *rs = get_remote_state ();
7559 struct remote_arch_state *rsa = get_remote_arch_state ();
7560 int i, buf_len;
7561 char *p;
7562 char *regs;
7563
7564 buf_len = strlen (rs->buf);
7565
7566 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7567 if (buf_len > 2 * rsa->sizeof_g_packet)
7568 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7569
7570 /* Save the size of the packet sent to us by the target. It is used
7571 as a heuristic when determining the max size of packets that the
7572 target can safely receive. */
7573 if (rsa->actual_register_packet_size == 0)
7574 rsa->actual_register_packet_size = buf_len;
7575
7576 /* If this is smaller than we guessed the 'g' packet would be,
7577 update our records. A 'g' reply that doesn't include a register's
7578 value implies either that the register is not available, or that
7579 the 'p' packet must be used. */
7580 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7581 {
74ca34ce
DJ
7582 rsa->sizeof_g_packet = buf_len / 2;
7583
4a22f64d 7584 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7585 {
74ca34ce
DJ
7586 if (rsa->regs[i].pnum == -1)
7587 continue;
7588
7589 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7590 rsa->regs[i].in_g_packet = 0;
b96ec7ac 7591 else
74ca34ce 7592 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7593 }
74ca34ce 7594 }
b323314b 7595
224c3ddb 7596 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7597
7598 /* Unimplemented registers read as all bits zero. */
ea9c271d 7599 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7600
c906108c
SS
7601 /* Reply describes registers byte by byte, each byte encoded as two
7602 hex characters. Suck them all up, then supply them to the
7603 register cacheing/storage mechanism. */
7604
74ca34ce 7605 p = rs->buf;
ea9c271d 7606 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7607 {
74ca34ce
DJ
7608 if (p[0] == 0 || p[1] == 0)
7609 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7610 internal_error (__FILE__, __LINE__,
9b20d036 7611 _("unexpected end of 'g' packet reply"));
74ca34ce 7612
c906108c 7613 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7614 regs[i] = 0; /* 'x' */
c906108c
SS
7615 else
7616 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7617 p += 2;
7618 }
7619
a744cf53
MS
7620 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7621 {
7622 struct packet_reg *r = &rsa->regs[i];
7623
7624 if (r->in_g_packet)
7625 {
7626 if (r->offset * 2 >= strlen (rs->buf))
7627 /* This shouldn't happen - we adjusted in_g_packet above. */
7628 internal_error (__FILE__, __LINE__,
9b20d036 7629 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7630 else if (rs->buf[r->offset * 2] == 'x')
7631 {
7632 gdb_assert (r->offset * 2 < strlen (rs->buf));
7633 /* The register isn't available, mark it as such (at
7634 the same time setting the value to zero). */
7635 regcache_raw_supply (regcache, r->regnum, NULL);
7636 }
7637 else
7638 regcache_raw_supply (regcache, r->regnum,
7639 regs + r->offset);
7640 }
7641 }
c906108c
SS
7642}
7643
29709017 7644static void
56be3814 7645fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7646{
7647 send_g_packet ();
56be3814 7648 process_g_packet (regcache);
29709017
DJ
7649}
7650
e6e4e701
PA
7651/* Make the remote selected traceframe match GDB's selected
7652 traceframe. */
7653
7654static void
7655set_remote_traceframe (void)
7656{
7657 int newnum;
262e1174 7658 struct remote_state *rs = get_remote_state ();
e6e4e701 7659
262e1174 7660 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7661 return;
7662
7663 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7664 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7665
7666 newnum = target_trace_find (tfind_number,
7667 get_traceframe_number (), 0, 0, NULL);
7668
7669 /* Should not happen. If it does, all bets are off. */
7670 if (newnum != get_traceframe_number ())
7671 warning (_("could not set remote traceframe"));
7672}
7673
74ca34ce 7674static void
28439f5e
PA
7675remote_fetch_registers (struct target_ops *ops,
7676 struct regcache *regcache, int regnum)
74ca34ce 7677{
74ca34ce
DJ
7678 struct remote_arch_state *rsa = get_remote_arch_state ();
7679 int i;
7680
e6e4e701 7681 set_remote_traceframe ();
79d7f229 7682 set_general_thread (inferior_ptid);
74ca34ce
DJ
7683
7684 if (regnum >= 0)
7685 {
7686 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7687
74ca34ce
DJ
7688 gdb_assert (reg != NULL);
7689
7690 /* If this register might be in the 'g' packet, try that first -
7691 we are likely to read more than one register. If this is the
7692 first 'g' packet, we might be overly optimistic about its
7693 contents, so fall back to 'p'. */
7694 if (reg->in_g_packet)
7695 {
56be3814 7696 fetch_registers_using_g (regcache);
74ca34ce
DJ
7697 if (reg->in_g_packet)
7698 return;
7699 }
7700
56be3814 7701 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7702 return;
7703
7704 /* This register is not available. */
56be3814 7705 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7706
7707 return;
7708 }
7709
56be3814 7710 fetch_registers_using_g (regcache);
74ca34ce 7711
4a22f64d 7712 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7713 if (!rsa->regs[i].in_g_packet)
56be3814 7714 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7715 {
7716 /* This register is not available. */
56be3814 7717 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7718 }
7719}
7720
c906108c
SS
7721/* Prepare to store registers. Since we may send them all (using a
7722 'G' request), we have to read out the ones we don't want to change
7723 first. */
7724
c5aa993b 7725static void
f32dbf8c 7726remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7727{
ea9c271d 7728 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7729 int i;
cfd77fa1 7730 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7731
c906108c 7732 /* Make sure the entire registers array is valid. */
4082afcc 7733 switch (packet_support (PACKET_P))
5a2468f5
JM
7734 {
7735 case PACKET_DISABLE:
7736 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7737 /* Make sure all the necessary registers are cached. */
4a22f64d 7738 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7739 if (rsa->regs[i].in_g_packet)
316f2060 7740 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7741 break;
7742 case PACKET_ENABLE:
7743 break;
7744 }
7745}
7746
ad10f812 7747/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7748 packet was not recognized. */
5a2468f5
JM
7749
7750static int
1f4437a4
MS
7751store_register_using_P (const struct regcache *regcache,
7752 struct packet_reg *reg)
5a2468f5 7753{
4a22f64d 7754 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7755 struct remote_state *rs = get_remote_state ();
5a2468f5 7756 /* Try storing a single register. */
6d820c5c 7757 char *buf = rs->buf;
cfd77fa1 7758 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7759 char *p;
5a2468f5 7760
4082afcc 7761 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7762 return 0;
7763
7764 if (reg->pnum == -1)
7765 return 0;
7766
ea9c271d 7767 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7768 p = buf + strlen (buf);
56be3814 7769 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7770 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7771 putpkt (rs->buf);
7772 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7773
74ca34ce
DJ
7774 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7775 {
7776 case PACKET_OK:
7777 return 1;
7778 case PACKET_ERROR:
27a9c0bf
MS
7779 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7780 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7781 case PACKET_UNKNOWN:
7782 return 0;
7783 default:
7784 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7785 }
c906108c
SS
7786}
7787
23860348
MS
7788/* Store register REGNUM, or all registers if REGNUM == -1, from the
7789 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7790
7791static void
56be3814 7792store_registers_using_G (const struct regcache *regcache)
c906108c 7793{
d01949b6 7794 struct remote_state *rs = get_remote_state ();
ea9c271d 7795 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7796 gdb_byte *regs;
c906108c
SS
7797 char *p;
7798
193cb69f
AC
7799 /* Extract all the registers in the regcache copying them into a
7800 local buffer. */
7801 {
b323314b 7802 int i;
a744cf53 7803
224c3ddb 7804 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7805 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7806 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7807 {
ea9c271d 7808 struct packet_reg *r = &rsa->regs[i];
a744cf53 7809
b323314b 7810 if (r->in_g_packet)
56be3814 7811 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7812 }
7813 }
c906108c
SS
7814
7815 /* Command describes registers byte by byte,
7816 each byte encoded as two hex characters. */
6d820c5c 7817 p = rs->buf;
193cb69f 7818 *p++ = 'G';
74ca34ce
DJ
7819 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7820 updated. */
7821 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7822 putpkt (rs->buf);
7823 getpkt (&rs->buf, &rs->buf_size, 0);
7824 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7825 error (_("Could not write registers; remote failure reply '%s'"),
7826 rs->buf);
c906108c 7827}
74ca34ce
DJ
7828
7829/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7830 of the register cache buffer. FIXME: ignores errors. */
7831
7832static void
28439f5e
PA
7833remote_store_registers (struct target_ops *ops,
7834 struct regcache *regcache, int regnum)
74ca34ce 7835{
74ca34ce
DJ
7836 struct remote_arch_state *rsa = get_remote_arch_state ();
7837 int i;
7838
e6e4e701 7839 set_remote_traceframe ();
79d7f229 7840 set_general_thread (inferior_ptid);
74ca34ce
DJ
7841
7842 if (regnum >= 0)
7843 {
7844 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7845
74ca34ce
DJ
7846 gdb_assert (reg != NULL);
7847
7848 /* Always prefer to store registers using the 'P' packet if
7849 possible; we often change only a small number of registers.
7850 Sometimes we change a larger number; we'd need help from a
7851 higher layer to know to use 'G'. */
56be3814 7852 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7853 return;
7854
7855 /* For now, don't complain if we have no way to write the
7856 register. GDB loses track of unavailable registers too
7857 easily. Some day, this may be an error. We don't have
0df8b418 7858 any way to read the register, either... */
74ca34ce
DJ
7859 if (!reg->in_g_packet)
7860 return;
7861
56be3814 7862 store_registers_using_G (regcache);
74ca34ce
DJ
7863 return;
7864 }
7865
56be3814 7866 store_registers_using_G (regcache);
74ca34ce 7867
4a22f64d 7868 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7869 if (!rsa->regs[i].in_g_packet)
56be3814 7870 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7871 /* See above for why we do not issue an error here. */
7872 continue;
7873}
c906108c
SS
7874\f
7875
7876/* Return the number of hex digits in num. */
7877
7878static int
fba45db2 7879hexnumlen (ULONGEST num)
c906108c
SS
7880{
7881 int i;
7882
7883 for (i = 0; num != 0; i++)
7884 num >>= 4;
7885
325fac50 7886 return std::max (i, 1);
c906108c
SS
7887}
7888
2df3850c 7889/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7890
7891static int
fba45db2 7892hexnumstr (char *buf, ULONGEST num)
c906108c 7893{
c906108c 7894 int len = hexnumlen (num);
a744cf53 7895
2df3850c
JM
7896 return hexnumnstr (buf, num, len);
7897}
7898
c906108c 7899
2df3850c 7900/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7901
2df3850c 7902static int
fba45db2 7903hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7904{
7905 int i;
7906
7907 buf[width] = '\0';
7908
7909 for (i = width - 1; i >= 0; i--)
c906108c 7910 {
c5aa993b 7911 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7912 num >>= 4;
7913 }
7914
2df3850c 7915 return width;
c906108c
SS
7916}
7917
23860348 7918/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7919
7920static CORE_ADDR
fba45db2 7921remote_address_masked (CORE_ADDR addr)
c906108c 7922{
883b9c6c 7923 unsigned int address_size = remote_address_size;
a744cf53 7924
911c95a5
UW
7925 /* If "remoteaddresssize" was not set, default to target address size. */
7926 if (!address_size)
f5656ead 7927 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7928
7929 if (address_size > 0
7930 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7931 {
7932 /* Only create a mask when that mask can safely be constructed
23860348 7933 in a ULONGEST variable. */
c906108c 7934 ULONGEST mask = 1;
a744cf53 7935
911c95a5 7936 mask = (mask << address_size) - 1;
c906108c
SS
7937 addr &= mask;
7938 }
7939 return addr;
7940}
7941
7942/* Determine whether the remote target supports binary downloading.
7943 This is accomplished by sending a no-op memory write of zero length
7944 to the target at the specified address. It does not suffice to send
23860348
MS
7945 the whole packet, since many stubs strip the eighth bit and
7946 subsequently compute a wrong checksum, which causes real havoc with
7947 remote_write_bytes.
7a292a7a 7948
96baa820 7949 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7950 clean. In cases like this, the user should clear "remote
23860348 7951 X-packet". */
96baa820 7952
c906108c 7953static void
fba45db2 7954check_binary_download (CORE_ADDR addr)
c906108c 7955{
d01949b6 7956 struct remote_state *rs = get_remote_state ();
24b06219 7957
4082afcc 7958 switch (packet_support (PACKET_X))
c906108c 7959 {
96baa820
JM
7960 case PACKET_DISABLE:
7961 break;
7962 case PACKET_ENABLE:
7963 break;
7964 case PACKET_SUPPORT_UNKNOWN:
7965 {
96baa820 7966 char *p;
802188a7 7967
2e9f7625 7968 p = rs->buf;
96baa820
JM
7969 *p++ = 'X';
7970 p += hexnumstr (p, (ULONGEST) addr);
7971 *p++ = ',';
7972 p += hexnumstr (p, (ULONGEST) 0);
7973 *p++ = ':';
7974 *p = '\0';
802188a7 7975
2e9f7625 7976 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7977 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7978
2e9f7625 7979 if (rs->buf[0] == '\0')
96baa820
JM
7980 {
7981 if (remote_debug)
7982 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7983 "binary downloading NOT "
7984 "supported by target\n");
444abaca 7985 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7986 }
7987 else
7988 {
7989 if (remote_debug)
7990 fprintf_unfiltered (gdb_stdlog,
64b9b334 7991 "binary downloading supported by target\n");
444abaca 7992 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7993 }
7994 break;
7995 }
c906108c
SS
7996 }
7997}
7998
124e13d9
SM
7999/* Helper function to resize the payload in order to try to get a good
8000 alignment. We try to write an amount of data such that the next write will
8001 start on an address aligned on REMOTE_ALIGN_WRITES. */
8002
8003static int
8004align_for_efficient_write (int todo, CORE_ADDR memaddr)
8005{
8006 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8007}
8008
c906108c
SS
8009/* Write memory data directly to the remote machine.
8010 This does not inform the data cache; the data cache uses this.
a76d924d 8011 HEADER is the starting part of the packet.
c906108c
SS
8012 MEMADDR is the address in the remote memory space.
8013 MYADDR is the address of the buffer in our space.
124e13d9
SM
8014 LEN_UNITS is the number of addressable units to write.
8015 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
8016 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8017 should send data as binary ('X'), or hex-encoded ('M').
8018
8019 The function creates packet of the form
8020 <HEADER><ADDRESS>,<LENGTH>:<DATA>
8021
124e13d9 8022 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
8023
8024 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8025 are omitted.
8026
9b409511 8027 Return the transferred status, error or OK (an
124e13d9
SM
8028 'enum target_xfer_status' value). Save the number of addressable units
8029 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
8030
8031 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8032 exchange between gdb and the stub could look like (?? in place of the
8033 checksum):
8034
8035 -> $m1000,4#??
8036 <- aaaabbbbccccdddd
8037
8038 -> $M1000,3:eeeeffffeeee#??
8039 <- OK
8040
8041 -> $m1000,4#??
8042 <- eeeeffffeeeedddd */
c906108c 8043
9b409511 8044static enum target_xfer_status
a76d924d 8045remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
8046 const gdb_byte *myaddr, ULONGEST len_units,
8047 int unit_size, ULONGEST *xfered_len_units,
8048 char packet_format, int use_length)
c906108c 8049{
6d820c5c 8050 struct remote_state *rs = get_remote_state ();
cfd77fa1 8051 char *p;
a76d924d
DJ
8052 char *plen = NULL;
8053 int plenlen = 0;
124e13d9
SM
8054 int todo_units;
8055 int units_written;
8056 int payload_capacity_bytes;
8057 int payload_length_bytes;
a76d924d
DJ
8058
8059 if (packet_format != 'X' && packet_format != 'M')
8060 internal_error (__FILE__, __LINE__,
9b20d036 8061 _("remote_write_bytes_aux: bad packet format"));
c906108c 8062
124e13d9 8063 if (len_units == 0)
9b409511 8064 return TARGET_XFER_EOF;
b2182ed2 8065
124e13d9 8066 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 8067
6d820c5c
DJ
8068 /* The packet buffer will be large enough for the payload;
8069 get_memory_packet_size ensures this. */
a76d924d 8070 rs->buf[0] = '\0';
c906108c 8071
a257b5bb 8072 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
8073 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
8074
124e13d9 8075 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 8076 if (!use_length)
0df8b418 8077 /* The comma won't be used. */
124e13d9
SM
8078 payload_capacity_bytes += 1;
8079 payload_capacity_bytes -= strlen (header);
8080 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 8081
a76d924d 8082 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 8083
a76d924d
DJ
8084 strcat (rs->buf, header);
8085 p = rs->buf + strlen (header);
8086
8087 /* Compute a best guess of the number of bytes actually transfered. */
8088 if (packet_format == 'X')
c906108c 8089 {
23860348 8090 /* Best guess at number of bytes that will fit. */
325fac50
PA
8091 todo_units = std::min (len_units,
8092 (ULONGEST) payload_capacity_bytes / unit_size);
a76d924d 8093 if (use_length)
124e13d9 8094 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50 8095 todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
8096 }
8097 else
8098 {
124e13d9 8099 /* Number of bytes that will fit. */
325fac50
PA
8100 todo_units
8101 = std::min (len_units,
8102 (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
a76d924d 8103 if (use_length)
124e13d9 8104 payload_capacity_bytes -= hexnumlen (todo_units);
325fac50
PA
8105 todo_units = std::min (todo_units,
8106 (payload_capacity_bytes / unit_size) / 2);
917317f4 8107 }
a76d924d 8108
124e13d9 8109 if (todo_units <= 0)
3de11b2e 8110 internal_error (__FILE__, __LINE__,
405f8e94 8111 _("minimum packet size too small to write data"));
802188a7 8112
6765f3e5
DJ
8113 /* If we already need another packet, then try to align the end
8114 of this packet to a useful boundary. */
124e13d9
SM
8115 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8116 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 8117
a257b5bb 8118 /* Append "<memaddr>". */
917317f4
JM
8119 memaddr = remote_address_masked (memaddr);
8120 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 8121
a76d924d
DJ
8122 if (use_length)
8123 {
8124 /* Append ",". */
8125 *p++ = ',';
802188a7 8126
124e13d9
SM
8127 /* Append the length and retain its location and size. It may need to be
8128 adjusted once the packet body has been created. */
a76d924d 8129 plen = p;
124e13d9 8130 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
8131 p += plenlen;
8132 }
a257b5bb
AC
8133
8134 /* Append ":". */
917317f4
JM
8135 *p++ = ':';
8136 *p = '\0';
802188a7 8137
a257b5bb 8138 /* Append the packet body. */
a76d924d 8139 if (packet_format == 'X')
917317f4 8140 {
917317f4
JM
8141 /* Binary mode. Send target system values byte by byte, in
8142 increasing byte addresses. Only escape certain critical
8143 characters. */
124e13d9
SM
8144 payload_length_bytes =
8145 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8146 &units_written, payload_capacity_bytes);
6765f3e5 8147
124e13d9 8148 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
8149 a second try to keep the end of the packet aligned. Don't do
8150 this if the packet is tiny. */
124e13d9 8151 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 8152 {
124e13d9
SM
8153 int new_todo_units;
8154
8155 new_todo_units = align_for_efficient_write (units_written, memaddr);
8156
8157 if (new_todo_units != units_written)
8158 payload_length_bytes =
8159 remote_escape_output (myaddr, new_todo_units, unit_size,
8160 (gdb_byte *) p, &units_written,
8161 payload_capacity_bytes);
6765f3e5
DJ
8162 }
8163
124e13d9
SM
8164 p += payload_length_bytes;
8165 if (use_length && units_written < todo_units)
c906108c 8166 {
802188a7 8167 /* Escape chars have filled up the buffer prematurely,
124e13d9 8168 and we have actually sent fewer units than planned.
917317f4
JM
8169 Fix-up the length field of the packet. Use the same
8170 number of characters as before. */
124e13d9
SM
8171 plen += hexnumnstr (plen, (ULONGEST) units_written,
8172 plenlen);
917317f4 8173 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 8174 }
a76d924d
DJ
8175 }
8176 else
8177 {
917317f4
JM
8178 /* Normal mode: Send target system values byte by byte, in
8179 increasing byte addresses. Each byte is encoded as a two hex
8180 value. */
124e13d9
SM
8181 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8182 units_written = todo_units;
c906108c 8183 }
802188a7 8184
2e9f7625 8185 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 8186 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 8187
2e9f7625 8188 if (rs->buf[0] == 'E')
00d84524 8189 return TARGET_XFER_E_IO;
802188a7 8190
124e13d9
SM
8191 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8192 send fewer units than we'd planned. */
8193 *xfered_len_units = (ULONGEST) units_written;
9b409511 8194 return TARGET_XFER_OK;
c906108c
SS
8195}
8196
a76d924d
DJ
8197/* Write memory data directly to the remote machine.
8198 This does not inform the data cache; the data cache uses this.
8199 MEMADDR is the address in the remote memory space.
8200 MYADDR is the address of the buffer in our space.
8201 LEN is the number of bytes.
8202
9b409511
YQ
8203 Return the transferred status, error or OK (an
8204 'enum target_xfer_status' value). Save the number of bytes
8205 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 8206
9b409511
YQ
8207static enum target_xfer_status
8208remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 8209 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
8210{
8211 char *packet_format = 0;
8212
8213 /* Check whether the target supports binary download. */
8214 check_binary_download (memaddr);
8215
4082afcc 8216 switch (packet_support (PACKET_X))
a76d924d
DJ
8217 {
8218 case PACKET_ENABLE:
8219 packet_format = "X";
8220 break;
8221 case PACKET_DISABLE:
8222 packet_format = "M";
8223 break;
8224 case PACKET_SUPPORT_UNKNOWN:
8225 internal_error (__FILE__, __LINE__,
8226 _("remote_write_bytes: bad internal state"));
8227 default:
8228 internal_error (__FILE__, __LINE__, _("bad switch"));
8229 }
8230
8231 return remote_write_bytes_aux (packet_format,
124e13d9 8232 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 8233 packet_format[0], 1);
a76d924d
DJ
8234}
8235
9217e74e
YQ
8236/* Read memory data directly from the remote machine.
8237 This does not use the data cache; the data cache uses this.
8238 MEMADDR is the address in the remote memory space.
8239 MYADDR is the address of the buffer in our space.
124e13d9
SM
8240 LEN_UNITS is the number of addressable memory units to read..
8241 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
8242
8243 Return the transferred status, error or OK (an
8244 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
8245 transferred in *XFERED_LEN_UNITS.
8246
8247 See the comment of remote_write_bytes_aux for an example of
8248 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
8249
8250static enum target_xfer_status
124e13d9
SM
8251remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8252 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
8253{
8254 struct remote_state *rs = get_remote_state ();
124e13d9 8255 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 8256 char *p;
124e13d9
SM
8257 int todo_units;
8258 int decoded_bytes;
9217e74e 8259
124e13d9 8260 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
8261 /* The packet buffer will be large enough for the payload;
8262 get_memory_packet_size ensures this. */
8263
124e13d9 8264 /* Number of units that will fit. */
325fac50
PA
8265 todo_units = std::min (len_units,
8266 (ULONGEST) (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
8267
8268 /* Construct "m"<memaddr>","<len>". */
8269 memaddr = remote_address_masked (memaddr);
8270 p = rs->buf;
8271 *p++ = 'm';
8272 p += hexnumstr (p, (ULONGEST) memaddr);
8273 *p++ = ',';
124e13d9 8274 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
8275 *p = '\0';
8276 putpkt (rs->buf);
8277 getpkt (&rs->buf, &rs->buf_size, 0);
8278 if (rs->buf[0] == 'E'
8279 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8280 && rs->buf[3] == '\0')
8281 return TARGET_XFER_E_IO;
8282 /* Reply describes memory byte by byte, each byte encoded as two hex
8283 characters. */
8284 p = rs->buf;
124e13d9 8285 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 8286 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 8287 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
8288 return TARGET_XFER_OK;
8289}
8290
b55fbac4
YQ
8291/* Using the set of read-only target sections of remote, read live
8292 read-only memory.
8acf9577
YQ
8293
8294 For interface/parameters/return description see target.h,
8295 to_xfer_partial. */
8296
8297static enum target_xfer_status
b55fbac4
YQ
8298remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8299 ULONGEST memaddr, ULONGEST len,
124e13d9 8300 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
8301{
8302 struct target_section *secp;
8303 struct target_section_table *table;
8304
8305 secp = target_section_by_addr (ops, memaddr);
8306 if (secp != NULL
8307 && (bfd_get_section_flags (secp->the_bfd_section->owner,
8308 secp->the_bfd_section)
8309 & SEC_READONLY))
8310 {
8311 struct target_section *p;
8312 ULONGEST memend = memaddr + len;
8313
8314 table = target_get_section_table (ops);
8315
8316 for (p = table->sections; p < table->sections_end; p++)
8317 {
8318 if (memaddr >= p->addr)
8319 {
8320 if (memend <= p->endaddr)
8321 {
8322 /* Entire transfer is within this section. */
124e13d9 8323 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8324 xfered_len);
8acf9577
YQ
8325 }
8326 else if (memaddr >= p->endaddr)
8327 {
8328 /* This section ends before the transfer starts. */
8329 continue;
8330 }
8331 else
8332 {
8333 /* This section overlaps the transfer. Just do half. */
8334 len = p->endaddr - memaddr;
124e13d9 8335 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 8336 xfered_len);
8acf9577
YQ
8337 }
8338 }
8339 }
8340 }
8341
8342 return TARGET_XFER_EOF;
8343}
8344
9217e74e
YQ
8345/* Similar to remote_read_bytes_1, but it reads from the remote stub
8346 first if the requested memory is unavailable in traceframe.
8347 Otherwise, fall back to remote_read_bytes_1. */
c906108c 8348
9b409511 8349static enum target_xfer_status
8acf9577 8350remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
8351 gdb_byte *myaddr, ULONGEST len, int unit_size,
8352 ULONGEST *xfered_len)
c906108c 8353{
6b6aa828 8354 if (len == 0)
96c4f946 8355 return TARGET_XFER_EOF;
b2182ed2 8356
8acf9577
YQ
8357 if (get_traceframe_number () != -1)
8358 {
8359 VEC(mem_range_s) *available;
8360
8361 /* If we fail to get the set of available memory, then the
8362 target does not support querying traceframe info, and so we
8363 attempt reading from the traceframe anyway (assuming the
8364 target implements the old QTro packet then). */
8365 if (traceframe_available_memory (&available, memaddr, len))
8366 {
8367 struct cleanup *old_chain;
8368
8369 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
8370
8371 if (VEC_empty (mem_range_s, available)
8372 || VEC_index (mem_range_s, available, 0)->start != memaddr)
8373 {
8374 enum target_xfer_status res;
8375
8376 /* Don't read into the traceframe's available
8377 memory. */
8378 if (!VEC_empty (mem_range_s, available))
8379 {
8380 LONGEST oldlen = len;
8381
8382 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8383 gdb_assert (len <= oldlen);
8384 }
8385
8386 do_cleanups (old_chain);
8387
8388 /* This goes through the topmost target again. */
b55fbac4 8389 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 8390 len, unit_size, xfered_len);
8acf9577
YQ
8391 if (res == TARGET_XFER_OK)
8392 return TARGET_XFER_OK;
8393 else
8394 {
8395 /* No use trying further, we know some memory starting
8396 at MEMADDR isn't available. */
8397 *xfered_len = len;
8398 return TARGET_XFER_UNAVAILABLE;
8399 }
8400 }
8401
8402 /* Don't try to read more than how much is available, in
8403 case the target implements the deprecated QTro packet to
8404 cater for older GDBs (the target's knowledge of read-only
8405 sections may be outdated by now). */
8406 len = VEC_index (mem_range_s, available, 0)->length;
8407
8408 do_cleanups (old_chain);
8409 }
8410 }
8411
124e13d9 8412 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8413}
74531fed 8414
c906108c 8415\f
c906108c 8416
a76d924d
DJ
8417/* Sends a packet with content determined by the printf format string
8418 FORMAT and the remaining arguments, then gets the reply. Returns
8419 whether the packet was a success, a failure, or unknown. */
8420
77b64a49
PA
8421static enum packet_result remote_send_printf (const char *format, ...)
8422 ATTRIBUTE_PRINTF (1, 2);
8423
2c0b251b 8424static enum packet_result
a76d924d
DJ
8425remote_send_printf (const char *format, ...)
8426{
8427 struct remote_state *rs = get_remote_state ();
8428 int max_size = get_remote_packet_size ();
a76d924d 8429 va_list ap;
a744cf53 8430
a76d924d
DJ
8431 va_start (ap, format);
8432
8433 rs->buf[0] = '\0';
8434 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8435 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8436
8437 if (putpkt (rs->buf) < 0)
8438 error (_("Communication problem with target."));
8439
8440 rs->buf[0] = '\0';
8441 getpkt (&rs->buf, &rs->buf_size, 0);
8442
8443 return packet_check_result (rs->buf);
8444}
8445
8446static void
8447restore_remote_timeout (void *p)
8448{
8449 int value = *(int *)p;
a744cf53 8450
a76d924d
DJ
8451 remote_timeout = value;
8452}
8453
8454/* Flash writing can take quite some time. We'll set
8455 effectively infinite timeout for flash operations.
8456 In future, we'll need to decide on a better approach. */
8457static const int remote_flash_timeout = 1000;
8458
8459static void
8460remote_flash_erase (struct target_ops *ops,
8461 ULONGEST address, LONGEST length)
8462{
f5656ead 8463 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
8464 int saved_remote_timeout = remote_timeout;
8465 enum packet_result ret;
a76d924d
DJ
8466 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8467 &saved_remote_timeout);
a744cf53 8468
a76d924d
DJ
8469 remote_timeout = remote_flash_timeout;
8470
8471 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8472 phex (address, addr_size),
a76d924d
DJ
8473 phex (length, 4));
8474 switch (ret)
8475 {
8476 case PACKET_UNKNOWN:
8477 error (_("Remote target does not support flash erase"));
8478 case PACKET_ERROR:
8479 error (_("Error erasing flash with vFlashErase packet"));
8480 default:
8481 break;
8482 }
8483
8484 do_cleanups (back_to);
8485}
8486
9b409511
YQ
8487static enum target_xfer_status
8488remote_flash_write (struct target_ops *ops, ULONGEST address,
8489 ULONGEST length, ULONGEST *xfered_len,
8490 const gdb_byte *data)
a76d924d
DJ
8491{
8492 int saved_remote_timeout = remote_timeout;
9b409511 8493 enum target_xfer_status ret;
a76d924d 8494 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 8495 &saved_remote_timeout);
a76d924d
DJ
8496
8497 remote_timeout = remote_flash_timeout;
124e13d9 8498 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 8499 xfered_len,'X', 0);
a76d924d
DJ
8500 do_cleanups (back_to);
8501
8502 return ret;
8503}
8504
8505static void
8506remote_flash_done (struct target_ops *ops)
8507{
8508 int saved_remote_timeout = remote_timeout;
8509 int ret;
8510 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8511 &saved_remote_timeout);
8512
8513 remote_timeout = remote_flash_timeout;
8514 ret = remote_send_printf ("vFlashDone");
8515 do_cleanups (back_to);
8516
8517 switch (ret)
8518 {
8519 case PACKET_UNKNOWN:
8520 error (_("Remote target does not support vFlashDone"));
8521 case PACKET_ERROR:
8522 error (_("Error finishing flash operation"));
8523 default:
8524 break;
8525 }
8526}
8527
c906108c 8528static void
fba45db2 8529remote_files_info (struct target_ops *ignore)
c906108c
SS
8530{
8531 puts_filtered ("Debugging a target over a serial line.\n");
8532}
8533\f
8534/* Stuff for dealing with the packets which are part of this protocol.
8535 See comment at top of file for details. */
8536
1927e618
PA
8537/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8538 error to higher layers. Called when a serial error is detected.
8539 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8540 the system error message for errno at function entry and final dot
8541 for output compatibility with throw_perror_with_name. */
1927e618
PA
8542
8543static void
8544unpush_and_perror (const char *string)
8545{
d6cb50a2 8546 int saved_errno = errno;
1927e618
PA
8547
8548 remote_unpush_target ();
d6cb50a2
JK
8549 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8550 safe_strerror (saved_errno));
1927e618
PA
8551}
8552
048094ac
PA
8553/* Read a single character from the remote end. The current quit
8554 handler is overridden to avoid quitting in the middle of packet
8555 sequence, as that would break communication with the remote server.
8556 See remote_serial_quit_handler for more detail. */
c906108c
SS
8557
8558static int
fba45db2 8559readchar (int timeout)
c906108c
SS
8560{
8561 int ch;
5d93a237 8562 struct remote_state *rs = get_remote_state ();
048094ac
PA
8563 struct cleanup *old_chain;
8564
8565 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8566
8567 rs->got_ctrlc_during_io = 0;
c906108c 8568
5d93a237 8569 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 8570
048094ac
PA
8571 if (rs->got_ctrlc_during_io)
8572 set_quit_flag ();
8573
8574 do_cleanups (old_chain);
8575
2acceee2 8576 if (ch >= 0)
0876f84a 8577 return ch;
2acceee2
JM
8578
8579 switch ((enum serial_rc) ch)
c906108c
SS
8580 {
8581 case SERIAL_EOF:
78a095c3 8582 remote_unpush_target ();
598d3636 8583 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8584 /* no return */
c906108c 8585 case SERIAL_ERROR:
1927e618
PA
8586 unpush_and_perror (_("Remote communication error. "
8587 "Target disconnected."));
2acceee2 8588 /* no return */
c906108c 8589 case SERIAL_TIMEOUT:
2acceee2 8590 break;
c906108c 8591 }
2acceee2 8592 return ch;
c906108c
SS
8593}
8594
c33e31fd 8595/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
8596 writing fails. The current quit handler is overridden to avoid
8597 quitting in the middle of packet sequence, as that would break
8598 communication with the remote server. See
8599 remote_serial_quit_handler for more detail. */
c33e31fd
PA
8600
8601static void
8602remote_serial_write (const char *str, int len)
8603{
5d93a237 8604 struct remote_state *rs = get_remote_state ();
048094ac
PA
8605 struct cleanup *old_chain;
8606
8607 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8608
8609 rs->got_ctrlc_during_io = 0;
5d93a237
TT
8610
8611 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8612 {
1927e618
PA
8613 unpush_and_perror (_("Remote communication error. "
8614 "Target disconnected."));
c33e31fd 8615 }
048094ac
PA
8616
8617 if (rs->got_ctrlc_during_io)
8618 set_quit_flag ();
8619
8620 do_cleanups (old_chain);
c33e31fd
PA
8621}
8622
6d820c5c
DJ
8623/* Send the command in *BUF to the remote machine, and read the reply
8624 into *BUF. Report an error if we get an error reply. Resize
8625 *BUF using xrealloc if necessary to hold the result, and update
8626 *SIZEOF_BUF. */
c906108c
SS
8627
8628static void
6d820c5c
DJ
8629remote_send (char **buf,
8630 long *sizeof_buf)
c906108c 8631{
6d820c5c 8632 putpkt (*buf);
c2d11a7d 8633 getpkt (buf, sizeof_buf, 0);
c906108c 8634
6d820c5c
DJ
8635 if ((*buf)[0] == 'E')
8636 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8637}
8638
6e5abd65
PA
8639/* Return a pointer to an xmalloc'ed string representing an escaped
8640 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8641 etc. The caller is responsible for releasing the returned
8642 memory. */
8643
8644static char *
8645escape_buffer (const char *buf, int n)
8646{
8647 struct cleanup *old_chain;
8648 struct ui_file *stb;
8649 char *str;
6e5abd65
PA
8650
8651 stb = mem_fileopen ();
8652 old_chain = make_cleanup_ui_file_delete (stb);
8653
6ef284bd 8654 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 8655 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
8656 do_cleanups (old_chain);
8657 return str;
8658}
8659
c906108c
SS
8660/* Display a null-terminated packet on stdout, for debugging, using C
8661 string notation. */
8662
8663static void
baa336ce 8664print_packet (const char *buf)
c906108c
SS
8665{
8666 puts_filtered ("\"");
43e526b9 8667 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8668 puts_filtered ("\"");
8669}
8670
8671int
baa336ce 8672putpkt (const char *buf)
c906108c
SS
8673{
8674 return putpkt_binary (buf, strlen (buf));
8675}
8676
8677/* Send a packet to the remote machine, with error checking. The data
23860348 8678 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8679 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8680 and for a possible /0 if we are debugging (remote_debug) and want
8681 to print the sent packet as a string. */
c906108c
SS
8682
8683static int
baa336ce 8684putpkt_binary (const char *buf, int cnt)
c906108c 8685{
2d717e4f 8686 struct remote_state *rs = get_remote_state ();
c906108c
SS
8687 int i;
8688 unsigned char csum = 0;
224c3ddb 8689 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8690 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8691
c906108c
SS
8692 int ch;
8693 int tcount = 0;
8694 char *p;
8695
e24a49d8
PA
8696 /* Catch cases like trying to read memory or listing threads while
8697 we're waiting for a stop reply. The remote server wouldn't be
8698 ready to handle this request, so we'd hang and timeout. We don't
8699 have to worry about this in synchronous mode, because in that
8700 case it's not possible to issue a command while the target is
74531fed
PA
8701 running. This is not a problem in non-stop mode, because in that
8702 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8703 if (!target_is_non_stop_p ()
8704 && target_is_async_p ()
8705 && rs->waiting_for_stop_reply)
9597b22a
DE
8706 {
8707 error (_("Cannot execute this command while the target is running.\n"
8708 "Use the \"interrupt\" command to stop the target\n"
8709 "and then try again."));
8710 }
e24a49d8 8711
2d717e4f
DJ
8712 /* We're sending out a new packet. Make sure we don't look at a
8713 stale cached response. */
8714 rs->cached_wait_status = 0;
8715
c906108c
SS
8716 /* Copy the packet into buffer BUF2, encapsulating it
8717 and giving it a checksum. */
8718
c906108c
SS
8719 p = buf2;
8720 *p++ = '$';
8721
8722 for (i = 0; i < cnt; i++)
8723 {
8724 csum += buf[i];
8725 *p++ = buf[i];
8726 }
8727 *p++ = '#';
8728 *p++ = tohex ((csum >> 4) & 0xf);
8729 *p++ = tohex (csum & 0xf);
8730
8731 /* Send it over and over until we get a positive ack. */
8732
8733 while (1)
8734 {
8735 int started_error_output = 0;
8736
8737 if (remote_debug)
8738 {
6e5abd65
PA
8739 struct cleanup *old_chain;
8740 char *str;
8741
c906108c 8742 *p = '\0';
6e5abd65
PA
8743 str = escape_buffer (buf2, p - buf2);
8744 old_chain = make_cleanup (xfree, str);
8745 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8746 gdb_flush (gdb_stdlog);
6e5abd65 8747 do_cleanups (old_chain);
c906108c 8748 }
c33e31fd 8749 remote_serial_write (buf2, p - buf2);
c906108c 8750
a6f3e723
SL
8751 /* If this is a no acks version of the remote protocol, send the
8752 packet and move on. */
8753 if (rs->noack_mode)
8754 break;
8755
74531fed
PA
8756 /* Read until either a timeout occurs (-2) or '+' is read.
8757 Handle any notification that arrives in the mean time. */
c906108c
SS
8758 while (1)
8759 {
8760 ch = readchar (remote_timeout);
8761
c5aa993b 8762 if (remote_debug)
c906108c
SS
8763 {
8764 switch (ch)
8765 {
8766 case '+':
1216fa2c 8767 case '-':
c906108c
SS
8768 case SERIAL_TIMEOUT:
8769 case '$':
74531fed 8770 case '%':
c906108c
SS
8771 if (started_error_output)
8772 {
8773 putchar_unfiltered ('\n');
8774 started_error_output = 0;
8775 }
8776 }
8777 }
8778
8779 switch (ch)
8780 {
8781 case '+':
8782 if (remote_debug)
0f71a2f6 8783 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8784 do_cleanups (old_chain);
c906108c 8785 return 1;
1216fa2c
AC
8786 case '-':
8787 if (remote_debug)
8788 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8789 /* FALLTHROUGH */
c906108c 8790 case SERIAL_TIMEOUT:
c5aa993b 8791 tcount++;
c906108c 8792 if (tcount > 3)
a5c0808e
PA
8793 {
8794 do_cleanups (old_chain);
8795 return 0;
8796 }
23860348 8797 break; /* Retransmit buffer. */
c906108c
SS
8798 case '$':
8799 {
40e3f985 8800 if (remote_debug)
2bc416ba 8801 fprintf_unfiltered (gdb_stdlog,
23860348 8802 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8803 /* It's probably an old response sent because an ACK
8804 was lost. Gobble up the packet and ack it so it
8805 doesn't get retransmitted when we resend this
8806 packet. */
6d820c5c 8807 skip_frame ();
c33e31fd 8808 remote_serial_write ("+", 1);
23860348 8809 continue; /* Now, go look for +. */
c906108c 8810 }
74531fed
PA
8811
8812 case '%':
8813 {
8814 int val;
8815
8816 /* If we got a notification, handle it, and go back to looking
8817 for an ack. */
8818 /* We've found the start of a notification. Now
8819 collect the data. */
8820 val = read_frame (&rs->buf, &rs->buf_size);
8821 if (val >= 0)
8822 {
8823 if (remote_debug)
8824 {
6e5abd65
PA
8825 struct cleanup *old_chain;
8826 char *str;
8827
8828 str = escape_buffer (rs->buf, val);
8829 old_chain = make_cleanup (xfree, str);
8830 fprintf_unfiltered (gdb_stdlog,
8831 " Notification received: %s\n",
8832 str);
8833 do_cleanups (old_chain);
74531fed 8834 }
5965e028 8835 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8836 /* We're in sync now, rewait for the ack. */
8837 tcount = 0;
8838 }
8839 else
8840 {
8841 if (remote_debug)
8842 {
8843 if (!started_error_output)
8844 {
8845 started_error_output = 1;
8846 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8847 }
8848 fputc_unfiltered (ch & 0177, gdb_stdlog);
8849 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8850 }
8851 }
8852 continue;
8853 }
8854 /* fall-through */
c906108c
SS
8855 default:
8856 if (remote_debug)
8857 {
8858 if (!started_error_output)
8859 {
8860 started_error_output = 1;
0f71a2f6 8861 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8862 }
0f71a2f6 8863 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8864 }
8865 continue;
8866 }
23860348 8867 break; /* Here to retransmit. */
c906108c
SS
8868 }
8869
8870#if 0
8871 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8872 able to get out next time we call QUIT, without anything as
8873 violent as interrupt_query. If we want to provide a way out of
8874 here without getting to the next QUIT, it should be based on
8875 hitting ^C twice as in remote_wait. */
c906108c
SS
8876 if (quit_flag)
8877 {
8878 quit_flag = 0;
8879 interrupt_query ();
8880 }
8881#endif
8882 }
a5c0808e
PA
8883
8884 do_cleanups (old_chain);
a6f3e723 8885 return 0;
c906108c
SS
8886}
8887
6d820c5c
DJ
8888/* Come here after finding the start of a frame when we expected an
8889 ack. Do our best to discard the rest of this packet. */
8890
8891static void
8892skip_frame (void)
8893{
8894 int c;
8895
8896 while (1)
8897 {
8898 c = readchar (remote_timeout);
8899 switch (c)
8900 {
8901 case SERIAL_TIMEOUT:
8902 /* Nothing we can do. */
8903 return;
8904 case '#':
8905 /* Discard the two bytes of checksum and stop. */
8906 c = readchar (remote_timeout);
8907 if (c >= 0)
8908 c = readchar (remote_timeout);
8909
8910 return;
8911 case '*': /* Run length encoding. */
8912 /* Discard the repeat count. */
8913 c = readchar (remote_timeout);
8914 if (c < 0)
8915 return;
8916 break;
8917 default:
8918 /* A regular character. */
8919 break;
8920 }
8921 }
8922}
8923
c906108c 8924/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8925 into *BUF, verifying the checksum, length, and handling run-length
8926 compression. NUL terminate the buffer. If there is not enough room,
8927 expand *BUF using xrealloc.
c906108c 8928
c2d11a7d
JM
8929 Returns -1 on error, number of characters in buffer (ignoring the
8930 trailing NULL) on success. (could be extended to return one of the
23860348 8931 SERIAL status indications). */
c2d11a7d
JM
8932
8933static long
6d820c5c
DJ
8934read_frame (char **buf_p,
8935 long *sizeof_buf)
c906108c
SS
8936{
8937 unsigned char csum;
c2d11a7d 8938 long bc;
c906108c 8939 int c;
6d820c5c 8940 char *buf = *buf_p;
a6f3e723 8941 struct remote_state *rs = get_remote_state ();
c906108c
SS
8942
8943 csum = 0;
c2d11a7d 8944 bc = 0;
c906108c
SS
8945
8946 while (1)
8947 {
8948 c = readchar (remote_timeout);
c906108c
SS
8949 switch (c)
8950 {
8951 case SERIAL_TIMEOUT:
8952 if (remote_debug)
0f71a2f6 8953 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8954 return -1;
c906108c
SS
8955 case '$':
8956 if (remote_debug)
0f71a2f6
JM
8957 fputs_filtered ("Saw new packet start in middle of old one\n",
8958 gdb_stdlog);
23860348 8959 return -1; /* Start a new packet, count retries. */
c906108c
SS
8960 case '#':
8961 {
8962 unsigned char pktcsum;
e1b09194
AC
8963 int check_0 = 0;
8964 int check_1 = 0;
c906108c 8965
c2d11a7d 8966 buf[bc] = '\0';
c906108c 8967
e1b09194
AC
8968 check_0 = readchar (remote_timeout);
8969 if (check_0 >= 0)
8970 check_1 = readchar (remote_timeout);
802188a7 8971
e1b09194
AC
8972 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8973 {
8974 if (remote_debug)
2bc416ba 8975 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8976 gdb_stdlog);
e1b09194
AC
8977 return -1;
8978 }
8979 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8980 {
8981 if (remote_debug)
2bc416ba 8982 fputs_filtered ("Communication error in checksum\n",
23860348 8983 gdb_stdlog);
40e3f985
FN
8984 return -1;
8985 }
c906108c 8986
a6f3e723
SL
8987 /* Don't recompute the checksum; with no ack packets we
8988 don't have any way to indicate a packet retransmission
8989 is necessary. */
8990 if (rs->noack_mode)
8991 return bc;
8992
e1b09194 8993 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8994 if (csum == pktcsum)
c2d11a7d 8995 return bc;
c906108c 8996
c5aa993b 8997 if (remote_debug)
c906108c 8998 {
6e5abd65
PA
8999 struct cleanup *old_chain;
9000 char *str;
9001
9002 str = escape_buffer (buf, bc);
9003 old_chain = make_cleanup (xfree, str);
9004 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
9005 "Bad checksum, sentsum=0x%x, "
9006 "csum=0x%x, buf=%s\n",
6e5abd65
PA
9007 pktcsum, csum, str);
9008 do_cleanups (old_chain);
c906108c 9009 }
c2d11a7d 9010 /* Number of characters in buffer ignoring trailing
23860348 9011 NULL. */
c2d11a7d 9012 return -1;
c906108c 9013 }
23860348 9014 case '*': /* Run length encoding. */
c2c6d25f
JM
9015 {
9016 int repeat;
c906108c 9017
a744cf53 9018 csum += c;
b4501125
AC
9019 c = readchar (remote_timeout);
9020 csum += c;
23860348 9021 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 9022
23860348 9023 /* The character before ``*'' is repeated. */
c2d11a7d 9024
6d820c5c 9025 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 9026 {
6d820c5c
DJ
9027 if (bc + repeat - 1 >= *sizeof_buf - 1)
9028 {
9029 /* Make some more room in the buffer. */
9030 *sizeof_buf += repeat;
224c3ddb 9031 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
9032 buf = *buf_p;
9033 }
9034
c2d11a7d
JM
9035 memset (&buf[bc], buf[bc - 1], repeat);
9036 bc += repeat;
c2c6d25f
JM
9037 continue;
9038 }
9039
c2d11a7d 9040 buf[bc] = '\0';
6d820c5c 9041 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 9042 return -1;
c2c6d25f 9043 }
c906108c 9044 default:
6d820c5c 9045 if (bc >= *sizeof_buf - 1)
c906108c 9046 {
6d820c5c
DJ
9047 /* Make some more room in the buffer. */
9048 *sizeof_buf *= 2;
224c3ddb 9049 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 9050 buf = *buf_p;
c906108c
SS
9051 }
9052
6d820c5c
DJ
9053 buf[bc++] = c;
9054 csum += c;
9055 continue;
c906108c
SS
9056 }
9057 }
9058}
9059
9060/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9061 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9062 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9063 rather than timing out; this is used (in synchronous mode) to wait
9064 for a target that is is executing user code to stop. */
d9fcf2fb
JM
9065/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9066 don't have to change all the calls to getpkt to deal with the
9067 return value, because at the moment I don't know what the right
23860348 9068 thing to do it for those. */
c906108c 9069void
6d820c5c
DJ
9070getpkt (char **buf,
9071 long *sizeof_buf,
c2d11a7d 9072 int forever)
d9fcf2fb 9073{
54887903 9074 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
9075}
9076
9077
9078/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
9079 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
9080 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
9081 rather than timing out; this is used (in synchronous mode) to wait
9082 for a target that is is executing user code to stop. If FOREVER ==
9083 0, this function is allowed to time out gracefully and return an
74531fed
PA
9084 indication of this to the caller. Otherwise return the number of
9085 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
9086 enough reason to return to the caller. *IS_NOTIF is an output
9087 boolean that indicates whether *BUF holds a notification or not
9088 (a regular packet). */
74531fed 9089
3172dc30 9090static int
74531fed 9091getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 9092 int expecting_notif, int *is_notif)
c906108c 9093{
2d717e4f 9094 struct remote_state *rs = get_remote_state ();
c906108c
SS
9095 int c;
9096 int tries;
9097 int timeout;
df4b58fe 9098 int val = -1;
c906108c 9099
2d717e4f
DJ
9100 /* We're reading a new response. Make sure we don't look at a
9101 previously cached response. */
9102 rs->cached_wait_status = 0;
9103
6d820c5c 9104 strcpy (*buf, "timeout");
c906108c
SS
9105
9106 if (forever)
74531fed
PA
9107 timeout = watchdog > 0 ? watchdog : -1;
9108 else if (expecting_notif)
9109 timeout = 0; /* There should already be a char in the buffer. If
9110 not, bail out. */
c906108c
SS
9111 else
9112 timeout = remote_timeout;
9113
9114#define MAX_TRIES 3
9115
74531fed
PA
9116 /* Process any number of notifications, and then return when
9117 we get a packet. */
9118 for (;;)
c906108c 9119 {
d9c43928 9120 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
9121 times. */
9122 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 9123 {
74531fed
PA
9124 /* This can loop forever if the remote side sends us
9125 characters continuously, but if it pauses, we'll get
9126 SERIAL_TIMEOUT from readchar because of timeout. Then
9127 we'll count that as a retry.
9128
9129 Note that even when forever is set, we will only wait
9130 forever prior to the start of a packet. After that, we
9131 expect characters to arrive at a brisk pace. They should
9132 show up within remote_timeout intervals. */
9133 do
9134 c = readchar (timeout);
9135 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
9136
9137 if (c == SERIAL_TIMEOUT)
9138 {
74531fed
PA
9139 if (expecting_notif)
9140 return -1; /* Don't complain, it's normal to not get
9141 anything in this case. */
9142
23860348 9143 if (forever) /* Watchdog went off? Kill the target. */
c906108c 9144 {
78a095c3 9145 remote_unpush_target ();
598d3636
JK
9146 throw_error (TARGET_CLOSE_ERROR,
9147 _("Watchdog timeout has expired. "
9148 "Target detached."));
c906108c 9149 }
c906108c 9150 if (remote_debug)
0f71a2f6 9151 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 9152 }
74531fed
PA
9153 else
9154 {
9155 /* We've found the start of a packet or notification.
9156 Now collect the data. */
9157 val = read_frame (buf, sizeof_buf);
9158 if (val >= 0)
9159 break;
9160 }
9161
c33e31fd 9162 remote_serial_write ("-", 1);
c906108c 9163 }
c906108c 9164
74531fed
PA
9165 if (tries > MAX_TRIES)
9166 {
9167 /* We have tried hard enough, and just can't receive the
9168 packet/notification. Give up. */
9169 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 9170
74531fed
PA
9171 /* Skip the ack char if we're in no-ack mode. */
9172 if (!rs->noack_mode)
c33e31fd 9173 remote_serial_write ("+", 1);
74531fed
PA
9174 return -1;
9175 }
c906108c 9176
74531fed
PA
9177 /* If we got an ordinary packet, return that to our caller. */
9178 if (c == '$')
c906108c
SS
9179 {
9180 if (remote_debug)
43e526b9 9181 {
6e5abd65
PA
9182 struct cleanup *old_chain;
9183 char *str;
9184
9185 str = escape_buffer (*buf, val);
9186 old_chain = make_cleanup (xfree, str);
9187 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
9188 do_cleanups (old_chain);
43e526b9 9189 }
a6f3e723
SL
9190
9191 /* Skip the ack char if we're in no-ack mode. */
9192 if (!rs->noack_mode)
c33e31fd 9193 remote_serial_write ("+", 1);
fee9eda9
YQ
9194 if (is_notif != NULL)
9195 *is_notif = 0;
0876f84a 9196 return val;
c906108c
SS
9197 }
9198
74531fed
PA
9199 /* If we got a notification, handle it, and go back to looking
9200 for a packet. */
9201 else
9202 {
9203 gdb_assert (c == '%');
9204
9205 if (remote_debug)
9206 {
6e5abd65
PA
9207 struct cleanup *old_chain;
9208 char *str;
9209
9210 str = escape_buffer (*buf, val);
9211 old_chain = make_cleanup (xfree, str);
9212 fprintf_unfiltered (gdb_stdlog,
9213 " Notification received: %s\n",
9214 str);
9215 do_cleanups (old_chain);
74531fed 9216 }
fee9eda9
YQ
9217 if (is_notif != NULL)
9218 *is_notif = 1;
c906108c 9219
5965e028 9220 handle_notification (rs->notif_state, *buf);
c906108c 9221
74531fed 9222 /* Notifications require no acknowledgement. */
a6f3e723 9223
74531fed 9224 if (expecting_notif)
fee9eda9 9225 return val;
74531fed
PA
9226 }
9227 }
9228}
9229
9230static int
9231getpkt_sane (char **buf, long *sizeof_buf, int forever)
9232{
fee9eda9 9233 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
9234}
9235
9236static int
fee9eda9
YQ
9237getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9238 int *is_notif)
74531fed 9239{
fee9eda9
YQ
9240 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9241 is_notif);
c906108c 9242}
74531fed 9243
cbb8991c
DB
9244/* Check whether EVENT is a fork event for the process specified
9245 by the pid passed in DATA, and if it is, kill the fork child. */
9246
9247static int
9248kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9249 QUEUE_ITER (stop_reply_p) *iter,
9250 stop_reply_p event,
9251 void *data)
9252{
19ba03f4 9253 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
9254 int parent_pid = *(int *) param->input;
9255
9256 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9257 {
9258 struct remote_state *rs = get_remote_state ();
9259 int child_pid = ptid_get_pid (event->ws.value.related_pid);
9260 int res;
9261
9262 res = remote_vkill (child_pid, rs);
9263 if (res != 0)
9264 error (_("Can't kill fork child process %d"), child_pid);
9265 }
9266
9267 return 1;
9268}
9269
9270/* Kill any new fork children of process PID that haven't been
9271 processed by follow_fork. */
9272
9273static void
9274kill_new_fork_children (int pid, struct remote_state *rs)
9275{
9276 struct thread_info *thread;
9277 struct notif_client *notif = &notif_client_stop;
9278 struct queue_iter_param param;
9279
9280 /* Kill the fork child threads of any threads in process PID
9281 that are stopped at a fork event. */
9282 ALL_NON_EXITED_THREADS (thread)
9283 {
9284 struct target_waitstatus *ws = &thread->pending_follow;
9285
9286 if (is_pending_fork_parent (ws, pid, thread->ptid))
9287 {
9288 struct remote_state *rs = get_remote_state ();
9289 int child_pid = ptid_get_pid (ws->value.related_pid);
9290 int res;
9291
9292 res = remote_vkill (child_pid, rs);
9293 if (res != 0)
9294 error (_("Can't kill fork child process %d"), child_pid);
9295 }
9296 }
9297
9298 /* Check for any pending fork events (not reported or processed yet)
9299 in process PID and kill those fork child threads as well. */
9300 remote_notif_get_pending_events (notif);
9301 param.input = &pid;
9302 param.output = NULL;
9303 QUEUE_iterate (stop_reply_p, stop_reply_queue,
9304 kill_child_of_pending_fork, &param);
9305}
9306
c906108c 9307\f
8020350c
DB
9308/* Target hook to kill the current inferior. */
9309
c906108c 9310static void
7d85a9c0 9311remote_kill (struct target_ops *ops)
43ff13b4 9312{
8020350c
DB
9313 int res = -1;
9314 int pid = ptid_get_pid (inferior_ptid);
9315 struct remote_state *rs = get_remote_state ();
0fdf84ca 9316
8020350c 9317 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 9318 {
8020350c
DB
9319 /* If we're stopped while forking and we haven't followed yet,
9320 kill the child task. We need to do this before killing the
9321 parent task because if this is a vfork then the parent will
9322 be sleeping. */
9323 kill_new_fork_children (pid, rs);
9324
9325 res = remote_vkill (pid, rs);
9326 if (res == 0)
0fdf84ca 9327 {
bc1e6c81 9328 target_mourn_inferior (inferior_ptid);
0fdf84ca
PA
9329 return;
9330 }
8020350c 9331 }
0fdf84ca 9332
8020350c
DB
9333 /* If we are in 'target remote' mode and we are killing the only
9334 inferior, then we will tell gdbserver to exit and unpush the
9335 target. */
9336 if (res == -1 && !remote_multi_process_p (rs)
9337 && number_of_live_inferiors () == 1)
9338 {
9339 remote_kill_k ();
9340
9341 /* We've killed the remote end, we get to mourn it. If we are
9342 not in extended mode, mourning the inferior also unpushes
9343 remote_ops from the target stack, which closes the remote
9344 connection. */
bc1e6c81 9345 target_mourn_inferior (inferior_ptid);
8020350c
DB
9346
9347 return;
0fdf84ca 9348 }
43ff13b4 9349
8020350c 9350 error (_("Can't kill process"));
43ff13b4
JM
9351}
9352
8020350c
DB
9353/* Send a kill request to the target using the 'vKill' packet. */
9354
82f73884
PA
9355static int
9356remote_vkill (int pid, struct remote_state *rs)
9357{
4082afcc 9358 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
9359 return -1;
9360
9361 /* Tell the remote target to detach. */
bba74b36 9362 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
9363 putpkt (rs->buf);
9364 getpkt (&rs->buf, &rs->buf_size, 0);
9365
4082afcc
PA
9366 switch (packet_ok (rs->buf,
9367 &remote_protocol_packets[PACKET_vKill]))
9368 {
9369 case PACKET_OK:
9370 return 0;
9371 case PACKET_ERROR:
9372 return 1;
9373 case PACKET_UNKNOWN:
9374 return -1;
9375 default:
9376 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9377 }
82f73884
PA
9378}
9379
8020350c
DB
9380/* Send a kill request to the target using the 'k' packet. */
9381
82f73884 9382static void
8020350c 9383remote_kill_k (void)
82f73884 9384{
8020350c
DB
9385 /* Catch errors so the user can quit from gdb even when we
9386 aren't on speaking terms with the remote system. */
9387 TRY
82f73884 9388 {
82f73884 9389 putpkt ("k");
82f73884 9390 }
8020350c
DB
9391 CATCH (ex, RETURN_MASK_ERROR)
9392 {
9393 if (ex.error == TARGET_CLOSE_ERROR)
9394 {
9395 /* If we got an (EOF) error that caused the target
9396 to go away, then we're done, that's what we wanted.
9397 "k" is susceptible to cause a premature EOF, given
9398 that the remote server isn't actually required to
9399 reply to "k", and it can happen that it doesn't
9400 even get to reply ACK to the "k". */
9401 return;
9402 }
82f73884 9403
8020350c
DB
9404 /* Otherwise, something went wrong. We didn't actually kill
9405 the target. Just propagate the exception, and let the
9406 user or higher layers decide what to do. */
9407 throw_exception (ex);
9408 }
9409 END_CATCH
82f73884
PA
9410}
9411
c906108c 9412static void
20f796c9 9413remote_mourn (struct target_ops *target)
c906108c 9414{
8020350c 9415 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9416
8020350c
DB
9417 /* In 'target remote' mode with one inferior, we close the connection. */
9418 if (!rs->extended && number_of_live_inferiors () <= 1)
9419 {
9420 unpush_target (target);
c906108c 9421
8020350c
DB
9422 /* remote_close takes care of doing most of the clean up. */
9423 generic_mourn_inferior ();
9424 return;
9425 }
c906108c 9426
e24a49d8
PA
9427 /* In case we got here due to an error, but we're going to stay
9428 connected. */
9429 rs->waiting_for_stop_reply = 0;
9430
dc1981d7
PA
9431 /* If the current general thread belonged to the process we just
9432 detached from or has exited, the remote side current general
9433 thread becomes undefined. Considering a case like this:
9434
9435 - We just got here due to a detach.
9436 - The process that we're detaching from happens to immediately
9437 report a global breakpoint being hit in non-stop mode, in the
9438 same thread we had selected before.
9439 - GDB attaches to this process again.
9440 - This event happens to be the next event we handle.
9441
9442 GDB would consider that the current general thread didn't need to
9443 be set on the stub side (with Hg), since for all it knew,
9444 GENERAL_THREAD hadn't changed.
9445
9446 Notice that although in all-stop mode, the remote server always
9447 sets the current thread to the thread reporting the stop event,
9448 that doesn't happen in non-stop mode; in non-stop, the stub *must
9449 not* change the current thread when reporting a breakpoint hit,
9450 due to the decoupling of event reporting and event handling.
9451
9452 To keep things simple, we always invalidate our notion of the
9453 current thread. */
47f8a51d 9454 record_currthread (rs, minus_one_ptid);
dc1981d7 9455
8020350c 9456 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9457 generic_mourn_inferior ();
9458
d729566a 9459 if (!have_inferiors ())
2d717e4f 9460 {
82f73884
PA
9461 if (!remote_multi_process_p (rs))
9462 {
9463 /* Check whether the target is running now - some remote stubs
9464 automatically restart after kill. */
9465 putpkt ("?");
9466 getpkt (&rs->buf, &rs->buf_size, 0);
9467
9468 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9469 {
3e43a32a
MS
9470 /* Assume that the target has been restarted. Set
9471 inferior_ptid so that bits of core GDB realizes
9472 there's something here, e.g., so that the user can
9473 say "kill" again. */
82f73884
PA
9474 inferior_ptid = magic_null_ptid;
9475 }
82f73884 9476 }
2d717e4f
DJ
9477 }
9478}
c906108c 9479
03583c20 9480static int
2bfc0540 9481extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 9482{
4082afcc 9483 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9484}
9485
9486static void
9487extended_remote_disable_randomization (int val)
9488{
9489 struct remote_state *rs = get_remote_state ();
9490 char *reply;
9491
bba74b36
YQ
9492 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9493 val);
03583c20
UW
9494 putpkt (rs->buf);
9495 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9496 if (*reply == '\0')
9497 error (_("Target does not support QDisableRandomization."));
9498 if (strcmp (reply, "OK") != 0)
9499 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9500}
9501
2d717e4f
DJ
9502static int
9503extended_remote_run (char *args)
9504{
9505 struct remote_state *rs = get_remote_state ();
2d717e4f 9506 int len;
94585166 9507 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9508
2d717e4f
DJ
9509 /* If the user has disabled vRun support, or we have detected that
9510 support is not available, do not try it. */
4082afcc 9511 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9512 return -1;
424163ea 9513
2d717e4f
DJ
9514 strcpy (rs->buf, "vRun;");
9515 len = strlen (rs->buf);
c906108c 9516
2d717e4f
DJ
9517 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9518 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9519 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9520 strlen (remote_exec_file));
2d717e4f 9521
d1a41061 9522 gdb_assert (args != NULL);
2d717e4f
DJ
9523 if (*args)
9524 {
9525 struct cleanup *back_to;
9526 int i;
9527 char **argv;
9528
d1a41061 9529 argv = gdb_buildargv (args);
6e366df1 9530 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
9531 for (i = 0; argv[i] != NULL; i++)
9532 {
9533 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9534 error (_("Argument list too long for run packet"));
9535 rs->buf[len++] = ';';
9f1b45b0
TT
9536 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9537 strlen (argv[i]));
2d717e4f
DJ
9538 }
9539 do_cleanups (back_to);
9540 }
9541
9542 rs->buf[len++] = '\0';
9543
9544 putpkt (rs->buf);
9545 getpkt (&rs->buf, &rs->buf_size, 0);
9546
4082afcc 9547 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9548 {
4082afcc 9549 case PACKET_OK:
3405876a 9550 /* We have a wait response. All is well. */
2d717e4f 9551 return 0;
4082afcc
PA
9552 case PACKET_UNKNOWN:
9553 return -1;
9554 case PACKET_ERROR:
2d717e4f
DJ
9555 if (remote_exec_file[0] == '\0')
9556 error (_("Running the default executable on the remote target failed; "
9557 "try \"set remote exec-file\"?"));
9558 else
9559 error (_("Running \"%s\" on the remote target failed"),
9560 remote_exec_file);
4082afcc
PA
9561 default:
9562 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9563 }
c906108c
SS
9564}
9565
2d717e4f
DJ
9566/* In the extended protocol we want to be able to do things like
9567 "run" and have them basically work as expected. So we need
9568 a special create_inferior function. We support changing the
9569 executable file and the command line arguments, but not the
9570 environment. */
9571
43ff13b4 9572static void
77a19445
TT
9573extended_remote_create_inferior (struct target_ops *ops,
9574 char *exec_file, char *args,
9575 char **env, int from_tty)
43ff13b4 9576{
3405876a
PA
9577 int run_worked;
9578 char *stop_reply;
9579 struct remote_state *rs = get_remote_state ();
94585166 9580 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9581
43ff13b4 9582 /* If running asynchronously, register the target file descriptor
23860348 9583 with the event loop. */
75c99385 9584 if (target_can_async_p ())
6a3753b3 9585 target_async (1);
43ff13b4 9586
03583c20 9587 /* Disable address space randomization if requested (and supported). */
2bfc0540 9588 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9589 extended_remote_disable_randomization (disable_randomization);
9590
43ff13b4 9591 /* Now restart the remote server. */
3405876a
PA
9592 run_worked = extended_remote_run (args) != -1;
9593 if (!run_worked)
2d717e4f
DJ
9594 {
9595 /* vRun was not supported. Fail if we need it to do what the
9596 user requested. */
9597 if (remote_exec_file[0])
9598 error (_("Remote target does not support \"set remote exec-file\""));
9599 if (args[0])
9600 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9601
2d717e4f
DJ
9602 /* Fall back to "R". */
9603 extended_remote_restart ();
9604 }
424163ea 9605
6c95b8df
PA
9606 if (!have_inferiors ())
9607 {
9608 /* Clean up from the last time we ran, before we mark the target
9609 running again. This will mark breakpoints uninserted, and
9610 get_offsets may insert breakpoints. */
9611 init_thread_list ();
9612 init_wait_for_inferior ();
9613 }
45280a52 9614
3405876a
PA
9615 /* vRun's success return is a stop reply. */
9616 stop_reply = run_worked ? rs->buf : NULL;
9617 add_current_inferior_and_thread (stop_reply);
c0a2216e 9618
2d717e4f
DJ
9619 /* Get updated offsets, if the stub uses qOffsets. */
9620 get_offsets ();
2d717e4f 9621}
c906108c 9622\f
c5aa993b 9623
b775012e
LM
9624/* Given a location's target info BP_TGT and the packet buffer BUF, output
9625 the list of conditions (in agent expression bytecode format), if any, the
9626 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9627 started from BUF and ended at BUF_END. */
b775012e
LM
9628
9629static int
9630remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9631 struct bp_target_info *bp_tgt, char *buf,
9632 char *buf_end)
b775012e
LM
9633{
9634 struct agent_expr *aexpr = NULL;
9635 int i, ix;
b775012e
LM
9636
9637 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9638 return 0;
9639
9640 buf += strlen (buf);
bba74b36 9641 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9642 buf++;
9643
9644 /* Send conditions to the target and free the vector. */
9645 for (ix = 0;
9646 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9647 ix++)
9648 {
bba74b36 9649 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
9650 buf += strlen (buf);
9651 for (i = 0; i < aexpr->len; ++i)
9652 buf = pack_hex_byte (buf, aexpr->buf[i]);
9653 *buf = '\0';
9654 }
b775012e
LM
9655 return 0;
9656}
9657
d3ce09f5
SS
9658static void
9659remote_add_target_side_commands (struct gdbarch *gdbarch,
9660 struct bp_target_info *bp_tgt, char *buf)
9661{
9662 struct agent_expr *aexpr = NULL;
9663 int i, ix;
9664
9665 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
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. */
9675 for (ix = 0;
9676 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9677 ix++)
9678 {
9679 sprintf (buf, "X%x,", aexpr->len);
9680 buf += strlen (buf);
9681 for (i = 0; i < aexpr->len; ++i)
9682 buf = pack_hex_byte (buf, aexpr->buf[i]);
9683 *buf = '\0';
9684 }
d3ce09f5
SS
9685}
9686
8181d85f
DJ
9687/* Insert a breakpoint. On targets that have software breakpoint
9688 support, we ask the remote target to do the work; on targets
9689 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9690
9691static int
3db08215
MM
9692remote_insert_breakpoint (struct target_ops *ops,
9693 struct gdbarch *gdbarch,
a6d9a66e 9694 struct bp_target_info *bp_tgt)
c906108c 9695{
d471ea57
AC
9696 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9697 If it succeeds, then set the support to PACKET_ENABLE. If it
9698 fails, and the user has explicitly requested the Z support then
23860348 9699 report an error, otherwise, mark it disabled and go on. */
802188a7 9700
4082afcc 9701 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9702 {
0d5ed153 9703 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9704 struct remote_state *rs;
bba74b36 9705 char *p, *endbuf;
7c0f6dcc 9706 int bpsize;
4fff2411 9707
28439a30
PA
9708 /* Make sure the remote is pointing at the right process, if
9709 necessary. */
9710 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9711 set_general_process ();
9712
a1dcb23a 9713 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
9714
9715 rs = get_remote_state ();
9716 p = rs->buf;
bba74b36 9717 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9718
96baa820
JM
9719 *(p++) = 'Z';
9720 *(p++) = '0';
9721 *(p++) = ',';
7c0f6dcc 9722 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9723 p += hexnumstr (p, addr);
bba74b36 9724 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 9725
efcc2da7 9726 if (remote_supports_cond_breakpoints (ops))
bba74b36 9727 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9728
78eff0ec 9729 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9730 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9731
6d820c5c
DJ
9732 putpkt (rs->buf);
9733 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9734
6d820c5c 9735 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9736 {
d471ea57
AC
9737 case PACKET_ERROR:
9738 return -1;
9739 case PACKET_OK:
7c0f6dcc
JL
9740 bp_tgt->placed_address = addr;
9741 bp_tgt->placed_size = bpsize;
d471ea57
AC
9742 return 0;
9743 case PACKET_UNKNOWN:
9744 break;
96baa820
JM
9745 }
9746 }
c906108c 9747
0000e5cc
PA
9748 /* If this breakpoint has target-side commands but this stub doesn't
9749 support Z0 packets, throw error. */
9750 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9751 throw_error (NOT_SUPPORTED_ERROR, _("\
9752Target doesn't support breakpoints that have target side commands."));
9753
3db08215 9754 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9755}
9756
9757static int
3db08215
MM
9758remote_remove_breakpoint (struct target_ops *ops,
9759 struct gdbarch *gdbarch,
73971819
PA
9760 struct bp_target_info *bp_tgt,
9761 enum remove_bp_reason reason)
c906108c 9762{
8181d85f 9763 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9764 struct remote_state *rs = get_remote_state ();
96baa820 9765
4082afcc 9766 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9767 {
6d820c5c 9768 char *p = rs->buf;
bba74b36 9769 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9770
28439a30
PA
9771 /* Make sure the remote is pointing at the right process, if
9772 necessary. */
9773 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9774 set_general_process ();
9775
96baa820
JM
9776 *(p++) = 'z';
9777 *(p++) = '0';
9778 *(p++) = ',';
9779
8181d85f
DJ
9780 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9781 p += hexnumstr (p, addr);
bba74b36 9782 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9783
6d820c5c
DJ
9784 putpkt (rs->buf);
9785 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9786
6d820c5c 9787 return (rs->buf[0] == 'E');
96baa820
JM
9788 }
9789
73971819 9790 return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
c906108c
SS
9791}
9792
f486487f 9793static enum Z_packet_type
d471ea57
AC
9794watchpoint_to_Z_packet (int type)
9795{
9796 switch (type)
9797 {
9798 case hw_write:
bb858e6a 9799 return Z_PACKET_WRITE_WP;
d471ea57
AC
9800 break;
9801 case hw_read:
bb858e6a 9802 return Z_PACKET_READ_WP;
d471ea57
AC
9803 break;
9804 case hw_access:
bb858e6a 9805 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9806 break;
9807 default:
8e65ff28 9808 internal_error (__FILE__, __LINE__,
e2e0b3e5 9809 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9810 }
9811}
9812
3c3bea1c 9813static int
f486487f
SM
9814remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9815 enum target_hw_bp_type type, struct expression *cond)
96baa820 9816{
d01949b6 9817 struct remote_state *rs = get_remote_state ();
bba74b36 9818 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9819 char *p;
d471ea57 9820 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9821
4082afcc 9822 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9823 return 1;
802188a7 9824
28439a30
PA
9825 /* Make sure the remote is pointing at the right process, if
9826 necessary. */
9827 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9828 set_general_process ();
9829
bba74b36 9830 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9831 p = strchr (rs->buf, '\0');
96baa820
JM
9832 addr = remote_address_masked (addr);
9833 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9834 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9835
6d820c5c
DJ
9836 putpkt (rs->buf);
9837 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9838
6d820c5c 9839 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9840 {
9841 case PACKET_ERROR:
d471ea57 9842 return -1;
85d721b8
PA
9843 case PACKET_UNKNOWN:
9844 return 1;
d471ea57
AC
9845 case PACKET_OK:
9846 return 0;
9847 }
8e65ff28 9848 internal_error (__FILE__, __LINE__,
e2e0b3e5 9849 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9850}
9851
283002cf
MR
9852static int
9853remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9854 CORE_ADDR start, int length)
9855{
9856 CORE_ADDR diff = remote_address_masked (addr - start);
9857
9858 return diff < length;
9859}
9860
d471ea57 9861
3c3bea1c 9862static int
f486487f
SM
9863remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9864 enum target_hw_bp_type type, struct expression *cond)
96baa820 9865{
d01949b6 9866 struct remote_state *rs = get_remote_state ();
bba74b36 9867 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9868 char *p;
d471ea57
AC
9869 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9870
4082afcc 9871 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9872 return -1;
802188a7 9873
28439a30
PA
9874 /* Make sure the remote is pointing at the right process, if
9875 necessary. */
9876 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9877 set_general_process ();
9878
bba74b36 9879 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9880 p = strchr (rs->buf, '\0');
96baa820
JM
9881 addr = remote_address_masked (addr);
9882 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9883 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9884 putpkt (rs->buf);
9885 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9886
6d820c5c 9887 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9888 {
9889 case PACKET_ERROR:
9890 case PACKET_UNKNOWN:
9891 return -1;
9892 case PACKET_OK:
9893 return 0;
9894 }
8e65ff28 9895 internal_error (__FILE__, __LINE__,
e2e0b3e5 9896 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9897}
9898
3c3bea1c 9899
501eef12 9900int remote_hw_watchpoint_limit = -1;
480a3f21 9901int remote_hw_watchpoint_length_limit = -1;
501eef12 9902int remote_hw_breakpoint_limit = -1;
d471ea57 9903
480a3f21 9904static int
31568a15
TT
9905remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9906 CORE_ADDR addr, int len)
480a3f21
PW
9907{
9908 if (remote_hw_watchpoint_length_limit == 0)
9909 return 0;
9910 else if (remote_hw_watchpoint_length_limit < 0)
9911 return 1;
9912 else if (len <= remote_hw_watchpoint_length_limit)
9913 return 1;
9914 else
9915 return 0;
9916}
9917
b9362cc7 9918static int
5461485a 9919remote_check_watch_resources (struct target_ops *self,
f486487f 9920 enum bptype type, int cnt, int ot)
96baa820 9921{
3c3bea1c
GS
9922 if (type == bp_hardware_breakpoint)
9923 {
9924 if (remote_hw_breakpoint_limit == 0)
9925 return 0;
501eef12
AC
9926 else if (remote_hw_breakpoint_limit < 0)
9927 return 1;
3c3bea1c
GS
9928 else if (cnt <= remote_hw_breakpoint_limit)
9929 return 1;
9930 }
9931 else
9932 {
9933 if (remote_hw_watchpoint_limit == 0)
9934 return 0;
501eef12
AC
9935 else if (remote_hw_watchpoint_limit < 0)
9936 return 1;
3c3bea1c
GS
9937 else if (ot)
9938 return -1;
9939 else if (cnt <= remote_hw_watchpoint_limit)
9940 return 1;
9941 }
9942 return -1;
9943}
9944
f7e6eed5
PA
9945/* The to_stopped_by_sw_breakpoint method of target remote. */
9946
9947static int
9948remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9949{
799a2abe 9950 struct thread_info *thread = inferior_thread ();
f7e6eed5 9951
799a2abe
PA
9952 return (thread->priv != NULL
9953 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9954}
9955
9956/* The to_supports_stopped_by_sw_breakpoint method of target
9957 remote. */
9958
9959static int
9960remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9961{
f7e6eed5
PA
9962 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9963}
9964
9965/* The to_stopped_by_hw_breakpoint method of target remote. */
9966
9967static int
9968remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9969{
799a2abe 9970 struct thread_info *thread = inferior_thread ();
f7e6eed5 9971
799a2abe
PA
9972 return (thread->priv != NULL
9973 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9974}
9975
9976/* The to_supports_stopped_by_hw_breakpoint method of target
9977 remote. */
9978
9979static int
9980remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9981{
f7e6eed5
PA
9982 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9983}
9984
b9362cc7 9985static int
6a109b6b 9986remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9987{
799a2abe 9988 struct thread_info *thread = inferior_thread ();
ee154bee 9989
799a2abe
PA
9990 return (thread->priv != NULL
9991 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9992}
9993
4aa7a7f5
JJ
9994static int
9995remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9996{
799a2abe 9997 struct thread_info *thread = inferior_thread ();
a744cf53 9998
799a2abe
PA
9999 if (thread->priv != NULL
10000 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 10001 {
799a2abe
PA
10002 *addr_p = thread->priv->watch_data_address;
10003 return 1;
4aa7a7f5
JJ
10004 }
10005
799a2abe 10006 return 0;
3c3bea1c
GS
10007}
10008
10009
10010static int
23a26771 10011remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 10012 struct bp_target_info *bp_tgt)
3c3bea1c 10013{
0d5ed153 10014 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 10015 struct remote_state *rs;
bba74b36 10016 char *p, *endbuf;
dd61ec5c 10017 char *message;
0d5ed153 10018 int bpsize;
802188a7 10019
c8189ed1 10020 /* The length field should be set to the size of a breakpoint
8181d85f 10021 instruction, even though we aren't inserting one ourselves. */
c8189ed1 10022
0d5ed153 10023 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 10024
4082afcc 10025 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10026 return -1;
2bc416ba 10027
28439a30
PA
10028 /* Make sure the remote is pointing at the right process, if
10029 necessary. */
10030 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10031 set_general_process ();
10032
4fff2411
JZ
10033 rs = get_remote_state ();
10034 p = rs->buf;
bba74b36 10035 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 10036
96baa820
JM
10037 *(p++) = 'Z';
10038 *(p++) = '1';
10039 *(p++) = ',';
802188a7 10040
0d5ed153 10041 addr = remote_address_masked (addr);
96baa820 10042 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 10043 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 10044
efcc2da7 10045 if (remote_supports_cond_breakpoints (self))
bba74b36 10046 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 10047
78eff0ec 10048 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
10049 remote_add_target_side_commands (gdbarch, bp_tgt, p);
10050
6d820c5c
DJ
10051 putpkt (rs->buf);
10052 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 10053
6d820c5c 10054 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10055 {
10056 case PACKET_ERROR:
dd61ec5c
MW
10057 if (rs->buf[1] == '.')
10058 {
10059 message = strchr (rs->buf + 2, '.');
10060 if (message)
0316657e 10061 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
10062 }
10063 return -1;
d471ea57
AC
10064 case PACKET_UNKNOWN:
10065 return -1;
10066 case PACKET_OK:
0d5ed153
MR
10067 bp_tgt->placed_address = addr;
10068 bp_tgt->placed_size = bpsize;
d471ea57
AC
10069 return 0;
10070 }
8e65ff28 10071 internal_error (__FILE__, __LINE__,
e2e0b3e5 10072 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
10073}
10074
d471ea57 10075
802188a7 10076static int
a64dc96c 10077remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 10078 struct bp_target_info *bp_tgt)
96baa820 10079{
8181d85f 10080 CORE_ADDR addr;
d01949b6 10081 struct remote_state *rs = get_remote_state ();
6d820c5c 10082 char *p = rs->buf;
bba74b36 10083 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 10084
4082afcc 10085 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 10086 return -1;
802188a7 10087
28439a30
PA
10088 /* Make sure the remote is pointing at the right process, if
10089 necessary. */
10090 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10091 set_general_process ();
10092
96baa820
JM
10093 *(p++) = 'z';
10094 *(p++) = '1';
10095 *(p++) = ',';
802188a7 10096
8181d85f 10097 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 10098 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 10099 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 10100
6d820c5c
DJ
10101 putpkt (rs->buf);
10102 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 10103
6d820c5c 10104 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
10105 {
10106 case PACKET_ERROR:
10107 case PACKET_UNKNOWN:
10108 return -1;
10109 case PACKET_OK:
10110 return 0;
10111 }
8e65ff28 10112 internal_error (__FILE__, __LINE__,
e2e0b3e5 10113 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 10114}
96baa820 10115
4a5e7a5b
PA
10116/* Verify memory using the "qCRC:" request. */
10117
10118static int
10119remote_verify_memory (struct target_ops *ops,
10120 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10121{
10122 struct remote_state *rs = get_remote_state ();
10123 unsigned long host_crc, target_crc;
10124 char *tmp;
10125
936d2992
PA
10126 /* It doesn't make sense to use qCRC if the remote target is
10127 connected but not running. */
10128 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10129 {
10130 enum packet_result result;
28439a30 10131
936d2992
PA
10132 /* Make sure the remote is pointing at the right process. */
10133 set_general_process ();
4a5e7a5b 10134
936d2992
PA
10135 /* FIXME: assumes lma can fit into long. */
10136 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10137 (long) lma, (long) size);
10138 putpkt (rs->buf);
4a5e7a5b 10139
936d2992
PA
10140 /* Be clever; compute the host_crc before waiting for target
10141 reply. */
10142 host_crc = xcrc32 (data, size, 0xffffffff);
10143
10144 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 10145
936d2992
PA
10146 result = packet_ok (rs->buf,
10147 &remote_protocol_packets[PACKET_qCRC]);
10148 if (result == PACKET_ERROR)
10149 return -1;
10150 else if (result == PACKET_OK)
10151 {
10152 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10153 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 10154
936d2992
PA
10155 return (host_crc == target_crc);
10156 }
10157 }
4a5e7a5b 10158
936d2992 10159 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
10160}
10161
c906108c
SS
10162/* compare-sections command
10163
10164 With no arguments, compares each loadable section in the exec bfd
10165 with the same memory range on the target, and reports mismatches.
4a5e7a5b 10166 Useful for verifying the image on the target against the exec file. */
e514a9d6 10167
c906108c 10168static void
fba45db2 10169compare_sections_command (char *args, int from_tty)
c906108c
SS
10170{
10171 asection *s;
c906108c 10172 struct cleanup *old_chain;
948f8e3d 10173 gdb_byte *sectdata;
ce359b09 10174 const char *sectname;
c906108c
SS
10175 bfd_size_type size;
10176 bfd_vma lma;
10177 int matched = 0;
10178 int mismatched = 0;
4a5e7a5b 10179 int res;
95cf3b38 10180 int read_only = 0;
c906108c
SS
10181
10182 if (!exec_bfd)
8a3fe4f8 10183 error (_("command cannot be used without an exec file"));
c906108c 10184
28439a30
PA
10185 /* Make sure the remote is pointing at the right process. */
10186 set_general_process ();
10187
95cf3b38
DT
10188 if (args != NULL && strcmp (args, "-r") == 0)
10189 {
10190 read_only = 1;
10191 args = NULL;
10192 }
10193
c5aa993b 10194 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
10195 {
10196 if (!(s->flags & SEC_LOAD))
0df8b418 10197 continue; /* Skip non-loadable section. */
c906108c 10198
95cf3b38
DT
10199 if (read_only && (s->flags & SEC_READONLY) == 0)
10200 continue; /* Skip writeable sections */
10201
2c500098 10202 size = bfd_get_section_size (s);
c906108c 10203 if (size == 0)
0df8b418 10204 continue; /* Skip zero-length section. */
c906108c 10205
ce359b09 10206 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 10207 if (args && strcmp (args, sectname) != 0)
0df8b418 10208 continue; /* Not the section selected by user. */
c906108c 10209
0df8b418 10210 matched = 1; /* Do this section. */
c906108c 10211 lma = s->lma;
c906108c 10212
224c3ddb 10213 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 10214 old_chain = make_cleanup (xfree, sectdata);
c906108c 10215 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 10216
4a5e7a5b
PA
10217 res = target_verify_memory (sectdata, lma, size);
10218
10219 if (res == -1)
5af949e3 10220 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
10221 paddress (target_gdbarch (), lma),
10222 paddress (target_gdbarch (), lma + size));
c906108c 10223
5af949e3 10224 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
10225 paddress (target_gdbarch (), lma),
10226 paddress (target_gdbarch (), lma + size));
4a5e7a5b 10227 if (res)
c906108c
SS
10228 printf_filtered ("matched.\n");
10229 else
c5aa993b
JM
10230 {
10231 printf_filtered ("MIS-MATCHED!\n");
10232 mismatched++;
10233 }
c906108c
SS
10234
10235 do_cleanups (old_chain);
10236 }
10237 if (mismatched > 0)
936d2992 10238 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 10239the loaded file\n"));
c906108c 10240 if (args && !matched)
a3f17187 10241 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
10242}
10243
0e7f50da
UW
10244/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10245 into remote target. The number of bytes written to the remote
10246 target is returned, or -1 for error. */
10247
9b409511 10248static enum target_xfer_status
0e7f50da
UW
10249remote_write_qxfer (struct target_ops *ops, const char *object_name,
10250 const char *annex, const gdb_byte *writebuf,
9b409511 10251 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
10252 struct packet_config *packet)
10253{
10254 int i, buf_len;
10255 ULONGEST n;
0e7f50da
UW
10256 struct remote_state *rs = get_remote_state ();
10257 int max_size = get_memory_write_packet_size ();
10258
10259 if (packet->support == PACKET_DISABLE)
2ed4b548 10260 return TARGET_XFER_E_IO;
0e7f50da
UW
10261
10262 /* Insert header. */
10263 i = snprintf (rs->buf, max_size,
10264 "qXfer:%s:write:%s:%s:",
10265 object_name, annex ? annex : "",
10266 phex_nz (offset, sizeof offset));
10267 max_size -= (i + 1);
10268
10269 /* Escape as much data as fits into rs->buf. */
10270 buf_len = remote_escape_output
124e13d9 10271 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
10272
10273 if (putpkt_binary (rs->buf, i + buf_len) < 0
10274 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10275 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10276 return TARGET_XFER_E_IO;
0e7f50da
UW
10277
10278 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
10279
10280 *xfered_len = n;
10281 return TARGET_XFER_OK;
0e7f50da
UW
10282}
10283
0876f84a
DJ
10284/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10285 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10286 number of bytes read is returned, or 0 for EOF, or -1 for error.
10287 The number of bytes read may be less than LEN without indicating an
10288 EOF. PACKET is checked and updated to indicate whether the remote
10289 target supports this object. */
10290
9b409511 10291static enum target_xfer_status
0876f84a
DJ
10292remote_read_qxfer (struct target_ops *ops, const char *object_name,
10293 const char *annex,
10294 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 10295 ULONGEST *xfered_len,
0876f84a
DJ
10296 struct packet_config *packet)
10297{
0876f84a 10298 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
10299 LONGEST i, n, packet_len;
10300
10301 if (packet->support == PACKET_DISABLE)
2ed4b548 10302 return TARGET_XFER_E_IO;
0876f84a
DJ
10303
10304 /* Check whether we've cached an end-of-object packet that matches
10305 this request. */
8e88304f 10306 if (rs->finished_object)
0876f84a 10307 {
8e88304f
TT
10308 if (strcmp (object_name, rs->finished_object) == 0
10309 && strcmp (annex ? annex : "", rs->finished_annex) == 0
10310 && offset == rs->finished_offset)
9b409511
YQ
10311 return TARGET_XFER_EOF;
10312
0876f84a
DJ
10313
10314 /* Otherwise, we're now reading something different. Discard
10315 the cache. */
8e88304f
TT
10316 xfree (rs->finished_object);
10317 xfree (rs->finished_annex);
10318 rs->finished_object = NULL;
10319 rs->finished_annex = NULL;
0876f84a
DJ
10320 }
10321
10322 /* Request only enough to fit in a single packet. The actual data
10323 may not, since we don't know how much of it will need to be escaped;
10324 the target is free to respond with slightly less data. We subtract
10325 five to account for the response type and the protocol frame. */
768adc05 10326 n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
0876f84a
DJ
10327 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10328 object_name, annex ? annex : "",
10329 phex_nz (offset, sizeof offset),
10330 phex_nz (n, sizeof n));
10331 i = putpkt (rs->buf);
10332 if (i < 0)
2ed4b548 10333 return TARGET_XFER_E_IO;
0876f84a
DJ
10334
10335 rs->buf[0] = '\0';
10336 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10337 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 10338 return TARGET_XFER_E_IO;
0876f84a
DJ
10339
10340 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10341 error (_("Unknown remote qXfer reply: %s"), rs->buf);
10342
10343 /* 'm' means there is (or at least might be) more data after this
10344 batch. That does not make sense unless there's at least one byte
10345 of data in this reply. */
10346 if (rs->buf[0] == 'm' && packet_len == 1)
10347 error (_("Remote qXfer reply contained no data."));
10348
10349 /* Got some data. */
bc20a4af
PA
10350 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10351 packet_len - 1, readbuf, n);
0876f84a
DJ
10352
10353 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
10354 or possibly empty. If we have the final block of a non-empty
10355 object, record this fact to bypass a subsequent partial read. */
10356 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 10357 {
8e88304f
TT
10358 rs->finished_object = xstrdup (object_name);
10359 rs->finished_annex = xstrdup (annex ? annex : "");
10360 rs->finished_offset = offset + i;
0876f84a
DJ
10361 }
10362
9b409511
YQ
10363 if (i == 0)
10364 return TARGET_XFER_EOF;
10365 else
10366 {
10367 *xfered_len = i;
10368 return TARGET_XFER_OK;
10369 }
0876f84a
DJ
10370}
10371
9b409511 10372static enum target_xfer_status
4b8a223f 10373remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 10374 const char *annex, gdb_byte *readbuf,
9b409511
YQ
10375 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10376 ULONGEST *xfered_len)
c906108c 10377{
82f73884 10378 struct remote_state *rs;
c906108c 10379 int i;
6d820c5c 10380 char *p2;
1e3ff5ad 10381 char query_type;
124e13d9 10382 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 10383
e6e4e701 10384 set_remote_traceframe ();
82f73884
PA
10385 set_general_thread (inferior_ptid);
10386
10387 rs = get_remote_state ();
10388
b2182ed2 10389 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
10390 if (object == TARGET_OBJECT_MEMORY)
10391 {
2d717e4f
DJ
10392 /* If the remote target is connected but not running, we should
10393 pass this request down to a lower stratum (e.g. the executable
10394 file). */
10395 if (!target_has_execution)
9b409511 10396 return TARGET_XFER_EOF;
2d717e4f 10397
21e3b9b9 10398 if (writebuf != NULL)
124e13d9
SM
10399 return remote_write_bytes (offset, writebuf, len, unit_size,
10400 xfered_len);
21e3b9b9 10401 else
124e13d9
SM
10402 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10403 xfered_len);
21e3b9b9
DJ
10404 }
10405
0df8b418 10406 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10407 if (object == TARGET_OBJECT_SPU)
10408 {
10409 if (readbuf)
10410 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
10411 xfered_len, &remote_protocol_packets
10412 [PACKET_qXfer_spu_read]);
0e7f50da
UW
10413 else
10414 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
10415 xfered_len, &remote_protocol_packets
10416 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10417 }
10418
4aa995e1
PA
10419 /* Handle extra signal info using qxfer packets. */
10420 if (object == TARGET_OBJECT_SIGNAL_INFO)
10421 {
10422 if (readbuf)
10423 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 10424 xfered_len, &remote_protocol_packets
4aa995e1
PA
10425 [PACKET_qXfer_siginfo_read]);
10426 else
3e43a32a 10427 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 10428 writebuf, offset, len, xfered_len,
4aa995e1
PA
10429 &remote_protocol_packets
10430 [PACKET_qXfer_siginfo_write]);
10431 }
10432
0fb4aa4b
PA
10433 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10434 {
10435 if (readbuf)
3e43a32a 10436 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 10437 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10438 &remote_protocol_packets
10439 [PACKET_qXfer_statictrace_read]);
10440 else
2ed4b548 10441 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10442 }
10443
a76d924d
DJ
10444 /* Only handle flash writes. */
10445 if (writebuf != NULL)
10446 {
a76d924d
DJ
10447 switch (object)
10448 {
10449 case TARGET_OBJECT_FLASH:
9b409511
YQ
10450 return remote_flash_write (ops, offset, len, xfered_len,
10451 writebuf);
a76d924d
DJ
10452
10453 default:
2ed4b548 10454 return TARGET_XFER_E_IO;
a76d924d
DJ
10455 }
10456 }
4b8a223f 10457
1e3ff5ad
AC
10458 /* Map pre-existing objects onto letters. DO NOT do this for new
10459 objects!!! Instead specify new query packets. */
10460 switch (object)
c906108c 10461 {
1e3ff5ad
AC
10462 case TARGET_OBJECT_AVR:
10463 query_type = 'R';
10464 break;
802188a7
RM
10465
10466 case TARGET_OBJECT_AUXV:
0876f84a
DJ
10467 gdb_assert (annex == NULL);
10468 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 10469 xfered_len,
0876f84a 10470 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10471
23181151
DJ
10472 case TARGET_OBJECT_AVAILABLE_FEATURES:
10473 return remote_read_qxfer
9b409511 10474 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10475 &remote_protocol_packets[PACKET_qXfer_features]);
10476
cfa9d6d9
DJ
10477 case TARGET_OBJECT_LIBRARIES:
10478 return remote_read_qxfer
9b409511 10479 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10480 &remote_protocol_packets[PACKET_qXfer_libraries]);
10481
2268b414
JK
10482 case TARGET_OBJECT_LIBRARIES_SVR4:
10483 return remote_read_qxfer
9b409511 10484 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10485 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10486
fd79ecee
DJ
10487 case TARGET_OBJECT_MEMORY_MAP:
10488 gdb_assert (annex == NULL);
10489 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 10490 xfered_len,
fd79ecee
DJ
10491 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10492
07e059b5
VP
10493 case TARGET_OBJECT_OSDATA:
10494 /* Should only get here if we're connected. */
5d93a237 10495 gdb_assert (rs->remote_desc);
07e059b5 10496 return remote_read_qxfer
9b409511 10497 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10498 &remote_protocol_packets[PACKET_qXfer_osdata]);
10499
dc146f7c
VP
10500 case TARGET_OBJECT_THREADS:
10501 gdb_assert (annex == NULL);
10502 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10503 xfered_len,
dc146f7c
VP
10504 &remote_protocol_packets[PACKET_qXfer_threads]);
10505
b3b9301e
PA
10506 case TARGET_OBJECT_TRACEFRAME_INFO:
10507 gdb_assert (annex == NULL);
10508 return remote_read_qxfer
9b409511 10509 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10510 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10511
10512 case TARGET_OBJECT_FDPIC:
10513 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10514 xfered_len,
78d85199 10515 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10516
10517 case TARGET_OBJECT_OPENVMS_UIB:
10518 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10519 xfered_len,
169081d0
TG
10520 &remote_protocol_packets[PACKET_qXfer_uib]);
10521
9accd112
MM
10522 case TARGET_OBJECT_BTRACE:
10523 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10524 xfered_len,
9accd112
MM
10525 &remote_protocol_packets[PACKET_qXfer_btrace]);
10526
f4abbc16
MM
10527 case TARGET_OBJECT_BTRACE_CONF:
10528 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10529 len, xfered_len,
10530 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10531
c78fa86a
GB
10532 case TARGET_OBJECT_EXEC_FILE:
10533 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10534 len, xfered_len,
10535 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10536
1e3ff5ad 10537 default:
2ed4b548 10538 return TARGET_XFER_E_IO;
c906108c
SS
10539 }
10540
0df8b418 10541 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10542 large enough let the caller deal with it. */
ea9c271d 10543 if (len < get_remote_packet_size ())
2ed4b548 10544 return TARGET_XFER_E_IO;
ea9c271d 10545 len = get_remote_packet_size ();
1e3ff5ad 10546
23860348 10547 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10548 if (!rs->remote_desc)
8a3fe4f8 10549 error (_("remote query is only available after target open"));
c906108c 10550
1e3ff5ad 10551 gdb_assert (annex != NULL);
4b8a223f 10552 gdb_assert (readbuf != NULL);
c906108c 10553
6d820c5c 10554 p2 = rs->buf;
c906108c
SS
10555 *p2++ = 'q';
10556 *p2++ = query_type;
10557
23860348
MS
10558 /* We used one buffer char for the remote protocol q command and
10559 another for the query type. As the remote protocol encapsulation
10560 uses 4 chars plus one extra in case we are debugging
10561 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10562 string. */
c906108c 10563 i = 0;
ea9c271d 10564 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10565 {
1e3ff5ad
AC
10566 /* Bad caller may have sent forbidden characters. */
10567 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10568 *p2++ = annex[i];
c906108c
SS
10569 i++;
10570 }
1e3ff5ad
AC
10571 *p2 = '\0';
10572 gdb_assert (annex[i] == '\0');
c906108c 10573
6d820c5c 10574 i = putpkt (rs->buf);
c5aa993b 10575 if (i < 0)
2ed4b548 10576 return TARGET_XFER_E_IO;
c906108c 10577
6d820c5c
DJ
10578 getpkt (&rs->buf, &rs->buf_size, 0);
10579 strcpy ((char *) readbuf, rs->buf);
c906108c 10580
9b409511
YQ
10581 *xfered_len = strlen ((char *) readbuf);
10582 return TARGET_XFER_OK;
c906108c
SS
10583}
10584
09c98b44
DB
10585/* Implementation of to_get_memory_xfer_limit. */
10586
10587static ULONGEST
10588remote_get_memory_xfer_limit (struct target_ops *ops)
10589{
10590 return get_memory_write_packet_size ();
10591}
10592
08388c79
DE
10593static int
10594remote_search_memory (struct target_ops* ops,
10595 CORE_ADDR start_addr, ULONGEST search_space_len,
10596 const gdb_byte *pattern, ULONGEST pattern_len,
10597 CORE_ADDR *found_addrp)
10598{
f5656ead 10599 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10600 struct remote_state *rs = get_remote_state ();
10601 int max_size = get_memory_write_packet_size ();
10602 struct packet_config *packet =
10603 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10604 /* Number of packet bytes used to encode the pattern;
10605 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10606 int escaped_pattern_len;
0df8b418 10607 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10608 int used_pattern_len;
10609 int i;
10610 int found;
10611 ULONGEST found_addr;
10612
10613 /* Don't go to the target if we don't have to.
10614 This is done before checking packet->support to avoid the possibility that
10615 a success for this edge case means the facility works in general. */
10616 if (pattern_len > search_space_len)
10617 return 0;
10618 if (pattern_len == 0)
10619 {
10620 *found_addrp = start_addr;
10621 return 1;
10622 }
10623
10624 /* If we already know the packet isn't supported, fall back to the simple
10625 way of searching memory. */
10626
4082afcc 10627 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10628 {
10629 /* Target doesn't provided special support, fall back and use the
10630 standard support (copy memory and do the search here). */
10631 return simple_search_memory (ops, start_addr, search_space_len,
10632 pattern, pattern_len, found_addrp);
10633 }
10634
28439a30
PA
10635 /* Make sure the remote is pointing at the right process. */
10636 set_general_process ();
10637
08388c79
DE
10638 /* Insert header. */
10639 i = snprintf (rs->buf, max_size,
10640 "qSearch:memory:%s;%s;",
5af949e3 10641 phex_nz (start_addr, addr_size),
08388c79
DE
10642 phex_nz (search_space_len, sizeof (search_space_len)));
10643 max_size -= (i + 1);
10644
10645 /* Escape as much data as fits into rs->buf. */
10646 escaped_pattern_len =
124e13d9 10647 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10648 &used_pattern_len, max_size);
10649
10650 /* Bail if the pattern is too large. */
10651 if (used_pattern_len != pattern_len)
9b20d036 10652 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10653
10654 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10655 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10656 || packet_ok (rs->buf, packet) != PACKET_OK)
10657 {
10658 /* The request may not have worked because the command is not
10659 supported. If so, fall back to the simple way. */
10660 if (packet->support == PACKET_DISABLE)
10661 {
10662 return simple_search_memory (ops, start_addr, search_space_len,
10663 pattern, pattern_len, found_addrp);
10664 }
10665 return -1;
10666 }
10667
10668 if (rs->buf[0] == '0')
10669 found = 0;
10670 else if (rs->buf[0] == '1')
10671 {
10672 found = 1;
10673 if (rs->buf[1] != ',')
10e0fa18 10674 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10675 unpack_varlen_hex (rs->buf + 2, &found_addr);
10676 *found_addrp = found_addr;
10677 }
10678 else
10e0fa18 10679 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10680
10681 return found;
10682}
10683
96baa820 10684static void
a30bf1f1 10685remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10686 struct ui_file *outbuf)
96baa820 10687{
d01949b6 10688 struct remote_state *rs = get_remote_state ();
2e9f7625 10689 char *p = rs->buf;
96baa820 10690
5d93a237 10691 if (!rs->remote_desc)
8a3fe4f8 10692 error (_("remote rcmd is only available after target open"));
96baa820 10693
23860348 10694 /* Send a NULL command across as an empty command. */
7be570e7
JM
10695 if (command == NULL)
10696 command = "";
10697
23860348 10698 /* The query prefix. */
2e9f7625
DJ
10699 strcpy (rs->buf, "qRcmd,");
10700 p = strchr (rs->buf, '\0');
96baa820 10701
3e43a32a
MS
10702 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10703 > get_remote_packet_size ())
8a3fe4f8 10704 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10705
23860348 10706 /* Encode the actual command. */
a30bf1f1 10707 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10708
6d820c5c 10709 if (putpkt (rs->buf) < 0)
8a3fe4f8 10710 error (_("Communication problem with target."));
96baa820
JM
10711
10712 /* get/display the response */
10713 while (1)
10714 {
2e9f7625
DJ
10715 char *buf;
10716
00bf0b85 10717 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10718 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10719 rs->buf[0] = '\0';
5b37825d
PW
10720 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10721 {
10722 /* Timeout. Continue to (try to) read responses.
10723 This is better than stopping with an error, assuming the stub
10724 is still executing the (long) monitor command.
10725 If needed, the user can interrupt gdb using C-c, obtaining
10726 an effect similar to stop on timeout. */
10727 continue;
10728 }
2e9f7625 10729 buf = rs->buf;
96baa820 10730 if (buf[0] == '\0')
8a3fe4f8 10731 error (_("Target does not support this command."));
96baa820
JM
10732 if (buf[0] == 'O' && buf[1] != 'K')
10733 {
23860348 10734 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10735 continue;
10736 }
10737 if (strcmp (buf, "OK") == 0)
10738 break;
7be570e7
JM
10739 if (strlen (buf) == 3 && buf[0] == 'E'
10740 && isdigit (buf[1]) && isdigit (buf[2]))
10741 {
8a3fe4f8 10742 error (_("Protocol error with Rcmd"));
7be570e7 10743 }
96baa820
JM
10744 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10745 {
10746 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10747
96baa820
JM
10748 fputc_unfiltered (c, outbuf);
10749 }
10750 break;
10751 }
10752}
10753
fd79ecee
DJ
10754static VEC(mem_region_s) *
10755remote_memory_map (struct target_ops *ops)
10756{
10757 VEC(mem_region_s) *result = NULL;
10758 char *text = target_read_stralloc (&current_target,
10759 TARGET_OBJECT_MEMORY_MAP, NULL);
10760
10761 if (text)
10762 {
10763 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10764
fd79ecee
DJ
10765 result = parse_memory_map (text);
10766 do_cleanups (back_to);
10767 }
10768
10769 return result;
10770}
10771
c906108c 10772static void
fba45db2 10773packet_command (char *args, int from_tty)
c906108c 10774{
d01949b6 10775 struct remote_state *rs = get_remote_state ();
c906108c 10776
5d93a237 10777 if (!rs->remote_desc)
8a3fe4f8 10778 error (_("command can only be used with remote target"));
c906108c 10779
c5aa993b 10780 if (!args)
8a3fe4f8 10781 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10782
10783 puts_filtered ("sending: ");
10784 print_packet (args);
10785 puts_filtered ("\n");
10786 putpkt (args);
10787
6d820c5c 10788 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10789 puts_filtered ("received: ");
6d820c5c 10790 print_packet (rs->buf);
c906108c
SS
10791 puts_filtered ("\n");
10792}
10793
10794#if 0
23860348 10795/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10796
a14ed312 10797static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10798
a14ed312 10799static void threadset_test_cmd (char *cmd, int tty);
c906108c 10800
a14ed312 10801static void threadalive_test (char *cmd, int tty);
c906108c 10802
a14ed312 10803static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10804
23860348 10805int get_and_display_threadinfo (threadref *ref);
c906108c 10806
a14ed312 10807static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10808
23860348 10809static int thread_display_step (threadref *ref, void *context);
c906108c 10810
a14ed312 10811static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10812
a14ed312 10813static void init_remote_threadtests (void);
c906108c 10814
23860348 10815#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10816
10817static void
fba45db2 10818threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10819{
10820 int sample_thread = SAMPLE_THREAD;
10821
a3f17187 10822 printf_filtered (_("Remote threadset test\n"));
79d7f229 10823 set_general_thread (sample_thread);
c906108c
SS
10824}
10825
10826
10827static void
fba45db2 10828threadalive_test (char *cmd, int tty)
c906108c
SS
10829{
10830 int sample_thread = SAMPLE_THREAD;
79d7f229 10831 int pid = ptid_get_pid (inferior_ptid);
ba348170 10832 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10833
79d7f229 10834 if (remote_thread_alive (ptid))
c906108c
SS
10835 printf_filtered ("PASS: Thread alive test\n");
10836 else
10837 printf_filtered ("FAIL: Thread alive test\n");
10838}
10839
23860348 10840void output_threadid (char *title, threadref *ref);
c906108c
SS
10841
10842void
fba45db2 10843output_threadid (char *title, threadref *ref)
c906108c
SS
10844{
10845 char hexid[20];
10846
23860348 10847 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10848 hexid[16] = 0;
10849 printf_filtered ("%s %s\n", title, (&hexid[0]));
10850}
10851
10852static void
fba45db2 10853threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10854{
10855 int startflag = 1;
10856 threadref nextthread;
10857 int done, result_count;
10858 threadref threadlist[3];
10859
10860 printf_filtered ("Remote Threadlist test\n");
10861 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10862 &result_count, &threadlist[0]))
10863 printf_filtered ("FAIL: threadlist test\n");
10864 else
10865 {
10866 threadref *scan = threadlist;
10867 threadref *limit = scan + result_count;
10868
10869 while (scan < limit)
10870 output_threadid (" thread ", scan++);
10871 }
10872}
10873
10874void
fba45db2 10875display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10876{
10877 output_threadid ("Threadid: ", &info->threadid);
10878 printf_filtered ("Name: %s\n ", info->shortname);
10879 printf_filtered ("State: %s\n", info->display);
10880 printf_filtered ("other: %s\n\n", info->more_display);
10881}
10882
10883int
fba45db2 10884get_and_display_threadinfo (threadref *ref)
c906108c
SS
10885{
10886 int result;
10887 int set;
10888 struct gdb_ext_thread_info threadinfo;
10889
10890 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10891 | TAG_MOREDISPLAY | TAG_DISPLAY;
10892 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10893 display_thread_info (&threadinfo);
10894 return result;
10895}
10896
10897static void
fba45db2 10898threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10899{
10900 int athread = SAMPLE_THREAD;
10901 threadref thread;
10902 int set;
10903
10904 int_to_threadref (&thread, athread);
10905 printf_filtered ("Remote Threadinfo test\n");
10906 if (!get_and_display_threadinfo (&thread))
10907 printf_filtered ("FAIL cannot get thread info\n");
10908}
10909
10910static int
fba45db2 10911thread_display_step (threadref *ref, void *context)
c906108c
SS
10912{
10913 /* output_threadid(" threadstep ",ref); *//* simple test */
10914 return get_and_display_threadinfo (ref);
10915}
10916
10917static void
fba45db2 10918threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10919{
10920 printf_filtered ("Remote Threadlist update test\n");
10921 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10922}
10923
10924static void
10925init_remote_threadtests (void)
10926{
3e43a32a
MS
10927 add_com ("tlist", class_obscure, threadlist_test_cmd,
10928 _("Fetch and print the remote list of "
10929 "thread identifiers, one pkt only"));
c906108c 10930 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10931 _("Fetch and display info about one thread"));
c906108c 10932 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10933 _("Test setting to a different thread"));
c906108c 10934 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10935 _("Iterate through updating all remote thread info"));
c906108c 10936 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10937 _(" Remote thread alive test "));
c906108c
SS
10938}
10939
10940#endif /* 0 */
10941
f3fb8c85
MS
10942/* Convert a thread ID to a string. Returns the string in a static
10943 buffer. */
10944
10945static char *
117de6a9 10946remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10947{
79d7f229 10948 static char buf[64];
82f73884 10949 struct remote_state *rs = get_remote_state ();
f3fb8c85 10950
7cee1e54
PA
10951 if (ptid_equal (ptid, null_ptid))
10952 return normal_pid_to_str (ptid);
10953 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10954 {
10955 /* Printing an inferior target id. */
10956
10957 /* When multi-process extensions are off, there's no way in the
10958 remote protocol to know the remote process id, if there's any
10959 at all. There's one exception --- when we're connected with
10960 target extended-remote, and we manually attached to a process
10961 with "attach PID". We don't record anywhere a flag that
10962 allows us to distinguish that case from the case of
10963 connecting with extended-remote and the stub already being
10964 attached to a process, and reporting yes to qAttached, hence
10965 no smart special casing here. */
10966 if (!remote_multi_process_p (rs))
10967 {
10968 xsnprintf (buf, sizeof buf, "Remote target");
10969 return buf;
10970 }
10971
10972 return normal_pid_to_str (ptid);
82f73884 10973 }
ecd0ada5 10974 else
79d7f229 10975 {
ecd0ada5
PA
10976 if (ptid_equal (magic_null_ptid, ptid))
10977 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 10978 else if (remote_multi_process_p (rs))
de0d863e
DB
10979 if (ptid_get_lwp (ptid) == 0)
10980 return normal_pid_to_str (ptid);
10981 else
10982 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10983 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10984 else
10985 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10986 ptid_get_lwp (ptid));
79d7f229
PA
10987 return buf;
10988 }
f3fb8c85
MS
10989}
10990
38691318
KB
10991/* Get the address of the thread local variable in OBJFILE which is
10992 stored at OFFSET within the thread local storage for thread PTID. */
10993
10994static CORE_ADDR
117de6a9
PA
10995remote_get_thread_local_address (struct target_ops *ops,
10996 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10997{
4082afcc 10998 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10999 {
11000 struct remote_state *rs = get_remote_state ();
6d820c5c 11001 char *p = rs->buf;
82f73884 11002 char *endp = rs->buf + get_remote_packet_size ();
571dd617 11003 enum packet_result result;
38691318
KB
11004
11005 strcpy (p, "qGetTLSAddr:");
11006 p += strlen (p);
82f73884 11007 p = write_ptid (p, endp, ptid);
38691318
KB
11008 *p++ = ',';
11009 p += hexnumstr (p, offset);
11010 *p++ = ',';
11011 p += hexnumstr (p, lm);
11012 *p++ = '\0';
11013
6d820c5c
DJ
11014 putpkt (rs->buf);
11015 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
11016 result = packet_ok (rs->buf,
11017 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 11018 if (result == PACKET_OK)
38691318
KB
11019 {
11020 ULONGEST result;
11021
6d820c5c 11022 unpack_varlen_hex (rs->buf, &result);
38691318
KB
11023 return result;
11024 }
571dd617 11025 else if (result == PACKET_UNKNOWN)
109c3e39
AC
11026 throw_error (TLS_GENERIC_ERROR,
11027 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 11028 else
109c3e39
AC
11029 throw_error (TLS_GENERIC_ERROR,
11030 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
11031 }
11032 else
109c3e39
AC
11033 throw_error (TLS_GENERIC_ERROR,
11034 _("TLS not supported or disabled on this target"));
38691318
KB
11035 /* Not reached. */
11036 return 0;
11037}
11038
711e434b
PM
11039/* Provide thread local base, i.e. Thread Information Block address.
11040 Returns 1 if ptid is found and thread_local_base is non zero. */
11041
70221824 11042static int
bd7ae0f5 11043remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 11044{
4082afcc 11045 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
11046 {
11047 struct remote_state *rs = get_remote_state ();
11048 char *p = rs->buf;
11049 char *endp = rs->buf + get_remote_packet_size ();
11050 enum packet_result result;
11051
11052 strcpy (p, "qGetTIBAddr:");
11053 p += strlen (p);
11054 p = write_ptid (p, endp, ptid);
11055 *p++ = '\0';
11056
11057 putpkt (rs->buf);
11058 getpkt (&rs->buf, &rs->buf_size, 0);
11059 result = packet_ok (rs->buf,
11060 &remote_protocol_packets[PACKET_qGetTIBAddr]);
11061 if (result == PACKET_OK)
11062 {
11063 ULONGEST result;
11064
11065 unpack_varlen_hex (rs->buf, &result);
11066 if (addr)
11067 *addr = (CORE_ADDR) result;
11068 return 1;
11069 }
11070 else if (result == PACKET_UNKNOWN)
11071 error (_("Remote target doesn't support qGetTIBAddr packet"));
11072 else
11073 error (_("Remote target failed to process qGetTIBAddr request"));
11074 }
11075 else
11076 error (_("qGetTIBAddr not supported or disabled on this target"));
11077 /* Not reached. */
11078 return 0;
11079}
11080
29709017
DJ
11081/* Support for inferring a target description based on the current
11082 architecture and the size of a 'g' packet. While the 'g' packet
11083 can have any size (since optional registers can be left off the
11084 end), some sizes are easily recognizable given knowledge of the
11085 approximate architecture. */
11086
11087struct remote_g_packet_guess
11088{
11089 int bytes;
11090 const struct target_desc *tdesc;
11091};
11092typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11093DEF_VEC_O(remote_g_packet_guess_s);
11094
11095struct remote_g_packet_data
11096{
11097 VEC(remote_g_packet_guess_s) *guesses;
11098};
11099
11100static struct gdbarch_data *remote_g_packet_data_handle;
11101
11102static void *
11103remote_g_packet_data_init (struct obstack *obstack)
11104{
11105 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11106}
11107
11108void
11109register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11110 const struct target_desc *tdesc)
11111{
11112 struct remote_g_packet_data *data
19ba03f4
SM
11113 = ((struct remote_g_packet_data *)
11114 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
11115 struct remote_g_packet_guess new_guess, *guess;
11116 int ix;
11117
11118 gdb_assert (tdesc != NULL);
11119
11120 for (ix = 0;
11121 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11122 ix++)
11123 if (guess->bytes == bytes)
11124 internal_error (__FILE__, __LINE__,
9b20d036 11125 _("Duplicate g packet description added for size %d"),
29709017
DJ
11126 bytes);
11127
11128 new_guess.bytes = bytes;
11129 new_guess.tdesc = tdesc;
11130 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11131}
11132
d962ef82
DJ
11133/* Return 1 if remote_read_description would do anything on this target
11134 and architecture, 0 otherwise. */
11135
11136static int
11137remote_read_description_p (struct target_ops *target)
11138{
11139 struct remote_g_packet_data *data
19ba03f4
SM
11140 = ((struct remote_g_packet_data *)
11141 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
11142
11143 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11144 return 1;
11145
11146 return 0;
11147}
11148
29709017
DJ
11149static const struct target_desc *
11150remote_read_description (struct target_ops *target)
11151{
11152 struct remote_g_packet_data *data
19ba03f4
SM
11153 = ((struct remote_g_packet_data *)
11154 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 11155
d962ef82
DJ
11156 /* Do not try this during initial connection, when we do not know
11157 whether there is a running but stopped thread. */
11158 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 11159 return target->beneath->to_read_description (target->beneath);
d962ef82 11160
29709017
DJ
11161 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11162 {
11163 struct remote_g_packet_guess *guess;
11164 int ix;
11165 int bytes = send_g_packet ();
11166
11167 for (ix = 0;
11168 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11169 ix++)
11170 if (guess->bytes == bytes)
11171 return guess->tdesc;
11172
11173 /* We discard the g packet. A minor optimization would be to
11174 hold on to it, and fill the register cache once we have selected
11175 an architecture, but it's too tricky to do safely. */
11176 }
11177
2117c711 11178 return target->beneath->to_read_description (target->beneath);
29709017
DJ
11179}
11180
a6b151f1
DJ
11181/* Remote file transfer support. This is host-initiated I/O, not
11182 target-initiated; for target-initiated, see remote-fileio.c. */
11183
11184/* If *LEFT is at least the length of STRING, copy STRING to
11185 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11186 decrease *LEFT. Otherwise raise an error. */
11187
11188static void
11189remote_buffer_add_string (char **buffer, int *left, char *string)
11190{
11191 int len = strlen (string);
11192
11193 if (len > *left)
11194 error (_("Packet too long for target."));
11195
11196 memcpy (*buffer, string, len);
11197 *buffer += len;
11198 *left -= len;
11199
11200 /* NUL-terminate the buffer as a convenience, if there is
11201 room. */
11202 if (*left)
11203 **buffer = '\0';
11204}
11205
11206/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11207 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11208 decrease *LEFT. Otherwise raise an error. */
11209
11210static void
11211remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11212 int len)
11213{
11214 if (2 * len > *left)
11215 error (_("Packet too long for target."));
11216
11217 bin2hex (bytes, *buffer, len);
11218 *buffer += 2 * len;
11219 *left -= 2 * len;
11220
11221 /* NUL-terminate the buffer as a convenience, if there is
11222 room. */
11223 if (*left)
11224 **buffer = '\0';
11225}
11226
11227/* If *LEFT is large enough, convert VALUE to hex and add it to
11228 *BUFFER, update *BUFFER to point to the new end of the buffer, and
11229 decrease *LEFT. Otherwise raise an error. */
11230
11231static void
11232remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11233{
11234 int len = hexnumlen (value);
11235
11236 if (len > *left)
11237 error (_("Packet too long for target."));
11238
11239 hexnumstr (*buffer, value);
11240 *buffer += len;
11241 *left -= len;
11242
11243 /* NUL-terminate the buffer as a convenience, if there is
11244 room. */
11245 if (*left)
11246 **buffer = '\0';
11247}
11248
11249/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
11250 value, *REMOTE_ERRNO to the remote error number or zero if none
11251 was included, and *ATTACHMENT to point to the start of the annex
11252 if any. The length of the packet isn't needed here; there may
11253 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11254
11255 Return 0 if the packet could be parsed, -1 if it could not. If
11256 -1 is returned, the other variables may not be initialized. */
11257
11258static int
11259remote_hostio_parse_result (char *buffer, int *retcode,
11260 int *remote_errno, char **attachment)
11261{
11262 char *p, *p2;
11263
11264 *remote_errno = 0;
11265 *attachment = NULL;
11266
11267 if (buffer[0] != 'F')
11268 return -1;
11269
11270 errno = 0;
11271 *retcode = strtol (&buffer[1], &p, 16);
11272 if (errno != 0 || p == &buffer[1])
11273 return -1;
11274
11275 /* Check for ",errno". */
11276 if (*p == ',')
11277 {
11278 errno = 0;
11279 *remote_errno = strtol (p + 1, &p2, 16);
11280 if (errno != 0 || p + 1 == p2)
11281 return -1;
11282 p = p2;
11283 }
11284
11285 /* Check for ";attachment". If there is no attachment, the
11286 packet should end here. */
11287 if (*p == ';')
11288 {
11289 *attachment = p + 1;
11290 return 0;
11291 }
11292 else if (*p == '\0')
11293 return 0;
11294 else
11295 return -1;
11296}
11297
11298/* Send a prepared I/O packet to the target and read its response.
11299 The prepared packet is in the global RS->BUF before this function
11300 is called, and the answer is there when we return.
11301
11302 COMMAND_BYTES is the length of the request to send, which may include
11303 binary data. WHICH_PACKET is the packet configuration to check
11304 before attempting a packet. If an error occurs, *REMOTE_ERRNO
11305 is set to the error number and -1 is returned. Otherwise the value
11306 returned by the function is returned.
11307
11308 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11309 attachment is expected; an error will be reported if there's a
11310 mismatch. If one is found, *ATTACHMENT will be set to point into
11311 the packet buffer and *ATTACHMENT_LEN will be set to the
11312 attachment's length. */
11313
11314static int
11315remote_hostio_send_command (int command_bytes, int which_packet,
11316 int *remote_errno, char **attachment,
11317 int *attachment_len)
11318{
11319 struct remote_state *rs = get_remote_state ();
11320 int ret, bytes_read;
11321 char *attachment_tmp;
11322
5d93a237 11323 if (!rs->remote_desc
4082afcc 11324 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
11325 {
11326 *remote_errno = FILEIO_ENOSYS;
11327 return -1;
11328 }
11329
11330 putpkt_binary (rs->buf, command_bytes);
11331 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11332
11333 /* If it timed out, something is wrong. Don't try to parse the
11334 buffer. */
11335 if (bytes_read < 0)
11336 {
11337 *remote_errno = FILEIO_EINVAL;
11338 return -1;
11339 }
11340
11341 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11342 {
11343 case PACKET_ERROR:
11344 *remote_errno = FILEIO_EINVAL;
11345 return -1;
11346 case PACKET_UNKNOWN:
11347 *remote_errno = FILEIO_ENOSYS;
11348 return -1;
11349 case PACKET_OK:
11350 break;
11351 }
11352
11353 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11354 &attachment_tmp))
11355 {
11356 *remote_errno = FILEIO_EINVAL;
11357 return -1;
11358 }
11359
11360 /* Make sure we saw an attachment if and only if we expected one. */
11361 if ((attachment_tmp == NULL && attachment != NULL)
11362 || (attachment_tmp != NULL && attachment == NULL))
11363 {
11364 *remote_errno = FILEIO_EINVAL;
11365 return -1;
11366 }
11367
11368 /* If an attachment was found, it must point into the packet buffer;
11369 work out how many bytes there were. */
11370 if (attachment_tmp != NULL)
11371 {
11372 *attachment = attachment_tmp;
11373 *attachment_len = bytes_read - (*attachment - rs->buf);
11374 }
11375
11376 return ret;
11377}
11378
80152258
PA
11379/* Invalidate the readahead cache. */
11380
11381static void
11382readahead_cache_invalidate (void)
11383{
11384 struct remote_state *rs = get_remote_state ();
11385
11386 rs->readahead_cache.fd = -1;
11387}
11388
11389/* Invalidate the readahead cache if it is holding data for FD. */
11390
11391static void
11392readahead_cache_invalidate_fd (int fd)
11393{
11394 struct remote_state *rs = get_remote_state ();
11395
11396 if (rs->readahead_cache.fd == fd)
11397 rs->readahead_cache.fd = -1;
11398}
11399
15a201c8
GB
11400/* Set the filesystem remote_hostio functions that take FILENAME
11401 arguments will use. Return 0 on success, or -1 if an error
11402 occurs (and set *REMOTE_ERRNO). */
11403
11404static int
11405remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11406{
11407 struct remote_state *rs = get_remote_state ();
11408 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11409 char *p = rs->buf;
11410 int left = get_remote_packet_size () - 1;
11411 char arg[9];
11412 int ret;
11413
11414 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11415 return 0;
11416
11417 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11418 return 0;
11419
11420 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11421
11422 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11423 remote_buffer_add_string (&p, &left, arg);
11424
11425 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11426 remote_errno, NULL, NULL);
11427
11428 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11429 return 0;
11430
11431 if (ret == 0)
11432 rs->fs_pid = required_pid;
11433
11434 return ret;
11435}
11436
12e2a5fd 11437/* Implementation of to_fileio_open. */
a6b151f1
DJ
11438
11439static int
cd897586 11440remote_hostio_open (struct target_ops *self,
07c138c8 11441 struct inferior *inf, const char *filename,
4313b8c0
GB
11442 int flags, int mode, int warn_if_slow,
11443 int *remote_errno)
a6b151f1
DJ
11444{
11445 struct remote_state *rs = get_remote_state ();
11446 char *p = rs->buf;
11447 int left = get_remote_packet_size () - 1;
11448
4313b8c0
GB
11449 if (warn_if_slow)
11450 {
11451 static int warning_issued = 0;
11452
11453 printf_unfiltered (_("Reading %s from remote target...\n"),
11454 filename);
11455
11456 if (!warning_issued)
11457 {
11458 warning (_("File transfers from remote targets can be slow."
11459 " Use \"set sysroot\" to access files locally"
11460 " instead."));
11461 warning_issued = 1;
11462 }
11463 }
11464
15a201c8
GB
11465 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11466 return -1;
11467
a6b151f1
DJ
11468 remote_buffer_add_string (&p, &left, "vFile:open:");
11469
11470 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11471 strlen (filename));
11472 remote_buffer_add_string (&p, &left, ",");
11473
11474 remote_buffer_add_int (&p, &left, flags);
11475 remote_buffer_add_string (&p, &left, ",");
11476
11477 remote_buffer_add_int (&p, &left, mode);
11478
11479 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11480 remote_errno, NULL, NULL);
11481}
11482
12e2a5fd 11483/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11484
11485static int
0d866f62
TT
11486remote_hostio_pwrite (struct target_ops *self,
11487 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11488 ULONGEST offset, int *remote_errno)
11489{
11490 struct remote_state *rs = get_remote_state ();
11491 char *p = rs->buf;
11492 int left = get_remote_packet_size ();
11493 int out_len;
11494
80152258
PA
11495 readahead_cache_invalidate_fd (fd);
11496
a6b151f1
DJ
11497 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11498
11499 remote_buffer_add_int (&p, &left, fd);
11500 remote_buffer_add_string (&p, &left, ",");
11501
11502 remote_buffer_add_int (&p, &left, offset);
11503 remote_buffer_add_string (&p, &left, ",");
11504
124e13d9 11505 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11506 get_remote_packet_size () - (p - rs->buf));
11507
11508 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11509 remote_errno, NULL, NULL);
11510}
11511
80152258
PA
11512/* Helper for the implementation of to_fileio_pread. Read the file
11513 from the remote side with vFile:pread. */
a6b151f1
DJ
11514
11515static int
80152258
PA
11516remote_hostio_pread_vFile (struct target_ops *self,
11517 int fd, gdb_byte *read_buf, int len,
11518 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11519{
11520 struct remote_state *rs = get_remote_state ();
11521 char *p = rs->buf;
11522 char *attachment;
11523 int left = get_remote_packet_size ();
11524 int ret, attachment_len;
11525 int read_len;
11526
11527 remote_buffer_add_string (&p, &left, "vFile:pread:");
11528
11529 remote_buffer_add_int (&p, &left, fd);
11530 remote_buffer_add_string (&p, &left, ",");
11531
11532 remote_buffer_add_int (&p, &left, len);
11533 remote_buffer_add_string (&p, &left, ",");
11534
11535 remote_buffer_add_int (&p, &left, offset);
11536
11537 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11538 remote_errno, &attachment,
11539 &attachment_len);
11540
11541 if (ret < 0)
11542 return ret;
11543
bc20a4af 11544 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11545 read_buf, len);
11546 if (read_len != ret)
11547 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11548
11549 return ret;
11550}
11551
80152258
PA
11552/* Serve pread from the readahead cache. Returns number of bytes
11553 read, or 0 if the request can't be served from the cache. */
11554
11555static int
11556remote_hostio_pread_from_cache (struct remote_state *rs,
11557 int fd, gdb_byte *read_buf, size_t len,
11558 ULONGEST offset)
11559{
11560 struct readahead_cache *cache = &rs->readahead_cache;
11561
11562 if (cache->fd == fd
11563 && cache->offset <= offset
11564 && offset < cache->offset + cache->bufsize)
11565 {
11566 ULONGEST max = cache->offset + cache->bufsize;
11567
11568 if (offset + len > max)
11569 len = max - offset;
11570
11571 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11572 return len;
11573 }
11574
11575 return 0;
11576}
11577
11578/* Implementation of to_fileio_pread. */
11579
11580static int
11581remote_hostio_pread (struct target_ops *self,
11582 int fd, gdb_byte *read_buf, int len,
11583 ULONGEST offset, int *remote_errno)
11584{
11585 int ret;
11586 struct remote_state *rs = get_remote_state ();
11587 struct readahead_cache *cache = &rs->readahead_cache;
11588
11589 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11590 if (ret > 0)
11591 {
11592 cache->hit_count++;
11593
11594 if (remote_debug)
11595 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11596 pulongest (cache->hit_count));
11597 return ret;
11598 }
11599
11600 cache->miss_count++;
11601 if (remote_debug)
11602 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11603 pulongest (cache->miss_count));
11604
11605 cache->fd = fd;
11606 cache->offset = offset;
11607 cache->bufsize = get_remote_packet_size ();
224c3ddb 11608 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11609
11610 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11611 cache->offset, remote_errno);
11612 if (ret <= 0)
11613 {
11614 readahead_cache_invalidate_fd (fd);
11615 return ret;
11616 }
11617
11618 cache->bufsize = ret;
11619 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11620}
11621
12e2a5fd 11622/* Implementation of to_fileio_close. */
a6b151f1
DJ
11623
11624static int
df39ea25 11625remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11626{
11627 struct remote_state *rs = get_remote_state ();
11628 char *p = rs->buf;
11629 int left = get_remote_packet_size () - 1;
11630
80152258
PA
11631 readahead_cache_invalidate_fd (fd);
11632
a6b151f1
DJ
11633 remote_buffer_add_string (&p, &left, "vFile:close:");
11634
11635 remote_buffer_add_int (&p, &left, fd);
11636
11637 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11638 remote_errno, NULL, NULL);
11639}
11640
12e2a5fd 11641/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11642
11643static int
dbbca37d 11644remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11645 struct inferior *inf, const char *filename,
11646 int *remote_errno)
a6b151f1
DJ
11647{
11648 struct remote_state *rs = get_remote_state ();
11649 char *p = rs->buf;
11650 int left = get_remote_packet_size () - 1;
11651
15a201c8
GB
11652 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11653 return -1;
11654
a6b151f1
DJ
11655 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11656
11657 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11658 strlen (filename));
11659
11660 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11661 remote_errno, NULL, NULL);
11662}
11663
12e2a5fd 11664/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11665
11666static char *
fab5aa7c 11667remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11668 struct inferior *inf, const char *filename,
11669 int *remote_errno)
b9e7b9c3
UW
11670{
11671 struct remote_state *rs = get_remote_state ();
11672 char *p = rs->buf;
11673 char *attachment;
11674 int left = get_remote_packet_size ();
11675 int len, attachment_len;
11676 int read_len;
11677 char *ret;
11678
15a201c8
GB
11679 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11680 return NULL;
11681
b9e7b9c3
UW
11682 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11683
11684 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11685 strlen (filename));
11686
11687 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11688 remote_errno, &attachment,
11689 &attachment_len);
11690
11691 if (len < 0)
11692 return NULL;
11693
224c3ddb 11694 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11695
bc20a4af
PA
11696 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11697 (gdb_byte *) ret, len);
b9e7b9c3
UW
11698 if (read_len != len)
11699 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11700
11701 ret[len] = '\0';
11702 return ret;
11703}
11704
12e2a5fd 11705/* Implementation of to_fileio_fstat. */
0a93529c
GB
11706
11707static int
11708remote_hostio_fstat (struct target_ops *self,
11709 int fd, struct stat *st,
11710 int *remote_errno)
11711{
11712 struct remote_state *rs = get_remote_state ();
11713 char *p = rs->buf;
11714 int left = get_remote_packet_size ();
11715 int attachment_len, ret;
11716 char *attachment;
11717 struct fio_stat fst;
11718 int read_len;
11719
464b0089
GB
11720 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11721
11722 remote_buffer_add_int (&p, &left, fd);
11723
11724 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11725 remote_errno, &attachment,
11726 &attachment_len);
11727 if (ret < 0)
0a93529c 11728 {
464b0089
GB
11729 if (*remote_errno != FILEIO_ENOSYS)
11730 return ret;
11731
0a93529c
GB
11732 /* Strictly we should return -1, ENOSYS here, but when
11733 "set sysroot remote:" was implemented in August 2008
11734 BFD's need for a stat function was sidestepped with
11735 this hack. This was not remedied until March 2015
11736 so we retain the previous behavior to avoid breaking
11737 compatibility.
11738
11739 Note that the memset is a March 2015 addition; older
11740 GDBs set st_size *and nothing else* so the structure
11741 would have garbage in all other fields. This might
11742 break something but retaining the previous behavior
11743 here would be just too wrong. */
11744
11745 memset (st, 0, sizeof (struct stat));
11746 st->st_size = INT_MAX;
11747 return 0;
11748 }
11749
0a93529c
GB
11750 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11751 (gdb_byte *) &fst, sizeof (fst));
11752
11753 if (read_len != ret)
11754 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11755
11756 if (read_len != sizeof (fst))
11757 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11758 read_len, (int) sizeof (fst));
11759
11760 remote_fileio_to_host_stat (&fst, st);
11761
11762 return 0;
11763}
11764
12e2a5fd 11765/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11766
11767static int
11768remote_filesystem_is_local (struct target_ops *self)
11769{
11770 /* Valgrind GDB presents itself as a remote target but works
11771 on the local filesystem: it does not implement remote get
11772 and users are not expected to set a sysroot. To handle
11773 this case we treat the remote filesystem as local if the
11774 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11775 does not support vFile:open. */
a3be80c3 11776 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11777 {
11778 enum packet_support ps = packet_support (PACKET_vFile_open);
11779
11780 if (ps == PACKET_SUPPORT_UNKNOWN)
11781 {
11782 int fd, remote_errno;
11783
11784 /* Try opening a file to probe support. The supplied
11785 filename is irrelevant, we only care about whether
11786 the stub recognizes the packet or not. */
07c138c8 11787 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11788 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11789 &remote_errno);
11790
11791 if (fd >= 0)
11792 remote_hostio_close (self, fd, &remote_errno);
11793
11794 ps = packet_support (PACKET_vFile_open);
11795 }
11796
11797 if (ps == PACKET_DISABLE)
11798 {
11799 static int warning_issued = 0;
11800
11801 if (!warning_issued)
11802 {
11803 warning (_("remote target does not support file"
11804 " transfer, attempting to access files"
11805 " from local filesystem."));
11806 warning_issued = 1;
11807 }
11808
11809 return 1;
11810 }
11811 }
11812
11813 return 0;
11814}
11815
a6b151f1
DJ
11816static int
11817remote_fileio_errno_to_host (int errnum)
11818{
11819 switch (errnum)
11820 {
11821 case FILEIO_EPERM:
11822 return EPERM;
11823 case FILEIO_ENOENT:
11824 return ENOENT;
11825 case FILEIO_EINTR:
11826 return EINTR;
11827 case FILEIO_EIO:
11828 return EIO;
11829 case FILEIO_EBADF:
11830 return EBADF;
11831 case FILEIO_EACCES:
11832 return EACCES;
11833 case FILEIO_EFAULT:
11834 return EFAULT;
11835 case FILEIO_EBUSY:
11836 return EBUSY;
11837 case FILEIO_EEXIST:
11838 return EEXIST;
11839 case FILEIO_ENODEV:
11840 return ENODEV;
11841 case FILEIO_ENOTDIR:
11842 return ENOTDIR;
11843 case FILEIO_EISDIR:
11844 return EISDIR;
11845 case FILEIO_EINVAL:
11846 return EINVAL;
11847 case FILEIO_ENFILE:
11848 return ENFILE;
11849 case FILEIO_EMFILE:
11850 return EMFILE;
11851 case FILEIO_EFBIG:
11852 return EFBIG;
11853 case FILEIO_ENOSPC:
11854 return ENOSPC;
11855 case FILEIO_ESPIPE:
11856 return ESPIPE;
11857 case FILEIO_EROFS:
11858 return EROFS;
11859 case FILEIO_ENOSYS:
11860 return ENOSYS;
11861 case FILEIO_ENAMETOOLONG:
11862 return ENAMETOOLONG;
11863 }
11864 return -1;
11865}
11866
11867static char *
11868remote_hostio_error (int errnum)
11869{
11870 int host_error = remote_fileio_errno_to_host (errnum);
11871
11872 if (host_error == -1)
11873 error (_("Unknown remote I/O error %d"), errnum);
11874 else
11875 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11876}
11877
a6b151f1
DJ
11878static void
11879remote_hostio_close_cleanup (void *opaque)
11880{
11881 int fd = *(int *) opaque;
11882 int remote_errno;
11883
df39ea25 11884 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11885}
11886
11887void
11888remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11889{
11890 struct cleanup *back_to, *close_cleanup;
11891 int retcode, fd, remote_errno, bytes, io_size;
11892 FILE *file;
11893 gdb_byte *buffer;
11894 int bytes_in_buffer;
11895 int saw_eof;
11896 ULONGEST offset;
5d93a237 11897 struct remote_state *rs = get_remote_state ();
a6b151f1 11898
5d93a237 11899 if (!rs->remote_desc)
a6b151f1
DJ
11900 error (_("command can only be used with remote target"));
11901
614c279d 11902 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11903 if (file == NULL)
11904 perror_with_name (local_file);
7c8a8b04 11905 back_to = make_cleanup_fclose (file);
a6b151f1 11906
07c138c8 11907 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11908 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11909 | FILEIO_O_TRUNC),
4313b8c0 11910 0700, 0, &remote_errno);
a6b151f1
DJ
11911 if (fd == -1)
11912 remote_hostio_error (remote_errno);
11913
11914 /* Send up to this many bytes at once. They won't all fit in the
11915 remote packet limit, so we'll transfer slightly fewer. */
11916 io_size = get_remote_packet_size ();
224c3ddb 11917 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11918 make_cleanup (xfree, buffer);
11919
11920 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11921
11922 bytes_in_buffer = 0;
11923 saw_eof = 0;
11924 offset = 0;
11925 while (bytes_in_buffer || !saw_eof)
11926 {
11927 if (!saw_eof)
11928 {
3e43a32a
MS
11929 bytes = fread (buffer + bytes_in_buffer, 1,
11930 io_size - bytes_in_buffer,
a6b151f1
DJ
11931 file);
11932 if (bytes == 0)
11933 {
11934 if (ferror (file))
11935 error (_("Error reading %s."), local_file);
11936 else
11937 {
11938 /* EOF. Unless there is something still in the
11939 buffer from the last iteration, we are done. */
11940 saw_eof = 1;
11941 if (bytes_in_buffer == 0)
11942 break;
11943 }
11944 }
11945 }
11946 else
11947 bytes = 0;
11948
11949 bytes += bytes_in_buffer;
11950 bytes_in_buffer = 0;
11951
0d866f62
TT
11952 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11953 fd, buffer, bytes,
3e43a32a 11954 offset, &remote_errno);
a6b151f1
DJ
11955
11956 if (retcode < 0)
11957 remote_hostio_error (remote_errno);
11958 else if (retcode == 0)
11959 error (_("Remote write of %d bytes returned 0!"), bytes);
11960 else if (retcode < bytes)
11961 {
11962 /* Short write. Save the rest of the read data for the next
11963 write. */
11964 bytes_in_buffer = bytes - retcode;
11965 memmove (buffer, buffer + retcode, bytes_in_buffer);
11966 }
11967
11968 offset += retcode;
11969 }
11970
11971 discard_cleanups (close_cleanup);
df39ea25 11972 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11973 remote_hostio_error (remote_errno);
11974
11975 if (from_tty)
11976 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11977 do_cleanups (back_to);
11978}
11979
11980void
11981remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11982{
11983 struct cleanup *back_to, *close_cleanup;
cea39f65 11984 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11985 FILE *file;
11986 gdb_byte *buffer;
11987 ULONGEST offset;
5d93a237 11988 struct remote_state *rs = get_remote_state ();
a6b151f1 11989
5d93a237 11990 if (!rs->remote_desc)
a6b151f1
DJ
11991 error (_("command can only be used with remote target"));
11992
07c138c8 11993 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11994 remote_file, FILEIO_O_RDONLY, 0, 0,
11995 &remote_errno);
a6b151f1
DJ
11996 if (fd == -1)
11997 remote_hostio_error (remote_errno);
11998
614c279d 11999 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
12000 if (file == NULL)
12001 perror_with_name (local_file);
7c8a8b04 12002 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
12003
12004 /* Send up to this many bytes at once. They won't all fit in the
12005 remote packet limit, so we'll transfer slightly fewer. */
12006 io_size = get_remote_packet_size ();
224c3ddb 12007 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
12008 make_cleanup (xfree, buffer);
12009
12010 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12011
12012 offset = 0;
12013 while (1)
12014 {
a3be983c
TT
12015 bytes = remote_hostio_pread (find_target_at (process_stratum),
12016 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
12017 if (bytes == 0)
12018 /* Success, but no bytes, means end-of-file. */
12019 break;
12020 if (bytes == -1)
12021 remote_hostio_error (remote_errno);
12022
12023 offset += bytes;
12024
12025 bytes = fwrite (buffer, 1, bytes, file);
12026 if (bytes == 0)
12027 perror_with_name (local_file);
12028 }
12029
12030 discard_cleanups (close_cleanup);
df39ea25 12031 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
12032 remote_hostio_error (remote_errno);
12033
12034 if (from_tty)
12035 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12036 do_cleanups (back_to);
12037}
12038
12039void
12040remote_file_delete (const char *remote_file, int from_tty)
12041{
12042 int retcode, remote_errno;
5d93a237 12043 struct remote_state *rs = get_remote_state ();
a6b151f1 12044
5d93a237 12045 if (!rs->remote_desc)
a6b151f1
DJ
12046 error (_("command can only be used with remote target"));
12047
dbbca37d 12048 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 12049 NULL, remote_file, &remote_errno);
a6b151f1
DJ
12050 if (retcode == -1)
12051 remote_hostio_error (remote_errno);
12052
12053 if (from_tty)
12054 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12055}
12056
12057static void
12058remote_put_command (char *args, int from_tty)
12059{
12060 struct cleanup *back_to;
12061 char **argv;
12062
d1a41061
PP
12063 if (args == NULL)
12064 error_no_arg (_("file to put"));
12065
12066 argv = gdb_buildargv (args);
a6b151f1
DJ
12067 back_to = make_cleanup_freeargv (argv);
12068 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12069 error (_("Invalid parameters to remote put"));
12070
12071 remote_file_put (argv[0], argv[1], from_tty);
12072
12073 do_cleanups (back_to);
12074}
12075
12076static void
12077remote_get_command (char *args, int from_tty)
12078{
12079 struct cleanup *back_to;
12080 char **argv;
12081
d1a41061
PP
12082 if (args == NULL)
12083 error_no_arg (_("file to get"));
12084
12085 argv = gdb_buildargv (args);
a6b151f1
DJ
12086 back_to = make_cleanup_freeargv (argv);
12087 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12088 error (_("Invalid parameters to remote get"));
12089
12090 remote_file_get (argv[0], argv[1], from_tty);
12091
12092 do_cleanups (back_to);
12093}
12094
12095static void
12096remote_delete_command (char *args, int from_tty)
12097{
12098 struct cleanup *back_to;
12099 char **argv;
12100
d1a41061
PP
12101 if (args == NULL)
12102 error_no_arg (_("file to delete"));
12103
12104 argv = gdb_buildargv (args);
a6b151f1
DJ
12105 back_to = make_cleanup_freeargv (argv);
12106 if (argv[0] == NULL || argv[1] != NULL)
12107 error (_("Invalid parameters to remote delete"));
12108
12109 remote_file_delete (argv[0], from_tty);
12110
12111 do_cleanups (back_to);
12112}
12113
12114static void
12115remote_command (char *args, int from_tty)
12116{
635c7e8a 12117 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
12118}
12119
b2175913 12120static int
19db3e69 12121remote_can_execute_reverse (struct target_ops *self)
b2175913 12122{
4082afcc
PA
12123 if (packet_support (PACKET_bs) == PACKET_ENABLE
12124 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
12125 return 1;
12126 else
12127 return 0;
b2175913
MS
12128}
12129
74531fed 12130static int
2a9a2795 12131remote_supports_non_stop (struct target_ops *self)
74531fed
PA
12132{
12133 return 1;
12134}
12135
03583c20 12136static int
2bfc0540 12137remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
12138{
12139 /* Only supported in extended mode. */
12140 return 0;
12141}
12142
8a305172 12143static int
86ce2668 12144remote_supports_multi_process (struct target_ops *self)
8a305172
PA
12145{
12146 struct remote_state *rs = get_remote_state ();
a744cf53 12147
8020350c 12148 return remote_multi_process_p (rs);
8a305172
PA
12149}
12150
70221824 12151static int
782b2b07
SS
12152remote_supports_cond_tracepoints (void)
12153{
4082afcc 12154 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
12155}
12156
3788aec7 12157static int
efcc2da7 12158remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 12159{
4082afcc 12160 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
12161}
12162
70221824 12163static int
7a697b8d
SS
12164remote_supports_fast_tracepoints (void)
12165{
4082afcc 12166 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
12167}
12168
0fb4aa4b
PA
12169static int
12170remote_supports_static_tracepoints (void)
12171{
4082afcc 12172 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
12173}
12174
1e4d1764
YQ
12175static int
12176remote_supports_install_in_trace (void)
12177{
4082afcc 12178 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
12179}
12180
d248b706 12181static int
7d178d6a 12182remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 12183{
4082afcc
PA
12184 return (packet_support (PACKET_EnableDisableTracepoints_feature)
12185 == PACKET_ENABLE);
d248b706
KY
12186}
12187
3065dfb6 12188static int
6de37a3a 12189remote_supports_string_tracing (struct target_ops *self)
3065dfb6 12190{
4082afcc 12191 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
12192}
12193
d3ce09f5 12194static int
78eff0ec 12195remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 12196{
4082afcc 12197 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
12198}
12199
35b1e5cc 12200static void
ecae04e1 12201remote_trace_init (struct target_ops *self)
35b1e5cc
SS
12202{
12203 putpkt ("QTinit");
12204 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 12205 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12206 error (_("Target does not support this command."));
12207}
12208
12209static void free_actions_list (char **actions_list);
12210static void free_actions_list_cleanup_wrapper (void *);
12211static void
12212free_actions_list_cleanup_wrapper (void *al)
12213{
19ba03f4 12214 free_actions_list ((char **) al);
35b1e5cc
SS
12215}
12216
12217static void
12218free_actions_list (char **actions_list)
12219{
12220 int ndx;
12221
12222 if (actions_list == 0)
12223 return;
12224
12225 for (ndx = 0; actions_list[ndx]; ndx++)
12226 xfree (actions_list[ndx]);
12227
12228 xfree (actions_list);
12229}
12230
409873ef
SS
12231/* Recursive routine to walk through command list including loops, and
12232 download packets for each command. */
12233
12234static void
12235remote_download_command_source (int num, ULONGEST addr,
12236 struct command_line *cmds)
12237{
12238 struct remote_state *rs = get_remote_state ();
12239 struct command_line *cmd;
12240
12241 for (cmd = cmds; cmd; cmd = cmd->next)
12242 {
0df8b418 12243 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12244 strcpy (rs->buf, "QTDPsrc:");
12245 encode_source_string (num, addr, "cmd", cmd->line,
12246 rs->buf + strlen (rs->buf),
12247 rs->buf_size - strlen (rs->buf));
12248 putpkt (rs->buf);
12249 remote_get_noisy_reply (&target_buf, &target_buf_size);
12250 if (strcmp (target_buf, "OK"))
12251 warning (_("Target does not support source download."));
12252
12253 if (cmd->control_type == while_control
12254 || cmd->control_type == while_stepping_control)
12255 {
12256 remote_download_command_source (num, addr, *cmd->body_list);
12257
0df8b418 12258 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
12259 strcpy (rs->buf, "QTDPsrc:");
12260 encode_source_string (num, addr, "cmd", "end",
12261 rs->buf + strlen (rs->buf),
12262 rs->buf_size - strlen (rs->buf));
12263 putpkt (rs->buf);
12264 remote_get_noisy_reply (&target_buf, &target_buf_size);
12265 if (strcmp (target_buf, "OK"))
12266 warning (_("Target does not support source download."));
12267 }
12268 }
12269}
12270
35b1e5cc 12271static void
548f7808 12272remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 12273{
bba74b36 12274#define BUF_SIZE 2048
e8ba3115 12275
35b1e5cc 12276 CORE_ADDR tpaddr;
409873ef 12277 char addrbuf[40];
bba74b36 12278 char buf[BUF_SIZE];
35b1e5cc
SS
12279 char **tdp_actions;
12280 char **stepping_actions;
12281 int ndx;
12282 struct cleanup *old_chain = NULL;
12283 struct agent_expr *aexpr;
12284 struct cleanup *aexpr_chain = NULL;
12285 char *pkt;
e8ba3115 12286 struct breakpoint *b = loc->owner;
d9b3f62e 12287 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 12288
dc673c81 12289 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
12290 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
12291 tdp_actions);
12292 (void) make_cleanup (free_actions_list_cleanup_wrapper,
12293 stepping_actions);
12294
12295 tpaddr = loc->address;
12296 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
12297 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12298 addrbuf, /* address */
12299 (b->enable_state == bp_enabled ? 'E' : 'D'),
12300 t->step_count, t->pass_count);
e8ba3115
YQ
12301 /* Fast tracepoints are mostly handled by the target, but we can
12302 tell the target how big of an instruction block should be moved
12303 around. */
12304 if (b->type == bp_fast_tracepoint)
12305 {
12306 /* Only test for support at download time; we may not know
12307 target capabilities at definition time. */
12308 if (remote_supports_fast_tracepoints ())
35b1e5cc 12309 {
6b940e6a
PL
12310 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12311 NULL))
bba74b36 12312 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 12313 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 12314 else
e8ba3115
YQ
12315 /* If it passed validation at definition but fails now,
12316 something is very wrong. */
12317 internal_error (__FILE__, __LINE__,
12318 _("Fast tracepoint not "
12319 "valid during download"));
35b1e5cc 12320 }
e8ba3115
YQ
12321 else
12322 /* Fast tracepoints are functionally identical to regular
12323 tracepoints, so don't take lack of support as a reason to
12324 give up on the trace run. */
12325 warning (_("Target does not support fast tracepoints, "
12326 "downloading %d as regular tracepoint"), b->number);
12327 }
12328 else if (b->type == bp_static_tracepoint)
12329 {
12330 /* Only test for support at download time; we may not know
12331 target capabilities at definition time. */
12332 if (remote_supports_static_tracepoints ())
0fb4aa4b 12333 {
e8ba3115 12334 struct static_tracepoint_marker marker;
0fb4aa4b 12335
e8ba3115
YQ
12336 if (target_static_tracepoint_marker_at (tpaddr, &marker))
12337 strcat (buf, ":S");
0fb4aa4b 12338 else
e8ba3115 12339 error (_("Static tracepoint not valid during download"));
0fb4aa4b 12340 }
e8ba3115
YQ
12341 else
12342 /* Fast tracepoints are functionally identical to regular
12343 tracepoints, so don't take lack of support as a reason
12344 to give up on the trace run. */
12345 error (_("Target does not support static tracepoints"));
12346 }
12347 /* If the tracepoint has a conditional, make it into an agent
12348 expression and append to the definition. */
12349 if (loc->cond)
12350 {
12351 /* Only test support at download time, we may not know target
12352 capabilities at definition time. */
12353 if (remote_supports_cond_tracepoints ())
35b1e5cc 12354 {
e8ba3115
YQ
12355 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
12356 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
12357 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12358 aexpr->len);
e8ba3115
YQ
12359 pkt = buf + strlen (buf);
12360 for (ndx = 0; ndx < aexpr->len; ++ndx)
12361 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12362 *pkt = '\0';
12363 do_cleanups (aexpr_chain);
35b1e5cc 12364 }
e8ba3115
YQ
12365 else
12366 warning (_("Target does not support conditional tracepoints, "
12367 "ignoring tp %d cond"), b->number);
12368 }
35b1e5cc 12369
d9b3f62e 12370 if (b->commands || *default_collect)
e8ba3115
YQ
12371 strcat (buf, "-");
12372 putpkt (buf);
12373 remote_get_noisy_reply (&target_buf, &target_buf_size);
12374 if (strcmp (target_buf, "OK"))
12375 error (_("Target does not support tracepoints."));
35b1e5cc 12376
e8ba3115
YQ
12377 /* do_single_steps (t); */
12378 if (tdp_actions)
12379 {
12380 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 12381 {
e8ba3115 12382 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
12383 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12384 b->number, addrbuf, /* address */
12385 tdp_actions[ndx],
12386 ((tdp_actions[ndx + 1] || stepping_actions)
12387 ? '-' : 0));
e8ba3115
YQ
12388 putpkt (buf);
12389 remote_get_noisy_reply (&target_buf,
12390 &target_buf_size);
12391 if (strcmp (target_buf, "OK"))
12392 error (_("Error on target while setting tracepoints."));
35b1e5cc 12393 }
e8ba3115
YQ
12394 }
12395 if (stepping_actions)
12396 {
12397 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 12398 {
e8ba3115 12399 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
12400 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12401 b->number, addrbuf, /* address */
12402 ((ndx == 0) ? "S" : ""),
12403 stepping_actions[ndx],
12404 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
12405 putpkt (buf);
12406 remote_get_noisy_reply (&target_buf,
12407 &target_buf_size);
12408 if (strcmp (target_buf, "OK"))
12409 error (_("Error on target while setting tracepoints."));
35b1e5cc 12410 }
e8ba3115 12411 }
409873ef 12412
4082afcc 12413 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 12414 {
f00aae0f 12415 if (b->location != NULL)
409873ef 12416 {
e8ba3115 12417 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
12418 encode_source_string (b->number, loc->address, "at",
12419 event_location_to_string (b->location),
12420 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
12421 putpkt (buf);
12422 remote_get_noisy_reply (&target_buf, &target_buf_size);
12423 if (strcmp (target_buf, "OK"))
12424 warning (_("Target does not support source download."));
409873ef 12425 }
e8ba3115
YQ
12426 if (b->cond_string)
12427 {
12428 strcpy (buf, "QTDPsrc:");
12429 encode_source_string (b->number, loc->address,
12430 "cond", b->cond_string, buf + strlen (buf),
12431 2048 - strlen (buf));
12432 putpkt (buf);
12433 remote_get_noisy_reply (&target_buf, &target_buf_size);
12434 if (strcmp (target_buf, "OK"))
12435 warning (_("Target does not support source download."));
12436 }
12437 remote_download_command_source (b->number, loc->address,
12438 breakpoint_commands (b));
35b1e5cc 12439 }
e8ba3115
YQ
12440
12441 do_cleanups (old_chain);
35b1e5cc
SS
12442}
12443
1e4d1764 12444static int
a52a8357 12445remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 12446{
1e51243a
PA
12447 struct remote_state *rs = get_remote_state ();
12448 struct trace_status *ts;
12449 int status;
12450
12451 /* Don't try to install tracepoints until we've relocated our
12452 symbols, and fetched and merged the target's tracepoint list with
12453 ours. */
12454 if (rs->starting_up)
12455 return 0;
12456
12457 ts = current_trace_status ();
8bd200f1 12458 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
12459
12460 if (status == -1 || !ts->running_known || !ts->running)
12461 return 0;
12462
12463 /* If we are in a tracing experiment, but remote stub doesn't support
12464 installing tracepoint in trace, we have to return. */
12465 if (!remote_supports_install_in_trace ())
12466 return 0;
12467
12468 return 1;
12469}
12470
12471
35b1e5cc 12472static void
559d2b81
TT
12473remote_download_trace_state_variable (struct target_ops *self,
12474 struct trace_state_variable *tsv)
35b1e5cc
SS
12475{
12476 struct remote_state *rs = get_remote_state ();
00bf0b85 12477 char *p;
35b1e5cc 12478
bba74b36
YQ
12479 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12480 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12481 tsv->builtin);
00bf0b85
SS
12482 p = rs->buf + strlen (rs->buf);
12483 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12484 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 12485 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 12486 *p++ = '\0';
35b1e5cc
SS
12487 putpkt (rs->buf);
12488 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12489 if (*target_buf == '\0')
12490 error (_("Target does not support this command."));
12491 if (strcmp (target_buf, "OK") != 0)
12492 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12493}
12494
d248b706 12495static void
46670d57
TT
12496remote_enable_tracepoint (struct target_ops *self,
12497 struct bp_location *location)
d248b706
KY
12498{
12499 struct remote_state *rs = get_remote_state ();
12500 char addr_buf[40];
12501
12502 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12503 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12504 location->owner->number, addr_buf);
d248b706
KY
12505 putpkt (rs->buf);
12506 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12507 if (*rs->buf == '\0')
12508 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12509 if (strcmp (rs->buf, "OK") != 0)
12510 error (_("Error on target while enabling tracepoint."));
12511}
12512
12513static void
780b049c
TT
12514remote_disable_tracepoint (struct target_ops *self,
12515 struct bp_location *location)
d248b706
KY
12516{
12517 struct remote_state *rs = get_remote_state ();
12518 char addr_buf[40];
12519
12520 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12521 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12522 location->owner->number, addr_buf);
d248b706
KY
12523 putpkt (rs->buf);
12524 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12525 if (*rs->buf == '\0')
12526 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12527 if (strcmp (rs->buf, "OK") != 0)
12528 error (_("Error on target while disabling tracepoint."));
12529}
12530
35b1e5cc 12531static void
583f9a86 12532remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12533{
12534 asection *s;
81b9b86e 12535 bfd *abfd = NULL;
35b1e5cc 12536 bfd_size_type size;
608bcef2 12537 bfd_vma vma;
35b1e5cc 12538 int anysecs = 0;
c2fa21f1 12539 int offset = 0;
35b1e5cc
SS
12540
12541 if (!exec_bfd)
12542 return; /* No information to give. */
12543
12544 strcpy (target_buf, "QTro");
9779ab84 12545 offset = strlen (target_buf);
35b1e5cc
SS
12546 for (s = exec_bfd->sections; s; s = s->next)
12547 {
12548 char tmp1[40], tmp2[40];
c2fa21f1 12549 int sec_length;
35b1e5cc
SS
12550
12551 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12552 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12553 (s->flags & SEC_READONLY) == 0)
12554 continue;
12555
12556 anysecs = 1;
81b9b86e 12557 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12558 size = bfd_get_section_size (s);
608bcef2
HZ
12559 sprintf_vma (tmp1, vma);
12560 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12561 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12562 if (offset + sec_length + 1 > target_buf_size)
12563 {
4082afcc 12564 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12565 warning (_("\
c2fa21f1
HZ
12566Too many sections for read-only sections definition packet."));
12567 break;
12568 }
bba74b36
YQ
12569 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12570 tmp1, tmp2);
c2fa21f1 12571 offset += sec_length;
35b1e5cc
SS
12572 }
12573 if (anysecs)
12574 {
12575 putpkt (target_buf);
12576 getpkt (&target_buf, &target_buf_size, 0);
12577 }
12578}
12579
12580static void
e2d1aae3 12581remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12582{
12583 putpkt ("QTStart");
12584 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12585 if (*target_buf == '\0')
12586 error (_("Target does not support this command."));
12587 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12588 error (_("Bogus reply from target: %s"), target_buf);
12589}
12590
12591static int
8bd200f1 12592remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12593{
953b98d1 12594 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12595 char *p = NULL;
0df8b418 12596 /* FIXME we need to get register block size some other way. */
00bf0b85 12597 extern int trace_regblock_size;
bd3eecc3
PA
12598 enum packet_result result;
12599
4082afcc 12600 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12601 return -1;
a744cf53 12602
00bf0b85
SS
12603 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12604
049dc89b
JK
12605 putpkt ("qTStatus");
12606
492d29ea 12607 TRY
67f41397
JK
12608 {
12609 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12610 }
492d29ea 12611 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12612 {
598d3636
JK
12613 if (ex.error != TARGET_CLOSE_ERROR)
12614 {
12615 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12616 return -1;
12617 }
12618 throw_exception (ex);
67f41397 12619 }
492d29ea 12620 END_CATCH
00bf0b85 12621
bd3eecc3
PA
12622 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12623
00bf0b85 12624 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12625 if (result == PACKET_UNKNOWN)
00bf0b85 12626 return -1;
35b1e5cc 12627
00bf0b85 12628 /* We're working with a live target. */
f5911ea1 12629 ts->filename = NULL;
00bf0b85 12630
00bf0b85 12631 if (*p++ != 'T')
35b1e5cc
SS
12632 error (_("Bogus trace status reply from target: %s"), target_buf);
12633
84cebc4a
YQ
12634 /* Function 'parse_trace_status' sets default value of each field of
12635 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12636 parse_trace_status (p, ts);
12637
12638 return ts->running;
35b1e5cc
SS
12639}
12640
70221824 12641static void
db90e85c 12642remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12643 struct uploaded_tp *utp)
12644{
12645 struct remote_state *rs = get_remote_state ();
f196051f
SS
12646 char *reply;
12647 struct bp_location *loc;
12648 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12649 size_t size = get_remote_packet_size ();
f196051f
SS
12650
12651 if (tp)
12652 {
12653 tp->base.hit_count = 0;
12654 tp->traceframe_usage = 0;
12655 for (loc = tp->base.loc; loc; loc = loc->next)
12656 {
12657 /* If the tracepoint was never downloaded, don't go asking for
12658 any status. */
12659 if (tp->number_on_target == 0)
12660 continue;
bba74b36
YQ
12661 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12662 phex_nz (loc->address, 0));
f196051f
SS
12663 putpkt (rs->buf);
12664 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12665 if (reply && *reply)
12666 {
12667 if (*reply == 'V')
12668 parse_tracepoint_status (reply + 1, bp, utp);
12669 }
12670 }
12671 }
12672 else if (utp)
12673 {
12674 utp->hit_count = 0;
12675 utp->traceframe_usage = 0;
bba74b36
YQ
12676 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12677 phex_nz (utp->addr, 0));
f196051f
SS
12678 putpkt (rs->buf);
12679 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12680 if (reply && *reply)
12681 {
12682 if (*reply == 'V')
12683 parse_tracepoint_status (reply + 1, bp, utp);
12684 }
12685 }
12686}
12687
35b1e5cc 12688static void
74499f1b 12689remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12690{
12691 putpkt ("QTStop");
12692 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12693 if (*target_buf == '\0')
12694 error (_("Target does not support this command."));
12695 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12696 error (_("Bogus reply from target: %s"), target_buf);
12697}
12698
12699static int
bd4c6793
TT
12700remote_trace_find (struct target_ops *self,
12701 enum trace_find_type type, int num,
cc5925ad 12702 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12703 int *tpp)
12704{
12705 struct remote_state *rs = get_remote_state ();
bba74b36 12706 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12707 char *p, *reply;
12708 int target_frameno = -1, target_tracept = -1;
12709
e6e4e701
PA
12710 /* Lookups other than by absolute frame number depend on the current
12711 trace selected, so make sure it is correct on the remote end
12712 first. */
12713 if (type != tfind_number)
12714 set_remote_traceframe ();
12715
35b1e5cc
SS
12716 p = rs->buf;
12717 strcpy (p, "QTFrame:");
12718 p = strchr (p, '\0');
12719 switch (type)
12720 {
12721 case tfind_number:
bba74b36 12722 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12723 break;
12724 case tfind_pc:
bba74b36 12725 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12726 break;
12727 case tfind_tp:
bba74b36 12728 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12729 break;
12730 case tfind_range:
bba74b36
YQ
12731 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12732 phex_nz (addr2, 0));
35b1e5cc
SS
12733 break;
12734 case tfind_outside:
bba74b36
YQ
12735 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12736 phex_nz (addr2, 0));
35b1e5cc
SS
12737 break;
12738 default:
9b20d036 12739 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12740 }
12741
12742 putpkt (rs->buf);
2f65bcb7 12743 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12744 if (*reply == '\0')
12745 error (_("Target does not support this command."));
35b1e5cc
SS
12746
12747 while (reply && *reply)
12748 switch (*reply)
12749 {
12750 case 'F':
f197e0f1
VP
12751 p = ++reply;
12752 target_frameno = (int) strtol (p, &reply, 16);
12753 if (reply == p)
12754 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12755 /* Don't update our remote traceframe number cache on failure
12756 to select a remote traceframe. */
f197e0f1
VP
12757 if (target_frameno == -1)
12758 return -1;
35b1e5cc
SS
12759 break;
12760 case 'T':
f197e0f1
VP
12761 p = ++reply;
12762 target_tracept = (int) strtol (p, &reply, 16);
12763 if (reply == p)
12764 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12765 break;
12766 case 'O': /* "OK"? */
12767 if (reply[1] == 'K' && reply[2] == '\0')
12768 reply += 2;
12769 else
12770 error (_("Bogus reply from target: %s"), reply);
12771 break;
12772 default:
12773 error (_("Bogus reply from target: %s"), reply);
12774 }
12775 if (tpp)
12776 *tpp = target_tracept;
e6e4e701 12777
262e1174 12778 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12779 return target_frameno;
12780}
12781
12782static int
4011015b
TT
12783remote_get_trace_state_variable_value (struct target_ops *self,
12784 int tsvnum, LONGEST *val)
35b1e5cc
SS
12785{
12786 struct remote_state *rs = get_remote_state ();
12787 char *reply;
12788 ULONGEST uval;
12789
e6e4e701
PA
12790 set_remote_traceframe ();
12791
bba74b36 12792 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12793 putpkt (rs->buf);
12794 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12795 if (reply && *reply)
12796 {
12797 if (*reply == 'V')
12798 {
12799 unpack_varlen_hex (reply + 1, &uval);
12800 *val = (LONGEST) uval;
12801 return 1;
12802 }
12803 }
12804 return 0;
12805}
12806
00bf0b85 12807static int
dc3decaf 12808remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12809{
12810 struct remote_state *rs = get_remote_state ();
12811 char *p, *reply;
12812
12813 p = rs->buf;
12814 strcpy (p, "QTSave:");
12815 p += strlen (p);
12816 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12817 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12818 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12819 *p++ = '\0';
12820 putpkt (rs->buf);
ad91cd99 12821 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12822 if (*reply == '\0')
ad91cd99
PA
12823 error (_("Target does not support this command."));
12824 if (strcmp (reply, "OK") != 0)
12825 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12826 return 0;
12827}
12828
12829/* This is basically a memory transfer, but needs to be its own packet
12830 because we don't know how the target actually organizes its trace
12831 memory, plus we want to be able to ask for as much as possible, but
12832 not be unhappy if we don't get as much as we ask for. */
12833
12834static LONGEST
88ee6f45
TT
12835remote_get_raw_trace_data (struct target_ops *self,
12836 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12837{
12838 struct remote_state *rs = get_remote_state ();
12839 char *reply;
12840 char *p;
12841 int rslt;
12842
12843 p = rs->buf;
12844 strcpy (p, "qTBuffer:");
12845 p += strlen (p);
12846 p += hexnumstr (p, offset);
12847 *p++ = ',';
12848 p += hexnumstr (p, len);
12849 *p++ = '\0';
12850
12851 putpkt (rs->buf);
12852 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12853 if (reply && *reply)
12854 {
12855 /* 'l' by itself means we're at the end of the buffer and
12856 there is nothing more to get. */
12857 if (*reply == 'l')
12858 return 0;
12859
12860 /* Convert the reply into binary. Limit the number of bytes to
12861 convert according to our passed-in buffer size, rather than
12862 what was returned in the packet; if the target is
12863 unexpectedly generous and gives us a bigger reply than we
12864 asked for, we don't want to crash. */
12865 rslt = hex2bin (target_buf, buf, len);
12866 return rslt;
12867 }
12868
12869 /* Something went wrong, flag as an error. */
12870 return -1;
12871}
12872
35b1e5cc 12873static void
37b25738 12874remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12875{
12876 struct remote_state *rs = get_remote_state ();
12877
4082afcc 12878 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12879 {
ad91cd99
PA
12880 char *reply;
12881
bba74b36 12882 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12883 putpkt (rs->buf);
ad91cd99
PA
12884 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12885 if (*reply == '\0')
33da3f1c 12886 error (_("Target does not support this command."));
ad91cd99
PA
12887 if (strcmp (reply, "OK") != 0)
12888 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12889 }
12890 else if (val)
12891 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12892}
12893
dc146f7c
VP
12894static int
12895remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12896{
12897 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12898
fe978cb0
PA
12899 if (info && info->priv)
12900 return info->priv->core;
dc146f7c
VP
12901 return -1;
12902}
12903
4daf5ac0 12904static void
736d5b1f 12905remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12906{
12907 struct remote_state *rs = get_remote_state ();
ad91cd99 12908 char *reply;
4daf5ac0 12909
bba74b36 12910 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12911 putpkt (rs->buf);
ad91cd99
PA
12912 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12913 if (*reply == '\0')
4daf5ac0 12914 error (_("Target does not support this command."));
ad91cd99
PA
12915 if (strcmp (reply, "OK") != 0)
12916 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12917}
12918
b3b9301e 12919static struct traceframe_info *
a893e81f 12920remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12921{
12922 char *text;
12923
12924 text = target_read_stralloc (&current_target,
12925 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12926 if (text != NULL)
12927 {
12928 struct traceframe_info *info;
12929 struct cleanup *back_to = make_cleanup (xfree, text);
12930
12931 info = parse_traceframe_info (text);
12932 do_cleanups (back_to);
12933 return info;
12934 }
12935
12936 return NULL;
12937}
12938
405f8e94
SS
12939/* Handle the qTMinFTPILen packet. Returns the minimum length of
12940 instruction on which a fast tracepoint may be placed. Returns -1
12941 if the packet is not supported, and 0 if the minimum instruction
12942 length is unknown. */
12943
12944static int
0e67620a 12945remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12946{
12947 struct remote_state *rs = get_remote_state ();
12948 char *reply;
12949
e886a173
PA
12950 /* If we're not debugging a process yet, the IPA can't be
12951 loaded. */
12952 if (!target_has_execution)
12953 return 0;
12954
12955 /* Make sure the remote is pointing at the right process. */
12956 set_general_process ();
12957
bba74b36 12958 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12959 putpkt (rs->buf);
12960 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12961 if (*reply == '\0')
12962 return -1;
12963 else
12964 {
12965 ULONGEST min_insn_len;
12966
12967 unpack_varlen_hex (reply, &min_insn_len);
12968
12969 return (int) min_insn_len;
12970 }
12971}
12972
f6f899bf 12973static void
4da384be 12974remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12975{
4082afcc 12976 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12977 {
12978 struct remote_state *rs = get_remote_state ();
12979 char *buf = rs->buf;
12980 char *endbuf = rs->buf + get_remote_packet_size ();
12981 enum packet_result result;
12982
12983 gdb_assert (val >= 0 || val == -1);
12984 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12985 /* Send -1 as literal "-1" to avoid host size dependency. */
12986 if (val < 0)
12987 {
12988 *buf++ = '-';
12989 buf += hexnumstr (buf, (ULONGEST) -val);
12990 }
12991 else
12992 buf += hexnumstr (buf, (ULONGEST) val);
12993
12994 putpkt (rs->buf);
12995 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12996 result = packet_ok (rs->buf,
12997 &remote_protocol_packets[PACKET_QTBuffer_size]);
12998
12999 if (result != PACKET_OK)
13000 warning (_("Bogus reply from target: %s"), rs->buf);
13001 }
13002}
13003
f196051f 13004static int
d9e68a2c
TT
13005remote_set_trace_notes (struct target_ops *self,
13006 const char *user, const char *notes,
ca623f82 13007 const char *stop_notes)
f196051f
SS
13008{
13009 struct remote_state *rs = get_remote_state ();
13010 char *reply;
13011 char *buf = rs->buf;
13012 char *endbuf = rs->buf + get_remote_packet_size ();
13013 int nbytes;
13014
13015 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13016 if (user)
13017 {
13018 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 13019 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
13020 buf += 2 * nbytes;
13021 *buf++ = ';';
13022 }
13023 if (notes)
13024 {
13025 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 13026 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
13027 buf += 2 * nbytes;
13028 *buf++ = ';';
13029 }
13030 if (stop_notes)
13031 {
13032 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 13033 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
13034 buf += 2 * nbytes;
13035 *buf++ = ';';
13036 }
13037 /* Ensure the buffer is terminated. */
13038 *buf = '\0';
13039
13040 putpkt (rs->buf);
13041 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
13042 if (*reply == '\0')
13043 return 0;
13044
13045 if (strcmp (reply, "OK") != 0)
13046 error (_("Bogus reply from target: %s"), reply);
13047
13048 return 1;
13049}
13050
d1feda86 13051static int
2c152180 13052remote_use_agent (struct target_ops *self, int use)
d1feda86 13053{
4082afcc 13054 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
13055 {
13056 struct remote_state *rs = get_remote_state ();
13057
13058 /* If the stub supports QAgent. */
bba74b36 13059 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
13060 putpkt (rs->buf);
13061 getpkt (&rs->buf, &rs->buf_size, 0);
13062
13063 if (strcmp (rs->buf, "OK") == 0)
13064 {
13065 use_agent = use;
13066 return 1;
13067 }
13068 }
13069
13070 return 0;
13071}
13072
13073static int
fe38f897 13074remote_can_use_agent (struct target_ops *self)
d1feda86 13075{
4082afcc 13076 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
13077}
13078
9accd112
MM
13079struct btrace_target_info
13080{
13081 /* The ptid of the traced thread. */
13082 ptid_t ptid;
f4abbc16
MM
13083
13084 /* The obtained branch trace configuration. */
13085 struct btrace_config conf;
9accd112
MM
13086};
13087
f4abbc16
MM
13088/* Reset our idea of our target's btrace configuration. */
13089
13090static void
13091remote_btrace_reset (void)
13092{
13093 struct remote_state *rs = get_remote_state ();
13094
13095 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13096}
13097
9accd112
MM
13098/* Check whether the target supports branch tracing. */
13099
13100static int
043c3577 13101remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 13102{
4082afcc 13103 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 13104 return 0;
4082afcc 13105 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
13106 return 0;
13107
043c3577
MM
13108 switch (format)
13109 {
13110 case BTRACE_FORMAT_NONE:
13111 return 0;
13112
13113 case BTRACE_FORMAT_BTS:
13114 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
13115
13116 case BTRACE_FORMAT_PT:
13117 /* The trace is decoded on the host. Even if our target supports it,
13118 we still need to have libipt to decode the trace. */
13119#if defined (HAVE_LIBIPT)
13120 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
13121#else /* !defined (HAVE_LIBIPT) */
13122 return 0;
13123#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
13124 }
13125
13126 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
13127}
13128
f4abbc16
MM
13129/* Synchronize the configuration with the target. */
13130
13131static void
13132btrace_sync_conf (const struct btrace_config *conf)
13133{
d33501a5
MM
13134 struct packet_config *packet;
13135 struct remote_state *rs;
13136 char *buf, *pos, *endbuf;
13137
13138 rs = get_remote_state ();
13139 buf = rs->buf;
13140 endbuf = buf + get_remote_packet_size ();
13141
13142 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13143 if (packet_config_support (packet) == PACKET_ENABLE
13144 && conf->bts.size != rs->btrace_config.bts.size)
13145 {
13146 pos = buf;
13147 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13148 conf->bts.size);
13149
13150 putpkt (buf);
13151 getpkt (&buf, &rs->buf_size, 0);
13152
13153 if (packet_ok (buf, packet) == PACKET_ERROR)
13154 {
13155 if (buf[0] == 'E' && buf[1] == '.')
13156 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13157 else
13158 error (_("Failed to configure the BTS buffer size."));
13159 }
13160
13161 rs->btrace_config.bts.size = conf->bts.size;
13162 }
b20a6524
MM
13163
13164 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13165 if (packet_config_support (packet) == PACKET_ENABLE
13166 && conf->pt.size != rs->btrace_config.pt.size)
13167 {
13168 pos = buf;
13169 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13170 conf->pt.size);
13171
13172 putpkt (buf);
13173 getpkt (&buf, &rs->buf_size, 0);
13174
13175 if (packet_ok (buf, packet) == PACKET_ERROR)
13176 {
13177 if (buf[0] == 'E' && buf[1] == '.')
13178 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13179 else
13180 error (_("Failed to configure the trace buffer size."));
13181 }
13182
13183 rs->btrace_config.pt.size = conf->pt.size;
13184 }
f4abbc16
MM
13185}
13186
13187/* Read the current thread's btrace configuration from the target and
13188 store it into CONF. */
13189
13190static void
13191btrace_read_config (struct btrace_config *conf)
13192{
13193 char *xml;
13194
13195 xml = target_read_stralloc (&current_target,
b20a6524 13196 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
13197 if (xml != NULL)
13198 {
13199 struct cleanup *cleanup;
13200
13201 cleanup = make_cleanup (xfree, xml);
13202 parse_xml_btrace_conf (conf, xml);
13203 do_cleanups (cleanup);
13204 }
13205}
13206
c0272db5
TW
13207/* Maybe reopen target btrace. */
13208
13209static void
13210remote_btrace_maybe_reopen (void)
13211{
13212 struct remote_state *rs = get_remote_state ();
13213 struct cleanup *cleanup;
13214 struct thread_info *tp;
13215 int btrace_target_pushed = 0;
13216 int warned = 0;
13217
13218 cleanup = make_cleanup_restore_current_thread ();
13219 ALL_NON_EXITED_THREADS (tp)
13220 {
13221 set_general_thread (tp->ptid);
13222
13223 memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13224 btrace_read_config (&rs->btrace_config);
13225
13226 if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13227 continue;
13228
13229#if !defined (HAVE_LIBIPT)
13230 if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13231 {
13232 if (!warned)
13233 {
13234 warned = 1;
13235 warning (_("GDB does not support Intel Processor Trace. "
13236 "\"record\" will not work in this session."));
13237 }
13238
13239 continue;
13240 }
13241#endif /* !defined (HAVE_LIBIPT) */
13242
13243 /* Push target, once, but before anything else happens. This way our
13244 changes to the threads will be cleaned up by unpushing the target
13245 in case btrace_read_config () throws. */
13246 if (!btrace_target_pushed)
13247 {
13248 btrace_target_pushed = 1;
13249 record_btrace_push_target ();
13250 printf_filtered (_("Target is recording using %s.\n"),
13251 btrace_format_string (rs->btrace_config.format));
13252 }
13253
13254 tp->btrace.target = XCNEW (struct btrace_target_info);
13255 tp->btrace.target->ptid = tp->ptid;
13256 tp->btrace.target->conf = rs->btrace_config;
13257 }
13258 do_cleanups (cleanup);
13259}
13260
9accd112
MM
13261/* Enable branch tracing. */
13262
13263static struct btrace_target_info *
f4abbc16
MM
13264remote_enable_btrace (struct target_ops *self, ptid_t ptid,
13265 const struct btrace_config *conf)
9accd112
MM
13266{
13267 struct btrace_target_info *tinfo = NULL;
b20a6524 13268 struct packet_config *packet = NULL;
9accd112
MM
13269 struct remote_state *rs = get_remote_state ();
13270 char *buf = rs->buf;
13271 char *endbuf = rs->buf + get_remote_packet_size ();
13272
b20a6524
MM
13273 switch (conf->format)
13274 {
13275 case BTRACE_FORMAT_BTS:
13276 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13277 break;
13278
13279 case BTRACE_FORMAT_PT:
13280 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13281 break;
13282 }
13283
13284 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13285 error (_("Target does not support branch tracing."));
13286
f4abbc16
MM
13287 btrace_sync_conf (conf);
13288
9accd112
MM
13289 set_general_thread (ptid);
13290
13291 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13292 putpkt (rs->buf);
13293 getpkt (&rs->buf, &rs->buf_size, 0);
13294
13295 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13296 {
13297 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13298 error (_("Could not enable branch tracing for %s: %s"),
13299 target_pid_to_str (ptid), rs->buf + 2);
13300 else
13301 error (_("Could not enable branch tracing for %s."),
13302 target_pid_to_str (ptid));
13303 }
13304
8d749320 13305 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
13306 tinfo->ptid = ptid;
13307
f4abbc16
MM
13308 /* If we fail to read the configuration, we lose some information, but the
13309 tracing itself is not impacted. */
492d29ea
PA
13310 TRY
13311 {
13312 btrace_read_config (&tinfo->conf);
13313 }
13314 CATCH (err, RETURN_MASK_ERROR)
13315 {
13316 if (err.message != NULL)
13317 warning ("%s", err.message);
13318 }
13319 END_CATCH
f4abbc16 13320
9accd112
MM
13321 return tinfo;
13322}
13323
13324/* Disable branch tracing. */
13325
13326static void
25e95349
TT
13327remote_disable_btrace (struct target_ops *self,
13328 struct btrace_target_info *tinfo)
9accd112
MM
13329{
13330 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13331 struct remote_state *rs = get_remote_state ();
13332 char *buf = rs->buf;
13333 char *endbuf = rs->buf + get_remote_packet_size ();
13334
4082afcc 13335 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13336 error (_("Target does not support branch tracing."));
13337
13338 set_general_thread (tinfo->ptid);
13339
13340 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13341 putpkt (rs->buf);
13342 getpkt (&rs->buf, &rs->buf_size, 0);
13343
13344 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13345 {
13346 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13347 error (_("Could not disable branch tracing for %s: %s"),
13348 target_pid_to_str (tinfo->ptid), rs->buf + 2);
13349 else
13350 error (_("Could not disable branch tracing for %s."),
13351 target_pid_to_str (tinfo->ptid));
13352 }
13353
13354 xfree (tinfo);
13355}
13356
13357/* Teardown branch tracing. */
13358
13359static void
1777056d
TT
13360remote_teardown_btrace (struct target_ops *self,
13361 struct btrace_target_info *tinfo)
9accd112
MM
13362{
13363 /* We must not talk to the target during teardown. */
13364 xfree (tinfo);
13365}
13366
13367/* Read the branch trace. */
13368
969c39fb 13369static enum btrace_error
39c49f83 13370remote_read_btrace (struct target_ops *self,
734b0e4b 13371 struct btrace_data *btrace,
969c39fb 13372 struct btrace_target_info *tinfo,
9accd112
MM
13373 enum btrace_read_type type)
13374{
13375 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
969c39fb 13376 struct cleanup *cleanup;
9accd112
MM
13377 const char *annex;
13378 char *xml;
13379
4082afcc 13380 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
13381 error (_("Target does not support branch tracing."));
13382
13383#if !defined(HAVE_LIBEXPAT)
13384 error (_("Cannot process branch tracing result. XML parsing not supported."));
13385#endif
13386
13387 switch (type)
13388 {
864089d2 13389 case BTRACE_READ_ALL:
9accd112
MM
13390 annex = "all";
13391 break;
864089d2 13392 case BTRACE_READ_NEW:
9accd112
MM
13393 annex = "new";
13394 break;
969c39fb
MM
13395 case BTRACE_READ_DELTA:
13396 annex = "delta";
13397 break;
9accd112
MM
13398 default:
13399 internal_error (__FILE__, __LINE__,
13400 _("Bad branch tracing read type: %u."),
13401 (unsigned int) type);
13402 }
13403
13404 xml = target_read_stralloc (&current_target,
b20a6524 13405 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
13406 if (xml == NULL)
13407 return BTRACE_ERR_UNKNOWN;
9accd112 13408
969c39fb 13409 cleanup = make_cleanup (xfree, xml);
734b0e4b 13410 parse_xml_btrace (btrace, xml);
969c39fb 13411 do_cleanups (cleanup);
9accd112 13412
969c39fb 13413 return BTRACE_ERR_NONE;
9accd112
MM
13414}
13415
f4abbc16
MM
13416static const struct btrace_config *
13417remote_btrace_conf (struct target_ops *self,
13418 const struct btrace_target_info *tinfo)
13419{
13420 return &tinfo->conf;
13421}
13422
ced63ec0 13423static int
5436ff03 13424remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 13425{
4082afcc
PA
13426 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13427 == PACKET_ENABLE);
ced63ec0
GB
13428}
13429
9dd130a0
TT
13430/* Implementation of to_load. */
13431
13432static void
9cbe5fff 13433remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
13434{
13435 generic_load (name, from_tty);
13436}
13437
c78fa86a
GB
13438/* Accepts an integer PID; returns a string representing a file that
13439 can be opened on the remote side to get the symbols for the child
13440 process. Returns NULL if the operation is not supported. */
13441
13442static char *
13443remote_pid_to_exec_file (struct target_ops *self, int pid)
13444{
13445 static char *filename = NULL;
835205d0
GB
13446 struct inferior *inf;
13447 char *annex = NULL;
c78fa86a
GB
13448
13449 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13450 return NULL;
13451
13452 if (filename != NULL)
13453 xfree (filename);
13454
835205d0
GB
13455 inf = find_inferior_pid (pid);
13456 if (inf == NULL)
13457 internal_error (__FILE__, __LINE__,
13458 _("not currently attached to process %d"), pid);
13459
13460 if (!inf->fake_pid_p)
13461 {
13462 const int annex_size = 9;
13463
224c3ddb 13464 annex = (char *) alloca (annex_size);
835205d0
GB
13465 xsnprintf (annex, annex_size, "%x", pid);
13466 }
13467
c78fa86a
GB
13468 filename = target_read_stralloc (&current_target,
13469 TARGET_OBJECT_EXEC_FILE, annex);
13470
13471 return filename;
13472}
13473
750ce8d1
YQ
13474/* Implement the to_can_do_single_step target_ops method. */
13475
13476static int
13477remote_can_do_single_step (struct target_ops *ops)
13478{
13479 /* We can only tell whether target supports single step or not by
13480 supported s and S vCont actions if the stub supports vContSupported
13481 feature. If the stub doesn't support vContSupported feature,
13482 we have conservatively to think target doesn't supports single
13483 step. */
13484 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13485 {
13486 struct remote_state *rs = get_remote_state ();
13487
13488 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13489 remote_vcont_probe (rs);
13490
13491 return rs->supports_vCont.s && rs->supports_vCont.S;
13492 }
13493 else
13494 return 0;
13495}
13496
3a00c802
PA
13497/* Implementation of the to_execution_direction method for the remote
13498 target. */
13499
13500static enum exec_direction_kind
13501remote_execution_direction (struct target_ops *self)
13502{
13503 struct remote_state *rs = get_remote_state ();
13504
13505 return rs->last_resume_exec_dir;
13506}
13507
c906108c 13508static void
fba45db2 13509init_remote_ops (void)
c906108c 13510{
c5aa993b 13511 remote_ops.to_shortname = "remote";
c906108c 13512 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 13513 remote_ops.to_doc =
c906108c 13514 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
13515Specify the serial device it is connected to\n\
13516(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
13517 remote_ops.to_open = remote_open;
13518 remote_ops.to_close = remote_close;
c906108c 13519 remote_ops.to_detach = remote_detach;
6ad8ae5c 13520 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 13521 remote_ops.to_resume = remote_resume;
85ad3aaf 13522 remote_ops.to_commit_resume = remote_commit_resume;
c906108c
SS
13523 remote_ops.to_wait = remote_wait;
13524 remote_ops.to_fetch_registers = remote_fetch_registers;
13525 remote_ops.to_store_registers = remote_store_registers;
13526 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 13527 remote_ops.to_files_info = remote_files_info;
c906108c
SS
13528 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13529 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
13530 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13531 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13532 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13533 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
13534 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13535 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
13536 remote_ops.to_watchpoint_addr_within_range =
13537 remote_watchpoint_addr_within_range;
3c3bea1c
GS
13538 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13539 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13540 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
13541 remote_ops.to_region_ok_for_hw_watchpoint
13542 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
13543 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13544 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 13545 remote_ops.to_kill = remote_kill;
9dd130a0 13546 remote_ops.to_load = remote_load;
c906108c 13547 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 13548 remote_ops.to_pass_signals = remote_pass_signals;
82075af2 13549 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
9b224c5e 13550 remote_ops.to_program_signals = remote_program_signals;
c906108c 13551 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 13552 remote_ops.to_thread_name = remote_thread_name;
e8032dde 13553 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 13554 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 13555 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 13556 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 13557 remote_ops.to_stop = remote_stop;
bfedc46a 13558 remote_ops.to_interrupt = remote_interrupt;
93692b58 13559 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
4b8a223f 13560 remote_ops.to_xfer_partial = remote_xfer_partial;
09c98b44 13561 remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
96baa820 13562 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 13563 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 13564 remote_ops.to_log_command = serial_log_command;
38691318 13565 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 13566 remote_ops.to_stratum = process_stratum;
c35b1492
PA
13567 remote_ops.to_has_all_memory = default_child_has_all_memory;
13568 remote_ops.to_has_memory = default_child_has_memory;
13569 remote_ops.to_has_stack = default_child_has_stack;
13570 remote_ops.to_has_registers = default_child_has_registers;
13571 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 13572 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13573 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13574 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13575 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13576 remote_ops.to_flash_erase = remote_flash_erase;
13577 remote_ops.to_flash_done = remote_flash_done;
29709017 13578 remote_ops.to_read_description = remote_read_description;
08388c79 13579 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13580 remote_ops.to_can_async_p = remote_can_async_p;
13581 remote_ops.to_is_async_p = remote_is_async_p;
13582 remote_ops.to_async = remote_async;
65706a29 13583 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13584 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13585 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13586 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13587 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13588 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13589 remote_ops.to_supports_disable_randomization
13590 = remote_supports_disable_randomization;
4bd7dc42 13591 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13592 remote_ops.to_fileio_open = remote_hostio_open;
13593 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13594 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13595 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13596 remote_ops.to_fileio_close = remote_hostio_close;
13597 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13598 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13599 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13600 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13601 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13602 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13603 remote_ops.to_trace_init = remote_trace_init;
13604 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13605 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13606 remote_ops.to_download_trace_state_variable
13607 = remote_download_trace_state_variable;
d248b706
KY
13608 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13609 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13610 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13611 remote_ops.to_trace_start = remote_trace_start;
13612 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13613 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13614 remote_ops.to_trace_stop = remote_trace_stop;
13615 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13616 remote_ops.to_get_trace_state_variable_value
13617 = remote_get_trace_state_variable_value;
00bf0b85
SS
13618 remote_ops.to_save_trace_data = remote_save_trace_data;
13619 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13620 remote_ops.to_upload_trace_state_variables
13621 = remote_upload_trace_state_variables;
00bf0b85 13622 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13623 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13624 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13625 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13626 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13627 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13628 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13629 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13630 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13631 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13632 remote_ops.to_static_tracepoint_marker_at
13633 = remote_static_tracepoint_marker_at;
13634 remote_ops.to_static_tracepoint_markers_by_strid
13635 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13636 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13637 remote_ops.to_use_agent = remote_use_agent;
13638 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13639 remote_ops.to_supports_btrace = remote_supports_btrace;
13640 remote_ops.to_enable_btrace = remote_enable_btrace;
13641 remote_ops.to_disable_btrace = remote_disable_btrace;
13642 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13643 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13644 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13645 remote_ops.to_augmented_libraries_svr4_read =
13646 remote_augmented_libraries_svr4_read;
8020350c
DB
13647 remote_ops.to_follow_fork = remote_follow_fork;
13648 remote_ops.to_follow_exec = remote_follow_exec;
13649 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13650 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13651 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13652 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13653 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13654 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
3a00c802 13655 remote_ops.to_execution_direction = remote_execution_direction;
c906108c
SS
13656}
13657
13658/* Set up the extended remote vector by making a copy of the standard
13659 remote vector and adding to it. */
13660
13661static void
fba45db2 13662init_extended_remote_ops (void)
c906108c
SS
13663{
13664 extended_remote_ops = remote_ops;
13665
0f71a2f6 13666 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13667 extended_remote_ops.to_longname =
c906108c 13668 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13669 extended_remote_ops.to_doc =
c906108c 13670 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13671Specify the serial device it is connected to (e.g. /dev/ttya).";
13672 extended_remote_ops.to_open = extended_remote_open;
c906108c 13673 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
2d717e4f
DJ
13674 extended_remote_ops.to_detach = extended_remote_detach;
13675 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13676 extended_remote_ops.to_post_attach = extended_remote_post_attach;
03583c20
UW
13677 extended_remote_ops.to_supports_disable_randomization
13678 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
13679}
13680
6426a772 13681static int
6a109b6b 13682remote_can_async_p (struct target_ops *ops)
6426a772 13683{
5d93a237
TT
13684 struct remote_state *rs = get_remote_state ();
13685
c6ebd6cf 13686 if (!target_async_permitted)
75c99385
PA
13687 /* We only enable async when the user specifically asks for it. */
13688 return 0;
13689
23860348 13690 /* We're async whenever the serial device is. */
5d93a237 13691 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13692}
13693
13694static int
6a109b6b 13695remote_is_async_p (struct target_ops *ops)
6426a772 13696{
5d93a237
TT
13697 struct remote_state *rs = get_remote_state ();
13698
c6ebd6cf 13699 if (!target_async_permitted)
75c99385
PA
13700 /* We only enable async when the user specifically asks for it. */
13701 return 0;
13702
23860348 13703 /* We're async whenever the serial device is. */
5d93a237 13704 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13705}
13706
2acceee2
JM
13707/* Pass the SERIAL event on and up to the client. One day this code
13708 will be able to delay notifying the client of an event until the
23860348 13709 point where an entire packet has been received. */
2acceee2 13710
2acceee2
JM
13711static serial_event_ftype remote_async_serial_handler;
13712
6426a772 13713static void
819cc324 13714remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13715{
2acceee2
JM
13716 /* Don't propogate error information up to the client. Instead let
13717 the client find out about the error by querying the target. */
6a3753b3 13718 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13719}
13720
74531fed
PA
13721static void
13722remote_async_inferior_event_handler (gdb_client_data data)
13723{
13724 inferior_event_handler (INF_REG_EVENT, NULL);
13725}
13726
2acceee2 13727static void
6a3753b3 13728remote_async (struct target_ops *ops, int enable)
2acceee2 13729{
5d93a237
TT
13730 struct remote_state *rs = get_remote_state ();
13731
6a3753b3 13732 if (enable)
2acceee2 13733 {
88b496c3 13734 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13735
13736 /* If there are pending events in the stop reply queue tell the
13737 event loop to process them. */
13738 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13739 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13740 /* For simplicity, below we clear the pending events token
13741 without remembering whether it is marked, so here we always
13742 mark it. If there's actually no pending notification to
13743 process, this ends up being a no-op (other than a spurious
13744 event-loop wakeup). */
13745 if (target_is_non_stop_p ())
13746 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13747 }
13748 else
b7d2e916
PA
13749 {
13750 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13751 /* If the core is disabling async, it doesn't want to be
13752 disturbed with target events. Clear all async event sources
13753 too. */
b7d2e916 13754 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13755 if (target_is_non_stop_p ())
13756 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13757 }
6426a772
JM
13758}
13759
65706a29
PA
13760/* Implementation of the to_thread_events method. */
13761
13762static void
13763remote_thread_events (struct target_ops *ops, int enable)
13764{
13765 struct remote_state *rs = get_remote_state ();
13766 size_t size = get_remote_packet_size ();
65706a29
PA
13767
13768 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13769 return;
13770
13771 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13772 putpkt (rs->buf);
13773 getpkt (&rs->buf, &rs->buf_size, 0);
13774
13775 switch (packet_ok (rs->buf,
13776 &remote_protocol_packets[PACKET_QThreadEvents]))
13777 {
13778 case PACKET_OK:
13779 if (strcmp (rs->buf, "OK") != 0)
13780 error (_("Remote refused setting thread events: %s"), rs->buf);
13781 break;
13782 case PACKET_ERROR:
13783 warning (_("Remote failure reply: %s"), rs->buf);
13784 break;
13785 case PACKET_UNKNOWN:
13786 break;
13787 }
13788}
13789
5a2468f5 13790static void
c2d11a7d 13791set_remote_cmd (char *args, int from_tty)
5a2468f5 13792{
635c7e8a 13793 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13794}
13795
d471ea57
AC
13796static void
13797show_remote_cmd (char *args, int from_tty)
13798{
37a105a1 13799 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13800 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13801 struct cleanup *showlist_chain;
13802 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13803 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13804
13805 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13806 for (; list != NULL; list = list->next)
13807 if (strcmp (list->name, "Z-packet") == 0)
13808 continue;
427c3a89
DJ
13809 else if (list->type == not_set_cmd)
13810 /* Alias commands are exactly like the original, except they
13811 don't have the normal type. */
13812 continue;
13813 else
37a105a1
DJ
13814 {
13815 struct cleanup *option_chain
13816 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13817
37a105a1
DJ
13818 ui_out_field_string (uiout, "name", list->name);
13819 ui_out_text (uiout, ": ");
427c3a89 13820 if (list->type == show_cmd)
f5c4fcd9 13821 do_show_command (NULL, from_tty, list);
427c3a89
DJ
13822 else
13823 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13824 /* Close the tuple. */
13825 do_cleanups (option_chain);
13826 }
427c3a89
DJ
13827
13828 /* Close the tuple. */
13829 do_cleanups (showlist_chain);
d471ea57 13830}
5a2468f5 13831
0f71a2f6 13832
23860348 13833/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13834static void
13835remote_new_objfile (struct objfile *objfile)
13836{
5d93a237
TT
13837 struct remote_state *rs = get_remote_state ();
13838
13839 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13840 remote_check_symbols ();
dc8acb97
MS
13841}
13842
00bf0b85
SS
13843/* Pull all the tracepoints defined on the target and create local
13844 data structures representing them. We don't want to create real
13845 tracepoints yet, we don't want to mess up the user's existing
13846 collection. */
13847
13848static int
ab6617cc 13849remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13850{
00bf0b85
SS
13851 struct remote_state *rs = get_remote_state ();
13852 char *p;
d5551862 13853
00bf0b85
SS
13854 /* Ask for a first packet of tracepoint definition. */
13855 putpkt ("qTfP");
13856 getpkt (&rs->buf, &rs->buf_size, 0);
13857 p = rs->buf;
13858 while (*p && *p != 'l')
d5551862 13859 {
00bf0b85
SS
13860 parse_tracepoint_definition (p, utpp);
13861 /* Ask for another packet of tracepoint definition. */
13862 putpkt ("qTsP");
13863 getpkt (&rs->buf, &rs->buf_size, 0);
13864 p = rs->buf;
d5551862 13865 }
00bf0b85 13866 return 0;
d5551862
SS
13867}
13868
00bf0b85 13869static int
181e3713
TT
13870remote_upload_trace_state_variables (struct target_ops *self,
13871 struct uploaded_tsv **utsvp)
d5551862 13872{
00bf0b85 13873 struct remote_state *rs = get_remote_state ();
d5551862 13874 char *p;
d5551862 13875
00bf0b85
SS
13876 /* Ask for a first packet of variable definition. */
13877 putpkt ("qTfV");
d5551862
SS
13878 getpkt (&rs->buf, &rs->buf_size, 0);
13879 p = rs->buf;
00bf0b85 13880 while (*p && *p != 'l')
d5551862 13881 {
00bf0b85
SS
13882 parse_tsv_definition (p, utsvp);
13883 /* Ask for another packet of variable definition. */
13884 putpkt ("qTsV");
d5551862
SS
13885 getpkt (&rs->buf, &rs->buf_size, 0);
13886 p = rs->buf;
13887 }
00bf0b85 13888 return 0;
d5551862
SS
13889}
13890
c1e36e3e
PA
13891/* The "set/show range-stepping" show hook. */
13892
13893static void
13894show_range_stepping (struct ui_file *file, int from_tty,
13895 struct cmd_list_element *c,
13896 const char *value)
13897{
13898 fprintf_filtered (file,
13899 _("Debugger's willingness to use range stepping "
13900 "is %s.\n"), value);
13901}
13902
13903/* The "set/show range-stepping" set hook. */
13904
13905static void
13906set_range_stepping (char *ignore_args, int from_tty,
13907 struct cmd_list_element *c)
13908{
5d93a237
TT
13909 struct remote_state *rs = get_remote_state ();
13910
c1e36e3e
PA
13911 /* Whene enabling, check whether range stepping is actually
13912 supported by the target, and warn if not. */
13913 if (use_range_stepping)
13914 {
5d93a237 13915 if (rs->remote_desc != NULL)
c1e36e3e 13916 {
4082afcc 13917 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13918 remote_vcont_probe (rs);
13919
4082afcc 13920 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13921 && rs->supports_vCont.r)
13922 return;
13923 }
13924
13925 warning (_("Range stepping is not supported by the current target"));
13926 }
13927}
13928
c906108c 13929void
fba45db2 13930_initialize_remote (void)
c906108c 13931{
9a7071a8 13932 struct cmd_list_element *cmd;
6f937416 13933 const char *cmd_name;
ea9c271d 13934
0f71a2f6 13935 /* architecture specific data */
2bc416ba 13936 remote_gdbarch_data_handle =
23860348 13937 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13938 remote_g_packet_data_handle =
13939 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13940
94585166
DB
13941 remote_pspace_data
13942 = register_program_space_data_with_cleanup (NULL,
13943 remote_pspace_data_cleanup);
13944
ea9c271d
DJ
13945 /* Initialize the per-target state. At the moment there is only one
13946 of these, not one per target. Only one target is active at a
cf792862
TT
13947 time. */
13948 remote_state = new_remote_state ();
ea9c271d 13949
c906108c
SS
13950 init_remote_ops ();
13951 add_target (&remote_ops);
13952
13953 init_extended_remote_ops ();
13954 add_target (&extended_remote_ops);
cce74817 13955
dc8acb97 13956 /* Hook into new objfile notification. */
06d3b283 13957 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13958 /* We're no longer interested in notification events of an inferior
13959 when it exits. */
13960 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13961
c906108c
SS
13962#if 0
13963 init_remote_threadtests ();
13964#endif
13965
722247f1 13966 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13967 /* set/show remote ... */
d471ea57 13968
1bedd215 13969 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13970Remote protocol specific variables\n\
13971Configure various remote-protocol specific variables such as\n\
1bedd215 13972the packets being used"),
cff3e48b 13973 &remote_set_cmdlist, "set remote ",
23860348 13974 0 /* allow-unknown */, &setlist);
1bedd215 13975 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13976Remote protocol specific variables\n\
13977Configure various remote-protocol specific variables such as\n\
1bedd215 13978the packets being used"),
cff3e48b 13979 &remote_show_cmdlist, "show remote ",
23860348 13980 0 /* allow-unknown */, &showlist);
5a2468f5 13981
1a966eab
AC
13982 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13983Compare section data on target to the exec file.\n\
95cf3b38
DT
13984Argument is a single section name (default: all loaded sections).\n\
13985To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13986 &cmdlist);
13987
1a966eab
AC
13988 add_cmd ("packet", class_maintenance, packet_command, _("\
13989Send an arbitrary packet to a remote target.\n\
c906108c
SS
13990 maintenance packet TEXT\n\
13991If GDB is talking to an inferior via the GDB serial protocol, then\n\
13992this command sends the string TEXT to the inferior, and displays the\n\
13993response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13994terminating `#' character and checksum."),
c906108c
SS
13995 &maintenancelist);
13996
7915a72c
AC
13997 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13998Set whether to send break if interrupted."), _("\
13999Show whether to send break if interrupted."), _("\
14000If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 14001 set_remotebreak, show_remotebreak,
e707bbc2 14002 &setlist, &showlist);
9a7071a8
JB
14003 cmd_name = "remotebreak";
14004 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14005 deprecate_cmd (cmd, "set remote interrupt-sequence");
14006 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14007 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14008 deprecate_cmd (cmd, "show remote interrupt-sequence");
14009
14010 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
14011 interrupt_sequence_modes, &interrupt_sequence_mode,
14012 _("\
9a7071a8
JB
14013Set interrupt sequence to remote target."), _("\
14014Show interrupt sequence to remote target."), _("\
14015Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14016 NULL, show_interrupt_sequence,
14017 &remote_set_cmdlist,
14018 &remote_show_cmdlist);
14019
14020 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14021 &interrupt_on_connect, _("\
14022Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14023Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
14024If set, interrupt sequence is sent to remote target."),
14025 NULL, NULL,
14026 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 14027
23860348 14028 /* Install commands for configuring memory read/write packets. */
11cf8741 14029
1a966eab
AC
14030 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14031Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 14032 &setlist);
1a966eab
AC
14033 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14034Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
14035 &showlist);
14036 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
14037 set_memory_write_packet_size, _("\
14038Set the maximum number of bytes per memory-write packet.\n\
14039Specify the number of bytes in a packet or 0 (zero) for the\n\
14040default packet size. The actual limit is further reduced\n\
14041dependent on the target. Specify ``fixed'' to disable the\n\
14042further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14043 &remote_set_cmdlist);
14044 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
14045 set_memory_read_packet_size, _("\
14046Set the maximum number of bytes per memory-read packet.\n\
14047Specify the number of bytes in a packet or 0 (zero) for the\n\
14048default packet size. The actual limit is further reduced\n\
14049dependent on the target. Specify ``fixed'' to disable the\n\
14050further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
14051 &remote_set_cmdlist);
14052 add_cmd ("memory-write-packet-size", no_class,
14053 show_memory_write_packet_size,
1a966eab 14054 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
14055 &remote_show_cmdlist);
14056 add_cmd ("memory-read-packet-size", no_class,
14057 show_memory_read_packet_size,
1a966eab 14058 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 14059 &remote_show_cmdlist);
c906108c 14060
b3f42336 14061 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
14062 &remote_hw_watchpoint_limit, _("\
14063Set the maximum number of target hardware watchpoints."), _("\
14064Show the maximum number of target hardware watchpoints."), _("\
14065Specify a negative limit for unlimited."),
3e43a32a
MS
14066 NULL, NULL, /* FIXME: i18n: The maximum
14067 number of target hardware
14068 watchpoints is %s. */
b3f42336 14069 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
14070 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14071 &remote_hw_watchpoint_length_limit, _("\
14072Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14073Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14074Specify a negative limit for unlimited."),
14075 NULL, NULL, /* FIXME: i18n: The maximum
14076 length (in bytes) of a target
14077 hardware watchpoint is %s. */
14078 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 14079 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
14080 &remote_hw_breakpoint_limit, _("\
14081Set the maximum number of target hardware breakpoints."), _("\
14082Show the maximum number of target hardware breakpoints."), _("\
14083Specify a negative limit for unlimited."),
3e43a32a
MS
14084 NULL, NULL, /* FIXME: i18n: The maximum
14085 number of target hardware
14086 breakpoints is %s. */
b3f42336 14087 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 14088
1b493192
PA
14089 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14090 &remote_address_size, _("\
4d28ad1e
AC
14091Set the maximum size of the address (in bits) in a memory packet."), _("\
14092Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
14093 NULL,
14094 NULL, /* FIXME: i18n: */
14095 &setlist, &showlist);
c906108c 14096
ca4f7f8b
PA
14097 init_all_packet_configs ();
14098
444abaca 14099 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 14100 "X", "binary-download", 1);
0f71a2f6 14101
444abaca 14102 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 14103 "vCont", "verbose-resume", 0);
506fb367 14104
89be2091
DJ
14105 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14106 "QPassSignals", "pass-signals", 0);
14107
82075af2
JS
14108 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14109 "QCatchSyscalls", "catch-syscalls", 0);
14110
9b224c5e
PA
14111 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14112 "QProgramSignals", "program-signals", 0);
14113
444abaca 14114 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 14115 "qSymbol", "symbol-lookup", 0);
dc8acb97 14116
444abaca 14117 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 14118 "P", "set-register", 1);
d471ea57 14119
444abaca 14120 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 14121 "p", "fetch-register", 1);
b96ec7ac 14122
444abaca 14123 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 14124 "Z0", "software-breakpoint", 0);
d471ea57 14125
444abaca 14126 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 14127 "Z1", "hardware-breakpoint", 0);
d471ea57 14128
444abaca 14129 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 14130 "Z2", "write-watchpoint", 0);
d471ea57 14131
444abaca 14132 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 14133 "Z3", "read-watchpoint", 0);
d471ea57 14134
444abaca 14135 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 14136 "Z4", "access-watchpoint", 0);
d471ea57 14137
0876f84a
DJ
14138 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14139 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 14140
c78fa86a
GB
14141 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14142 "qXfer:exec-file:read", "pid-to-exec-file", 0);
14143
23181151
DJ
14144 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14145 "qXfer:features:read", "target-features", 0);
14146
cfa9d6d9
DJ
14147 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14148 "qXfer:libraries:read", "library-info", 0);
14149
2268b414
JK
14150 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14151 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14152
fd79ecee
DJ
14153 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14154 "qXfer:memory-map:read", "memory-map", 0);
14155
0e7f50da
UW
14156 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14157 "qXfer:spu:read", "read-spu-object", 0);
14158
14159 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14160 "qXfer:spu:write", "write-spu-object", 0);
14161
07e059b5
VP
14162 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14163 "qXfer:osdata:read", "osdata", 0);
14164
dc146f7c
VP
14165 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14166 "qXfer:threads:read", "threads", 0);
14167
4aa995e1
PA
14168 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14169 "qXfer:siginfo:read", "read-siginfo-object", 0);
14170
14171 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14172 "qXfer:siginfo:write", "write-siginfo-object", 0);
14173
b3b9301e
PA
14174 add_packet_config_cmd
14175 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 14176 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 14177
169081d0
TG
14178 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14179 "qXfer:uib:read", "unwind-info-block", 0);
14180
444abaca 14181 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 14182 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
14183 0);
14184
711e434b
PM
14185 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14186 "qGetTIBAddr", "get-thread-information-block-address",
14187 0);
14188
40ab02ce
MS
14189 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14190 "bc", "reverse-continue", 0);
14191
14192 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14193 "bs", "reverse-step", 0);
14194
be2a5f71
DJ
14195 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14196 "qSupported", "supported-packets", 0);
14197
08388c79
DE
14198 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14199 "qSearch:memory", "search-memory", 0);
14200
bd3eecc3
PA
14201 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14202 "qTStatus", "trace-status", 0);
14203
15a201c8
GB
14204 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14205 "vFile:setfs", "hostio-setfs", 0);
14206
a6b151f1
DJ
14207 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14208 "vFile:open", "hostio-open", 0);
14209
14210 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14211 "vFile:pread", "hostio-pread", 0);
14212
14213 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14214 "vFile:pwrite", "hostio-pwrite", 0);
14215
14216 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14217 "vFile:close", "hostio-close", 0);
14218
14219 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14220 "vFile:unlink", "hostio-unlink", 0);
14221
b9e7b9c3
UW
14222 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14223 "vFile:readlink", "hostio-readlink", 0);
14224
0a93529c
GB
14225 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14226 "vFile:fstat", "hostio-fstat", 0);
14227
2d717e4f
DJ
14228 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14229 "vAttach", "attach", 0);
14230
14231 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14232 "vRun", "run", 0);
14233
a6f3e723
SL
14234 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14235 "QStartNoAckMode", "noack", 0);
14236
82f73884
PA
14237 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14238 "vKill", "kill", 0);
14239
0b16c5cf
PA
14240 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14241 "qAttached", "query-attached", 0);
14242
782b2b07 14243 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
14244 "ConditionalTracepoints",
14245 "conditional-tracepoints", 0);
3788aec7
LM
14246
14247 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14248 "ConditionalBreakpoints",
14249 "conditional-breakpoints", 0);
14250
d3ce09f5
SS
14251 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14252 "BreakpointCommands",
14253 "breakpoint-commands", 0);
14254
7a697b8d
SS
14255 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14256 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 14257
409873ef
SS
14258 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14259 "TracepointSource", "TracepointSource", 0);
14260
d914c394
SS
14261 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14262 "QAllow", "allow", 0);
14263
0fb4aa4b
PA
14264 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14265 "StaticTracepoints", "static-tracepoints", 0);
14266
1e4d1764
YQ
14267 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14268 "InstallInTrace", "install-in-trace", 0);
14269
0fb4aa4b
PA
14270 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14271 "qXfer:statictrace:read", "read-sdata-object", 0);
14272
78d85199
YQ
14273 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14274 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14275
03583c20
UW
14276 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14277 "QDisableRandomization", "disable-randomization", 0);
14278
d1feda86
YQ
14279 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14280 "QAgent", "agent", 0);
14281
f6f899bf
HAQ
14282 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14283 "QTBuffer:size", "trace-buffer-size", 0);
14284
9accd112
MM
14285 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14286 "Qbtrace:off", "disable-btrace", 0);
14287
14288 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
14289 "Qbtrace:bts", "enable-btrace-bts", 0);
14290
14291 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14292 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
14293
14294 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14295 "qXfer:btrace", "read-btrace", 0);
14296
f4abbc16
MM
14297 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14298 "qXfer:btrace-conf", "read-btrace-conf", 0);
14299
d33501a5
MM
14300 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14301 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14302
73b8c1fd
PA
14303 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14304 "multiprocess-feature", "multiprocess-feature", 0);
14305
f7e6eed5
PA
14306 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14307 "swbreak-feature", "swbreak-feature", 0);
14308
14309 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14310 "hwbreak-feature", "hwbreak-feature", 0);
14311
89245bc0
DB
14312 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14313 "fork-event-feature", "fork-event-feature", 0);
14314
14315 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14316 "vfork-event-feature", "vfork-event-feature", 0);
14317
b20a6524
MM
14318 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14319 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14320
750ce8d1
YQ
14321 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14322 "vContSupported", "verbose-resume-supported", 0);
14323
94585166
DB
14324 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14325 "exec-event-feature", "exec-event-feature", 0);
14326
de979965
PA
14327 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14328 "vCtrlC", "ctrl-c", 0);
14329
65706a29
PA
14330 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14331 "QThreadEvents", "thread-events", 0);
14332
f2faf941
PA
14333 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14334 "N stop reply", "no-resumed-stop-reply", 0);
14335
0b736949
DB
14336 /* Assert that we've registered "set remote foo-packet" commands
14337 for all packet configs. */
ca4f7f8b
PA
14338 {
14339 int i;
14340
14341 for (i = 0; i < PACKET_MAX; i++)
14342 {
14343 /* Ideally all configs would have a command associated. Some
14344 still don't though. */
14345 int excepted;
14346
14347 switch (i)
14348 {
14349 case PACKET_QNonStop:
ca4f7f8b
PA
14350 case PACKET_EnableDisableTracepoints_feature:
14351 case PACKET_tracenz_feature:
14352 case PACKET_DisconnectedTracing_feature:
14353 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
14354 case PACKET_qCRC:
14355 /* Additions to this list need to be well justified:
14356 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
14357 excepted = 1;
14358 break;
14359 default:
14360 excepted = 0;
14361 break;
14362 }
14363
14364 /* This catches both forgetting to add a config command, and
14365 forgetting to remove a packet from the exception list. */
14366 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14367 }
14368 }
14369
37a105a1
DJ
14370 /* Keep the old ``set remote Z-packet ...'' working. Each individual
14371 Z sub-packet has its own set and show commands, but users may
14372 have sets to this variable in their .gdbinit files (or in their
14373 documentation). */
e9e68a56 14374 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
14375 &remote_Z_packet_detect, _("\
14376Set use of remote protocol `Z' packets"), _("\
14377Show use of remote protocol `Z' packets "), _("\
3b64bf98 14378When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 14379packets."),
e9e68a56 14380 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
14381 show_remote_protocol_Z_packet_cmd,
14382 /* FIXME: i18n: Use of remote protocol
14383 `Z' packets is %s. */
e9e68a56 14384 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 14385
a6b151f1
DJ
14386 add_prefix_cmd ("remote", class_files, remote_command, _("\
14387Manipulate files on the remote system\n\
14388Transfer files to and from the remote target system."),
14389 &remote_cmdlist, "remote ",
14390 0 /* allow-unknown */, &cmdlist);
14391
14392 add_cmd ("put", class_files, remote_put_command,
14393 _("Copy a local file to the remote system."),
14394 &remote_cmdlist);
14395
14396 add_cmd ("get", class_files, remote_get_command,
14397 _("Copy a remote file to the local system."),
14398 &remote_cmdlist);
14399
14400 add_cmd ("delete", class_files, remote_delete_command,
14401 _("Delete a remote file."),
14402 &remote_cmdlist);
14403
2d717e4f 14404 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 14405 &remote_exec_file_var, _("\
2d717e4f 14406Set the remote pathname for \"run\""), _("\
94585166
DB
14407Show the remote pathname for \"run\""), NULL,
14408 set_remote_exec_file,
14409 show_remote_exec_file,
14410 &remote_set_cmdlist,
14411 &remote_show_cmdlist);
2d717e4f 14412
c1e36e3e
PA
14413 add_setshow_boolean_cmd ("range-stepping", class_run,
14414 &use_range_stepping, _("\
14415Enable or disable range stepping."), _("\
14416Show whether target-assisted range stepping is enabled."), _("\
14417If on, and the target supports it, when stepping a source line, GDB\n\
14418tells the target to step the corresponding range of addresses itself instead\n\
14419of issuing multiple single-steps. This speeds up source level\n\
14420stepping. If off, GDB always issues single-steps, even if range\n\
14421stepping is supported by the target. The default is on."),
14422 set_range_stepping,
14423 show_range_stepping,
14424 &setlist,
14425 &showlist);
14426
449092f6
CV
14427 /* Eventually initialize fileio. See fileio.c */
14428 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 14429
ba348170 14430 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 14431 special ptids with it set to != 0. */
ba348170
PA
14432 magic_null_ptid = ptid_build (42000, -1, 1);
14433 not_sent_ptid = ptid_build (42000, -2, 1);
14434 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
14435
14436 target_buf_size = 2048;
224c3ddb 14437 target_buf = (char *) xmalloc (target_buf_size);
c906108c 14438}
10760264 14439
This page took 4.635875 seconds and 4 git commands to generate.