]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
Run gdb.base/disp-step-syscall.exp for aarch64-linux
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
32d0add0 3 Copyright (C) 1988-2015 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"
35b1e5cc 73
0df8b418 74/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
75static char *target_buf;
76static long target_buf_size;
35b1e5cc 77
94585166
DB
78/* Per-program-space data key. */
79static const struct program_space_data *remote_pspace_data;
80
81/* The variable registered as the control variable used by the
82 remote exec-file commands. While the remote exec-file setting is
83 per-program-space, the set/show machinery uses this as the
84 location of the remote exec-file value. */
85static char *remote_exec_file_var;
86
6765f3e5
DJ
87/* The size to align memory write packets, when practical. The protocol
88 does not guarantee any alignment, and gdb will generate short
89 writes and unaligned writes, but even as a best-effort attempt this
90 can improve bulk transfers. For instance, if a write is misaligned
91 relative to the target's data bus, the stub may need to make an extra
92 round trip fetching data from the target. This doesn't make a
93 huge difference, but it's easy to do, so we try to be helpful.
94
95 The alignment chosen is arbitrary; usually data bus width is
96 important here, not the possibly larger cache line size. */
97enum { REMOTE_ALIGN_WRITES = 16 };
98
23860348 99/* Prototypes for local functions. */
934b9bac 100static void async_cleanup_sigint_signal_handler (void *dummy);
6d820c5c 101static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 102static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 103 int forever, int *is_notif);
6426a772 104
934b9bac
JK
105static void async_handle_remote_sigint (int);
106static void async_handle_remote_sigint_twice (int);
43ff13b4 107
a14ed312 108static void remote_files_info (struct target_ops *ignore);
c906108c 109
f32dbf8c
MM
110static void remote_prepare_to_store (struct target_ops *self,
111 struct regcache *regcache);
c906108c 112
014f9477
TT
113static void remote_open_1 (const char *, int, struct target_ops *,
114 int extended_p);
c906108c 115
de90e03d 116static void remote_close (struct target_ops *self);
c906108c 117
cbb8991c
DB
118struct remote_state;
119
120static int remote_vkill (int pid, struct remote_state *rs);
121
136d6dae 122static void remote_mourn (struct target_ops *ops);
c906108c 123
a14ed312 124static void extended_remote_restart (void);
c906108c 125
136d6dae 126static void extended_remote_mourn (struct target_ops *);
c906108c 127
6d820c5c 128static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 129
a14ed312 130static int readchar (int timeout);
c906108c 131
c33e31fd
PA
132static void remote_serial_write (const char *str, int len);
133
7d85a9c0 134static void remote_kill (struct target_ops *ops);
c906108c 135
6a109b6b 136static int remote_can_async_p (struct target_ops *);
75c99385 137
6a109b6b 138static int remote_is_async_p (struct target_ops *);
75c99385 139
6a3753b3 140static void remote_async (struct target_ops *ops, int enable);
75c99385 141
65706a29
PA
142static void remote_thread_events (struct target_ops *ops, int enable);
143
934b9bac 144static void sync_remote_interrupt_twice (int signo);
7a292a7a 145
a14ed312 146static void interrupt_query (void);
c906108c 147
79d7f229
PA
148static void set_general_thread (struct ptid ptid);
149static void set_continue_thread (struct ptid ptid);
c906108c 150
a14ed312 151static void get_offsets (void);
c906108c 152
6d820c5c
DJ
153static void skip_frame (void);
154
155static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 156
a14ed312 157static int hexnumlen (ULONGEST num);
c906108c 158
a14ed312 159static void init_remote_ops (void);
c906108c 160
a14ed312 161static void init_extended_remote_ops (void);
c906108c 162
1eab8a48 163static void remote_stop (struct target_ops *self, ptid_t);
c906108c 164
a14ed312 165static int stubhex (int ch);
c906108c 166
a14ed312 167static int hexnumstr (char *, ULONGEST);
c906108c 168
a14ed312 169static int hexnumnstr (char *, ULONGEST, int);
2df3850c 170
a14ed312 171static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 172
baa336ce 173static void print_packet (const char *);
c906108c 174
a14ed312 175static void compare_sections_command (char *, int);
c906108c 176
a14ed312 177static void packet_command (char *, int);
c906108c 178
a14ed312 179static int stub_unpack_int (char *buff, int fieldlength);
c906108c 180
39f77062 181static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 182
baa336ce 183static int putpkt_binary (const char *buf, int cnt);
c906108c 184
a14ed312 185static void check_binary_download (CORE_ADDR addr);
c906108c 186
5a2468f5 187struct packet_config;
5a2468f5 188
a14ed312 189static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 190
bb572ddd
DJ
191static void show_remote_protocol_packet_cmd (struct ui_file *file,
192 int from_tty,
193 struct cmd_list_element *c,
194 const char *value);
195
82f73884
PA
196static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
197static ptid_t read_ptid (char *buf, char **obuf);
198
c378d69d 199static void remote_set_permissions (struct target_ops *self);
d914c394 200
8bd200f1
TT
201static int remote_get_trace_status (struct target_ops *self,
202 struct trace_status *ts);
d5551862 203
ab6617cc
TT
204static int remote_upload_tracepoints (struct target_ops *self,
205 struct uploaded_tp **utpp);
00bf0b85 206
181e3713
TT
207static int remote_upload_trace_state_variables (struct target_ops *self,
208 struct uploaded_tsv **utsvp);
00bf0b85 209
c8d104ad
PA
210static void remote_query_supported (void);
211
36d25514 212static void remote_check_symbols (void);
c8d104ad 213
a14ed312 214void _initialize_remote (void);
c906108c 215
74531fed 216struct stop_reply;
74531fed 217static void stop_reply_xfree (struct stop_reply *);
722247f1 218static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 219static void push_stop_reply (struct stop_reply *);
bcc75809 220static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
221static int peek_stop_reply (ptid_t ptid);
222
cbb8991c
DB
223struct threads_listing_context;
224static void remove_new_fork_children (struct threads_listing_context *);
225
74531fed 226static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 227
e3594fd1 228static void remote_terminal_ours (struct target_ops *self);
d3fd5342 229
d962ef82
DJ
230static int remote_read_description_p (struct target_ops *target);
231
176a6961 232static void remote_console_output (char *msg);
dde08ee1 233
efcc2da7 234static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 235
78eff0ec 236static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 237
f4abbc16
MM
238static void remote_btrace_reset (void);
239
221e1a37
PA
240static int stop_reply_queue_length (void);
241
80152258
PA
242static void readahead_cache_invalidate (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
TT
365
366 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
367 remote_open knows that we don't have a file open when the program
368 starts. */
369 struct serial *remote_desc;
47f8a51d
TT
370
371 /* These are the threads which we last sent to the remote system. The
372 TID member will be -1 for all or -2 for not sent yet. */
373 ptid_t general_thread;
374 ptid_t continue_thread;
262e1174
TT
375
376 /* This is the traceframe which we last selected on the remote system.
377 It will be -1 if no traceframe is selected. */
378 int remote_traceframe_number;
747dc59d
TT
379
380 char *last_pass_packet;
5e4a05c4
TT
381
382 /* The last QProgramSignals packet sent to the target. We bypass
383 sending a new program signals list down to the target if the new
384 packet is exactly the same as the last we sent. IOW, we only let
385 the target know about program signals list changes. */
386 char *last_program_signals_packet;
b73be471
TT
387
388 enum gdb_signal last_sent_signal;
280ceea3
TT
389
390 int last_sent_step;
8e88304f
TT
391
392 char *finished_object;
393 char *finished_annex;
394 ULONGEST finished_offset;
b80fafe3
TT
395
396 /* Should we try the 'ThreadInfo' query packet?
397
398 This variable (NOT available to the user: auto-detect only!)
399 determines whether GDB will use the new, simpler "ThreadInfo"
400 query or the older, more complex syntax for thread queries.
401 This is an auto-detect variable (set to true at each connect,
402 and set to false when the target fails to recognize it). */
403 int use_threadinfo_query;
404 int use_threadextra_query;
88b496c3 405
0d031856
TT
406 threadref echo_nextthread;
407 threadref nextthread;
408 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
409
410 /* The state of remote notification. */
411 struct remote_notif_state *notif_state;
f4abbc16
MM
412
413 /* The branch trace configuration. */
414 struct btrace_config btrace_config;
15a201c8
GB
415
416 /* The argument to the last "vFile:setfs:" packet we sent, used
417 to avoid sending repeated unnecessary "vFile:setfs:" packets.
418 Initialized to -1 to indicate that no "vFile:setfs:" packet
419 has yet been sent. */
420 int fs_pid;
80152258
PA
421
422 /* A readahead cache for vFile:pread. Often, reading a binary
423 involves a sequence of small reads. E.g., when parsing an ELF
424 file. A readahead cache helps mostly the case of remote
425 debugging on a connection with higher latency, due to the
426 request/reply nature of the RSP. We only cache data for a single
427 file descriptor at a time. */
428 struct readahead_cache readahead_cache;
ea9c271d
DJ
429};
430
dc146f7c
VP
431/* Private data that we'll store in (struct thread_info)->private. */
432struct private_thread_info
433{
434 char *extra;
79efa585 435 char *name;
dc146f7c 436 int core;
799a2abe
PA
437
438 /* Whether the target stopped for a breakpoint/watchpoint. */
439 enum target_stop_reason stop_reason;
440
441 /* This is set to the data address of the access causing the target
442 to stop for a watchpoint. */
443 CORE_ADDR watch_data_address;
dc146f7c
VP
444};
445
446static void
447free_private_thread_info (struct private_thread_info *info)
448{
449 xfree (info->extra);
79efa585 450 xfree (info->name);
dc146f7c
VP
451 xfree (info);
452}
453
ea9c271d
DJ
454/* This data could be associated with a target, but we do not always
455 have access to the current target when we need it, so for now it is
456 static. This will be fine for as long as only one target is in use
457 at a time. */
cf792862 458static struct remote_state *remote_state;
ea9c271d
DJ
459
460static struct remote_state *
0b83947e 461get_remote_state_raw (void)
ea9c271d 462{
cf792862
TT
463 return remote_state;
464}
465
466/* Allocate a new struct remote_state with xmalloc, initialize it, and
467 return it. */
468
469static struct remote_state *
470new_remote_state (void)
471{
472 struct remote_state *result = XCNEW (struct remote_state);
473
474 /* The default buffer size is unimportant; it will be expanded
475 whenever a larger buffer is needed. */
476 result->buf_size = 400;
224c3ddb 477 result->buf = (char *) xmalloc (result->buf_size);
262e1174 478 result->remote_traceframe_number = -1;
b73be471 479 result->last_sent_signal = GDB_SIGNAL_0;
15a201c8 480 result->fs_pid = -1;
cf792862
TT
481
482 return result;
ea9c271d
DJ
483}
484
485/* Description of the remote protocol for a given architecture. */
d01949b6 486
ad10f812
AC
487struct packet_reg
488{
489 long offset; /* Offset into G packet. */
490 long regnum; /* GDB's internal register number. */
491 LONGEST pnum; /* Remote protocol register number. */
b323314b 492 int in_g_packet; /* Always part of G packet. */
f5656ead 493 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 494 at present. */
f5656ead 495 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 496 at present. */
ad10f812
AC
497};
498
ea9c271d 499struct remote_arch_state
d01949b6 500{
ad10f812
AC
501 /* Description of the remote protocol registers. */
502 long sizeof_g_packet;
b323314b
AC
503
504 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 505 (making an array gdbarch_num_regs in size). */
b323314b 506 struct packet_reg *regs;
ad10f812 507
d01949b6
AC
508 /* This is the size (in chars) of the first response to the ``g''
509 packet. It is used as a heuristic when determining the maximum
510 size of memory-read and memory-write packets. A target will
511 typically only reserve a buffer large enough to hold the ``g''
512 packet. The size does not include packet overhead (headers and
23860348 513 trailers). */
d01949b6
AC
514 long actual_register_packet_size;
515
516 /* This is the maximum size (in chars) of a non read/write packet.
23860348 517 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
518 long remote_packet_size;
519};
520
35b1e5cc
SS
521/* Utility: generate error from an incoming stub packet. */
522static void
523trace_error (char *buf)
524{
525 if (*buf++ != 'E')
526 return; /* not an error msg */
527 switch (*buf)
528 {
529 case '1': /* malformed packet error */
530 if (*++buf == '0') /* general case: */
531 error (_("remote.c: error in outgoing packet."));
532 else
533 error (_("remote.c: error in outgoing packet at field #%ld."),
534 strtol (buf, NULL, 16));
35b1e5cc
SS
535 default:
536 error (_("Target returns error code '%s'."), buf);
537 }
538}
539
540/* Utility: wait for reply from stub, while accepting "O" packets. */
541static char *
542remote_get_noisy_reply (char **buf_p,
543 long *sizeof_buf)
544{
545 do /* Loop on reply from remote stub. */
546 {
547 char *buf;
a744cf53 548
0df8b418 549 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
550 getpkt (buf_p, sizeof_buf, 0);
551 buf = *buf_p;
ad91cd99 552 if (buf[0] == 'E')
35b1e5cc 553 trace_error (buf);
61012eef 554 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
555 {
556 ULONGEST ul;
557 CORE_ADDR from, to, org_to;
558 char *p, *pp;
559 int adjusted_size = 0;
7556d4a4 560 int relocated = 0;
dde08ee1
PA
561
562 p = buf + strlen ("qRelocInsn:");
563 pp = unpack_varlen_hex (p, &ul);
564 if (*pp != ';')
cb91c06a 565 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
566 from = ul;
567
568 p = pp + 1;
a9cbf802 569 unpack_varlen_hex (p, &ul);
dde08ee1
PA
570 to = ul;
571
572 org_to = to;
573
492d29ea 574 TRY
dde08ee1 575 {
f5656ead 576 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 577 relocated = 1;
dde08ee1 578 }
492d29ea 579 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
580 {
581 if (ex.error == MEMORY_ERROR)
582 {
583 /* Propagate memory errors silently back to the
584 target. The stub may have limited the range of
585 addresses we can write to, for example. */
586 }
587 else
588 {
589 /* Something unexpectedly bad happened. Be verbose
590 so we can tell what, and propagate the error back
591 to the stub, so it doesn't get stuck waiting for
592 a response. */
593 exception_fprintf (gdb_stderr, ex,
594 _("warning: relocating instruction: "));
595 }
596 putpkt ("E01");
597 }
492d29ea 598 END_CATCH
7556d4a4
PA
599
600 if (relocated)
dde08ee1
PA
601 {
602 adjusted_size = to - org_to;
603
bba74b36 604 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
605 putpkt (buf);
606 }
dde08ee1 607 }
ad91cd99 608 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
609 remote_console_output (buf + 1); /* 'O' message from stub */
610 else
0df8b418 611 return buf; /* Here's the actual reply. */
35b1e5cc
SS
612 }
613 while (1);
614}
3c3bea1c 615
d01949b6
AC
616/* Handle for retreving the remote protocol data from gdbarch. */
617static struct gdbarch_data *remote_gdbarch_data_handle;
618
ea9c271d
DJ
619static struct remote_arch_state *
620get_remote_arch_state (void)
d01949b6 621{
17d8546e 622 gdb_assert (target_gdbarch () != NULL);
19ba03f4
SM
623 return ((struct remote_arch_state *)
624 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
d01949b6
AC
625}
626
0b83947e
DJ
627/* Fetch the global remote target state. */
628
629static struct remote_state *
630get_remote_state (void)
631{
632 /* Make sure that the remote architecture state has been
633 initialized, because doing so might reallocate rs->buf. Any
634 function which calls getpkt also needs to be mindful of changes
635 to rs->buf, but this call limits the number of places which run
636 into trouble. */
637 get_remote_arch_state ();
638
639 return get_remote_state_raw ();
640}
641
94585166
DB
642/* Cleanup routine for the remote module's pspace data. */
643
644static void
645remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
646{
19ba03f4 647 char *remote_exec_file = (char *) arg;
94585166
DB
648
649 xfree (remote_exec_file);
650}
651
652/* Fetch the remote exec-file from the current program space. */
653
654static const char *
655get_remote_exec_file (void)
656{
657 char *remote_exec_file;
658
19ba03f4
SM
659 remote_exec_file
660 = (char *) program_space_data (current_program_space,
661 remote_pspace_data);
94585166
DB
662 if (remote_exec_file == NULL)
663 return "";
664
665 return remote_exec_file;
666}
667
668/* Set the remote exec file for PSPACE. */
669
670static void
671set_pspace_remote_exec_file (struct program_space *pspace,
672 char *remote_exec_file)
673{
19ba03f4 674 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
675
676 xfree (old_file);
677 set_program_space_data (pspace, remote_pspace_data,
678 xstrdup (remote_exec_file));
679}
680
681/* The "set/show remote exec-file" set command hook. */
682
683static void
684set_remote_exec_file (char *ignored, int from_tty,
685 struct cmd_list_element *c)
686{
687 gdb_assert (remote_exec_file_var != NULL);
688 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
689}
690
691/* The "set/show remote exec-file" show command hook. */
692
693static void
694show_remote_exec_file (struct ui_file *file, int from_tty,
695 struct cmd_list_element *cmd, const char *value)
696{
697 fprintf_filtered (file, "%s\n", remote_exec_file_var);
698}
699
74ca34ce
DJ
700static int
701compare_pnums (const void *lhs_, const void *rhs_)
702{
19ba03f4
SM
703 const struct packet_reg * const *lhs
704 = (const struct packet_reg * const *) lhs_;
705 const struct packet_reg * const *rhs
706 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
707
708 if ((*lhs)->pnum < (*rhs)->pnum)
709 return -1;
710 else if ((*lhs)->pnum == (*rhs)->pnum)
711 return 0;
712 else
713 return 1;
714}
715
c21236dc
PA
716static int
717map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 718{
74ca34ce 719 int regnum, num_remote_regs, offset;
74ca34ce 720 struct packet_reg **remote_regs;
ea9c271d 721
4a22f64d 722 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 723 {
c21236dc 724 struct packet_reg *r = &regs[regnum];
baef701f 725
4a22f64d 726 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
727 /* Do not try to fetch zero-sized (placeholder) registers. */
728 r->pnum = -1;
729 else
730 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
731
b323314b 732 r->regnum = regnum;
74ca34ce
DJ
733 }
734
735 /* Define the g/G packet format as the contents of each register
736 with a remote protocol number, in order of ascending protocol
737 number. */
738
224c3ddb 739 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 740 for (num_remote_regs = 0, regnum = 0;
4a22f64d 741 regnum < gdbarch_num_regs (gdbarch);
f57d151a 742 regnum++)
c21236dc
PA
743 if (regs[regnum].pnum != -1)
744 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 745
74ca34ce
DJ
746 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
747 compare_pnums);
748
749 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
750 {
751 remote_regs[regnum]->in_g_packet = 1;
752 remote_regs[regnum]->offset = offset;
4a22f64d 753 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
754 }
755
c21236dc
PA
756 return offset;
757}
758
759/* Given the architecture described by GDBARCH, return the remote
760 protocol register's number and the register's offset in the g/G
761 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
762 If the target does not have a mapping for REGNUM, return false,
763 otherwise, return true. */
764
765int
766remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
767 int *pnum, int *poffset)
768{
769 int sizeof_g_packet;
770 struct packet_reg *regs;
771 struct cleanup *old_chain;
772
773 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
774
224c3ddb 775 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
c21236dc
PA
776 old_chain = make_cleanup (xfree, regs);
777
778 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
779
780 *pnum = regs[regnum].pnum;
781 *poffset = regs[regnum].offset;
782
783 do_cleanups (old_chain);
784
785 return *pnum != -1;
786}
787
788static void *
789init_remote_state (struct gdbarch *gdbarch)
790{
791 struct remote_state *rs = get_remote_state_raw ();
792 struct remote_arch_state *rsa;
793
794 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
795
796 /* Use the architecture to build a regnum<->pnum table, which will be
797 1:1 unless a feature set specifies otherwise. */
798 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
799 gdbarch_num_regs (gdbarch),
800 struct packet_reg);
801
74ca34ce
DJ
802 /* Record the maximum possible size of the g packet - it may turn out
803 to be smaller. */
c21236dc 804 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 805
0df8b418 806 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
807 remote stubs have a hardwired buffer size of 400 bytes
808 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
809 as the maximum packet-size to ensure that the packet and an extra
810 NUL character can always fit in the buffer. This stops GDB
811 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
812 already a full buffer (As of 1999-12-04 that was most stubs). */
813 rsa->remote_packet_size = 400 - 1;
d01949b6 814
ea9c271d
DJ
815 /* This one is filled in when a ``g'' packet is received. */
816 rsa->actual_register_packet_size = 0;
817
818 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
819 default, adjust the size accordingly. Remember that each byte is
820 encoded as two characters. 32 is the overhead for the packet
821 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 822 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 823 little. */
ea9c271d
DJ
824 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
825 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 826
ea9c271d
DJ
827 /* Make sure that the packet buffer is plenty big enough for
828 this architecture. */
829 if (rs->buf_size < rsa->remote_packet_size)
830 {
831 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 832 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 833 }
6d820c5c 834
ea9c271d
DJ
835 return rsa;
836}
837
838/* Return the current allowed size of a remote packet. This is
839 inferred from the current architecture, and should be used to
840 limit the length of outgoing packets. */
841static long
842get_remote_packet_size (void)
843{
be2a5f71 844 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
845 struct remote_arch_state *rsa = get_remote_arch_state ();
846
be2a5f71
DJ
847 if (rs->explicit_packet_size)
848 return rs->explicit_packet_size;
849
ea9c271d 850 return rsa->remote_packet_size;
d01949b6
AC
851}
852
ad10f812 853static struct packet_reg *
ea9c271d 854packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 855{
f5656ead 856 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
857 return NULL;
858 else
ad10f812 859 {
ea9c271d 860 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 861
b323314b
AC
862 gdb_assert (r->regnum == regnum);
863 return r;
ad10f812 864 }
ad10f812
AC
865}
866
867static struct packet_reg *
ea9c271d 868packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 869{
b323314b 870 int i;
a744cf53 871
f5656ead 872 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 873 {
ea9c271d 874 struct packet_reg *r = &rsa->regs[i];
a744cf53 875
b323314b
AC
876 if (r->pnum == pnum)
877 return r;
ad10f812
AC
878 }
879 return NULL;
d01949b6
AC
880}
881
c906108c
SS
882static struct target_ops remote_ops;
883
884static struct target_ops extended_remote_ops;
885
6426a772
JM
886/* FIXME: cagney/1999-09-23: Even though getpkt was called with
887 ``forever'' still use the normal timeout mechanism. This is
888 currently used by the ASYNC code to guarentee that target reads
889 during the initial connect always time-out. Once getpkt has been
890 modified to return a timeout indication and, in turn
891 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 892 this can go away. */
6426a772
JM
893static int wait_forever_enabled_p = 1;
894
9a7071a8
JB
895/* Allow the user to specify what sequence to send to the remote
896 when he requests a program interruption: Although ^C is usually
897 what remote systems expect (this is the default, here), it is
898 sometimes preferable to send a break. On other systems such
899 as the Linux kernel, a break followed by g, which is Magic SysRq g
900 is required in order to interrupt the execution. */
901const char interrupt_sequence_control_c[] = "Ctrl-C";
902const char interrupt_sequence_break[] = "BREAK";
903const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 904static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
905 {
906 interrupt_sequence_control_c,
907 interrupt_sequence_break,
908 interrupt_sequence_break_g,
909 NULL
910 };
911static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
912
913static void
914show_interrupt_sequence (struct ui_file *file, int from_tty,
915 struct cmd_list_element *c,
916 const char *value)
917{
918 if (interrupt_sequence_mode == interrupt_sequence_control_c)
919 fprintf_filtered (file,
920 _("Send the ASCII ETX character (Ctrl-c) "
921 "to the remote target to interrupt the "
922 "execution of the program.\n"));
923 else if (interrupt_sequence_mode == interrupt_sequence_break)
924 fprintf_filtered (file,
925 _("send a break signal to the remote target "
926 "to interrupt the execution of the program.\n"));
927 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
928 fprintf_filtered (file,
929 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
930 "the remote target to interrupt the execution "
931 "of Linux kernel.\n"));
932 else
933 internal_error (__FILE__, __LINE__,
934 _("Invalid value for interrupt_sequence_mode: %s."),
935 interrupt_sequence_mode);
936}
6426a772 937
9a7071a8
JB
938/* This boolean variable specifies whether interrupt_sequence is sent
939 to the remote target when gdb connects to it.
940 This is mostly needed when you debug the Linux kernel: The Linux kernel
941 expects BREAK g which is Magic SysRq g for connecting gdb. */
942static int interrupt_on_connect = 0;
c906108c 943
9a7071a8
JB
944/* This variable is used to implement the "set/show remotebreak" commands.
945 Since these commands are now deprecated in favor of "set/show remote
946 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
947static int remote_break;
948
9a7071a8
JB
949static void
950set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
951{
952 if (remote_break)
953 interrupt_sequence_mode = interrupt_sequence_break;
954 else
955 interrupt_sequence_mode = interrupt_sequence_control_c;
956}
957
958static void
959show_remotebreak (struct ui_file *file, int from_tty,
960 struct cmd_list_element *c,
961 const char *value)
962{
963}
964
c906108c
SS
965/* This variable sets the number of bits in an address that are to be
966 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 967 leading zeros, the entire address would be sent. This variable
c906108c
SS
968 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
969 initial implementation of remote.c restricted the address sent in
970 memory packets to ``host::sizeof long'' bytes - (typically 32
971 bits). Consequently, for 64 bit targets, the upper 32 bits of an
972 address was never sent. Since fixing this bug may cause a break in
973 some remote targets this variable is principly provided to
23860348 974 facilitate backward compatibility. */
c906108c 975
883b9c6c 976static unsigned int remote_address_size;
c906108c 977
75c99385
PA
978/* Temporary to track who currently owns the terminal. See
979 remote_terminal_* for more details. */
6426a772
JM
980
981static int remote_async_terminal_ours_p;
982
11cf8741 983\f
11cf8741 984/* User configurable variables for the number of characters in a
ea9c271d
DJ
985 memory read/write packet. MIN (rsa->remote_packet_size,
986 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 987 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
988 (speed up transfers). The variables ``preferred_*'' (the user
989 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 990 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
991
992struct memory_packet_config
993{
994 char *name;
995 long size;
996 int fixed_p;
997};
998
a5c0808e
PA
999/* The default max memory-write-packet-size. The 16k is historical.
1000 (It came from older GDB's using alloca for buffers and the
1001 knowledge (folklore?) that some hosts don't cope very well with
1002 large alloca calls.) */
1003#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1004
1005/* The minimum remote packet size for memory transfers. Ensures we
1006 can write at least one byte. */
1007#define MIN_MEMORY_PACKET_SIZE 20
1008
11cf8741
JM
1009/* Compute the current size of a read/write packet. Since this makes
1010 use of ``actual_register_packet_size'' the computation is dynamic. */
1011
1012static long
1013get_memory_packet_size (struct memory_packet_config *config)
1014{
d01949b6 1015 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
1016 struct remote_arch_state *rsa = get_remote_arch_state ();
1017
11cf8741
JM
1018 long what_they_get;
1019 if (config->fixed_p)
1020 {
1021 if (config->size <= 0)
a5c0808e 1022 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1023 else
1024 what_they_get = config->size;
1025 }
1026 else
1027 {
ea9c271d 1028 what_they_get = get_remote_packet_size ();
23860348 1029 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1030 if (config->size > 0
1031 && what_they_get > config->size)
1032 what_they_get = config->size;
be2a5f71
DJ
1033
1034 /* Limit it to the size of the targets ``g'' response unless we have
1035 permission from the stub to use a larger packet size. */
1036 if (rs->explicit_packet_size == 0
1037 && rsa->actual_register_packet_size > 0
1038 && what_they_get > rsa->actual_register_packet_size)
1039 what_they_get = rsa->actual_register_packet_size;
11cf8741 1040 }
a5c0808e
PA
1041 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1042 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1043
1044 /* Make sure there is room in the global buffer for this packet
1045 (including its trailing NUL byte). */
1046 if (rs->buf_size < what_they_get + 1)
1047 {
1048 rs->buf_size = 2 * what_they_get;
224c3ddb 1049 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1050 }
1051
11cf8741
JM
1052 return what_they_get;
1053}
1054
0df8b418 1055/* Update the size of a read/write packet. If they user wants
23860348 1056 something really big then do a sanity check. */
11cf8741
JM
1057
1058static void
1059set_memory_packet_size (char *args, struct memory_packet_config *config)
1060{
1061 int fixed_p = config->fixed_p;
1062 long size = config->size;
a744cf53 1063
11cf8741 1064 if (args == NULL)
8a3fe4f8 1065 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1066 else if (strcmp (args, "hard") == 0
1067 || strcmp (args, "fixed") == 0)
1068 fixed_p = 1;
1069 else if (strcmp (args, "soft") == 0
1070 || strcmp (args, "limit") == 0)
1071 fixed_p = 0;
1072 else
1073 {
1074 char *end;
a744cf53 1075
11cf8741
JM
1076 size = strtoul (args, &end, 0);
1077 if (args == end)
8a3fe4f8 1078 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1079
1080 /* Instead of explicitly capping the size of a packet to or
1081 disallowing it, the user is allowed to set the size to
1082 something arbitrarily large. */
11cf8741 1083 }
a5c0808e
PA
1084
1085 /* So that the query shows the correct value. */
1086 if (size <= 0)
1087 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1088
23860348 1089 /* Extra checks? */
11cf8741
JM
1090 if (fixed_p && !config->fixed_p)
1091 {
e2e0b3e5
AC
1092 if (! query (_("The target may not be able to correctly handle a %s\n"
1093 "of %ld bytes. Change the packet size? "),
11cf8741 1094 config->name, size))
8a3fe4f8 1095 error (_("Packet size not changed."));
11cf8741 1096 }
23860348 1097 /* Update the config. */
11cf8741
JM
1098 config->fixed_p = fixed_p;
1099 config->size = size;
1100}
1101
1102static void
1103show_memory_packet_size (struct memory_packet_config *config)
1104{
a3f17187 1105 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1106 if (config->fixed_p)
a3f17187 1107 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1108 get_memory_packet_size (config));
1109 else
a3f17187 1110 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1111 get_memory_packet_size (config));
1112}
1113
1114static struct memory_packet_config memory_write_packet_config =
1115{
1116 "memory-write-packet-size",
1117};
1118
1119static void
1120set_memory_write_packet_size (char *args, int from_tty)
1121{
1122 set_memory_packet_size (args, &memory_write_packet_config);
1123}
1124
1125static void
1126show_memory_write_packet_size (char *args, int from_tty)
1127{
1128 show_memory_packet_size (&memory_write_packet_config);
1129}
1130
1131static long
1132get_memory_write_packet_size (void)
1133{
1134 return get_memory_packet_size (&memory_write_packet_config);
1135}
1136
1137static struct memory_packet_config memory_read_packet_config =
1138{
1139 "memory-read-packet-size",
1140};
1141
1142static void
1143set_memory_read_packet_size (char *args, int from_tty)
1144{
1145 set_memory_packet_size (args, &memory_read_packet_config);
1146}
1147
1148static void
1149show_memory_read_packet_size (char *args, int from_tty)
1150{
1151 show_memory_packet_size (&memory_read_packet_config);
1152}
1153
1154static long
1155get_memory_read_packet_size (void)
1156{
1157 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1158
11cf8741
JM
1159 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1160 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1161 increased beyond this. */
1162 if (size > get_remote_packet_size ())
1163 size = get_remote_packet_size ();
11cf8741
JM
1164 return size;
1165}
1166
11cf8741 1167\f
5a2468f5 1168/* Generic configuration support for packets the stub optionally
0df8b418 1169 supports. Allows the user to specify the use of the packet as well
23860348 1170 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1171
1172enum packet_support
1173 {
1174 PACKET_SUPPORT_UNKNOWN = 0,
1175 PACKET_ENABLE,
1176 PACKET_DISABLE
1177 };
1178
5a2468f5
JM
1179struct packet_config
1180 {
bb572ddd
DJ
1181 const char *name;
1182 const char *title;
4082afcc
PA
1183
1184 /* If auto, GDB auto-detects support for this packet or feature,
1185 either through qSupported, or by trying the packet and looking
1186 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1187 packet. If false, the packet is disabled. Configs that don't
1188 have an associated command always have this set to auto. */
7f19b9a2 1189 enum auto_boolean detect;
4082afcc
PA
1190
1191 /* Does the target support this packet? */
5a2468f5
JM
1192 enum packet_support support;
1193 };
1194
d471ea57 1195/* Analyze a packet's return value and update the packet config
23860348 1196 accordingly. */
d471ea57
AC
1197
1198enum packet_result
1199{
1200 PACKET_ERROR,
1201 PACKET_OK,
1202 PACKET_UNKNOWN
1203};
1204
4082afcc
PA
1205static enum packet_support packet_config_support (struct packet_config *config);
1206static enum packet_support packet_support (int packet);
5a2468f5
JM
1207
1208static void
fba45db2 1209show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1210{
1211 char *support = "internal-error";
a744cf53 1212
4082afcc 1213 switch (packet_config_support (config))
5a2468f5
JM
1214 {
1215 case PACKET_ENABLE:
1216 support = "enabled";
1217 break;
1218 case PACKET_DISABLE:
1219 support = "disabled";
1220 break;
1221 case PACKET_SUPPORT_UNKNOWN:
1222 support = "unknown";
1223 break;
1224 }
1225 switch (config->detect)
1226 {
7f19b9a2 1227 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1228 printf_filtered (_("Support for the `%s' packet "
1229 "is auto-detected, currently %s.\n"),
37a105a1 1230 config->name, support);
5a2468f5 1231 break;
7f19b9a2
AC
1232 case AUTO_BOOLEAN_TRUE:
1233 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1234 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1235 config->name, support);
8e248173 1236 break;
5a2468f5
JM
1237 }
1238}
1239
1240static void
bb572ddd
DJ
1241add_packet_config_cmd (struct packet_config *config, const char *name,
1242 const char *title, int legacy)
d471ea57 1243{
5a2468f5
JM
1244 char *set_doc;
1245 char *show_doc;
d471ea57 1246 char *cmd_name;
3ed07be4 1247
5a2468f5
JM
1248 config->name = name;
1249 config->title = title;
b435e160
AC
1250 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1251 name, title);
3e43a32a
MS
1252 show_doc = xstrprintf ("Show current use of remote "
1253 "protocol `%s' (%s) packet",
b435e160 1254 name, title);
d471ea57 1255 /* set/show TITLE-packet {auto,on,off} */
b435e160 1256 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1257 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1258 &config->detect, set_doc,
1259 show_doc, NULL, /* help_doc */
4082afcc 1260 NULL,
bb572ddd
DJ
1261 show_remote_protocol_packet_cmd,
1262 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1263 /* The command code copies the documentation strings. */
1264 xfree (set_doc);
1265 xfree (show_doc);
23860348 1266 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1267 if (legacy)
1268 {
1269 char *legacy_name;
a744cf53 1270
b435e160 1271 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1272 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1273 &remote_set_cmdlist);
d471ea57 1274 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1275 &remote_show_cmdlist);
d471ea57 1276 }
5a2468f5
JM
1277}
1278
d471ea57 1279static enum packet_result
a76d924d 1280packet_check_result (const char *buf)
5a2468f5 1281{
d471ea57 1282 if (buf[0] != '\0')
5a2468f5 1283 {
d471ea57 1284 /* The stub recognized the packet request. Check that the
23860348 1285 operation succeeded. */
a76d924d
DJ
1286 if (buf[0] == 'E'
1287 && isxdigit (buf[1]) && isxdigit (buf[2])
1288 && buf[3] == '\0')
1289 /* "Enn" - definitly an error. */
1290 return PACKET_ERROR;
1291
1292 /* Always treat "E." as an error. This will be used for
1293 more verbose error messages, such as E.memtypes. */
1294 if (buf[0] == 'E' && buf[1] == '.')
1295 return PACKET_ERROR;
1296
1297 /* The packet may or may not be OK. Just assume it is. */
1298 return PACKET_OK;
1299 }
1300 else
1301 /* The stub does not support the packet. */
1302 return PACKET_UNKNOWN;
1303}
1304
1305static enum packet_result
1306packet_ok (const char *buf, struct packet_config *config)
1307{
1308 enum packet_result result;
1309
4082afcc
PA
1310 if (config->detect != AUTO_BOOLEAN_TRUE
1311 && config->support == PACKET_DISABLE)
1312 internal_error (__FILE__, __LINE__,
1313 _("packet_ok: attempt to use a disabled packet"));
1314
a76d924d
DJ
1315 result = packet_check_result (buf);
1316 switch (result)
1317 {
1318 case PACKET_OK:
1319 case PACKET_ERROR:
1320 /* The stub recognized the packet request. */
4082afcc 1321 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1322 {
d471ea57
AC
1323 if (remote_debug)
1324 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1325 "Packet %s (%s) is supported\n",
1326 config->name, config->title);
d471ea57 1327 config->support = PACKET_ENABLE;
d471ea57 1328 }
a76d924d
DJ
1329 break;
1330 case PACKET_UNKNOWN:
23860348 1331 /* The stub does not support the packet. */
4082afcc
PA
1332 if (config->detect == AUTO_BOOLEAN_AUTO
1333 && config->support == PACKET_ENABLE)
d471ea57 1334 {
4082afcc
PA
1335 /* If the stub previously indicated that the packet was
1336 supported then there is a protocol error. */
1337 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1338 config->name, config->title);
1339 }
1340 else if (config->detect == AUTO_BOOLEAN_TRUE)
1341 {
1342 /* The user set it wrong. */
1343 error (_("Enabled packet %s (%s) not recognized by stub"),
1344 config->name, config->title);
d471ea57 1345 }
4082afcc
PA
1346
1347 if (remote_debug)
1348 fprintf_unfiltered (gdb_stdlog,
1349 "Packet %s (%s) is NOT supported\n",
1350 config->name, config->title);
1351 config->support = PACKET_DISABLE;
a76d924d 1352 break;
5a2468f5 1353 }
a76d924d
DJ
1354
1355 return result;
5a2468f5
JM
1356}
1357
444abaca
DJ
1358enum {
1359 PACKET_vCont = 0,
1360 PACKET_X,
1361 PACKET_qSymbol,
1362 PACKET_P,
1363 PACKET_p,
1364 PACKET_Z0,
1365 PACKET_Z1,
1366 PACKET_Z2,
1367 PACKET_Z3,
1368 PACKET_Z4,
15a201c8 1369 PACKET_vFile_setfs,
a6b151f1
DJ
1370 PACKET_vFile_open,
1371 PACKET_vFile_pread,
1372 PACKET_vFile_pwrite,
1373 PACKET_vFile_close,
1374 PACKET_vFile_unlink,
b9e7b9c3 1375 PACKET_vFile_readlink,
0a93529c 1376 PACKET_vFile_fstat,
0876f84a 1377 PACKET_qXfer_auxv,
23181151 1378 PACKET_qXfer_features,
c78fa86a 1379 PACKET_qXfer_exec_file,
cfa9d6d9 1380 PACKET_qXfer_libraries,
2268b414 1381 PACKET_qXfer_libraries_svr4,
fd79ecee 1382 PACKET_qXfer_memory_map,
0e7f50da
UW
1383 PACKET_qXfer_spu_read,
1384 PACKET_qXfer_spu_write,
07e059b5 1385 PACKET_qXfer_osdata,
dc146f7c 1386 PACKET_qXfer_threads,
0fb4aa4b 1387 PACKET_qXfer_statictrace_read,
b3b9301e 1388 PACKET_qXfer_traceframe_info,
169081d0 1389 PACKET_qXfer_uib,
711e434b 1390 PACKET_qGetTIBAddr,
444abaca 1391 PACKET_qGetTLSAddr,
be2a5f71 1392 PACKET_qSupported,
bd3eecc3 1393 PACKET_qTStatus,
89be2091 1394 PACKET_QPassSignals,
9b224c5e 1395 PACKET_QProgramSignals,
936d2992 1396 PACKET_qCRC,
08388c79 1397 PACKET_qSearch_memory,
2d717e4f
DJ
1398 PACKET_vAttach,
1399 PACKET_vRun,
a6f3e723 1400 PACKET_QStartNoAckMode,
82f73884 1401 PACKET_vKill,
4aa995e1
PA
1402 PACKET_qXfer_siginfo_read,
1403 PACKET_qXfer_siginfo_write,
0b16c5cf 1404 PACKET_qAttached,
4082afcc
PA
1405
1406 /* Support for conditional tracepoints. */
782b2b07 1407 PACKET_ConditionalTracepoints,
4082afcc
PA
1408
1409 /* Support for target-side breakpoint conditions. */
3788aec7 1410 PACKET_ConditionalBreakpoints,
4082afcc
PA
1411
1412 /* Support for target-side breakpoint commands. */
d3ce09f5 1413 PACKET_BreakpointCommands,
4082afcc
PA
1414
1415 /* Support for fast tracepoints. */
7a697b8d 1416 PACKET_FastTracepoints,
4082afcc
PA
1417
1418 /* Support for static tracepoints. */
0fb4aa4b 1419 PACKET_StaticTracepoints,
4082afcc
PA
1420
1421 /* Support for installing tracepoints while a trace experiment is
1422 running. */
1e4d1764 1423 PACKET_InstallInTrace,
4082afcc 1424
40ab02ce
MS
1425 PACKET_bc,
1426 PACKET_bs,
409873ef 1427 PACKET_TracepointSource,
d914c394 1428 PACKET_QAllow,
78d85199 1429 PACKET_qXfer_fdpic,
03583c20 1430 PACKET_QDisableRandomization,
d1feda86 1431 PACKET_QAgent,
f6f899bf 1432 PACKET_QTBuffer_size,
9accd112
MM
1433 PACKET_Qbtrace_off,
1434 PACKET_Qbtrace_bts,
b20a6524 1435 PACKET_Qbtrace_pt,
9accd112 1436 PACKET_qXfer_btrace,
4082afcc
PA
1437
1438 /* Support for the QNonStop packet. */
1439 PACKET_QNonStop,
1440
65706a29
PA
1441 /* Support for the QThreadEvents packet. */
1442 PACKET_QThreadEvents,
1443
4082afcc
PA
1444 /* Support for multi-process extensions. */
1445 PACKET_multiprocess_feature,
1446
1447 /* Support for enabling and disabling tracepoints while a trace
1448 experiment is running. */
1449 PACKET_EnableDisableTracepoints_feature,
1450
1451 /* Support for collecting strings using the tracenz bytecode. */
1452 PACKET_tracenz_feature,
1453
1454 /* Support for continuing to run a trace experiment while GDB is
1455 disconnected. */
1456 PACKET_DisconnectedTracing_feature,
1457
1458 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1459 PACKET_augmented_libraries_svr4_read_feature,
1460
f4abbc16
MM
1461 /* Support for the qXfer:btrace-conf:read packet. */
1462 PACKET_qXfer_btrace_conf,
1463
d33501a5
MM
1464 /* Support for the Qbtrace-conf:bts:size packet. */
1465 PACKET_Qbtrace_conf_bts_size,
1466
f7e6eed5
PA
1467 /* Support for swbreak+ feature. */
1468 PACKET_swbreak_feature,
1469
1470 /* Support for hwbreak+ feature. */
1471 PACKET_hwbreak_feature,
1472
89245bc0
DB
1473 /* Support for fork events. */
1474 PACKET_fork_event_feature,
1475
1476 /* Support for vfork events. */
1477 PACKET_vfork_event_feature,
1478
b20a6524
MM
1479 /* Support for the Qbtrace-conf:pt:size packet. */
1480 PACKET_Qbtrace_conf_pt_size,
1481
94585166
DB
1482 /* Support for exec events. */
1483 PACKET_exec_event_feature,
1484
750ce8d1
YQ
1485 /* Support for query supported vCont actions. */
1486 PACKET_vContSupported,
1487
de979965
PA
1488 /* Support remote CTRL-C. */
1489 PACKET_vCtrlC,
1490
f2faf941
PA
1491 /* Support TARGET_WAITKIND_NO_RESUMED. */
1492 PACKET_no_resumed,
1493
444abaca
DJ
1494 PACKET_MAX
1495};
506fb367 1496
444abaca 1497static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1498
f7e6eed5
PA
1499/* Returns the packet's corresponding "set remote foo-packet" command
1500 state. See struct packet_config for more details. */
1501
1502static enum auto_boolean
1503packet_set_cmd_state (int packet)
1504{
1505 return remote_protocol_packets[packet].detect;
1506}
1507
4082afcc
PA
1508/* Returns whether a given packet or feature is supported. This takes
1509 into account the state of the corresponding "set remote foo-packet"
1510 command, which may be used to bypass auto-detection. */
dc8acb97 1511
4082afcc
PA
1512static enum packet_support
1513packet_config_support (struct packet_config *config)
1514{
1515 switch (config->detect)
444abaca 1516 {
4082afcc
PA
1517 case AUTO_BOOLEAN_TRUE:
1518 return PACKET_ENABLE;
1519 case AUTO_BOOLEAN_FALSE:
1520 return PACKET_DISABLE;
1521 case AUTO_BOOLEAN_AUTO:
1522 return config->support;
1523 default:
1524 gdb_assert_not_reached (_("bad switch"));
444abaca 1525 }
4082afcc
PA
1526}
1527
1528/* Same as packet_config_support, but takes the packet's enum value as
1529 argument. */
1530
1531static enum packet_support
1532packet_support (int packet)
1533{
1534 struct packet_config *config = &remote_protocol_packets[packet];
1535
1536 return packet_config_support (config);
dc8acb97
MS
1537}
1538
5a2468f5 1539static void
444abaca
DJ
1540show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1541 struct cmd_list_element *c,
1542 const char *value)
5a2468f5 1543{
444abaca 1544 struct packet_config *packet;
5a2468f5 1545
444abaca
DJ
1546 for (packet = remote_protocol_packets;
1547 packet < &remote_protocol_packets[PACKET_MAX];
1548 packet++)
1549 {
1550 if (&packet->detect == c->var)
1551 {
1552 show_packet_config_cmd (packet);
1553 return;
1554 }
1555 }
9b20d036 1556 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1557 c->name);
5a2468f5
JM
1558}
1559
d471ea57
AC
1560/* Should we try one of the 'Z' requests? */
1561
1562enum Z_packet_type
1563{
1564 Z_PACKET_SOFTWARE_BP,
1565 Z_PACKET_HARDWARE_BP,
1566 Z_PACKET_WRITE_WP,
1567 Z_PACKET_READ_WP,
1568 Z_PACKET_ACCESS_WP,
1569 NR_Z_PACKET_TYPES
1570};
96baa820 1571
d471ea57 1572/* For compatibility with older distributions. Provide a ``set remote
23860348 1573 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1574
7f19b9a2 1575static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1576
1577static void
fba45db2
KB
1578set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1579 struct cmd_list_element *c)
96baa820 1580{
d471ea57 1581 int i;
a744cf53 1582
d471ea57 1583 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1584 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1585}
1586
1587static void
08546159
AC
1588show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1589 struct cmd_list_element *c,
1590 const char *value)
96baa820 1591{
d471ea57 1592 int i;
a744cf53 1593
d471ea57
AC
1594 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1595 {
444abaca 1596 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1597 }
96baa820
JM
1598}
1599
4082afcc
PA
1600/* Returns true if the multi-process extensions are in effect. */
1601
1602static int
1603remote_multi_process_p (struct remote_state *rs)
1604{
1605 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1606}
1607
de0d863e
DB
1608/* Returns true if fork events are supported. */
1609
1610static int
1611remote_fork_event_p (struct remote_state *rs)
1612{
1613 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1614}
1615
c269dbdb
DB
1616/* Returns true if vfork events are supported. */
1617
1618static int
1619remote_vfork_event_p (struct remote_state *rs)
1620{
1621 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1622}
1623
d46addbb
DB
1624/* Returns true if exec events are supported. */
1625
1626static int
1627remote_exec_event_p (struct remote_state *rs)
1628{
1629 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1630}
1631
cbb8991c
DB
1632/* Insert fork catchpoint target routine. If fork events are enabled
1633 then return success, nothing more to do. */
1634
1635static int
1636remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1637{
1638 struct remote_state *rs = get_remote_state ();
1639
1640 return !remote_fork_event_p (rs);
1641}
1642
1643/* Remove fork catchpoint target routine. Nothing to do, just
1644 return success. */
1645
1646static int
1647remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1648{
1649 return 0;
1650}
1651
1652/* Insert vfork catchpoint target routine. If vfork events are enabled
1653 then return success, nothing more to do. */
1654
1655static int
1656remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1657{
1658 struct remote_state *rs = get_remote_state ();
1659
1660 return !remote_vfork_event_p (rs);
1661}
1662
1663/* Remove vfork catchpoint target routine. Nothing to do, just
1664 return success. */
1665
1666static int
1667remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1668{
1669 return 0;
1670}
1671
d46addbb
DB
1672/* Insert exec catchpoint target routine. If exec events are
1673 enabled, just return success. */
1674
1675static int
1676remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1677{
1678 struct remote_state *rs = get_remote_state ();
1679
1680 return !remote_exec_event_p (rs);
1681}
1682
1683/* Remove exec catchpoint target routine. Nothing to do, just
1684 return success. */
1685
1686static int
1687remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1688{
1689 return 0;
1690}
1691
23860348 1692/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1693static struct async_signal_handler *async_sigint_remote_twice_token;
1694static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1695
74531fed
PA
1696\f
1697/* Asynchronous signal handle registered as event loop source for
1698 when we have pending events ready to be passed to the core. */
1699
1700static struct async_event_handler *remote_async_inferior_event_token;
1701
c906108c
SS
1702\f
1703
79d7f229
PA
1704static ptid_t magic_null_ptid;
1705static ptid_t not_sent_ptid;
1706static ptid_t any_thread_ptid;
1707
0b16c5cf
PA
1708/* Find out if the stub attached to PID (and hence GDB should offer to
1709 detach instead of killing it when bailing out). */
1710
1711static int
1712remote_query_attached (int pid)
1713{
1714 struct remote_state *rs = get_remote_state ();
bba74b36 1715 size_t size = get_remote_packet_size ();
0b16c5cf 1716
4082afcc 1717 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1718 return 0;
1719
1720 if (remote_multi_process_p (rs))
bba74b36 1721 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1722 else
bba74b36 1723 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1724
1725 putpkt (rs->buf);
1726 getpkt (&rs->buf, &rs->buf_size, 0);
1727
1728 switch (packet_ok (rs->buf,
1554e9be 1729 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1730 {
1731 case PACKET_OK:
1732 if (strcmp (rs->buf, "1") == 0)
1733 return 1;
1734 break;
1735 case PACKET_ERROR:
1736 warning (_("Remote failure reply: %s"), rs->buf);
1737 break;
1738 case PACKET_UNKNOWN:
1739 break;
1740 }
1741
1742 return 0;
1743}
1744
49c62f2e
PA
1745/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1746 has been invented by GDB, instead of reported by the target. Since
1747 we can be connected to a remote system before before knowing about
1748 any inferior, mark the target with execution when we find the first
1749 inferior. If ATTACHED is 1, then we had just attached to this
1750 inferior. If it is 0, then we just created this inferior. If it
1751 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1752 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1753 attempt to open this inferior's executable as the main executable
1754 if no main executable is open already. */
1941c569
PA
1755
1756static struct inferior *
1b6e6f5c
GB
1757remote_add_inferior (int fake_pid_p, int pid, int attached,
1758 int try_open_exec)
1941c569 1759{
1941c569
PA
1760 struct inferior *inf;
1761
0b16c5cf
PA
1762 /* Check whether this process we're learning about is to be
1763 considered attached, or if is to be considered to have been
1764 spawned by the stub. */
1765 if (attached == -1)
1766 attached = remote_query_attached (pid);
1767
f5656ead 1768 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1769 {
1770 /* If the target shares code across all inferiors, then every
1771 attach adds a new inferior. */
1772 inf = add_inferior (pid);
1773
1774 /* ... and every inferior is bound to the same program space.
1775 However, each inferior may still have its own address
1776 space. */
1777 inf->aspace = maybe_new_address_space ();
1778 inf->pspace = current_program_space;
1779 }
1780 else
1781 {
1782 /* In the traditional debugging scenario, there's a 1-1 match
1783 between program/address spaces. We simply bind the inferior
1784 to the program space's address space. */
1785 inf = current_inferior ();
1786 inferior_appeared (inf, pid);
1787 }
1941c569 1788
0b16c5cf 1789 inf->attach_flag = attached;
49c62f2e 1790 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1791
1b6e6f5c
GB
1792 /* If no main executable is currently open then attempt to
1793 open the file that was executed to create this inferior. */
835205d0 1794 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1795 exec_file_locate_attach (pid, 1);
1796
1941c569
PA
1797 return inf;
1798}
1799
1800/* Add thread PTID to GDB's thread list. Tag it as executing/running
1801 according to RUNNING. */
1802
c906108c 1803static void
1941c569 1804remote_add_thread (ptid_t ptid, int running)
c906108c 1805{
b7ea362b
PA
1806 struct remote_state *rs = get_remote_state ();
1807
1808 /* GDB historically didn't pull threads in the initial connection
1809 setup. If the remote target doesn't even have a concept of
1810 threads (e.g., a bare-metal target), even if internally we
1811 consider that a single-threaded target, mentioning a new thread
1812 might be confusing to the user. Be silent then, preserving the
1813 age old behavior. */
1814 if (rs->starting_up)
1815 add_thread_silent (ptid);
1816 else
1817 add_thread (ptid);
1941c569
PA
1818
1819 set_executing (ptid, running);
1820 set_running (ptid, running);
1821}
1822
1823/* Come here when we learn about a thread id from the remote target.
1824 It may be the first time we hear about such thread, so take the
1825 opportunity to add it to GDB's thread list. In case this is the
1826 first time we're noticing its corresponding inferior, add it to
1827 GDB's inferior list as well. */
1828
1829static void
1830remote_notice_new_inferior (ptid_t currthread, int running)
1831{
c906108c
SS
1832 /* If this is a new thread, add it to GDB's thread list.
1833 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1834
1835 if (in_thread_list (currthread) && is_exited (currthread))
1836 {
1837 /* We're seeing an event on a thread id we knew had exited.
1838 This has to be a new thread reusing the old id. Add it. */
1941c569 1839 remote_add_thread (currthread, running);
82f73884
PA
1840 return;
1841 }
1842
79d7f229 1843 if (!in_thread_list (currthread))
c0a2216e 1844 {
1941c569 1845 struct inferior *inf = NULL;
bad34192 1846 int pid = ptid_get_pid (currthread);
1941c569 1847
bad34192
PA
1848 if (ptid_is_pid (inferior_ptid)
1849 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1850 {
1851 /* inferior_ptid has no thread member yet. This can happen
1852 with the vAttach -> remote_wait,"TAAthread:" path if the
1853 stub doesn't support qC. This is the first stop reported
1854 after an attach, so this is the main thread. Update the
1855 ptid in the thread list. */
bad34192
PA
1856 if (in_thread_list (pid_to_ptid (pid)))
1857 thread_change_ptid (inferior_ptid, currthread);
1858 else
1859 {
1860 remote_add_thread (currthread, running);
1861 inferior_ptid = currthread;
1862 }
dc146f7c 1863 return;
c0a2216e 1864 }
82f73884
PA
1865
1866 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1867 {
1868 /* inferior_ptid is not set yet. This can happen with the
1869 vRun -> remote_wait,"TAAthread:" path if the stub
1870 doesn't support qC. This is the first stop reported
1871 after an attach, so this is the main thread. Update the
1872 ptid in the thread list. */
dc146f7c 1873 thread_change_ptid (inferior_ptid, currthread);
82f73884 1874 return;
c0a2216e 1875 }
82f73884 1876
29c87f7f
PA
1877 /* When connecting to a target remote, or to a target
1878 extended-remote which already was debugging an inferior, we
1879 may not know about it yet. Add it before adding its child
1880 thread, so notifications are emitted in a sensible order. */
1881 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1882 {
1883 struct remote_state *rs = get_remote_state ();
1884 int fake_pid_p = !remote_multi_process_p (rs);
1885
1886 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1887 ptid_get_pid (currthread), -1, 1);
49c62f2e 1888 }
29c87f7f 1889
82f73884 1890 /* This is really a new thread. Add it. */
1941c569
PA
1891 remote_add_thread (currthread, running);
1892
1893 /* If we found a new inferior, let the common code do whatever
1894 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1895 breakpoints), unless we're just setting up an all-stop
1896 connection. */
1941c569 1897 if (inf != NULL)
b7ea362b
PA
1898 {
1899 struct remote_state *rs = get_remote_state ();
1900
6efcd9a8 1901 if (!rs->starting_up)
b7ea362b
PA
1902 notice_new_inferior (currthread, running, 0);
1903 }
c0a2216e 1904 }
c906108c
SS
1905}
1906
dc146f7c
VP
1907/* Return the private thread data, creating it if necessary. */
1908
70221824 1909static struct private_thread_info *
dc146f7c
VP
1910demand_private_info (ptid_t ptid)
1911{
1912 struct thread_info *info = find_thread_ptid (ptid);
1913
1914 gdb_assert (info);
1915
fe978cb0 1916 if (!info->priv)
dc146f7c 1917 {
8d749320 1918 info->priv = XNEW (struct private_thread_info);
dc146f7c 1919 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1920 info->priv->core = -1;
1921 info->priv->extra = 0;
dc146f7c
VP
1922 }
1923
fe978cb0 1924 return info->priv;
dc146f7c
VP
1925}
1926
74531fed
PA
1927/* Call this function as a result of
1928 1) A halt indication (T packet) containing a thread id
1929 2) A direct query of currthread
0df8b418 1930 3) Successful execution of set thread */
74531fed
PA
1931
1932static void
47f8a51d 1933record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1934{
47f8a51d 1935 rs->general_thread = currthread;
74531fed
PA
1936}
1937
89be2091
DJ
1938/* If 'QPassSignals' is supported, tell the remote stub what signals
1939 it can simply pass through to the inferior without reporting. */
1940
1941static void
94bedb42
TT
1942remote_pass_signals (struct target_ops *self,
1943 int numsigs, unsigned char *pass_signals)
89be2091 1944{
4082afcc 1945 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1946 {
1947 char *pass_packet, *p;
89be2091 1948 int count = 0, i;
747dc59d 1949 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1950
1951 gdb_assert (numsigs < 256);
1952 for (i = 0; i < numsigs; i++)
1953 {
2455069d 1954 if (pass_signals[i])
89be2091
DJ
1955 count++;
1956 }
224c3ddb 1957 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
1958 strcpy (pass_packet, "QPassSignals:");
1959 p = pass_packet + strlen (pass_packet);
1960 for (i = 0; i < numsigs; i++)
1961 {
2455069d 1962 if (pass_signals[i])
89be2091
DJ
1963 {
1964 if (i >= 16)
1965 *p++ = tohex (i >> 4);
1966 *p++ = tohex (i & 15);
1967 if (count)
1968 *p++ = ';';
1969 else
1970 break;
1971 count--;
1972 }
1973 }
1974 *p = 0;
747dc59d 1975 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1976 {
89be2091
DJ
1977 putpkt (pass_packet);
1978 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1979 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1980 if (rs->last_pass_packet)
1981 xfree (rs->last_pass_packet);
1982 rs->last_pass_packet = pass_packet;
89be2091
DJ
1983 }
1984 else
1985 xfree (pass_packet);
1986 }
1987}
1988
9b224c5e
PA
1989/* If 'QProgramSignals' is supported, tell the remote stub what
1990 signals it should pass through to the inferior when detaching. */
1991
1992static void
daf5e9b6
TT
1993remote_program_signals (struct target_ops *self,
1994 int numsigs, unsigned char *signals)
9b224c5e 1995{
4082afcc 1996 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1997 {
1998 char *packet, *p;
1999 int count = 0, i;
5e4a05c4 2000 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2001
2002 gdb_assert (numsigs < 256);
2003 for (i = 0; i < numsigs; i++)
2004 {
2005 if (signals[i])
2006 count++;
2007 }
224c3ddb 2008 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2009 strcpy (packet, "QProgramSignals:");
2010 p = packet + strlen (packet);
2011 for (i = 0; i < numsigs; i++)
2012 {
2013 if (signal_pass_state (i))
2014 {
2015 if (i >= 16)
2016 *p++ = tohex (i >> 4);
2017 *p++ = tohex (i & 15);
2018 if (count)
2019 *p++ = ';';
2020 else
2021 break;
2022 count--;
2023 }
2024 }
2025 *p = 0;
5e4a05c4
TT
2026 if (!rs->last_program_signals_packet
2027 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2028 {
9b224c5e
PA
2029 putpkt (packet);
2030 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2031 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2032 xfree (rs->last_program_signals_packet);
2033 rs->last_program_signals_packet = packet;
9b224c5e
PA
2034 }
2035 else
2036 xfree (packet);
2037 }
2038}
2039
79d7f229
PA
2040/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2041 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2042 thread. If GEN is set, set the general thread, if not, then set
2043 the step/continue thread. */
c906108c 2044static void
79d7f229 2045set_thread (struct ptid ptid, int gen)
c906108c 2046{
d01949b6 2047 struct remote_state *rs = get_remote_state ();
47f8a51d 2048 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2049 char *buf = rs->buf;
79d7f229 2050 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2051
79d7f229 2052 if (ptid_equal (state, ptid))
c906108c
SS
2053 return;
2054
79d7f229
PA
2055 *buf++ = 'H';
2056 *buf++ = gen ? 'g' : 'c';
2057 if (ptid_equal (ptid, magic_null_ptid))
2058 xsnprintf (buf, endbuf - buf, "0");
2059 else if (ptid_equal (ptid, any_thread_ptid))
2060 xsnprintf (buf, endbuf - buf, "0");
2061 else if (ptid_equal (ptid, minus_one_ptid))
2062 xsnprintf (buf, endbuf - buf, "-1");
2063 else
82f73884 2064 write_ptid (buf, endbuf, ptid);
79d7f229 2065 putpkt (rs->buf);
6d820c5c 2066 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2067 if (gen)
47f8a51d 2068 rs->general_thread = ptid;
c906108c 2069 else
47f8a51d 2070 rs->continue_thread = ptid;
c906108c 2071}
79d7f229
PA
2072
2073static void
2074set_general_thread (struct ptid ptid)
2075{
2076 set_thread (ptid, 1);
2077}
2078
2079static void
2080set_continue_thread (struct ptid ptid)
2081{
2082 set_thread (ptid, 0);
2083}
2084
3c9c4b83
PA
2085/* Change the remote current process. Which thread within the process
2086 ends up selected isn't important, as long as it is the same process
2087 as what INFERIOR_PTID points to.
2088
2089 This comes from that fact that there is no explicit notion of
2090 "selected process" in the protocol. The selected process for
2091 general operations is the process the selected general thread
2092 belongs to. */
2093
2094static void
2095set_general_process (void)
2096{
2097 struct remote_state *rs = get_remote_state ();
2098
2099 /* If the remote can't handle multiple processes, don't bother. */
901f9912 2100 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
2101 return;
2102
2103 /* We only need to change the remote current thread if it's pointing
2104 at some other process. */
47f8a51d 2105 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2106 set_general_thread (inferior_ptid);
2107}
2108
c906108c 2109\f
7d1a114c
PA
2110/* Return nonzero if this is the main thread that we made up ourselves
2111 to model non-threaded targets as single-threaded. */
c906108c
SS
2112
2113static int
7d1a114c 2114remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2115{
6d820c5c 2116 struct remote_state *rs = get_remote_state ();
82f73884 2117 char *p, *endp;
c906108c 2118
c0a2216e
PA
2119 if (ptid_equal (ptid, magic_null_ptid))
2120 /* The main thread is always alive. */
2121 return 1;
2122
ba348170 2123 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2124 /* The main thread is always alive. This can happen after a
2125 vAttach, if the remote side doesn't support
2126 multi-threading. */
2127 return 1;
2128
7d1a114c
PA
2129 return 0;
2130}
2131
2132/* Return nonzero if the thread PTID is still alive on the remote
2133 system. */
2134
2135static int
2136remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2137{
2138 struct remote_state *rs = get_remote_state ();
2139 char *p, *endp;
2140
2141 /* Check if this is a thread that we made up ourselves to model
2142 non-threaded targets as single-threaded. */
2143 if (remote_thread_always_alive (ops, ptid))
2144 return 1;
2145
82f73884
PA
2146 p = rs->buf;
2147 endp = rs->buf + get_remote_packet_size ();
2148
2149 *p++ = 'T';
2150 write_ptid (p, endp, ptid);
2151
2e9f7625 2152 putpkt (rs->buf);
6d820c5c 2153 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2154 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2155}
2156
79efa585
SM
2157/* Return a pointer to a thread name if we know it and NULL otherwise.
2158 The thread_info object owns the memory for the name. */
2159
2160static const char *
2161remote_thread_name (struct target_ops *ops, struct thread_info *info)
2162{
2163 if (info->priv != NULL)
2164 return info->priv->name;
2165
2166 return NULL;
2167}
2168
c906108c
SS
2169/* About these extended threadlist and threadinfo packets. They are
2170 variable length packets but, the fields within them are often fixed
2171 length. They are redundent enough to send over UDP as is the
2172 remote protocol in general. There is a matching unit test module
2173 in libstub. */
2174
23860348 2175/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2176 libstub protocol encoding, and remote.c. It is not particularly
23860348 2177 changable. */
cce74817
JM
2178
2179/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2180 Plan to fix this. */
cce74817 2181
23860348 2182typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2183
9d1f7ab2 2184/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2185 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2186
2187struct gdb_ext_thread_info
c5aa993b 2188 {
23860348 2189 threadref threadid; /* External form of thread reference. */
2bc416ba 2190 int active; /* Has state interesting to GDB?
23860348 2191 regs, stack. */
2bc416ba 2192 char display[256]; /* Brief state display, name,
cedea757 2193 blocked/suspended. */
23860348 2194 char shortname[32]; /* To be used to name threads. */
2bc416ba 2195 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2196 whatever. */
c5aa993b 2197 };
cce74817
JM
2198
2199/* The volume of remote transfers can be limited by submitting
2200 a mask containing bits specifying the desired information.
2201 Use a union of these values as the 'selection' parameter to
0df8b418 2202 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2203
2204#define TAG_THREADID 1
2205#define TAG_EXISTS 2
2206#define TAG_DISPLAY 4
2207#define TAG_THREADNAME 8
c5aa993b 2208#define TAG_MOREDISPLAY 16
cce74817 2209
23860348 2210#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2211
a14ed312 2212static char *unpack_nibble (char *buf, int *val);
cce74817 2213
a14ed312 2214static char *unpack_byte (char *buf, int *value);
cce74817 2215
a14ed312 2216static char *pack_int (char *buf, int value);
cce74817 2217
a14ed312 2218static char *unpack_int (char *buf, int *value);
cce74817 2219
a14ed312 2220static char *unpack_string (char *src, char *dest, int length);
cce74817 2221
23860348 2222static char *pack_threadid (char *pkt, threadref *id);
cce74817 2223
23860348 2224static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2225
23860348 2226void int_to_threadref (threadref *id, int value);
cce74817 2227
23860348 2228static int threadref_to_int (threadref *ref);
cce74817 2229
23860348 2230static void copy_threadref (threadref *dest, threadref *src);
cce74817 2231
23860348 2232static int threadmatch (threadref *dest, threadref *src);
cce74817 2233
2bc416ba 2234static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2235 threadref *id);
cce74817 2236
a14ed312 2237static int remote_unpack_thread_info_response (char *pkt,
23860348 2238 threadref *expectedref,
a14ed312
KB
2239 struct gdb_ext_thread_info
2240 *info);
cce74817
JM
2241
2242
2bc416ba 2243static int remote_get_threadinfo (threadref *threadid,
23860348 2244 int fieldset, /*TAG mask */
a14ed312 2245 struct gdb_ext_thread_info *info);
cce74817 2246
a14ed312
KB
2247static char *pack_threadlist_request (char *pkt, int startflag,
2248 int threadcount,
23860348 2249 threadref *nextthread);
cce74817 2250
a14ed312
KB
2251static int parse_threadlist_response (char *pkt,
2252 int result_limit,
23860348 2253 threadref *original_echo,
2bc416ba 2254 threadref *resultlist,
23860348 2255 int *doneflag);
cce74817 2256
a14ed312 2257static int remote_get_threadlist (int startflag,
23860348 2258 threadref *nextthread,
a14ed312
KB
2259 int result_limit,
2260 int *done,
2bc416ba 2261 int *result_count,
23860348 2262 threadref *threadlist);
cce74817 2263
23860348 2264typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2265
a14ed312
KB
2266static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2267 void *context, int looplimit);
cce74817 2268
23860348 2269static int remote_newthread_step (threadref *ref, void *context);
cce74817 2270
82f73884
PA
2271
2272/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2273 buffer we're allowed to write to. Returns
2274 BUF+CHARACTERS_WRITTEN. */
2275
2276static char *
2277write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2278{
2279 int pid, tid;
2280 struct remote_state *rs = get_remote_state ();
2281
2282 if (remote_multi_process_p (rs))
2283 {
2284 pid = ptid_get_pid (ptid);
2285 if (pid < 0)
2286 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2287 else
2288 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2289 }
ba348170 2290 tid = ptid_get_lwp (ptid);
82f73884
PA
2291 if (tid < 0)
2292 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2293 else
2294 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2295
2296 return buf;
2297}
2298
2299/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2300 passed the last parsed char. Returns null_ptid on error. */
2301
2302static ptid_t
2303read_ptid (char *buf, char **obuf)
2304{
2305 char *p = buf;
2306 char *pp;
2307 ULONGEST pid = 0, tid = 0;
82f73884
PA
2308
2309 if (*p == 'p')
2310 {
2311 /* Multi-process ptid. */
2312 pp = unpack_varlen_hex (p + 1, &pid);
2313 if (*pp != '.')
b37520b6 2314 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2315
2316 p = pp;
2317 pp = unpack_varlen_hex (p + 1, &tid);
2318 if (obuf)
2319 *obuf = pp;
ba348170 2320 return ptid_build (pid, tid, 0);
82f73884
PA
2321 }
2322
2323 /* No multi-process. Just a tid. */
2324 pp = unpack_varlen_hex (p, &tid);
2325
c9f35b34
KB
2326 /* Return null_ptid when no thread id is found. */
2327 if (p == pp)
2328 {
2329 if (obuf)
2330 *obuf = pp;
2331 return null_ptid;
2332 }
2333
82f73884 2334 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2335 what's in inferior_ptid, unless it's null at this point. If so,
2336 then since there's no way to know the pid of the reported
2337 threads, use the magic number. */
2338 if (ptid_equal (inferior_ptid, null_ptid))
2339 pid = ptid_get_pid (magic_null_ptid);
2340 else
2341 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2342
2343 if (obuf)
2344 *obuf = pp;
ba348170 2345 return ptid_build (pid, tid, 0);
82f73884
PA
2346}
2347
c906108c 2348static int
fba45db2 2349stubhex (int ch)
c906108c
SS
2350{
2351 if (ch >= 'a' && ch <= 'f')
2352 return ch - 'a' + 10;
2353 if (ch >= '0' && ch <= '9')
2354 return ch - '0';
2355 if (ch >= 'A' && ch <= 'F')
2356 return ch - 'A' + 10;
2357 return -1;
2358}
2359
2360static int
fba45db2 2361stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2362{
2363 int nibble;
2364 int retval = 0;
2365
2366 while (fieldlength)
2367 {
2368 nibble = stubhex (*buff++);
2369 retval |= nibble;
2370 fieldlength--;
2371 if (fieldlength)
2372 retval = retval << 4;
2373 }
2374 return retval;
2375}
2376
c906108c 2377static char *
fba45db2 2378unpack_nibble (char *buf, int *val)
c906108c 2379{
b7589f7d 2380 *val = fromhex (*buf++);
c906108c
SS
2381 return buf;
2382}
2383
c906108c 2384static char *
fba45db2 2385unpack_byte (char *buf, int *value)
c906108c
SS
2386{
2387 *value = stub_unpack_int (buf, 2);
2388 return buf + 2;
2389}
2390
2391static char *
fba45db2 2392pack_int (char *buf, int value)
c906108c
SS
2393{
2394 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2395 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2396 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2397 buf = pack_hex_byte (buf, (value & 0xff));
2398 return buf;
2399}
2400
2401static char *
fba45db2 2402unpack_int (char *buf, int *value)
c906108c
SS
2403{
2404 *value = stub_unpack_int (buf, 8);
2405 return buf + 8;
2406}
2407
23860348 2408#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2409static char *pack_string (char *pkt, char *string);
c906108c
SS
2410
2411static char *
fba45db2 2412pack_string (char *pkt, char *string)
c906108c
SS
2413{
2414 char ch;
2415 int len;
2416
2417 len = strlen (string);
2418 if (len > 200)
23860348 2419 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2420 pkt = pack_hex_byte (pkt, len);
2421 while (len-- > 0)
2422 {
2423 ch = *string++;
2424 if ((ch == '\0') || (ch == '#'))
23860348 2425 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2426 *pkt++ = ch;
2427 }
2428 return pkt;
2429}
2430#endif /* 0 (unused) */
2431
2432static char *
fba45db2 2433unpack_string (char *src, char *dest, int length)
c906108c
SS
2434{
2435 while (length--)
2436 *dest++ = *src++;
2437 *dest = '\0';
2438 return src;
2439}
2440
2441static char *
fba45db2 2442pack_threadid (char *pkt, threadref *id)
c906108c
SS
2443{
2444 char *limit;
2445 unsigned char *altid;
2446
2447 altid = (unsigned char *) id;
2448 limit = pkt + BUF_THREAD_ID_SIZE;
2449 while (pkt < limit)
2450 pkt = pack_hex_byte (pkt, *altid++);
2451 return pkt;
2452}
2453
2454
2455static char *
fba45db2 2456unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2457{
2458 char *altref;
2459 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2460 int x, y;
2461
2462 altref = (char *) id;
2463
2464 while (inbuf < limit)
2465 {
2466 x = stubhex (*inbuf++);
2467 y = stubhex (*inbuf++);
2468 *altref++ = (x << 4) | y;
2469 }
2470 return inbuf;
2471}
2472
2473/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2474 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2475 to use 64bit thread references internally. This is an adapter
2476 function. */
2477
2478void
fba45db2 2479int_to_threadref (threadref *id, int value)
c906108c
SS
2480{
2481 unsigned char *scan;
2482
2483 scan = (unsigned char *) id;
2484 {
2485 int i = 4;
2486 while (i--)
2487 *scan++ = 0;
2488 }
2489 *scan++ = (value >> 24) & 0xff;
2490 *scan++ = (value >> 16) & 0xff;
2491 *scan++ = (value >> 8) & 0xff;
2492 *scan++ = (value & 0xff);
2493}
2494
2495static int
fba45db2 2496threadref_to_int (threadref *ref)
c906108c
SS
2497{
2498 int i, value = 0;
2499 unsigned char *scan;
2500
cfd77fa1 2501 scan = *ref;
c906108c
SS
2502 scan += 4;
2503 i = 4;
2504 while (i-- > 0)
2505 value = (value << 8) | ((*scan++) & 0xff);
2506 return value;
2507}
2508
2509static void
fba45db2 2510copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2511{
2512 int i;
2513 unsigned char *csrc, *cdest;
2514
2515 csrc = (unsigned char *) src;
2516 cdest = (unsigned char *) dest;
2517 i = 8;
2518 while (i--)
2519 *cdest++ = *csrc++;
2520}
2521
2522static int
fba45db2 2523threadmatch (threadref *dest, threadref *src)
c906108c 2524{
23860348 2525 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2526#if 0
2527 unsigned char *srcp, *destp;
2528 int i, result;
2529 srcp = (char *) src;
2530 destp = (char *) dest;
2531
2532 result = 1;
2533 while (i-- > 0)
2534 result &= (*srcp++ == *destp++) ? 1 : 0;
2535 return result;
2536#endif
2537 return 1;
2538}
2539
2540/*
c5aa993b
JM
2541 threadid:1, # always request threadid
2542 context_exists:2,
2543 display:4,
2544 unique_name:8,
2545 more_display:16
2546 */
c906108c
SS
2547
2548/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2549
2550static char *
fba45db2 2551pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2552{
23860348
MS
2553 *pkt++ = 'q'; /* Info Query */
2554 *pkt++ = 'P'; /* process or thread info */
2555 pkt = pack_int (pkt, mode); /* mode */
c906108c 2556 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2557 *pkt = '\0'; /* terminate */
c906108c
SS
2558 return pkt;
2559}
2560
23860348 2561/* These values tag the fields in a thread info response packet. */
c906108c 2562/* Tagging the fields allows us to request specific fields and to
23860348 2563 add more fields as time goes by. */
c906108c 2564
23860348 2565#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2566#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2567 fetch registers and its stack? */
c5aa993b 2568#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2569#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2570#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2571 the process. */
c906108c
SS
2572
2573static int
fba45db2
KB
2574remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2575 struct gdb_ext_thread_info *info)
c906108c 2576{
d01949b6 2577 struct remote_state *rs = get_remote_state ();
c906108c 2578 int mask, length;
cfd77fa1 2579 int tag;
c906108c 2580 threadref ref;
6d820c5c 2581 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2582 int retval = 1;
2583
23860348 2584 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2585 info->active = 0;
2586 info->display[0] = '\0';
2587 info->shortname[0] = '\0';
2588 info->more_display[0] = '\0';
2589
23860348
MS
2590 /* Assume the characters indicating the packet type have been
2591 stripped. */
c906108c
SS
2592 pkt = unpack_int (pkt, &mask); /* arg mask */
2593 pkt = unpack_threadid (pkt, &ref);
2594
2595 if (mask == 0)
8a3fe4f8 2596 warning (_("Incomplete response to threadinfo request."));
c906108c 2597 if (!threadmatch (&ref, expectedref))
23860348 2598 { /* This is an answer to a different request. */
8a3fe4f8 2599 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2600 return 0;
2601 }
2602 copy_threadref (&info->threadid, &ref);
2603
23860348 2604 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2605
23860348
MS
2606 /* Packets are terminated with nulls. */
2607 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2608 {
2609 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2610 pkt = unpack_byte (pkt, &length); /* length */
2611 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2612 {
8a3fe4f8 2613 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2614 retval = 0;
2615 break;
2616 }
2617 if (tag == TAG_THREADID)
2618 {
2619 if (length != 16)
2620 {
8a3fe4f8 2621 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2622 retval = 0;
2623 break;
2624 }
2625 pkt = unpack_threadid (pkt, &ref);
2626 mask = mask & ~TAG_THREADID;
2627 continue;
2628 }
2629 if (tag == TAG_EXISTS)
2630 {
2631 info->active = stub_unpack_int (pkt, length);
2632 pkt += length;
2633 mask = mask & ~(TAG_EXISTS);
2634 if (length > 8)
2635 {
8a3fe4f8 2636 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2637 retval = 0;
2638 break;
2639 }
2640 continue;
2641 }
2642 if (tag == TAG_THREADNAME)
2643 {
2644 pkt = unpack_string (pkt, &info->shortname[0], length);
2645 mask = mask & ~TAG_THREADNAME;
2646 continue;
2647 }
2648 if (tag == TAG_DISPLAY)
2649 {
2650 pkt = unpack_string (pkt, &info->display[0], length);
2651 mask = mask & ~TAG_DISPLAY;
2652 continue;
2653 }
2654 if (tag == TAG_MOREDISPLAY)
2655 {
2656 pkt = unpack_string (pkt, &info->more_display[0], length);
2657 mask = mask & ~TAG_MOREDISPLAY;
2658 continue;
2659 }
8a3fe4f8 2660 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2661 break; /* Not a tag we know about. */
c906108c
SS
2662 }
2663 return retval;
2664}
2665
2666static int
fba45db2
KB
2667remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2668 struct gdb_ext_thread_info *info)
c906108c 2669{
d01949b6 2670 struct remote_state *rs = get_remote_state ();
c906108c 2671 int result;
c906108c 2672
2e9f7625
DJ
2673 pack_threadinfo_request (rs->buf, fieldset, threadid);
2674 putpkt (rs->buf);
6d820c5c 2675 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2676
2677 if (rs->buf[0] == '\0')
2678 return 0;
2679
2e9f7625 2680 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2681 threadid, info);
c906108c
SS
2682 return result;
2683}
2684
c906108c
SS
2685/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2686
2687static char *
fba45db2
KB
2688pack_threadlist_request (char *pkt, int startflag, int threadcount,
2689 threadref *nextthread)
c906108c
SS
2690{
2691 *pkt++ = 'q'; /* info query packet */
2692 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2693 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2694 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2695 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2696 *pkt = '\0';
2697 return pkt;
2698}
2699
2700/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2701
2702static int
fba45db2
KB
2703parse_threadlist_response (char *pkt, int result_limit,
2704 threadref *original_echo, threadref *resultlist,
2705 int *doneflag)
c906108c 2706{
d01949b6 2707 struct remote_state *rs = get_remote_state ();
c906108c
SS
2708 char *limit;
2709 int count, resultcount, done;
2710
2711 resultcount = 0;
2712 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2713 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2714 /* done parse past here */
c906108c
SS
2715 pkt = unpack_byte (pkt, &count); /* count field */
2716 pkt = unpack_nibble (pkt, &done);
2717 /* The first threadid is the argument threadid. */
2718 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2719 while ((count-- > 0) && (pkt < limit))
2720 {
2721 pkt = unpack_threadid (pkt, resultlist++);
2722 if (resultcount++ >= result_limit)
2723 break;
2724 }
2725 if (doneflag)
2726 *doneflag = done;
2727 return resultcount;
2728}
2729
6dc54d91
PA
2730/* Fetch the next batch of threads from the remote. Returns -1 if the
2731 qL packet is not supported, 0 on error and 1 on success. */
2732
c906108c 2733static int
fba45db2
KB
2734remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2735 int *done, int *result_count, threadref *threadlist)
c906108c 2736{
d01949b6 2737 struct remote_state *rs = get_remote_state ();
c906108c
SS
2738 int result = 1;
2739
23860348 2740 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2741 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2742 >= get_remote_packet_size ())
ea9c271d 2743 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2744
6d820c5c
DJ
2745 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2746 putpkt (rs->buf);
2747 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2748 if (*rs->buf == '\0')
6dc54d91
PA
2749 {
2750 /* Packet not supported. */
2751 return -1;
2752 }
2753
2754 *result_count =
2755 parse_threadlist_response (rs->buf + 2, result_limit,
2756 &rs->echo_nextthread, threadlist, done);
c906108c 2757
0d031856 2758 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2759 {
23860348
MS
2760 /* FIXME: This is a good reason to drop the packet. */
2761 /* Possably, there is a duplicate response. */
c906108c
SS
2762 /* Possabilities :
2763 retransmit immediatly - race conditions
2764 retransmit after timeout - yes
2765 exit
2766 wait for packet, then exit
2767 */
8a3fe4f8 2768 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2769 return 0; /* I choose simply exiting. */
c906108c
SS
2770 }
2771 if (*result_count <= 0)
2772 {
2773 if (*done != 1)
2774 {
8a3fe4f8 2775 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2776 result = 0;
2777 }
2778 return result; /* break; */
2779 }
2780 if (*result_count > result_limit)
2781 {
2782 *result_count = 0;
8a3fe4f8 2783 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2784 return 0;
2785 }
2786 return result;
2787}
2788
6dc54d91
PA
2789/* Fetch the list of remote threads, with the qL packet, and call
2790 STEPFUNCTION for each thread found. Stops iterating and returns 1
2791 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2792 STEPFUNCTION returns false. If the packet is not supported,
2793 returns -1. */
c906108c 2794
c906108c 2795static int
fba45db2
KB
2796remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2797 int looplimit)
c906108c 2798{
0d031856 2799 struct remote_state *rs = get_remote_state ();
c906108c
SS
2800 int done, i, result_count;
2801 int startflag = 1;
2802 int result = 1;
2803 int loopcount = 0;
c906108c
SS
2804
2805 done = 0;
2806 while (!done)
2807 {
2808 if (loopcount++ > looplimit)
2809 {
2810 result = 0;
8a3fe4f8 2811 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2812 break;
2813 }
6dc54d91
PA
2814 result = remote_get_threadlist (startflag, &rs->nextthread,
2815 MAXTHREADLISTRESULTS,
2816 &done, &result_count,
2817 rs->resultthreadlist);
2818 if (result <= 0)
2819 break;
23860348 2820 /* Clear for later iterations. */
c906108c
SS
2821 startflag = 0;
2822 /* Setup to resume next batch of thread references, set nextthread. */
2823 if (result_count >= 1)
0d031856
TT
2824 copy_threadref (&rs->nextthread,
2825 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2826 i = 0;
2827 while (result_count--)
6dc54d91
PA
2828 {
2829 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2830 {
2831 result = 0;
2832 break;
2833 }
2834 }
c906108c
SS
2835 }
2836 return result;
2837}
2838
6dc54d91
PA
2839/* A thread found on the remote target. */
2840
2841typedef struct thread_item
2842{
2843 /* The thread's PTID. */
2844 ptid_t ptid;
2845
2846 /* The thread's extra info. May be NULL. */
2847 char *extra;
2848
79efa585
SM
2849 /* The thread's name. May be NULL. */
2850 char *name;
2851
6dc54d91
PA
2852 /* The core the thread was running on. -1 if not known. */
2853 int core;
2854} thread_item_t;
2855DEF_VEC_O(thread_item_t);
2856
2857/* Context passed around to the various methods listing remote
2858 threads. As new threads are found, they're added to the ITEMS
2859 vector. */
2860
2861struct threads_listing_context
2862{
2863 /* The threads found on the remote target. */
2864 VEC (thread_item_t) *items;
2865};
2866
80134cf5
PA
2867/* Discard the contents of the constructed thread listing context. */
2868
2869static void
2870clear_threads_listing_context (void *p)
2871{
19ba03f4
SM
2872 struct threads_listing_context *context
2873 = (struct threads_listing_context *) p;
80134cf5
PA
2874 int i;
2875 struct thread_item *item;
2876
2877 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
2878 {
2879 xfree (item->extra);
2880 xfree (item->name);
2881 }
80134cf5
PA
2882
2883 VEC_free (thread_item_t, context->items);
2884}
2885
cbb8991c
DB
2886/* Remove the thread specified as the related_pid field of WS
2887 from the CONTEXT list. */
2888
2889static void
2890threads_listing_context_remove (struct target_waitstatus *ws,
2891 struct threads_listing_context *context)
2892{
2893 struct thread_item *item;
2894 int i;
2895 ptid_t child_ptid = ws->value.related_pid;
2896
2897 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2898 {
2899 if (ptid_equal (item->ptid, child_ptid))
2900 {
2901 VEC_ordered_remove (thread_item_t, context->items, i);
2902 break;
2903 }
2904 }
2905}
2906
c906108c 2907static int
6dc54d91 2908remote_newthread_step (threadref *ref, void *data)
c906108c 2909{
19ba03f4
SM
2910 struct threads_listing_context *context
2911 = (struct threads_listing_context *) data;
6dc54d91 2912 struct thread_item item;
79d7f229 2913 int pid = ptid_get_pid (inferior_ptid);
39f77062 2914
6dc54d91
PA
2915 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2916 item.core = -1;
2917 item.extra = NULL;
2918
2919 VEC_safe_push (thread_item_t, context->items, &item);
2920
c906108c
SS
2921 return 1; /* continue iterator */
2922}
2923
2924#define CRAZY_MAX_THREADS 1000
2925
39f77062
KB
2926static ptid_t
2927remote_current_thread (ptid_t oldpid)
c906108c 2928{
d01949b6 2929 struct remote_state *rs = get_remote_state ();
c906108c
SS
2930
2931 putpkt ("qC");
6d820c5c 2932 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2933 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
2934 {
2935 char *obuf;
2936 ptid_t result;
2937
2938 result = read_ptid (&rs->buf[2], &obuf);
2939 if (*obuf != '\0' && remote_debug)
2940 fprintf_unfiltered (gdb_stdlog,
2941 "warning: garbage in qC reply\n");
2942
2943 return result;
2944 }
c906108c
SS
2945 else
2946 return oldpid;
2947}
2948
6dc54d91 2949/* List remote threads using the deprecated qL packet. */
cce74817 2950
6dc54d91
PA
2951static int
2952remote_get_threads_with_ql (struct target_ops *ops,
2953 struct threads_listing_context *context)
c906108c 2954{
6dc54d91
PA
2955 if (remote_threadlist_iterator (remote_newthread_step, context,
2956 CRAZY_MAX_THREADS) >= 0)
2957 return 1;
2958
2959 return 0;
c906108c
SS
2960}
2961
dc146f7c
VP
2962#if defined(HAVE_LIBEXPAT)
2963
dc146f7c
VP
2964static void
2965start_thread (struct gdb_xml_parser *parser,
2966 const struct gdb_xml_element *element,
2967 void *user_data, VEC(gdb_xml_value_s) *attributes)
2968{
19ba03f4
SM
2969 struct threads_listing_context *data
2970 = (struct threads_listing_context *) user_data;
dc146f7c
VP
2971
2972 struct thread_item item;
2973 char *id;
3d2c1d41 2974 struct gdb_xml_value *attr;
dc146f7c 2975
19ba03f4 2976 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2977 item.ptid = read_ptid (id, NULL);
2978
3d2c1d41
PA
2979 attr = xml_find_attribute (attributes, "core");
2980 if (attr != NULL)
2981 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2982 else
2983 item.core = -1;
2984
79efa585 2985 attr = xml_find_attribute (attributes, "name");
e1961661 2986 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 2987
dc146f7c
VP
2988 item.extra = 0;
2989
2990 VEC_safe_push (thread_item_t, data->items, &item);
2991}
2992
2993static void
2994end_thread (struct gdb_xml_parser *parser,
2995 const struct gdb_xml_element *element,
2996 void *user_data, const char *body_text)
2997{
19ba03f4
SM
2998 struct threads_listing_context *data
2999 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3000
3001 if (body_text && *body_text)
2ae2a0b7 3002 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3003}
3004
3005const struct gdb_xml_attribute thread_attributes[] = {
3006 { "id", GDB_XML_AF_NONE, NULL, NULL },
3007 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3008 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3009 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3010};
3011
3012const struct gdb_xml_element thread_children[] = {
3013 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3014};
3015
3016const struct gdb_xml_element threads_children[] = {
3017 { "thread", thread_attributes, thread_children,
3018 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3019 start_thread, end_thread },
3020 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3021};
3022
3023const struct gdb_xml_element threads_elements[] = {
3024 { "threads", NULL, threads_children,
3025 GDB_XML_EF_NONE, NULL, NULL },
3026 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3027};
3028
3029#endif
3030
6dc54d91 3031/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3032
6dc54d91
PA
3033static int
3034remote_get_threads_with_qxfer (struct target_ops *ops,
3035 struct threads_listing_context *context)
0f71a2f6 3036{
dc146f7c 3037#if defined(HAVE_LIBEXPAT)
4082afcc 3038 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3039 {
6dc54d91 3040 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3041 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3042
6dc54d91 3043 if (xml != NULL && *xml != '\0')
dc146f7c 3044 {
6dc54d91
PA
3045 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3046 threads_elements, xml, context);
dc146f7c
VP
3047 }
3048
3049 do_cleanups (back_to);
6dc54d91 3050 return 1;
dc146f7c
VP
3051 }
3052#endif
3053
6dc54d91
PA
3054 return 0;
3055}
3056
3057/* List remote threads using qfThreadInfo/qsThreadInfo. */
3058
3059static int
3060remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3061 struct threads_listing_context *context)
3062{
3063 struct remote_state *rs = get_remote_state ();
3064
b80fafe3 3065 if (rs->use_threadinfo_query)
9d1f7ab2 3066 {
6dc54d91
PA
3067 char *bufp;
3068
9d1f7ab2 3069 putpkt ("qfThreadInfo");
6d820c5c 3070 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3071 bufp = rs->buf;
9d1f7ab2 3072 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3073 {
9d1f7ab2
MS
3074 while (*bufp++ == 'm') /* reply contains one or more TID */
3075 {
3076 do
3077 {
6dc54d91
PA
3078 struct thread_item item;
3079
3080 item.ptid = read_ptid (bufp, &bufp);
3081 item.core = -1;
3082 item.extra = NULL;
3083
3084 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3085 }
3086 while (*bufp++ == ','); /* comma-separated list */
3087 putpkt ("qsThreadInfo");
6d820c5c 3088 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3089 bufp = rs->buf;
9d1f7ab2 3090 }
6dc54d91
PA
3091 return 1;
3092 }
3093 else
3094 {
3095 /* Packet not recognized. */
3096 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3097 }
3098 }
3099
6dc54d91
PA
3100 return 0;
3101}
3102
e8032dde 3103/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3104 targets. */
3105
3106static void
e8032dde 3107remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
3108{
3109 struct remote_state *rs = get_remote_state ();
3110 struct threads_listing_context context;
3111 struct cleanup *old_chain;
ab970af1 3112 int got_list = 0;
e8032dde 3113
6dc54d91
PA
3114 context.items = NULL;
3115 old_chain = make_cleanup (clear_threads_listing_context, &context);
3116
3117 /* We have a few different mechanisms to fetch the thread list. Try
3118 them all, starting with the most preferred one first, falling
3119 back to older methods. */
3120 if (remote_get_threads_with_qxfer (ops, &context)
3121 || remote_get_threads_with_qthreadinfo (ops, &context)
3122 || remote_get_threads_with_ql (ops, &context))
3123 {
3124 int i;
3125 struct thread_item *item;
ab970af1
PA
3126 struct thread_info *tp, *tmp;
3127
3128 got_list = 1;
3129
7d1a114c
PA
3130 if (VEC_empty (thread_item_t, context.items)
3131 && remote_thread_always_alive (ops, inferior_ptid))
3132 {
3133 /* Some targets don't really support threads, but still
3134 reply an (empty) thread list in response to the thread
3135 listing packets, instead of replying "packet not
3136 supported". Exit early so we don't delete the main
3137 thread. */
3138 do_cleanups (old_chain);
3139 return;
3140 }
3141
ab970af1
PA
3142 /* CONTEXT now holds the current thread list on the remote
3143 target end. Delete GDB-side threads no longer found on the
3144 target. */
8a06aea7 3145 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3146 {
ab970af1
PA
3147 for (i = 0;
3148 VEC_iterate (thread_item_t, context.items, i, item);
3149 ++i)
3150 {
3151 if (ptid_equal (item->ptid, tp->ptid))
3152 break;
3153 }
3154
3155 if (i == VEC_length (thread_item_t, context.items))
3156 {
3157 /* Not found. */
3158 delete_thread (tp->ptid);
3159 }
cbb8991c
DB
3160 }
3161
3162 /* Remove any unreported fork child threads from CONTEXT so
3163 that we don't interfere with follow fork, which is where
3164 creation of such threads is handled. */
3165 remove_new_fork_children (&context);
74531fed 3166
ab970af1 3167 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3168 for (i = 0;
3169 VEC_iterate (thread_item_t, context.items, i, item);
3170 ++i)
3171 {
3172 if (!ptid_equal (item->ptid, null_ptid))
3173 {
3174 struct private_thread_info *info;
3175 /* In non-stop mode, we assume new found threads are
3176 running until proven otherwise with a stop reply. In
3177 all-stop, we can only get here if all threads are
3178 stopped. */
6efcd9a8 3179 int running = target_is_non_stop_p () ? 1 : 0;
6dc54d91
PA
3180
3181 remote_notice_new_inferior (item->ptid, running);
3182
3183 info = demand_private_info (item->ptid);
3184 info->core = item->core;
3185 info->extra = item->extra;
3186 item->extra = NULL;
79efa585
SM
3187 info->name = item->name;
3188 item->name = NULL;
6dc54d91
PA
3189 }
3190 }
3191 }
3192
ab970af1
PA
3193 if (!got_list)
3194 {
3195 /* If no thread listing method is supported, then query whether
3196 each known thread is alive, one by one, with the T packet.
3197 If the target doesn't support threads at all, then this is a
3198 no-op. See remote_thread_alive. */
3199 prune_threads ();
3200 }
3201
6dc54d91 3202 do_cleanups (old_chain);
9d1f7ab2
MS
3203}
3204
802188a7 3205/*
9d1f7ab2
MS
3206 * Collect a descriptive string about the given thread.
3207 * The target may say anything it wants to about the thread
3208 * (typically info about its blocked / runnable state, name, etc.).
3209 * This string will appear in the info threads display.
802188a7 3210 *
9d1f7ab2
MS
3211 * Optional: targets are not required to implement this function.
3212 */
3213
3214static char *
c15906d8 3215remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3216{
d01949b6 3217 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3218 int result;
3219 int set;
3220 threadref id;
3221 struct gdb_ext_thread_info threadinfo;
23860348 3222 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3223 int n = 0; /* position in display_buf */
3224
5d93a237 3225 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3226 internal_error (__FILE__, __LINE__,
e2e0b3e5 3227 _("remote_threads_extra_info"));
9d1f7ab2 3228
60e569b9 3229 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3230 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3231 /* This is the main thread which was added by GDB. The remote
3232 server doesn't know about it. */
3233 return NULL;
3234
4082afcc 3235 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3236 {
3237 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3238
fe978cb0
PA
3239 if (info && info->priv)
3240 return info->priv->extra;
dc146f7c
VP
3241 else
3242 return NULL;
3243 }
3244
b80fafe3 3245 if (rs->use_threadextra_query)
9d1f7ab2 3246 {
82f73884
PA
3247 char *b = rs->buf;
3248 char *endb = rs->buf + get_remote_packet_size ();
3249
3250 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3251 b += strlen (b);
3252 write_ptid (b, endb, tp->ptid);
3253
2e9f7625 3254 putpkt (rs->buf);
6d820c5c 3255 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3256 if (rs->buf[0] != 0)
9d1f7ab2 3257 {
2e9f7625
DJ
3258 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3259 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3260 display_buf [result] = '\0';
9d1f7ab2
MS
3261 return display_buf;
3262 }
0f71a2f6 3263 }
9d1f7ab2
MS
3264
3265 /* If the above query fails, fall back to the old method. */
b80fafe3 3266 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3267 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3268 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3269 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3270 if (remote_get_threadinfo (&id, set, &threadinfo))
3271 if (threadinfo.active)
0f71a2f6 3272 {
9d1f7ab2 3273 if (*threadinfo.shortname)
2bc416ba 3274 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3275 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3276 if (*threadinfo.display)
2bc416ba 3277 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3278 " State: %s,", threadinfo.display);
9d1f7ab2 3279 if (*threadinfo.more_display)
2bc416ba 3280 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3281 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3282
3283 if (n > 0)
c5aa993b 3284 {
23860348 3285 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3286 if (',' == display_buf[n-1])
3287 display_buf[n-1] = ' ';
3288 return display_buf;
c5aa993b 3289 }
0f71a2f6 3290 }
9d1f7ab2 3291 return NULL;
0f71a2f6 3292}
c906108c 3293\f
c5aa993b 3294
0fb4aa4b 3295static int
61fc905d 3296remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3297 struct static_tracepoint_marker *marker)
3298{
3299 struct remote_state *rs = get_remote_state ();
3300 char *p = rs->buf;
3301
bba74b36 3302 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3303 p += strlen (p);
3304 p += hexnumstr (p, addr);
3305 putpkt (rs->buf);
3306 getpkt (&rs->buf, &rs->buf_size, 0);
3307 p = rs->buf;
3308
3309 if (*p == 'E')
3310 error (_("Remote failure reply: %s"), p);
3311
3312 if (*p++ == 'm')
3313 {
3314 parse_static_tracepoint_marker_definition (p, &p, marker);
3315 return 1;
3316 }
3317
3318 return 0;
3319}
3320
0fb4aa4b 3321static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3322remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3323 const char *strid)
0fb4aa4b
PA
3324{
3325 struct remote_state *rs = get_remote_state ();
3326 VEC(static_tracepoint_marker_p) *markers = NULL;
3327 struct static_tracepoint_marker *marker = NULL;
3328 struct cleanup *old_chain;
3329 char *p;
3330
3331 /* Ask for a first packet of static tracepoint marker
3332 definition. */
3333 putpkt ("qTfSTM");
3334 getpkt (&rs->buf, &rs->buf_size, 0);
3335 p = rs->buf;
3336 if (*p == 'E')
3337 error (_("Remote failure reply: %s"), p);
3338
3339 old_chain = make_cleanup (free_current_marker, &marker);
3340
3341 while (*p++ == 'm')
3342 {
3343 if (marker == NULL)
3344 marker = XCNEW (struct static_tracepoint_marker);
3345
3346 do
3347 {
3348 parse_static_tracepoint_marker_definition (p, &p, marker);
3349
3350 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3351 {
3352 VEC_safe_push (static_tracepoint_marker_p,
3353 markers, marker);
3354 marker = NULL;
3355 }
3356 else
3357 {
3358 release_static_tracepoint_marker (marker);
3359 memset (marker, 0, sizeof (*marker));
3360 }
3361 }
3362 while (*p++ == ','); /* comma-separated list */
3363 /* Ask for another packet of static tracepoint definition. */
3364 putpkt ("qTsSTM");
3365 getpkt (&rs->buf, &rs->buf_size, 0);
3366 p = rs->buf;
3367 }
3368
3369 do_cleanups (old_chain);
3370 return markers;
3371}
3372
3373\f
10760264
JB
3374/* Implement the to_get_ada_task_ptid function for the remote targets. */
3375
3376static ptid_t
1e6b91a4 3377remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3378{
ba348170 3379 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3380}
3381\f
3382
24b06219 3383/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3384
3385static void
fba45db2 3386extended_remote_restart (void)
c906108c 3387{
d01949b6 3388 struct remote_state *rs = get_remote_state ();
c906108c
SS
3389
3390 /* Send the restart command; for reasons I don't understand the
3391 remote side really expects a number after the "R". */
ea9c271d 3392 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3393 putpkt (rs->buf);
c906108c 3394
ad9a8f3f 3395 remote_fileio_reset ();
c906108c
SS
3396}
3397\f
3398/* Clean up connection to a remote debugger. */
3399
c906108c 3400static void
de90e03d 3401remote_close (struct target_ops *self)
c906108c 3402{
5d93a237
TT
3403 struct remote_state *rs = get_remote_state ();
3404
3405 if (rs->remote_desc == NULL)
d3fd5342
PA
3406 return; /* already closed */
3407
3408 /* Make sure we leave stdin registered in the event loop, and we
3409 don't leave the async SIGINT signal handler installed. */
e3594fd1 3410 remote_terminal_ours (self);
ce5ce7ed 3411
5d93a237
TT
3412 serial_close (rs->remote_desc);
3413 rs->remote_desc = NULL;
ce5ce7ed
PA
3414
3415 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3416 of all the inferiors and their threads we were controlling.
3417 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3418 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3419 inferior_ptid = null_ptid;
f67fd822 3420 discard_all_inferiors ();
ce5ce7ed 3421
f48ff2a7
YQ
3422 /* We are closing the remote target, so we should discard
3423 everything of this target. */
bcc75809 3424 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3425
3426 if (remote_async_inferior_event_token)
3427 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3428
5965e028 3429 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3430
3431 trace_reset_local_state ();
c906108c
SS
3432}
3433
23860348 3434/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3435
3436static void
fba45db2 3437get_offsets (void)
c906108c 3438{
d01949b6 3439 struct remote_state *rs = get_remote_state ();
2e9f7625 3440 char *buf;
085dd6e6 3441 char *ptr;
31d99776
DJ
3442 int lose, num_segments = 0, do_sections, do_segments;
3443 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3444 struct section_offsets *offs;
31d99776
DJ
3445 struct symfile_segment_data *data;
3446
3447 if (symfile_objfile == NULL)
3448 return;
c906108c
SS
3449
3450 putpkt ("qOffsets");
6d820c5c 3451 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3452 buf = rs->buf;
c906108c
SS
3453
3454 if (buf[0] == '\000')
3455 return; /* Return silently. Stub doesn't support
23860348 3456 this command. */
c906108c
SS
3457 if (buf[0] == 'E')
3458 {
8a3fe4f8 3459 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3460 return;
3461 }
3462
3463 /* Pick up each field in turn. This used to be done with scanf, but
3464 scanf will make trouble if CORE_ADDR size doesn't match
3465 conversion directives correctly. The following code will work
3466 with any size of CORE_ADDR. */
3467 text_addr = data_addr = bss_addr = 0;
3468 ptr = buf;
3469 lose = 0;
3470
61012eef 3471 if (startswith (ptr, "Text="))
c906108c
SS
3472 {
3473 ptr += 5;
3474 /* Don't use strtol, could lose on big values. */
3475 while (*ptr && *ptr != ';')
3476 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3477
61012eef 3478 if (startswith (ptr, ";Data="))
31d99776
DJ
3479 {
3480 ptr += 6;
3481 while (*ptr && *ptr != ';')
3482 data_addr = (data_addr << 4) + fromhex (*ptr++);
3483 }
3484 else
3485 lose = 1;
3486
61012eef 3487 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3488 {
3489 ptr += 5;
3490 while (*ptr && *ptr != ';')
3491 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3492
31d99776
DJ
3493 if (bss_addr != data_addr)
3494 warning (_("Target reported unsupported offsets: %s"), buf);
3495 }
3496 else
3497 lose = 1;
3498 }
61012eef 3499 else if (startswith (ptr, "TextSeg="))
c906108c 3500 {
31d99776
DJ
3501 ptr += 8;
3502 /* Don't use strtol, could lose on big values. */
c906108c 3503 while (*ptr && *ptr != ';')
31d99776
DJ
3504 text_addr = (text_addr << 4) + fromhex (*ptr++);
3505 num_segments = 1;
3506
61012eef 3507 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3508 {
3509 ptr += 9;
3510 while (*ptr && *ptr != ';')
3511 data_addr = (data_addr << 4) + fromhex (*ptr++);
3512 num_segments++;
3513 }
c906108c
SS
3514 }
3515 else
3516 lose = 1;
3517
3518 if (lose)
8a3fe4f8 3519 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3520 else if (*ptr != '\0')
3521 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3522
802188a7 3523 offs = ((struct section_offsets *)
a39a16c4 3524 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3525 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3526 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3527
31d99776
DJ
3528 data = get_symfile_segment_data (symfile_objfile->obfd);
3529 do_segments = (data != NULL);
3530 do_sections = num_segments == 0;
c906108c 3531
28c32713 3532 if (num_segments > 0)
31d99776 3533 {
31d99776
DJ
3534 segments[0] = text_addr;
3535 segments[1] = data_addr;
3536 }
28c32713
JB
3537 /* If we have two segments, we can still try to relocate everything
3538 by assuming that the .text and .data offsets apply to the whole
3539 text and data segments. Convert the offsets given in the packet
3540 to base addresses for symfile_map_offsets_to_segments. */
3541 else if (data && data->num_segments == 2)
3542 {
3543 segments[0] = data->segment_bases[0] + text_addr;
3544 segments[1] = data->segment_bases[1] + data_addr;
3545 num_segments = 2;
3546 }
8d385431
DJ
3547 /* If the object file has only one segment, assume that it is text
3548 rather than data; main programs with no writable data are rare,
3549 but programs with no code are useless. Of course the code might
3550 have ended up in the data segment... to detect that we would need
3551 the permissions here. */
3552 else if (data && data->num_segments == 1)
3553 {
3554 segments[0] = data->segment_bases[0] + text_addr;
3555 num_segments = 1;
3556 }
28c32713
JB
3557 /* There's no way to relocate by segment. */
3558 else
3559 do_segments = 0;
31d99776
DJ
3560
3561 if (do_segments)
3562 {
3563 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3564 offs, num_segments, segments);
3565
3566 if (ret == 0 && !do_sections)
3e43a32a
MS
3567 error (_("Can not handle qOffsets TextSeg "
3568 "response with this symbol file"));
31d99776
DJ
3569
3570 if (ret > 0)
3571 do_sections = 0;
3572 }
c906108c 3573
9ef895d6
DJ
3574 if (data)
3575 free_symfile_segment_data (data);
31d99776
DJ
3576
3577 if (do_sections)
3578 {
3579 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3580
3e43a32a
MS
3581 /* This is a temporary kludge to force data and bss to use the
3582 same offsets because that's what nlmconv does now. The real
3583 solution requires changes to the stub and remote.c that I
3584 don't have time to do right now. */
31d99776
DJ
3585
3586 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3587 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3588 }
c906108c
SS
3589
3590 objfile_relocate (symfile_objfile, offs);
3591}
3592
9a7071a8
JB
3593/* Send interrupt_sequence to remote target. */
3594static void
eeae04df 3595send_interrupt_sequence (void)
9a7071a8 3596{
5d93a237
TT
3597 struct remote_state *rs = get_remote_state ();
3598
9a7071a8 3599 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3600 remote_serial_write ("\x03", 1);
9a7071a8 3601 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3602 serial_send_break (rs->remote_desc);
9a7071a8
JB
3603 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3604 {
5d93a237 3605 serial_send_break (rs->remote_desc);
c33e31fd 3606 remote_serial_write ("g", 1);
9a7071a8
JB
3607 }
3608 else
3609 internal_error (__FILE__, __LINE__,
3610 _("Invalid value for interrupt_sequence_mode: %s."),
3611 interrupt_sequence_mode);
3612}
3613
3405876a
PA
3614
3615/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3616 and extract the PTID. Returns NULL_PTID if not found. */
3617
3618static ptid_t
3619stop_reply_extract_thread (char *stop_reply)
3620{
3621 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3622 {
3623 char *p;
3624
3625 /* Txx r:val ; r:val (...) */
3626 p = &stop_reply[3];
3627
3628 /* Look for "register" named "thread". */
3629 while (*p != '\0')
3630 {
3631 char *p1;
3632
3633 p1 = strchr (p, ':');
3634 if (p1 == NULL)
3635 return null_ptid;
3636
3637 if (strncmp (p, "thread", p1 - p) == 0)
3638 return read_ptid (++p1, &p);
3639
3640 p1 = strchr (p, ';');
3641 if (p1 == NULL)
3642 return null_ptid;
3643 p1++;
3644
3645 p = p1;
3646 }
3647 }
3648
3649 return null_ptid;
3650}
3651
b7ea362b
PA
3652/* Determine the remote side's current thread. If we have a stop
3653 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3654 "thread" register we can extract the current thread from. If not,
3655 ask the remote which is the current thread with qC. The former
3656 method avoids a roundtrip. */
3657
3658static ptid_t
3659get_current_thread (char *wait_status)
3660{
6a49a997 3661 ptid_t ptid = null_ptid;
b7ea362b
PA
3662
3663 /* Note we don't use remote_parse_stop_reply as that makes use of
3664 the target architecture, which we haven't yet fully determined at
3665 this point. */
3666 if (wait_status != NULL)
3667 ptid = stop_reply_extract_thread (wait_status);
3668 if (ptid_equal (ptid, null_ptid))
3669 ptid = remote_current_thread (inferior_ptid);
3670
3671 return ptid;
3672}
3673
49c62f2e
PA
3674/* Query the remote target for which is the current thread/process,
3675 add it to our tables, and update INFERIOR_PTID. The caller is
3676 responsible for setting the state such that the remote end is ready
3405876a
PA
3677 to return the current thread.
3678
3679 This function is called after handling the '?' or 'vRun' packets,
3680 whose response is a stop reply from which we can also try
3681 extracting the thread. If the target doesn't support the explicit
3682 qC query, we infer the current thread from that stop reply, passed
3683 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3684
3685static void
3405876a 3686add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3687{
3688 struct remote_state *rs = get_remote_state ();
3689 int fake_pid_p = 0;
6a49a997 3690 ptid_t ptid;
49c62f2e
PA
3691
3692 inferior_ptid = null_ptid;
3693
b7ea362b
PA
3694 /* Now, if we have thread information, update inferior_ptid. */
3695 ptid = get_current_thread (wait_status);
3405876a 3696
49c62f2e
PA
3697 if (!ptid_equal (ptid, null_ptid))
3698 {
3699 if (!remote_multi_process_p (rs))
3700 fake_pid_p = 1;
3701
3702 inferior_ptid = ptid;
3703 }
3704 else
3705 {
3706 /* Without this, some commands which require an active target
3707 (such as kill) won't work. This variable serves (at least)
3708 double duty as both the pid of the target process (if it has
3709 such), and as a flag indicating that a target is active. */
3710 inferior_ptid = magic_null_ptid;
3711 fake_pid_p = 1;
3712 }
3713
1b6e6f5c 3714 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3715
3716 /* Add the main thread. */
3717 add_thread_silent (inferior_ptid);
3718}
3719
6efcd9a8
PA
3720/* Print info about a thread that was found already stopped on
3721 connection. */
3722
3723static void
3724print_one_stopped_thread (struct thread_info *thread)
3725{
3726 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3727
3728 switch_to_thread (thread->ptid);
3729 stop_pc = get_frame_pc (get_current_frame ());
3730 set_current_sal_from_frame (get_current_frame ());
3731
3732 thread->suspend.waitstatus_pending_p = 0;
3733
3734 if (ws->kind == TARGET_WAITKIND_STOPPED)
3735 {
3736 enum gdb_signal sig = ws->value.sig;
3737
3738 if (signal_print_state (sig))
3739 observer_notify_signal_received (sig);
3740 }
3741 observer_notify_normal_stop (NULL, 1);
3742}
3743
221e1a37
PA
3744/* Process all initial stop replies the remote side sent in response
3745 to the ? packet. These indicate threads that were already stopped
3746 on initial connection. We mark these threads as stopped and print
3747 their current frame before giving the user the prompt. */
3748
3749static void
6efcd9a8 3750process_initial_stop_replies (int from_tty)
221e1a37
PA
3751{
3752 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3753 struct inferior *inf;
3754 struct thread_info *thread;
3755 struct thread_info *selected = NULL;
3756 struct thread_info *lowest_stopped = NULL;
3757 struct thread_info *first = NULL;
221e1a37
PA
3758
3759 /* Consume the initial pending events. */
3760 while (pending_stop_replies-- > 0)
3761 {
3762 ptid_t waiton_ptid = minus_one_ptid;
3763 ptid_t event_ptid;
3764 struct target_waitstatus ws;
3765 int ignore_event = 0;
6efcd9a8 3766 struct thread_info *thread;
221e1a37
PA
3767
3768 memset (&ws, 0, sizeof (ws));
3769 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3770 if (remote_debug)
3771 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3772
3773 switch (ws.kind)
3774 {
3775 case TARGET_WAITKIND_IGNORE:
3776 case TARGET_WAITKIND_NO_RESUMED:
3777 case TARGET_WAITKIND_SIGNALLED:
3778 case TARGET_WAITKIND_EXITED:
3779 /* We shouldn't see these, but if we do, just ignore. */
3780 if (remote_debug)
3781 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3782 ignore_event = 1;
3783 break;
3784
3785 case TARGET_WAITKIND_EXECD:
3786 xfree (ws.value.execd_pathname);
3787 break;
3788 default:
3789 break;
3790 }
3791
3792 if (ignore_event)
3793 continue;
3794
6efcd9a8 3795 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3796
3797 if (ws.kind == TARGET_WAITKIND_STOPPED)
3798 {
3799 enum gdb_signal sig = ws.value.sig;
3800
3801 /* Stubs traditionally report SIGTRAP as initial signal,
3802 instead of signal 0. Suppress it. */
3803 if (sig == GDB_SIGNAL_TRAP)
3804 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3805 thread->suspend.stop_signal = sig;
3806 ws.value.sig = sig;
3807 }
221e1a37 3808
6efcd9a8
PA
3809 thread->suspend.waitstatus = ws;
3810
3811 if (ws.kind != TARGET_WAITKIND_STOPPED
3812 || ws.value.sig != GDB_SIGNAL_0)
3813 thread->suspend.waitstatus_pending_p = 1;
3814
3815 set_executing (event_ptid, 0);
3816 set_running (event_ptid, 0);
3817 }
3818
3819 /* "Notice" the new inferiors before anything related to
3820 registers/memory. */
3821 ALL_INFERIORS (inf)
3822 {
3823 if (inf->pid == 0)
3824 continue;
3825
3826 inf->needs_setup = 1;
3827
3828 if (non_stop)
3829 {
3830 thread = any_live_thread_of_process (inf->pid);
3831 notice_new_inferior (thread->ptid,
3832 thread->state == THREAD_RUNNING,
3833 from_tty);
3834 }
3835 }
3836
3837 /* If all-stop on top of non-stop, pause all threads. Note this
3838 records the threads' stop pc, so must be done after "noticing"
3839 the inferiors. */
3840 if (!non_stop)
3841 {
3842 stop_all_threads ();
3843
3844 /* If all threads of an inferior were already stopped, we
3845 haven't setup the inferior yet. */
3846 ALL_INFERIORS (inf)
3847 {
3848 if (inf->pid == 0)
3849 continue;
221e1a37 3850
6efcd9a8
PA
3851 if (inf->needs_setup)
3852 {
3853 thread = any_live_thread_of_process (inf->pid);
3854 switch_to_thread_no_regs (thread);
3855 setup_inferior (0);
3856 }
3857 }
221e1a37 3858 }
6efcd9a8
PA
3859
3860 /* Now go over all threads that are stopped, and print their current
3861 frame. If all-stop, then if there's a signalled thread, pick
3862 that as current. */
3863 ALL_NON_EXITED_THREADS (thread)
3864 {
3865 struct target_waitstatus *ws;
3866
3867 if (first == NULL)
3868 first = thread;
3869
3870 if (!non_stop)
3871 set_running (thread->ptid, 0);
3872 else if (thread->state != THREAD_STOPPED)
3873 continue;
3874
3875 ws = &thread->suspend.waitstatus;
3876
3877 if (selected == NULL
3878 && thread->suspend.waitstatus_pending_p)
3879 selected = thread;
3880
3881 if (lowest_stopped == NULL || thread->num < lowest_stopped->num)
3882 lowest_stopped = thread;
3883
3884 if (non_stop)
3885 print_one_stopped_thread (thread);
3886 }
3887
3888 /* In all-stop, we only print the status of one thread, and leave
3889 others with their status pending. */
3890 if (!non_stop)
3891 {
3892 thread = selected;
3893 if (thread == NULL)
3894 thread = lowest_stopped;
3895 if (thread == NULL)
3896 thread = first;
3897
3898 print_one_stopped_thread (thread);
3899 }
3900
3901 /* For "info program". */
3902 thread = inferior_thread ();
3903 if (thread->state == THREAD_STOPPED)
3904 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
3905}
3906
9cbc821d 3907static void
04bd08de 3908remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3909{
c8d104ad
PA
3910 struct remote_state *rs = get_remote_state ();
3911 struct packet_config *noack_config;
2d717e4f 3912 char *wait_status = NULL;
8621d6a9 3913
23860348 3914 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3915 QUIT;
c906108c 3916
9a7071a8
JB
3917 if (interrupt_on_connect)
3918 send_interrupt_sequence ();
3919
57e12211 3920 /* Ack any packet which the remote side has already sent. */
5d93a237 3921 serial_write (rs->remote_desc, "+", 1);
57e12211 3922
1e51243a
PA
3923 /* Signal other parts that we're going through the initial setup,
3924 and so things may not be stable yet. */
3925 rs->starting_up = 1;
3926
c8d104ad
PA
3927 /* The first packet we send to the target is the optional "supported
3928 packets" request. If the target can answer this, it will tell us
3929 which later probes to skip. */
3930 remote_query_supported ();
3931
d914c394 3932 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3933 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3934 remote_set_permissions (target);
d914c394 3935
c8d104ad
PA
3936 /* Next, we possibly activate noack mode.
3937
3938 If the QStartNoAckMode packet configuration is set to AUTO,
3939 enable noack mode if the stub reported a wish for it with
3940 qSupported.
3941
3942 If set to TRUE, then enable noack mode even if the stub didn't
3943 report it in qSupported. If the stub doesn't reply OK, the
3944 session ends with an error.
3945
3946 If FALSE, then don't activate noack mode, regardless of what the
3947 stub claimed should be the default with qSupported. */
3948
3949 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3950 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3951 {
3952 putpkt ("QStartNoAckMode");
3953 getpkt (&rs->buf, &rs->buf_size, 0);
3954 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3955 rs->noack_mode = 1;
3956 }
3957
04bd08de 3958 if (extended_p)
5fe04517
PA
3959 {
3960 /* Tell the remote that we are using the extended protocol. */
3961 putpkt ("!");
3962 getpkt (&rs->buf, &rs->buf_size, 0);
3963 }
3964
9b224c5e
PA
3965 /* Let the target know which signals it is allowed to pass down to
3966 the program. */
3967 update_signals_program_target ();
3968
d962ef82
DJ
3969 /* Next, if the target can specify a description, read it. We do
3970 this before anything involving memory or registers. */
3971 target_find_description ();
3972
6c95b8df
PA
3973 /* Next, now that we know something about the target, update the
3974 address spaces in the program spaces. */
3975 update_address_spaces ();
3976
50c71eaf
PA
3977 /* On OSs where the list of libraries is global to all
3978 processes, we fetch them early. */
f5656ead 3979 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3980 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3981
6efcd9a8 3982 if (target_is_non_stop_p ())
74531fed 3983 {
4082afcc 3984 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3985 error (_("Non-stop mode requested, but remote "
3986 "does not support non-stop"));
74531fed
PA
3987
3988 putpkt ("QNonStop:1");
3989 getpkt (&rs->buf, &rs->buf_size, 0);
3990
3991 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3992 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3993
3994 /* Find about threads and processes the stub is already
3995 controlling. We default to adding them in the running state.
3996 The '?' query below will then tell us about which threads are
3997 stopped. */
e8032dde 3998 remote_update_thread_list (target);
74531fed 3999 }
4082afcc 4000 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4001 {
4002 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4003 Request it explicitly. */
74531fed
PA
4004 putpkt ("QNonStop:0");
4005 getpkt (&rs->buf, &rs->buf_size, 0);
4006
4007 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4008 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4009 }
4010
a0743c90
YQ
4011 /* Upload TSVs regardless of whether the target is running or not. The
4012 remote stub, such as GDBserver, may have some predefined or builtin
4013 TSVs, even if the target is not running. */
8bd200f1 4014 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4015 {
4016 struct uploaded_tsv *uploaded_tsvs = NULL;
4017
181e3713 4018 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4019 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4020 }
4021
2d717e4f
DJ
4022 /* Check whether the target is running now. */
4023 putpkt ("?");
4024 getpkt (&rs->buf, &rs->buf_size, 0);
4025
6efcd9a8 4026 if (!target_is_non_stop_p ())
2d717e4f 4027 {
e714e1bf
UW
4028 ptid_t ptid;
4029 int fake_pid_p = 0;
4030 struct inferior *inf;
4031
74531fed 4032 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4033 {
04bd08de 4034 if (!extended_p)
74531fed 4035 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4036
4037 /* We're connected, but not running. Drop out before we
4038 call start_remote. */
e278ad5b 4039 rs->starting_up = 0;
c35b1492 4040 return;
2d717e4f
DJ
4041 }
4042 else
74531fed 4043 {
74531fed 4044 /* Save the reply for later. */
224c3ddb 4045 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4046 strcpy (wait_status, rs->buf);
4047 }
4048
b7ea362b 4049 /* Fetch thread list. */
e8032dde 4050 target_update_thread_list ();
b7ea362b 4051
74531fed
PA
4052 /* Let the stub know that we want it to return the thread. */
4053 set_continue_thread (minus_one_ptid);
4054
b7ea362b
PA
4055 if (thread_count () == 0)
4056 {
4057 /* Target has no concept of threads at all. GDB treats
4058 non-threaded target as single-threaded; add a main
4059 thread. */
4060 add_current_inferior_and_thread (wait_status);
4061 }
4062 else
4063 {
4064 /* We have thread information; select the thread the target
4065 says should be current. If we're reconnecting to a
4066 multi-threaded program, this will ideally be the thread
4067 that last reported an event before GDB disconnected. */
4068 inferior_ptid = get_current_thread (wait_status);
4069 if (ptid_equal (inferior_ptid, null_ptid))
4070 {
4071 /* Odd... The target was able to list threads, but not
4072 tell us which thread was current (no "thread"
4073 register in T stop reply?). Just pick the first
4074 thread in the thread list then. */
c9f35b34
KB
4075
4076 if (remote_debug)
4077 fprintf_unfiltered (gdb_stdlog,
4078 "warning: couldn't determine remote "
4079 "current thread; picking first in list.\n");
4080
b7ea362b
PA
4081 inferior_ptid = thread_list->ptid;
4082 }
4083 }
74531fed 4084
6e586cc5
YQ
4085 /* init_wait_for_inferior should be called before get_offsets in order
4086 to manage `inserted' flag in bp loc in a correct state.
4087 breakpoint_init_inferior, called from init_wait_for_inferior, set
4088 `inserted' flag to 0, while before breakpoint_re_set, called from
4089 start_remote, set `inserted' flag to 1. In the initialization of
4090 inferior, breakpoint_init_inferior should be called first, and then
4091 breakpoint_re_set can be called. If this order is broken, state of
4092 `inserted' flag is wrong, and cause some problems on breakpoint
4093 manipulation. */
4094 init_wait_for_inferior ();
4095
74531fed
PA
4096 get_offsets (); /* Get text, data & bss offsets. */
4097
d962ef82
DJ
4098 /* If we could not find a description using qXfer, and we know
4099 how to do it some other way, try again. This is not
4100 supported for non-stop; it could be, but it is tricky if
4101 there are no stopped threads when we connect. */
04bd08de 4102 if (remote_read_description_p (target)
f5656ead 4103 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4104 {
4105 target_clear_description ();
4106 target_find_description ();
4107 }
4108
74531fed
PA
4109 /* Use the previously fetched status. */
4110 gdb_assert (wait_status != NULL);
4111 strcpy (rs->buf, wait_status);
4112 rs->cached_wait_status = 1;
4113
4114 immediate_quit--;
04bd08de 4115 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4116 }
4117 else
4118 {
68c97600
PA
4119 /* Clear WFI global state. Do this before finding about new
4120 threads and inferiors, and setting the current inferior.
4121 Otherwise we would clear the proceed status of the current
4122 inferior when we want its stop_soon state to be preserved
4123 (see notice_new_inferior). */
4124 init_wait_for_inferior ();
4125
74531fed
PA
4126 /* In non-stop, we will either get an "OK", meaning that there
4127 are no stopped threads at this time; or, a regular stop
4128 reply. In the latter case, there may be more than one thread
4129 stopped --- we pull them all out using the vStopped
4130 mechanism. */
4131 if (strcmp (rs->buf, "OK") != 0)
4132 {
722247f1 4133 struct notif_client *notif = &notif_client_stop;
2d717e4f 4134
722247f1
YQ
4135 /* remote_notif_get_pending_replies acks this one, and gets
4136 the rest out. */
f48ff2a7 4137 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4138 = remote_notif_parse (notif, rs->buf);
4139 remote_notif_get_pending_events (notif);
74531fed 4140 }
2d717e4f 4141
74531fed
PA
4142 if (thread_count () == 0)
4143 {
04bd08de 4144 if (!extended_p)
74531fed 4145 error (_("The target is not running (try extended-remote?)"));
82f73884 4146
c35b1492
PA
4147 /* We're connected, but not running. Drop out before we
4148 call start_remote. */
e278ad5b 4149 rs->starting_up = 0;
c35b1492
PA
4150 return;
4151 }
74531fed 4152
74531fed
PA
4153 /* In non-stop mode, any cached wait status will be stored in
4154 the stop reply queue. */
4155 gdb_assert (wait_status == NULL);
f0223081 4156
2455069d 4157 /* Report all signals during attach/startup. */
94bedb42 4158 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4159
4160 /* If there are already stopped threads, mark them stopped and
4161 report their stops before giving the prompt to the user. */
6efcd9a8 4162 process_initial_stop_replies (from_tty);
221e1a37
PA
4163
4164 if (target_can_async_p ())
4165 target_async (1);
74531fed 4166 }
c8d104ad 4167
c8d104ad
PA
4168 /* If we connected to a live target, do some additional setup. */
4169 if (target_has_execution)
4170 {
f4ccffad 4171 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4172 remote_check_symbols ();
c8d104ad 4173 }
50c71eaf 4174
d5551862
SS
4175 /* Possibly the target has been engaged in a trace run started
4176 previously; find out where things are at. */
8bd200f1 4177 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4178 {
00bf0b85 4179 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4180
00bf0b85
SS
4181 if (current_trace_status ()->running)
4182 printf_filtered (_("Trace is already running on the target.\n"));
4183
ab6617cc 4184 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4185
4186 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4187 }
4188
1e51243a
PA
4189 /* The thread and inferior lists are now synchronized with the
4190 target, our symbols have been relocated, and we're merged the
4191 target's tracepoints with ours. We're done with basic start
4192 up. */
4193 rs->starting_up = 0;
4194
a25a5a45
PA
4195 /* Maybe breakpoints are global and need to be inserted now. */
4196 if (breakpoints_should_be_inserted_now ())
50c71eaf 4197 insert_breakpoints ();
c906108c
SS
4198}
4199
4200/* Open a connection to a remote debugger.
4201 NAME is the filename used for communication. */
4202
4203static void
014f9477 4204remote_open (const char *name, int from_tty)
c906108c 4205{
75c99385 4206 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4207}
4208
c906108c
SS
4209/* Open a connection to a remote debugger using the extended
4210 remote gdb protocol. NAME is the filename used for communication. */
4211
4212static void
014f9477 4213extended_remote_open (const char *name, int from_tty)
c906108c 4214{
75c99385 4215 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4216}
4217
ca4f7f8b
PA
4218/* Reset all packets back to "unknown support". Called when opening a
4219 new connection to a remote target. */
c906108c 4220
d471ea57 4221static void
ca4f7f8b 4222reset_all_packet_configs_support (void)
d471ea57
AC
4223{
4224 int i;
a744cf53 4225
444abaca 4226 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4227 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4228}
4229
ca4f7f8b
PA
4230/* Initialize all packet configs. */
4231
4232static void
4233init_all_packet_configs (void)
4234{
4235 int i;
4236
4237 for (i = 0; i < PACKET_MAX; i++)
4238 {
4239 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4240 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4241 }
4242}
4243
23860348 4244/* Symbol look-up. */
dc8acb97
MS
4245
4246static void
36d25514 4247remote_check_symbols (void)
dc8acb97 4248{
d01949b6 4249 struct remote_state *rs = get_remote_state ();
dc8acb97 4250 char *msg, *reply, *tmp;
3b7344d5 4251 struct bound_minimal_symbol sym;
dc8acb97 4252 int end;
a5c0808e 4253 struct cleanup *old_chain;
dc8acb97 4254
63154eca
PA
4255 /* The remote side has no concept of inferiors that aren't running
4256 yet, it only knows about running processes. If we're connected
4257 but our current inferior is not running, we should not invite the
4258 remote target to request symbol lookups related to its
4259 (unrelated) current process. */
4260 if (!target_has_execution)
4261 return;
4262
4082afcc 4263 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4264 return;
4265
63154eca
PA
4266 /* Make sure the remote is pointing at the right process. Note
4267 there's no way to select "no process". */
3c9c4b83
PA
4268 set_general_process ();
4269
6d820c5c
DJ
4270 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4271 because we need both at the same time. */
224c3ddb 4272 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4273 old_chain = make_cleanup (xfree, msg);
6d820c5c 4274
23860348 4275 /* Invite target to request symbol lookups. */
dc8acb97
MS
4276
4277 putpkt ("qSymbol::");
6d820c5c
DJ
4278 getpkt (&rs->buf, &rs->buf_size, 0);
4279 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 4280 reply = rs->buf;
dc8acb97 4281
61012eef 4282 while (startswith (reply, "qSymbol:"))
dc8acb97 4283 {
77e371c0
TT
4284 struct bound_minimal_symbol sym;
4285
dc8acb97 4286 tmp = &reply[8];
cfd77fa1 4287 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4288 msg[end] = '\0';
4289 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4290 if (sym.minsym == NULL)
ea9c271d 4291 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4292 else
2bbe3cc1 4293 {
f5656ead 4294 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4295 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4296
4297 /* If this is a function address, return the start of code
4298 instead of any data function descriptor. */
f5656ead 4299 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4300 sym_addr,
4301 &current_target);
4302
4303 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4304 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4305 }
4306
dc8acb97 4307 putpkt (msg);
6d820c5c 4308 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4309 reply = rs->buf;
dc8acb97 4310 }
a5c0808e
PA
4311
4312 do_cleanups (old_chain);
dc8acb97
MS
4313}
4314
9db8d71f 4315static struct serial *
baa336ce 4316remote_serial_open (const char *name)
9db8d71f
DJ
4317{
4318 static int udp_warning = 0;
4319
4320 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4321 of in ser-tcp.c, because it is the remote protocol assuming that the
4322 serial connection is reliable and not the serial connection promising
4323 to be. */
61012eef 4324 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4325 {
3e43a32a
MS
4326 warning (_("The remote protocol may be unreliable over UDP.\n"
4327 "Some events may be lost, rendering further debugging "
4328 "impossible."));
9db8d71f
DJ
4329 udp_warning = 1;
4330 }
4331
4332 return serial_open (name);
4333}
4334
d914c394
SS
4335/* Inform the target of our permission settings. The permission flags
4336 work without this, but if the target knows the settings, it can do
4337 a couple things. First, it can add its own check, to catch cases
4338 that somehow manage to get by the permissions checks in target
4339 methods. Second, if the target is wired to disallow particular
4340 settings (for instance, a system in the field that is not set up to
4341 be able to stop at a breakpoint), it can object to any unavailable
4342 permissions. */
4343
4344void
c378d69d 4345remote_set_permissions (struct target_ops *self)
d914c394
SS
4346{
4347 struct remote_state *rs = get_remote_state ();
4348
bba74b36
YQ
4349 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4350 "WriteReg:%x;WriteMem:%x;"
4351 "InsertBreak:%x;InsertTrace:%x;"
4352 "InsertFastTrace:%x;Stop:%x",
4353 may_write_registers, may_write_memory,
4354 may_insert_breakpoints, may_insert_tracepoints,
4355 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4356 putpkt (rs->buf);
4357 getpkt (&rs->buf, &rs->buf_size, 0);
4358
4359 /* If the target didn't like the packet, warn the user. Do not try
4360 to undo the user's settings, that would just be maddening. */
4361 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4362 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4363}
4364
be2a5f71
DJ
4365/* This type describes each known response to the qSupported
4366 packet. */
4367struct protocol_feature
4368{
4369 /* The name of this protocol feature. */
4370 const char *name;
4371
4372 /* The default for this protocol feature. */
4373 enum packet_support default_support;
4374
4375 /* The function to call when this feature is reported, or after
4376 qSupported processing if the feature is not supported.
4377 The first argument points to this structure. The second
4378 argument indicates whether the packet requested support be
4379 enabled, disabled, or probed (or the default, if this function
4380 is being called at the end of processing and this feature was
4381 not reported). The third argument may be NULL; if not NULL, it
4382 is a NUL-terminated string taken from the packet following
4383 this feature's name and an equals sign. */
4384 void (*func) (const struct protocol_feature *, enum packet_support,
4385 const char *);
4386
4387 /* The corresponding packet for this feature. Only used if
4388 FUNC is remote_supported_packet. */
4389 int packet;
4390};
4391
be2a5f71
DJ
4392static void
4393remote_supported_packet (const struct protocol_feature *feature,
4394 enum packet_support support,
4395 const char *argument)
4396{
4397 if (argument)
4398 {
4399 warning (_("Remote qSupported response supplied an unexpected value for"
4400 " \"%s\"."), feature->name);
4401 return;
4402 }
4403
4082afcc 4404 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4405}
be2a5f71
DJ
4406
4407static void
4408remote_packet_size (const struct protocol_feature *feature,
4409 enum packet_support support, const char *value)
4410{
4411 struct remote_state *rs = get_remote_state ();
4412
4413 int packet_size;
4414 char *value_end;
4415
4416 if (support != PACKET_ENABLE)
4417 return;
4418
4419 if (value == NULL || *value == '\0')
4420 {
4421 warning (_("Remote target reported \"%s\" without a size."),
4422 feature->name);
4423 return;
4424 }
4425
4426 errno = 0;
4427 packet_size = strtol (value, &value_end, 16);
4428 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4429 {
4430 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4431 feature->name, value);
4432 return;
4433 }
4434
be2a5f71
DJ
4435 /* Record the new maximum packet size. */
4436 rs->explicit_packet_size = packet_size;
4437}
4438
dc473cfb 4439static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4440 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4441 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4442 PACKET_qXfer_auxv },
c78fa86a
GB
4443 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4444 PACKET_qXfer_exec_file },
23181151
DJ
4445 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4446 PACKET_qXfer_features },
cfa9d6d9
DJ
4447 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4448 PACKET_qXfer_libraries },
2268b414
JK
4449 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4450 PACKET_qXfer_libraries_svr4 },
ced63ec0 4451 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4452 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4453 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4454 PACKET_qXfer_memory_map },
4de6483e
UW
4455 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4456 PACKET_qXfer_spu_read },
4457 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4458 PACKET_qXfer_spu_write },
07e059b5
VP
4459 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4460 PACKET_qXfer_osdata },
dc146f7c
VP
4461 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4462 PACKET_qXfer_threads },
b3b9301e
PA
4463 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4464 PACKET_qXfer_traceframe_info },
89be2091
DJ
4465 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4466 PACKET_QPassSignals },
9b224c5e
PA
4467 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4468 PACKET_QProgramSignals },
a6f3e723
SL
4469 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4470 PACKET_QStartNoAckMode },
4082afcc
PA
4471 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4472 PACKET_multiprocess_feature },
4473 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4474 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4475 PACKET_qXfer_siginfo_read },
4476 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4477 PACKET_qXfer_siginfo_write },
4082afcc 4478 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4479 PACKET_ConditionalTracepoints },
4082afcc 4480 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4481 PACKET_ConditionalBreakpoints },
4082afcc 4482 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4483 PACKET_BreakpointCommands },
4082afcc 4484 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4485 PACKET_FastTracepoints },
4082afcc 4486 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4487 PACKET_StaticTracepoints },
4082afcc 4488 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4489 PACKET_InstallInTrace},
4082afcc
PA
4490 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4491 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4492 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4493 PACKET_bc },
4494 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4495 PACKET_bs },
409873ef
SS
4496 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4497 PACKET_TracepointSource },
d914c394
SS
4498 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4499 PACKET_QAllow },
4082afcc
PA
4500 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4501 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4502 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4503 PACKET_qXfer_fdpic },
169081d0
TG
4504 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4505 PACKET_qXfer_uib },
03583c20
UW
4506 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4507 PACKET_QDisableRandomization },
d1feda86 4508 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4509 { "QTBuffer:size", PACKET_DISABLE,
4510 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4511 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4512 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4513 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4514 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4515 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4516 PACKET_qXfer_btrace },
4517 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4518 PACKET_qXfer_btrace_conf },
4519 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4520 PACKET_Qbtrace_conf_bts_size },
4521 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4522 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4523 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4524 PACKET_fork_event_feature },
4525 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4526 PACKET_vfork_event_feature },
94585166
DB
4527 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4528 PACKET_exec_event_feature },
b20a6524 4529 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4530 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4531 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4532 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4533 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4534};
4535
c8d5aac9
L
4536static char *remote_support_xml;
4537
4538/* Register string appended to "xmlRegisters=" in qSupported query. */
4539
4540void
6e39997a 4541register_remote_support_xml (const char *xml)
c8d5aac9
L
4542{
4543#if defined(HAVE_LIBEXPAT)
4544 if (remote_support_xml == NULL)
c4f7c687 4545 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4546 else
4547 {
4548 char *copy = xstrdup (remote_support_xml + 13);
4549 char *p = strtok (copy, ",");
4550
4551 do
4552 {
4553 if (strcmp (p, xml) == 0)
4554 {
4555 /* already there */
4556 xfree (copy);
4557 return;
4558 }
4559 }
4560 while ((p = strtok (NULL, ",")) != NULL);
4561 xfree (copy);
4562
94b0dee1
PA
4563 remote_support_xml = reconcat (remote_support_xml,
4564 remote_support_xml, ",", xml,
4565 (char *) NULL);
c8d5aac9
L
4566 }
4567#endif
4568}
4569
4570static char *
4571remote_query_supported_append (char *msg, const char *append)
4572{
4573 if (msg)
94b0dee1 4574 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4575 else
4576 return xstrdup (append);
4577}
4578
be2a5f71
DJ
4579static void
4580remote_query_supported (void)
4581{
4582 struct remote_state *rs = get_remote_state ();
4583 char *next;
4584 int i;
4585 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4586
4587 /* The packet support flags are handled differently for this packet
4588 than for most others. We treat an error, a disabled packet, and
4589 an empty response identically: any features which must be reported
4590 to be used will be automatically disabled. An empty buffer
4591 accomplishes this, since that is also the representation for a list
4592 containing no features. */
4593
4594 rs->buf[0] = 0;
4082afcc 4595 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4596 {
c8d5aac9 4597 char *q = NULL;
94b0dee1 4598 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4599
73b8c1fd
PA
4600 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4601 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4602
f7e6eed5
PA
4603 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4604 q = remote_query_supported_append (q, "swbreak+");
4605 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4606 q = remote_query_supported_append (q, "hwbreak+");
4607
dde08ee1
PA
4608 q = remote_query_supported_append (q, "qRelocInsn+");
4609
89245bc0
DB
4610 if (rs->extended)
4611 {
4612 if (packet_set_cmd_state (PACKET_fork_event_feature)
4613 != AUTO_BOOLEAN_FALSE)
4614 q = remote_query_supported_append (q, "fork-events+");
4615 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4616 != AUTO_BOOLEAN_FALSE)
4617 q = remote_query_supported_append (q, "vfork-events+");
94585166
DB
4618 if (packet_set_cmd_state (PACKET_exec_event_feature)
4619 != AUTO_BOOLEAN_FALSE)
4620 q = remote_query_supported_append (q, "exec-events+");
89245bc0
DB
4621 }
4622
750ce8d1
YQ
4623 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4624 q = remote_query_supported_append (q, "vContSupported+");
4625
65706a29
PA
4626 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4627 q = remote_query_supported_append (q, "QThreadEvents+");
4628
f2faf941
PA
4629 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4630 q = remote_query_supported_append (q, "no-resumed+");
4631
b35d5edb
PA
4632 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4633 the qSupported:xmlRegisters=i386 handling. */
4634 if (remote_support_xml != NULL)
4635 q = remote_query_supported_append (q, remote_support_xml);
4636
dde08ee1
PA
4637 q = reconcat (q, "qSupported:", q, (char *) NULL);
4638 putpkt (q);
82f73884 4639
94b0dee1
PA
4640 do_cleanups (old_chain);
4641
be2a5f71
DJ
4642 getpkt (&rs->buf, &rs->buf_size, 0);
4643
4644 /* If an error occured, warn, but do not return - just reset the
4645 buffer to empty and go on to disable features. */
4646 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4647 == PACKET_ERROR)
4648 {
4649 warning (_("Remote failure reply: %s"), rs->buf);
4650 rs->buf[0] = 0;
4651 }
4652 }
4653
4654 memset (seen, 0, sizeof (seen));
4655
4656 next = rs->buf;
4657 while (*next)
4658 {
4659 enum packet_support is_supported;
4660 char *p, *end, *name_end, *value;
4661
4662 /* First separate out this item from the rest of the packet. If
4663 there's another item after this, we overwrite the separator
4664 (terminated strings are much easier to work with). */
4665 p = next;
4666 end = strchr (p, ';');
4667 if (end == NULL)
4668 {
4669 end = p + strlen (p);
4670 next = end;
4671 }
4672 else
4673 {
89be2091
DJ
4674 *end = '\0';
4675 next = end + 1;
4676
be2a5f71
DJ
4677 if (end == p)
4678 {
4679 warning (_("empty item in \"qSupported\" response"));
4680 continue;
4681 }
be2a5f71
DJ
4682 }
4683
4684 name_end = strchr (p, '=');
4685 if (name_end)
4686 {
4687 /* This is a name=value entry. */
4688 is_supported = PACKET_ENABLE;
4689 value = name_end + 1;
4690 *name_end = '\0';
4691 }
4692 else
4693 {
4694 value = NULL;
4695 switch (end[-1])
4696 {
4697 case '+':
4698 is_supported = PACKET_ENABLE;
4699 break;
4700
4701 case '-':
4702 is_supported = PACKET_DISABLE;
4703 break;
4704
4705 case '?':
4706 is_supported = PACKET_SUPPORT_UNKNOWN;
4707 break;
4708
4709 default:
3e43a32a
MS
4710 warning (_("unrecognized item \"%s\" "
4711 "in \"qSupported\" response"), p);
be2a5f71
DJ
4712 continue;
4713 }
4714 end[-1] = '\0';
4715 }
4716
4717 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4718 if (strcmp (remote_protocol_features[i].name, p) == 0)
4719 {
4720 const struct protocol_feature *feature;
4721
4722 seen[i] = 1;
4723 feature = &remote_protocol_features[i];
4724 feature->func (feature, is_supported, value);
4725 break;
4726 }
4727 }
4728
4729 /* If we increased the packet size, make sure to increase the global
4730 buffer size also. We delay this until after parsing the entire
4731 qSupported packet, because this is the same buffer we were
4732 parsing. */
4733 if (rs->buf_size < rs->explicit_packet_size)
4734 {
4735 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4736 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4737 }
4738
4739 /* Handle the defaults for unmentioned features. */
4740 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4741 if (!seen[i])
4742 {
4743 const struct protocol_feature *feature;
4744
4745 feature = &remote_protocol_features[i];
4746 feature->func (feature, feature->default_support, NULL);
4747 }
4748}
4749
78a095c3
JK
4750/* Remove any of the remote.c targets from target stack. Upper targets depend
4751 on it so remove them first. */
4752
4753static void
4754remote_unpush_target (void)
4755{
915ef8b1 4756 pop_all_targets_at_and_above (process_stratum);
78a095c3 4757}
be2a5f71 4758
c906108c 4759static void
014f9477 4760remote_open_1 (const char *name, int from_tty,
3e43a32a 4761 struct target_ops *target, int extended_p)
c906108c 4762{
d01949b6 4763 struct remote_state *rs = get_remote_state ();
a6f3e723 4764
c906108c 4765 if (name == 0)
8a3fe4f8 4766 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4767 "serial device is attached to the remote system\n"
8a3fe4f8 4768 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4769
23860348 4770 /* See FIXME above. */
c6ebd6cf 4771 if (!target_async_permitted)
92d1e331 4772 wait_forever_enabled_p = 1;
6426a772 4773
2d717e4f 4774 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4775 Ask this question first, before target_preopen has a chance to kill
4776 anything. */
5d93a237 4777 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4778 {
78a095c3
JK
4779 if (from_tty
4780 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4781 error (_("Still connected."));
4782 }
4783
78a095c3 4784 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4785 target_preopen (from_tty);
4786
89be2091 4787 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4788 xfree (rs->last_pass_packet);
4789 rs->last_pass_packet = NULL;
89be2091 4790
9b224c5e
PA
4791 /* Make sure we send the program signals list the next time we
4792 resume. */
5e4a05c4
TT
4793 xfree (rs->last_program_signals_packet);
4794 rs->last_program_signals_packet = NULL;
9b224c5e 4795
ad9a8f3f 4796 remote_fileio_reset ();
1dd41f16
NS
4797 reopen_exec_file ();
4798 reread_symbols ();
4799
5d93a237
TT
4800 rs->remote_desc = remote_serial_open (name);
4801 if (!rs->remote_desc)
c906108c
SS
4802 perror_with_name (name);
4803
4804 if (baud_rate != -1)
4805 {
5d93a237 4806 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4807 {
9b74d5d3
KB
4808 /* The requested speed could not be set. Error out to
4809 top level after closing remote_desc. Take care to
4810 set remote_desc to NULL to avoid closing remote_desc
4811 more than once. */
5d93a237
TT
4812 serial_close (rs->remote_desc);
4813 rs->remote_desc = NULL;
c906108c
SS
4814 perror_with_name (name);
4815 }
4816 }
4817
236af5e3 4818 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4819 serial_raw (rs->remote_desc);
c906108c
SS
4820
4821 /* If there is something sitting in the buffer we might take it as a
4822 response to a command, which would be bad. */
5d93a237 4823 serial_flush_input (rs->remote_desc);
c906108c
SS
4824
4825 if (from_tty)
4826 {
4827 puts_filtered ("Remote debugging using ");
4828 puts_filtered (name);
4829 puts_filtered ("\n");
4830 }
23860348 4831 push_target (target); /* Switch to using remote target now. */
c906108c 4832
74531fed
PA
4833 /* Register extra event sources in the event loop. */
4834 remote_async_inferior_event_token
4835 = create_async_event_handler (remote_async_inferior_event_handler,
4836 NULL);
5965e028 4837 rs->notif_state = remote_notif_state_allocate ();
74531fed 4838
be2a5f71
DJ
4839 /* Reset the target state; these things will be queried either by
4840 remote_query_supported or as they are needed. */
ca4f7f8b 4841 reset_all_packet_configs_support ();
74531fed 4842 rs->cached_wait_status = 0;
be2a5f71 4843 rs->explicit_packet_size = 0;
a6f3e723 4844 rs->noack_mode = 0;
82f73884 4845 rs->extended = extended_p;
e24a49d8 4846 rs->waiting_for_stop_reply = 0;
3a29589a 4847 rs->ctrlc_pending_p = 0;
802188a7 4848
47f8a51d
TT
4849 rs->general_thread = not_sent_ptid;
4850 rs->continue_thread = not_sent_ptid;
262e1174 4851 rs->remote_traceframe_number = -1;
c906108c 4852
9d1f7ab2 4853 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4854 rs->use_threadinfo_query = 1;
4855 rs->use_threadextra_query = 1;
9d1f7ab2 4856
80152258
PA
4857 readahead_cache_invalidate ();
4858
c6ebd6cf 4859 if (target_async_permitted)
92d1e331 4860 {
23860348 4861 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4862 remote_async_terminal_ours_p = 1;
4863
4864 /* FIXME: cagney/1999-09-23: During the initial connection it is
4865 assumed that the target is already ready and able to respond to
0df8b418 4866 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4867 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4868 around this. Eventually a mechanism that allows
92d1e331 4869 wait_for_inferior() to expect/get timeouts will be
23860348 4870 implemented. */
92d1e331
DJ
4871 wait_forever_enabled_p = 0;
4872 }
4873
23860348 4874 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4875 no_shared_libraries (NULL, 0);
f78f6cf1 4876
74531fed
PA
4877 /* Start afresh. */
4878 init_thread_list ();
4879
36918e70 4880 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4881 target (we'd otherwise be in an inconsistent state) and then
4882 propogate the error on up the exception chain. This ensures that
4883 the caller doesn't stumble along blindly assuming that the
4884 function succeeded. The CLI doesn't have this problem but other
4885 UI's, such as MI do.
36918e70
AC
4886
4887 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4888 this function should return an error indication letting the
ce2826aa 4889 caller restore the previous state. Unfortunately the command
36918e70
AC
4890 ``target remote'' is directly wired to this function making that
4891 impossible. On a positive note, the CLI side of this problem has
4892 been fixed - the function set_cmd_context() makes it possible for
4893 all the ``target ....'' commands to share a common callback
4894 function. See cli-dump.c. */
109c3e39 4895 {
2d717e4f 4896
492d29ea 4897 TRY
04bd08de
TT
4898 {
4899 remote_start_remote (from_tty, target, extended_p);
4900 }
492d29ea 4901 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4902 {
c8d104ad
PA
4903 /* Pop the partially set up target - unless something else did
4904 already before throwing the exception. */
5d93a237 4905 if (rs->remote_desc != NULL)
78a095c3 4906 remote_unpush_target ();
c6ebd6cf 4907 if (target_async_permitted)
109c3e39
AC
4908 wait_forever_enabled_p = 1;
4909 throw_exception (ex);
4910 }
492d29ea 4911 END_CATCH
109c3e39 4912 }
c906108c 4913
f4abbc16
MM
4914 remote_btrace_reset ();
4915
c6ebd6cf 4916 if (target_async_permitted)
92d1e331 4917 wait_forever_enabled_p = 1;
43ff13b4
JM
4918}
4919
de0d863e
DB
4920/* Detach the specified process. */
4921
4922static void
4923remote_detach_pid (int pid)
4924{
4925 struct remote_state *rs = get_remote_state ();
4926
4927 if (remote_multi_process_p (rs))
4928 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4929 else
4930 strcpy (rs->buf, "D");
4931
4932 putpkt (rs->buf);
4933 getpkt (&rs->buf, &rs->buf_size, 0);
4934
4935 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4936 ;
4937 else if (rs->buf[0] == '\0')
4938 error (_("Remote doesn't know how to detach"));
4939 else
4940 error (_("Can't detach process."));
4941}
4942
4943/* This detaches a program to which we previously attached, using
4944 inferior_ptid to identify the process. After this is done, GDB
4945 can be used to debug some other program. We better not have left
4946 any breakpoints in the target program or it'll die when it hits
4947 one. */
c906108c
SS
4948
4949static void
de0d863e 4950remote_detach_1 (const char *args, int from_tty)
c906108c 4951{
82f73884 4952 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4953 struct remote_state *rs = get_remote_state ();
de0d863e
DB
4954 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4955 int is_fork_parent;
c906108c
SS
4956
4957 if (args)
8a3fe4f8 4958 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4959
2d717e4f
DJ
4960 if (!target_has_execution)
4961 error (_("No process to detach from."));
4962
7cee1e54
PA
4963 if (from_tty)
4964 {
4965 char *exec_file = get_exec_file (0);
4966 if (exec_file == NULL)
4967 exec_file = "";
4968 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4969 target_pid_to_str (pid_to_ptid (pid)));
4970 gdb_flush (gdb_stdout);
4971 }
4972
c906108c 4973 /* Tell the remote target to detach. */
de0d863e 4974 remote_detach_pid (pid);
82f73884 4975
de0d863e 4976 if (from_tty && !rs->extended)
7cee1e54 4977 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4978
de0d863e
DB
4979 /* Check to see if we are detaching a fork parent. Note that if we
4980 are detaching a fork child, tp == NULL. */
4981 is_fork_parent = (tp != NULL
4982 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4983
4984 /* If doing detach-on-fork, we don't mourn, because that will delete
4985 breakpoints that should be available for the followed inferior. */
4986 if (!is_fork_parent)
4987 target_mourn_inferior ();
4988 else
4989 {
4990 inferior_ptid = null_ptid;
4991 detach_inferior (pid);
4992 }
2d717e4f
DJ
4993}
4994
4995static void
52554a0e 4996remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4997{
de0d863e 4998 remote_detach_1 (args, from_tty);
2d717e4f
DJ
4999}
5000
5001static void
52554a0e 5002extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5003{
de0d863e
DB
5004 remote_detach_1 (args, from_tty);
5005}
5006
5007/* Target follow-fork function for remote targets. On entry, and
5008 at return, the current inferior is the fork parent.
5009
5010 Note that although this is currently only used for extended-remote,
5011 it is named remote_follow_fork in anticipation of using it for the
5012 remote target as well. */
5013
5014static int
5015remote_follow_fork (struct target_ops *ops, int follow_child,
5016 int detach_fork)
5017{
5018 struct remote_state *rs = get_remote_state ();
c269dbdb 5019 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5020
c269dbdb
DB
5021 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5022 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5023 {
5024 /* When following the parent and detaching the child, we detach
5025 the child here. For the case of following the child and
5026 detaching the parent, the detach is done in the target-
5027 independent follow fork code in infrun.c. We can't use
5028 target_detach when detaching an unfollowed child because
5029 the client side doesn't know anything about the child. */
5030 if (detach_fork && !follow_child)
5031 {
5032 /* Detach the fork child. */
5033 ptid_t child_ptid;
5034 pid_t child_pid;
5035
5036 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5037 child_pid = ptid_get_pid (child_ptid);
5038
5039 remote_detach_pid (child_pid);
5040 detach_inferior (child_pid);
5041 }
5042 }
5043 return 0;
c906108c
SS
5044}
5045
94585166
DB
5046/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5047 in the program space of the new inferior. On entry and at return the
5048 current inferior is the exec'ing inferior. INF is the new exec'd
5049 inferior, which may be the same as the exec'ing inferior unless
5050 follow-exec-mode is "new". */
5051
5052static void
5053remote_follow_exec (struct target_ops *ops,
5054 struct inferior *inf, char *execd_pathname)
5055{
5056 /* We know that this is a target file name, so if it has the "target:"
5057 prefix we strip it off before saving it in the program space. */
5058 if (is_target_filename (execd_pathname))
5059 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5060
5061 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5062}
5063
6ad8ae5c
DJ
5064/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5065
43ff13b4 5066static void
fee354ee 5067remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5068{
43ff13b4 5069 if (args)
2d717e4f 5070 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5071
2d717e4f 5072 /* Make sure we unpush even the extended remote targets; mourn
20f796c9 5073 won't do it. So call remote_mourn directly instead of
2d717e4f 5074 target_mourn_inferior. */
20f796c9 5075 remote_mourn (target);
2d717e4f 5076
43ff13b4
JM
5077 if (from_tty)
5078 puts_filtered ("Ending remote debugging.\n");
5079}
5080
2d717e4f
DJ
5081/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5082 be chatty about it. */
5083
5084static void
20f796c9
GB
5085extended_remote_attach (struct target_ops *target, const char *args,
5086 int from_tty)
2d717e4f
DJ
5087{
5088 struct remote_state *rs = get_remote_state ();
be86555c 5089 int pid;
96ef3384 5090 char *wait_status = NULL;
2d717e4f 5091
74164c56 5092 pid = parse_pid_to_attach (args);
2d717e4f 5093
74164c56
JK
5094 /* Remote PID can be freely equal to getpid, do not check it here the same
5095 way as in other targets. */
2d717e4f 5096
4082afcc 5097 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5098 error (_("This target does not support attaching to a process"));
5099
7cee1e54
PA
5100 if (from_tty)
5101 {
5102 char *exec_file = get_exec_file (0);
5103
5104 if (exec_file)
5105 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5106 target_pid_to_str (pid_to_ptid (pid)));
5107 else
5108 printf_unfiltered (_("Attaching to %s\n"),
5109 target_pid_to_str (pid_to_ptid (pid)));
5110
5111 gdb_flush (gdb_stdout);
5112 }
5113
bba74b36 5114 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5115 putpkt (rs->buf);
5116 getpkt (&rs->buf, &rs->buf_size, 0);
5117
4082afcc
PA
5118 switch (packet_ok (rs->buf,
5119 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5120 {
4082afcc 5121 case PACKET_OK:
6efcd9a8 5122 if (!target_is_non_stop_p ())
74531fed
PA
5123 {
5124 /* Save the reply for later. */
224c3ddb 5125 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5126 strcpy (wait_status, rs->buf);
5127 }
5128 else if (strcmp (rs->buf, "OK") != 0)
5129 error (_("Attaching to %s failed with: %s"),
5130 target_pid_to_str (pid_to_ptid (pid)),
5131 rs->buf);
4082afcc
PA
5132 break;
5133 case PACKET_UNKNOWN:
5134 error (_("This target does not support attaching to a process"));
5135 default:
5136 error (_("Attaching to %s failed"),
5137 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5138 }
2d717e4f 5139
1b6e6f5c 5140 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5141
2d717e4f 5142 inferior_ptid = pid_to_ptid (pid);
79d7f229 5143
6efcd9a8 5144 if (target_is_non_stop_p ())
bad34192
PA
5145 {
5146 struct thread_info *thread;
79d7f229 5147
bad34192 5148 /* Get list of threads. */
e8032dde 5149 remote_update_thread_list (target);
82f73884 5150
bad34192
PA
5151 thread = first_thread_of_process (pid);
5152 if (thread)
5153 inferior_ptid = thread->ptid;
5154 else
5155 inferior_ptid = pid_to_ptid (pid);
5156
5157 /* Invalidate our notion of the remote current thread. */
47f8a51d 5158 record_currthread (rs, minus_one_ptid);
bad34192 5159 }
74531fed 5160 else
bad34192
PA
5161 {
5162 /* Now, if we have thread information, update inferior_ptid. */
5163 inferior_ptid = remote_current_thread (inferior_ptid);
5164
5165 /* Add the main thread to the thread list. */
5166 add_thread_silent (inferior_ptid);
5167 }
c0a2216e 5168
96ef3384
UW
5169 /* Next, if the target can specify a description, read it. We do
5170 this before anything involving memory or registers. */
5171 target_find_description ();
5172
6efcd9a8 5173 if (!target_is_non_stop_p ())
74531fed
PA
5174 {
5175 /* Use the previously fetched status. */
5176 gdb_assert (wait_status != NULL);
5177
5178 if (target_can_async_p ())
5179 {
722247f1
YQ
5180 struct notif_event *reply
5181 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5182
722247f1 5183 push_stop_reply ((struct stop_reply *) reply);
74531fed 5184
6a3753b3 5185 target_async (1);
74531fed
PA
5186 }
5187 else
5188 {
5189 gdb_assert (wait_status != NULL);
5190 strcpy (rs->buf, wait_status);
5191 rs->cached_wait_status = 1;
5192 }
5193 }
5194 else
5195 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5196}
5197
b9c1d481
AS
5198/* Implementation of the to_post_attach method. */
5199
5200static void
5201extended_remote_post_attach (struct target_ops *ops, int pid)
5202{
6efcd9a8
PA
5203 /* Get text, data & bss offsets. */
5204 get_offsets ();
5205
b9c1d481
AS
5206 /* In certain cases GDB might not have had the chance to start
5207 symbol lookup up until now. This could happen if the debugged
5208 binary is not using shared libraries, the vsyscall page is not
5209 present (on Linux) and the binary itself hadn't changed since the
5210 debugging process was started. */
5211 if (symfile_objfile != NULL)
5212 remote_check_symbols();
5213}
5214
c906108c 5215\f
506fb367
DJ
5216/* Check for the availability of vCont. This function should also check
5217 the response. */
c906108c
SS
5218
5219static void
6d820c5c 5220remote_vcont_probe (struct remote_state *rs)
c906108c 5221{
2e9f7625 5222 char *buf;
6d820c5c 5223
2e9f7625
DJ
5224 strcpy (rs->buf, "vCont?");
5225 putpkt (rs->buf);
6d820c5c 5226 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5227 buf = rs->buf;
c906108c 5228
506fb367 5229 /* Make sure that the features we assume are supported. */
61012eef 5230 if (startswith (buf, "vCont"))
506fb367
DJ
5231 {
5232 char *p = &buf[5];
750ce8d1 5233 int support_c, support_C;
506fb367 5234
750ce8d1
YQ
5235 rs->supports_vCont.s = 0;
5236 rs->supports_vCont.S = 0;
506fb367
DJ
5237 support_c = 0;
5238 support_C = 0;
d458bd84 5239 rs->supports_vCont.t = 0;
c1e36e3e 5240 rs->supports_vCont.r = 0;
506fb367
DJ
5241 while (p && *p == ';')
5242 {
5243 p++;
5244 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5245 rs->supports_vCont.s = 1;
506fb367 5246 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5247 rs->supports_vCont.S = 1;
506fb367
DJ
5248 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5249 support_c = 1;
5250 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5251 support_C = 1;
74531fed 5252 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5253 rs->supports_vCont.t = 1;
c1e36e3e
PA
5254 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5255 rs->supports_vCont.r = 1;
506fb367
DJ
5256
5257 p = strchr (p, ';');
5258 }
c906108c 5259
750ce8d1
YQ
5260 /* If c, and C are not all supported, we can't use vCont. Clearing
5261 BUF will make packet_ok disable the packet. */
5262 if (!support_c || !support_C)
506fb367
DJ
5263 buf[0] = 0;
5264 }
c906108c 5265
444abaca 5266 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5267}
c906108c 5268
0d8f58ca
PA
5269/* Helper function for building "vCont" resumptions. Write a
5270 resumption to P. ENDP points to one-passed-the-end of the buffer
5271 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5272 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5273 resumed thread should be single-stepped and/or signalled. If PTID
5274 equals minus_one_ptid, then all threads are resumed; if PTID
5275 represents a process, then all threads of the process are resumed;
5276 the thread to be stepped and/or signalled is given in the global
5277 INFERIOR_PTID. */
5278
5279static char *
5280append_resumption (char *p, char *endp,
2ea28649 5281 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5282{
5283 struct remote_state *rs = get_remote_state ();
5284
a493e3e2 5285 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5286 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5287 else if (step
5288 /* GDB is willing to range step. */
5289 && use_range_stepping
5290 /* Target supports range stepping. */
5291 && rs->supports_vCont.r
5292 /* We don't currently support range stepping multiple
5293 threads with a wildcard (though the protocol allows it,
5294 so stubs shouldn't make an active effort to forbid
5295 it). */
5296 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5297 {
5298 struct thread_info *tp;
5299
5300 if (ptid_equal (ptid, minus_one_ptid))
5301 {
5302 /* If we don't know about the target thread's tid, then
5303 we're resuming magic_null_ptid (see caller). */
5304 tp = find_thread_ptid (magic_null_ptid);
5305 }
5306 else
5307 tp = find_thread_ptid (ptid);
5308 gdb_assert (tp != NULL);
5309
5310 if (tp->control.may_range_step)
5311 {
5312 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5313
5314 p += xsnprintf (p, endp - p, ";r%s,%s",
5315 phex_nz (tp->control.step_range_start,
5316 addr_size),
5317 phex_nz (tp->control.step_range_end,
5318 addr_size));
5319 }
5320 else
5321 p += xsnprintf (p, endp - p, ";s");
5322 }
0d8f58ca
PA
5323 else if (step)
5324 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5325 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5326 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5327 else
5328 p += xsnprintf (p, endp - p, ";c");
5329
5330 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5331 {
5332 ptid_t nptid;
5333
5334 /* All (-1) threads of process. */
ba348170 5335 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5336
5337 p += xsnprintf (p, endp - p, ":");
5338 p = write_ptid (p, endp, nptid);
5339 }
5340 else if (!ptid_equal (ptid, minus_one_ptid))
5341 {
5342 p += xsnprintf (p, endp - p, ":");
5343 p = write_ptid (p, endp, ptid);
5344 }
5345
5346 return p;
5347}
5348
799a2abe
PA
5349/* Clear the thread's private info on resume. */
5350
5351static void
5352resume_clear_thread_private_info (struct thread_info *thread)
5353{
5354 if (thread->priv != NULL)
5355 {
5356 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5357 thread->priv->watch_data_address = 0;
5358 }
5359}
5360
e5ef252a
PA
5361/* Append a vCont continue-with-signal action for threads that have a
5362 non-zero stop signal. */
5363
5364static char *
5365append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5366{
5367 struct thread_info *thread;
5368
034f788c 5369 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5370 if (ptid_match (thread->ptid, ptid)
5371 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5372 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5373 {
5374 p = append_resumption (p, endp, thread->ptid,
5375 0, thread->suspend.stop_signal);
5376 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5377 resume_clear_thread_private_info (thread);
e5ef252a
PA
5378 }
5379
5380 return p;
5381}
5382
506fb367
DJ
5383/* Resume the remote inferior by using a "vCont" packet. The thread
5384 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5385 resumed thread should be single-stepped and/or signalled. If PTID
5386 equals minus_one_ptid, then all threads are resumed; the thread to
5387 be stepped and/or signalled is given in the global INFERIOR_PTID.
5388 This function returns non-zero iff it resumes the inferior.
44eaed12 5389
506fb367
DJ
5390 This function issues a strict subset of all possible vCont commands at the
5391 moment. */
44eaed12 5392
506fb367 5393static int
2ea28649 5394remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5395{
5396 struct remote_state *rs = get_remote_state ();
82f73884
PA
5397 char *p;
5398 char *endp;
44eaed12 5399
4082afcc 5400 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5401 remote_vcont_probe (rs);
44eaed12 5402
4082afcc 5403 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5404 return 0;
44eaed12 5405
82f73884
PA
5406 p = rs->buf;
5407 endp = rs->buf + get_remote_packet_size ();
5408
506fb367
DJ
5409 /* If we could generate a wider range of packets, we'd have to worry
5410 about overflowing BUF. Should there be a generic
5411 "multi-part-packet" packet? */
5412
0d8f58ca
PA
5413 p += xsnprintf (p, endp - p, "vCont");
5414
79d7f229 5415 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5416 {
79d7f229
PA
5417 /* MAGIC_NULL_PTID means that we don't have any active threads,
5418 so we don't have any TID numbers the inferior will
5419 understand. Make sure to only send forms that do not specify
5420 a TID. */
a9cbf802 5421 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5422 }
0d8f58ca 5423 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5424 {
0d8f58ca
PA
5425 /* Resume all threads (of all processes, or of a single
5426 process), with preference for INFERIOR_PTID. This assumes
5427 inferior_ptid belongs to the set of all threads we are about
5428 to resume. */
a493e3e2 5429 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5430 {
0d8f58ca
PA
5431 /* Step inferior_ptid, with or without signal. */
5432 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5433 }
0d8f58ca 5434
e5ef252a
PA
5435 /* Also pass down any pending signaled resumption for other
5436 threads not the current. */
5437 p = append_pending_thread_resumptions (p, endp, ptid);
5438
0d8f58ca 5439 /* And continue others without a signal. */
a493e3e2 5440 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5441 }
5442 else
506fb367
DJ
5443 {
5444 /* Scheduler locking; resume only PTID. */
a9cbf802 5445 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5446 }
c906108c 5447
82f73884
PA
5448 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5449 putpkt (rs->buf);
506fb367 5450
6efcd9a8 5451 if (target_is_non_stop_p ())
74531fed
PA
5452 {
5453 /* In non-stop, the stub replies to vCont with "OK". The stop
5454 reply will be reported asynchronously by means of a `%Stop'
5455 notification. */
5456 getpkt (&rs->buf, &rs->buf_size, 0);
5457 if (strcmp (rs->buf, "OK") != 0)
5458 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5459 }
5460
506fb367 5461 return 1;
c906108c 5462}
43ff13b4 5463
506fb367
DJ
5464/* Tell the remote machine to resume. */
5465
43ff13b4 5466static void
28439f5e 5467remote_resume (struct target_ops *ops,
2ea28649 5468 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5469{
d01949b6 5470 struct remote_state *rs = get_remote_state ();
2e9f7625 5471 char *buf;
799a2abe 5472 struct thread_info *thread;
43ff13b4 5473
722247f1
YQ
5474 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5475 (explained in remote-notif.c:handle_notification) so
5476 remote_notif_process is not called. We need find a place where
5477 it is safe to start a 'vNotif' sequence. It is good to do it
5478 before resuming inferior, because inferior was stopped and no RSP
5479 traffic at that moment. */
6efcd9a8 5480 if (!target_is_non_stop_p ())
5965e028 5481 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5482
b73be471 5483 rs->last_sent_signal = siggnal;
280ceea3 5484 rs->last_sent_step = step;
43ff13b4 5485
506fb367 5486 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5487 /* No reverse support (yet) for vCont. */
5488 if (execution_direction != EXEC_REVERSE)
5489 if (remote_vcont_resume (ptid, step, siggnal))
5490 goto done;
506fb367 5491
79d7f229
PA
5492 /* All other supported resume packets do use Hc, so set the continue
5493 thread. */
5494 if (ptid_equal (ptid, minus_one_ptid))
5495 set_continue_thread (any_thread_ptid);
506fb367 5496 else
79d7f229 5497 set_continue_thread (ptid);
506fb367 5498
799a2abe
PA
5499 ALL_NON_EXITED_THREADS (thread)
5500 resume_clear_thread_private_info (thread);
5501
2e9f7625 5502 buf = rs->buf;
b2175913
MS
5503 if (execution_direction == EXEC_REVERSE)
5504 {
5505 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5506 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5507 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5508 siggnal);
40ab02ce 5509
4082afcc 5510 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5511 error (_("Remote reverse-step not supported."));
4082afcc 5512 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5513 error (_("Remote reverse-continue not supported."));
40ab02ce 5514
b2175913
MS
5515 strcpy (buf, step ? "bs" : "bc");
5516 }
a493e3e2 5517 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5518 {
5519 buf[0] = step ? 'S' : 'C';
c5aa993b 5520 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5521 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5522 buf[3] = '\0';
5523 }
5524 else
c5aa993b 5525 strcpy (buf, step ? "s" : "c");
506fb367 5526
44eaed12 5527 putpkt (buf);
43ff13b4 5528
75c99385 5529 done:
2acceee2 5530 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5531 with the event loop. NOTE: this is the one place where all the
5532 execution commands end up. We could alternatively do this in each
23860348 5533 of the execution commands in infcmd.c. */
2acceee2
JM
5534 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5535 into infcmd.c in order to allow inferior function calls to work
23860348 5536 NOT asynchronously. */
362646f5 5537 if (target_can_async_p ())
6a3753b3 5538 target_async (1);
e24a49d8
PA
5539
5540 /* We've just told the target to resume. The remote server will
5541 wait for the inferior to stop, and then send a stop reply. In
5542 the mean time, we can't start another command/query ourselves
74531fed
PA
5543 because the stub wouldn't be ready to process it. This applies
5544 only to the base all-stop protocol, however. In non-stop (which
5545 only supports vCont), the stub replies with an "OK", and is
5546 immediate able to process further serial input. */
6efcd9a8 5547 if (!target_is_non_stop_p ())
74531fed 5548 rs->waiting_for_stop_reply = 1;
43ff13b4 5549}
c906108c 5550\f
43ff13b4
JM
5551
5552/* Set up the signal handler for SIGINT, while the target is
23860348 5553 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5554static void
934b9bac 5555async_initialize_sigint_signal_handler (void)
43ff13b4 5556{
934b9bac 5557 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5558}
5559
23860348 5560/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5561static void
934b9bac 5562async_handle_remote_sigint (int sig)
43ff13b4 5563{
934b9bac 5564 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5565 /* Note we need to go through gdb_call_async_signal_handler in order
5566 to wake up the event loop on Windows. */
5567 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5568}
5569
5570/* Signal handler for SIGINT, installed after SIGINT has already been
5571 sent once. It will take effect the second time that the user sends
23860348 5572 a ^C. */
43ff13b4 5573static void
934b9bac 5574async_handle_remote_sigint_twice (int sig)
43ff13b4 5575{
934b9bac 5576 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5577 /* See note in async_handle_remote_sigint. */
5578 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5579}
5580
abc56d60
PA
5581/* Implementation of to_check_pending_interrupt. */
5582
5583static void
5584remote_check_pending_interrupt (struct target_ops *self)
5585{
5586 struct async_signal_handler *token = async_sigint_remote_twice_token;
5587
5588 if (async_signal_handler_is_marked (token))
5589 {
5590 clear_async_signal_handler (token);
5591 call_async_signal_handler (token);
5592 }
5593}
5594
6426a772 5595/* Perform the real interruption of the target execution, in response
23860348 5596 to a ^C. */
c5aa993b 5597static void
fba45db2 5598async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5599{
5600 if (remote_debug)
248fd3bf 5601 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5602
de979965 5603 target_interrupt (inferior_ptid);
43ff13b4
JM
5604}
5605
0df8b418 5606/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5607 up on the target alltogether. */
47e1ce27 5608static void
fba45db2 5609async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5610{
2df3850c 5611 if (remote_debug)
248fd3bf 5612 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5613
5614 interrupt_query ();
43ff13b4
JM
5615}
5616
5617/* Reinstall the usual SIGINT handlers, after the target has
23860348 5618 stopped. */
6426a772 5619static void
934b9bac 5620async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5621{
5622 signal (SIGINT, handle_sigint);
43ff13b4
JM
5623}
5624
c906108c
SS
5625/* Send ^C to target to halt it. Target will respond, and send us a
5626 packet. */
507f3c78 5627static void (*ofunc) (int);
c906108c 5628
bfedc46a
PA
5629/* The command line interface's interrupt routine. This function is installed
5630 as a signal handler for SIGINT. The first time a user requests an
5631 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5632 response from the target (it didn't stop when the user requested it),
23860348 5633 we ask the user if he'd like to detach from the target. */
bfedc46a 5634
c906108c 5635static void
934b9bac 5636sync_remote_interrupt (int signo)
c906108c 5637{
23860348 5638 /* If this doesn't work, try more severe steps. */
934b9bac 5639 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5640
934b9bac 5641 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5642}
5643
5644/* The user typed ^C twice. */
5645
5646static void
934b9bac 5647sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5648{
5649 signal (signo, ofunc);
934b9bac
JK
5650 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5651 signal (signo, sync_remote_interrupt);
c906108c 5652}
7a292a7a 5653
74531fed
PA
5654/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5655 thread, all threads of a remote process, or all threads of all
5656 processes. */
5657
5658static void
5659remote_stop_ns (ptid_t ptid)
5660{
5661 struct remote_state *rs = get_remote_state ();
5662 char *p = rs->buf;
5663 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5664
4082afcc 5665 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5666 remote_vcont_probe (rs);
5667
d458bd84 5668 if (!rs->supports_vCont.t)
74531fed
PA
5669 error (_("Remote server does not support stopping threads"));
5670
f91d3df5
PA
5671 if (ptid_equal (ptid, minus_one_ptid)
5672 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5673 p += xsnprintf (p, endp - p, "vCont;t");
5674 else
5675 {
5676 ptid_t nptid;
5677
74531fed
PA
5678 p += xsnprintf (p, endp - p, "vCont;t:");
5679
5680 if (ptid_is_pid (ptid))
5681 /* All (-1) threads of process. */
ba348170 5682 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5683 else
5684 {
5685 /* Small optimization: if we already have a stop reply for
5686 this thread, no use in telling the stub we want this
5687 stopped. */
5688 if (peek_stop_reply (ptid))
5689 return;
5690
5691 nptid = ptid;
5692 }
5693
a9cbf802 5694 write_ptid (p, endp, nptid);
74531fed
PA
5695 }
5696
5697 /* In non-stop, we get an immediate OK reply. The stop reply will
5698 come in asynchronously by notification. */
5699 putpkt (rs->buf);
5700 getpkt (&rs->buf, &rs->buf_size, 0);
5701 if (strcmp (rs->buf, "OK") != 0)
5702 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5703}
5704
bfedc46a
PA
5705/* All-stop version of target_interrupt. Sends a break or a ^C to
5706 interrupt the remote target. It is undefined which thread of which
5707 process reports the interrupt. */
74531fed
PA
5708
5709static void
de979965 5710remote_interrupt_as (void)
74531fed
PA
5711{
5712 struct remote_state *rs = get_remote_state ();
5713
3a29589a
DJ
5714 rs->ctrlc_pending_p = 1;
5715
74531fed
PA
5716 /* If the inferior is stopped already, but the core didn't know
5717 about it yet, just ignore the request. The cached wait status
5718 will be collected in remote_wait. */
5719 if (rs->cached_wait_status)
5720 return;
5721
9a7071a8
JB
5722 /* Send interrupt_sequence to remote target. */
5723 send_interrupt_sequence ();
74531fed
PA
5724}
5725
de979965
PA
5726/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5727 the remote target. It is undefined which thread of which process
5728 reports the interrupt. Returns true if the packet is supported by
5729 the server, false otherwise. */
5730
5731static int
5732remote_interrupt_ns (void)
5733{
5734 struct remote_state *rs = get_remote_state ();
5735 char *p = rs->buf;
5736 char *endp = rs->buf + get_remote_packet_size ();
5737
5738 xsnprintf (p, endp - p, "vCtrlC");
5739
5740 /* In non-stop, we get an immediate OK reply. The stop reply will
5741 come in asynchronously by notification. */
5742 putpkt (rs->buf);
5743 getpkt (&rs->buf, &rs->buf_size, 0);
5744
5745 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5746 {
5747 case PACKET_OK:
5748 break;
5749 case PACKET_UNKNOWN:
5750 return 0;
5751 case PACKET_ERROR:
5752 error (_("Interrupting target failed: %s"), rs->buf);
5753 }
5754
5755 return 1;
5756}
5757
bfedc46a 5758/* Implement the to_stop function for the remote targets. */
74531fed 5759
c906108c 5760static void
1eab8a48 5761remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5762{
7a292a7a 5763 if (remote_debug)
0f71a2f6 5764 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5765
6efcd9a8 5766 if (target_is_non_stop_p ())
74531fed 5767 remote_stop_ns (ptid);
c906108c 5768 else
bfedc46a
PA
5769 {
5770 /* We don't currently have a way to transparently pause the
5771 remote target in all-stop mode. Interrupt it instead. */
de979965 5772 remote_interrupt_as ();
bfedc46a
PA
5773 }
5774}
5775
5776/* Implement the to_interrupt function for the remote targets. */
5777
5778static void
5779remote_interrupt (struct target_ops *self, ptid_t ptid)
5780{
5781 if (remote_debug)
5782 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5783
de979965 5784 if (non_stop)
bfedc46a 5785 {
de979965 5786 /* In non-stop mode, we always stop with no signal instead. */
bfedc46a
PA
5787 remote_stop_ns (ptid);
5788 }
5789 else
de979965
PA
5790 {
5791 /* In all-stop, we emulate ^C-ing the remote target's
5792 terminal. */
5793 if (target_is_non_stop_p ())
5794 {
5795 if (!remote_interrupt_ns ())
5796 {
5797 /* No support for ^C-ing the remote target. Stop it
5798 (with no signal) instead. */
5799 remote_stop_ns (ptid);
5800 }
5801 }
5802 else
5803 remote_interrupt_as ();
5804 }
c906108c
SS
5805}
5806
5807/* Ask the user what to do when an interrupt is received. */
5808
5809static void
fba45db2 5810interrupt_query (void)
c906108c 5811{
abc56d60
PA
5812 struct remote_state *rs = get_remote_state ();
5813 struct cleanup *old_chain;
5814
5815 old_chain = make_cleanup_restore_target_terminal ();
c906108c
SS
5816 target_terminal_ours ();
5817
abc56d60 5818 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5819 {
abc56d60
PA
5820 if (query (_("The target is not responding to interrupt requests.\n"
5821 "Stop debugging it? ")))
74531fed 5822 {
78a095c3 5823 remote_unpush_target ();
abc56d60 5824 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5825 }
5826 }
abc56d60
PA
5827 else
5828 {
5829 if (query (_("Interrupted while waiting for the program.\n"
5830 "Give up waiting? ")))
5831 quit ();
5832 }
c906108c 5833
abc56d60 5834 do_cleanups (old_chain);
c906108c
SS
5835}
5836
6426a772
JM
5837/* Enable/disable target terminal ownership. Most targets can use
5838 terminal groups to control terminal ownership. Remote targets are
5839 different in that explicit transfer of ownership to/from GDB/target
23860348 5840 is required. */
6426a772
JM
5841
5842static void
d2f640d4 5843remote_terminal_inferior (struct target_ops *self)
6426a772 5844{
c6ebd6cf 5845 if (!target_async_permitted)
75c99385
PA
5846 /* Nothing to do. */
5847 return;
5848
d9d2d8b6
PA
5849 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5850 idempotent. The event-loop GDB talking to an asynchronous target
5851 with a synchronous command calls this function from both
5852 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5853 transfer the terminal to the target when it shouldn't this guard
5854 can go away. */
6426a772
JM
5855 if (!remote_async_terminal_ours_p)
5856 return;
5857 delete_file_handler (input_fd);
5858 remote_async_terminal_ours_p = 0;
934b9bac 5859 async_initialize_sigint_signal_handler ();
6426a772
JM
5860 /* NOTE: At this point we could also register our selves as the
5861 recipient of all input. Any characters typed could then be
23860348 5862 passed on down to the target. */
6426a772
JM
5863}
5864
5865static void
e3594fd1 5866remote_terminal_ours (struct target_ops *self)
6426a772 5867{
c6ebd6cf 5868 if (!target_async_permitted)
75c99385
PA
5869 /* Nothing to do. */
5870 return;
5871
5872 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5873 if (remote_async_terminal_ours_p)
5874 return;
934b9bac 5875 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5876 add_file_handler (input_fd, stdin_event_handler, 0);
5877 remote_async_terminal_ours_p = 1;
5878}
5879
176a6961 5880static void
917317f4 5881remote_console_output (char *msg)
c906108c
SS
5882{
5883 char *p;
5884
c5aa993b 5885 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5886 {
5887 char tb[2];
5888 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5889
c906108c
SS
5890 tb[0] = c;
5891 tb[1] = 0;
43ff13b4 5892 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5893 }
00db5b94
PA
5894 gdb_flush (gdb_stdtarg);
5895}
74531fed
PA
5896
5897typedef struct cached_reg
5898{
5899 int num;
5900 gdb_byte data[MAX_REGISTER_SIZE];
5901} cached_reg_t;
5902
5903DEF_VEC_O(cached_reg_t);
5904
722247f1 5905typedef struct stop_reply
74531fed 5906{
722247f1 5907 struct notif_event base;
74531fed 5908
722247f1 5909 /* The identifier of the thread about this event */
74531fed
PA
5910 ptid_t ptid;
5911
340e3c99 5912 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5913 connection, represented by a remote_state object, is closed,
5914 all the associated stop_reply events should be released. */
5915 struct remote_state *rs;
5916
74531fed
PA
5917 struct target_waitstatus ws;
5918
15148d6a
PA
5919 /* Expedited registers. This makes remote debugging a bit more
5920 efficient for those targets that provide critical registers as
5921 part of their normal status mechanism (as another roundtrip to
5922 fetch them is avoided). */
74531fed
PA
5923 VEC(cached_reg_t) *regcache;
5924
f7e6eed5
PA
5925 enum target_stop_reason stop_reason;
5926
74531fed
PA
5927 CORE_ADDR watch_data_address;
5928
dc146f7c 5929 int core;
722247f1 5930} *stop_reply_p;
a744cf53 5931
722247f1
YQ
5932DECLARE_QUEUE_P (stop_reply_p);
5933DEFINE_QUEUE_P (stop_reply_p);
5934/* The list of already fetched and acknowledged stop events. This
5935 queue is used for notification Stop, and other notifications
5936 don't need queue for their events, because the notification events
5937 of Stop can't be consumed immediately, so that events should be
5938 queued first, and be consumed by remote_wait_{ns,as} one per
5939 time. Other notifications can consume their events immediately,
5940 so queue is not needed for them. */
5941static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5942
5943static void
5944stop_reply_xfree (struct stop_reply *r)
5945{
f48ff2a7 5946 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5947}
5948
221e1a37
PA
5949/* Return the length of the stop reply queue. */
5950
5951static int
5952stop_reply_queue_length (void)
5953{
5954 return QUEUE_length (stop_reply_p, stop_reply_queue);
5955}
5956
722247f1
YQ
5957static void
5958remote_notif_stop_parse (struct notif_client *self, char *buf,
5959 struct notif_event *event)
5960{
5961 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5962}
5963
5964static void
5965remote_notif_stop_ack (struct notif_client *self, char *buf,
5966 struct notif_event *event)
5967{
5968 struct stop_reply *stop_reply = (struct stop_reply *) event;
5969
5970 /* acknowledge */
5971 putpkt ((char *) self->ack_command);
5972
5973 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5974 /* We got an unknown stop reply. */
5975 error (_("Unknown stop reply"));
5976
5977 push_stop_reply (stop_reply);
5978}
5979
5980static int
5981remote_notif_stop_can_get_pending_events (struct notif_client *self)
5982{
5983 /* We can't get pending events in remote_notif_process for
5984 notification stop, and we have to do this in remote_wait_ns
5985 instead. If we fetch all queued events from stub, remote stub
5986 may exit and we have no chance to process them back in
5987 remote_wait_ns. */
5988 mark_async_event_handler (remote_async_inferior_event_token);
5989 return 0;
5990}
5991
5992static void
5993stop_reply_dtr (struct notif_event *event)
5994{
5995 struct stop_reply *r = (struct stop_reply *) event;
5996
5997 VEC_free (cached_reg_t, r->regcache);
5998}
5999
6000static struct notif_event *
6001remote_notif_stop_alloc_reply (void)
6002{
8d749320
SM
6003 /* We cast to a pointer to the "base class". */
6004 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6005
6006 r->dtr = stop_reply_dtr;
6007
6008 return r;
6009}
6010
6011/* A client of notification Stop. */
6012
6013struct notif_client notif_client_stop =
6014{
6015 "Stop",
6016 "vStopped",
6017 remote_notif_stop_parse,
6018 remote_notif_stop_ack,
6019 remote_notif_stop_can_get_pending_events,
6020 remote_notif_stop_alloc_reply,
f48ff2a7 6021 REMOTE_NOTIF_STOP,
722247f1
YQ
6022};
6023
6024/* A parameter to pass data in and out. */
6025
6026struct queue_iter_param
6027{
6028 void *input;
6029 struct stop_reply *output;
6030};
6031
cbb8991c
DB
6032/* Determine if THREAD is a pending fork parent thread. ARG contains
6033 the pid of the process that owns the threads we want to check, or
6034 -1 if we want to check all threads. */
6035
6036static int
6037is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6038 ptid_t thread_ptid)
6039{
6040 if (ws->kind == TARGET_WAITKIND_FORKED
6041 || ws->kind == TARGET_WAITKIND_VFORKED)
6042 {
6043 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6044 return 1;
6045 }
6046
6047 return 0;
6048}
6049
6050/* Check whether EVENT is a fork event, and if it is, remove the
6051 fork child from the context list passed in DATA. */
6052
6053static int
6054remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6055 QUEUE_ITER (stop_reply_p) *iter,
6056 stop_reply_p event,
6057 void *data)
6058{
19ba03f4
SM
6059 struct queue_iter_param *param = (struct queue_iter_param *) data;
6060 struct threads_listing_context *context
6061 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6062
6063 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6064 || event->ws.kind == TARGET_WAITKIND_VFORKED
6065 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6066 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6067
6068 return 1;
6069}
6070
6071/* If CONTEXT contains any fork child threads that have not been
6072 reported yet, remove them from the CONTEXT list. If such a
6073 thread exists it is because we are stopped at a fork catchpoint
6074 and have not yet called follow_fork, which will set up the
6075 host-side data structures for the new process. */
6076
6077static void
6078remove_new_fork_children (struct threads_listing_context *context)
6079{
6080 struct thread_info * thread;
6081 int pid = -1;
6082 struct notif_client *notif = &notif_client_stop;
6083 struct queue_iter_param param;
6084
6085 /* For any threads stopped at a fork event, remove the corresponding
6086 fork child threads from the CONTEXT list. */
6087 ALL_NON_EXITED_THREADS (thread)
6088 {
6089 struct target_waitstatus *ws = &thread->pending_follow;
6090
6091 if (is_pending_fork_parent (ws, pid, thread->ptid))
6092 {
6093 threads_listing_context_remove (ws, context);
6094 }
6095 }
6096
6097 /* Check for any pending fork events (not reported or processed yet)
6098 in process PID and remove those fork child threads from the
6099 CONTEXT list as well. */
6100 remote_notif_get_pending_events (notif);
6101 param.input = context;
6102 param.output = NULL;
6103 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6104 remove_child_of_pending_fork, &param);
6105}
6106
f48ff2a7
YQ
6107/* Remove stop replies in the queue if its pid is equal to the given
6108 inferior's pid. */
722247f1
YQ
6109
6110static int
f48ff2a7
YQ
6111remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6112 QUEUE_ITER (stop_reply_p) *iter,
6113 stop_reply_p event,
6114 void *data)
722247f1 6115{
19ba03f4
SM
6116 struct queue_iter_param *param = (struct queue_iter_param *) data;
6117 struct inferior *inf = (struct inferior *) param->input;
722247f1 6118
f48ff2a7 6119 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6120 {
6121 stop_reply_xfree (event);
6122 QUEUE_remove_elem (stop_reply_p, q, iter);
6123 }
6124
6125 return 1;
6126}
6127
f48ff2a7 6128/* Discard all pending stop replies of inferior INF. */
c906108c 6129
74531fed 6130static void
5f4cf0bb 6131discard_pending_stop_replies (struct inferior *inf)
c906108c 6132{
722247f1
YQ
6133 int i;
6134 struct queue_iter_param param;
f48ff2a7
YQ
6135 struct stop_reply *reply;
6136 struct remote_state *rs = get_remote_state ();
6137 struct remote_notif_state *rns = rs->notif_state;
6138
6139 /* This function can be notified when an inferior exists. When the
6140 target is not remote, the notification state is NULL. */
6141 if (rs->remote_desc == NULL)
6142 return;
6143
6144 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6145
74531fed 6146 /* Discard the in-flight notification. */
f48ff2a7 6147 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6148 {
722247f1 6149 stop_reply_xfree (reply);
f48ff2a7 6150 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6151 }
c906108c 6152
722247f1
YQ
6153 param.input = inf;
6154 param.output = NULL;
74531fed
PA
6155 /* Discard the stop replies we have already pulled with
6156 vStopped. */
722247f1 6157 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6158 remove_stop_reply_for_inferior, &param);
6159}
6160
bcc75809
YQ
6161/* If its remote state is equal to the given remote state,
6162 remove EVENT from the stop reply queue. */
6163
6164static int
6165remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6166 QUEUE_ITER (stop_reply_p) *iter,
6167 stop_reply_p event,
6168 void *data)
6169{
19ba03f4
SM
6170 struct queue_iter_param *param = (struct queue_iter_param *) data;
6171 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6172
6173 if (event->rs == rs)
6174 {
6175 stop_reply_xfree (event);
6176 QUEUE_remove_elem (stop_reply_p, q, iter);
6177 }
6178
6179 return 1;
6180}
6181
6182/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6183
6184static void
bcc75809 6185discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6186{
6187 struct queue_iter_param param;
6188
bcc75809 6189 param.input = rs;
f48ff2a7
YQ
6190 param.output = NULL;
6191 /* Discard the stop replies we have already pulled with
6192 vStopped. */
6193 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6194 remove_stop_reply_of_remote_state, &param);
722247f1 6195}
74531fed 6196
722247f1
YQ
6197/* A parameter to pass data in and out. */
6198
6199static int
6200remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6201 QUEUE_ITER (stop_reply_p) *iter,
6202 stop_reply_p event,
6203 void *data)
6204{
19ba03f4
SM
6205 struct queue_iter_param *param = (struct queue_iter_param *) data;
6206 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6207
6208 if (ptid_match (event->ptid, *ptid))
6209 {
6210 param->output = event;
6211 QUEUE_remove_elem (stop_reply_p, q, iter);
6212 return 0;
c8e38a49 6213 }
722247f1
YQ
6214
6215 return 1;
74531fed 6216}
43ff13b4 6217
722247f1
YQ
6218/* Remove the first reply in 'stop_reply_queue' which matches
6219 PTID. */
2e9f7625 6220
722247f1
YQ
6221static struct stop_reply *
6222remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6223{
722247f1
YQ
6224 struct queue_iter_param param;
6225
6226 param.input = &ptid;
6227 param.output = NULL;
6228
6229 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6230 remote_notif_remove_once_on_match, &param);
6231 if (notif_debug)
6232 fprintf_unfiltered (gdb_stdlog,
6233 "notif: discard queued event: 'Stop' in %s\n",
6234 target_pid_to_str (ptid));
a744cf53 6235
722247f1 6236 return param.output;
74531fed 6237}
75c99385 6238
74531fed
PA
6239/* Look for a queued stop reply belonging to PTID. If one is found,
6240 remove it from the queue, and return it. Returns NULL if none is
6241 found. If there are still queued events left to process, tell the
6242 event loop to get back to target_wait soon. */
e24a49d8 6243
74531fed
PA
6244static struct stop_reply *
6245queued_stop_reply (ptid_t ptid)
6246{
722247f1 6247 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6248
722247f1 6249 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6250 /* There's still at least an event left. */
6251 mark_async_event_handler (remote_async_inferior_event_token);
6252
722247f1 6253 return r;
74531fed
PA
6254}
6255
6256/* Push a fully parsed stop reply in the stop reply queue. Since we
6257 know that we now have at least one queued event left to pass to the
6258 core side, tell the event loop to get back to target_wait soon. */
6259
6260static void
6261push_stop_reply (struct stop_reply *new_event)
6262{
722247f1 6263 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6264
722247f1
YQ
6265 if (notif_debug)
6266 fprintf_unfiltered (gdb_stdlog,
6267 "notif: push 'Stop' %s to queue %d\n",
6268 target_pid_to_str (new_event->ptid),
6269 QUEUE_length (stop_reply_p,
6270 stop_reply_queue));
74531fed
PA
6271
6272 mark_async_event_handler (remote_async_inferior_event_token);
6273}
6274
722247f1
YQ
6275static int
6276stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6277 QUEUE_ITER (stop_reply_p) *iter,
6278 struct stop_reply *event,
6279 void *data)
6280{
19ba03f4 6281 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6282
6283 return !(ptid_equal (*ptid, event->ptid)
6284 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6285}
6286
74531fed
PA
6287/* Returns true if we have a stop reply for PTID. */
6288
6289static int
6290peek_stop_reply (ptid_t ptid)
6291{
722247f1
YQ
6292 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6293 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6294}
6295
1f10ba14
PA
6296/* Skip PACKET until the next semi-colon (or end of string). */
6297
6298static char *
6299skip_to_semicolon (char *p)
6300{
6301 while (*p != '\0' && *p != ';')
6302 p++;
6303 return p;
6304}
6305
26d56a93
SL
6306/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6307 starting with P and ending with PEND matches PREFIX. */
6308
6309static int
6310strprefix (const char *p, const char *pend, const char *prefix)
6311{
6312 for ( ; p < pend; p++, prefix++)
6313 if (*p != *prefix)
6314 return 0;
6315 return *prefix == '\0';
6316}
6317
74531fed
PA
6318/* Parse the stop reply in BUF. Either the function succeeds, and the
6319 result is stored in EVENT, or throws an error. */
6320
6321static void
6322remote_parse_stop_reply (char *buf, struct stop_reply *event)
6323{
6324 struct remote_arch_state *rsa = get_remote_arch_state ();
6325 ULONGEST addr;
6326 char *p;
94585166 6327 int skipregs = 0;
74531fed
PA
6328
6329 event->ptid = null_ptid;
bcc75809 6330 event->rs = get_remote_state ();
74531fed
PA
6331 event->ws.kind = TARGET_WAITKIND_IGNORE;
6332 event->ws.value.integer = 0;
f7e6eed5 6333 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6334 event->regcache = NULL;
dc146f7c 6335 event->core = -1;
74531fed
PA
6336
6337 switch (buf[0])
6338 {
6339 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6340 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6341 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6342 ss = signal number
6343 n... = register number
6344 r... = register contents
6345 */
6346
6347 p = &buf[3]; /* after Txx */
6348 while (*p)
6349 {
6350 char *p1;
cea39f65 6351 int fieldsize;
43ff13b4 6352
1f10ba14
PA
6353 p1 = strchr (p, ':');
6354 if (p1 == NULL)
6355 error (_("Malformed packet(a) (missing colon): %s\n\
6356Packet: '%s'\n"),
6357 p, buf);
6358 if (p == p1)
6359 error (_("Malformed packet(a) (missing register number): %s\n\
6360Packet: '%s'\n"),
6361 p, buf);
3c3bea1c 6362
1f10ba14
PA
6363 /* Some "registers" are actually extended stop information.
6364 Note if you're adding a new entry here: GDB 7.9 and
6365 earlier assume that all register "numbers" that start
6366 with an hex digit are real register numbers. Make sure
6367 the server only sends such a packet if it knows the
6368 client understands it. */
c8e38a49 6369
26d56a93 6370 if (strprefix (p, p1, "thread"))
1f10ba14 6371 event->ptid = read_ptid (++p1, &p);
26d56a93
SL
6372 else if (strprefix (p, p1, "watch")
6373 || strprefix (p, p1, "rwatch")
6374 || strprefix (p, p1, "awatch"))
cea39f65 6375 {
f7e6eed5 6376 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6377 p = unpack_varlen_hex (++p1, &addr);
6378 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6379 }
26d56a93 6380 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6381 {
6382 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6383
6384 /* Make sure the stub doesn't forget to indicate support
6385 with qSupported. */
6386 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6387 error (_("Unexpected swbreak stop reason"));
6388
6389 /* The value part is documented as "must be empty",
6390 though we ignore it, in case we ever decide to make
6391 use of it in a backward compatible way. */
6392 p = skip_to_semicolon (p1 + 1);
6393 }
26d56a93 6394 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6395 {
6396 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6397
6398 /* Make sure the stub doesn't forget to indicate support
6399 with qSupported. */
6400 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6401 error (_("Unexpected hwbreak stop reason"));
6402
6403 /* See above. */
6404 p = skip_to_semicolon (p1 + 1);
6405 }
26d56a93 6406 else if (strprefix (p, p1, "library"))
cea39f65 6407 {
1f10ba14
PA
6408 event->ws.kind = TARGET_WAITKIND_LOADED;
6409 p = skip_to_semicolon (p1 + 1);
6410 }
26d56a93 6411 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6412 {
6413 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6414 /* p1 will indicate "begin" or "end", but it makes
6415 no difference for now, so ignore it. */
6416 p = skip_to_semicolon (p1 + 1);
6417 }
26d56a93 6418 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6419 {
6420 ULONGEST c;
a744cf53 6421
1f10ba14
PA
6422 p = unpack_varlen_hex (++p1, &c);
6423 event->core = c;
cea39f65 6424 }
26d56a93 6425 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6426 {
6427 event->ws.value.related_pid = read_ptid (++p1, &p);
6428 event->ws.kind = TARGET_WAITKIND_FORKED;
6429 }
26d56a93 6430 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6431 {
6432 event->ws.value.related_pid = read_ptid (++p1, &p);
6433 event->ws.kind = TARGET_WAITKIND_VFORKED;
6434 }
26d56a93 6435 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6436 {
6437 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6438 p = skip_to_semicolon (p1 + 1);
6439 }
6ab24463 6440 else if (strprefix (p, p1, "exec"))
94585166
DB
6441 {
6442 ULONGEST ignored;
6443 char pathname[PATH_MAX];
6444 int pathlen;
6445
6446 /* Determine the length of the execd pathname. */
6447 p = unpack_varlen_hex (++p1, &ignored);
6448 pathlen = (p - p1) / 2;
6449
6450 /* Save the pathname for event reporting and for
6451 the next run command. */
6452 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6453 pathname[pathlen] = '\0';
6454
6455 /* This is freed during event handling. */
6456 event->ws.value.execd_pathname = xstrdup (pathname);
6457 event->ws.kind = TARGET_WAITKIND_EXECD;
6458
6459 /* Skip the registers included in this packet, since
6460 they may be for an architecture different from the
6461 one used by the original program. */
6462 skipregs = 1;
6463 }
65706a29
PA
6464 else if (strprefix (p, p1, "create"))
6465 {
6466 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6467 p = skip_to_semicolon (p1 + 1);
6468 }
cea39f65
MS
6469 else
6470 {
1f10ba14
PA
6471 ULONGEST pnum;
6472 char *p_temp;
6473
94585166
DB
6474 if (skipregs)
6475 {
6476 p = skip_to_semicolon (p1 + 1);
6477 p++;
6478 continue;
6479 }
6480
1f10ba14
PA
6481 /* Maybe a real ``P'' register number. */
6482 p_temp = unpack_varlen_hex (p, &pnum);
6483 /* If the first invalid character is the colon, we got a
6484 register number. Otherwise, it's an unknown stop
6485 reason. */
6486 if (p_temp == p1)
6487 {
6488 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6489 cached_reg_t cached_reg;
43ff13b4 6490
1f10ba14
PA
6491 if (reg == NULL)
6492 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6493Packet: '%s'\n"),
1f10ba14 6494 hex_string (pnum), p, buf);
c8e38a49 6495
1f10ba14 6496 cached_reg.num = reg->regnum;
4100683b 6497
1f10ba14
PA
6498 p = p1 + 1;
6499 fieldsize = hex2bin (p, cached_reg.data,
6500 register_size (target_gdbarch (),
6501 reg->regnum));
6502 p += 2 * fieldsize;
6503 if (fieldsize < register_size (target_gdbarch (),
6504 reg->regnum))
6505 warning (_("Remote reply is too short: %s"), buf);
74531fed 6506
1f10ba14
PA
6507 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6508 }
6509 else
6510 {
6511 /* Not a number. Silently skip unknown optional
6512 info. */
6513 p = skip_to_semicolon (p1 + 1);
6514 }
cea39f65 6515 }
c8e38a49 6516
cea39f65
MS
6517 if (*p != ';')
6518 error (_("Remote register badly formatted: %s\nhere: %s"),
6519 buf, p);
6520 ++p;
6521 }
5b5596ff
PA
6522
6523 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6524 break;
6525
c8e38a49
PA
6526 /* fall through */
6527 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6528 {
6529 int sig;
6530
6531 event->ws.kind = TARGET_WAITKIND_STOPPED;
6532 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6533 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6534 event->ws.value.sig = (enum gdb_signal) sig;
6535 else
6536 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6537 }
c8e38a49 6538 break;
65706a29
PA
6539 case 'w': /* Thread exited. */
6540 {
6541 char *p;
6542 ULONGEST value;
6543
6544 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6545 p = unpack_varlen_hex (&buf[1], &value);
6546 event->ws.value.integer = value;
6547 if (*p != ';')
6548 error (_("stop reply packet badly formatted: %s"), buf);
6549 event->ptid = read_ptid (++p, &p);
6550 break;
6551 }
c8e38a49
PA
6552 case 'W': /* Target exited. */
6553 case 'X':
6554 {
6555 char *p;
6556 int pid;
6557 ULONGEST value;
82f73884 6558
c8e38a49
PA
6559 /* GDB used to accept only 2 hex chars here. Stubs should
6560 only send more if they detect GDB supports multi-process
6561 support. */
6562 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6563
c8e38a49
PA
6564 if (buf[0] == 'W')
6565 {
6566 /* The remote process exited. */
74531fed
PA
6567 event->ws.kind = TARGET_WAITKIND_EXITED;
6568 event->ws.value.integer = value;
c8e38a49
PA
6569 }
6570 else
6571 {
6572 /* The remote process exited with a signal. */
74531fed 6573 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6574 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6575 event->ws.value.sig = (enum gdb_signal) value;
6576 else
6577 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6578 }
82f73884 6579
c8e38a49
PA
6580 /* If no process is specified, assume inferior_ptid. */
6581 pid = ptid_get_pid (inferior_ptid);
6582 if (*p == '\0')
6583 ;
6584 else if (*p == ';')
6585 {
6586 p++;
6587
0b24eb2d 6588 if (*p == '\0')
82f73884 6589 ;
61012eef 6590 else if (startswith (p, "process:"))
82f73884 6591 {
c8e38a49 6592 ULONGEST upid;
a744cf53 6593
c8e38a49
PA
6594 p += sizeof ("process:") - 1;
6595 unpack_varlen_hex (p, &upid);
6596 pid = upid;
82f73884
PA
6597 }
6598 else
6599 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6600 }
c8e38a49
PA
6601 else
6602 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6603 event->ptid = pid_to_ptid (pid);
6604 }
6605 break;
f2faf941
PA
6606 case 'N':
6607 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6608 event->ptid = minus_one_ptid;
6609 break;
74531fed
PA
6610 }
6611
6efcd9a8 6612 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
6613 error (_("No process or thread specified in stop reply: %s"), buf);
6614}
6615
722247f1
YQ
6616/* When the stub wants to tell GDB about a new notification reply, it
6617 sends a notification (%Stop, for example). Those can come it at
6618 any time, hence, we have to make sure that any pending
6619 putpkt/getpkt sequence we're making is finished, before querying
6620 the stub for more events with the corresponding ack command
6621 (vStopped, for example). E.g., if we started a vStopped sequence
6622 immediately upon receiving the notification, something like this
6623 could happen:
74531fed
PA
6624
6625 1.1) --> Hg 1
6626 1.2) <-- OK
6627 1.3) --> g
6628 1.4) <-- %Stop
6629 1.5) --> vStopped
6630 1.6) <-- (registers reply to step #1.3)
6631
6632 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6633 query.
6634
796cb314 6635 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6636 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6637 doing whatever we were doing:
6638
6639 2.1) --> Hg 1
6640 2.2) <-- OK
6641 2.3) --> g
6642 2.4) <-- %Stop
6643 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6644 2.5) <-- (registers reply to step #2.3)
6645
6646 Eventualy after step #2.5, we return to the event loop, which
6647 notices there's an event on the
6648 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6649 associated callback --- the function below. At this point, we're
6650 always safe to start a vStopped sequence. :
6651
6652 2.6) --> vStopped
6653 2.7) <-- T05 thread:2
6654 2.8) --> vStopped
6655 2.9) --> OK
6656*/
6657
722247f1
YQ
6658void
6659remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6660{
6661 struct remote_state *rs = get_remote_state ();
74531fed 6662
f48ff2a7 6663 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6664 {
722247f1
YQ
6665 if (notif_debug)
6666 fprintf_unfiltered (gdb_stdlog,
6667 "notif: process: '%s' ack pending event\n",
6668 nc->name);
74531fed 6669
722247f1 6670 /* acknowledge */
f48ff2a7
YQ
6671 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6672 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6673
6674 while (1)
6675 {
6676 getpkt (&rs->buf, &rs->buf_size, 0);
6677 if (strcmp (rs->buf, "OK") == 0)
6678 break;
6679 else
722247f1 6680 remote_notif_ack (nc, rs->buf);
74531fed
PA
6681 }
6682 }
722247f1
YQ
6683 else
6684 {
6685 if (notif_debug)
6686 fprintf_unfiltered (gdb_stdlog,
6687 "notif: process: '%s' no pending reply\n",
6688 nc->name);
6689 }
74531fed
PA
6690}
6691
74531fed
PA
6692/* Called when it is decided that STOP_REPLY holds the info of the
6693 event that is to be returned to the core. This function always
6694 destroys STOP_REPLY. */
6695
6696static ptid_t
6697process_stop_reply (struct stop_reply *stop_reply,
6698 struct target_waitstatus *status)
6699{
6700 ptid_t ptid;
6701
6702 *status = stop_reply->ws;
6703 ptid = stop_reply->ptid;
6704
6705 /* If no thread/process was reported by the stub, assume the current
6706 inferior. */
6707 if (ptid_equal (ptid, null_ptid))
6708 ptid = inferior_ptid;
6709
5f3563ea 6710 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
6711 && status->kind != TARGET_WAITKIND_SIGNALLED
6712 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 6713 {
ee154bee 6714 struct remote_state *rs = get_remote_state ();
799a2abe 6715 struct private_thread_info *remote_thr;
ee154bee 6716
5f3563ea
PA
6717 /* Expedited registers. */
6718 if (stop_reply->regcache)
6719 {
217f1f79 6720 struct regcache *regcache
f5656ead 6721 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6722 cached_reg_t *reg;
6723 int ix;
6724
6725 for (ix = 0;
6726 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6727 ix++)
217f1f79 6728 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6729 VEC_free (cached_reg_t, stop_reply->regcache);
6730 }
74531fed 6731
1941c569 6732 remote_notice_new_inferior (ptid, 0);
799a2abe
PA
6733 remote_thr = demand_private_info (ptid);
6734 remote_thr->core = stop_reply->core;
6735 remote_thr->stop_reason = stop_reply->stop_reason;
6736 remote_thr->watch_data_address = stop_reply->watch_data_address;
74531fed
PA
6737 }
6738
74531fed
PA
6739 stop_reply_xfree (stop_reply);
6740 return ptid;
6741}
6742
6743/* The non-stop mode version of target_wait. */
6744
6745static ptid_t
47608cb1 6746remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6747{
6748 struct remote_state *rs = get_remote_state ();
74531fed
PA
6749 struct stop_reply *stop_reply;
6750 int ret;
fee9eda9 6751 int is_notif = 0;
74531fed
PA
6752
6753 /* If in non-stop mode, get out of getpkt even if a
6754 notification is received. */
6755
6756 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6757 0 /* forever */, &is_notif);
74531fed
PA
6758 while (1)
6759 {
fee9eda9 6760 if (ret != -1 && !is_notif)
74531fed
PA
6761 switch (rs->buf[0])
6762 {
6763 case 'E': /* Error of some sort. */
6764 /* We're out of sync with the target now. Did it continue
6765 or not? We can't tell which thread it was in non-stop,
6766 so just ignore this. */
6767 warning (_("Remote failure reply: %s"), rs->buf);
6768 break;
6769 case 'O': /* Console output. */
6770 remote_console_output (rs->buf + 1);
6771 break;
6772 default:
6773 warning (_("Invalid remote reply: %s"), rs->buf);
6774 break;
6775 }
6776
6777 /* Acknowledge a pending stop reply that may have arrived in the
6778 mean time. */
f48ff2a7 6779 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6780 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6781
6782 /* If indeed we noticed a stop reply, we're done. */
6783 stop_reply = queued_stop_reply (ptid);
6784 if (stop_reply != NULL)
6785 return process_stop_reply (stop_reply, status);
6786
47608cb1 6787 /* Still no event. If we're just polling for an event, then
74531fed 6788 return to the event loop. */
47608cb1 6789 if (options & TARGET_WNOHANG)
74531fed
PA
6790 {
6791 status->kind = TARGET_WAITKIND_IGNORE;
6792 return minus_one_ptid;
6793 }
6794
47608cb1 6795 /* Otherwise do a blocking wait. */
74531fed 6796 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6797 1 /* forever */, &is_notif);
74531fed
PA
6798 }
6799}
6800
6801/* Wait until the remote machine stops, then return, storing status in
6802 STATUS just as `wait' would. */
6803
6804static ptid_t
47608cb1 6805remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6806{
6807 struct remote_state *rs = get_remote_state ();
74531fed 6808 ptid_t event_ptid = null_ptid;
cea39f65 6809 char *buf;
74531fed
PA
6810 struct stop_reply *stop_reply;
6811
47608cb1
PA
6812 again:
6813
74531fed
PA
6814 status->kind = TARGET_WAITKIND_IGNORE;
6815 status->value.integer = 0;
6816
6817 stop_reply = queued_stop_reply (ptid);
6818 if (stop_reply != NULL)
6819 return process_stop_reply (stop_reply, status);
6820
6821 if (rs->cached_wait_status)
6822 /* Use the cached wait status, but only once. */
6823 rs->cached_wait_status = 0;
6824 else
6825 {
6826 int ret;
722247f1 6827 int is_notif;
567420d1
PA
6828 int forever = ((options & TARGET_WNOHANG) == 0
6829 && wait_forever_enabled_p);
6830
6831 if (!rs->waiting_for_stop_reply)
6832 {
6833 status->kind = TARGET_WAITKIND_NO_RESUMED;
6834 return minus_one_ptid;
6835 }
74531fed
PA
6836
6837 if (!target_is_async_p ())
6838 {
934b9bac 6839 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6840 /* If the user hit C-c before this packet, or between packets,
6841 pretend that it was hit right here. */
522002f9 6842 if (check_quit_flag ())
74531fed 6843 {
522002f9 6844 clear_quit_flag ();
934b9bac 6845 sync_remote_interrupt (SIGINT);
74531fed
PA
6846 }
6847 }
6848
6849 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6850 _never_ wait for ever -> test on target_is_async_p().
6851 However, before we do that we need to ensure that the caller
6852 knows how to take the target into/out of async mode. */
722247f1 6853 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6854 forever, &is_notif);
722247f1 6855
5e1b953b
SDJ
6856 if (!target_is_async_p ())
6857 signal (SIGINT, ofunc);
6858
722247f1
YQ
6859 /* GDB gets a notification. Return to core as this event is
6860 not interesting. */
6861 if (ret != -1 && is_notif)
6862 return minus_one_ptid;
567420d1
PA
6863
6864 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6865 return minus_one_ptid;
74531fed
PA
6866 }
6867
6868 buf = rs->buf;
6869
3a29589a
DJ
6870 /* Assume that the target has acknowledged Ctrl-C unless we receive
6871 an 'F' or 'O' packet. */
6872 if (buf[0] != 'F' && buf[0] != 'O')
6873 rs->ctrlc_pending_p = 0;
6874
74531fed
PA
6875 switch (buf[0])
6876 {
6877 case 'E': /* Error of some sort. */
6878 /* We're out of sync with the target now. Did it continue or
6879 not? Not is more likely, so report a stop. */
29090fb6
LM
6880 rs->waiting_for_stop_reply = 0;
6881
74531fed
PA
6882 warning (_("Remote failure reply: %s"), buf);
6883 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6884 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6885 break;
6886 case 'F': /* File-I/O request. */
3a29589a
DJ
6887 remote_fileio_request (buf, rs->ctrlc_pending_p);
6888 rs->ctrlc_pending_p = 0;
74531fed 6889 break;
f2faf941 6890 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 6891 {
29090fb6
LM
6892 struct stop_reply *stop_reply;
6893
6894 /* There is a stop reply to handle. */
6895 rs->waiting_for_stop_reply = 0;
6896
6897 stop_reply
722247f1
YQ
6898 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6899 rs->buf);
74531fed 6900
74531fed 6901 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6902 break;
6903 }
6904 case 'O': /* Console output. */
6905 remote_console_output (buf + 1);
c8e38a49
PA
6906 break;
6907 case '\0':
b73be471 6908 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6909 {
6910 /* Zero length reply means that we tried 'S' or 'C' and the
6911 remote system doesn't support it. */
6912 target_terminal_ours_for_output ();
6913 printf_filtered
6914 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6915 gdb_signal_to_name (rs->last_sent_signal));
6916 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6917 target_terminal_inferior ();
6918
280ceea3 6919 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49 6920 putpkt ((char *) buf);
c8e38a49 6921 break;
43ff13b4 6922 }
c8e38a49
PA
6923 /* else fallthrough */
6924 default:
6925 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 6926 break;
43ff13b4 6927 }
c8e38a49 6928
f2faf941
PA
6929 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
6930 return minus_one_ptid;
6931 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6932 {
6933 /* Nothing interesting happened. If we're doing a non-blocking
6934 poll, we're done. Otherwise, go back to waiting. */
6935 if (options & TARGET_WNOHANG)
6936 return minus_one_ptid;
6937 else
6938 goto again;
6939 }
74531fed
PA
6940 else if (status->kind != TARGET_WAITKIND_EXITED
6941 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6942 {
6943 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6944 record_currthread (rs, event_ptid);
82f73884
PA
6945 else
6946 event_ptid = inferior_ptid;
43ff13b4 6947 }
74531fed
PA
6948 else
6949 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6950 record_currthread (rs, minus_one_ptid);
79d7f229 6951
82f73884 6952 return event_ptid;
43ff13b4
JM
6953}
6954
74531fed
PA
6955/* Wait until the remote machine stops, then return, storing status in
6956 STATUS just as `wait' would. */
6957
c8e38a49 6958static ptid_t
117de6a9 6959remote_wait (struct target_ops *ops,
47608cb1 6960 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6961{
6962 ptid_t event_ptid;
6963
6efcd9a8 6964 if (target_is_non_stop_p ())
47608cb1 6965 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6966 else
47608cb1 6967 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6968
d9d41e78 6969 if (target_is_async_p ())
c8e38a49 6970 {
74531fed
PA
6971 /* If there are are events left in the queue tell the event loop
6972 to return here. */
722247f1 6973 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6974 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6975 }
c8e38a49
PA
6976
6977 return event_ptid;
6978}
6979
74ca34ce 6980/* Fetch a single register using a 'p' packet. */
c906108c 6981
b96ec7ac 6982static int
56be3814 6983fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6984{
6985 struct remote_state *rs = get_remote_state ();
2e9f7625 6986 char *buf, *p;
b96ec7ac
AC
6987 char regp[MAX_REGISTER_SIZE];
6988 int i;
6989
4082afcc 6990 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6991 return 0;
6992
6993 if (reg->pnum == -1)
6994 return 0;
6995
2e9f7625 6996 p = rs->buf;
fcad0fa4 6997 *p++ = 'p';
74ca34ce 6998 p += hexnumstr (p, reg->pnum);
fcad0fa4 6999 *p++ = '\0';
1f4437a4
MS
7000 putpkt (rs->buf);
7001 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7002
2e9f7625
DJ
7003 buf = rs->buf;
7004
74ca34ce
DJ
7005 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7006 {
7007 case PACKET_OK:
7008 break;
7009 case PACKET_UNKNOWN:
7010 return 0;
7011 case PACKET_ERROR:
27a9c0bf
MS
7012 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7013 gdbarch_register_name (get_regcache_arch (regcache),
7014 reg->regnum),
7015 buf);
74ca34ce 7016 }
3f9a994c
JB
7017
7018 /* If this register is unfetchable, tell the regcache. */
7019 if (buf[0] == 'x')
8480adf2 7020 {
56be3814 7021 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7022 return 1;
b96ec7ac 7023 }
b96ec7ac 7024
3f9a994c
JB
7025 /* Otherwise, parse and supply the value. */
7026 p = buf;
7027 i = 0;
7028 while (p[0] != 0)
7029 {
7030 if (p[1] == 0)
74ca34ce 7031 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7032
7033 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7034 p += 2;
7035 }
56be3814 7036 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7037 return 1;
b96ec7ac
AC
7038}
7039
74ca34ce
DJ
7040/* Fetch the registers included in the target's 'g' packet. */
7041
29709017
DJ
7042static int
7043send_g_packet (void)
c906108c 7044{
d01949b6 7045 struct remote_state *rs = get_remote_state ();
cea39f65 7046 int buf_len;
c906108c 7047
bba74b36 7048 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7049 remote_send (&rs->buf, &rs->buf_size);
c906108c 7050
29709017
DJ
7051 /* We can get out of synch in various cases. If the first character
7052 in the buffer is not a hex character, assume that has happened
7053 and try to fetch another packet to read. */
7054 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7055 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7056 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7057 && rs->buf[0] != 'x') /* New: unavailable register value. */
7058 {
7059 if (remote_debug)
7060 fprintf_unfiltered (gdb_stdlog,
7061 "Bad register packet; fetching a new packet\n");
7062 getpkt (&rs->buf, &rs->buf_size, 0);
7063 }
7064
74ca34ce
DJ
7065 buf_len = strlen (rs->buf);
7066
7067 /* Sanity check the received packet. */
7068 if (buf_len % 2 != 0)
7069 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7070
7071 return buf_len / 2;
7072}
7073
7074static void
56be3814 7075process_g_packet (struct regcache *regcache)
29709017 7076{
4a22f64d 7077 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7078 struct remote_state *rs = get_remote_state ();
7079 struct remote_arch_state *rsa = get_remote_arch_state ();
7080 int i, buf_len;
7081 char *p;
7082 char *regs;
7083
7084 buf_len = strlen (rs->buf);
7085
7086 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7087 if (buf_len > 2 * rsa->sizeof_g_packet)
7088 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7089
7090 /* Save the size of the packet sent to us by the target. It is used
7091 as a heuristic when determining the max size of packets that the
7092 target can safely receive. */
7093 if (rsa->actual_register_packet_size == 0)
7094 rsa->actual_register_packet_size = buf_len;
7095
7096 /* If this is smaller than we guessed the 'g' packet would be,
7097 update our records. A 'g' reply that doesn't include a register's
7098 value implies either that the register is not available, or that
7099 the 'p' packet must be used. */
7100 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7101 {
74ca34ce
DJ
7102 rsa->sizeof_g_packet = buf_len / 2;
7103
4a22f64d 7104 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7105 {
74ca34ce
DJ
7106 if (rsa->regs[i].pnum == -1)
7107 continue;
7108
7109 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7110 rsa->regs[i].in_g_packet = 0;
b96ec7ac 7111 else
74ca34ce 7112 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7113 }
74ca34ce 7114 }
b323314b 7115
224c3ddb 7116 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7117
7118 /* Unimplemented registers read as all bits zero. */
ea9c271d 7119 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7120
c906108c
SS
7121 /* Reply describes registers byte by byte, each byte encoded as two
7122 hex characters. Suck them all up, then supply them to the
7123 register cacheing/storage mechanism. */
7124
74ca34ce 7125 p = rs->buf;
ea9c271d 7126 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7127 {
74ca34ce
DJ
7128 if (p[0] == 0 || p[1] == 0)
7129 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7130 internal_error (__FILE__, __LINE__,
9b20d036 7131 _("unexpected end of 'g' packet reply"));
74ca34ce 7132
c906108c 7133 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7134 regs[i] = 0; /* 'x' */
c906108c
SS
7135 else
7136 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7137 p += 2;
7138 }
7139
a744cf53
MS
7140 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7141 {
7142 struct packet_reg *r = &rsa->regs[i];
7143
7144 if (r->in_g_packet)
7145 {
7146 if (r->offset * 2 >= strlen (rs->buf))
7147 /* This shouldn't happen - we adjusted in_g_packet above. */
7148 internal_error (__FILE__, __LINE__,
9b20d036 7149 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7150 else if (rs->buf[r->offset * 2] == 'x')
7151 {
7152 gdb_assert (r->offset * 2 < strlen (rs->buf));
7153 /* The register isn't available, mark it as such (at
7154 the same time setting the value to zero). */
7155 regcache_raw_supply (regcache, r->regnum, NULL);
7156 }
7157 else
7158 regcache_raw_supply (regcache, r->regnum,
7159 regs + r->offset);
7160 }
7161 }
c906108c
SS
7162}
7163
29709017 7164static void
56be3814 7165fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7166{
7167 send_g_packet ();
56be3814 7168 process_g_packet (regcache);
29709017
DJ
7169}
7170
e6e4e701
PA
7171/* Make the remote selected traceframe match GDB's selected
7172 traceframe. */
7173
7174static void
7175set_remote_traceframe (void)
7176{
7177 int newnum;
262e1174 7178 struct remote_state *rs = get_remote_state ();
e6e4e701 7179
262e1174 7180 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7181 return;
7182
7183 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7184 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7185
7186 newnum = target_trace_find (tfind_number,
7187 get_traceframe_number (), 0, 0, NULL);
7188
7189 /* Should not happen. If it does, all bets are off. */
7190 if (newnum != get_traceframe_number ())
7191 warning (_("could not set remote traceframe"));
7192}
7193
74ca34ce 7194static void
28439f5e
PA
7195remote_fetch_registers (struct target_ops *ops,
7196 struct regcache *regcache, int regnum)
74ca34ce 7197{
74ca34ce
DJ
7198 struct remote_arch_state *rsa = get_remote_arch_state ();
7199 int i;
7200
e6e4e701 7201 set_remote_traceframe ();
79d7f229 7202 set_general_thread (inferior_ptid);
74ca34ce
DJ
7203
7204 if (regnum >= 0)
7205 {
7206 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7207
74ca34ce
DJ
7208 gdb_assert (reg != NULL);
7209
7210 /* If this register might be in the 'g' packet, try that first -
7211 we are likely to read more than one register. If this is the
7212 first 'g' packet, we might be overly optimistic about its
7213 contents, so fall back to 'p'. */
7214 if (reg->in_g_packet)
7215 {
56be3814 7216 fetch_registers_using_g (regcache);
74ca34ce
DJ
7217 if (reg->in_g_packet)
7218 return;
7219 }
7220
56be3814 7221 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7222 return;
7223
7224 /* This register is not available. */
56be3814 7225 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7226
7227 return;
7228 }
7229
56be3814 7230 fetch_registers_using_g (regcache);
74ca34ce 7231
4a22f64d 7232 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7233 if (!rsa->regs[i].in_g_packet)
56be3814 7234 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7235 {
7236 /* This register is not available. */
56be3814 7237 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7238 }
7239}
7240
c906108c
SS
7241/* Prepare to store registers. Since we may send them all (using a
7242 'G' request), we have to read out the ones we don't want to change
7243 first. */
7244
c5aa993b 7245static void
f32dbf8c 7246remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7247{
ea9c271d 7248 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7249 int i;
cfd77fa1 7250 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7251
c906108c 7252 /* Make sure the entire registers array is valid. */
4082afcc 7253 switch (packet_support (PACKET_P))
5a2468f5
JM
7254 {
7255 case PACKET_DISABLE:
7256 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7257 /* Make sure all the necessary registers are cached. */
4a22f64d 7258 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7259 if (rsa->regs[i].in_g_packet)
316f2060 7260 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7261 break;
7262 case PACKET_ENABLE:
7263 break;
7264 }
7265}
7266
ad10f812 7267/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7268 packet was not recognized. */
5a2468f5
JM
7269
7270static int
1f4437a4
MS
7271store_register_using_P (const struct regcache *regcache,
7272 struct packet_reg *reg)
5a2468f5 7273{
4a22f64d 7274 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7275 struct remote_state *rs = get_remote_state ();
5a2468f5 7276 /* Try storing a single register. */
6d820c5c 7277 char *buf = rs->buf;
cfd77fa1 7278 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7279 char *p;
5a2468f5 7280
4082afcc 7281 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7282 return 0;
7283
7284 if (reg->pnum == -1)
7285 return 0;
7286
ea9c271d 7287 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7288 p = buf + strlen (buf);
56be3814 7289 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7290 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7291 putpkt (rs->buf);
7292 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7293
74ca34ce
DJ
7294 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7295 {
7296 case PACKET_OK:
7297 return 1;
7298 case PACKET_ERROR:
27a9c0bf
MS
7299 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7300 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7301 case PACKET_UNKNOWN:
7302 return 0;
7303 default:
7304 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7305 }
c906108c
SS
7306}
7307
23860348
MS
7308/* Store register REGNUM, or all registers if REGNUM == -1, from the
7309 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7310
7311static void
56be3814 7312store_registers_using_G (const struct regcache *regcache)
c906108c 7313{
d01949b6 7314 struct remote_state *rs = get_remote_state ();
ea9c271d 7315 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7316 gdb_byte *regs;
c906108c
SS
7317 char *p;
7318
193cb69f
AC
7319 /* Extract all the registers in the regcache copying them into a
7320 local buffer. */
7321 {
b323314b 7322 int i;
a744cf53 7323
224c3ddb 7324 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7325 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7326 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7327 {
ea9c271d 7328 struct packet_reg *r = &rsa->regs[i];
a744cf53 7329
b323314b 7330 if (r->in_g_packet)
56be3814 7331 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7332 }
7333 }
c906108c
SS
7334
7335 /* Command describes registers byte by byte,
7336 each byte encoded as two hex characters. */
6d820c5c 7337 p = rs->buf;
193cb69f 7338 *p++ = 'G';
74ca34ce
DJ
7339 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7340 updated. */
7341 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7342 putpkt (rs->buf);
7343 getpkt (&rs->buf, &rs->buf_size, 0);
7344 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7345 error (_("Could not write registers; remote failure reply '%s'"),
7346 rs->buf);
c906108c 7347}
74ca34ce
DJ
7348
7349/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7350 of the register cache buffer. FIXME: ignores errors. */
7351
7352static void
28439f5e
PA
7353remote_store_registers (struct target_ops *ops,
7354 struct regcache *regcache, int regnum)
74ca34ce 7355{
74ca34ce
DJ
7356 struct remote_arch_state *rsa = get_remote_arch_state ();
7357 int i;
7358
e6e4e701 7359 set_remote_traceframe ();
79d7f229 7360 set_general_thread (inferior_ptid);
74ca34ce
DJ
7361
7362 if (regnum >= 0)
7363 {
7364 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7365
74ca34ce
DJ
7366 gdb_assert (reg != NULL);
7367
7368 /* Always prefer to store registers using the 'P' packet if
7369 possible; we often change only a small number of registers.
7370 Sometimes we change a larger number; we'd need help from a
7371 higher layer to know to use 'G'. */
56be3814 7372 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7373 return;
7374
7375 /* For now, don't complain if we have no way to write the
7376 register. GDB loses track of unavailable registers too
7377 easily. Some day, this may be an error. We don't have
0df8b418 7378 any way to read the register, either... */
74ca34ce
DJ
7379 if (!reg->in_g_packet)
7380 return;
7381
56be3814 7382 store_registers_using_G (regcache);
74ca34ce
DJ
7383 return;
7384 }
7385
56be3814 7386 store_registers_using_G (regcache);
74ca34ce 7387
4a22f64d 7388 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7389 if (!rsa->regs[i].in_g_packet)
56be3814 7390 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7391 /* See above for why we do not issue an error here. */
7392 continue;
7393}
c906108c
SS
7394\f
7395
7396/* Return the number of hex digits in num. */
7397
7398static int
fba45db2 7399hexnumlen (ULONGEST num)
c906108c
SS
7400{
7401 int i;
7402
7403 for (i = 0; num != 0; i++)
7404 num >>= 4;
7405
7406 return max (i, 1);
7407}
7408
2df3850c 7409/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7410
7411static int
fba45db2 7412hexnumstr (char *buf, ULONGEST num)
c906108c 7413{
c906108c 7414 int len = hexnumlen (num);
a744cf53 7415
2df3850c
JM
7416 return hexnumnstr (buf, num, len);
7417}
7418
c906108c 7419
2df3850c 7420/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7421
2df3850c 7422static int
fba45db2 7423hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7424{
7425 int i;
7426
7427 buf[width] = '\0';
7428
7429 for (i = width - 1; i >= 0; i--)
c906108c 7430 {
c5aa993b 7431 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7432 num >>= 4;
7433 }
7434
2df3850c 7435 return width;
c906108c
SS
7436}
7437
23860348 7438/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7439
7440static CORE_ADDR
fba45db2 7441remote_address_masked (CORE_ADDR addr)
c906108c 7442{
883b9c6c 7443 unsigned int address_size = remote_address_size;
a744cf53 7444
911c95a5
UW
7445 /* If "remoteaddresssize" was not set, default to target address size. */
7446 if (!address_size)
f5656ead 7447 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7448
7449 if (address_size > 0
7450 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7451 {
7452 /* Only create a mask when that mask can safely be constructed
23860348 7453 in a ULONGEST variable. */
c906108c 7454 ULONGEST mask = 1;
a744cf53 7455
911c95a5 7456 mask = (mask << address_size) - 1;
c906108c
SS
7457 addr &= mask;
7458 }
7459 return addr;
7460}
7461
7462/* Determine whether the remote target supports binary downloading.
7463 This is accomplished by sending a no-op memory write of zero length
7464 to the target at the specified address. It does not suffice to send
23860348
MS
7465 the whole packet, since many stubs strip the eighth bit and
7466 subsequently compute a wrong checksum, which causes real havoc with
7467 remote_write_bytes.
7a292a7a 7468
96baa820 7469 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7470 clean. In cases like this, the user should clear "remote
23860348 7471 X-packet". */
96baa820 7472
c906108c 7473static void
fba45db2 7474check_binary_download (CORE_ADDR addr)
c906108c 7475{
d01949b6 7476 struct remote_state *rs = get_remote_state ();
24b06219 7477
4082afcc 7478 switch (packet_support (PACKET_X))
c906108c 7479 {
96baa820
JM
7480 case PACKET_DISABLE:
7481 break;
7482 case PACKET_ENABLE:
7483 break;
7484 case PACKET_SUPPORT_UNKNOWN:
7485 {
96baa820 7486 char *p;
802188a7 7487
2e9f7625 7488 p = rs->buf;
96baa820
JM
7489 *p++ = 'X';
7490 p += hexnumstr (p, (ULONGEST) addr);
7491 *p++ = ',';
7492 p += hexnumstr (p, (ULONGEST) 0);
7493 *p++ = ':';
7494 *p = '\0';
802188a7 7495
2e9f7625 7496 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7497 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7498
2e9f7625 7499 if (rs->buf[0] == '\0')
96baa820
JM
7500 {
7501 if (remote_debug)
7502 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7503 "binary downloading NOT "
7504 "supported by target\n");
444abaca 7505 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7506 }
7507 else
7508 {
7509 if (remote_debug)
7510 fprintf_unfiltered (gdb_stdlog,
64b9b334 7511 "binary downloading supported by target\n");
444abaca 7512 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7513 }
7514 break;
7515 }
c906108c
SS
7516 }
7517}
7518
124e13d9
SM
7519/* Helper function to resize the payload in order to try to get a good
7520 alignment. We try to write an amount of data such that the next write will
7521 start on an address aligned on REMOTE_ALIGN_WRITES. */
7522
7523static int
7524align_for_efficient_write (int todo, CORE_ADDR memaddr)
7525{
7526 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7527}
7528
c906108c
SS
7529/* Write memory data directly to the remote machine.
7530 This does not inform the data cache; the data cache uses this.
a76d924d 7531 HEADER is the starting part of the packet.
c906108c
SS
7532 MEMADDR is the address in the remote memory space.
7533 MYADDR is the address of the buffer in our space.
124e13d9
SM
7534 LEN_UNITS is the number of addressable units to write.
7535 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7536 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7537 should send data as binary ('X'), or hex-encoded ('M').
7538
7539 The function creates packet of the form
7540 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7541
124e13d9 7542 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7543
7544 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7545 are omitted.
7546
9b409511 7547 Return the transferred status, error or OK (an
124e13d9
SM
7548 'enum target_xfer_status' value). Save the number of addressable units
7549 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7550
7551 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7552 exchange between gdb and the stub could look like (?? in place of the
7553 checksum):
7554
7555 -> $m1000,4#??
7556 <- aaaabbbbccccdddd
7557
7558 -> $M1000,3:eeeeffffeeee#??
7559 <- OK
7560
7561 -> $m1000,4#??
7562 <- eeeeffffeeeedddd */
c906108c 7563
9b409511 7564static enum target_xfer_status
a76d924d 7565remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7566 const gdb_byte *myaddr, ULONGEST len_units,
7567 int unit_size, ULONGEST *xfered_len_units,
7568 char packet_format, int use_length)
c906108c 7569{
6d820c5c 7570 struct remote_state *rs = get_remote_state ();
cfd77fa1 7571 char *p;
a76d924d
DJ
7572 char *plen = NULL;
7573 int plenlen = 0;
124e13d9
SM
7574 int todo_units;
7575 int units_written;
7576 int payload_capacity_bytes;
7577 int payload_length_bytes;
a76d924d
DJ
7578
7579 if (packet_format != 'X' && packet_format != 'M')
7580 internal_error (__FILE__, __LINE__,
9b20d036 7581 _("remote_write_bytes_aux: bad packet format"));
c906108c 7582
124e13d9 7583 if (len_units == 0)
9b409511 7584 return TARGET_XFER_EOF;
b2182ed2 7585
124e13d9 7586 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7587
6d820c5c
DJ
7588 /* The packet buffer will be large enough for the payload;
7589 get_memory_packet_size ensures this. */
a76d924d 7590 rs->buf[0] = '\0';
c906108c 7591
a257b5bb 7592 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7593 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7594
124e13d9 7595 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7596 if (!use_length)
0df8b418 7597 /* The comma won't be used. */
124e13d9
SM
7598 payload_capacity_bytes += 1;
7599 payload_capacity_bytes -= strlen (header);
7600 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7601
a76d924d 7602 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7603
a76d924d
DJ
7604 strcat (rs->buf, header);
7605 p = rs->buf + strlen (header);
7606
7607 /* Compute a best guess of the number of bytes actually transfered. */
7608 if (packet_format == 'X')
c906108c 7609 {
23860348 7610 /* Best guess at number of bytes that will fit. */
124e13d9 7611 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7612 if (use_length)
124e13d9
SM
7613 payload_capacity_bytes -= hexnumlen (todo_units);
7614 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7615 }
7616 else
7617 {
124e13d9
SM
7618 /* Number of bytes that will fit. */
7619 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7620 if (use_length)
124e13d9
SM
7621 payload_capacity_bytes -= hexnumlen (todo_units);
7622 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7623 }
a76d924d 7624
124e13d9 7625 if (todo_units <= 0)
3de11b2e 7626 internal_error (__FILE__, __LINE__,
405f8e94 7627 _("minimum packet size too small to write data"));
802188a7 7628
6765f3e5
DJ
7629 /* If we already need another packet, then try to align the end
7630 of this packet to a useful boundary. */
124e13d9
SM
7631 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7632 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7633
a257b5bb 7634 /* Append "<memaddr>". */
917317f4
JM
7635 memaddr = remote_address_masked (memaddr);
7636 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7637
a76d924d
DJ
7638 if (use_length)
7639 {
7640 /* Append ",". */
7641 *p++ = ',';
802188a7 7642
124e13d9
SM
7643 /* Append the length and retain its location and size. It may need to be
7644 adjusted once the packet body has been created. */
a76d924d 7645 plen = p;
124e13d9 7646 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7647 p += plenlen;
7648 }
a257b5bb
AC
7649
7650 /* Append ":". */
917317f4
JM
7651 *p++ = ':';
7652 *p = '\0';
802188a7 7653
a257b5bb 7654 /* Append the packet body. */
a76d924d 7655 if (packet_format == 'X')
917317f4 7656 {
917317f4
JM
7657 /* Binary mode. Send target system values byte by byte, in
7658 increasing byte addresses. Only escape certain critical
7659 characters. */
124e13d9
SM
7660 payload_length_bytes =
7661 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7662 &units_written, payload_capacity_bytes);
6765f3e5 7663
124e13d9 7664 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7665 a second try to keep the end of the packet aligned. Don't do
7666 this if the packet is tiny. */
124e13d9 7667 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7668 {
124e13d9
SM
7669 int new_todo_units;
7670
7671 new_todo_units = align_for_efficient_write (units_written, memaddr);
7672
7673 if (new_todo_units != units_written)
7674 payload_length_bytes =
7675 remote_escape_output (myaddr, new_todo_units, unit_size,
7676 (gdb_byte *) p, &units_written,
7677 payload_capacity_bytes);
6765f3e5
DJ
7678 }
7679
124e13d9
SM
7680 p += payload_length_bytes;
7681 if (use_length && units_written < todo_units)
c906108c 7682 {
802188a7 7683 /* Escape chars have filled up the buffer prematurely,
124e13d9 7684 and we have actually sent fewer units than planned.
917317f4
JM
7685 Fix-up the length field of the packet. Use the same
7686 number of characters as before. */
124e13d9
SM
7687 plen += hexnumnstr (plen, (ULONGEST) units_written,
7688 plenlen);
917317f4 7689 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7690 }
a76d924d
DJ
7691 }
7692 else
7693 {
917317f4
JM
7694 /* Normal mode: Send target system values byte by byte, in
7695 increasing byte addresses. Each byte is encoded as a two hex
7696 value. */
124e13d9
SM
7697 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7698 units_written = todo_units;
c906108c 7699 }
802188a7 7700
2e9f7625 7701 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7702 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7703
2e9f7625 7704 if (rs->buf[0] == 'E')
00d84524 7705 return TARGET_XFER_E_IO;
802188a7 7706
124e13d9
SM
7707 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7708 send fewer units than we'd planned. */
7709 *xfered_len_units = (ULONGEST) units_written;
9b409511 7710 return TARGET_XFER_OK;
c906108c
SS
7711}
7712
a76d924d
DJ
7713/* Write memory data directly to the remote machine.
7714 This does not inform the data cache; the data cache uses this.
7715 MEMADDR is the address in the remote memory space.
7716 MYADDR is the address of the buffer in our space.
7717 LEN is the number of bytes.
7718
9b409511
YQ
7719 Return the transferred status, error or OK (an
7720 'enum target_xfer_status' value). Save the number of bytes
7721 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7722
9b409511
YQ
7723static enum target_xfer_status
7724remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7725 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7726{
7727 char *packet_format = 0;
7728
7729 /* Check whether the target supports binary download. */
7730 check_binary_download (memaddr);
7731
4082afcc 7732 switch (packet_support (PACKET_X))
a76d924d
DJ
7733 {
7734 case PACKET_ENABLE:
7735 packet_format = "X";
7736 break;
7737 case PACKET_DISABLE:
7738 packet_format = "M";
7739 break;
7740 case PACKET_SUPPORT_UNKNOWN:
7741 internal_error (__FILE__, __LINE__,
7742 _("remote_write_bytes: bad internal state"));
7743 default:
7744 internal_error (__FILE__, __LINE__, _("bad switch"));
7745 }
7746
7747 return remote_write_bytes_aux (packet_format,
124e13d9 7748 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7749 packet_format[0], 1);
a76d924d
DJ
7750}
7751
9217e74e
YQ
7752/* Read memory data directly from the remote machine.
7753 This does not use the data cache; the data cache uses this.
7754 MEMADDR is the address in the remote memory space.
7755 MYADDR is the address of the buffer in our space.
124e13d9
SM
7756 LEN_UNITS is the number of addressable memory units to read..
7757 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7758
7759 Return the transferred status, error or OK (an
7760 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7761 transferred in *XFERED_LEN_UNITS.
7762
7763 See the comment of remote_write_bytes_aux for an example of
7764 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7765
7766static enum target_xfer_status
124e13d9
SM
7767remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7768 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7769{
7770 struct remote_state *rs = get_remote_state ();
124e13d9 7771 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7772 char *p;
124e13d9
SM
7773 int todo_units;
7774 int decoded_bytes;
9217e74e 7775
124e13d9 7776 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7777 /* The packet buffer will be large enough for the payload;
7778 get_memory_packet_size ensures this. */
7779
124e13d9
SM
7780 /* Number of units that will fit. */
7781 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7782
7783 /* Construct "m"<memaddr>","<len>". */
7784 memaddr = remote_address_masked (memaddr);
7785 p = rs->buf;
7786 *p++ = 'm';
7787 p += hexnumstr (p, (ULONGEST) memaddr);
7788 *p++ = ',';
124e13d9 7789 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7790 *p = '\0';
7791 putpkt (rs->buf);
7792 getpkt (&rs->buf, &rs->buf_size, 0);
7793 if (rs->buf[0] == 'E'
7794 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7795 && rs->buf[3] == '\0')
7796 return TARGET_XFER_E_IO;
7797 /* Reply describes memory byte by byte, each byte encoded as two hex
7798 characters. */
7799 p = rs->buf;
124e13d9 7800 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7801 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7802 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7803 return TARGET_XFER_OK;
7804}
7805
b55fbac4
YQ
7806/* Using the set of read-only target sections of remote, read live
7807 read-only memory.
8acf9577
YQ
7808
7809 For interface/parameters/return description see target.h,
7810 to_xfer_partial. */
7811
7812static enum target_xfer_status
b55fbac4
YQ
7813remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7814 ULONGEST memaddr, ULONGEST len,
124e13d9 7815 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7816{
7817 struct target_section *secp;
7818 struct target_section_table *table;
7819
7820 secp = target_section_by_addr (ops, memaddr);
7821 if (secp != NULL
7822 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7823 secp->the_bfd_section)
7824 & SEC_READONLY))
7825 {
7826 struct target_section *p;
7827 ULONGEST memend = memaddr + len;
7828
7829 table = target_get_section_table (ops);
7830
7831 for (p = table->sections; p < table->sections_end; p++)
7832 {
7833 if (memaddr >= p->addr)
7834 {
7835 if (memend <= p->endaddr)
7836 {
7837 /* Entire transfer is within this section. */
124e13d9 7838 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7839 xfered_len);
8acf9577
YQ
7840 }
7841 else if (memaddr >= p->endaddr)
7842 {
7843 /* This section ends before the transfer starts. */
7844 continue;
7845 }
7846 else
7847 {
7848 /* This section overlaps the transfer. Just do half. */
7849 len = p->endaddr - memaddr;
124e13d9 7850 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7851 xfered_len);
8acf9577
YQ
7852 }
7853 }
7854 }
7855 }
7856
7857 return TARGET_XFER_EOF;
7858}
7859
9217e74e
YQ
7860/* Similar to remote_read_bytes_1, but it reads from the remote stub
7861 first if the requested memory is unavailable in traceframe.
7862 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7863
9b409511 7864static enum target_xfer_status
8acf9577 7865remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7866 gdb_byte *myaddr, ULONGEST len, int unit_size,
7867 ULONGEST *xfered_len)
c906108c 7868{
6b6aa828 7869 if (len == 0)
96c4f946 7870 return TARGET_XFER_EOF;
b2182ed2 7871
8acf9577
YQ
7872 if (get_traceframe_number () != -1)
7873 {
7874 VEC(mem_range_s) *available;
7875
7876 /* If we fail to get the set of available memory, then the
7877 target does not support querying traceframe info, and so we
7878 attempt reading from the traceframe anyway (assuming the
7879 target implements the old QTro packet then). */
7880 if (traceframe_available_memory (&available, memaddr, len))
7881 {
7882 struct cleanup *old_chain;
7883
7884 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7885
7886 if (VEC_empty (mem_range_s, available)
7887 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7888 {
7889 enum target_xfer_status res;
7890
7891 /* Don't read into the traceframe's available
7892 memory. */
7893 if (!VEC_empty (mem_range_s, available))
7894 {
7895 LONGEST oldlen = len;
7896
7897 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7898 gdb_assert (len <= oldlen);
7899 }
7900
7901 do_cleanups (old_chain);
7902
7903 /* This goes through the topmost target again. */
b55fbac4 7904 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7905 len, unit_size, xfered_len);
8acf9577
YQ
7906 if (res == TARGET_XFER_OK)
7907 return TARGET_XFER_OK;
7908 else
7909 {
7910 /* No use trying further, we know some memory starting
7911 at MEMADDR isn't available. */
7912 *xfered_len = len;
7913 return TARGET_XFER_UNAVAILABLE;
7914 }
7915 }
7916
7917 /* Don't try to read more than how much is available, in
7918 case the target implements the deprecated QTro packet to
7919 cater for older GDBs (the target's knowledge of read-only
7920 sections may be outdated by now). */
7921 len = VEC_index (mem_range_s, available, 0)->length;
7922
7923 do_cleanups (old_chain);
7924 }
7925 }
7926
124e13d9 7927 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7928}
74531fed 7929
c906108c 7930\f
c906108c 7931
a76d924d
DJ
7932/* Sends a packet with content determined by the printf format string
7933 FORMAT and the remaining arguments, then gets the reply. Returns
7934 whether the packet was a success, a failure, or unknown. */
7935
77b64a49
PA
7936static enum packet_result remote_send_printf (const char *format, ...)
7937 ATTRIBUTE_PRINTF (1, 2);
7938
2c0b251b 7939static enum packet_result
a76d924d
DJ
7940remote_send_printf (const char *format, ...)
7941{
7942 struct remote_state *rs = get_remote_state ();
7943 int max_size = get_remote_packet_size ();
a76d924d 7944 va_list ap;
a744cf53 7945
a76d924d
DJ
7946 va_start (ap, format);
7947
7948 rs->buf[0] = '\0';
7949 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7950 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7951
7952 if (putpkt (rs->buf) < 0)
7953 error (_("Communication problem with target."));
7954
7955 rs->buf[0] = '\0';
7956 getpkt (&rs->buf, &rs->buf_size, 0);
7957
7958 return packet_check_result (rs->buf);
7959}
7960
7961static void
7962restore_remote_timeout (void *p)
7963{
7964 int value = *(int *)p;
a744cf53 7965
a76d924d
DJ
7966 remote_timeout = value;
7967}
7968
7969/* Flash writing can take quite some time. We'll set
7970 effectively infinite timeout for flash operations.
7971 In future, we'll need to decide on a better approach. */
7972static const int remote_flash_timeout = 1000;
7973
7974static void
7975remote_flash_erase (struct target_ops *ops,
7976 ULONGEST address, LONGEST length)
7977{
f5656ead 7978 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7979 int saved_remote_timeout = remote_timeout;
7980 enum packet_result ret;
a76d924d
DJ
7981 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7982 &saved_remote_timeout);
a744cf53 7983
a76d924d
DJ
7984 remote_timeout = remote_flash_timeout;
7985
7986 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7987 phex (address, addr_size),
a76d924d
DJ
7988 phex (length, 4));
7989 switch (ret)
7990 {
7991 case PACKET_UNKNOWN:
7992 error (_("Remote target does not support flash erase"));
7993 case PACKET_ERROR:
7994 error (_("Error erasing flash with vFlashErase packet"));
7995 default:
7996 break;
7997 }
7998
7999 do_cleanups (back_to);
8000}
8001
9b409511
YQ
8002static enum target_xfer_status
8003remote_flash_write (struct target_ops *ops, ULONGEST address,
8004 ULONGEST length, ULONGEST *xfered_len,
8005 const gdb_byte *data)
a76d924d
DJ
8006{
8007 int saved_remote_timeout = remote_timeout;
9b409511 8008 enum target_xfer_status ret;
a76d924d 8009 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 8010 &saved_remote_timeout);
a76d924d
DJ
8011
8012 remote_timeout = remote_flash_timeout;
124e13d9 8013 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 8014 xfered_len,'X', 0);
a76d924d
DJ
8015 do_cleanups (back_to);
8016
8017 return ret;
8018}
8019
8020static void
8021remote_flash_done (struct target_ops *ops)
8022{
8023 int saved_remote_timeout = remote_timeout;
8024 int ret;
8025 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8026 &saved_remote_timeout);
8027
8028 remote_timeout = remote_flash_timeout;
8029 ret = remote_send_printf ("vFlashDone");
8030 do_cleanups (back_to);
8031
8032 switch (ret)
8033 {
8034 case PACKET_UNKNOWN:
8035 error (_("Remote target does not support vFlashDone"));
8036 case PACKET_ERROR:
8037 error (_("Error finishing flash operation"));
8038 default:
8039 break;
8040 }
8041}
8042
c906108c 8043static void
fba45db2 8044remote_files_info (struct target_ops *ignore)
c906108c
SS
8045{
8046 puts_filtered ("Debugging a target over a serial line.\n");
8047}
8048\f
8049/* Stuff for dealing with the packets which are part of this protocol.
8050 See comment at top of file for details. */
8051
1927e618
PA
8052/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8053 error to higher layers. Called when a serial error is detected.
8054 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8055 the system error message for errno at function entry and final dot
8056 for output compatibility with throw_perror_with_name. */
1927e618
PA
8057
8058static void
8059unpush_and_perror (const char *string)
8060{
d6cb50a2 8061 int saved_errno = errno;
1927e618
PA
8062
8063 remote_unpush_target ();
d6cb50a2
JK
8064 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8065 safe_strerror (saved_errno));
1927e618
PA
8066}
8067
0876f84a 8068/* Read a single character from the remote end. */
c906108c
SS
8069
8070static int
fba45db2 8071readchar (int timeout)
c906108c
SS
8072{
8073 int ch;
5d93a237 8074 struct remote_state *rs = get_remote_state ();
c906108c 8075
5d93a237 8076 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 8077
2acceee2 8078 if (ch >= 0)
0876f84a 8079 return ch;
2acceee2
JM
8080
8081 switch ((enum serial_rc) ch)
c906108c
SS
8082 {
8083 case SERIAL_EOF:
78a095c3 8084 remote_unpush_target ();
598d3636 8085 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8086 /* no return */
c906108c 8087 case SERIAL_ERROR:
1927e618
PA
8088 unpush_and_perror (_("Remote communication error. "
8089 "Target disconnected."));
2acceee2 8090 /* no return */
c906108c 8091 case SERIAL_TIMEOUT:
2acceee2 8092 break;
c906108c 8093 }
2acceee2 8094 return ch;
c906108c
SS
8095}
8096
c33e31fd
PA
8097/* Wrapper for serial_write that closes the target and throws if
8098 writing fails. */
8099
8100static void
8101remote_serial_write (const char *str, int len)
8102{
5d93a237
TT
8103 struct remote_state *rs = get_remote_state ();
8104
8105 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8106 {
1927e618
PA
8107 unpush_and_perror (_("Remote communication error. "
8108 "Target disconnected."));
c33e31fd
PA
8109 }
8110}
8111
6d820c5c
DJ
8112/* Send the command in *BUF to the remote machine, and read the reply
8113 into *BUF. Report an error if we get an error reply. Resize
8114 *BUF using xrealloc if necessary to hold the result, and update
8115 *SIZEOF_BUF. */
c906108c
SS
8116
8117static void
6d820c5c
DJ
8118remote_send (char **buf,
8119 long *sizeof_buf)
c906108c 8120{
6d820c5c 8121 putpkt (*buf);
c2d11a7d 8122 getpkt (buf, sizeof_buf, 0);
c906108c 8123
6d820c5c
DJ
8124 if ((*buf)[0] == 'E')
8125 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8126}
8127
6e5abd65
PA
8128/* Return a pointer to an xmalloc'ed string representing an escaped
8129 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8130 etc. The caller is responsible for releasing the returned
8131 memory. */
8132
8133static char *
8134escape_buffer (const char *buf, int n)
8135{
8136 struct cleanup *old_chain;
8137 struct ui_file *stb;
8138 char *str;
6e5abd65
PA
8139
8140 stb = mem_fileopen ();
8141 old_chain = make_cleanup_ui_file_delete (stb);
8142
6ef284bd 8143 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 8144 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
8145 do_cleanups (old_chain);
8146 return str;
8147}
8148
c906108c
SS
8149/* Display a null-terminated packet on stdout, for debugging, using C
8150 string notation. */
8151
8152static void
baa336ce 8153print_packet (const char *buf)
c906108c
SS
8154{
8155 puts_filtered ("\"");
43e526b9 8156 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8157 puts_filtered ("\"");
8158}
8159
8160int
baa336ce 8161putpkt (const char *buf)
c906108c
SS
8162{
8163 return putpkt_binary (buf, strlen (buf));
8164}
8165
8166/* Send a packet to the remote machine, with error checking. The data
23860348 8167 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8168 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8169 and for a possible /0 if we are debugging (remote_debug) and want
8170 to print the sent packet as a string. */
c906108c
SS
8171
8172static int
baa336ce 8173putpkt_binary (const char *buf, int cnt)
c906108c 8174{
2d717e4f 8175 struct remote_state *rs = get_remote_state ();
c906108c
SS
8176 int i;
8177 unsigned char csum = 0;
224c3ddb 8178 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8179 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8180
c906108c
SS
8181 int ch;
8182 int tcount = 0;
8183 char *p;
dd61ec5c 8184 char *message;
c906108c 8185
e24a49d8
PA
8186 /* Catch cases like trying to read memory or listing threads while
8187 we're waiting for a stop reply. The remote server wouldn't be
8188 ready to handle this request, so we'd hang and timeout. We don't
8189 have to worry about this in synchronous mode, because in that
8190 case it's not possible to issue a command while the target is
74531fed
PA
8191 running. This is not a problem in non-stop mode, because in that
8192 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8193 if (!target_is_non_stop_p ()
8194 && target_is_async_p ()
8195 && rs->waiting_for_stop_reply)
9597b22a
DE
8196 {
8197 error (_("Cannot execute this command while the target is running.\n"
8198 "Use the \"interrupt\" command to stop the target\n"
8199 "and then try again."));
8200 }
e24a49d8 8201
2d717e4f
DJ
8202 /* We're sending out a new packet. Make sure we don't look at a
8203 stale cached response. */
8204 rs->cached_wait_status = 0;
8205
c906108c
SS
8206 /* Copy the packet into buffer BUF2, encapsulating it
8207 and giving it a checksum. */
8208
c906108c
SS
8209 p = buf2;
8210 *p++ = '$';
8211
8212 for (i = 0; i < cnt; i++)
8213 {
8214 csum += buf[i];
8215 *p++ = buf[i];
8216 }
8217 *p++ = '#';
8218 *p++ = tohex ((csum >> 4) & 0xf);
8219 *p++ = tohex (csum & 0xf);
8220
8221 /* Send it over and over until we get a positive ack. */
8222
8223 while (1)
8224 {
8225 int started_error_output = 0;
8226
8227 if (remote_debug)
8228 {
6e5abd65
PA
8229 struct cleanup *old_chain;
8230 char *str;
8231
c906108c 8232 *p = '\0';
6e5abd65
PA
8233 str = escape_buffer (buf2, p - buf2);
8234 old_chain = make_cleanup (xfree, str);
8235 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8236 gdb_flush (gdb_stdlog);
6e5abd65 8237 do_cleanups (old_chain);
c906108c 8238 }
c33e31fd 8239 remote_serial_write (buf2, p - buf2);
c906108c 8240
a6f3e723
SL
8241 /* If this is a no acks version of the remote protocol, send the
8242 packet and move on. */
8243 if (rs->noack_mode)
8244 break;
8245
74531fed
PA
8246 /* Read until either a timeout occurs (-2) or '+' is read.
8247 Handle any notification that arrives in the mean time. */
c906108c
SS
8248 while (1)
8249 {
8250 ch = readchar (remote_timeout);
8251
c5aa993b 8252 if (remote_debug)
c906108c
SS
8253 {
8254 switch (ch)
8255 {
8256 case '+':
1216fa2c 8257 case '-':
c906108c
SS
8258 case SERIAL_TIMEOUT:
8259 case '$':
74531fed 8260 case '%':
c906108c
SS
8261 if (started_error_output)
8262 {
8263 putchar_unfiltered ('\n');
8264 started_error_output = 0;
8265 }
8266 }
8267 }
8268
8269 switch (ch)
8270 {
8271 case '+':
8272 if (remote_debug)
0f71a2f6 8273 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8274 do_cleanups (old_chain);
c906108c 8275 return 1;
1216fa2c
AC
8276 case '-':
8277 if (remote_debug)
8278 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8279 /* FALLTHROUGH */
c906108c 8280 case SERIAL_TIMEOUT:
c5aa993b 8281 tcount++;
c906108c 8282 if (tcount > 3)
a5c0808e
PA
8283 {
8284 do_cleanups (old_chain);
8285 return 0;
8286 }
23860348 8287 break; /* Retransmit buffer. */
c906108c
SS
8288 case '$':
8289 {
40e3f985 8290 if (remote_debug)
2bc416ba 8291 fprintf_unfiltered (gdb_stdlog,
23860348 8292 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8293 /* It's probably an old response sent because an ACK
8294 was lost. Gobble up the packet and ack it so it
8295 doesn't get retransmitted when we resend this
8296 packet. */
6d820c5c 8297 skip_frame ();
c33e31fd 8298 remote_serial_write ("+", 1);
23860348 8299 continue; /* Now, go look for +. */
c906108c 8300 }
74531fed
PA
8301
8302 case '%':
8303 {
8304 int val;
8305
8306 /* If we got a notification, handle it, and go back to looking
8307 for an ack. */
8308 /* We've found the start of a notification. Now
8309 collect the data. */
8310 val = read_frame (&rs->buf, &rs->buf_size);
8311 if (val >= 0)
8312 {
8313 if (remote_debug)
8314 {
6e5abd65
PA
8315 struct cleanup *old_chain;
8316 char *str;
8317
8318 str = escape_buffer (rs->buf, val);
8319 old_chain = make_cleanup (xfree, str);
8320 fprintf_unfiltered (gdb_stdlog,
8321 " Notification received: %s\n",
8322 str);
8323 do_cleanups (old_chain);
74531fed 8324 }
5965e028 8325 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8326 /* We're in sync now, rewait for the ack. */
8327 tcount = 0;
8328 }
8329 else
8330 {
8331 if (remote_debug)
8332 {
8333 if (!started_error_output)
8334 {
8335 started_error_output = 1;
8336 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8337 }
8338 fputc_unfiltered (ch & 0177, gdb_stdlog);
8339 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8340 }
8341 }
8342 continue;
8343 }
8344 /* fall-through */
c906108c
SS
8345 default:
8346 if (remote_debug)
8347 {
8348 if (!started_error_output)
8349 {
8350 started_error_output = 1;
0f71a2f6 8351 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8352 }
0f71a2f6 8353 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8354 }
8355 continue;
8356 }
23860348 8357 break; /* Here to retransmit. */
c906108c
SS
8358 }
8359
8360#if 0
8361 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8362 able to get out next time we call QUIT, without anything as
8363 violent as interrupt_query. If we want to provide a way out of
8364 here without getting to the next QUIT, it should be based on
8365 hitting ^C twice as in remote_wait. */
c906108c
SS
8366 if (quit_flag)
8367 {
8368 quit_flag = 0;
8369 interrupt_query ();
8370 }
8371#endif
8372 }
a5c0808e
PA
8373
8374 do_cleanups (old_chain);
a6f3e723 8375 return 0;
c906108c
SS
8376}
8377
6d820c5c
DJ
8378/* Come here after finding the start of a frame when we expected an
8379 ack. Do our best to discard the rest of this packet. */
8380
8381static void
8382skip_frame (void)
8383{
8384 int c;
8385
8386 while (1)
8387 {
8388 c = readchar (remote_timeout);
8389 switch (c)
8390 {
8391 case SERIAL_TIMEOUT:
8392 /* Nothing we can do. */
8393 return;
8394 case '#':
8395 /* Discard the two bytes of checksum and stop. */
8396 c = readchar (remote_timeout);
8397 if (c >= 0)
8398 c = readchar (remote_timeout);
8399
8400 return;
8401 case '*': /* Run length encoding. */
8402 /* Discard the repeat count. */
8403 c = readchar (remote_timeout);
8404 if (c < 0)
8405 return;
8406 break;
8407 default:
8408 /* A regular character. */
8409 break;
8410 }
8411 }
8412}
8413
c906108c 8414/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8415 into *BUF, verifying the checksum, length, and handling run-length
8416 compression. NUL terminate the buffer. If there is not enough room,
8417 expand *BUF using xrealloc.
c906108c 8418
c2d11a7d
JM
8419 Returns -1 on error, number of characters in buffer (ignoring the
8420 trailing NULL) on success. (could be extended to return one of the
23860348 8421 SERIAL status indications). */
c2d11a7d
JM
8422
8423static long
6d820c5c
DJ
8424read_frame (char **buf_p,
8425 long *sizeof_buf)
c906108c
SS
8426{
8427 unsigned char csum;
c2d11a7d 8428 long bc;
c906108c 8429 int c;
6d820c5c 8430 char *buf = *buf_p;
a6f3e723 8431 struct remote_state *rs = get_remote_state ();
c906108c
SS
8432
8433 csum = 0;
c2d11a7d 8434 bc = 0;
c906108c
SS
8435
8436 while (1)
8437 {
8438 c = readchar (remote_timeout);
c906108c
SS
8439 switch (c)
8440 {
8441 case SERIAL_TIMEOUT:
8442 if (remote_debug)
0f71a2f6 8443 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8444 return -1;
c906108c
SS
8445 case '$':
8446 if (remote_debug)
0f71a2f6
JM
8447 fputs_filtered ("Saw new packet start in middle of old one\n",
8448 gdb_stdlog);
23860348 8449 return -1; /* Start a new packet, count retries. */
c906108c
SS
8450 case '#':
8451 {
8452 unsigned char pktcsum;
e1b09194
AC
8453 int check_0 = 0;
8454 int check_1 = 0;
c906108c 8455
c2d11a7d 8456 buf[bc] = '\0';
c906108c 8457
e1b09194
AC
8458 check_0 = readchar (remote_timeout);
8459 if (check_0 >= 0)
8460 check_1 = readchar (remote_timeout);
802188a7 8461
e1b09194
AC
8462 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8463 {
8464 if (remote_debug)
2bc416ba 8465 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8466 gdb_stdlog);
e1b09194
AC
8467 return -1;
8468 }
8469 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8470 {
8471 if (remote_debug)
2bc416ba 8472 fputs_filtered ("Communication error in checksum\n",
23860348 8473 gdb_stdlog);
40e3f985
FN
8474 return -1;
8475 }
c906108c 8476
a6f3e723
SL
8477 /* Don't recompute the checksum; with no ack packets we
8478 don't have any way to indicate a packet retransmission
8479 is necessary. */
8480 if (rs->noack_mode)
8481 return bc;
8482
e1b09194 8483 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8484 if (csum == pktcsum)
c2d11a7d 8485 return bc;
c906108c 8486
c5aa993b 8487 if (remote_debug)
c906108c 8488 {
6e5abd65
PA
8489 struct cleanup *old_chain;
8490 char *str;
8491
8492 str = escape_buffer (buf, bc);
8493 old_chain = make_cleanup (xfree, str);
8494 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8495 "Bad checksum, sentsum=0x%x, "
8496 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8497 pktcsum, csum, str);
8498 do_cleanups (old_chain);
c906108c 8499 }
c2d11a7d 8500 /* Number of characters in buffer ignoring trailing
23860348 8501 NULL. */
c2d11a7d 8502 return -1;
c906108c 8503 }
23860348 8504 case '*': /* Run length encoding. */
c2c6d25f
JM
8505 {
8506 int repeat;
c906108c 8507
a744cf53 8508 csum += c;
b4501125
AC
8509 c = readchar (remote_timeout);
8510 csum += c;
23860348 8511 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8512
23860348 8513 /* The character before ``*'' is repeated. */
c2d11a7d 8514
6d820c5c 8515 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8516 {
6d820c5c
DJ
8517 if (bc + repeat - 1 >= *sizeof_buf - 1)
8518 {
8519 /* Make some more room in the buffer. */
8520 *sizeof_buf += repeat;
224c3ddb 8521 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
8522 buf = *buf_p;
8523 }
8524
c2d11a7d
JM
8525 memset (&buf[bc], buf[bc - 1], repeat);
8526 bc += repeat;
c2c6d25f
JM
8527 continue;
8528 }
8529
c2d11a7d 8530 buf[bc] = '\0';
6d820c5c 8531 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8532 return -1;
c2c6d25f 8533 }
c906108c 8534 default:
6d820c5c 8535 if (bc >= *sizeof_buf - 1)
c906108c 8536 {
6d820c5c
DJ
8537 /* Make some more room in the buffer. */
8538 *sizeof_buf *= 2;
224c3ddb 8539 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 8540 buf = *buf_p;
c906108c
SS
8541 }
8542
6d820c5c
DJ
8543 buf[bc++] = c;
8544 csum += c;
8545 continue;
c906108c
SS
8546 }
8547 }
8548}
8549
8550/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8551 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8552 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8553 rather than timing out; this is used (in synchronous mode) to wait
8554 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8555/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8556 don't have to change all the calls to getpkt to deal with the
8557 return value, because at the moment I don't know what the right
23860348 8558 thing to do it for those. */
c906108c 8559void
6d820c5c
DJ
8560getpkt (char **buf,
8561 long *sizeof_buf,
c2d11a7d 8562 int forever)
d9fcf2fb
JM
8563{
8564 int timed_out;
8565
8566 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8567}
8568
8569
8570/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8571 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8572 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8573 rather than timing out; this is used (in synchronous mode) to wait
8574 for a target that is is executing user code to stop. If FOREVER ==
8575 0, this function is allowed to time out gracefully and return an
74531fed
PA
8576 indication of this to the caller. Otherwise return the number of
8577 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8578 enough reason to return to the caller. *IS_NOTIF is an output
8579 boolean that indicates whether *BUF holds a notification or not
8580 (a regular packet). */
74531fed 8581
3172dc30 8582static int
74531fed 8583getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8584 int expecting_notif, int *is_notif)
c906108c 8585{
2d717e4f 8586 struct remote_state *rs = get_remote_state ();
c906108c
SS
8587 int c;
8588 int tries;
8589 int timeout;
df4b58fe 8590 int val = -1;
c906108c 8591
2d717e4f
DJ
8592 /* We're reading a new response. Make sure we don't look at a
8593 previously cached response. */
8594 rs->cached_wait_status = 0;
8595
6d820c5c 8596 strcpy (*buf, "timeout");
c906108c
SS
8597
8598 if (forever)
74531fed
PA
8599 timeout = watchdog > 0 ? watchdog : -1;
8600 else if (expecting_notif)
8601 timeout = 0; /* There should already be a char in the buffer. If
8602 not, bail out. */
c906108c
SS
8603 else
8604 timeout = remote_timeout;
8605
8606#define MAX_TRIES 3
8607
74531fed
PA
8608 /* Process any number of notifications, and then return when
8609 we get a packet. */
8610 for (;;)
c906108c 8611 {
d9c43928 8612 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8613 times. */
8614 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8615 {
74531fed
PA
8616 /* This can loop forever if the remote side sends us
8617 characters continuously, but if it pauses, we'll get
8618 SERIAL_TIMEOUT from readchar because of timeout. Then
8619 we'll count that as a retry.
8620
8621 Note that even when forever is set, we will only wait
8622 forever prior to the start of a packet. After that, we
8623 expect characters to arrive at a brisk pace. They should
8624 show up within remote_timeout intervals. */
8625 do
8626 c = readchar (timeout);
8627 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8628
8629 if (c == SERIAL_TIMEOUT)
8630 {
74531fed
PA
8631 if (expecting_notif)
8632 return -1; /* Don't complain, it's normal to not get
8633 anything in this case. */
8634
23860348 8635 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8636 {
2acceee2 8637 QUIT;
78a095c3 8638 remote_unpush_target ();
598d3636
JK
8639 throw_error (TARGET_CLOSE_ERROR,
8640 _("Watchdog timeout has expired. "
8641 "Target detached."));
c906108c 8642 }
c906108c 8643 if (remote_debug)
0f71a2f6 8644 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8645 }
74531fed
PA
8646 else
8647 {
8648 /* We've found the start of a packet or notification.
8649 Now collect the data. */
8650 val = read_frame (buf, sizeof_buf);
8651 if (val >= 0)
8652 break;
8653 }
8654
c33e31fd 8655 remote_serial_write ("-", 1);
c906108c 8656 }
c906108c 8657
74531fed
PA
8658 if (tries > MAX_TRIES)
8659 {
8660 /* We have tried hard enough, and just can't receive the
8661 packet/notification. Give up. */
8662 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8663
74531fed
PA
8664 /* Skip the ack char if we're in no-ack mode. */
8665 if (!rs->noack_mode)
c33e31fd 8666 remote_serial_write ("+", 1);
74531fed
PA
8667 return -1;
8668 }
c906108c 8669
74531fed
PA
8670 /* If we got an ordinary packet, return that to our caller. */
8671 if (c == '$')
c906108c
SS
8672 {
8673 if (remote_debug)
43e526b9 8674 {
6e5abd65
PA
8675 struct cleanup *old_chain;
8676 char *str;
8677
8678 str = escape_buffer (*buf, val);
8679 old_chain = make_cleanup (xfree, str);
8680 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8681 do_cleanups (old_chain);
43e526b9 8682 }
a6f3e723
SL
8683
8684 /* Skip the ack char if we're in no-ack mode. */
8685 if (!rs->noack_mode)
c33e31fd 8686 remote_serial_write ("+", 1);
fee9eda9
YQ
8687 if (is_notif != NULL)
8688 *is_notif = 0;
0876f84a 8689 return val;
c906108c
SS
8690 }
8691
74531fed
PA
8692 /* If we got a notification, handle it, and go back to looking
8693 for a packet. */
8694 else
8695 {
8696 gdb_assert (c == '%');
8697
8698 if (remote_debug)
8699 {
6e5abd65
PA
8700 struct cleanup *old_chain;
8701 char *str;
8702
8703 str = escape_buffer (*buf, val);
8704 old_chain = make_cleanup (xfree, str);
8705 fprintf_unfiltered (gdb_stdlog,
8706 " Notification received: %s\n",
8707 str);
8708 do_cleanups (old_chain);
74531fed 8709 }
fee9eda9
YQ
8710 if (is_notif != NULL)
8711 *is_notif = 1;
c906108c 8712
5965e028 8713 handle_notification (rs->notif_state, *buf);
c906108c 8714
74531fed 8715 /* Notifications require no acknowledgement. */
a6f3e723 8716
74531fed 8717 if (expecting_notif)
fee9eda9 8718 return val;
74531fed
PA
8719 }
8720 }
8721}
8722
8723static int
8724getpkt_sane (char **buf, long *sizeof_buf, int forever)
8725{
fee9eda9 8726 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8727}
8728
8729static int
fee9eda9
YQ
8730getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8731 int *is_notif)
74531fed 8732{
fee9eda9
YQ
8733 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8734 is_notif);
c906108c 8735}
74531fed 8736
cbb8991c
DB
8737/* Check whether EVENT is a fork event for the process specified
8738 by the pid passed in DATA, and if it is, kill the fork child. */
8739
8740static int
8741kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8742 QUEUE_ITER (stop_reply_p) *iter,
8743 stop_reply_p event,
8744 void *data)
8745{
19ba03f4 8746 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
8747 int parent_pid = *(int *) param->input;
8748
8749 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8750 {
8751 struct remote_state *rs = get_remote_state ();
8752 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8753 int res;
8754
8755 res = remote_vkill (child_pid, rs);
8756 if (res != 0)
8757 error (_("Can't kill fork child process %d"), child_pid);
8758 }
8759
8760 return 1;
8761}
8762
8763/* Kill any new fork children of process PID that haven't been
8764 processed by follow_fork. */
8765
8766static void
8767kill_new_fork_children (int pid, struct remote_state *rs)
8768{
8769 struct thread_info *thread;
8770 struct notif_client *notif = &notif_client_stop;
8771 struct queue_iter_param param;
8772
8773 /* Kill the fork child threads of any threads in process PID
8774 that are stopped at a fork event. */
8775 ALL_NON_EXITED_THREADS (thread)
8776 {
8777 struct target_waitstatus *ws = &thread->pending_follow;
8778
8779 if (is_pending_fork_parent (ws, pid, thread->ptid))
8780 {
8781 struct remote_state *rs = get_remote_state ();
8782 int child_pid = ptid_get_pid (ws->value.related_pid);
8783 int res;
8784
8785 res = remote_vkill (child_pid, rs);
8786 if (res != 0)
8787 error (_("Can't kill fork child process %d"), child_pid);
8788 }
8789 }
8790
8791 /* Check for any pending fork events (not reported or processed yet)
8792 in process PID and kill those fork child threads as well. */
8793 remote_notif_get_pending_events (notif);
8794 param.input = &pid;
8795 param.output = NULL;
8796 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8797 kill_child_of_pending_fork, &param);
8798}
8799
c906108c
SS
8800\f
8801static void
7d85a9c0 8802remote_kill (struct target_ops *ops)
43ff13b4 8803{
0fdf84ca
PA
8804
8805 /* Catch errors so the user can quit from gdb even when we
23860348 8806 aren't on speaking terms with the remote system. */
492d29ea 8807 TRY
0fdf84ca
PA
8808 {
8809 putpkt ("k");
8810 }
492d29ea 8811 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
8812 {
8813 if (ex.error == TARGET_CLOSE_ERROR)
8814 {
8815 /* If we got an (EOF) error that caused the target
8816 to go away, then we're done, that's what we wanted.
8817 "k" is susceptible to cause a premature EOF, given
8818 that the remote server isn't actually required to
8819 reply to "k", and it can happen that it doesn't
8820 even get to reply ACK to the "k". */
8821 return;
8822 }
8823
8824 /* Otherwise, something went wrong. We didn't actually kill
8825 the target. Just propagate the exception, and let the
8826 user or higher layers decide what to do. */
8827 throw_exception (ex);
8828 }
492d29ea 8829 END_CATCH
43ff13b4 8830
0fdf84ca
PA
8831 /* We've killed the remote end, we get to mourn it. Since this is
8832 target remote, single-process, mourning the inferior also
8833 unpushes remote_ops. */
43ff13b4
JM
8834 target_mourn_inferior ();
8835}
8836
82f73884
PA
8837static int
8838remote_vkill (int pid, struct remote_state *rs)
8839{
4082afcc 8840 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8841 return -1;
8842
8843 /* Tell the remote target to detach. */
bba74b36 8844 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8845 putpkt (rs->buf);
8846 getpkt (&rs->buf, &rs->buf_size, 0);
8847
4082afcc
PA
8848 switch (packet_ok (rs->buf,
8849 &remote_protocol_packets[PACKET_vKill]))
8850 {
8851 case PACKET_OK:
8852 return 0;
8853 case PACKET_ERROR:
8854 return 1;
8855 case PACKET_UNKNOWN:
8856 return -1;
8857 default:
8858 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8859 }
82f73884
PA
8860}
8861
8862static void
7d85a9c0 8863extended_remote_kill (struct target_ops *ops)
82f73884
PA
8864{
8865 int res;
8866 int pid = ptid_get_pid (inferior_ptid);
8867 struct remote_state *rs = get_remote_state ();
8868
cbb8991c
DB
8869 /* If we're stopped while forking and we haven't followed yet, kill the
8870 child task. We need to do this before killing the parent task
8871 because if this is a vfork then the parent will be sleeping. */
8872 kill_new_fork_children (pid, rs);
8873
82f73884 8874 res = remote_vkill (pid, rs);
901f9912 8875 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
8876 {
8877 /* Don't try 'k' on a multi-process aware stub -- it has no way
8878 to specify the pid. */
8879
8880 putpkt ("k");
8881#if 0
8882 getpkt (&rs->buf, &rs->buf_size, 0);
8883 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8884 res = 1;
8885#else
8886 /* Don't wait for it to die. I'm not really sure it matters whether
8887 we do or not. For the existing stubs, kill is a noop. */
8888 res = 0;
8889#endif
8890 }
8891
8892 if (res != 0)
8893 error (_("Can't kill process"));
8894
82f73884
PA
8895 target_mourn_inferior ();
8896}
8897
c906108c 8898static void
20f796c9 8899remote_mourn (struct target_ops *target)
c906108c
SS
8900{
8901 unpush_target (target);
ce5ce7ed 8902
8a2492ee
PA
8903 /* remote_close takes care of doing most of the clean up. */
8904 generic_mourn_inferior ();
c906108c
SS
8905}
8906
2d717e4f 8907static void
20f796c9 8908extended_remote_mourn (struct target_ops *target)
2d717e4f
DJ
8909{
8910 struct remote_state *rs = get_remote_state ();
c906108c 8911
e24a49d8
PA
8912 /* In case we got here due to an error, but we're going to stay
8913 connected. */
8914 rs->waiting_for_stop_reply = 0;
8915
dc1981d7
PA
8916 /* If the current general thread belonged to the process we just
8917 detached from or has exited, the remote side current general
8918 thread becomes undefined. Considering a case like this:
8919
8920 - We just got here due to a detach.
8921 - The process that we're detaching from happens to immediately
8922 report a global breakpoint being hit in non-stop mode, in the
8923 same thread we had selected before.
8924 - GDB attaches to this process again.
8925 - This event happens to be the next event we handle.
8926
8927 GDB would consider that the current general thread didn't need to
8928 be set on the stub side (with Hg), since for all it knew,
8929 GENERAL_THREAD hadn't changed.
8930
8931 Notice that although in all-stop mode, the remote server always
8932 sets the current thread to the thread reporting the stop event,
8933 that doesn't happen in non-stop mode; in non-stop, the stub *must
8934 not* change the current thread when reporting a breakpoint hit,
8935 due to the decoupling of event reporting and event handling.
8936
8937 To keep things simple, we always invalidate our notion of the
8938 current thread. */
47f8a51d 8939 record_currthread (rs, minus_one_ptid);
dc1981d7 8940
2d717e4f
DJ
8941 /* Unlike "target remote", we do not want to unpush the target; then
8942 the next time the user says "run", we won't be connected. */
8943
48aa3c27
PA
8944 /* Call common code to mark the inferior as not running. */
8945 generic_mourn_inferior ();
8946
d729566a 8947 if (!have_inferiors ())
2d717e4f 8948 {
82f73884
PA
8949 if (!remote_multi_process_p (rs))
8950 {
8951 /* Check whether the target is running now - some remote stubs
8952 automatically restart after kill. */
8953 putpkt ("?");
8954 getpkt (&rs->buf, &rs->buf_size, 0);
8955
8956 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8957 {
3e43a32a
MS
8958 /* Assume that the target has been restarted. Set
8959 inferior_ptid so that bits of core GDB realizes
8960 there's something here, e.g., so that the user can
8961 say "kill" again. */
82f73884
PA
8962 inferior_ptid = magic_null_ptid;
8963 }
82f73884 8964 }
2d717e4f
DJ
8965 }
8966}
c906108c 8967
03583c20 8968static int
2bfc0540 8969extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8970{
4082afcc 8971 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8972}
8973
8974static void
8975extended_remote_disable_randomization (int val)
8976{
8977 struct remote_state *rs = get_remote_state ();
8978 char *reply;
8979
bba74b36
YQ
8980 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8981 val);
03583c20
UW
8982 putpkt (rs->buf);
8983 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8984 if (*reply == '\0')
8985 error (_("Target does not support QDisableRandomization."));
8986 if (strcmp (reply, "OK") != 0)
8987 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8988}
8989
2d717e4f
DJ
8990static int
8991extended_remote_run (char *args)
8992{
8993 struct remote_state *rs = get_remote_state ();
2d717e4f 8994 int len;
94585166 8995 const char *remote_exec_file = get_remote_exec_file ();
c906108c 8996
2d717e4f
DJ
8997 /* If the user has disabled vRun support, or we have detected that
8998 support is not available, do not try it. */
4082afcc 8999 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9000 return -1;
424163ea 9001
2d717e4f
DJ
9002 strcpy (rs->buf, "vRun;");
9003 len = strlen (rs->buf);
c906108c 9004
2d717e4f
DJ
9005 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9006 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9007 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9008 strlen (remote_exec_file));
2d717e4f 9009
d1a41061 9010 gdb_assert (args != NULL);
2d717e4f
DJ
9011 if (*args)
9012 {
9013 struct cleanup *back_to;
9014 int i;
9015 char **argv;
9016
d1a41061 9017 argv = gdb_buildargv (args);
6e366df1 9018 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
9019 for (i = 0; argv[i] != NULL; i++)
9020 {
9021 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9022 error (_("Argument list too long for run packet"));
9023 rs->buf[len++] = ';';
9f1b45b0
TT
9024 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9025 strlen (argv[i]));
2d717e4f
DJ
9026 }
9027 do_cleanups (back_to);
9028 }
9029
9030 rs->buf[len++] = '\0';
9031
9032 putpkt (rs->buf);
9033 getpkt (&rs->buf, &rs->buf_size, 0);
9034
4082afcc 9035 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9036 {
4082afcc 9037 case PACKET_OK:
3405876a 9038 /* We have a wait response. All is well. */
2d717e4f 9039 return 0;
4082afcc
PA
9040 case PACKET_UNKNOWN:
9041 return -1;
9042 case PACKET_ERROR:
2d717e4f
DJ
9043 if (remote_exec_file[0] == '\0')
9044 error (_("Running the default executable on the remote target failed; "
9045 "try \"set remote exec-file\"?"));
9046 else
9047 error (_("Running \"%s\" on the remote target failed"),
9048 remote_exec_file);
4082afcc
PA
9049 default:
9050 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9051 }
c906108c
SS
9052}
9053
2d717e4f
DJ
9054/* In the extended protocol we want to be able to do things like
9055 "run" and have them basically work as expected. So we need
9056 a special create_inferior function. We support changing the
9057 executable file and the command line arguments, but not the
9058 environment. */
9059
43ff13b4 9060static void
77a19445
TT
9061extended_remote_create_inferior (struct target_ops *ops,
9062 char *exec_file, char *args,
9063 char **env, int from_tty)
43ff13b4 9064{
3405876a
PA
9065 int run_worked;
9066 char *stop_reply;
9067 struct remote_state *rs = get_remote_state ();
94585166 9068 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9069
43ff13b4 9070 /* If running asynchronously, register the target file descriptor
23860348 9071 with the event loop. */
75c99385 9072 if (target_can_async_p ())
6a3753b3 9073 target_async (1);
43ff13b4 9074
03583c20 9075 /* Disable address space randomization if requested (and supported). */
2bfc0540 9076 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9077 extended_remote_disable_randomization (disable_randomization);
9078
43ff13b4 9079 /* Now restart the remote server. */
3405876a
PA
9080 run_worked = extended_remote_run (args) != -1;
9081 if (!run_worked)
2d717e4f
DJ
9082 {
9083 /* vRun was not supported. Fail if we need it to do what the
9084 user requested. */
9085 if (remote_exec_file[0])
9086 error (_("Remote target does not support \"set remote exec-file\""));
9087 if (args[0])
9088 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9089
2d717e4f
DJ
9090 /* Fall back to "R". */
9091 extended_remote_restart ();
9092 }
424163ea 9093
6c95b8df
PA
9094 if (!have_inferiors ())
9095 {
9096 /* Clean up from the last time we ran, before we mark the target
9097 running again. This will mark breakpoints uninserted, and
9098 get_offsets may insert breakpoints. */
9099 init_thread_list ();
9100 init_wait_for_inferior ();
9101 }
45280a52 9102
3405876a
PA
9103 /* vRun's success return is a stop reply. */
9104 stop_reply = run_worked ? rs->buf : NULL;
9105 add_current_inferior_and_thread (stop_reply);
c0a2216e 9106
2d717e4f
DJ
9107 /* Get updated offsets, if the stub uses qOffsets. */
9108 get_offsets ();
2d717e4f 9109}
c906108c 9110\f
c5aa993b 9111
b775012e
LM
9112/* Given a location's target info BP_TGT and the packet buffer BUF, output
9113 the list of conditions (in agent expression bytecode format), if any, the
9114 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9115 started from BUF and ended at BUF_END. */
b775012e
LM
9116
9117static int
9118remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9119 struct bp_target_info *bp_tgt, char *buf,
9120 char *buf_end)
b775012e
LM
9121{
9122 struct agent_expr *aexpr = NULL;
9123 int i, ix;
9124 char *pkt;
9125 char *buf_start = buf;
9126
9127 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9128 return 0;
9129
9130 buf += strlen (buf);
bba74b36 9131 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9132 buf++;
9133
9134 /* Send conditions to the target and free the vector. */
9135 for (ix = 0;
9136 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9137 ix++)
9138 {
bba74b36 9139 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
9140 buf += strlen (buf);
9141 for (i = 0; i < aexpr->len; ++i)
9142 buf = pack_hex_byte (buf, aexpr->buf[i]);
9143 *buf = '\0';
9144 }
b775012e
LM
9145 return 0;
9146}
9147
d3ce09f5
SS
9148static void
9149remote_add_target_side_commands (struct gdbarch *gdbarch,
9150 struct bp_target_info *bp_tgt, char *buf)
9151{
9152 struct agent_expr *aexpr = NULL;
9153 int i, ix;
9154
9155 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9156 return;
9157
9158 buf += strlen (buf);
9159
9160 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9161 buf += strlen (buf);
9162
9163 /* Concatenate all the agent expressions that are commands into the
9164 cmds parameter. */
9165 for (ix = 0;
9166 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9167 ix++)
9168 {
9169 sprintf (buf, "X%x,", aexpr->len);
9170 buf += strlen (buf);
9171 for (i = 0; i < aexpr->len; ++i)
9172 buf = pack_hex_byte (buf, aexpr->buf[i]);
9173 *buf = '\0';
9174 }
d3ce09f5
SS
9175}
9176
8181d85f
DJ
9177/* Insert a breakpoint. On targets that have software breakpoint
9178 support, we ask the remote target to do the work; on targets
9179 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9180
9181static int
3db08215
MM
9182remote_insert_breakpoint (struct target_ops *ops,
9183 struct gdbarch *gdbarch,
a6d9a66e 9184 struct bp_target_info *bp_tgt)
c906108c 9185{
d471ea57
AC
9186 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9187 If it succeeds, then set the support to PACKET_ENABLE. If it
9188 fails, and the user has explicitly requested the Z support then
23860348 9189 report an error, otherwise, mark it disabled and go on. */
802188a7 9190
4082afcc 9191 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9192 {
0d5ed153 9193 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9194 struct remote_state *rs;
bba74b36 9195 char *p, *endbuf;
7c0f6dcc 9196 int bpsize;
b775012e 9197 struct condition_list *cond = NULL;
4fff2411 9198
28439a30
PA
9199 /* Make sure the remote is pointing at the right process, if
9200 necessary. */
9201 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9202 set_general_process ();
9203
a1dcb23a 9204 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
9205
9206 rs = get_remote_state ();
9207 p = rs->buf;
bba74b36 9208 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9209
96baa820
JM
9210 *(p++) = 'Z';
9211 *(p++) = '0';
9212 *(p++) = ',';
7c0f6dcc 9213 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9214 p += hexnumstr (p, addr);
bba74b36 9215 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 9216
efcc2da7 9217 if (remote_supports_cond_breakpoints (ops))
bba74b36 9218 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9219
78eff0ec 9220 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9221 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9222
6d820c5c
DJ
9223 putpkt (rs->buf);
9224 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9225
6d820c5c 9226 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9227 {
d471ea57
AC
9228 case PACKET_ERROR:
9229 return -1;
9230 case PACKET_OK:
7c0f6dcc
JL
9231 bp_tgt->placed_address = addr;
9232 bp_tgt->placed_size = bpsize;
d471ea57
AC
9233 return 0;
9234 case PACKET_UNKNOWN:
9235 break;
96baa820
JM
9236 }
9237 }
c906108c 9238
0000e5cc
PA
9239 /* If this breakpoint has target-side commands but this stub doesn't
9240 support Z0 packets, throw error. */
9241 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9242 throw_error (NOT_SUPPORTED_ERROR, _("\
9243Target doesn't support breakpoints that have target side commands."));
9244
3db08215 9245 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9246}
9247
9248static int
3db08215
MM
9249remote_remove_breakpoint (struct target_ops *ops,
9250 struct gdbarch *gdbarch,
a6d9a66e 9251 struct bp_target_info *bp_tgt)
c906108c 9252{
8181d85f 9253 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9254 struct remote_state *rs = get_remote_state ();
96baa820 9255
4082afcc 9256 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9257 {
6d820c5c 9258 char *p = rs->buf;
bba74b36 9259 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9260
28439a30
PA
9261 /* Make sure the remote is pointing at the right process, if
9262 necessary. */
9263 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9264 set_general_process ();
9265
96baa820
JM
9266 *(p++) = 'z';
9267 *(p++) = '0';
9268 *(p++) = ',';
9269
8181d85f
DJ
9270 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9271 p += hexnumstr (p, addr);
bba74b36 9272 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9273
6d820c5c
DJ
9274 putpkt (rs->buf);
9275 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9276
6d820c5c 9277 return (rs->buf[0] == 'E');
96baa820
JM
9278 }
9279
3db08215 9280 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9281}
9282
f486487f 9283static enum Z_packet_type
d471ea57
AC
9284watchpoint_to_Z_packet (int type)
9285{
9286 switch (type)
9287 {
9288 case hw_write:
bb858e6a 9289 return Z_PACKET_WRITE_WP;
d471ea57
AC
9290 break;
9291 case hw_read:
bb858e6a 9292 return Z_PACKET_READ_WP;
d471ea57
AC
9293 break;
9294 case hw_access:
bb858e6a 9295 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9296 break;
9297 default:
8e65ff28 9298 internal_error (__FILE__, __LINE__,
e2e0b3e5 9299 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9300 }
9301}
9302
3c3bea1c 9303static int
f486487f
SM
9304remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9305 enum target_hw_bp_type type, struct expression *cond)
96baa820 9306{
d01949b6 9307 struct remote_state *rs = get_remote_state ();
bba74b36 9308 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9309 char *p;
d471ea57 9310 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9311
4082afcc 9312 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9313 return 1;
802188a7 9314
28439a30
PA
9315 /* Make sure the remote is pointing at the right process, if
9316 necessary. */
9317 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9318 set_general_process ();
9319
bba74b36 9320 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9321 p = strchr (rs->buf, '\0');
96baa820
JM
9322 addr = remote_address_masked (addr);
9323 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9324 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9325
6d820c5c
DJ
9326 putpkt (rs->buf);
9327 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9328
6d820c5c 9329 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9330 {
9331 case PACKET_ERROR:
d471ea57 9332 return -1;
85d721b8
PA
9333 case PACKET_UNKNOWN:
9334 return 1;
d471ea57
AC
9335 case PACKET_OK:
9336 return 0;
9337 }
8e65ff28 9338 internal_error (__FILE__, __LINE__,
e2e0b3e5 9339 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9340}
9341
283002cf
MR
9342static int
9343remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9344 CORE_ADDR start, int length)
9345{
9346 CORE_ADDR diff = remote_address_masked (addr - start);
9347
9348 return diff < length;
9349}
9350
d471ea57 9351
3c3bea1c 9352static int
f486487f
SM
9353remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9354 enum target_hw_bp_type type, struct expression *cond)
96baa820 9355{
d01949b6 9356 struct remote_state *rs = get_remote_state ();
bba74b36 9357 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9358 char *p;
d471ea57
AC
9359 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9360
4082afcc 9361 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9362 return -1;
802188a7 9363
28439a30
PA
9364 /* Make sure the remote is pointing at the right process, if
9365 necessary. */
9366 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9367 set_general_process ();
9368
bba74b36 9369 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9370 p = strchr (rs->buf, '\0');
96baa820
JM
9371 addr = remote_address_masked (addr);
9372 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9373 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9374 putpkt (rs->buf);
9375 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9376
6d820c5c 9377 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9378 {
9379 case PACKET_ERROR:
9380 case PACKET_UNKNOWN:
9381 return -1;
9382 case PACKET_OK:
9383 return 0;
9384 }
8e65ff28 9385 internal_error (__FILE__, __LINE__,
e2e0b3e5 9386 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9387}
9388
3c3bea1c 9389
501eef12 9390int remote_hw_watchpoint_limit = -1;
480a3f21 9391int remote_hw_watchpoint_length_limit = -1;
501eef12 9392int remote_hw_breakpoint_limit = -1;
d471ea57 9393
480a3f21 9394static int
31568a15
TT
9395remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9396 CORE_ADDR addr, int len)
480a3f21
PW
9397{
9398 if (remote_hw_watchpoint_length_limit == 0)
9399 return 0;
9400 else if (remote_hw_watchpoint_length_limit < 0)
9401 return 1;
9402 else if (len <= remote_hw_watchpoint_length_limit)
9403 return 1;
9404 else
9405 return 0;
9406}
9407
b9362cc7 9408static int
5461485a 9409remote_check_watch_resources (struct target_ops *self,
f486487f 9410 enum bptype type, int cnt, int ot)
96baa820 9411{
3c3bea1c
GS
9412 if (type == bp_hardware_breakpoint)
9413 {
9414 if (remote_hw_breakpoint_limit == 0)
9415 return 0;
501eef12
AC
9416 else if (remote_hw_breakpoint_limit < 0)
9417 return 1;
3c3bea1c
GS
9418 else if (cnt <= remote_hw_breakpoint_limit)
9419 return 1;
9420 }
9421 else
9422 {
9423 if (remote_hw_watchpoint_limit == 0)
9424 return 0;
501eef12
AC
9425 else if (remote_hw_watchpoint_limit < 0)
9426 return 1;
3c3bea1c
GS
9427 else if (ot)
9428 return -1;
9429 else if (cnt <= remote_hw_watchpoint_limit)
9430 return 1;
9431 }
9432 return -1;
9433}
9434
f7e6eed5
PA
9435/* The to_stopped_by_sw_breakpoint method of target remote. */
9436
9437static int
9438remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9439{
799a2abe 9440 struct thread_info *thread = inferior_thread ();
f7e6eed5 9441
799a2abe
PA
9442 return (thread->priv != NULL
9443 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9444}
9445
9446/* The to_supports_stopped_by_sw_breakpoint method of target
9447 remote. */
9448
9449static int
9450remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9451{
9452 struct remote_state *rs = get_remote_state ();
9453
9454 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9455}
9456
9457/* The to_stopped_by_hw_breakpoint method of target remote. */
9458
9459static int
9460remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9461{
799a2abe 9462 struct thread_info *thread = inferior_thread ();
f7e6eed5 9463
799a2abe
PA
9464 return (thread->priv != NULL
9465 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9466}
9467
9468/* The to_supports_stopped_by_hw_breakpoint method of target
9469 remote. */
9470
9471static int
9472remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9473{
9474 struct remote_state *rs = get_remote_state ();
9475
9476 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9477}
9478
b9362cc7 9479static int
6a109b6b 9480remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9481{
799a2abe 9482 struct thread_info *thread = inferior_thread ();
ee154bee 9483
799a2abe
PA
9484 return (thread->priv != NULL
9485 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9486}
9487
4aa7a7f5
JJ
9488static int
9489remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9490{
799a2abe 9491 struct thread_info *thread = inferior_thread ();
a744cf53 9492
799a2abe
PA
9493 if (thread->priv != NULL
9494 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9495 {
799a2abe
PA
9496 *addr_p = thread->priv->watch_data_address;
9497 return 1;
4aa7a7f5
JJ
9498 }
9499
799a2abe 9500 return 0;
3c3bea1c
GS
9501}
9502
9503
9504static int
23a26771 9505remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9506 struct bp_target_info *bp_tgt)
3c3bea1c 9507{
0d5ed153 9508 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9509 struct remote_state *rs;
bba74b36 9510 char *p, *endbuf;
dd61ec5c 9511 char *message;
0d5ed153 9512 int bpsize;
802188a7 9513
c8189ed1 9514 /* The length field should be set to the size of a breakpoint
8181d85f 9515 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9516
0d5ed153 9517 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9518
4082afcc 9519 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9520 return -1;
2bc416ba 9521
28439a30
PA
9522 /* Make sure the remote is pointing at the right process, if
9523 necessary. */
9524 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9525 set_general_process ();
9526
4fff2411
JZ
9527 rs = get_remote_state ();
9528 p = rs->buf;
bba74b36 9529 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9530
96baa820
JM
9531 *(p++) = 'Z';
9532 *(p++) = '1';
9533 *(p++) = ',';
802188a7 9534
0d5ed153 9535 addr = remote_address_masked (addr);
96baa820 9536 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9537 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9538
efcc2da7 9539 if (remote_supports_cond_breakpoints (self))
bba74b36 9540 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9541
78eff0ec 9542 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9543 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9544
6d820c5c
DJ
9545 putpkt (rs->buf);
9546 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9547
6d820c5c 9548 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9549 {
9550 case PACKET_ERROR:
dd61ec5c
MW
9551 if (rs->buf[1] == '.')
9552 {
9553 message = strchr (rs->buf + 2, '.');
9554 if (message)
0316657e 9555 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9556 }
9557 return -1;
d471ea57
AC
9558 case PACKET_UNKNOWN:
9559 return -1;
9560 case PACKET_OK:
0d5ed153
MR
9561 bp_tgt->placed_address = addr;
9562 bp_tgt->placed_size = bpsize;
d471ea57
AC
9563 return 0;
9564 }
8e65ff28 9565 internal_error (__FILE__, __LINE__,
e2e0b3e5 9566 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9567}
9568
d471ea57 9569
802188a7 9570static int
a64dc96c 9571remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9572 struct bp_target_info *bp_tgt)
96baa820 9573{
8181d85f 9574 CORE_ADDR addr;
d01949b6 9575 struct remote_state *rs = get_remote_state ();
6d820c5c 9576 char *p = rs->buf;
bba74b36 9577 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9578
4082afcc 9579 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9580 return -1;
802188a7 9581
28439a30
PA
9582 /* Make sure the remote is pointing at the right process, if
9583 necessary. */
9584 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9585 set_general_process ();
9586
96baa820
JM
9587 *(p++) = 'z';
9588 *(p++) = '1';
9589 *(p++) = ',';
802188a7 9590
8181d85f 9591 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9592 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9593 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9594
6d820c5c
DJ
9595 putpkt (rs->buf);
9596 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9597
6d820c5c 9598 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9599 {
9600 case PACKET_ERROR:
9601 case PACKET_UNKNOWN:
9602 return -1;
9603 case PACKET_OK:
9604 return 0;
9605 }
8e65ff28 9606 internal_error (__FILE__, __LINE__,
e2e0b3e5 9607 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9608}
96baa820 9609
4a5e7a5b
PA
9610/* Verify memory using the "qCRC:" request. */
9611
9612static int
9613remote_verify_memory (struct target_ops *ops,
9614 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9615{
9616 struct remote_state *rs = get_remote_state ();
9617 unsigned long host_crc, target_crc;
9618 char *tmp;
9619
936d2992
PA
9620 /* It doesn't make sense to use qCRC if the remote target is
9621 connected but not running. */
9622 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9623 {
9624 enum packet_result result;
28439a30 9625
936d2992
PA
9626 /* Make sure the remote is pointing at the right process. */
9627 set_general_process ();
4a5e7a5b 9628
936d2992
PA
9629 /* FIXME: assumes lma can fit into long. */
9630 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9631 (long) lma, (long) size);
9632 putpkt (rs->buf);
4a5e7a5b 9633
936d2992
PA
9634 /* Be clever; compute the host_crc before waiting for target
9635 reply. */
9636 host_crc = xcrc32 (data, size, 0xffffffff);
9637
9638 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9639
936d2992
PA
9640 result = packet_ok (rs->buf,
9641 &remote_protocol_packets[PACKET_qCRC]);
9642 if (result == PACKET_ERROR)
9643 return -1;
9644 else if (result == PACKET_OK)
9645 {
9646 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9647 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9648
936d2992
PA
9649 return (host_crc == target_crc);
9650 }
9651 }
4a5e7a5b 9652
936d2992 9653 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9654}
9655
c906108c
SS
9656/* compare-sections command
9657
9658 With no arguments, compares each loadable section in the exec bfd
9659 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9660 Useful for verifying the image on the target against the exec file. */
e514a9d6 9661
c906108c 9662static void
fba45db2 9663compare_sections_command (char *args, int from_tty)
c906108c
SS
9664{
9665 asection *s;
c906108c 9666 struct cleanup *old_chain;
948f8e3d 9667 gdb_byte *sectdata;
ce359b09 9668 const char *sectname;
c906108c
SS
9669 bfd_size_type size;
9670 bfd_vma lma;
9671 int matched = 0;
9672 int mismatched = 0;
4a5e7a5b 9673 int res;
95cf3b38 9674 int read_only = 0;
c906108c
SS
9675
9676 if (!exec_bfd)
8a3fe4f8 9677 error (_("command cannot be used without an exec file"));
c906108c 9678
28439a30
PA
9679 /* Make sure the remote is pointing at the right process. */
9680 set_general_process ();
9681
95cf3b38
DT
9682 if (args != NULL && strcmp (args, "-r") == 0)
9683 {
9684 read_only = 1;
9685 args = NULL;
9686 }
9687
c5aa993b 9688 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9689 {
9690 if (!(s->flags & SEC_LOAD))
0df8b418 9691 continue; /* Skip non-loadable section. */
c906108c 9692
95cf3b38
DT
9693 if (read_only && (s->flags & SEC_READONLY) == 0)
9694 continue; /* Skip writeable sections */
9695
2c500098 9696 size = bfd_get_section_size (s);
c906108c 9697 if (size == 0)
0df8b418 9698 continue; /* Skip zero-length section. */
c906108c 9699
ce359b09 9700 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9701 if (args && strcmp (args, sectname) != 0)
0df8b418 9702 continue; /* Not the section selected by user. */
c906108c 9703
0df8b418 9704 matched = 1; /* Do this section. */
c906108c 9705 lma = s->lma;
c906108c 9706
224c3ddb 9707 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9708 old_chain = make_cleanup (xfree, sectdata);
c906108c 9709 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9710
4a5e7a5b
PA
9711 res = target_verify_memory (sectdata, lma, size);
9712
9713 if (res == -1)
5af949e3 9714 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9715 paddress (target_gdbarch (), lma),
9716 paddress (target_gdbarch (), lma + size));
c906108c 9717
5af949e3 9718 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9719 paddress (target_gdbarch (), lma),
9720 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9721 if (res)
c906108c
SS
9722 printf_filtered ("matched.\n");
9723 else
c5aa993b
JM
9724 {
9725 printf_filtered ("MIS-MATCHED!\n");
9726 mismatched++;
9727 }
c906108c
SS
9728
9729 do_cleanups (old_chain);
9730 }
9731 if (mismatched > 0)
936d2992 9732 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9733the loaded file\n"));
c906108c 9734 if (args && !matched)
a3f17187 9735 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9736}
9737
0e7f50da
UW
9738/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9739 into remote target. The number of bytes written to the remote
9740 target is returned, or -1 for error. */
9741
9b409511 9742static enum target_xfer_status
0e7f50da
UW
9743remote_write_qxfer (struct target_ops *ops, const char *object_name,
9744 const char *annex, const gdb_byte *writebuf,
9b409511 9745 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9746 struct packet_config *packet)
9747{
9748 int i, buf_len;
9749 ULONGEST n;
0e7f50da
UW
9750 struct remote_state *rs = get_remote_state ();
9751 int max_size = get_memory_write_packet_size ();
9752
9753 if (packet->support == PACKET_DISABLE)
2ed4b548 9754 return TARGET_XFER_E_IO;
0e7f50da
UW
9755
9756 /* Insert header. */
9757 i = snprintf (rs->buf, max_size,
9758 "qXfer:%s:write:%s:%s:",
9759 object_name, annex ? annex : "",
9760 phex_nz (offset, sizeof offset));
9761 max_size -= (i + 1);
9762
9763 /* Escape as much data as fits into rs->buf. */
9764 buf_len = remote_escape_output
124e13d9 9765 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9766
9767 if (putpkt_binary (rs->buf, i + buf_len) < 0
9768 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9769 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9770 return TARGET_XFER_E_IO;
0e7f50da
UW
9771
9772 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9773
9774 *xfered_len = n;
9775 return TARGET_XFER_OK;
0e7f50da
UW
9776}
9777
0876f84a
DJ
9778/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9779 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9780 number of bytes read is returned, or 0 for EOF, or -1 for error.
9781 The number of bytes read may be less than LEN without indicating an
9782 EOF. PACKET is checked and updated to indicate whether the remote
9783 target supports this object. */
9784
9b409511 9785static enum target_xfer_status
0876f84a
DJ
9786remote_read_qxfer (struct target_ops *ops, const char *object_name,
9787 const char *annex,
9788 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9789 ULONGEST *xfered_len,
0876f84a
DJ
9790 struct packet_config *packet)
9791{
0876f84a 9792 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9793 LONGEST i, n, packet_len;
9794
9795 if (packet->support == PACKET_DISABLE)
2ed4b548 9796 return TARGET_XFER_E_IO;
0876f84a
DJ
9797
9798 /* Check whether we've cached an end-of-object packet that matches
9799 this request. */
8e88304f 9800 if (rs->finished_object)
0876f84a 9801 {
8e88304f
TT
9802 if (strcmp (object_name, rs->finished_object) == 0
9803 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9804 && offset == rs->finished_offset)
9b409511
YQ
9805 return TARGET_XFER_EOF;
9806
0876f84a
DJ
9807
9808 /* Otherwise, we're now reading something different. Discard
9809 the cache. */
8e88304f
TT
9810 xfree (rs->finished_object);
9811 xfree (rs->finished_annex);
9812 rs->finished_object = NULL;
9813 rs->finished_annex = NULL;
0876f84a
DJ
9814 }
9815
9816 /* Request only enough to fit in a single packet. The actual data
9817 may not, since we don't know how much of it will need to be escaped;
9818 the target is free to respond with slightly less data. We subtract
9819 five to account for the response type and the protocol frame. */
9820 n = min (get_remote_packet_size () - 5, len);
9821 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9822 object_name, annex ? annex : "",
9823 phex_nz (offset, sizeof offset),
9824 phex_nz (n, sizeof n));
9825 i = putpkt (rs->buf);
9826 if (i < 0)
2ed4b548 9827 return TARGET_XFER_E_IO;
0876f84a
DJ
9828
9829 rs->buf[0] = '\0';
9830 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9831 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9832 return TARGET_XFER_E_IO;
0876f84a
DJ
9833
9834 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9835 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9836
9837 /* 'm' means there is (or at least might be) more data after this
9838 batch. That does not make sense unless there's at least one byte
9839 of data in this reply. */
9840 if (rs->buf[0] == 'm' && packet_len == 1)
9841 error (_("Remote qXfer reply contained no data."));
9842
9843 /* Got some data. */
bc20a4af
PA
9844 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9845 packet_len - 1, readbuf, n);
0876f84a
DJ
9846
9847 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9848 or possibly empty. If we have the final block of a non-empty
9849 object, record this fact to bypass a subsequent partial read. */
9850 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9851 {
8e88304f
TT
9852 rs->finished_object = xstrdup (object_name);
9853 rs->finished_annex = xstrdup (annex ? annex : "");
9854 rs->finished_offset = offset + i;
0876f84a
DJ
9855 }
9856
9b409511
YQ
9857 if (i == 0)
9858 return TARGET_XFER_EOF;
9859 else
9860 {
9861 *xfered_len = i;
9862 return TARGET_XFER_OK;
9863 }
0876f84a
DJ
9864}
9865
9b409511 9866static enum target_xfer_status
4b8a223f 9867remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9868 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9869 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9870 ULONGEST *xfered_len)
c906108c 9871{
82f73884 9872 struct remote_state *rs;
c906108c 9873 int i;
6d820c5c 9874 char *p2;
1e3ff5ad 9875 char query_type;
124e13d9 9876 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9877
e6e4e701 9878 set_remote_traceframe ();
82f73884
PA
9879 set_general_thread (inferior_ptid);
9880
9881 rs = get_remote_state ();
9882
b2182ed2 9883 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9884 if (object == TARGET_OBJECT_MEMORY)
9885 {
2d717e4f
DJ
9886 /* If the remote target is connected but not running, we should
9887 pass this request down to a lower stratum (e.g. the executable
9888 file). */
9889 if (!target_has_execution)
9b409511 9890 return TARGET_XFER_EOF;
2d717e4f 9891
21e3b9b9 9892 if (writebuf != NULL)
124e13d9
SM
9893 return remote_write_bytes (offset, writebuf, len, unit_size,
9894 xfered_len);
21e3b9b9 9895 else
124e13d9
SM
9896 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9897 xfered_len);
21e3b9b9
DJ
9898 }
9899
0df8b418 9900 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9901 if (object == TARGET_OBJECT_SPU)
9902 {
9903 if (readbuf)
9904 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9905 xfered_len, &remote_protocol_packets
9906 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9907 else
9908 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9909 xfered_len, &remote_protocol_packets
9910 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9911 }
9912
4aa995e1
PA
9913 /* Handle extra signal info using qxfer packets. */
9914 if (object == TARGET_OBJECT_SIGNAL_INFO)
9915 {
9916 if (readbuf)
9917 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 9918 xfered_len, &remote_protocol_packets
4aa995e1
PA
9919 [PACKET_qXfer_siginfo_read]);
9920 else
3e43a32a 9921 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 9922 writebuf, offset, len, xfered_len,
4aa995e1
PA
9923 &remote_protocol_packets
9924 [PACKET_qXfer_siginfo_write]);
9925 }
9926
0fb4aa4b
PA
9927 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9928 {
9929 if (readbuf)
3e43a32a 9930 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 9931 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
9932 &remote_protocol_packets
9933 [PACKET_qXfer_statictrace_read]);
9934 else
2ed4b548 9935 return TARGET_XFER_E_IO;
0fb4aa4b
PA
9936 }
9937
a76d924d
DJ
9938 /* Only handle flash writes. */
9939 if (writebuf != NULL)
9940 {
9941 LONGEST xfered;
9942
9943 switch (object)
9944 {
9945 case TARGET_OBJECT_FLASH:
9b409511
YQ
9946 return remote_flash_write (ops, offset, len, xfered_len,
9947 writebuf);
a76d924d
DJ
9948
9949 default:
2ed4b548 9950 return TARGET_XFER_E_IO;
a76d924d
DJ
9951 }
9952 }
4b8a223f 9953
1e3ff5ad
AC
9954 /* Map pre-existing objects onto letters. DO NOT do this for new
9955 objects!!! Instead specify new query packets. */
9956 switch (object)
c906108c 9957 {
1e3ff5ad
AC
9958 case TARGET_OBJECT_AVR:
9959 query_type = 'R';
9960 break;
802188a7
RM
9961
9962 case TARGET_OBJECT_AUXV:
0876f84a
DJ
9963 gdb_assert (annex == NULL);
9964 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9965 xfered_len,
0876f84a 9966 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9967
23181151
DJ
9968 case TARGET_OBJECT_AVAILABLE_FEATURES:
9969 return remote_read_qxfer
9b409511 9970 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9971 &remote_protocol_packets[PACKET_qXfer_features]);
9972
cfa9d6d9
DJ
9973 case TARGET_OBJECT_LIBRARIES:
9974 return remote_read_qxfer
9b409511 9975 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9976 &remote_protocol_packets[PACKET_qXfer_libraries]);
9977
2268b414
JK
9978 case TARGET_OBJECT_LIBRARIES_SVR4:
9979 return remote_read_qxfer
9b409511 9980 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9981 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9982
fd79ecee
DJ
9983 case TARGET_OBJECT_MEMORY_MAP:
9984 gdb_assert (annex == NULL);
9985 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9986 xfered_len,
fd79ecee
DJ
9987 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9988
07e059b5
VP
9989 case TARGET_OBJECT_OSDATA:
9990 /* Should only get here if we're connected. */
5d93a237 9991 gdb_assert (rs->remote_desc);
07e059b5 9992 return remote_read_qxfer
9b409511 9993 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9994 &remote_protocol_packets[PACKET_qXfer_osdata]);
9995
dc146f7c
VP
9996 case TARGET_OBJECT_THREADS:
9997 gdb_assert (annex == NULL);
9998 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9999 xfered_len,
dc146f7c
VP
10000 &remote_protocol_packets[PACKET_qXfer_threads]);
10001
b3b9301e
PA
10002 case TARGET_OBJECT_TRACEFRAME_INFO:
10003 gdb_assert (annex == NULL);
10004 return remote_read_qxfer
9b409511 10005 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10006 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10007
10008 case TARGET_OBJECT_FDPIC:
10009 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10010 xfered_len,
78d85199 10011 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10012
10013 case TARGET_OBJECT_OPENVMS_UIB:
10014 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10015 xfered_len,
169081d0
TG
10016 &remote_protocol_packets[PACKET_qXfer_uib]);
10017
9accd112
MM
10018 case TARGET_OBJECT_BTRACE:
10019 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10020 xfered_len,
9accd112
MM
10021 &remote_protocol_packets[PACKET_qXfer_btrace]);
10022
f4abbc16
MM
10023 case TARGET_OBJECT_BTRACE_CONF:
10024 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10025 len, xfered_len,
10026 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10027
c78fa86a
GB
10028 case TARGET_OBJECT_EXEC_FILE:
10029 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10030 len, xfered_len,
10031 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10032
1e3ff5ad 10033 default:
2ed4b548 10034 return TARGET_XFER_E_IO;
c906108c
SS
10035 }
10036
0df8b418 10037 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10038 large enough let the caller deal with it. */
ea9c271d 10039 if (len < get_remote_packet_size ())
2ed4b548 10040 return TARGET_XFER_E_IO;
ea9c271d 10041 len = get_remote_packet_size ();
1e3ff5ad 10042
23860348 10043 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10044 if (!rs->remote_desc)
8a3fe4f8 10045 error (_("remote query is only available after target open"));
c906108c 10046
1e3ff5ad 10047 gdb_assert (annex != NULL);
4b8a223f 10048 gdb_assert (readbuf != NULL);
c906108c 10049
6d820c5c 10050 p2 = rs->buf;
c906108c
SS
10051 *p2++ = 'q';
10052 *p2++ = query_type;
10053
23860348
MS
10054 /* We used one buffer char for the remote protocol q command and
10055 another for the query type. As the remote protocol encapsulation
10056 uses 4 chars plus one extra in case we are debugging
10057 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10058 string. */
c906108c 10059 i = 0;
ea9c271d 10060 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10061 {
1e3ff5ad
AC
10062 /* Bad caller may have sent forbidden characters. */
10063 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10064 *p2++ = annex[i];
c906108c
SS
10065 i++;
10066 }
1e3ff5ad
AC
10067 *p2 = '\0';
10068 gdb_assert (annex[i] == '\0');
c906108c 10069
6d820c5c 10070 i = putpkt (rs->buf);
c5aa993b 10071 if (i < 0)
2ed4b548 10072 return TARGET_XFER_E_IO;
c906108c 10073
6d820c5c
DJ
10074 getpkt (&rs->buf, &rs->buf_size, 0);
10075 strcpy ((char *) readbuf, rs->buf);
c906108c 10076
9b409511
YQ
10077 *xfered_len = strlen ((char *) readbuf);
10078 return TARGET_XFER_OK;
c906108c
SS
10079}
10080
08388c79
DE
10081static int
10082remote_search_memory (struct target_ops* ops,
10083 CORE_ADDR start_addr, ULONGEST search_space_len,
10084 const gdb_byte *pattern, ULONGEST pattern_len,
10085 CORE_ADDR *found_addrp)
10086{
f5656ead 10087 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10088 struct remote_state *rs = get_remote_state ();
10089 int max_size = get_memory_write_packet_size ();
10090 struct packet_config *packet =
10091 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10092 /* Number of packet bytes used to encode the pattern;
10093 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10094 int escaped_pattern_len;
0df8b418 10095 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10096 int used_pattern_len;
10097 int i;
10098 int found;
10099 ULONGEST found_addr;
10100
10101 /* Don't go to the target if we don't have to.
10102 This is done before checking packet->support to avoid the possibility that
10103 a success for this edge case means the facility works in general. */
10104 if (pattern_len > search_space_len)
10105 return 0;
10106 if (pattern_len == 0)
10107 {
10108 *found_addrp = start_addr;
10109 return 1;
10110 }
10111
10112 /* If we already know the packet isn't supported, fall back to the simple
10113 way of searching memory. */
10114
4082afcc 10115 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10116 {
10117 /* Target doesn't provided special support, fall back and use the
10118 standard support (copy memory and do the search here). */
10119 return simple_search_memory (ops, start_addr, search_space_len,
10120 pattern, pattern_len, found_addrp);
10121 }
10122
28439a30
PA
10123 /* Make sure the remote is pointing at the right process. */
10124 set_general_process ();
10125
08388c79
DE
10126 /* Insert header. */
10127 i = snprintf (rs->buf, max_size,
10128 "qSearch:memory:%s;%s;",
5af949e3 10129 phex_nz (start_addr, addr_size),
08388c79
DE
10130 phex_nz (search_space_len, sizeof (search_space_len)));
10131 max_size -= (i + 1);
10132
10133 /* Escape as much data as fits into rs->buf. */
10134 escaped_pattern_len =
124e13d9 10135 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10136 &used_pattern_len, max_size);
10137
10138 /* Bail if the pattern is too large. */
10139 if (used_pattern_len != pattern_len)
9b20d036 10140 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10141
10142 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10143 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10144 || packet_ok (rs->buf, packet) != PACKET_OK)
10145 {
10146 /* The request may not have worked because the command is not
10147 supported. If so, fall back to the simple way. */
10148 if (packet->support == PACKET_DISABLE)
10149 {
10150 return simple_search_memory (ops, start_addr, search_space_len,
10151 pattern, pattern_len, found_addrp);
10152 }
10153 return -1;
10154 }
10155
10156 if (rs->buf[0] == '0')
10157 found = 0;
10158 else if (rs->buf[0] == '1')
10159 {
10160 found = 1;
10161 if (rs->buf[1] != ',')
10e0fa18 10162 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10163 unpack_varlen_hex (rs->buf + 2, &found_addr);
10164 *found_addrp = found_addr;
10165 }
10166 else
10e0fa18 10167 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10168
10169 return found;
10170}
10171
96baa820 10172static void
a30bf1f1 10173remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10174 struct ui_file *outbuf)
96baa820 10175{
d01949b6 10176 struct remote_state *rs = get_remote_state ();
2e9f7625 10177 char *p = rs->buf;
96baa820 10178
5d93a237 10179 if (!rs->remote_desc)
8a3fe4f8 10180 error (_("remote rcmd is only available after target open"));
96baa820 10181
23860348 10182 /* Send a NULL command across as an empty command. */
7be570e7
JM
10183 if (command == NULL)
10184 command = "";
10185
23860348 10186 /* The query prefix. */
2e9f7625
DJ
10187 strcpy (rs->buf, "qRcmd,");
10188 p = strchr (rs->buf, '\0');
96baa820 10189
3e43a32a
MS
10190 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10191 > get_remote_packet_size ())
8a3fe4f8 10192 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10193
23860348 10194 /* Encode the actual command. */
a30bf1f1 10195 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10196
6d820c5c 10197 if (putpkt (rs->buf) < 0)
8a3fe4f8 10198 error (_("Communication problem with target."));
96baa820
JM
10199
10200 /* get/display the response */
10201 while (1)
10202 {
2e9f7625
DJ
10203 char *buf;
10204
00bf0b85 10205 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10206 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10207 rs->buf[0] = '\0';
5b37825d
PW
10208 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10209 {
10210 /* Timeout. Continue to (try to) read responses.
10211 This is better than stopping with an error, assuming the stub
10212 is still executing the (long) monitor command.
10213 If needed, the user can interrupt gdb using C-c, obtaining
10214 an effect similar to stop on timeout. */
10215 continue;
10216 }
2e9f7625 10217 buf = rs->buf;
96baa820 10218 if (buf[0] == '\0')
8a3fe4f8 10219 error (_("Target does not support this command."));
96baa820
JM
10220 if (buf[0] == 'O' && buf[1] != 'K')
10221 {
23860348 10222 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10223 continue;
10224 }
10225 if (strcmp (buf, "OK") == 0)
10226 break;
7be570e7
JM
10227 if (strlen (buf) == 3 && buf[0] == 'E'
10228 && isdigit (buf[1]) && isdigit (buf[2]))
10229 {
8a3fe4f8 10230 error (_("Protocol error with Rcmd"));
7be570e7 10231 }
96baa820
JM
10232 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10233 {
10234 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10235
96baa820
JM
10236 fputc_unfiltered (c, outbuf);
10237 }
10238 break;
10239 }
10240}
10241
fd79ecee
DJ
10242static VEC(mem_region_s) *
10243remote_memory_map (struct target_ops *ops)
10244{
10245 VEC(mem_region_s) *result = NULL;
10246 char *text = target_read_stralloc (&current_target,
10247 TARGET_OBJECT_MEMORY_MAP, NULL);
10248
10249 if (text)
10250 {
10251 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10252
fd79ecee
DJ
10253 result = parse_memory_map (text);
10254 do_cleanups (back_to);
10255 }
10256
10257 return result;
10258}
10259
c906108c 10260static void
fba45db2 10261packet_command (char *args, int from_tty)
c906108c 10262{
d01949b6 10263 struct remote_state *rs = get_remote_state ();
c906108c 10264
5d93a237 10265 if (!rs->remote_desc)
8a3fe4f8 10266 error (_("command can only be used with remote target"));
c906108c 10267
c5aa993b 10268 if (!args)
8a3fe4f8 10269 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10270
10271 puts_filtered ("sending: ");
10272 print_packet (args);
10273 puts_filtered ("\n");
10274 putpkt (args);
10275
6d820c5c 10276 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10277 puts_filtered ("received: ");
6d820c5c 10278 print_packet (rs->buf);
c906108c
SS
10279 puts_filtered ("\n");
10280}
10281
10282#if 0
23860348 10283/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10284
a14ed312 10285static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10286
a14ed312 10287static void threadset_test_cmd (char *cmd, int tty);
c906108c 10288
a14ed312 10289static void threadalive_test (char *cmd, int tty);
c906108c 10290
a14ed312 10291static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10292
23860348 10293int get_and_display_threadinfo (threadref *ref);
c906108c 10294
a14ed312 10295static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10296
23860348 10297static int thread_display_step (threadref *ref, void *context);
c906108c 10298
a14ed312 10299static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10300
a14ed312 10301static void init_remote_threadtests (void);
c906108c 10302
23860348 10303#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10304
10305static void
fba45db2 10306threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10307{
10308 int sample_thread = SAMPLE_THREAD;
10309
a3f17187 10310 printf_filtered (_("Remote threadset test\n"));
79d7f229 10311 set_general_thread (sample_thread);
c906108c
SS
10312}
10313
10314
10315static void
fba45db2 10316threadalive_test (char *cmd, int tty)
c906108c
SS
10317{
10318 int sample_thread = SAMPLE_THREAD;
79d7f229 10319 int pid = ptid_get_pid (inferior_ptid);
ba348170 10320 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10321
79d7f229 10322 if (remote_thread_alive (ptid))
c906108c
SS
10323 printf_filtered ("PASS: Thread alive test\n");
10324 else
10325 printf_filtered ("FAIL: Thread alive test\n");
10326}
10327
23860348 10328void output_threadid (char *title, threadref *ref);
c906108c
SS
10329
10330void
fba45db2 10331output_threadid (char *title, threadref *ref)
c906108c
SS
10332{
10333 char hexid[20];
10334
23860348 10335 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10336 hexid[16] = 0;
10337 printf_filtered ("%s %s\n", title, (&hexid[0]));
10338}
10339
10340static void
fba45db2 10341threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10342{
10343 int startflag = 1;
10344 threadref nextthread;
10345 int done, result_count;
10346 threadref threadlist[3];
10347
10348 printf_filtered ("Remote Threadlist test\n");
10349 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10350 &result_count, &threadlist[0]))
10351 printf_filtered ("FAIL: threadlist test\n");
10352 else
10353 {
10354 threadref *scan = threadlist;
10355 threadref *limit = scan + result_count;
10356
10357 while (scan < limit)
10358 output_threadid (" thread ", scan++);
10359 }
10360}
10361
10362void
fba45db2 10363display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10364{
10365 output_threadid ("Threadid: ", &info->threadid);
10366 printf_filtered ("Name: %s\n ", info->shortname);
10367 printf_filtered ("State: %s\n", info->display);
10368 printf_filtered ("other: %s\n\n", info->more_display);
10369}
10370
10371int
fba45db2 10372get_and_display_threadinfo (threadref *ref)
c906108c
SS
10373{
10374 int result;
10375 int set;
10376 struct gdb_ext_thread_info threadinfo;
10377
10378 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10379 | TAG_MOREDISPLAY | TAG_DISPLAY;
10380 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10381 display_thread_info (&threadinfo);
10382 return result;
10383}
10384
10385static void
fba45db2 10386threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10387{
10388 int athread = SAMPLE_THREAD;
10389 threadref thread;
10390 int set;
10391
10392 int_to_threadref (&thread, athread);
10393 printf_filtered ("Remote Threadinfo test\n");
10394 if (!get_and_display_threadinfo (&thread))
10395 printf_filtered ("FAIL cannot get thread info\n");
10396}
10397
10398static int
fba45db2 10399thread_display_step (threadref *ref, void *context)
c906108c
SS
10400{
10401 /* output_threadid(" threadstep ",ref); *//* simple test */
10402 return get_and_display_threadinfo (ref);
10403}
10404
10405static void
fba45db2 10406threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10407{
10408 printf_filtered ("Remote Threadlist update test\n");
10409 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10410}
10411
10412static void
10413init_remote_threadtests (void)
10414{
3e43a32a
MS
10415 add_com ("tlist", class_obscure, threadlist_test_cmd,
10416 _("Fetch and print the remote list of "
10417 "thread identifiers, one pkt only"));
c906108c 10418 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10419 _("Fetch and display info about one thread"));
c906108c 10420 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10421 _("Test setting to a different thread"));
c906108c 10422 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10423 _("Iterate through updating all remote thread info"));
c906108c 10424 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10425 _(" Remote thread alive test "));
c906108c
SS
10426}
10427
10428#endif /* 0 */
10429
f3fb8c85
MS
10430/* Convert a thread ID to a string. Returns the string in a static
10431 buffer. */
10432
10433static char *
117de6a9 10434remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10435{
79d7f229 10436 static char buf[64];
82f73884 10437 struct remote_state *rs = get_remote_state ();
f3fb8c85 10438
7cee1e54
PA
10439 if (ptid_equal (ptid, null_ptid))
10440 return normal_pid_to_str (ptid);
10441 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10442 {
10443 /* Printing an inferior target id. */
10444
10445 /* When multi-process extensions are off, there's no way in the
10446 remote protocol to know the remote process id, if there's any
10447 at all. There's one exception --- when we're connected with
10448 target extended-remote, and we manually attached to a process
10449 with "attach PID". We don't record anywhere a flag that
10450 allows us to distinguish that case from the case of
10451 connecting with extended-remote and the stub already being
10452 attached to a process, and reporting yes to qAttached, hence
10453 no smart special casing here. */
10454 if (!remote_multi_process_p (rs))
10455 {
10456 xsnprintf (buf, sizeof buf, "Remote target");
10457 return buf;
10458 }
10459
10460 return normal_pid_to_str (ptid);
82f73884 10461 }
ecd0ada5 10462 else
79d7f229 10463 {
ecd0ada5
PA
10464 if (ptid_equal (magic_null_ptid, ptid))
10465 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 10466 else if (rs->extended && remote_multi_process_p (rs))
de0d863e
DB
10467 if (ptid_get_lwp (ptid) == 0)
10468 return normal_pid_to_str (ptid);
10469 else
10470 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10471 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10472 else
10473 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10474 ptid_get_lwp (ptid));
79d7f229
PA
10475 return buf;
10476 }
f3fb8c85
MS
10477}
10478
38691318
KB
10479/* Get the address of the thread local variable in OBJFILE which is
10480 stored at OFFSET within the thread local storage for thread PTID. */
10481
10482static CORE_ADDR
117de6a9
PA
10483remote_get_thread_local_address (struct target_ops *ops,
10484 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10485{
4082afcc 10486 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10487 {
10488 struct remote_state *rs = get_remote_state ();
6d820c5c 10489 char *p = rs->buf;
82f73884 10490 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10491 enum packet_result result;
38691318
KB
10492
10493 strcpy (p, "qGetTLSAddr:");
10494 p += strlen (p);
82f73884 10495 p = write_ptid (p, endp, ptid);
38691318
KB
10496 *p++ = ',';
10497 p += hexnumstr (p, offset);
10498 *p++ = ',';
10499 p += hexnumstr (p, lm);
10500 *p++ = '\0';
10501
6d820c5c
DJ
10502 putpkt (rs->buf);
10503 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10504 result = packet_ok (rs->buf,
10505 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10506 if (result == PACKET_OK)
38691318
KB
10507 {
10508 ULONGEST result;
10509
6d820c5c 10510 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10511 return result;
10512 }
571dd617 10513 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10514 throw_error (TLS_GENERIC_ERROR,
10515 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10516 else
109c3e39
AC
10517 throw_error (TLS_GENERIC_ERROR,
10518 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10519 }
10520 else
109c3e39
AC
10521 throw_error (TLS_GENERIC_ERROR,
10522 _("TLS not supported or disabled on this target"));
38691318
KB
10523 /* Not reached. */
10524 return 0;
10525}
10526
711e434b
PM
10527/* Provide thread local base, i.e. Thread Information Block address.
10528 Returns 1 if ptid is found and thread_local_base is non zero. */
10529
70221824 10530static int
bd7ae0f5 10531remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10532{
4082afcc 10533 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10534 {
10535 struct remote_state *rs = get_remote_state ();
10536 char *p = rs->buf;
10537 char *endp = rs->buf + get_remote_packet_size ();
10538 enum packet_result result;
10539
10540 strcpy (p, "qGetTIBAddr:");
10541 p += strlen (p);
10542 p = write_ptid (p, endp, ptid);
10543 *p++ = '\0';
10544
10545 putpkt (rs->buf);
10546 getpkt (&rs->buf, &rs->buf_size, 0);
10547 result = packet_ok (rs->buf,
10548 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10549 if (result == PACKET_OK)
10550 {
10551 ULONGEST result;
10552
10553 unpack_varlen_hex (rs->buf, &result);
10554 if (addr)
10555 *addr = (CORE_ADDR) result;
10556 return 1;
10557 }
10558 else if (result == PACKET_UNKNOWN)
10559 error (_("Remote target doesn't support qGetTIBAddr packet"));
10560 else
10561 error (_("Remote target failed to process qGetTIBAddr request"));
10562 }
10563 else
10564 error (_("qGetTIBAddr not supported or disabled on this target"));
10565 /* Not reached. */
10566 return 0;
10567}
10568
29709017
DJ
10569/* Support for inferring a target description based on the current
10570 architecture and the size of a 'g' packet. While the 'g' packet
10571 can have any size (since optional registers can be left off the
10572 end), some sizes are easily recognizable given knowledge of the
10573 approximate architecture. */
10574
10575struct remote_g_packet_guess
10576{
10577 int bytes;
10578 const struct target_desc *tdesc;
10579};
10580typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10581DEF_VEC_O(remote_g_packet_guess_s);
10582
10583struct remote_g_packet_data
10584{
10585 VEC(remote_g_packet_guess_s) *guesses;
10586};
10587
10588static struct gdbarch_data *remote_g_packet_data_handle;
10589
10590static void *
10591remote_g_packet_data_init (struct obstack *obstack)
10592{
10593 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10594}
10595
10596void
10597register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10598 const struct target_desc *tdesc)
10599{
10600 struct remote_g_packet_data *data
19ba03f4
SM
10601 = ((struct remote_g_packet_data *)
10602 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10603 struct remote_g_packet_guess new_guess, *guess;
10604 int ix;
10605
10606 gdb_assert (tdesc != NULL);
10607
10608 for (ix = 0;
10609 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10610 ix++)
10611 if (guess->bytes == bytes)
10612 internal_error (__FILE__, __LINE__,
9b20d036 10613 _("Duplicate g packet description added for size %d"),
29709017
DJ
10614 bytes);
10615
10616 new_guess.bytes = bytes;
10617 new_guess.tdesc = tdesc;
10618 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10619}
10620
d962ef82
DJ
10621/* Return 1 if remote_read_description would do anything on this target
10622 and architecture, 0 otherwise. */
10623
10624static int
10625remote_read_description_p (struct target_ops *target)
10626{
10627 struct remote_g_packet_data *data
19ba03f4
SM
10628 = ((struct remote_g_packet_data *)
10629 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10630
10631 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10632 return 1;
10633
10634 return 0;
10635}
10636
29709017
DJ
10637static const struct target_desc *
10638remote_read_description (struct target_ops *target)
10639{
10640 struct remote_g_packet_data *data
19ba03f4
SM
10641 = ((struct remote_g_packet_data *)
10642 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10643
d962ef82
DJ
10644 /* Do not try this during initial connection, when we do not know
10645 whether there is a running but stopped thread. */
10646 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10647 return target->beneath->to_read_description (target->beneath);
d962ef82 10648
29709017
DJ
10649 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10650 {
10651 struct remote_g_packet_guess *guess;
10652 int ix;
10653 int bytes = send_g_packet ();
10654
10655 for (ix = 0;
10656 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10657 ix++)
10658 if (guess->bytes == bytes)
10659 return guess->tdesc;
10660
10661 /* We discard the g packet. A minor optimization would be to
10662 hold on to it, and fill the register cache once we have selected
10663 an architecture, but it's too tricky to do safely. */
10664 }
10665
2117c711 10666 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10667}
10668
a6b151f1
DJ
10669/* Remote file transfer support. This is host-initiated I/O, not
10670 target-initiated; for target-initiated, see remote-fileio.c. */
10671
10672/* If *LEFT is at least the length of STRING, copy STRING to
10673 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10674 decrease *LEFT. Otherwise raise an error. */
10675
10676static void
10677remote_buffer_add_string (char **buffer, int *left, char *string)
10678{
10679 int len = strlen (string);
10680
10681 if (len > *left)
10682 error (_("Packet too long for target."));
10683
10684 memcpy (*buffer, string, len);
10685 *buffer += len;
10686 *left -= len;
10687
10688 /* NUL-terminate the buffer as a convenience, if there is
10689 room. */
10690 if (*left)
10691 **buffer = '\0';
10692}
10693
10694/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10695 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10696 decrease *LEFT. Otherwise raise an error. */
10697
10698static void
10699remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10700 int len)
10701{
10702 if (2 * len > *left)
10703 error (_("Packet too long for target."));
10704
10705 bin2hex (bytes, *buffer, len);
10706 *buffer += 2 * len;
10707 *left -= 2 * len;
10708
10709 /* NUL-terminate the buffer as a convenience, if there is
10710 room. */
10711 if (*left)
10712 **buffer = '\0';
10713}
10714
10715/* If *LEFT is large enough, convert VALUE to hex and add it to
10716 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10717 decrease *LEFT. Otherwise raise an error. */
10718
10719static void
10720remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10721{
10722 int len = hexnumlen (value);
10723
10724 if (len > *left)
10725 error (_("Packet too long for target."));
10726
10727 hexnumstr (*buffer, value);
10728 *buffer += len;
10729 *left -= len;
10730
10731 /* NUL-terminate the buffer as a convenience, if there is
10732 room. */
10733 if (*left)
10734 **buffer = '\0';
10735}
10736
10737/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10738 value, *REMOTE_ERRNO to the remote error number or zero if none
10739 was included, and *ATTACHMENT to point to the start of the annex
10740 if any. The length of the packet isn't needed here; there may
10741 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10742
10743 Return 0 if the packet could be parsed, -1 if it could not. If
10744 -1 is returned, the other variables may not be initialized. */
10745
10746static int
10747remote_hostio_parse_result (char *buffer, int *retcode,
10748 int *remote_errno, char **attachment)
10749{
10750 char *p, *p2;
10751
10752 *remote_errno = 0;
10753 *attachment = NULL;
10754
10755 if (buffer[0] != 'F')
10756 return -1;
10757
10758 errno = 0;
10759 *retcode = strtol (&buffer[1], &p, 16);
10760 if (errno != 0 || p == &buffer[1])
10761 return -1;
10762
10763 /* Check for ",errno". */
10764 if (*p == ',')
10765 {
10766 errno = 0;
10767 *remote_errno = strtol (p + 1, &p2, 16);
10768 if (errno != 0 || p + 1 == p2)
10769 return -1;
10770 p = p2;
10771 }
10772
10773 /* Check for ";attachment". If there is no attachment, the
10774 packet should end here. */
10775 if (*p == ';')
10776 {
10777 *attachment = p + 1;
10778 return 0;
10779 }
10780 else if (*p == '\0')
10781 return 0;
10782 else
10783 return -1;
10784}
10785
10786/* Send a prepared I/O packet to the target and read its response.
10787 The prepared packet is in the global RS->BUF before this function
10788 is called, and the answer is there when we return.
10789
10790 COMMAND_BYTES is the length of the request to send, which may include
10791 binary data. WHICH_PACKET is the packet configuration to check
10792 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10793 is set to the error number and -1 is returned. Otherwise the value
10794 returned by the function is returned.
10795
10796 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10797 attachment is expected; an error will be reported if there's a
10798 mismatch. If one is found, *ATTACHMENT will be set to point into
10799 the packet buffer and *ATTACHMENT_LEN will be set to the
10800 attachment's length. */
10801
10802static int
10803remote_hostio_send_command (int command_bytes, int which_packet,
10804 int *remote_errno, char **attachment,
10805 int *attachment_len)
10806{
10807 struct remote_state *rs = get_remote_state ();
10808 int ret, bytes_read;
10809 char *attachment_tmp;
10810
5d93a237 10811 if (!rs->remote_desc
4082afcc 10812 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10813 {
10814 *remote_errno = FILEIO_ENOSYS;
10815 return -1;
10816 }
10817
10818 putpkt_binary (rs->buf, command_bytes);
10819 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10820
10821 /* If it timed out, something is wrong. Don't try to parse the
10822 buffer. */
10823 if (bytes_read < 0)
10824 {
10825 *remote_errno = FILEIO_EINVAL;
10826 return -1;
10827 }
10828
10829 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10830 {
10831 case PACKET_ERROR:
10832 *remote_errno = FILEIO_EINVAL;
10833 return -1;
10834 case PACKET_UNKNOWN:
10835 *remote_errno = FILEIO_ENOSYS;
10836 return -1;
10837 case PACKET_OK:
10838 break;
10839 }
10840
10841 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10842 &attachment_tmp))
10843 {
10844 *remote_errno = FILEIO_EINVAL;
10845 return -1;
10846 }
10847
10848 /* Make sure we saw an attachment if and only if we expected one. */
10849 if ((attachment_tmp == NULL && attachment != NULL)
10850 || (attachment_tmp != NULL && attachment == NULL))
10851 {
10852 *remote_errno = FILEIO_EINVAL;
10853 return -1;
10854 }
10855
10856 /* If an attachment was found, it must point into the packet buffer;
10857 work out how many bytes there were. */
10858 if (attachment_tmp != NULL)
10859 {
10860 *attachment = attachment_tmp;
10861 *attachment_len = bytes_read - (*attachment - rs->buf);
10862 }
10863
10864 return ret;
10865}
10866
80152258
PA
10867/* Invalidate the readahead cache. */
10868
10869static void
10870readahead_cache_invalidate (void)
10871{
10872 struct remote_state *rs = get_remote_state ();
10873
10874 rs->readahead_cache.fd = -1;
10875}
10876
10877/* Invalidate the readahead cache if it is holding data for FD. */
10878
10879static void
10880readahead_cache_invalidate_fd (int fd)
10881{
10882 struct remote_state *rs = get_remote_state ();
10883
10884 if (rs->readahead_cache.fd == fd)
10885 rs->readahead_cache.fd = -1;
10886}
10887
15a201c8
GB
10888/* Set the filesystem remote_hostio functions that take FILENAME
10889 arguments will use. Return 0 on success, or -1 if an error
10890 occurs (and set *REMOTE_ERRNO). */
10891
10892static int
10893remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10894{
10895 struct remote_state *rs = get_remote_state ();
10896 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10897 char *p = rs->buf;
10898 int left = get_remote_packet_size () - 1;
10899 char arg[9];
10900 int ret;
10901
10902 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10903 return 0;
10904
10905 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10906 return 0;
10907
10908 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10909
10910 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10911 remote_buffer_add_string (&p, &left, arg);
10912
10913 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10914 remote_errno, NULL, NULL);
10915
10916 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10917 return 0;
10918
10919 if (ret == 0)
10920 rs->fs_pid = required_pid;
10921
10922 return ret;
10923}
10924
12e2a5fd 10925/* Implementation of to_fileio_open. */
a6b151f1
DJ
10926
10927static int
cd897586 10928remote_hostio_open (struct target_ops *self,
07c138c8 10929 struct inferior *inf, const char *filename,
4313b8c0
GB
10930 int flags, int mode, int warn_if_slow,
10931 int *remote_errno)
a6b151f1
DJ
10932{
10933 struct remote_state *rs = get_remote_state ();
10934 char *p = rs->buf;
10935 int left = get_remote_packet_size () - 1;
10936
4313b8c0
GB
10937 if (warn_if_slow)
10938 {
10939 static int warning_issued = 0;
10940
10941 printf_unfiltered (_("Reading %s from remote target...\n"),
10942 filename);
10943
10944 if (!warning_issued)
10945 {
10946 warning (_("File transfers from remote targets can be slow."
10947 " Use \"set sysroot\" to access files locally"
10948 " instead."));
10949 warning_issued = 1;
10950 }
10951 }
10952
15a201c8
GB
10953 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10954 return -1;
10955
a6b151f1
DJ
10956 remote_buffer_add_string (&p, &left, "vFile:open:");
10957
10958 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10959 strlen (filename));
10960 remote_buffer_add_string (&p, &left, ",");
10961
10962 remote_buffer_add_int (&p, &left, flags);
10963 remote_buffer_add_string (&p, &left, ",");
10964
10965 remote_buffer_add_int (&p, &left, mode);
10966
10967 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10968 remote_errno, NULL, NULL);
10969}
10970
12e2a5fd 10971/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
10972
10973static int
0d866f62
TT
10974remote_hostio_pwrite (struct target_ops *self,
10975 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
10976 ULONGEST offset, int *remote_errno)
10977{
10978 struct remote_state *rs = get_remote_state ();
10979 char *p = rs->buf;
10980 int left = get_remote_packet_size ();
10981 int out_len;
10982
80152258
PA
10983 readahead_cache_invalidate_fd (fd);
10984
a6b151f1
DJ
10985 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10986
10987 remote_buffer_add_int (&p, &left, fd);
10988 remote_buffer_add_string (&p, &left, ",");
10989
10990 remote_buffer_add_int (&p, &left, offset);
10991 remote_buffer_add_string (&p, &left, ",");
10992
124e13d9 10993 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
10994 get_remote_packet_size () - (p - rs->buf));
10995
10996 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10997 remote_errno, NULL, NULL);
10998}
10999
80152258
PA
11000/* Helper for the implementation of to_fileio_pread. Read the file
11001 from the remote side with vFile:pread. */
a6b151f1
DJ
11002
11003static int
80152258
PA
11004remote_hostio_pread_vFile (struct target_ops *self,
11005 int fd, gdb_byte *read_buf, int len,
11006 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11007{
11008 struct remote_state *rs = get_remote_state ();
11009 char *p = rs->buf;
11010 char *attachment;
11011 int left = get_remote_packet_size ();
11012 int ret, attachment_len;
11013 int read_len;
11014
11015 remote_buffer_add_string (&p, &left, "vFile:pread:");
11016
11017 remote_buffer_add_int (&p, &left, fd);
11018 remote_buffer_add_string (&p, &left, ",");
11019
11020 remote_buffer_add_int (&p, &left, len);
11021 remote_buffer_add_string (&p, &left, ",");
11022
11023 remote_buffer_add_int (&p, &left, offset);
11024
11025 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11026 remote_errno, &attachment,
11027 &attachment_len);
11028
11029 if (ret < 0)
11030 return ret;
11031
bc20a4af 11032 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11033 read_buf, len);
11034 if (read_len != ret)
11035 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11036
11037 return ret;
11038}
11039
80152258
PA
11040/* Serve pread from the readahead cache. Returns number of bytes
11041 read, or 0 if the request can't be served from the cache. */
11042
11043static int
11044remote_hostio_pread_from_cache (struct remote_state *rs,
11045 int fd, gdb_byte *read_buf, size_t len,
11046 ULONGEST offset)
11047{
11048 struct readahead_cache *cache = &rs->readahead_cache;
11049
11050 if (cache->fd == fd
11051 && cache->offset <= offset
11052 && offset < cache->offset + cache->bufsize)
11053 {
11054 ULONGEST max = cache->offset + cache->bufsize;
11055
11056 if (offset + len > max)
11057 len = max - offset;
11058
11059 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11060 return len;
11061 }
11062
11063 return 0;
11064}
11065
11066/* Implementation of to_fileio_pread. */
11067
11068static int
11069remote_hostio_pread (struct target_ops *self,
11070 int fd, gdb_byte *read_buf, int len,
11071 ULONGEST offset, int *remote_errno)
11072{
11073 int ret;
11074 struct remote_state *rs = get_remote_state ();
11075 struct readahead_cache *cache = &rs->readahead_cache;
11076
11077 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11078 if (ret > 0)
11079 {
11080 cache->hit_count++;
11081
11082 if (remote_debug)
11083 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11084 pulongest (cache->hit_count));
11085 return ret;
11086 }
11087
11088 cache->miss_count++;
11089 if (remote_debug)
11090 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11091 pulongest (cache->miss_count));
11092
11093 cache->fd = fd;
11094 cache->offset = offset;
11095 cache->bufsize = get_remote_packet_size ();
224c3ddb 11096 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11097
11098 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11099 cache->offset, remote_errno);
11100 if (ret <= 0)
11101 {
11102 readahead_cache_invalidate_fd (fd);
11103 return ret;
11104 }
11105
11106 cache->bufsize = ret;
11107 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11108}
11109
12e2a5fd 11110/* Implementation of to_fileio_close. */
a6b151f1
DJ
11111
11112static int
df39ea25 11113remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11114{
11115 struct remote_state *rs = get_remote_state ();
11116 char *p = rs->buf;
11117 int left = get_remote_packet_size () - 1;
11118
80152258
PA
11119 readahead_cache_invalidate_fd (fd);
11120
a6b151f1
DJ
11121 remote_buffer_add_string (&p, &left, "vFile:close:");
11122
11123 remote_buffer_add_int (&p, &left, fd);
11124
11125 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11126 remote_errno, NULL, NULL);
11127}
11128
12e2a5fd 11129/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11130
11131static int
dbbca37d 11132remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11133 struct inferior *inf, const char *filename,
11134 int *remote_errno)
a6b151f1
DJ
11135{
11136 struct remote_state *rs = get_remote_state ();
11137 char *p = rs->buf;
11138 int left = get_remote_packet_size () - 1;
11139
15a201c8
GB
11140 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11141 return -1;
11142
a6b151f1
DJ
11143 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11144
11145 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11146 strlen (filename));
11147
11148 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11149 remote_errno, NULL, NULL);
11150}
11151
12e2a5fd 11152/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11153
11154static char *
fab5aa7c 11155remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11156 struct inferior *inf, const char *filename,
11157 int *remote_errno)
b9e7b9c3
UW
11158{
11159 struct remote_state *rs = get_remote_state ();
11160 char *p = rs->buf;
11161 char *attachment;
11162 int left = get_remote_packet_size ();
11163 int len, attachment_len;
11164 int read_len;
11165 char *ret;
11166
15a201c8
GB
11167 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11168 return NULL;
11169
b9e7b9c3
UW
11170 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11171
11172 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11173 strlen (filename));
11174
11175 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11176 remote_errno, &attachment,
11177 &attachment_len);
11178
11179 if (len < 0)
11180 return NULL;
11181
224c3ddb 11182 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11183
bc20a4af
PA
11184 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11185 (gdb_byte *) ret, len);
b9e7b9c3
UW
11186 if (read_len != len)
11187 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11188
11189 ret[len] = '\0';
11190 return ret;
11191}
11192
12e2a5fd 11193/* Implementation of to_fileio_fstat. */
0a93529c
GB
11194
11195static int
11196remote_hostio_fstat (struct target_ops *self,
11197 int fd, struct stat *st,
11198 int *remote_errno)
11199{
11200 struct remote_state *rs = get_remote_state ();
11201 char *p = rs->buf;
11202 int left = get_remote_packet_size ();
11203 int attachment_len, ret;
11204 char *attachment;
11205 struct fio_stat fst;
11206 int read_len;
11207
464b0089
GB
11208 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11209
11210 remote_buffer_add_int (&p, &left, fd);
11211
11212 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11213 remote_errno, &attachment,
11214 &attachment_len);
11215 if (ret < 0)
0a93529c 11216 {
464b0089
GB
11217 if (*remote_errno != FILEIO_ENOSYS)
11218 return ret;
11219
0a93529c
GB
11220 /* Strictly we should return -1, ENOSYS here, but when
11221 "set sysroot remote:" was implemented in August 2008
11222 BFD's need for a stat function was sidestepped with
11223 this hack. This was not remedied until March 2015
11224 so we retain the previous behavior to avoid breaking
11225 compatibility.
11226
11227 Note that the memset is a March 2015 addition; older
11228 GDBs set st_size *and nothing else* so the structure
11229 would have garbage in all other fields. This might
11230 break something but retaining the previous behavior
11231 here would be just too wrong. */
11232
11233 memset (st, 0, sizeof (struct stat));
11234 st->st_size = INT_MAX;
11235 return 0;
11236 }
11237
0a93529c
GB
11238 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11239 (gdb_byte *) &fst, sizeof (fst));
11240
11241 if (read_len != ret)
11242 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11243
11244 if (read_len != sizeof (fst))
11245 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11246 read_len, (int) sizeof (fst));
11247
11248 remote_fileio_to_host_stat (&fst, st);
11249
11250 return 0;
11251}
11252
12e2a5fd 11253/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11254
11255static int
11256remote_filesystem_is_local (struct target_ops *self)
11257{
11258 /* Valgrind GDB presents itself as a remote target but works
11259 on the local filesystem: it does not implement remote get
11260 and users are not expected to set a sysroot. To handle
11261 this case we treat the remote filesystem as local if the
11262 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11263 does not support vFile:open. */
a3be80c3 11264 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11265 {
11266 enum packet_support ps = packet_support (PACKET_vFile_open);
11267
11268 if (ps == PACKET_SUPPORT_UNKNOWN)
11269 {
11270 int fd, remote_errno;
11271
11272 /* Try opening a file to probe support. The supplied
11273 filename is irrelevant, we only care about whether
11274 the stub recognizes the packet or not. */
07c138c8 11275 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11276 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11277 &remote_errno);
11278
11279 if (fd >= 0)
11280 remote_hostio_close (self, fd, &remote_errno);
11281
11282 ps = packet_support (PACKET_vFile_open);
11283 }
11284
11285 if (ps == PACKET_DISABLE)
11286 {
11287 static int warning_issued = 0;
11288
11289 if (!warning_issued)
11290 {
11291 warning (_("remote target does not support file"
11292 " transfer, attempting to access files"
11293 " from local filesystem."));
11294 warning_issued = 1;
11295 }
11296
11297 return 1;
11298 }
11299 }
11300
11301 return 0;
11302}
11303
a6b151f1
DJ
11304static int
11305remote_fileio_errno_to_host (int errnum)
11306{
11307 switch (errnum)
11308 {
11309 case FILEIO_EPERM:
11310 return EPERM;
11311 case FILEIO_ENOENT:
11312 return ENOENT;
11313 case FILEIO_EINTR:
11314 return EINTR;
11315 case FILEIO_EIO:
11316 return EIO;
11317 case FILEIO_EBADF:
11318 return EBADF;
11319 case FILEIO_EACCES:
11320 return EACCES;
11321 case FILEIO_EFAULT:
11322 return EFAULT;
11323 case FILEIO_EBUSY:
11324 return EBUSY;
11325 case FILEIO_EEXIST:
11326 return EEXIST;
11327 case FILEIO_ENODEV:
11328 return ENODEV;
11329 case FILEIO_ENOTDIR:
11330 return ENOTDIR;
11331 case FILEIO_EISDIR:
11332 return EISDIR;
11333 case FILEIO_EINVAL:
11334 return EINVAL;
11335 case FILEIO_ENFILE:
11336 return ENFILE;
11337 case FILEIO_EMFILE:
11338 return EMFILE;
11339 case FILEIO_EFBIG:
11340 return EFBIG;
11341 case FILEIO_ENOSPC:
11342 return ENOSPC;
11343 case FILEIO_ESPIPE:
11344 return ESPIPE;
11345 case FILEIO_EROFS:
11346 return EROFS;
11347 case FILEIO_ENOSYS:
11348 return ENOSYS;
11349 case FILEIO_ENAMETOOLONG:
11350 return ENAMETOOLONG;
11351 }
11352 return -1;
11353}
11354
11355static char *
11356remote_hostio_error (int errnum)
11357{
11358 int host_error = remote_fileio_errno_to_host (errnum);
11359
11360 if (host_error == -1)
11361 error (_("Unknown remote I/O error %d"), errnum);
11362 else
11363 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11364}
11365
a6b151f1
DJ
11366static void
11367remote_hostio_close_cleanup (void *opaque)
11368{
11369 int fd = *(int *) opaque;
11370 int remote_errno;
11371
df39ea25 11372 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11373}
11374
11375void
11376remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11377{
11378 struct cleanup *back_to, *close_cleanup;
11379 int retcode, fd, remote_errno, bytes, io_size;
11380 FILE *file;
11381 gdb_byte *buffer;
11382 int bytes_in_buffer;
11383 int saw_eof;
11384 ULONGEST offset;
5d93a237 11385 struct remote_state *rs = get_remote_state ();
a6b151f1 11386
5d93a237 11387 if (!rs->remote_desc)
a6b151f1
DJ
11388 error (_("command can only be used with remote target"));
11389
614c279d 11390 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11391 if (file == NULL)
11392 perror_with_name (local_file);
7c8a8b04 11393 back_to = make_cleanup_fclose (file);
a6b151f1 11394
07c138c8 11395 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11396 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11397 | FILEIO_O_TRUNC),
4313b8c0 11398 0700, 0, &remote_errno);
a6b151f1
DJ
11399 if (fd == -1)
11400 remote_hostio_error (remote_errno);
11401
11402 /* Send up to this many bytes at once. They won't all fit in the
11403 remote packet limit, so we'll transfer slightly fewer. */
11404 io_size = get_remote_packet_size ();
224c3ddb 11405 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11406 make_cleanup (xfree, buffer);
11407
11408 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11409
11410 bytes_in_buffer = 0;
11411 saw_eof = 0;
11412 offset = 0;
11413 while (bytes_in_buffer || !saw_eof)
11414 {
11415 if (!saw_eof)
11416 {
3e43a32a
MS
11417 bytes = fread (buffer + bytes_in_buffer, 1,
11418 io_size - bytes_in_buffer,
a6b151f1
DJ
11419 file);
11420 if (bytes == 0)
11421 {
11422 if (ferror (file))
11423 error (_("Error reading %s."), local_file);
11424 else
11425 {
11426 /* EOF. Unless there is something still in the
11427 buffer from the last iteration, we are done. */
11428 saw_eof = 1;
11429 if (bytes_in_buffer == 0)
11430 break;
11431 }
11432 }
11433 }
11434 else
11435 bytes = 0;
11436
11437 bytes += bytes_in_buffer;
11438 bytes_in_buffer = 0;
11439
0d866f62
TT
11440 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11441 fd, buffer, bytes,
3e43a32a 11442 offset, &remote_errno);
a6b151f1
DJ
11443
11444 if (retcode < 0)
11445 remote_hostio_error (remote_errno);
11446 else if (retcode == 0)
11447 error (_("Remote write of %d bytes returned 0!"), bytes);
11448 else if (retcode < bytes)
11449 {
11450 /* Short write. Save the rest of the read data for the next
11451 write. */
11452 bytes_in_buffer = bytes - retcode;
11453 memmove (buffer, buffer + retcode, bytes_in_buffer);
11454 }
11455
11456 offset += retcode;
11457 }
11458
11459 discard_cleanups (close_cleanup);
df39ea25 11460 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11461 remote_hostio_error (remote_errno);
11462
11463 if (from_tty)
11464 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11465 do_cleanups (back_to);
11466}
11467
11468void
11469remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11470{
11471 struct cleanup *back_to, *close_cleanup;
cea39f65 11472 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11473 FILE *file;
11474 gdb_byte *buffer;
11475 ULONGEST offset;
5d93a237 11476 struct remote_state *rs = get_remote_state ();
a6b151f1 11477
5d93a237 11478 if (!rs->remote_desc)
a6b151f1
DJ
11479 error (_("command can only be used with remote target"));
11480
07c138c8 11481 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11482 remote_file, FILEIO_O_RDONLY, 0, 0,
11483 &remote_errno);
a6b151f1
DJ
11484 if (fd == -1)
11485 remote_hostio_error (remote_errno);
11486
614c279d 11487 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11488 if (file == NULL)
11489 perror_with_name (local_file);
7c8a8b04 11490 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11491
11492 /* Send up to this many bytes at once. They won't all fit in the
11493 remote packet limit, so we'll transfer slightly fewer. */
11494 io_size = get_remote_packet_size ();
224c3ddb 11495 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11496 make_cleanup (xfree, buffer);
11497
11498 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11499
11500 offset = 0;
11501 while (1)
11502 {
a3be983c
TT
11503 bytes = remote_hostio_pread (find_target_at (process_stratum),
11504 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11505 if (bytes == 0)
11506 /* Success, but no bytes, means end-of-file. */
11507 break;
11508 if (bytes == -1)
11509 remote_hostio_error (remote_errno);
11510
11511 offset += bytes;
11512
11513 bytes = fwrite (buffer, 1, bytes, file);
11514 if (bytes == 0)
11515 perror_with_name (local_file);
11516 }
11517
11518 discard_cleanups (close_cleanup);
df39ea25 11519 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11520 remote_hostio_error (remote_errno);
11521
11522 if (from_tty)
11523 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11524 do_cleanups (back_to);
11525}
11526
11527void
11528remote_file_delete (const char *remote_file, int from_tty)
11529{
11530 int retcode, remote_errno;
5d93a237 11531 struct remote_state *rs = get_remote_state ();
a6b151f1 11532
5d93a237 11533 if (!rs->remote_desc)
a6b151f1
DJ
11534 error (_("command can only be used with remote target"));
11535
dbbca37d 11536 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11537 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11538 if (retcode == -1)
11539 remote_hostio_error (remote_errno);
11540
11541 if (from_tty)
11542 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11543}
11544
11545static void
11546remote_put_command (char *args, int from_tty)
11547{
11548 struct cleanup *back_to;
11549 char **argv;
11550
d1a41061
PP
11551 if (args == NULL)
11552 error_no_arg (_("file to put"));
11553
11554 argv = gdb_buildargv (args);
a6b151f1
DJ
11555 back_to = make_cleanup_freeargv (argv);
11556 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11557 error (_("Invalid parameters to remote put"));
11558
11559 remote_file_put (argv[0], argv[1], from_tty);
11560
11561 do_cleanups (back_to);
11562}
11563
11564static void
11565remote_get_command (char *args, int from_tty)
11566{
11567 struct cleanup *back_to;
11568 char **argv;
11569
d1a41061
PP
11570 if (args == NULL)
11571 error_no_arg (_("file to get"));
11572
11573 argv = gdb_buildargv (args);
a6b151f1
DJ
11574 back_to = make_cleanup_freeargv (argv);
11575 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11576 error (_("Invalid parameters to remote get"));
11577
11578 remote_file_get (argv[0], argv[1], from_tty);
11579
11580 do_cleanups (back_to);
11581}
11582
11583static void
11584remote_delete_command (char *args, int from_tty)
11585{
11586 struct cleanup *back_to;
11587 char **argv;
11588
d1a41061
PP
11589 if (args == NULL)
11590 error_no_arg (_("file to delete"));
11591
11592 argv = gdb_buildargv (args);
a6b151f1
DJ
11593 back_to = make_cleanup_freeargv (argv);
11594 if (argv[0] == NULL || argv[1] != NULL)
11595 error (_("Invalid parameters to remote delete"));
11596
11597 remote_file_delete (argv[0], from_tty);
11598
11599 do_cleanups (back_to);
11600}
11601
11602static void
11603remote_command (char *args, int from_tty)
11604{
635c7e8a 11605 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11606}
11607
b2175913 11608static int
19db3e69 11609remote_can_execute_reverse (struct target_ops *self)
b2175913 11610{
4082afcc
PA
11611 if (packet_support (PACKET_bs) == PACKET_ENABLE
11612 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11613 return 1;
11614 else
11615 return 0;
b2175913
MS
11616}
11617
74531fed 11618static int
2a9a2795 11619remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11620{
11621 return 1;
11622}
11623
03583c20 11624static int
2bfc0540 11625remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11626{
11627 /* Only supported in extended mode. */
11628 return 0;
11629}
11630
8a305172 11631static int
86ce2668 11632remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11633{
11634 struct remote_state *rs = get_remote_state ();
a744cf53 11635
901f9912
UW
11636 /* Only extended-remote handles being attached to multiple
11637 processes, even though plain remote can use the multi-process
11638 thread id extensions, so that GDB knows the target process's
11639 PID. */
11640 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
11641}
11642
70221824 11643static int
782b2b07
SS
11644remote_supports_cond_tracepoints (void)
11645{
4082afcc 11646 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11647}
11648
3788aec7 11649static int
efcc2da7 11650remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11651{
4082afcc 11652 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11653}
11654
70221824 11655static int
7a697b8d
SS
11656remote_supports_fast_tracepoints (void)
11657{
4082afcc 11658 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11659}
11660
0fb4aa4b
PA
11661static int
11662remote_supports_static_tracepoints (void)
11663{
4082afcc 11664 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11665}
11666
1e4d1764
YQ
11667static int
11668remote_supports_install_in_trace (void)
11669{
4082afcc 11670 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11671}
11672
d248b706 11673static int
7d178d6a 11674remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11675{
4082afcc
PA
11676 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11677 == PACKET_ENABLE);
d248b706
KY
11678}
11679
3065dfb6 11680static int
6de37a3a 11681remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11682{
4082afcc 11683 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11684}
11685
d3ce09f5 11686static int
78eff0ec 11687remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11688{
4082afcc 11689 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11690}
11691
35b1e5cc 11692static void
ecae04e1 11693remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11694{
11695 putpkt ("QTinit");
11696 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11697 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11698 error (_("Target does not support this command."));
11699}
11700
11701static void free_actions_list (char **actions_list);
11702static void free_actions_list_cleanup_wrapper (void *);
11703static void
11704free_actions_list_cleanup_wrapper (void *al)
11705{
19ba03f4 11706 free_actions_list ((char **) al);
35b1e5cc
SS
11707}
11708
11709static void
11710free_actions_list (char **actions_list)
11711{
11712 int ndx;
11713
11714 if (actions_list == 0)
11715 return;
11716
11717 for (ndx = 0; actions_list[ndx]; ndx++)
11718 xfree (actions_list[ndx]);
11719
11720 xfree (actions_list);
11721}
11722
409873ef
SS
11723/* Recursive routine to walk through command list including loops, and
11724 download packets for each command. */
11725
11726static void
11727remote_download_command_source (int num, ULONGEST addr,
11728 struct command_line *cmds)
11729{
11730 struct remote_state *rs = get_remote_state ();
11731 struct command_line *cmd;
11732
11733 for (cmd = cmds; cmd; cmd = cmd->next)
11734 {
0df8b418 11735 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11736 strcpy (rs->buf, "QTDPsrc:");
11737 encode_source_string (num, addr, "cmd", cmd->line,
11738 rs->buf + strlen (rs->buf),
11739 rs->buf_size - strlen (rs->buf));
11740 putpkt (rs->buf);
11741 remote_get_noisy_reply (&target_buf, &target_buf_size);
11742 if (strcmp (target_buf, "OK"))
11743 warning (_("Target does not support source download."));
11744
11745 if (cmd->control_type == while_control
11746 || cmd->control_type == while_stepping_control)
11747 {
11748 remote_download_command_source (num, addr, *cmd->body_list);
11749
0df8b418 11750 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11751 strcpy (rs->buf, "QTDPsrc:");
11752 encode_source_string (num, addr, "cmd", "end",
11753 rs->buf + strlen (rs->buf),
11754 rs->buf_size - strlen (rs->buf));
11755 putpkt (rs->buf);
11756 remote_get_noisy_reply (&target_buf, &target_buf_size);
11757 if (strcmp (target_buf, "OK"))
11758 warning (_("Target does not support source download."));
11759 }
11760 }
11761}
11762
35b1e5cc 11763static void
548f7808 11764remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11765{
bba74b36 11766#define BUF_SIZE 2048
e8ba3115 11767
35b1e5cc 11768 CORE_ADDR tpaddr;
409873ef 11769 char addrbuf[40];
bba74b36 11770 char buf[BUF_SIZE];
35b1e5cc
SS
11771 char **tdp_actions;
11772 char **stepping_actions;
11773 int ndx;
11774 struct cleanup *old_chain = NULL;
11775 struct agent_expr *aexpr;
11776 struct cleanup *aexpr_chain = NULL;
11777 char *pkt;
e8ba3115 11778 struct breakpoint *b = loc->owner;
d9b3f62e 11779 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11780
dc673c81 11781 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11782 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11783 tdp_actions);
11784 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11785 stepping_actions);
11786
11787 tpaddr = loc->address;
11788 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11789 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11790 addrbuf, /* address */
11791 (b->enable_state == bp_enabled ? 'E' : 'D'),
11792 t->step_count, t->pass_count);
e8ba3115
YQ
11793 /* Fast tracepoints are mostly handled by the target, but we can
11794 tell the target how big of an instruction block should be moved
11795 around. */
11796 if (b->type == bp_fast_tracepoint)
11797 {
11798 /* Only test for support at download time; we may not know
11799 target capabilities at definition time. */
11800 if (remote_supports_fast_tracepoints ())
35b1e5cc 11801 {
6b940e6a
PL
11802 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11803 NULL))
bba74b36 11804 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11805 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11806 else
e8ba3115
YQ
11807 /* If it passed validation at definition but fails now,
11808 something is very wrong. */
11809 internal_error (__FILE__, __LINE__,
11810 _("Fast tracepoint not "
11811 "valid during download"));
35b1e5cc 11812 }
e8ba3115
YQ
11813 else
11814 /* Fast tracepoints are functionally identical to regular
11815 tracepoints, so don't take lack of support as a reason to
11816 give up on the trace run. */
11817 warning (_("Target does not support fast tracepoints, "
11818 "downloading %d as regular tracepoint"), b->number);
11819 }
11820 else if (b->type == bp_static_tracepoint)
11821 {
11822 /* Only test for support at download time; we may not know
11823 target capabilities at definition time. */
11824 if (remote_supports_static_tracepoints ())
0fb4aa4b 11825 {
e8ba3115 11826 struct static_tracepoint_marker marker;
0fb4aa4b 11827
e8ba3115
YQ
11828 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11829 strcat (buf, ":S");
0fb4aa4b 11830 else
e8ba3115 11831 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11832 }
e8ba3115
YQ
11833 else
11834 /* Fast tracepoints are functionally identical to regular
11835 tracepoints, so don't take lack of support as a reason
11836 to give up on the trace run. */
11837 error (_("Target does not support static tracepoints"));
11838 }
11839 /* If the tracepoint has a conditional, make it into an agent
11840 expression and append to the definition. */
11841 if (loc->cond)
11842 {
11843 /* Only test support at download time, we may not know target
11844 capabilities at definition time. */
11845 if (remote_supports_cond_tracepoints ())
35b1e5cc 11846 {
e8ba3115
YQ
11847 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11848 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11849 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11850 aexpr->len);
e8ba3115
YQ
11851 pkt = buf + strlen (buf);
11852 for (ndx = 0; ndx < aexpr->len; ++ndx)
11853 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11854 *pkt = '\0';
11855 do_cleanups (aexpr_chain);
35b1e5cc 11856 }
e8ba3115
YQ
11857 else
11858 warning (_("Target does not support conditional tracepoints, "
11859 "ignoring tp %d cond"), b->number);
11860 }
35b1e5cc 11861
d9b3f62e 11862 if (b->commands || *default_collect)
e8ba3115
YQ
11863 strcat (buf, "-");
11864 putpkt (buf);
11865 remote_get_noisy_reply (&target_buf, &target_buf_size);
11866 if (strcmp (target_buf, "OK"))
11867 error (_("Target does not support tracepoints."));
35b1e5cc 11868
e8ba3115
YQ
11869 /* do_single_steps (t); */
11870 if (tdp_actions)
11871 {
11872 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11873 {
e8ba3115 11874 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11875 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11876 b->number, addrbuf, /* address */
11877 tdp_actions[ndx],
11878 ((tdp_actions[ndx + 1] || stepping_actions)
11879 ? '-' : 0));
e8ba3115
YQ
11880 putpkt (buf);
11881 remote_get_noisy_reply (&target_buf,
11882 &target_buf_size);
11883 if (strcmp (target_buf, "OK"))
11884 error (_("Error on target while setting tracepoints."));
35b1e5cc 11885 }
e8ba3115
YQ
11886 }
11887 if (stepping_actions)
11888 {
11889 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11890 {
e8ba3115 11891 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11892 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11893 b->number, addrbuf, /* address */
11894 ((ndx == 0) ? "S" : ""),
11895 stepping_actions[ndx],
11896 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11897 putpkt (buf);
11898 remote_get_noisy_reply (&target_buf,
11899 &target_buf_size);
11900 if (strcmp (target_buf, "OK"))
11901 error (_("Error on target while setting tracepoints."));
35b1e5cc 11902 }
e8ba3115 11903 }
409873ef 11904
4082afcc 11905 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11906 {
f00aae0f 11907 if (b->location != NULL)
409873ef 11908 {
e8ba3115 11909 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11910 encode_source_string (b->number, loc->address, "at",
11911 event_location_to_string (b->location),
11912 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11913 putpkt (buf);
11914 remote_get_noisy_reply (&target_buf, &target_buf_size);
11915 if (strcmp (target_buf, "OK"))
11916 warning (_("Target does not support source download."));
409873ef 11917 }
e8ba3115
YQ
11918 if (b->cond_string)
11919 {
11920 strcpy (buf, "QTDPsrc:");
11921 encode_source_string (b->number, loc->address,
11922 "cond", b->cond_string, buf + strlen (buf),
11923 2048 - strlen (buf));
11924 putpkt (buf);
11925 remote_get_noisy_reply (&target_buf, &target_buf_size);
11926 if (strcmp (target_buf, "OK"))
11927 warning (_("Target does not support source download."));
11928 }
11929 remote_download_command_source (b->number, loc->address,
11930 breakpoint_commands (b));
35b1e5cc 11931 }
e8ba3115
YQ
11932
11933 do_cleanups (old_chain);
35b1e5cc
SS
11934}
11935
1e4d1764 11936static int
a52a8357 11937remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 11938{
1e51243a
PA
11939 struct remote_state *rs = get_remote_state ();
11940 struct trace_status *ts;
11941 int status;
11942
11943 /* Don't try to install tracepoints until we've relocated our
11944 symbols, and fetched and merged the target's tracepoint list with
11945 ours. */
11946 if (rs->starting_up)
11947 return 0;
11948
11949 ts = current_trace_status ();
8bd200f1 11950 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
11951
11952 if (status == -1 || !ts->running_known || !ts->running)
11953 return 0;
11954
11955 /* If we are in a tracing experiment, but remote stub doesn't support
11956 installing tracepoint in trace, we have to return. */
11957 if (!remote_supports_install_in_trace ())
11958 return 0;
11959
11960 return 1;
11961}
11962
11963
35b1e5cc 11964static void
559d2b81
TT
11965remote_download_trace_state_variable (struct target_ops *self,
11966 struct trace_state_variable *tsv)
35b1e5cc
SS
11967{
11968 struct remote_state *rs = get_remote_state ();
00bf0b85 11969 char *p;
35b1e5cc 11970
bba74b36
YQ
11971 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11972 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11973 tsv->builtin);
00bf0b85
SS
11974 p = rs->buf + strlen (rs->buf);
11975 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11976 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 11977 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 11978 *p++ = '\0';
35b1e5cc
SS
11979 putpkt (rs->buf);
11980 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11981 if (*target_buf == '\0')
11982 error (_("Target does not support this command."));
11983 if (strcmp (target_buf, "OK") != 0)
11984 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
11985}
11986
d248b706 11987static void
46670d57
TT
11988remote_enable_tracepoint (struct target_ops *self,
11989 struct bp_location *location)
d248b706
KY
11990{
11991 struct remote_state *rs = get_remote_state ();
11992 char addr_buf[40];
11993
11994 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11995 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11996 location->owner->number, addr_buf);
d248b706
KY
11997 putpkt (rs->buf);
11998 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11999 if (*rs->buf == '\0')
12000 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12001 if (strcmp (rs->buf, "OK") != 0)
12002 error (_("Error on target while enabling tracepoint."));
12003}
12004
12005static void
780b049c
TT
12006remote_disable_tracepoint (struct target_ops *self,
12007 struct bp_location *location)
d248b706
KY
12008{
12009 struct remote_state *rs = get_remote_state ();
12010 char addr_buf[40];
12011
12012 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12013 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12014 location->owner->number, addr_buf);
d248b706
KY
12015 putpkt (rs->buf);
12016 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12017 if (*rs->buf == '\0')
12018 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12019 if (strcmp (rs->buf, "OK") != 0)
12020 error (_("Error on target while disabling tracepoint."));
12021}
12022
35b1e5cc 12023static void
583f9a86 12024remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12025{
12026 asection *s;
81b9b86e 12027 bfd *abfd = NULL;
35b1e5cc 12028 bfd_size_type size;
608bcef2 12029 bfd_vma vma;
35b1e5cc 12030 int anysecs = 0;
c2fa21f1 12031 int offset = 0;
35b1e5cc
SS
12032
12033 if (!exec_bfd)
12034 return; /* No information to give. */
12035
12036 strcpy (target_buf, "QTro");
9779ab84 12037 offset = strlen (target_buf);
35b1e5cc
SS
12038 for (s = exec_bfd->sections; s; s = s->next)
12039 {
12040 char tmp1[40], tmp2[40];
c2fa21f1 12041 int sec_length;
35b1e5cc
SS
12042
12043 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12044 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12045 (s->flags & SEC_READONLY) == 0)
12046 continue;
12047
12048 anysecs = 1;
81b9b86e 12049 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12050 size = bfd_get_section_size (s);
608bcef2
HZ
12051 sprintf_vma (tmp1, vma);
12052 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12053 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12054 if (offset + sec_length + 1 > target_buf_size)
12055 {
4082afcc 12056 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12057 warning (_("\
c2fa21f1
HZ
12058Too many sections for read-only sections definition packet."));
12059 break;
12060 }
bba74b36
YQ
12061 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12062 tmp1, tmp2);
c2fa21f1 12063 offset += sec_length;
35b1e5cc
SS
12064 }
12065 if (anysecs)
12066 {
12067 putpkt (target_buf);
12068 getpkt (&target_buf, &target_buf_size, 0);
12069 }
12070}
12071
12072static void
e2d1aae3 12073remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12074{
12075 putpkt ("QTStart");
12076 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12077 if (*target_buf == '\0')
12078 error (_("Target does not support this command."));
12079 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12080 error (_("Bogus reply from target: %s"), target_buf);
12081}
12082
12083static int
8bd200f1 12084remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12085{
953b98d1 12086 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12087 char *p = NULL;
0df8b418 12088 /* FIXME we need to get register block size some other way. */
00bf0b85 12089 extern int trace_regblock_size;
bd3eecc3
PA
12090 enum packet_result result;
12091
4082afcc 12092 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12093 return -1;
a744cf53 12094
00bf0b85
SS
12095 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12096
049dc89b
JK
12097 putpkt ("qTStatus");
12098
492d29ea 12099 TRY
67f41397
JK
12100 {
12101 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12102 }
492d29ea 12103 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12104 {
598d3636
JK
12105 if (ex.error != TARGET_CLOSE_ERROR)
12106 {
12107 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12108 return -1;
12109 }
12110 throw_exception (ex);
67f41397 12111 }
492d29ea 12112 END_CATCH
00bf0b85 12113
bd3eecc3
PA
12114 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12115
00bf0b85 12116 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12117 if (result == PACKET_UNKNOWN)
00bf0b85 12118 return -1;
35b1e5cc 12119
00bf0b85 12120 /* We're working with a live target. */
f5911ea1 12121 ts->filename = NULL;
00bf0b85 12122
00bf0b85 12123 if (*p++ != 'T')
35b1e5cc
SS
12124 error (_("Bogus trace status reply from target: %s"), target_buf);
12125
84cebc4a
YQ
12126 /* Function 'parse_trace_status' sets default value of each field of
12127 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12128 parse_trace_status (p, ts);
12129
12130 return ts->running;
35b1e5cc
SS
12131}
12132
70221824 12133static void
db90e85c 12134remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12135 struct uploaded_tp *utp)
12136{
12137 struct remote_state *rs = get_remote_state ();
f196051f
SS
12138 char *reply;
12139 struct bp_location *loc;
12140 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12141 size_t size = get_remote_packet_size ();
f196051f
SS
12142
12143 if (tp)
12144 {
12145 tp->base.hit_count = 0;
12146 tp->traceframe_usage = 0;
12147 for (loc = tp->base.loc; loc; loc = loc->next)
12148 {
12149 /* If the tracepoint was never downloaded, don't go asking for
12150 any status. */
12151 if (tp->number_on_target == 0)
12152 continue;
bba74b36
YQ
12153 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12154 phex_nz (loc->address, 0));
f196051f
SS
12155 putpkt (rs->buf);
12156 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12157 if (reply && *reply)
12158 {
12159 if (*reply == 'V')
12160 parse_tracepoint_status (reply + 1, bp, utp);
12161 }
12162 }
12163 }
12164 else if (utp)
12165 {
12166 utp->hit_count = 0;
12167 utp->traceframe_usage = 0;
bba74b36
YQ
12168 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12169 phex_nz (utp->addr, 0));
f196051f
SS
12170 putpkt (rs->buf);
12171 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12172 if (reply && *reply)
12173 {
12174 if (*reply == 'V')
12175 parse_tracepoint_status (reply + 1, bp, utp);
12176 }
12177 }
12178}
12179
35b1e5cc 12180static void
74499f1b 12181remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12182{
12183 putpkt ("QTStop");
12184 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12185 if (*target_buf == '\0')
12186 error (_("Target does not support this command."));
12187 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12188 error (_("Bogus reply from target: %s"), target_buf);
12189}
12190
12191static int
bd4c6793
TT
12192remote_trace_find (struct target_ops *self,
12193 enum trace_find_type type, int num,
cc5925ad 12194 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12195 int *tpp)
12196{
12197 struct remote_state *rs = get_remote_state ();
bba74b36 12198 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12199 char *p, *reply;
12200 int target_frameno = -1, target_tracept = -1;
12201
e6e4e701
PA
12202 /* Lookups other than by absolute frame number depend on the current
12203 trace selected, so make sure it is correct on the remote end
12204 first. */
12205 if (type != tfind_number)
12206 set_remote_traceframe ();
12207
35b1e5cc
SS
12208 p = rs->buf;
12209 strcpy (p, "QTFrame:");
12210 p = strchr (p, '\0');
12211 switch (type)
12212 {
12213 case tfind_number:
bba74b36 12214 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12215 break;
12216 case tfind_pc:
bba74b36 12217 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12218 break;
12219 case tfind_tp:
bba74b36 12220 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12221 break;
12222 case tfind_range:
bba74b36
YQ
12223 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12224 phex_nz (addr2, 0));
35b1e5cc
SS
12225 break;
12226 case tfind_outside:
bba74b36
YQ
12227 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12228 phex_nz (addr2, 0));
35b1e5cc
SS
12229 break;
12230 default:
9b20d036 12231 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12232 }
12233
12234 putpkt (rs->buf);
2f65bcb7 12235 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12236 if (*reply == '\0')
12237 error (_("Target does not support this command."));
35b1e5cc
SS
12238
12239 while (reply && *reply)
12240 switch (*reply)
12241 {
12242 case 'F':
f197e0f1
VP
12243 p = ++reply;
12244 target_frameno = (int) strtol (p, &reply, 16);
12245 if (reply == p)
12246 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12247 /* Don't update our remote traceframe number cache on failure
12248 to select a remote traceframe. */
f197e0f1
VP
12249 if (target_frameno == -1)
12250 return -1;
35b1e5cc
SS
12251 break;
12252 case 'T':
f197e0f1
VP
12253 p = ++reply;
12254 target_tracept = (int) strtol (p, &reply, 16);
12255 if (reply == p)
12256 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12257 break;
12258 case 'O': /* "OK"? */
12259 if (reply[1] == 'K' && reply[2] == '\0')
12260 reply += 2;
12261 else
12262 error (_("Bogus reply from target: %s"), reply);
12263 break;
12264 default:
12265 error (_("Bogus reply from target: %s"), reply);
12266 }
12267 if (tpp)
12268 *tpp = target_tracept;
e6e4e701 12269
262e1174 12270 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12271 return target_frameno;
12272}
12273
12274static int
4011015b
TT
12275remote_get_trace_state_variable_value (struct target_ops *self,
12276 int tsvnum, LONGEST *val)
35b1e5cc
SS
12277{
12278 struct remote_state *rs = get_remote_state ();
12279 char *reply;
12280 ULONGEST uval;
12281
e6e4e701
PA
12282 set_remote_traceframe ();
12283
bba74b36 12284 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12285 putpkt (rs->buf);
12286 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12287 if (reply && *reply)
12288 {
12289 if (*reply == 'V')
12290 {
12291 unpack_varlen_hex (reply + 1, &uval);
12292 *val = (LONGEST) uval;
12293 return 1;
12294 }
12295 }
12296 return 0;
12297}
12298
00bf0b85 12299static int
dc3decaf 12300remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12301{
12302 struct remote_state *rs = get_remote_state ();
12303 char *p, *reply;
12304
12305 p = rs->buf;
12306 strcpy (p, "QTSave:");
12307 p += strlen (p);
12308 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12309 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12310 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12311 *p++ = '\0';
12312 putpkt (rs->buf);
ad91cd99 12313 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12314 if (*reply == '\0')
ad91cd99
PA
12315 error (_("Target does not support this command."));
12316 if (strcmp (reply, "OK") != 0)
12317 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12318 return 0;
12319}
12320
12321/* This is basically a memory transfer, but needs to be its own packet
12322 because we don't know how the target actually organizes its trace
12323 memory, plus we want to be able to ask for as much as possible, but
12324 not be unhappy if we don't get as much as we ask for. */
12325
12326static LONGEST
88ee6f45
TT
12327remote_get_raw_trace_data (struct target_ops *self,
12328 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12329{
12330 struct remote_state *rs = get_remote_state ();
12331 char *reply;
12332 char *p;
12333 int rslt;
12334
12335 p = rs->buf;
12336 strcpy (p, "qTBuffer:");
12337 p += strlen (p);
12338 p += hexnumstr (p, offset);
12339 *p++ = ',';
12340 p += hexnumstr (p, len);
12341 *p++ = '\0';
12342
12343 putpkt (rs->buf);
12344 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12345 if (reply && *reply)
12346 {
12347 /* 'l' by itself means we're at the end of the buffer and
12348 there is nothing more to get. */
12349 if (*reply == 'l')
12350 return 0;
12351
12352 /* Convert the reply into binary. Limit the number of bytes to
12353 convert according to our passed-in buffer size, rather than
12354 what was returned in the packet; if the target is
12355 unexpectedly generous and gives us a bigger reply than we
12356 asked for, we don't want to crash. */
12357 rslt = hex2bin (target_buf, buf, len);
12358 return rslt;
12359 }
12360
12361 /* Something went wrong, flag as an error. */
12362 return -1;
12363}
12364
35b1e5cc 12365static void
37b25738 12366remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12367{
12368 struct remote_state *rs = get_remote_state ();
12369
4082afcc 12370 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12371 {
ad91cd99
PA
12372 char *reply;
12373
bba74b36 12374 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12375 putpkt (rs->buf);
ad91cd99
PA
12376 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12377 if (*reply == '\0')
33da3f1c 12378 error (_("Target does not support this command."));
ad91cd99
PA
12379 if (strcmp (reply, "OK") != 0)
12380 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12381 }
12382 else if (val)
12383 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12384}
12385
dc146f7c
VP
12386static int
12387remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12388{
12389 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12390
fe978cb0
PA
12391 if (info && info->priv)
12392 return info->priv->core;
dc146f7c
VP
12393 return -1;
12394}
12395
4daf5ac0 12396static void
736d5b1f 12397remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12398{
12399 struct remote_state *rs = get_remote_state ();
ad91cd99 12400 char *reply;
4daf5ac0 12401
bba74b36 12402 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12403 putpkt (rs->buf);
ad91cd99
PA
12404 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12405 if (*reply == '\0')
4daf5ac0 12406 error (_("Target does not support this command."));
ad91cd99
PA
12407 if (strcmp (reply, "OK") != 0)
12408 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12409}
12410
b3b9301e 12411static struct traceframe_info *
a893e81f 12412remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12413{
12414 char *text;
12415
12416 text = target_read_stralloc (&current_target,
12417 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12418 if (text != NULL)
12419 {
12420 struct traceframe_info *info;
12421 struct cleanup *back_to = make_cleanup (xfree, text);
12422
12423 info = parse_traceframe_info (text);
12424 do_cleanups (back_to);
12425 return info;
12426 }
12427
12428 return NULL;
12429}
12430
405f8e94
SS
12431/* Handle the qTMinFTPILen packet. Returns the minimum length of
12432 instruction on which a fast tracepoint may be placed. Returns -1
12433 if the packet is not supported, and 0 if the minimum instruction
12434 length is unknown. */
12435
12436static int
0e67620a 12437remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12438{
12439 struct remote_state *rs = get_remote_state ();
12440 char *reply;
12441
e886a173
PA
12442 /* If we're not debugging a process yet, the IPA can't be
12443 loaded. */
12444 if (!target_has_execution)
12445 return 0;
12446
12447 /* Make sure the remote is pointing at the right process. */
12448 set_general_process ();
12449
bba74b36 12450 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12451 putpkt (rs->buf);
12452 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12453 if (*reply == '\0')
12454 return -1;
12455 else
12456 {
12457 ULONGEST min_insn_len;
12458
12459 unpack_varlen_hex (reply, &min_insn_len);
12460
12461 return (int) min_insn_len;
12462 }
12463}
12464
f6f899bf 12465static void
4da384be 12466remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12467{
4082afcc 12468 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12469 {
12470 struct remote_state *rs = get_remote_state ();
12471 char *buf = rs->buf;
12472 char *endbuf = rs->buf + get_remote_packet_size ();
12473 enum packet_result result;
12474
12475 gdb_assert (val >= 0 || val == -1);
12476 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12477 /* Send -1 as literal "-1" to avoid host size dependency. */
12478 if (val < 0)
12479 {
12480 *buf++ = '-';
12481 buf += hexnumstr (buf, (ULONGEST) -val);
12482 }
12483 else
12484 buf += hexnumstr (buf, (ULONGEST) val);
12485
12486 putpkt (rs->buf);
12487 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12488 result = packet_ok (rs->buf,
12489 &remote_protocol_packets[PACKET_QTBuffer_size]);
12490
12491 if (result != PACKET_OK)
12492 warning (_("Bogus reply from target: %s"), rs->buf);
12493 }
12494}
12495
f196051f 12496static int
d9e68a2c
TT
12497remote_set_trace_notes (struct target_ops *self,
12498 const char *user, const char *notes,
ca623f82 12499 const char *stop_notes)
f196051f
SS
12500{
12501 struct remote_state *rs = get_remote_state ();
12502 char *reply;
12503 char *buf = rs->buf;
12504 char *endbuf = rs->buf + get_remote_packet_size ();
12505 int nbytes;
12506
12507 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12508 if (user)
12509 {
12510 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12511 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12512 buf += 2 * nbytes;
12513 *buf++ = ';';
12514 }
12515 if (notes)
12516 {
12517 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12518 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12519 buf += 2 * nbytes;
12520 *buf++ = ';';
12521 }
12522 if (stop_notes)
12523 {
12524 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12525 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12526 buf += 2 * nbytes;
12527 *buf++ = ';';
12528 }
12529 /* Ensure the buffer is terminated. */
12530 *buf = '\0';
12531
12532 putpkt (rs->buf);
12533 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12534 if (*reply == '\0')
12535 return 0;
12536
12537 if (strcmp (reply, "OK") != 0)
12538 error (_("Bogus reply from target: %s"), reply);
12539
12540 return 1;
12541}
12542
d1feda86 12543static int
2c152180 12544remote_use_agent (struct target_ops *self, int use)
d1feda86 12545{
4082afcc 12546 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12547 {
12548 struct remote_state *rs = get_remote_state ();
12549
12550 /* If the stub supports QAgent. */
bba74b36 12551 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12552 putpkt (rs->buf);
12553 getpkt (&rs->buf, &rs->buf_size, 0);
12554
12555 if (strcmp (rs->buf, "OK") == 0)
12556 {
12557 use_agent = use;
12558 return 1;
12559 }
12560 }
12561
12562 return 0;
12563}
12564
12565static int
fe38f897 12566remote_can_use_agent (struct target_ops *self)
d1feda86 12567{
4082afcc 12568 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12569}
12570
9accd112
MM
12571struct btrace_target_info
12572{
12573 /* The ptid of the traced thread. */
12574 ptid_t ptid;
f4abbc16
MM
12575
12576 /* The obtained branch trace configuration. */
12577 struct btrace_config conf;
9accd112
MM
12578};
12579
f4abbc16
MM
12580/* Reset our idea of our target's btrace configuration. */
12581
12582static void
12583remote_btrace_reset (void)
12584{
12585 struct remote_state *rs = get_remote_state ();
12586
12587 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12588}
12589
9accd112
MM
12590/* Check whether the target supports branch tracing. */
12591
12592static int
043c3577 12593remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12594{
4082afcc 12595 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12596 return 0;
4082afcc 12597 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12598 return 0;
12599
043c3577
MM
12600 switch (format)
12601 {
12602 case BTRACE_FORMAT_NONE:
12603 return 0;
12604
12605 case BTRACE_FORMAT_BTS:
12606 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12607
12608 case BTRACE_FORMAT_PT:
12609 /* The trace is decoded on the host. Even if our target supports it,
12610 we still need to have libipt to decode the trace. */
12611#if defined (HAVE_LIBIPT)
12612 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12613#else /* !defined (HAVE_LIBIPT) */
12614 return 0;
12615#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12616 }
12617
12618 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12619}
12620
f4abbc16
MM
12621/* Synchronize the configuration with the target. */
12622
12623static void
12624btrace_sync_conf (const struct btrace_config *conf)
12625{
d33501a5
MM
12626 struct packet_config *packet;
12627 struct remote_state *rs;
12628 char *buf, *pos, *endbuf;
12629
12630 rs = get_remote_state ();
12631 buf = rs->buf;
12632 endbuf = buf + get_remote_packet_size ();
12633
12634 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12635 if (packet_config_support (packet) == PACKET_ENABLE
12636 && conf->bts.size != rs->btrace_config.bts.size)
12637 {
12638 pos = buf;
12639 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12640 conf->bts.size);
12641
12642 putpkt (buf);
12643 getpkt (&buf, &rs->buf_size, 0);
12644
12645 if (packet_ok (buf, packet) == PACKET_ERROR)
12646 {
12647 if (buf[0] == 'E' && buf[1] == '.')
12648 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12649 else
12650 error (_("Failed to configure the BTS buffer size."));
12651 }
12652
12653 rs->btrace_config.bts.size = conf->bts.size;
12654 }
b20a6524
MM
12655
12656 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12657 if (packet_config_support (packet) == PACKET_ENABLE
12658 && conf->pt.size != rs->btrace_config.pt.size)
12659 {
12660 pos = buf;
12661 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12662 conf->pt.size);
12663
12664 putpkt (buf);
12665 getpkt (&buf, &rs->buf_size, 0);
12666
12667 if (packet_ok (buf, packet) == PACKET_ERROR)
12668 {
12669 if (buf[0] == 'E' && buf[1] == '.')
12670 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12671 else
12672 error (_("Failed to configure the trace buffer size."));
12673 }
12674
12675 rs->btrace_config.pt.size = conf->pt.size;
12676 }
f4abbc16
MM
12677}
12678
12679/* Read the current thread's btrace configuration from the target and
12680 store it into CONF. */
12681
12682static void
12683btrace_read_config (struct btrace_config *conf)
12684{
12685 char *xml;
12686
12687 xml = target_read_stralloc (&current_target,
b20a6524 12688 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12689 if (xml != NULL)
12690 {
12691 struct cleanup *cleanup;
12692
12693 cleanup = make_cleanup (xfree, xml);
12694 parse_xml_btrace_conf (conf, xml);
12695 do_cleanups (cleanup);
12696 }
12697}
12698
9accd112
MM
12699/* Enable branch tracing. */
12700
12701static struct btrace_target_info *
f4abbc16
MM
12702remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12703 const struct btrace_config *conf)
9accd112
MM
12704{
12705 struct btrace_target_info *tinfo = NULL;
b20a6524 12706 struct packet_config *packet = NULL;
9accd112
MM
12707 struct remote_state *rs = get_remote_state ();
12708 char *buf = rs->buf;
12709 char *endbuf = rs->buf + get_remote_packet_size ();
12710
b20a6524
MM
12711 switch (conf->format)
12712 {
12713 case BTRACE_FORMAT_BTS:
12714 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12715 break;
12716
12717 case BTRACE_FORMAT_PT:
12718 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12719 break;
12720 }
12721
12722 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12723 error (_("Target does not support branch tracing."));
12724
f4abbc16
MM
12725 btrace_sync_conf (conf);
12726
9accd112
MM
12727 set_general_thread (ptid);
12728
12729 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12730 putpkt (rs->buf);
12731 getpkt (&rs->buf, &rs->buf_size, 0);
12732
12733 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12734 {
12735 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12736 error (_("Could not enable branch tracing for %s: %s"),
12737 target_pid_to_str (ptid), rs->buf + 2);
12738 else
12739 error (_("Could not enable branch tracing for %s."),
12740 target_pid_to_str (ptid));
12741 }
12742
8d749320 12743 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12744 tinfo->ptid = ptid;
12745
f4abbc16
MM
12746 /* If we fail to read the configuration, we lose some information, but the
12747 tracing itself is not impacted. */
492d29ea
PA
12748 TRY
12749 {
12750 btrace_read_config (&tinfo->conf);
12751 }
12752 CATCH (err, RETURN_MASK_ERROR)
12753 {
12754 if (err.message != NULL)
12755 warning ("%s", err.message);
12756 }
12757 END_CATCH
f4abbc16 12758
9accd112
MM
12759 return tinfo;
12760}
12761
12762/* Disable branch tracing. */
12763
12764static void
25e95349
TT
12765remote_disable_btrace (struct target_ops *self,
12766 struct btrace_target_info *tinfo)
9accd112
MM
12767{
12768 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12769 struct remote_state *rs = get_remote_state ();
12770 char *buf = rs->buf;
12771 char *endbuf = rs->buf + get_remote_packet_size ();
12772
4082afcc 12773 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12774 error (_("Target does not support branch tracing."));
12775
12776 set_general_thread (tinfo->ptid);
12777
12778 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12779 putpkt (rs->buf);
12780 getpkt (&rs->buf, &rs->buf_size, 0);
12781
12782 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12783 {
12784 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12785 error (_("Could not disable branch tracing for %s: %s"),
12786 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12787 else
12788 error (_("Could not disable branch tracing for %s."),
12789 target_pid_to_str (tinfo->ptid));
12790 }
12791
12792 xfree (tinfo);
12793}
12794
12795/* Teardown branch tracing. */
12796
12797static void
1777056d
TT
12798remote_teardown_btrace (struct target_ops *self,
12799 struct btrace_target_info *tinfo)
9accd112
MM
12800{
12801 /* We must not talk to the target during teardown. */
12802 xfree (tinfo);
12803}
12804
12805/* Read the branch trace. */
12806
969c39fb 12807static enum btrace_error
39c49f83 12808remote_read_btrace (struct target_ops *self,
734b0e4b 12809 struct btrace_data *btrace,
969c39fb 12810 struct btrace_target_info *tinfo,
9accd112
MM
12811 enum btrace_read_type type)
12812{
12813 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12814 struct remote_state *rs = get_remote_state ();
969c39fb 12815 struct cleanup *cleanup;
9accd112
MM
12816 const char *annex;
12817 char *xml;
12818
4082afcc 12819 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12820 error (_("Target does not support branch tracing."));
12821
12822#if !defined(HAVE_LIBEXPAT)
12823 error (_("Cannot process branch tracing result. XML parsing not supported."));
12824#endif
12825
12826 switch (type)
12827 {
864089d2 12828 case BTRACE_READ_ALL:
9accd112
MM
12829 annex = "all";
12830 break;
864089d2 12831 case BTRACE_READ_NEW:
9accd112
MM
12832 annex = "new";
12833 break;
969c39fb
MM
12834 case BTRACE_READ_DELTA:
12835 annex = "delta";
12836 break;
9accd112
MM
12837 default:
12838 internal_error (__FILE__, __LINE__,
12839 _("Bad branch tracing read type: %u."),
12840 (unsigned int) type);
12841 }
12842
12843 xml = target_read_stralloc (&current_target,
b20a6524 12844 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12845 if (xml == NULL)
12846 return BTRACE_ERR_UNKNOWN;
9accd112 12847
969c39fb 12848 cleanup = make_cleanup (xfree, xml);
734b0e4b 12849 parse_xml_btrace (btrace, xml);
969c39fb 12850 do_cleanups (cleanup);
9accd112 12851
969c39fb 12852 return BTRACE_ERR_NONE;
9accd112
MM
12853}
12854
f4abbc16
MM
12855static const struct btrace_config *
12856remote_btrace_conf (struct target_ops *self,
12857 const struct btrace_target_info *tinfo)
12858{
12859 return &tinfo->conf;
12860}
12861
ced63ec0 12862static int
5436ff03 12863remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12864{
4082afcc
PA
12865 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12866 == PACKET_ENABLE);
ced63ec0
GB
12867}
12868
9dd130a0
TT
12869/* Implementation of to_load. */
12870
12871static void
9cbe5fff 12872remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12873{
12874 generic_load (name, from_tty);
12875}
12876
c78fa86a
GB
12877/* Accepts an integer PID; returns a string representing a file that
12878 can be opened on the remote side to get the symbols for the child
12879 process. Returns NULL if the operation is not supported. */
12880
12881static char *
12882remote_pid_to_exec_file (struct target_ops *self, int pid)
12883{
12884 static char *filename = NULL;
835205d0
GB
12885 struct inferior *inf;
12886 char *annex = NULL;
c78fa86a
GB
12887
12888 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12889 return NULL;
12890
12891 if (filename != NULL)
12892 xfree (filename);
12893
835205d0
GB
12894 inf = find_inferior_pid (pid);
12895 if (inf == NULL)
12896 internal_error (__FILE__, __LINE__,
12897 _("not currently attached to process %d"), pid);
12898
12899 if (!inf->fake_pid_p)
12900 {
12901 const int annex_size = 9;
12902
224c3ddb 12903 annex = (char *) alloca (annex_size);
835205d0
GB
12904 xsnprintf (annex, annex_size, "%x", pid);
12905 }
12906
c78fa86a
GB
12907 filename = target_read_stralloc (&current_target,
12908 TARGET_OBJECT_EXEC_FILE, annex);
12909
12910 return filename;
12911}
12912
750ce8d1
YQ
12913/* Implement the to_can_do_single_step target_ops method. */
12914
12915static int
12916remote_can_do_single_step (struct target_ops *ops)
12917{
12918 /* We can only tell whether target supports single step or not by
12919 supported s and S vCont actions if the stub supports vContSupported
12920 feature. If the stub doesn't support vContSupported feature,
12921 we have conservatively to think target doesn't supports single
12922 step. */
12923 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12924 {
12925 struct remote_state *rs = get_remote_state ();
12926
12927 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12928 remote_vcont_probe (rs);
12929
12930 return rs->supports_vCont.s && rs->supports_vCont.S;
12931 }
12932 else
12933 return 0;
12934}
12935
c906108c 12936static void
fba45db2 12937init_remote_ops (void)
c906108c 12938{
c5aa993b 12939 remote_ops.to_shortname = "remote";
c906108c 12940 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 12941 remote_ops.to_doc =
c906108c 12942 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
12943Specify the serial device it is connected to\n\
12944(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
12945 remote_ops.to_open = remote_open;
12946 remote_ops.to_close = remote_close;
c906108c 12947 remote_ops.to_detach = remote_detach;
6ad8ae5c 12948 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 12949 remote_ops.to_resume = remote_resume;
c906108c
SS
12950 remote_ops.to_wait = remote_wait;
12951 remote_ops.to_fetch_registers = remote_fetch_registers;
12952 remote_ops.to_store_registers = remote_store_registers;
12953 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 12954 remote_ops.to_files_info = remote_files_info;
c906108c
SS
12955 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12956 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
12957 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12958 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12959 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12960 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
12961 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12962 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
12963 remote_ops.to_watchpoint_addr_within_range =
12964 remote_watchpoint_addr_within_range;
3c3bea1c
GS
12965 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12966 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12967 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
12968 remote_ops.to_region_ok_for_hw_watchpoint
12969 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
12970 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12971 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 12972 remote_ops.to_kill = remote_kill;
9dd130a0 12973 remote_ops.to_load = remote_load;
c906108c 12974 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 12975 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 12976 remote_ops.to_program_signals = remote_program_signals;
c906108c 12977 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 12978 remote_ops.to_thread_name = remote_thread_name;
e8032dde 12979 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 12980 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 12981 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 12982 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 12983 remote_ops.to_stop = remote_stop;
bfedc46a 12984 remote_ops.to_interrupt = remote_interrupt;
abc56d60 12985 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
4b8a223f 12986 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 12987 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 12988 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 12989 remote_ops.to_log_command = serial_log_command;
38691318 12990 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 12991 remote_ops.to_stratum = process_stratum;
c35b1492
PA
12992 remote_ops.to_has_all_memory = default_child_has_all_memory;
12993 remote_ops.to_has_memory = default_child_has_memory;
12994 remote_ops.to_has_stack = default_child_has_stack;
12995 remote_ops.to_has_registers = default_child_has_registers;
12996 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 12997 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 12998 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 12999 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13000 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13001 remote_ops.to_flash_erase = remote_flash_erase;
13002 remote_ops.to_flash_done = remote_flash_done;
29709017 13003 remote_ops.to_read_description = remote_read_description;
08388c79 13004 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13005 remote_ops.to_can_async_p = remote_can_async_p;
13006 remote_ops.to_is_async_p = remote_is_async_p;
13007 remote_ops.to_async = remote_async;
65706a29 13008 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13009 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13010 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13011 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13012 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13013 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13014 remote_ops.to_supports_disable_randomization
13015 = remote_supports_disable_randomization;
4bd7dc42 13016 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13017 remote_ops.to_fileio_open = remote_hostio_open;
13018 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13019 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13020 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13021 remote_ops.to_fileio_close = remote_hostio_close;
13022 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13023 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13024 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13025 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13026 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13027 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13028 remote_ops.to_trace_init = remote_trace_init;
13029 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13030 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13031 remote_ops.to_download_trace_state_variable
13032 = remote_download_trace_state_variable;
d248b706
KY
13033 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13034 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13035 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13036 remote_ops.to_trace_start = remote_trace_start;
13037 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13038 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13039 remote_ops.to_trace_stop = remote_trace_stop;
13040 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13041 remote_ops.to_get_trace_state_variable_value
13042 = remote_get_trace_state_variable_value;
00bf0b85
SS
13043 remote_ops.to_save_trace_data = remote_save_trace_data;
13044 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13045 remote_ops.to_upload_trace_state_variables
13046 = remote_upload_trace_state_variables;
00bf0b85 13047 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13048 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13049 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13050 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13051 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13052 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13053 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13054 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13055 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13056 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13057 remote_ops.to_static_tracepoint_marker_at
13058 = remote_static_tracepoint_marker_at;
13059 remote_ops.to_static_tracepoint_markers_by_strid
13060 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13061 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13062 remote_ops.to_use_agent = remote_use_agent;
13063 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13064 remote_ops.to_supports_btrace = remote_supports_btrace;
13065 remote_ops.to_enable_btrace = remote_enable_btrace;
13066 remote_ops.to_disable_btrace = remote_disable_btrace;
13067 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13068 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13069 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13070 remote_ops.to_augmented_libraries_svr4_read =
13071 remote_augmented_libraries_svr4_read;
c906108c
SS
13072}
13073
13074/* Set up the extended remote vector by making a copy of the standard
13075 remote vector and adding to it. */
13076
13077static void
fba45db2 13078init_extended_remote_ops (void)
c906108c
SS
13079{
13080 extended_remote_ops = remote_ops;
13081
0f71a2f6 13082 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13083 extended_remote_ops.to_longname =
c906108c 13084 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13085 extended_remote_ops.to_doc =
c906108c 13086 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13087Specify the serial device it is connected to (e.g. /dev/ttya).";
13088 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
13089 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13090 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
13091 extended_remote_ops.to_detach = extended_remote_detach;
13092 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13093 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 13094 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
13095 extended_remote_ops.to_supports_disable_randomization
13096 = extended_remote_supports_disable_randomization;
de0d863e 13097 extended_remote_ops.to_follow_fork = remote_follow_fork;
94585166 13098 extended_remote_ops.to_follow_exec = remote_follow_exec;
cbb8991c
DB
13099 extended_remote_ops.to_insert_fork_catchpoint
13100 = remote_insert_fork_catchpoint;
13101 extended_remote_ops.to_remove_fork_catchpoint
13102 = remote_remove_fork_catchpoint;
13103 extended_remote_ops.to_insert_vfork_catchpoint
13104 = remote_insert_vfork_catchpoint;
13105 extended_remote_ops.to_remove_vfork_catchpoint
13106 = remote_remove_vfork_catchpoint;
d46addbb
DB
13107 extended_remote_ops.to_insert_exec_catchpoint
13108 = remote_insert_exec_catchpoint;
13109 extended_remote_ops.to_remove_exec_catchpoint
13110 = remote_remove_exec_catchpoint;
0f71a2f6
JM
13111}
13112
6426a772 13113static int
6a109b6b 13114remote_can_async_p (struct target_ops *ops)
6426a772 13115{
5d93a237
TT
13116 struct remote_state *rs = get_remote_state ();
13117
c6ebd6cf 13118 if (!target_async_permitted)
75c99385
PA
13119 /* We only enable async when the user specifically asks for it. */
13120 return 0;
13121
23860348 13122 /* We're async whenever the serial device is. */
5d93a237 13123 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13124}
13125
13126static int
6a109b6b 13127remote_is_async_p (struct target_ops *ops)
6426a772 13128{
5d93a237
TT
13129 struct remote_state *rs = get_remote_state ();
13130
c6ebd6cf 13131 if (!target_async_permitted)
75c99385
PA
13132 /* We only enable async when the user specifically asks for it. */
13133 return 0;
13134
23860348 13135 /* We're async whenever the serial device is. */
5d93a237 13136 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13137}
13138
2acceee2
JM
13139/* Pass the SERIAL event on and up to the client. One day this code
13140 will be able to delay notifying the client of an event until the
23860348 13141 point where an entire packet has been received. */
2acceee2 13142
2acceee2
JM
13143static serial_event_ftype remote_async_serial_handler;
13144
6426a772 13145static void
819cc324 13146remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13147{
19ba03f4 13148 struct remote_state *rs = (struct remote_state *) context;
88b496c3 13149
2acceee2
JM
13150 /* Don't propogate error information up to the client. Instead let
13151 the client find out about the error by querying the target. */
6a3753b3 13152 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13153}
13154
74531fed
PA
13155static void
13156remote_async_inferior_event_handler (gdb_client_data data)
13157{
13158 inferior_event_handler (INF_REG_EVENT, NULL);
13159}
13160
2acceee2 13161static void
6a3753b3 13162remote_async (struct target_ops *ops, int enable)
2acceee2 13163{
5d93a237
TT
13164 struct remote_state *rs = get_remote_state ();
13165
6a3753b3 13166 if (enable)
2acceee2 13167 {
88b496c3 13168 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13169
13170 /* If there are pending events in the stop reply queue tell the
13171 event loop to process them. */
13172 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13173 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13174 /* For simplicity, below we clear the pending events token
13175 without remembering whether it is marked, so here we always
13176 mark it. If there's actually no pending notification to
13177 process, this ends up being a no-op (other than a spurious
13178 event-loop wakeup). */
13179 if (target_is_non_stop_p ())
13180 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13181 }
13182 else
b7d2e916
PA
13183 {
13184 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13185 /* If the core is disabling async, it doesn't want to be
13186 disturbed with target events. Clear all async event sources
13187 too. */
b7d2e916 13188 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13189 if (target_is_non_stop_p ())
13190 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13191 }
6426a772
JM
13192}
13193
65706a29
PA
13194/* Implementation of the to_thread_events method. */
13195
13196static void
13197remote_thread_events (struct target_ops *ops, int enable)
13198{
13199 struct remote_state *rs = get_remote_state ();
13200 size_t size = get_remote_packet_size ();
13201 char *p = rs->buf;
13202
13203 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13204 return;
13205
13206 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13207 putpkt (rs->buf);
13208 getpkt (&rs->buf, &rs->buf_size, 0);
13209
13210 switch (packet_ok (rs->buf,
13211 &remote_protocol_packets[PACKET_QThreadEvents]))
13212 {
13213 case PACKET_OK:
13214 if (strcmp (rs->buf, "OK") != 0)
13215 error (_("Remote refused setting thread events: %s"), rs->buf);
13216 break;
13217 case PACKET_ERROR:
13218 warning (_("Remote failure reply: %s"), rs->buf);
13219 break;
13220 case PACKET_UNKNOWN:
13221 break;
13222 }
13223}
13224
5a2468f5 13225static void
c2d11a7d 13226set_remote_cmd (char *args, int from_tty)
5a2468f5 13227{
635c7e8a 13228 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13229}
13230
d471ea57
AC
13231static void
13232show_remote_cmd (char *args, int from_tty)
13233{
37a105a1 13234 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13235 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13236 struct cleanup *showlist_chain;
13237 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13238 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13239
13240 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13241 for (; list != NULL; list = list->next)
13242 if (strcmp (list->name, "Z-packet") == 0)
13243 continue;
427c3a89
DJ
13244 else if (list->type == not_set_cmd)
13245 /* Alias commands are exactly like the original, except they
13246 don't have the normal type. */
13247 continue;
13248 else
37a105a1
DJ
13249 {
13250 struct cleanup *option_chain
13251 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13252
37a105a1
DJ
13253 ui_out_field_string (uiout, "name", list->name);
13254 ui_out_text (uiout, ": ");
427c3a89 13255 if (list->type == show_cmd)
5b9afe8a 13256 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
13257 else
13258 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13259 /* Close the tuple. */
13260 do_cleanups (option_chain);
13261 }
427c3a89
DJ
13262
13263 /* Close the tuple. */
13264 do_cleanups (showlist_chain);
d471ea57 13265}
5a2468f5 13266
0f71a2f6 13267
23860348 13268/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13269static void
13270remote_new_objfile (struct objfile *objfile)
13271{
5d93a237
TT
13272 struct remote_state *rs = get_remote_state ();
13273
13274 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13275 remote_check_symbols ();
dc8acb97
MS
13276}
13277
00bf0b85
SS
13278/* Pull all the tracepoints defined on the target and create local
13279 data structures representing them. We don't want to create real
13280 tracepoints yet, we don't want to mess up the user's existing
13281 collection. */
13282
13283static int
ab6617cc 13284remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13285{
00bf0b85
SS
13286 struct remote_state *rs = get_remote_state ();
13287 char *p;
d5551862 13288
00bf0b85
SS
13289 /* Ask for a first packet of tracepoint definition. */
13290 putpkt ("qTfP");
13291 getpkt (&rs->buf, &rs->buf_size, 0);
13292 p = rs->buf;
13293 while (*p && *p != 'l')
d5551862 13294 {
00bf0b85
SS
13295 parse_tracepoint_definition (p, utpp);
13296 /* Ask for another packet of tracepoint definition. */
13297 putpkt ("qTsP");
13298 getpkt (&rs->buf, &rs->buf_size, 0);
13299 p = rs->buf;
d5551862 13300 }
00bf0b85 13301 return 0;
d5551862
SS
13302}
13303
00bf0b85 13304static int
181e3713
TT
13305remote_upload_trace_state_variables (struct target_ops *self,
13306 struct uploaded_tsv **utsvp)
d5551862 13307{
00bf0b85 13308 struct remote_state *rs = get_remote_state ();
d5551862 13309 char *p;
d5551862 13310
00bf0b85
SS
13311 /* Ask for a first packet of variable definition. */
13312 putpkt ("qTfV");
d5551862
SS
13313 getpkt (&rs->buf, &rs->buf_size, 0);
13314 p = rs->buf;
00bf0b85 13315 while (*p && *p != 'l')
d5551862 13316 {
00bf0b85
SS
13317 parse_tsv_definition (p, utsvp);
13318 /* Ask for another packet of variable definition. */
13319 putpkt ("qTsV");
d5551862
SS
13320 getpkt (&rs->buf, &rs->buf_size, 0);
13321 p = rs->buf;
13322 }
00bf0b85 13323 return 0;
d5551862
SS
13324}
13325
c1e36e3e
PA
13326/* The "set/show range-stepping" show hook. */
13327
13328static void
13329show_range_stepping (struct ui_file *file, int from_tty,
13330 struct cmd_list_element *c,
13331 const char *value)
13332{
13333 fprintf_filtered (file,
13334 _("Debugger's willingness to use range stepping "
13335 "is %s.\n"), value);
13336}
13337
13338/* The "set/show range-stepping" set hook. */
13339
13340static void
13341set_range_stepping (char *ignore_args, int from_tty,
13342 struct cmd_list_element *c)
13343{
5d93a237
TT
13344 struct remote_state *rs = get_remote_state ();
13345
c1e36e3e
PA
13346 /* Whene enabling, check whether range stepping is actually
13347 supported by the target, and warn if not. */
13348 if (use_range_stepping)
13349 {
5d93a237 13350 if (rs->remote_desc != NULL)
c1e36e3e 13351 {
4082afcc 13352 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13353 remote_vcont_probe (rs);
13354
4082afcc 13355 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13356 && rs->supports_vCont.r)
13357 return;
13358 }
13359
13360 warning (_("Range stepping is not supported by the current target"));
13361 }
13362}
13363
c906108c 13364void
fba45db2 13365_initialize_remote (void)
c906108c 13366{
ea9c271d 13367 struct remote_state *rs;
9a7071a8 13368 struct cmd_list_element *cmd;
6f937416 13369 const char *cmd_name;
ea9c271d 13370
0f71a2f6 13371 /* architecture specific data */
2bc416ba 13372 remote_gdbarch_data_handle =
23860348 13373 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13374 remote_g_packet_data_handle =
13375 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13376
94585166
DB
13377 remote_pspace_data
13378 = register_program_space_data_with_cleanup (NULL,
13379 remote_pspace_data_cleanup);
13380
ea9c271d
DJ
13381 /* Initialize the per-target state. At the moment there is only one
13382 of these, not one per target. Only one target is active at a
cf792862
TT
13383 time. */
13384 remote_state = new_remote_state ();
ea9c271d 13385
c906108c
SS
13386 init_remote_ops ();
13387 add_target (&remote_ops);
13388
13389 init_extended_remote_ops ();
13390 add_target (&extended_remote_ops);
cce74817 13391
dc8acb97 13392 /* Hook into new objfile notification. */
06d3b283 13393 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13394 /* We're no longer interested in notification events of an inferior
13395 when it exits. */
13396 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13397
b803fb0f 13398 /* Set up signal handlers. */
934b9bac 13399 async_sigint_remote_token =
b803fb0f 13400 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 13401 async_sigint_remote_twice_token =
6d549500 13402 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 13403
c906108c
SS
13404#if 0
13405 init_remote_threadtests ();
13406#endif
13407
722247f1 13408 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13409 /* set/show remote ... */
d471ea57 13410
1bedd215 13411 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13412Remote protocol specific variables\n\
13413Configure various remote-protocol specific variables such as\n\
1bedd215 13414the packets being used"),
cff3e48b 13415 &remote_set_cmdlist, "set remote ",
23860348 13416 0 /* allow-unknown */, &setlist);
1bedd215 13417 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13418Remote protocol specific variables\n\
13419Configure various remote-protocol specific variables such as\n\
1bedd215 13420the packets being used"),
cff3e48b 13421 &remote_show_cmdlist, "show remote ",
23860348 13422 0 /* allow-unknown */, &showlist);
5a2468f5 13423
1a966eab
AC
13424 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13425Compare section data on target to the exec file.\n\
95cf3b38
DT
13426Argument is a single section name (default: all loaded sections).\n\
13427To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13428 &cmdlist);
13429
1a966eab
AC
13430 add_cmd ("packet", class_maintenance, packet_command, _("\
13431Send an arbitrary packet to a remote target.\n\
c906108c
SS
13432 maintenance packet TEXT\n\
13433If GDB is talking to an inferior via the GDB serial protocol, then\n\
13434this command sends the string TEXT to the inferior, and displays the\n\
13435response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13436terminating `#' character and checksum."),
c906108c
SS
13437 &maintenancelist);
13438
7915a72c
AC
13439 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13440Set whether to send break if interrupted."), _("\
13441Show whether to send break if interrupted."), _("\
13442If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13443 set_remotebreak, show_remotebreak,
e707bbc2 13444 &setlist, &showlist);
9a7071a8
JB
13445 cmd_name = "remotebreak";
13446 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13447 deprecate_cmd (cmd, "set remote interrupt-sequence");
13448 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13449 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13450 deprecate_cmd (cmd, "show remote interrupt-sequence");
13451
13452 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13453 interrupt_sequence_modes, &interrupt_sequence_mode,
13454 _("\
9a7071a8
JB
13455Set interrupt sequence to remote target."), _("\
13456Show interrupt sequence to remote target."), _("\
13457Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13458 NULL, show_interrupt_sequence,
13459 &remote_set_cmdlist,
13460 &remote_show_cmdlist);
13461
13462 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13463 &interrupt_on_connect, _("\
13464Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13465Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13466If set, interrupt sequence is sent to remote target."),
13467 NULL, NULL,
13468 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13469
23860348 13470 /* Install commands for configuring memory read/write packets. */
11cf8741 13471
1a966eab
AC
13472 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13473Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13474 &setlist);
1a966eab
AC
13475 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13476Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13477 &showlist);
13478 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13479 set_memory_write_packet_size, _("\
13480Set the maximum number of bytes per memory-write packet.\n\
13481Specify the number of bytes in a packet or 0 (zero) for the\n\
13482default packet size. The actual limit is further reduced\n\
13483dependent on the target. Specify ``fixed'' to disable the\n\
13484further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13485 &remote_set_cmdlist);
13486 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13487 set_memory_read_packet_size, _("\
13488Set the maximum number of bytes per memory-read packet.\n\
13489Specify the number of bytes in a packet or 0 (zero) for the\n\
13490default packet size. The actual limit is further reduced\n\
13491dependent on the target. Specify ``fixed'' to disable the\n\
13492further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13493 &remote_set_cmdlist);
13494 add_cmd ("memory-write-packet-size", no_class,
13495 show_memory_write_packet_size,
1a966eab 13496 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13497 &remote_show_cmdlist);
13498 add_cmd ("memory-read-packet-size", no_class,
13499 show_memory_read_packet_size,
1a966eab 13500 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13501 &remote_show_cmdlist);
c906108c 13502
b3f42336 13503 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13504 &remote_hw_watchpoint_limit, _("\
13505Set the maximum number of target hardware watchpoints."), _("\
13506Show the maximum number of target hardware watchpoints."), _("\
13507Specify a negative limit for unlimited."),
3e43a32a
MS
13508 NULL, NULL, /* FIXME: i18n: The maximum
13509 number of target hardware
13510 watchpoints is %s. */
b3f42336 13511 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13512 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13513 &remote_hw_watchpoint_length_limit, _("\
13514Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13515Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13516Specify a negative limit for unlimited."),
13517 NULL, NULL, /* FIXME: i18n: The maximum
13518 length (in bytes) of a target
13519 hardware watchpoint is %s. */
13520 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13521 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13522 &remote_hw_breakpoint_limit, _("\
13523Set the maximum number of target hardware breakpoints."), _("\
13524Show the maximum number of target hardware breakpoints."), _("\
13525Specify a negative limit for unlimited."),
3e43a32a
MS
13526 NULL, NULL, /* FIXME: i18n: The maximum
13527 number of target hardware
13528 breakpoints is %s. */
b3f42336 13529 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13530
1b493192
PA
13531 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13532 &remote_address_size, _("\
4d28ad1e
AC
13533Set the maximum size of the address (in bits) in a memory packet."), _("\
13534Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13535 NULL,
13536 NULL, /* FIXME: i18n: */
13537 &setlist, &showlist);
c906108c 13538
ca4f7f8b
PA
13539 init_all_packet_configs ();
13540
444abaca 13541 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13542 "X", "binary-download", 1);
0f71a2f6 13543
444abaca 13544 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13545 "vCont", "verbose-resume", 0);
506fb367 13546
89be2091
DJ
13547 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13548 "QPassSignals", "pass-signals", 0);
13549
9b224c5e
PA
13550 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13551 "QProgramSignals", "program-signals", 0);
13552
444abaca 13553 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13554 "qSymbol", "symbol-lookup", 0);
dc8acb97 13555
444abaca 13556 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13557 "P", "set-register", 1);
d471ea57 13558
444abaca 13559 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13560 "p", "fetch-register", 1);
b96ec7ac 13561
444abaca 13562 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13563 "Z0", "software-breakpoint", 0);
d471ea57 13564
444abaca 13565 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13566 "Z1", "hardware-breakpoint", 0);
d471ea57 13567
444abaca 13568 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13569 "Z2", "write-watchpoint", 0);
d471ea57 13570
444abaca 13571 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13572 "Z3", "read-watchpoint", 0);
d471ea57 13573
444abaca 13574 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13575 "Z4", "access-watchpoint", 0);
d471ea57 13576
0876f84a
DJ
13577 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13578 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13579
c78fa86a
GB
13580 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13581 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13582
23181151
DJ
13583 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13584 "qXfer:features:read", "target-features", 0);
13585
cfa9d6d9
DJ
13586 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13587 "qXfer:libraries:read", "library-info", 0);
13588
2268b414
JK
13589 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13590 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13591
fd79ecee
DJ
13592 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13593 "qXfer:memory-map:read", "memory-map", 0);
13594
0e7f50da
UW
13595 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13596 "qXfer:spu:read", "read-spu-object", 0);
13597
13598 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13599 "qXfer:spu:write", "write-spu-object", 0);
13600
07e059b5
VP
13601 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13602 "qXfer:osdata:read", "osdata", 0);
13603
dc146f7c
VP
13604 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13605 "qXfer:threads:read", "threads", 0);
13606
4aa995e1
PA
13607 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13608 "qXfer:siginfo:read", "read-siginfo-object", 0);
13609
13610 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13611 "qXfer:siginfo:write", "write-siginfo-object", 0);
13612
b3b9301e
PA
13613 add_packet_config_cmd
13614 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13615 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13616
169081d0
TG
13617 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13618 "qXfer:uib:read", "unwind-info-block", 0);
13619
444abaca 13620 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13621 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13622 0);
13623
711e434b
PM
13624 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13625 "qGetTIBAddr", "get-thread-information-block-address",
13626 0);
13627
40ab02ce
MS
13628 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13629 "bc", "reverse-continue", 0);
13630
13631 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13632 "bs", "reverse-step", 0);
13633
be2a5f71
DJ
13634 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13635 "qSupported", "supported-packets", 0);
13636
08388c79
DE
13637 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13638 "qSearch:memory", "search-memory", 0);
13639
bd3eecc3
PA
13640 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13641 "qTStatus", "trace-status", 0);
13642
15a201c8
GB
13643 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13644 "vFile:setfs", "hostio-setfs", 0);
13645
a6b151f1
DJ
13646 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13647 "vFile:open", "hostio-open", 0);
13648
13649 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13650 "vFile:pread", "hostio-pread", 0);
13651
13652 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13653 "vFile:pwrite", "hostio-pwrite", 0);
13654
13655 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13656 "vFile:close", "hostio-close", 0);
13657
13658 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13659 "vFile:unlink", "hostio-unlink", 0);
13660
b9e7b9c3
UW
13661 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13662 "vFile:readlink", "hostio-readlink", 0);
13663
0a93529c
GB
13664 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13665 "vFile:fstat", "hostio-fstat", 0);
13666
2d717e4f
DJ
13667 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13668 "vAttach", "attach", 0);
13669
13670 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13671 "vRun", "run", 0);
13672
a6f3e723
SL
13673 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13674 "QStartNoAckMode", "noack", 0);
13675
82f73884
PA
13676 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13677 "vKill", "kill", 0);
13678
0b16c5cf
PA
13679 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13680 "qAttached", "query-attached", 0);
13681
782b2b07 13682 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13683 "ConditionalTracepoints",
13684 "conditional-tracepoints", 0);
3788aec7
LM
13685
13686 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13687 "ConditionalBreakpoints",
13688 "conditional-breakpoints", 0);
13689
d3ce09f5
SS
13690 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13691 "BreakpointCommands",
13692 "breakpoint-commands", 0);
13693
7a697b8d
SS
13694 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13695 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13696
409873ef
SS
13697 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13698 "TracepointSource", "TracepointSource", 0);
13699
d914c394
SS
13700 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13701 "QAllow", "allow", 0);
13702
0fb4aa4b
PA
13703 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13704 "StaticTracepoints", "static-tracepoints", 0);
13705
1e4d1764
YQ
13706 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13707 "InstallInTrace", "install-in-trace", 0);
13708
0fb4aa4b
PA
13709 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13710 "qXfer:statictrace:read", "read-sdata-object", 0);
13711
78d85199
YQ
13712 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13713 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13714
03583c20
UW
13715 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13716 "QDisableRandomization", "disable-randomization", 0);
13717
d1feda86
YQ
13718 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13719 "QAgent", "agent", 0);
13720
f6f899bf
HAQ
13721 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13722 "QTBuffer:size", "trace-buffer-size", 0);
13723
9accd112
MM
13724 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13725 "Qbtrace:off", "disable-btrace", 0);
13726
13727 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13728 "Qbtrace:bts", "enable-btrace-bts", 0);
13729
13730 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13731 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13732
13733 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13734 "qXfer:btrace", "read-btrace", 0);
13735
f4abbc16
MM
13736 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13737 "qXfer:btrace-conf", "read-btrace-conf", 0);
13738
d33501a5
MM
13739 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13740 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13741
73b8c1fd
PA
13742 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13743 "multiprocess-feature", "multiprocess-feature", 0);
13744
f7e6eed5
PA
13745 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13746 "swbreak-feature", "swbreak-feature", 0);
13747
13748 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13749 "hwbreak-feature", "hwbreak-feature", 0);
13750
89245bc0
DB
13751 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13752 "fork-event-feature", "fork-event-feature", 0);
13753
13754 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13755 "vfork-event-feature", "vfork-event-feature", 0);
13756
b20a6524
MM
13757 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13758 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13759
750ce8d1
YQ
13760 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13761 "vContSupported", "verbose-resume-supported", 0);
13762
94585166
DB
13763 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13764 "exec-event-feature", "exec-event-feature", 0);
13765
de979965
PA
13766 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13767 "vCtrlC", "ctrl-c", 0);
13768
65706a29
PA
13769 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13770 "QThreadEvents", "thread-events", 0);
13771
f2faf941
PA
13772 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13773 "N stop reply", "no-resumed-stop-reply", 0);
13774
0b736949
DB
13775 /* Assert that we've registered "set remote foo-packet" commands
13776 for all packet configs. */
ca4f7f8b
PA
13777 {
13778 int i;
13779
13780 for (i = 0; i < PACKET_MAX; i++)
13781 {
13782 /* Ideally all configs would have a command associated. Some
13783 still don't though. */
13784 int excepted;
13785
13786 switch (i)
13787 {
13788 case PACKET_QNonStop:
ca4f7f8b
PA
13789 case PACKET_EnableDisableTracepoints_feature:
13790 case PACKET_tracenz_feature:
13791 case PACKET_DisconnectedTracing_feature:
13792 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13793 case PACKET_qCRC:
13794 /* Additions to this list need to be well justified:
13795 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13796 excepted = 1;
13797 break;
13798 default:
13799 excepted = 0;
13800 break;
13801 }
13802
13803 /* This catches both forgetting to add a config command, and
13804 forgetting to remove a packet from the exception list. */
13805 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13806 }
13807 }
13808
37a105a1
DJ
13809 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13810 Z sub-packet has its own set and show commands, but users may
13811 have sets to this variable in their .gdbinit files (or in their
13812 documentation). */
e9e68a56 13813 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13814 &remote_Z_packet_detect, _("\
13815Set use of remote protocol `Z' packets"), _("\
13816Show use of remote protocol `Z' packets "), _("\
3b64bf98 13817When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13818packets."),
e9e68a56 13819 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13820 show_remote_protocol_Z_packet_cmd,
13821 /* FIXME: i18n: Use of remote protocol
13822 `Z' packets is %s. */
e9e68a56 13823 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13824
a6b151f1
DJ
13825 add_prefix_cmd ("remote", class_files, remote_command, _("\
13826Manipulate files on the remote system\n\
13827Transfer files to and from the remote target system."),
13828 &remote_cmdlist, "remote ",
13829 0 /* allow-unknown */, &cmdlist);
13830
13831 add_cmd ("put", class_files, remote_put_command,
13832 _("Copy a local file to the remote system."),
13833 &remote_cmdlist);
13834
13835 add_cmd ("get", class_files, remote_get_command,
13836 _("Copy a remote file to the local system."),
13837 &remote_cmdlist);
13838
13839 add_cmd ("delete", class_files, remote_delete_command,
13840 _("Delete a remote file."),
13841 &remote_cmdlist);
13842
2d717e4f 13843 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13844 &remote_exec_file_var, _("\
2d717e4f 13845Set the remote pathname for \"run\""), _("\
94585166
DB
13846Show the remote pathname for \"run\""), NULL,
13847 set_remote_exec_file,
13848 show_remote_exec_file,
13849 &remote_set_cmdlist,
13850 &remote_show_cmdlist);
2d717e4f 13851
c1e36e3e
PA
13852 add_setshow_boolean_cmd ("range-stepping", class_run,
13853 &use_range_stepping, _("\
13854Enable or disable range stepping."), _("\
13855Show whether target-assisted range stepping is enabled."), _("\
13856If on, and the target supports it, when stepping a source line, GDB\n\
13857tells the target to step the corresponding range of addresses itself instead\n\
13858of issuing multiple single-steps. This speeds up source level\n\
13859stepping. If off, GDB always issues single-steps, even if range\n\
13860stepping is supported by the target. The default is on."),
13861 set_range_stepping,
13862 show_range_stepping,
13863 &setlist,
13864 &showlist);
13865
449092f6
CV
13866 /* Eventually initialize fileio. See fileio.c */
13867 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13868
ba348170 13869 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13870 special ptids with it set to != 0. */
ba348170
PA
13871 magic_null_ptid = ptid_build (42000, -1, 1);
13872 not_sent_ptid = ptid_build (42000, -2, 1);
13873 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13874
13875 target_buf_size = 2048;
224c3ddb 13876 target_buf = (char *) xmalloc (target_buf_size);
c906108c 13877}
10760264 13878