Target remote mode fork and exec test updates
[deliverable/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;
2e3b657e 2917 item.name = NULL;
6dc54d91
PA
2918 item.extra = NULL;
2919
2920 VEC_safe_push (thread_item_t, context->items, &item);
2921
c906108c
SS
2922 return 1; /* continue iterator */
2923}
2924
2925#define CRAZY_MAX_THREADS 1000
2926
39f77062
KB
2927static ptid_t
2928remote_current_thread (ptid_t oldpid)
c906108c 2929{
d01949b6 2930 struct remote_state *rs = get_remote_state ();
c906108c
SS
2931
2932 putpkt ("qC");
6d820c5c 2933 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2934 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
2935 {
2936 char *obuf;
2937 ptid_t result;
2938
2939 result = read_ptid (&rs->buf[2], &obuf);
2940 if (*obuf != '\0' && remote_debug)
2941 fprintf_unfiltered (gdb_stdlog,
2942 "warning: garbage in qC reply\n");
2943
2944 return result;
2945 }
c906108c
SS
2946 else
2947 return oldpid;
2948}
2949
6dc54d91 2950/* List remote threads using the deprecated qL packet. */
cce74817 2951
6dc54d91
PA
2952static int
2953remote_get_threads_with_ql (struct target_ops *ops,
2954 struct threads_listing_context *context)
c906108c 2955{
6dc54d91
PA
2956 if (remote_threadlist_iterator (remote_newthread_step, context,
2957 CRAZY_MAX_THREADS) >= 0)
2958 return 1;
2959
2960 return 0;
c906108c
SS
2961}
2962
dc146f7c
VP
2963#if defined(HAVE_LIBEXPAT)
2964
dc146f7c
VP
2965static void
2966start_thread (struct gdb_xml_parser *parser,
2967 const struct gdb_xml_element *element,
2968 void *user_data, VEC(gdb_xml_value_s) *attributes)
2969{
19ba03f4
SM
2970 struct threads_listing_context *data
2971 = (struct threads_listing_context *) user_data;
dc146f7c
VP
2972
2973 struct thread_item item;
2974 char *id;
3d2c1d41 2975 struct gdb_xml_value *attr;
dc146f7c 2976
19ba03f4 2977 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2978 item.ptid = read_ptid (id, NULL);
2979
3d2c1d41
PA
2980 attr = xml_find_attribute (attributes, "core");
2981 if (attr != NULL)
2982 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2983 else
2984 item.core = -1;
2985
79efa585 2986 attr = xml_find_attribute (attributes, "name");
e1961661 2987 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 2988
dc146f7c
VP
2989 item.extra = 0;
2990
2991 VEC_safe_push (thread_item_t, data->items, &item);
2992}
2993
2994static void
2995end_thread (struct gdb_xml_parser *parser,
2996 const struct gdb_xml_element *element,
2997 void *user_data, const char *body_text)
2998{
19ba03f4
SM
2999 struct threads_listing_context *data
3000 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3001
3002 if (body_text && *body_text)
2ae2a0b7 3003 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3004}
3005
3006const struct gdb_xml_attribute thread_attributes[] = {
3007 { "id", GDB_XML_AF_NONE, NULL, NULL },
3008 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3009 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3010 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3011};
3012
3013const struct gdb_xml_element thread_children[] = {
3014 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3015};
3016
3017const struct gdb_xml_element threads_children[] = {
3018 { "thread", thread_attributes, thread_children,
3019 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3020 start_thread, end_thread },
3021 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3022};
3023
3024const struct gdb_xml_element threads_elements[] = {
3025 { "threads", NULL, threads_children,
3026 GDB_XML_EF_NONE, NULL, NULL },
3027 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3028};
3029
3030#endif
3031
6dc54d91 3032/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3033
6dc54d91
PA
3034static int
3035remote_get_threads_with_qxfer (struct target_ops *ops,
3036 struct threads_listing_context *context)
0f71a2f6 3037{
dc146f7c 3038#if defined(HAVE_LIBEXPAT)
4082afcc 3039 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3040 {
6dc54d91 3041 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3042 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3043
6dc54d91 3044 if (xml != NULL && *xml != '\0')
dc146f7c 3045 {
6dc54d91
PA
3046 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3047 threads_elements, xml, context);
dc146f7c
VP
3048 }
3049
3050 do_cleanups (back_to);
6dc54d91 3051 return 1;
dc146f7c
VP
3052 }
3053#endif
3054
6dc54d91
PA
3055 return 0;
3056}
3057
3058/* List remote threads using qfThreadInfo/qsThreadInfo. */
3059
3060static int
3061remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3062 struct threads_listing_context *context)
3063{
3064 struct remote_state *rs = get_remote_state ();
3065
b80fafe3 3066 if (rs->use_threadinfo_query)
9d1f7ab2 3067 {
6dc54d91
PA
3068 char *bufp;
3069
9d1f7ab2 3070 putpkt ("qfThreadInfo");
6d820c5c 3071 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3072 bufp = rs->buf;
9d1f7ab2 3073 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3074 {
9d1f7ab2
MS
3075 while (*bufp++ == 'm') /* reply contains one or more TID */
3076 {
3077 do
3078 {
6dc54d91
PA
3079 struct thread_item item;
3080
3081 item.ptid = read_ptid (bufp, &bufp);
3082 item.core = -1;
2e3b657e 3083 item.name = NULL;
6dc54d91
PA
3084 item.extra = NULL;
3085
3086 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3087 }
3088 while (*bufp++ == ','); /* comma-separated list */
3089 putpkt ("qsThreadInfo");
6d820c5c 3090 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3091 bufp = rs->buf;
9d1f7ab2 3092 }
6dc54d91
PA
3093 return 1;
3094 }
3095 else
3096 {
3097 /* Packet not recognized. */
3098 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3099 }
3100 }
3101
6dc54d91
PA
3102 return 0;
3103}
3104
e8032dde 3105/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3106 targets. */
3107
3108static void
e8032dde 3109remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
3110{
3111 struct remote_state *rs = get_remote_state ();
3112 struct threads_listing_context context;
3113 struct cleanup *old_chain;
ab970af1 3114 int got_list = 0;
e8032dde 3115
6dc54d91
PA
3116 context.items = NULL;
3117 old_chain = make_cleanup (clear_threads_listing_context, &context);
3118
3119 /* We have a few different mechanisms to fetch the thread list. Try
3120 them all, starting with the most preferred one first, falling
3121 back to older methods. */
3122 if (remote_get_threads_with_qxfer (ops, &context)
3123 || remote_get_threads_with_qthreadinfo (ops, &context)
3124 || remote_get_threads_with_ql (ops, &context))
3125 {
3126 int i;
3127 struct thread_item *item;
ab970af1
PA
3128 struct thread_info *tp, *tmp;
3129
3130 got_list = 1;
3131
7d1a114c
PA
3132 if (VEC_empty (thread_item_t, context.items)
3133 && remote_thread_always_alive (ops, inferior_ptid))
3134 {
3135 /* Some targets don't really support threads, but still
3136 reply an (empty) thread list in response to the thread
3137 listing packets, instead of replying "packet not
3138 supported". Exit early so we don't delete the main
3139 thread. */
3140 do_cleanups (old_chain);
3141 return;
3142 }
3143
ab970af1
PA
3144 /* CONTEXT now holds the current thread list on the remote
3145 target end. Delete GDB-side threads no longer found on the
3146 target. */
8a06aea7 3147 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3148 {
ab970af1
PA
3149 for (i = 0;
3150 VEC_iterate (thread_item_t, context.items, i, item);
3151 ++i)
3152 {
3153 if (ptid_equal (item->ptid, tp->ptid))
3154 break;
3155 }
3156
3157 if (i == VEC_length (thread_item_t, context.items))
3158 {
3159 /* Not found. */
3160 delete_thread (tp->ptid);
3161 }
cbb8991c
DB
3162 }
3163
3164 /* Remove any unreported fork child threads from CONTEXT so
3165 that we don't interfere with follow fork, which is where
3166 creation of such threads is handled. */
3167 remove_new_fork_children (&context);
74531fed 3168
ab970af1 3169 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3170 for (i = 0;
3171 VEC_iterate (thread_item_t, context.items, i, item);
3172 ++i)
3173 {
3174 if (!ptid_equal (item->ptid, null_ptid))
3175 {
3176 struct private_thread_info *info;
3177 /* In non-stop mode, we assume new found threads are
3178 running until proven otherwise with a stop reply. In
3179 all-stop, we can only get here if all threads are
3180 stopped. */
6efcd9a8 3181 int running = target_is_non_stop_p () ? 1 : 0;
6dc54d91
PA
3182
3183 remote_notice_new_inferior (item->ptid, running);
3184
3185 info = demand_private_info (item->ptid);
3186 info->core = item->core;
3187 info->extra = item->extra;
3188 item->extra = NULL;
79efa585
SM
3189 info->name = item->name;
3190 item->name = NULL;
6dc54d91
PA
3191 }
3192 }
3193 }
3194
ab970af1
PA
3195 if (!got_list)
3196 {
3197 /* If no thread listing method is supported, then query whether
3198 each known thread is alive, one by one, with the T packet.
3199 If the target doesn't support threads at all, then this is a
3200 no-op. See remote_thread_alive. */
3201 prune_threads ();
3202 }
3203
6dc54d91 3204 do_cleanups (old_chain);
9d1f7ab2
MS
3205}
3206
802188a7 3207/*
9d1f7ab2
MS
3208 * Collect a descriptive string about the given thread.
3209 * The target may say anything it wants to about the thread
3210 * (typically info about its blocked / runnable state, name, etc.).
3211 * This string will appear in the info threads display.
802188a7 3212 *
9d1f7ab2
MS
3213 * Optional: targets are not required to implement this function.
3214 */
3215
3216static char *
c15906d8 3217remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3218{
d01949b6 3219 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3220 int result;
3221 int set;
3222 threadref id;
3223 struct gdb_ext_thread_info threadinfo;
23860348 3224 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3225 int n = 0; /* position in display_buf */
3226
5d93a237 3227 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3228 internal_error (__FILE__, __LINE__,
e2e0b3e5 3229 _("remote_threads_extra_info"));
9d1f7ab2 3230
60e569b9 3231 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3232 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3233 /* This is the main thread which was added by GDB. The remote
3234 server doesn't know about it. */
3235 return NULL;
3236
4082afcc 3237 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3238 {
3239 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3240
fe978cb0
PA
3241 if (info && info->priv)
3242 return info->priv->extra;
dc146f7c
VP
3243 else
3244 return NULL;
3245 }
3246
b80fafe3 3247 if (rs->use_threadextra_query)
9d1f7ab2 3248 {
82f73884
PA
3249 char *b = rs->buf;
3250 char *endb = rs->buf + get_remote_packet_size ();
3251
3252 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3253 b += strlen (b);
3254 write_ptid (b, endb, tp->ptid);
3255
2e9f7625 3256 putpkt (rs->buf);
6d820c5c 3257 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3258 if (rs->buf[0] != 0)
9d1f7ab2 3259 {
2e9f7625
DJ
3260 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3261 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3262 display_buf [result] = '\0';
9d1f7ab2
MS
3263 return display_buf;
3264 }
0f71a2f6 3265 }
9d1f7ab2
MS
3266
3267 /* If the above query fails, fall back to the old method. */
b80fafe3 3268 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3269 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3270 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3271 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3272 if (remote_get_threadinfo (&id, set, &threadinfo))
3273 if (threadinfo.active)
0f71a2f6 3274 {
9d1f7ab2 3275 if (*threadinfo.shortname)
2bc416ba 3276 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3277 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3278 if (*threadinfo.display)
2bc416ba 3279 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3280 " State: %s,", threadinfo.display);
9d1f7ab2 3281 if (*threadinfo.more_display)
2bc416ba 3282 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3283 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3284
3285 if (n > 0)
c5aa993b 3286 {
23860348 3287 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3288 if (',' == display_buf[n-1])
3289 display_buf[n-1] = ' ';
3290 return display_buf;
c5aa993b 3291 }
0f71a2f6 3292 }
9d1f7ab2 3293 return NULL;
0f71a2f6 3294}
c906108c 3295\f
c5aa993b 3296
0fb4aa4b 3297static int
61fc905d 3298remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3299 struct static_tracepoint_marker *marker)
3300{
3301 struct remote_state *rs = get_remote_state ();
3302 char *p = rs->buf;
3303
bba74b36 3304 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3305 p += strlen (p);
3306 p += hexnumstr (p, addr);
3307 putpkt (rs->buf);
3308 getpkt (&rs->buf, &rs->buf_size, 0);
3309 p = rs->buf;
3310
3311 if (*p == 'E')
3312 error (_("Remote failure reply: %s"), p);
3313
3314 if (*p++ == 'm')
3315 {
3316 parse_static_tracepoint_marker_definition (p, &p, marker);
3317 return 1;
3318 }
3319
3320 return 0;
3321}
3322
0fb4aa4b 3323static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3324remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3325 const char *strid)
0fb4aa4b
PA
3326{
3327 struct remote_state *rs = get_remote_state ();
3328 VEC(static_tracepoint_marker_p) *markers = NULL;
3329 struct static_tracepoint_marker *marker = NULL;
3330 struct cleanup *old_chain;
3331 char *p;
3332
3333 /* Ask for a first packet of static tracepoint marker
3334 definition. */
3335 putpkt ("qTfSTM");
3336 getpkt (&rs->buf, &rs->buf_size, 0);
3337 p = rs->buf;
3338 if (*p == 'E')
3339 error (_("Remote failure reply: %s"), p);
3340
3341 old_chain = make_cleanup (free_current_marker, &marker);
3342
3343 while (*p++ == 'm')
3344 {
3345 if (marker == NULL)
3346 marker = XCNEW (struct static_tracepoint_marker);
3347
3348 do
3349 {
3350 parse_static_tracepoint_marker_definition (p, &p, marker);
3351
3352 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3353 {
3354 VEC_safe_push (static_tracepoint_marker_p,
3355 markers, marker);
3356 marker = NULL;
3357 }
3358 else
3359 {
3360 release_static_tracepoint_marker (marker);
3361 memset (marker, 0, sizeof (*marker));
3362 }
3363 }
3364 while (*p++ == ','); /* comma-separated list */
3365 /* Ask for another packet of static tracepoint definition. */
3366 putpkt ("qTsSTM");
3367 getpkt (&rs->buf, &rs->buf_size, 0);
3368 p = rs->buf;
3369 }
3370
3371 do_cleanups (old_chain);
3372 return markers;
3373}
3374
3375\f
10760264
JB
3376/* Implement the to_get_ada_task_ptid function for the remote targets. */
3377
3378static ptid_t
1e6b91a4 3379remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3380{
ba348170 3381 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3382}
3383\f
3384
24b06219 3385/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3386
3387static void
fba45db2 3388extended_remote_restart (void)
c906108c 3389{
d01949b6 3390 struct remote_state *rs = get_remote_state ();
c906108c
SS
3391
3392 /* Send the restart command; for reasons I don't understand the
3393 remote side really expects a number after the "R". */
ea9c271d 3394 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3395 putpkt (rs->buf);
c906108c 3396
ad9a8f3f 3397 remote_fileio_reset ();
c906108c
SS
3398}
3399\f
3400/* Clean up connection to a remote debugger. */
3401
c906108c 3402static void
de90e03d 3403remote_close (struct target_ops *self)
c906108c 3404{
5d93a237
TT
3405 struct remote_state *rs = get_remote_state ();
3406
3407 if (rs->remote_desc == NULL)
d3fd5342
PA
3408 return; /* already closed */
3409
3410 /* Make sure we leave stdin registered in the event loop, and we
3411 don't leave the async SIGINT signal handler installed. */
e3594fd1 3412 remote_terminal_ours (self);
ce5ce7ed 3413
5d93a237
TT
3414 serial_close (rs->remote_desc);
3415 rs->remote_desc = NULL;
ce5ce7ed
PA
3416
3417 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3418 of all the inferiors and their threads we were controlling.
3419 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3420 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3421 inferior_ptid = null_ptid;
f67fd822 3422 discard_all_inferiors ();
ce5ce7ed 3423
f48ff2a7
YQ
3424 /* We are closing the remote target, so we should discard
3425 everything of this target. */
bcc75809 3426 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3427
3428 if (remote_async_inferior_event_token)
3429 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3430
5965e028 3431 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3432
3433 trace_reset_local_state ();
c906108c
SS
3434}
3435
23860348 3436/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3437
3438static void
fba45db2 3439get_offsets (void)
c906108c 3440{
d01949b6 3441 struct remote_state *rs = get_remote_state ();
2e9f7625 3442 char *buf;
085dd6e6 3443 char *ptr;
31d99776
DJ
3444 int lose, num_segments = 0, do_sections, do_segments;
3445 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3446 struct section_offsets *offs;
31d99776
DJ
3447 struct symfile_segment_data *data;
3448
3449 if (symfile_objfile == NULL)
3450 return;
c906108c
SS
3451
3452 putpkt ("qOffsets");
6d820c5c 3453 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3454 buf = rs->buf;
c906108c
SS
3455
3456 if (buf[0] == '\000')
3457 return; /* Return silently. Stub doesn't support
23860348 3458 this command. */
c906108c
SS
3459 if (buf[0] == 'E')
3460 {
8a3fe4f8 3461 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3462 return;
3463 }
3464
3465 /* Pick up each field in turn. This used to be done with scanf, but
3466 scanf will make trouble if CORE_ADDR size doesn't match
3467 conversion directives correctly. The following code will work
3468 with any size of CORE_ADDR. */
3469 text_addr = data_addr = bss_addr = 0;
3470 ptr = buf;
3471 lose = 0;
3472
61012eef 3473 if (startswith (ptr, "Text="))
c906108c
SS
3474 {
3475 ptr += 5;
3476 /* Don't use strtol, could lose on big values. */
3477 while (*ptr && *ptr != ';')
3478 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3479
61012eef 3480 if (startswith (ptr, ";Data="))
31d99776
DJ
3481 {
3482 ptr += 6;
3483 while (*ptr && *ptr != ';')
3484 data_addr = (data_addr << 4) + fromhex (*ptr++);
3485 }
3486 else
3487 lose = 1;
3488
61012eef 3489 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3490 {
3491 ptr += 5;
3492 while (*ptr && *ptr != ';')
3493 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3494
31d99776
DJ
3495 if (bss_addr != data_addr)
3496 warning (_("Target reported unsupported offsets: %s"), buf);
3497 }
3498 else
3499 lose = 1;
3500 }
61012eef 3501 else if (startswith (ptr, "TextSeg="))
c906108c 3502 {
31d99776
DJ
3503 ptr += 8;
3504 /* Don't use strtol, could lose on big values. */
c906108c 3505 while (*ptr && *ptr != ';')
31d99776
DJ
3506 text_addr = (text_addr << 4) + fromhex (*ptr++);
3507 num_segments = 1;
3508
61012eef 3509 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3510 {
3511 ptr += 9;
3512 while (*ptr && *ptr != ';')
3513 data_addr = (data_addr << 4) + fromhex (*ptr++);
3514 num_segments++;
3515 }
c906108c
SS
3516 }
3517 else
3518 lose = 1;
3519
3520 if (lose)
8a3fe4f8 3521 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3522 else if (*ptr != '\0')
3523 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3524
802188a7 3525 offs = ((struct section_offsets *)
a39a16c4 3526 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3527 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3528 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3529
31d99776
DJ
3530 data = get_symfile_segment_data (symfile_objfile->obfd);
3531 do_segments = (data != NULL);
3532 do_sections = num_segments == 0;
c906108c 3533
28c32713 3534 if (num_segments > 0)
31d99776 3535 {
31d99776
DJ
3536 segments[0] = text_addr;
3537 segments[1] = data_addr;
3538 }
28c32713
JB
3539 /* If we have two segments, we can still try to relocate everything
3540 by assuming that the .text and .data offsets apply to the whole
3541 text and data segments. Convert the offsets given in the packet
3542 to base addresses for symfile_map_offsets_to_segments. */
3543 else if (data && data->num_segments == 2)
3544 {
3545 segments[0] = data->segment_bases[0] + text_addr;
3546 segments[1] = data->segment_bases[1] + data_addr;
3547 num_segments = 2;
3548 }
8d385431
DJ
3549 /* If the object file has only one segment, assume that it is text
3550 rather than data; main programs with no writable data are rare,
3551 but programs with no code are useless. Of course the code might
3552 have ended up in the data segment... to detect that we would need
3553 the permissions here. */
3554 else if (data && data->num_segments == 1)
3555 {
3556 segments[0] = data->segment_bases[0] + text_addr;
3557 num_segments = 1;
3558 }
28c32713
JB
3559 /* There's no way to relocate by segment. */
3560 else
3561 do_segments = 0;
31d99776
DJ
3562
3563 if (do_segments)
3564 {
3565 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3566 offs, num_segments, segments);
3567
3568 if (ret == 0 && !do_sections)
3e43a32a
MS
3569 error (_("Can not handle qOffsets TextSeg "
3570 "response with this symbol file"));
31d99776
DJ
3571
3572 if (ret > 0)
3573 do_sections = 0;
3574 }
c906108c 3575
9ef895d6
DJ
3576 if (data)
3577 free_symfile_segment_data (data);
31d99776
DJ
3578
3579 if (do_sections)
3580 {
3581 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3582
3e43a32a
MS
3583 /* This is a temporary kludge to force data and bss to use the
3584 same offsets because that's what nlmconv does now. The real
3585 solution requires changes to the stub and remote.c that I
3586 don't have time to do right now. */
31d99776
DJ
3587
3588 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3589 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3590 }
c906108c
SS
3591
3592 objfile_relocate (symfile_objfile, offs);
3593}
3594
9a7071a8
JB
3595/* Send interrupt_sequence to remote target. */
3596static void
eeae04df 3597send_interrupt_sequence (void)
9a7071a8 3598{
5d93a237
TT
3599 struct remote_state *rs = get_remote_state ();
3600
9a7071a8 3601 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3602 remote_serial_write ("\x03", 1);
9a7071a8 3603 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3604 serial_send_break (rs->remote_desc);
9a7071a8
JB
3605 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3606 {
5d93a237 3607 serial_send_break (rs->remote_desc);
c33e31fd 3608 remote_serial_write ("g", 1);
9a7071a8
JB
3609 }
3610 else
3611 internal_error (__FILE__, __LINE__,
3612 _("Invalid value for interrupt_sequence_mode: %s."),
3613 interrupt_sequence_mode);
3614}
3615
3405876a
PA
3616
3617/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3618 and extract the PTID. Returns NULL_PTID if not found. */
3619
3620static ptid_t
3621stop_reply_extract_thread (char *stop_reply)
3622{
3623 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3624 {
3625 char *p;
3626
3627 /* Txx r:val ; r:val (...) */
3628 p = &stop_reply[3];
3629
3630 /* Look for "register" named "thread". */
3631 while (*p != '\0')
3632 {
3633 char *p1;
3634
3635 p1 = strchr (p, ':');
3636 if (p1 == NULL)
3637 return null_ptid;
3638
3639 if (strncmp (p, "thread", p1 - p) == 0)
3640 return read_ptid (++p1, &p);
3641
3642 p1 = strchr (p, ';');
3643 if (p1 == NULL)
3644 return null_ptid;
3645 p1++;
3646
3647 p = p1;
3648 }
3649 }
3650
3651 return null_ptid;
3652}
3653
b7ea362b
PA
3654/* Determine the remote side's current thread. If we have a stop
3655 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3656 "thread" register we can extract the current thread from. If not,
3657 ask the remote which is the current thread with qC. The former
3658 method avoids a roundtrip. */
3659
3660static ptid_t
3661get_current_thread (char *wait_status)
3662{
6a49a997 3663 ptid_t ptid = null_ptid;
b7ea362b
PA
3664
3665 /* Note we don't use remote_parse_stop_reply as that makes use of
3666 the target architecture, which we haven't yet fully determined at
3667 this point. */
3668 if (wait_status != NULL)
3669 ptid = stop_reply_extract_thread (wait_status);
3670 if (ptid_equal (ptid, null_ptid))
3671 ptid = remote_current_thread (inferior_ptid);
3672
3673 return ptid;
3674}
3675
49c62f2e
PA
3676/* Query the remote target for which is the current thread/process,
3677 add it to our tables, and update INFERIOR_PTID. The caller is
3678 responsible for setting the state such that the remote end is ready
3405876a
PA
3679 to return the current thread.
3680
3681 This function is called after handling the '?' or 'vRun' packets,
3682 whose response is a stop reply from which we can also try
3683 extracting the thread. If the target doesn't support the explicit
3684 qC query, we infer the current thread from that stop reply, passed
3685 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3686
3687static void
3405876a 3688add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3689{
3690 struct remote_state *rs = get_remote_state ();
3691 int fake_pid_p = 0;
6a49a997 3692 ptid_t ptid;
49c62f2e
PA
3693
3694 inferior_ptid = null_ptid;
3695
b7ea362b
PA
3696 /* Now, if we have thread information, update inferior_ptid. */
3697 ptid = get_current_thread (wait_status);
3405876a 3698
49c62f2e
PA
3699 if (!ptid_equal (ptid, null_ptid))
3700 {
3701 if (!remote_multi_process_p (rs))
3702 fake_pid_p = 1;
3703
3704 inferior_ptid = ptid;
3705 }
3706 else
3707 {
3708 /* Without this, some commands which require an active target
3709 (such as kill) won't work. This variable serves (at least)
3710 double duty as both the pid of the target process (if it has
3711 such), and as a flag indicating that a target is active. */
3712 inferior_ptid = magic_null_ptid;
3713 fake_pid_p = 1;
3714 }
3715
1b6e6f5c 3716 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3717
3718 /* Add the main thread. */
3719 add_thread_silent (inferior_ptid);
3720}
3721
6efcd9a8
PA
3722/* Print info about a thread that was found already stopped on
3723 connection. */
3724
3725static void
3726print_one_stopped_thread (struct thread_info *thread)
3727{
3728 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3729
3730 switch_to_thread (thread->ptid);
3731 stop_pc = get_frame_pc (get_current_frame ());
3732 set_current_sal_from_frame (get_current_frame ());
3733
3734 thread->suspend.waitstatus_pending_p = 0;
3735
3736 if (ws->kind == TARGET_WAITKIND_STOPPED)
3737 {
3738 enum gdb_signal sig = ws->value.sig;
3739
3740 if (signal_print_state (sig))
3741 observer_notify_signal_received (sig);
3742 }
3743 observer_notify_normal_stop (NULL, 1);
3744}
3745
221e1a37
PA
3746/* Process all initial stop replies the remote side sent in response
3747 to the ? packet. These indicate threads that were already stopped
3748 on initial connection. We mark these threads as stopped and print
3749 their current frame before giving the user the prompt. */
3750
3751static void
6efcd9a8 3752process_initial_stop_replies (int from_tty)
221e1a37
PA
3753{
3754 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3755 struct inferior *inf;
3756 struct thread_info *thread;
3757 struct thread_info *selected = NULL;
3758 struct thread_info *lowest_stopped = NULL;
3759 struct thread_info *first = NULL;
221e1a37
PA
3760
3761 /* Consume the initial pending events. */
3762 while (pending_stop_replies-- > 0)
3763 {
3764 ptid_t waiton_ptid = minus_one_ptid;
3765 ptid_t event_ptid;
3766 struct target_waitstatus ws;
3767 int ignore_event = 0;
6efcd9a8 3768 struct thread_info *thread;
221e1a37
PA
3769
3770 memset (&ws, 0, sizeof (ws));
3771 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3772 if (remote_debug)
3773 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3774
3775 switch (ws.kind)
3776 {
3777 case TARGET_WAITKIND_IGNORE:
3778 case TARGET_WAITKIND_NO_RESUMED:
3779 case TARGET_WAITKIND_SIGNALLED:
3780 case TARGET_WAITKIND_EXITED:
3781 /* We shouldn't see these, but if we do, just ignore. */
3782 if (remote_debug)
3783 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3784 ignore_event = 1;
3785 break;
3786
3787 case TARGET_WAITKIND_EXECD:
3788 xfree (ws.value.execd_pathname);
3789 break;
3790 default:
3791 break;
3792 }
3793
3794 if (ignore_event)
3795 continue;
3796
6efcd9a8 3797 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3798
3799 if (ws.kind == TARGET_WAITKIND_STOPPED)
3800 {
3801 enum gdb_signal sig = ws.value.sig;
3802
3803 /* Stubs traditionally report SIGTRAP as initial signal,
3804 instead of signal 0. Suppress it. */
3805 if (sig == GDB_SIGNAL_TRAP)
3806 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3807 thread->suspend.stop_signal = sig;
3808 ws.value.sig = sig;
3809 }
221e1a37 3810
6efcd9a8
PA
3811 thread->suspend.waitstatus = ws;
3812
3813 if (ws.kind != TARGET_WAITKIND_STOPPED
3814 || ws.value.sig != GDB_SIGNAL_0)
3815 thread->suspend.waitstatus_pending_p = 1;
3816
3817 set_executing (event_ptid, 0);
3818 set_running (event_ptid, 0);
3819 }
3820
3821 /* "Notice" the new inferiors before anything related to
3822 registers/memory. */
3823 ALL_INFERIORS (inf)
3824 {
3825 if (inf->pid == 0)
3826 continue;
3827
3828 inf->needs_setup = 1;
3829
3830 if (non_stop)
3831 {
3832 thread = any_live_thread_of_process (inf->pid);
3833 notice_new_inferior (thread->ptid,
3834 thread->state == THREAD_RUNNING,
3835 from_tty);
3836 }
3837 }
3838
3839 /* If all-stop on top of non-stop, pause all threads. Note this
3840 records the threads' stop pc, so must be done after "noticing"
3841 the inferiors. */
3842 if (!non_stop)
3843 {
3844 stop_all_threads ();
3845
3846 /* If all threads of an inferior were already stopped, we
3847 haven't setup the inferior yet. */
3848 ALL_INFERIORS (inf)
3849 {
3850 if (inf->pid == 0)
3851 continue;
221e1a37 3852
6efcd9a8
PA
3853 if (inf->needs_setup)
3854 {
3855 thread = any_live_thread_of_process (inf->pid);
3856 switch_to_thread_no_regs (thread);
3857 setup_inferior (0);
3858 }
3859 }
221e1a37 3860 }
6efcd9a8
PA
3861
3862 /* Now go over all threads that are stopped, and print their current
3863 frame. If all-stop, then if there's a signalled thread, pick
3864 that as current. */
3865 ALL_NON_EXITED_THREADS (thread)
3866 {
3867 struct target_waitstatus *ws;
3868
3869 if (first == NULL)
3870 first = thread;
3871
3872 if (!non_stop)
3873 set_running (thread->ptid, 0);
3874 else if (thread->state != THREAD_STOPPED)
3875 continue;
3876
3877 ws = &thread->suspend.waitstatus;
3878
3879 if (selected == NULL
3880 && thread->suspend.waitstatus_pending_p)
3881 selected = thread;
3882
3883 if (lowest_stopped == NULL || thread->num < lowest_stopped->num)
3884 lowest_stopped = thread;
3885
3886 if (non_stop)
3887 print_one_stopped_thread (thread);
3888 }
3889
3890 /* In all-stop, we only print the status of one thread, and leave
3891 others with their status pending. */
3892 if (!non_stop)
3893 {
3894 thread = selected;
3895 if (thread == NULL)
3896 thread = lowest_stopped;
3897 if (thread == NULL)
3898 thread = first;
3899
3900 print_one_stopped_thread (thread);
3901 }
3902
3903 /* For "info program". */
3904 thread = inferior_thread ();
3905 if (thread->state == THREAD_STOPPED)
3906 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
3907}
3908
9cbc821d 3909static void
04bd08de 3910remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3911{
c8d104ad
PA
3912 struct remote_state *rs = get_remote_state ();
3913 struct packet_config *noack_config;
2d717e4f 3914 char *wait_status = NULL;
8621d6a9 3915
23860348 3916 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3917 QUIT;
c906108c 3918
9a7071a8
JB
3919 if (interrupt_on_connect)
3920 send_interrupt_sequence ();
3921
57e12211 3922 /* Ack any packet which the remote side has already sent. */
5d93a237 3923 serial_write (rs->remote_desc, "+", 1);
57e12211 3924
1e51243a
PA
3925 /* Signal other parts that we're going through the initial setup,
3926 and so things may not be stable yet. */
3927 rs->starting_up = 1;
3928
c8d104ad
PA
3929 /* The first packet we send to the target is the optional "supported
3930 packets" request. If the target can answer this, it will tell us
3931 which later probes to skip. */
3932 remote_query_supported ();
3933
d914c394 3934 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3935 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3936 remote_set_permissions (target);
d914c394 3937
c8d104ad
PA
3938 /* Next, we possibly activate noack mode.
3939
3940 If the QStartNoAckMode packet configuration is set to AUTO,
3941 enable noack mode if the stub reported a wish for it with
3942 qSupported.
3943
3944 If set to TRUE, then enable noack mode even if the stub didn't
3945 report it in qSupported. If the stub doesn't reply OK, the
3946 session ends with an error.
3947
3948 If FALSE, then don't activate noack mode, regardless of what the
3949 stub claimed should be the default with qSupported. */
3950
3951 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3952 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3953 {
3954 putpkt ("QStartNoAckMode");
3955 getpkt (&rs->buf, &rs->buf_size, 0);
3956 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3957 rs->noack_mode = 1;
3958 }
3959
04bd08de 3960 if (extended_p)
5fe04517
PA
3961 {
3962 /* Tell the remote that we are using the extended protocol. */
3963 putpkt ("!");
3964 getpkt (&rs->buf, &rs->buf_size, 0);
3965 }
3966
9b224c5e
PA
3967 /* Let the target know which signals it is allowed to pass down to
3968 the program. */
3969 update_signals_program_target ();
3970
d962ef82
DJ
3971 /* Next, if the target can specify a description, read it. We do
3972 this before anything involving memory or registers. */
3973 target_find_description ();
3974
6c95b8df
PA
3975 /* Next, now that we know something about the target, update the
3976 address spaces in the program spaces. */
3977 update_address_spaces ();
3978
50c71eaf
PA
3979 /* On OSs where the list of libraries is global to all
3980 processes, we fetch them early. */
f5656ead 3981 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3982 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3983
6efcd9a8 3984 if (target_is_non_stop_p ())
74531fed 3985 {
4082afcc 3986 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3987 error (_("Non-stop mode requested, but remote "
3988 "does not support non-stop"));
74531fed
PA
3989
3990 putpkt ("QNonStop:1");
3991 getpkt (&rs->buf, &rs->buf_size, 0);
3992
3993 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3994 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3995
3996 /* Find about threads and processes the stub is already
3997 controlling. We default to adding them in the running state.
3998 The '?' query below will then tell us about which threads are
3999 stopped. */
e8032dde 4000 remote_update_thread_list (target);
74531fed 4001 }
4082afcc 4002 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4003 {
4004 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4005 Request it explicitly. */
74531fed
PA
4006 putpkt ("QNonStop:0");
4007 getpkt (&rs->buf, &rs->buf_size, 0);
4008
4009 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4010 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4011 }
4012
a0743c90
YQ
4013 /* Upload TSVs regardless of whether the target is running or not. The
4014 remote stub, such as GDBserver, may have some predefined or builtin
4015 TSVs, even if the target is not running. */
8bd200f1 4016 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4017 {
4018 struct uploaded_tsv *uploaded_tsvs = NULL;
4019
181e3713 4020 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4021 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4022 }
4023
2d717e4f
DJ
4024 /* Check whether the target is running now. */
4025 putpkt ("?");
4026 getpkt (&rs->buf, &rs->buf_size, 0);
4027
6efcd9a8 4028 if (!target_is_non_stop_p ())
2d717e4f 4029 {
e714e1bf
UW
4030 ptid_t ptid;
4031 int fake_pid_p = 0;
4032 struct inferior *inf;
4033
74531fed 4034 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4035 {
04bd08de 4036 if (!extended_p)
74531fed 4037 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4038
4039 /* We're connected, but not running. Drop out before we
4040 call start_remote. */
e278ad5b 4041 rs->starting_up = 0;
c35b1492 4042 return;
2d717e4f
DJ
4043 }
4044 else
74531fed 4045 {
74531fed 4046 /* Save the reply for later. */
224c3ddb 4047 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4048 strcpy (wait_status, rs->buf);
4049 }
4050
b7ea362b 4051 /* Fetch thread list. */
e8032dde 4052 target_update_thread_list ();
b7ea362b 4053
74531fed
PA
4054 /* Let the stub know that we want it to return the thread. */
4055 set_continue_thread (minus_one_ptid);
4056
b7ea362b
PA
4057 if (thread_count () == 0)
4058 {
4059 /* Target has no concept of threads at all. GDB treats
4060 non-threaded target as single-threaded; add a main
4061 thread. */
4062 add_current_inferior_and_thread (wait_status);
4063 }
4064 else
4065 {
4066 /* We have thread information; select the thread the target
4067 says should be current. If we're reconnecting to a
4068 multi-threaded program, this will ideally be the thread
4069 that last reported an event before GDB disconnected. */
4070 inferior_ptid = get_current_thread (wait_status);
4071 if (ptid_equal (inferior_ptid, null_ptid))
4072 {
4073 /* Odd... The target was able to list threads, but not
4074 tell us which thread was current (no "thread"
4075 register in T stop reply?). Just pick the first
4076 thread in the thread list then. */
c9f35b34
KB
4077
4078 if (remote_debug)
4079 fprintf_unfiltered (gdb_stdlog,
4080 "warning: couldn't determine remote "
4081 "current thread; picking first in list.\n");
4082
b7ea362b
PA
4083 inferior_ptid = thread_list->ptid;
4084 }
4085 }
74531fed 4086
6e586cc5
YQ
4087 /* init_wait_for_inferior should be called before get_offsets in order
4088 to manage `inserted' flag in bp loc in a correct state.
4089 breakpoint_init_inferior, called from init_wait_for_inferior, set
4090 `inserted' flag to 0, while before breakpoint_re_set, called from
4091 start_remote, set `inserted' flag to 1. In the initialization of
4092 inferior, breakpoint_init_inferior should be called first, and then
4093 breakpoint_re_set can be called. If this order is broken, state of
4094 `inserted' flag is wrong, and cause some problems on breakpoint
4095 manipulation. */
4096 init_wait_for_inferior ();
4097
74531fed
PA
4098 get_offsets (); /* Get text, data & bss offsets. */
4099
d962ef82
DJ
4100 /* If we could not find a description using qXfer, and we know
4101 how to do it some other way, try again. This is not
4102 supported for non-stop; it could be, but it is tricky if
4103 there are no stopped threads when we connect. */
04bd08de 4104 if (remote_read_description_p (target)
f5656ead 4105 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4106 {
4107 target_clear_description ();
4108 target_find_description ();
4109 }
4110
74531fed
PA
4111 /* Use the previously fetched status. */
4112 gdb_assert (wait_status != NULL);
4113 strcpy (rs->buf, wait_status);
4114 rs->cached_wait_status = 1;
4115
4116 immediate_quit--;
04bd08de 4117 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4118 }
4119 else
4120 {
68c97600
PA
4121 /* Clear WFI global state. Do this before finding about new
4122 threads and inferiors, and setting the current inferior.
4123 Otherwise we would clear the proceed status of the current
4124 inferior when we want its stop_soon state to be preserved
4125 (see notice_new_inferior). */
4126 init_wait_for_inferior ();
4127
74531fed
PA
4128 /* In non-stop, we will either get an "OK", meaning that there
4129 are no stopped threads at this time; or, a regular stop
4130 reply. In the latter case, there may be more than one thread
4131 stopped --- we pull them all out using the vStopped
4132 mechanism. */
4133 if (strcmp (rs->buf, "OK") != 0)
4134 {
722247f1 4135 struct notif_client *notif = &notif_client_stop;
2d717e4f 4136
722247f1
YQ
4137 /* remote_notif_get_pending_replies acks this one, and gets
4138 the rest out. */
f48ff2a7 4139 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4140 = remote_notif_parse (notif, rs->buf);
4141 remote_notif_get_pending_events (notif);
74531fed 4142 }
2d717e4f 4143
74531fed
PA
4144 if (thread_count () == 0)
4145 {
04bd08de 4146 if (!extended_p)
74531fed 4147 error (_("The target is not running (try extended-remote?)"));
82f73884 4148
c35b1492
PA
4149 /* We're connected, but not running. Drop out before we
4150 call start_remote. */
e278ad5b 4151 rs->starting_up = 0;
c35b1492
PA
4152 return;
4153 }
74531fed 4154
74531fed
PA
4155 /* In non-stop mode, any cached wait status will be stored in
4156 the stop reply queue. */
4157 gdb_assert (wait_status == NULL);
f0223081 4158
2455069d 4159 /* Report all signals during attach/startup. */
94bedb42 4160 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4161
4162 /* If there are already stopped threads, mark them stopped and
4163 report their stops before giving the prompt to the user. */
6efcd9a8 4164 process_initial_stop_replies (from_tty);
221e1a37
PA
4165
4166 if (target_can_async_p ())
4167 target_async (1);
74531fed 4168 }
c8d104ad 4169
c8d104ad
PA
4170 /* If we connected to a live target, do some additional setup. */
4171 if (target_has_execution)
4172 {
f4ccffad 4173 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4174 remote_check_symbols ();
c8d104ad 4175 }
50c71eaf 4176
d5551862
SS
4177 /* Possibly the target has been engaged in a trace run started
4178 previously; find out where things are at. */
8bd200f1 4179 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4180 {
00bf0b85 4181 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4182
00bf0b85
SS
4183 if (current_trace_status ()->running)
4184 printf_filtered (_("Trace is already running on the target.\n"));
4185
ab6617cc 4186 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4187
4188 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4189 }
4190
1e51243a
PA
4191 /* The thread and inferior lists are now synchronized with the
4192 target, our symbols have been relocated, and we're merged the
4193 target's tracepoints with ours. We're done with basic start
4194 up. */
4195 rs->starting_up = 0;
4196
a25a5a45
PA
4197 /* Maybe breakpoints are global and need to be inserted now. */
4198 if (breakpoints_should_be_inserted_now ())
50c71eaf 4199 insert_breakpoints ();
c906108c
SS
4200}
4201
4202/* Open a connection to a remote debugger.
4203 NAME is the filename used for communication. */
4204
4205static void
014f9477 4206remote_open (const char *name, int from_tty)
c906108c 4207{
75c99385 4208 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4209}
4210
c906108c
SS
4211/* Open a connection to a remote debugger using the extended
4212 remote gdb protocol. NAME is the filename used for communication. */
4213
4214static void
014f9477 4215extended_remote_open (const char *name, int from_tty)
c906108c 4216{
75c99385 4217 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4218}
4219
ca4f7f8b
PA
4220/* Reset all packets back to "unknown support". Called when opening a
4221 new connection to a remote target. */
c906108c 4222
d471ea57 4223static void
ca4f7f8b 4224reset_all_packet_configs_support (void)
d471ea57
AC
4225{
4226 int i;
a744cf53 4227
444abaca 4228 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4229 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4230}
4231
ca4f7f8b
PA
4232/* Initialize all packet configs. */
4233
4234static void
4235init_all_packet_configs (void)
4236{
4237 int i;
4238
4239 for (i = 0; i < PACKET_MAX; i++)
4240 {
4241 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4242 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4243 }
4244}
4245
23860348 4246/* Symbol look-up. */
dc8acb97
MS
4247
4248static void
36d25514 4249remote_check_symbols (void)
dc8acb97 4250{
d01949b6 4251 struct remote_state *rs = get_remote_state ();
dc8acb97 4252 char *msg, *reply, *tmp;
3b7344d5 4253 struct bound_minimal_symbol sym;
dc8acb97 4254 int end;
a5c0808e 4255 struct cleanup *old_chain;
dc8acb97 4256
63154eca
PA
4257 /* The remote side has no concept of inferiors that aren't running
4258 yet, it only knows about running processes. If we're connected
4259 but our current inferior is not running, we should not invite the
4260 remote target to request symbol lookups related to its
4261 (unrelated) current process. */
4262 if (!target_has_execution)
4263 return;
4264
4082afcc 4265 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4266 return;
4267
63154eca
PA
4268 /* Make sure the remote is pointing at the right process. Note
4269 there's no way to select "no process". */
3c9c4b83
PA
4270 set_general_process ();
4271
6d820c5c
DJ
4272 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4273 because we need both at the same time. */
224c3ddb 4274 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4275 old_chain = make_cleanup (xfree, msg);
6d820c5c 4276
23860348 4277 /* Invite target to request symbol lookups. */
dc8acb97
MS
4278
4279 putpkt ("qSymbol::");
6d820c5c
DJ
4280 getpkt (&rs->buf, &rs->buf_size, 0);
4281 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 4282 reply = rs->buf;
dc8acb97 4283
61012eef 4284 while (startswith (reply, "qSymbol:"))
dc8acb97 4285 {
77e371c0
TT
4286 struct bound_minimal_symbol sym;
4287
dc8acb97 4288 tmp = &reply[8];
cfd77fa1 4289 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4290 msg[end] = '\0';
4291 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4292 if (sym.minsym == NULL)
ea9c271d 4293 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4294 else
2bbe3cc1 4295 {
f5656ead 4296 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4297 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4298
4299 /* If this is a function address, return the start of code
4300 instead of any data function descriptor. */
f5656ead 4301 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4302 sym_addr,
4303 &current_target);
4304
4305 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4306 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4307 }
4308
dc8acb97 4309 putpkt (msg);
6d820c5c 4310 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4311 reply = rs->buf;
dc8acb97 4312 }
a5c0808e
PA
4313
4314 do_cleanups (old_chain);
dc8acb97
MS
4315}
4316
9db8d71f 4317static struct serial *
baa336ce 4318remote_serial_open (const char *name)
9db8d71f
DJ
4319{
4320 static int udp_warning = 0;
4321
4322 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4323 of in ser-tcp.c, because it is the remote protocol assuming that the
4324 serial connection is reliable and not the serial connection promising
4325 to be. */
61012eef 4326 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4327 {
3e43a32a
MS
4328 warning (_("The remote protocol may be unreliable over UDP.\n"
4329 "Some events may be lost, rendering further debugging "
4330 "impossible."));
9db8d71f
DJ
4331 udp_warning = 1;
4332 }
4333
4334 return serial_open (name);
4335}
4336
d914c394
SS
4337/* Inform the target of our permission settings. The permission flags
4338 work without this, but if the target knows the settings, it can do
4339 a couple things. First, it can add its own check, to catch cases
4340 that somehow manage to get by the permissions checks in target
4341 methods. Second, if the target is wired to disallow particular
4342 settings (for instance, a system in the field that is not set up to
4343 be able to stop at a breakpoint), it can object to any unavailable
4344 permissions. */
4345
4346void
c378d69d 4347remote_set_permissions (struct target_ops *self)
d914c394
SS
4348{
4349 struct remote_state *rs = get_remote_state ();
4350
bba74b36
YQ
4351 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4352 "WriteReg:%x;WriteMem:%x;"
4353 "InsertBreak:%x;InsertTrace:%x;"
4354 "InsertFastTrace:%x;Stop:%x",
4355 may_write_registers, may_write_memory,
4356 may_insert_breakpoints, may_insert_tracepoints,
4357 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4358 putpkt (rs->buf);
4359 getpkt (&rs->buf, &rs->buf_size, 0);
4360
4361 /* If the target didn't like the packet, warn the user. Do not try
4362 to undo the user's settings, that would just be maddening. */
4363 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4364 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4365}
4366
be2a5f71
DJ
4367/* This type describes each known response to the qSupported
4368 packet. */
4369struct protocol_feature
4370{
4371 /* The name of this protocol feature. */
4372 const char *name;
4373
4374 /* The default for this protocol feature. */
4375 enum packet_support default_support;
4376
4377 /* The function to call when this feature is reported, or after
4378 qSupported processing if the feature is not supported.
4379 The first argument points to this structure. The second
4380 argument indicates whether the packet requested support be
4381 enabled, disabled, or probed (or the default, if this function
4382 is being called at the end of processing and this feature was
4383 not reported). The third argument may be NULL; if not NULL, it
4384 is a NUL-terminated string taken from the packet following
4385 this feature's name and an equals sign. */
4386 void (*func) (const struct protocol_feature *, enum packet_support,
4387 const char *);
4388
4389 /* The corresponding packet for this feature. Only used if
4390 FUNC is remote_supported_packet. */
4391 int packet;
4392};
4393
be2a5f71
DJ
4394static void
4395remote_supported_packet (const struct protocol_feature *feature,
4396 enum packet_support support,
4397 const char *argument)
4398{
4399 if (argument)
4400 {
4401 warning (_("Remote qSupported response supplied an unexpected value for"
4402 " \"%s\"."), feature->name);
4403 return;
4404 }
4405
4082afcc 4406 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4407}
be2a5f71
DJ
4408
4409static void
4410remote_packet_size (const struct protocol_feature *feature,
4411 enum packet_support support, const char *value)
4412{
4413 struct remote_state *rs = get_remote_state ();
4414
4415 int packet_size;
4416 char *value_end;
4417
4418 if (support != PACKET_ENABLE)
4419 return;
4420
4421 if (value == NULL || *value == '\0')
4422 {
4423 warning (_("Remote target reported \"%s\" without a size."),
4424 feature->name);
4425 return;
4426 }
4427
4428 errno = 0;
4429 packet_size = strtol (value, &value_end, 16);
4430 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4431 {
4432 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4433 feature->name, value);
4434 return;
4435 }
4436
be2a5f71
DJ
4437 /* Record the new maximum packet size. */
4438 rs->explicit_packet_size = packet_size;
4439}
4440
dc473cfb 4441static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4442 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4443 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4444 PACKET_qXfer_auxv },
c78fa86a
GB
4445 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4446 PACKET_qXfer_exec_file },
23181151
DJ
4447 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4448 PACKET_qXfer_features },
cfa9d6d9
DJ
4449 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4450 PACKET_qXfer_libraries },
2268b414
JK
4451 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4452 PACKET_qXfer_libraries_svr4 },
ced63ec0 4453 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4454 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4455 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4456 PACKET_qXfer_memory_map },
4de6483e
UW
4457 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4458 PACKET_qXfer_spu_read },
4459 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4460 PACKET_qXfer_spu_write },
07e059b5
VP
4461 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4462 PACKET_qXfer_osdata },
dc146f7c
VP
4463 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4464 PACKET_qXfer_threads },
b3b9301e
PA
4465 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4466 PACKET_qXfer_traceframe_info },
89be2091
DJ
4467 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4468 PACKET_QPassSignals },
9b224c5e
PA
4469 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4470 PACKET_QProgramSignals },
a6f3e723
SL
4471 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4472 PACKET_QStartNoAckMode },
4082afcc
PA
4473 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4474 PACKET_multiprocess_feature },
4475 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4476 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4477 PACKET_qXfer_siginfo_read },
4478 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4479 PACKET_qXfer_siginfo_write },
4082afcc 4480 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4481 PACKET_ConditionalTracepoints },
4082afcc 4482 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4483 PACKET_ConditionalBreakpoints },
4082afcc 4484 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4485 PACKET_BreakpointCommands },
4082afcc 4486 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4487 PACKET_FastTracepoints },
4082afcc 4488 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4489 PACKET_StaticTracepoints },
4082afcc 4490 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4491 PACKET_InstallInTrace},
4082afcc
PA
4492 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4493 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4494 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4495 PACKET_bc },
4496 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4497 PACKET_bs },
409873ef
SS
4498 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4499 PACKET_TracepointSource },
d914c394
SS
4500 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4501 PACKET_QAllow },
4082afcc
PA
4502 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4503 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4504 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4505 PACKET_qXfer_fdpic },
169081d0
TG
4506 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4507 PACKET_qXfer_uib },
03583c20
UW
4508 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4509 PACKET_QDisableRandomization },
d1feda86 4510 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4511 { "QTBuffer:size", PACKET_DISABLE,
4512 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4513 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4514 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4515 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4516 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4517 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4518 PACKET_qXfer_btrace },
4519 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4520 PACKET_qXfer_btrace_conf },
4521 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4522 PACKET_Qbtrace_conf_bts_size },
4523 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4524 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4525 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4526 PACKET_fork_event_feature },
4527 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4528 PACKET_vfork_event_feature },
94585166
DB
4529 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4530 PACKET_exec_event_feature },
b20a6524 4531 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4532 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4533 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4534 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4535 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4536};
4537
c8d5aac9
L
4538static char *remote_support_xml;
4539
4540/* Register string appended to "xmlRegisters=" in qSupported query. */
4541
4542void
6e39997a 4543register_remote_support_xml (const char *xml)
c8d5aac9
L
4544{
4545#if defined(HAVE_LIBEXPAT)
4546 if (remote_support_xml == NULL)
c4f7c687 4547 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4548 else
4549 {
4550 char *copy = xstrdup (remote_support_xml + 13);
4551 char *p = strtok (copy, ",");
4552
4553 do
4554 {
4555 if (strcmp (p, xml) == 0)
4556 {
4557 /* already there */
4558 xfree (copy);
4559 return;
4560 }
4561 }
4562 while ((p = strtok (NULL, ",")) != NULL);
4563 xfree (copy);
4564
94b0dee1
PA
4565 remote_support_xml = reconcat (remote_support_xml,
4566 remote_support_xml, ",", xml,
4567 (char *) NULL);
c8d5aac9
L
4568 }
4569#endif
4570}
4571
4572static char *
4573remote_query_supported_append (char *msg, const char *append)
4574{
4575 if (msg)
94b0dee1 4576 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4577 else
4578 return xstrdup (append);
4579}
4580
be2a5f71
DJ
4581static void
4582remote_query_supported (void)
4583{
4584 struct remote_state *rs = get_remote_state ();
4585 char *next;
4586 int i;
4587 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4588
4589 /* The packet support flags are handled differently for this packet
4590 than for most others. We treat an error, a disabled packet, and
4591 an empty response identically: any features which must be reported
4592 to be used will be automatically disabled. An empty buffer
4593 accomplishes this, since that is also the representation for a list
4594 containing no features. */
4595
4596 rs->buf[0] = 0;
4082afcc 4597 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4598 {
c8d5aac9 4599 char *q = NULL;
94b0dee1 4600 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4601
73b8c1fd
PA
4602 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4603 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4604
f7e6eed5
PA
4605 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4606 q = remote_query_supported_append (q, "swbreak+");
4607 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4608 q = remote_query_supported_append (q, "hwbreak+");
4609
dde08ee1
PA
4610 q = remote_query_supported_append (q, "qRelocInsn+");
4611
89245bc0
DB
4612 if (rs->extended)
4613 {
4614 if (packet_set_cmd_state (PACKET_fork_event_feature)
4615 != AUTO_BOOLEAN_FALSE)
4616 q = remote_query_supported_append (q, "fork-events+");
4617 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4618 != AUTO_BOOLEAN_FALSE)
4619 q = remote_query_supported_append (q, "vfork-events+");
94585166
DB
4620 if (packet_set_cmd_state (PACKET_exec_event_feature)
4621 != AUTO_BOOLEAN_FALSE)
4622 q = remote_query_supported_append (q, "exec-events+");
89245bc0
DB
4623 }
4624
750ce8d1
YQ
4625 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4626 q = remote_query_supported_append (q, "vContSupported+");
4627
65706a29
PA
4628 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4629 q = remote_query_supported_append (q, "QThreadEvents+");
4630
f2faf941
PA
4631 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4632 q = remote_query_supported_append (q, "no-resumed+");
4633
b35d5edb
PA
4634 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4635 the qSupported:xmlRegisters=i386 handling. */
4636 if (remote_support_xml != NULL)
4637 q = remote_query_supported_append (q, remote_support_xml);
4638
dde08ee1
PA
4639 q = reconcat (q, "qSupported:", q, (char *) NULL);
4640 putpkt (q);
82f73884 4641
94b0dee1
PA
4642 do_cleanups (old_chain);
4643
be2a5f71
DJ
4644 getpkt (&rs->buf, &rs->buf_size, 0);
4645
4646 /* If an error occured, warn, but do not return - just reset the
4647 buffer to empty and go on to disable features. */
4648 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4649 == PACKET_ERROR)
4650 {
4651 warning (_("Remote failure reply: %s"), rs->buf);
4652 rs->buf[0] = 0;
4653 }
4654 }
4655
4656 memset (seen, 0, sizeof (seen));
4657
4658 next = rs->buf;
4659 while (*next)
4660 {
4661 enum packet_support is_supported;
4662 char *p, *end, *name_end, *value;
4663
4664 /* First separate out this item from the rest of the packet. If
4665 there's another item after this, we overwrite the separator
4666 (terminated strings are much easier to work with). */
4667 p = next;
4668 end = strchr (p, ';');
4669 if (end == NULL)
4670 {
4671 end = p + strlen (p);
4672 next = end;
4673 }
4674 else
4675 {
89be2091
DJ
4676 *end = '\0';
4677 next = end + 1;
4678
be2a5f71
DJ
4679 if (end == p)
4680 {
4681 warning (_("empty item in \"qSupported\" response"));
4682 continue;
4683 }
be2a5f71
DJ
4684 }
4685
4686 name_end = strchr (p, '=');
4687 if (name_end)
4688 {
4689 /* This is a name=value entry. */
4690 is_supported = PACKET_ENABLE;
4691 value = name_end + 1;
4692 *name_end = '\0';
4693 }
4694 else
4695 {
4696 value = NULL;
4697 switch (end[-1])
4698 {
4699 case '+':
4700 is_supported = PACKET_ENABLE;
4701 break;
4702
4703 case '-':
4704 is_supported = PACKET_DISABLE;
4705 break;
4706
4707 case '?':
4708 is_supported = PACKET_SUPPORT_UNKNOWN;
4709 break;
4710
4711 default:
3e43a32a
MS
4712 warning (_("unrecognized item \"%s\" "
4713 "in \"qSupported\" response"), p);
be2a5f71
DJ
4714 continue;
4715 }
4716 end[-1] = '\0';
4717 }
4718
4719 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4720 if (strcmp (remote_protocol_features[i].name, p) == 0)
4721 {
4722 const struct protocol_feature *feature;
4723
4724 seen[i] = 1;
4725 feature = &remote_protocol_features[i];
4726 feature->func (feature, is_supported, value);
4727 break;
4728 }
4729 }
4730
4731 /* If we increased the packet size, make sure to increase the global
4732 buffer size also. We delay this until after parsing the entire
4733 qSupported packet, because this is the same buffer we were
4734 parsing. */
4735 if (rs->buf_size < rs->explicit_packet_size)
4736 {
4737 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4738 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4739 }
4740
4741 /* Handle the defaults for unmentioned features. */
4742 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4743 if (!seen[i])
4744 {
4745 const struct protocol_feature *feature;
4746
4747 feature = &remote_protocol_features[i];
4748 feature->func (feature, feature->default_support, NULL);
4749 }
4750}
4751
78a095c3
JK
4752/* Remove any of the remote.c targets from target stack. Upper targets depend
4753 on it so remove them first. */
4754
4755static void
4756remote_unpush_target (void)
4757{
915ef8b1 4758 pop_all_targets_at_and_above (process_stratum);
78a095c3 4759}
be2a5f71 4760
c906108c 4761static void
014f9477 4762remote_open_1 (const char *name, int from_tty,
3e43a32a 4763 struct target_ops *target, int extended_p)
c906108c 4764{
d01949b6 4765 struct remote_state *rs = get_remote_state ();
a6f3e723 4766
c906108c 4767 if (name == 0)
8a3fe4f8 4768 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4769 "serial device is attached to the remote system\n"
8a3fe4f8 4770 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4771
23860348 4772 /* See FIXME above. */
c6ebd6cf 4773 if (!target_async_permitted)
92d1e331 4774 wait_forever_enabled_p = 1;
6426a772 4775
2d717e4f 4776 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4777 Ask this question first, before target_preopen has a chance to kill
4778 anything. */
5d93a237 4779 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4780 {
78a095c3
JK
4781 if (from_tty
4782 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4783 error (_("Still connected."));
4784 }
4785
78a095c3 4786 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4787 target_preopen (from_tty);
4788
89be2091 4789 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4790 xfree (rs->last_pass_packet);
4791 rs->last_pass_packet = NULL;
89be2091 4792
9b224c5e
PA
4793 /* Make sure we send the program signals list the next time we
4794 resume. */
5e4a05c4
TT
4795 xfree (rs->last_program_signals_packet);
4796 rs->last_program_signals_packet = NULL;
9b224c5e 4797
ad9a8f3f 4798 remote_fileio_reset ();
1dd41f16
NS
4799 reopen_exec_file ();
4800 reread_symbols ();
4801
5d93a237
TT
4802 rs->remote_desc = remote_serial_open (name);
4803 if (!rs->remote_desc)
c906108c
SS
4804 perror_with_name (name);
4805
4806 if (baud_rate != -1)
4807 {
5d93a237 4808 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4809 {
9b74d5d3
KB
4810 /* The requested speed could not be set. Error out to
4811 top level after closing remote_desc. Take care to
4812 set remote_desc to NULL to avoid closing remote_desc
4813 more than once. */
5d93a237
TT
4814 serial_close (rs->remote_desc);
4815 rs->remote_desc = NULL;
c906108c
SS
4816 perror_with_name (name);
4817 }
4818 }
4819
236af5e3 4820 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4821 serial_raw (rs->remote_desc);
c906108c
SS
4822
4823 /* If there is something sitting in the buffer we might take it as a
4824 response to a command, which would be bad. */
5d93a237 4825 serial_flush_input (rs->remote_desc);
c906108c
SS
4826
4827 if (from_tty)
4828 {
4829 puts_filtered ("Remote debugging using ");
4830 puts_filtered (name);
4831 puts_filtered ("\n");
4832 }
23860348 4833 push_target (target); /* Switch to using remote target now. */
c906108c 4834
74531fed
PA
4835 /* Register extra event sources in the event loop. */
4836 remote_async_inferior_event_token
4837 = create_async_event_handler (remote_async_inferior_event_handler,
4838 NULL);
5965e028 4839 rs->notif_state = remote_notif_state_allocate ();
74531fed 4840
be2a5f71
DJ
4841 /* Reset the target state; these things will be queried either by
4842 remote_query_supported or as they are needed. */
ca4f7f8b 4843 reset_all_packet_configs_support ();
74531fed 4844 rs->cached_wait_status = 0;
be2a5f71 4845 rs->explicit_packet_size = 0;
a6f3e723 4846 rs->noack_mode = 0;
82f73884 4847 rs->extended = extended_p;
e24a49d8 4848 rs->waiting_for_stop_reply = 0;
3a29589a 4849 rs->ctrlc_pending_p = 0;
802188a7 4850
47f8a51d
TT
4851 rs->general_thread = not_sent_ptid;
4852 rs->continue_thread = not_sent_ptid;
262e1174 4853 rs->remote_traceframe_number = -1;
c906108c 4854
9d1f7ab2 4855 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4856 rs->use_threadinfo_query = 1;
4857 rs->use_threadextra_query = 1;
9d1f7ab2 4858
80152258
PA
4859 readahead_cache_invalidate ();
4860
c6ebd6cf 4861 if (target_async_permitted)
92d1e331 4862 {
23860348 4863 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4864 remote_async_terminal_ours_p = 1;
4865
4866 /* FIXME: cagney/1999-09-23: During the initial connection it is
4867 assumed that the target is already ready and able to respond to
0df8b418 4868 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4869 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4870 around this. Eventually a mechanism that allows
92d1e331 4871 wait_for_inferior() to expect/get timeouts will be
23860348 4872 implemented. */
92d1e331
DJ
4873 wait_forever_enabled_p = 0;
4874 }
4875
23860348 4876 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4877 no_shared_libraries (NULL, 0);
f78f6cf1 4878
74531fed
PA
4879 /* Start afresh. */
4880 init_thread_list ();
4881
36918e70 4882 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4883 target (we'd otherwise be in an inconsistent state) and then
4884 propogate the error on up the exception chain. This ensures that
4885 the caller doesn't stumble along blindly assuming that the
4886 function succeeded. The CLI doesn't have this problem but other
4887 UI's, such as MI do.
36918e70
AC
4888
4889 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4890 this function should return an error indication letting the
ce2826aa 4891 caller restore the previous state. Unfortunately the command
36918e70
AC
4892 ``target remote'' is directly wired to this function making that
4893 impossible. On a positive note, the CLI side of this problem has
4894 been fixed - the function set_cmd_context() makes it possible for
4895 all the ``target ....'' commands to share a common callback
4896 function. See cli-dump.c. */
109c3e39 4897 {
2d717e4f 4898
492d29ea 4899 TRY
04bd08de
TT
4900 {
4901 remote_start_remote (from_tty, target, extended_p);
4902 }
492d29ea 4903 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4904 {
c8d104ad
PA
4905 /* Pop the partially set up target - unless something else did
4906 already before throwing the exception. */
5d93a237 4907 if (rs->remote_desc != NULL)
78a095c3 4908 remote_unpush_target ();
c6ebd6cf 4909 if (target_async_permitted)
109c3e39
AC
4910 wait_forever_enabled_p = 1;
4911 throw_exception (ex);
4912 }
492d29ea 4913 END_CATCH
109c3e39 4914 }
c906108c 4915
f4abbc16
MM
4916 remote_btrace_reset ();
4917
c6ebd6cf 4918 if (target_async_permitted)
92d1e331 4919 wait_forever_enabled_p = 1;
43ff13b4
JM
4920}
4921
de0d863e
DB
4922/* Detach the specified process. */
4923
4924static void
4925remote_detach_pid (int pid)
4926{
4927 struct remote_state *rs = get_remote_state ();
4928
4929 if (remote_multi_process_p (rs))
4930 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4931 else
4932 strcpy (rs->buf, "D");
4933
4934 putpkt (rs->buf);
4935 getpkt (&rs->buf, &rs->buf_size, 0);
4936
4937 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4938 ;
4939 else if (rs->buf[0] == '\0')
4940 error (_("Remote doesn't know how to detach"));
4941 else
4942 error (_("Can't detach process."));
4943}
4944
4945/* This detaches a program to which we previously attached, using
4946 inferior_ptid to identify the process. After this is done, GDB
4947 can be used to debug some other program. We better not have left
4948 any breakpoints in the target program or it'll die when it hits
4949 one. */
c906108c
SS
4950
4951static void
de0d863e 4952remote_detach_1 (const char *args, int from_tty)
c906108c 4953{
82f73884 4954 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4955 struct remote_state *rs = get_remote_state ();
de0d863e
DB
4956 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4957 int is_fork_parent;
c906108c
SS
4958
4959 if (args)
8a3fe4f8 4960 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4961
2d717e4f
DJ
4962 if (!target_has_execution)
4963 error (_("No process to detach from."));
4964
7cee1e54
PA
4965 if (from_tty)
4966 {
4967 char *exec_file = get_exec_file (0);
4968 if (exec_file == NULL)
4969 exec_file = "";
4970 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4971 target_pid_to_str (pid_to_ptid (pid)));
4972 gdb_flush (gdb_stdout);
4973 }
4974
c906108c 4975 /* Tell the remote target to detach. */
de0d863e 4976 remote_detach_pid (pid);
82f73884 4977
de0d863e 4978 if (from_tty && !rs->extended)
7cee1e54 4979 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4980
de0d863e
DB
4981 /* Check to see if we are detaching a fork parent. Note that if we
4982 are detaching a fork child, tp == NULL. */
4983 is_fork_parent = (tp != NULL
4984 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4985
4986 /* If doing detach-on-fork, we don't mourn, because that will delete
4987 breakpoints that should be available for the followed inferior. */
4988 if (!is_fork_parent)
4989 target_mourn_inferior ();
4990 else
4991 {
4992 inferior_ptid = null_ptid;
4993 detach_inferior (pid);
4994 }
2d717e4f
DJ
4995}
4996
4997static void
52554a0e 4998remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4999{
de0d863e 5000 remote_detach_1 (args, from_tty);
2d717e4f
DJ
5001}
5002
5003static void
52554a0e 5004extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5005{
de0d863e
DB
5006 remote_detach_1 (args, from_tty);
5007}
5008
5009/* Target follow-fork function for remote targets. On entry, and
5010 at return, the current inferior is the fork parent.
5011
5012 Note that although this is currently only used for extended-remote,
5013 it is named remote_follow_fork in anticipation of using it for the
5014 remote target as well. */
5015
5016static int
5017remote_follow_fork (struct target_ops *ops, int follow_child,
5018 int detach_fork)
5019{
5020 struct remote_state *rs = get_remote_state ();
c269dbdb 5021 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5022
c269dbdb
DB
5023 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5024 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5025 {
5026 /* When following the parent and detaching the child, we detach
5027 the child here. For the case of following the child and
5028 detaching the parent, the detach is done in the target-
5029 independent follow fork code in infrun.c. We can't use
5030 target_detach when detaching an unfollowed child because
5031 the client side doesn't know anything about the child. */
5032 if (detach_fork && !follow_child)
5033 {
5034 /* Detach the fork child. */
5035 ptid_t child_ptid;
5036 pid_t child_pid;
5037
5038 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5039 child_pid = ptid_get_pid (child_ptid);
5040
5041 remote_detach_pid (child_pid);
5042 detach_inferior (child_pid);
5043 }
5044 }
5045 return 0;
c906108c
SS
5046}
5047
94585166
DB
5048/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5049 in the program space of the new inferior. On entry and at return the
5050 current inferior is the exec'ing inferior. INF is the new exec'd
5051 inferior, which may be the same as the exec'ing inferior unless
5052 follow-exec-mode is "new". */
5053
5054static void
5055remote_follow_exec (struct target_ops *ops,
5056 struct inferior *inf, char *execd_pathname)
5057{
5058 /* We know that this is a target file name, so if it has the "target:"
5059 prefix we strip it off before saving it in the program space. */
5060 if (is_target_filename (execd_pathname))
5061 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5062
5063 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5064}
5065
6ad8ae5c
DJ
5066/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5067
43ff13b4 5068static void
fee354ee 5069remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5070{
43ff13b4 5071 if (args)
2d717e4f 5072 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5073
2d717e4f 5074 /* Make sure we unpush even the extended remote targets; mourn
20f796c9 5075 won't do it. So call remote_mourn directly instead of
2d717e4f 5076 target_mourn_inferior. */
20f796c9 5077 remote_mourn (target);
2d717e4f 5078
43ff13b4
JM
5079 if (from_tty)
5080 puts_filtered ("Ending remote debugging.\n");
5081}
5082
2d717e4f
DJ
5083/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5084 be chatty about it. */
5085
5086static void
20f796c9
GB
5087extended_remote_attach (struct target_ops *target, const char *args,
5088 int from_tty)
2d717e4f
DJ
5089{
5090 struct remote_state *rs = get_remote_state ();
be86555c 5091 int pid;
96ef3384 5092 char *wait_status = NULL;
2d717e4f 5093
74164c56 5094 pid = parse_pid_to_attach (args);
2d717e4f 5095
74164c56
JK
5096 /* Remote PID can be freely equal to getpid, do not check it here the same
5097 way as in other targets. */
2d717e4f 5098
4082afcc 5099 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5100 error (_("This target does not support attaching to a process"));
5101
7cee1e54
PA
5102 if (from_tty)
5103 {
5104 char *exec_file = get_exec_file (0);
5105
5106 if (exec_file)
5107 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5108 target_pid_to_str (pid_to_ptid (pid)));
5109 else
5110 printf_unfiltered (_("Attaching to %s\n"),
5111 target_pid_to_str (pid_to_ptid (pid)));
5112
5113 gdb_flush (gdb_stdout);
5114 }
5115
bba74b36 5116 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5117 putpkt (rs->buf);
5118 getpkt (&rs->buf, &rs->buf_size, 0);
5119
4082afcc
PA
5120 switch (packet_ok (rs->buf,
5121 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5122 {
4082afcc 5123 case PACKET_OK:
6efcd9a8 5124 if (!target_is_non_stop_p ())
74531fed
PA
5125 {
5126 /* Save the reply for later. */
224c3ddb 5127 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5128 strcpy (wait_status, rs->buf);
5129 }
5130 else if (strcmp (rs->buf, "OK") != 0)
5131 error (_("Attaching to %s failed with: %s"),
5132 target_pid_to_str (pid_to_ptid (pid)),
5133 rs->buf);
4082afcc
PA
5134 break;
5135 case PACKET_UNKNOWN:
5136 error (_("This target does not support attaching to a process"));
5137 default:
5138 error (_("Attaching to %s failed"),
5139 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5140 }
2d717e4f 5141
1b6e6f5c 5142 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5143
2d717e4f 5144 inferior_ptid = pid_to_ptid (pid);
79d7f229 5145
6efcd9a8 5146 if (target_is_non_stop_p ())
bad34192
PA
5147 {
5148 struct thread_info *thread;
79d7f229 5149
bad34192 5150 /* Get list of threads. */
e8032dde 5151 remote_update_thread_list (target);
82f73884 5152
bad34192
PA
5153 thread = first_thread_of_process (pid);
5154 if (thread)
5155 inferior_ptid = thread->ptid;
5156 else
5157 inferior_ptid = pid_to_ptid (pid);
5158
5159 /* Invalidate our notion of the remote current thread. */
47f8a51d 5160 record_currthread (rs, minus_one_ptid);
bad34192 5161 }
74531fed 5162 else
bad34192
PA
5163 {
5164 /* Now, if we have thread information, update inferior_ptid. */
5165 inferior_ptid = remote_current_thread (inferior_ptid);
5166
5167 /* Add the main thread to the thread list. */
5168 add_thread_silent (inferior_ptid);
5169 }
c0a2216e 5170
96ef3384
UW
5171 /* Next, if the target can specify a description, read it. We do
5172 this before anything involving memory or registers. */
5173 target_find_description ();
5174
6efcd9a8 5175 if (!target_is_non_stop_p ())
74531fed
PA
5176 {
5177 /* Use the previously fetched status. */
5178 gdb_assert (wait_status != NULL);
5179
5180 if (target_can_async_p ())
5181 {
722247f1
YQ
5182 struct notif_event *reply
5183 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5184
722247f1 5185 push_stop_reply ((struct stop_reply *) reply);
74531fed 5186
6a3753b3 5187 target_async (1);
74531fed
PA
5188 }
5189 else
5190 {
5191 gdb_assert (wait_status != NULL);
5192 strcpy (rs->buf, wait_status);
5193 rs->cached_wait_status = 1;
5194 }
5195 }
5196 else
5197 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5198}
5199
b9c1d481
AS
5200/* Implementation of the to_post_attach method. */
5201
5202static void
5203extended_remote_post_attach (struct target_ops *ops, int pid)
5204{
6efcd9a8
PA
5205 /* Get text, data & bss offsets. */
5206 get_offsets ();
5207
b9c1d481
AS
5208 /* In certain cases GDB might not have had the chance to start
5209 symbol lookup up until now. This could happen if the debugged
5210 binary is not using shared libraries, the vsyscall page is not
5211 present (on Linux) and the binary itself hadn't changed since the
5212 debugging process was started. */
5213 if (symfile_objfile != NULL)
5214 remote_check_symbols();
5215}
5216
c906108c 5217\f
506fb367
DJ
5218/* Check for the availability of vCont. This function should also check
5219 the response. */
c906108c
SS
5220
5221static void
6d820c5c 5222remote_vcont_probe (struct remote_state *rs)
c906108c 5223{
2e9f7625 5224 char *buf;
6d820c5c 5225
2e9f7625
DJ
5226 strcpy (rs->buf, "vCont?");
5227 putpkt (rs->buf);
6d820c5c 5228 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5229 buf = rs->buf;
c906108c 5230
506fb367 5231 /* Make sure that the features we assume are supported. */
61012eef 5232 if (startswith (buf, "vCont"))
506fb367
DJ
5233 {
5234 char *p = &buf[5];
750ce8d1 5235 int support_c, support_C;
506fb367 5236
750ce8d1
YQ
5237 rs->supports_vCont.s = 0;
5238 rs->supports_vCont.S = 0;
506fb367
DJ
5239 support_c = 0;
5240 support_C = 0;
d458bd84 5241 rs->supports_vCont.t = 0;
c1e36e3e 5242 rs->supports_vCont.r = 0;
506fb367
DJ
5243 while (p && *p == ';')
5244 {
5245 p++;
5246 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5247 rs->supports_vCont.s = 1;
506fb367 5248 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5249 rs->supports_vCont.S = 1;
506fb367
DJ
5250 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5251 support_c = 1;
5252 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5253 support_C = 1;
74531fed 5254 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5255 rs->supports_vCont.t = 1;
c1e36e3e
PA
5256 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5257 rs->supports_vCont.r = 1;
506fb367
DJ
5258
5259 p = strchr (p, ';');
5260 }
c906108c 5261
750ce8d1
YQ
5262 /* If c, and C are not all supported, we can't use vCont. Clearing
5263 BUF will make packet_ok disable the packet. */
5264 if (!support_c || !support_C)
506fb367
DJ
5265 buf[0] = 0;
5266 }
c906108c 5267
444abaca 5268 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5269}
c906108c 5270
0d8f58ca
PA
5271/* Helper function for building "vCont" resumptions. Write a
5272 resumption to P. ENDP points to one-passed-the-end of the buffer
5273 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5274 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5275 resumed thread should be single-stepped and/or signalled. If PTID
5276 equals minus_one_ptid, then all threads are resumed; if PTID
5277 represents a process, then all threads of the process are resumed;
5278 the thread to be stepped and/or signalled is given in the global
5279 INFERIOR_PTID. */
5280
5281static char *
5282append_resumption (char *p, char *endp,
2ea28649 5283 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5284{
5285 struct remote_state *rs = get_remote_state ();
5286
a493e3e2 5287 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5288 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5289 else if (step
5290 /* GDB is willing to range step. */
5291 && use_range_stepping
5292 /* Target supports range stepping. */
5293 && rs->supports_vCont.r
5294 /* We don't currently support range stepping multiple
5295 threads with a wildcard (though the protocol allows it,
5296 so stubs shouldn't make an active effort to forbid
5297 it). */
5298 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5299 {
5300 struct thread_info *tp;
5301
5302 if (ptid_equal (ptid, minus_one_ptid))
5303 {
5304 /* If we don't know about the target thread's tid, then
5305 we're resuming magic_null_ptid (see caller). */
5306 tp = find_thread_ptid (magic_null_ptid);
5307 }
5308 else
5309 tp = find_thread_ptid (ptid);
5310 gdb_assert (tp != NULL);
5311
5312 if (tp->control.may_range_step)
5313 {
5314 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5315
5316 p += xsnprintf (p, endp - p, ";r%s,%s",
5317 phex_nz (tp->control.step_range_start,
5318 addr_size),
5319 phex_nz (tp->control.step_range_end,
5320 addr_size));
5321 }
5322 else
5323 p += xsnprintf (p, endp - p, ";s");
5324 }
0d8f58ca
PA
5325 else if (step)
5326 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5327 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5328 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5329 else
5330 p += xsnprintf (p, endp - p, ";c");
5331
5332 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5333 {
5334 ptid_t nptid;
5335
5336 /* All (-1) threads of process. */
ba348170 5337 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5338
5339 p += xsnprintf (p, endp - p, ":");
5340 p = write_ptid (p, endp, nptid);
5341 }
5342 else if (!ptid_equal (ptid, minus_one_ptid))
5343 {
5344 p += xsnprintf (p, endp - p, ":");
5345 p = write_ptid (p, endp, ptid);
5346 }
5347
5348 return p;
5349}
5350
799a2abe
PA
5351/* Clear the thread's private info on resume. */
5352
5353static void
5354resume_clear_thread_private_info (struct thread_info *thread)
5355{
5356 if (thread->priv != NULL)
5357 {
5358 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5359 thread->priv->watch_data_address = 0;
5360 }
5361}
5362
e5ef252a
PA
5363/* Append a vCont continue-with-signal action for threads that have a
5364 non-zero stop signal. */
5365
5366static char *
5367append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5368{
5369 struct thread_info *thread;
5370
034f788c 5371 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5372 if (ptid_match (thread->ptid, ptid)
5373 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5374 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5375 {
5376 p = append_resumption (p, endp, thread->ptid,
5377 0, thread->suspend.stop_signal);
5378 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5379 resume_clear_thread_private_info (thread);
e5ef252a
PA
5380 }
5381
5382 return p;
5383}
5384
506fb367
DJ
5385/* Resume the remote inferior by using a "vCont" packet. The thread
5386 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5387 resumed thread should be single-stepped and/or signalled. If PTID
5388 equals minus_one_ptid, then all threads are resumed; the thread to
5389 be stepped and/or signalled is given in the global INFERIOR_PTID.
5390 This function returns non-zero iff it resumes the inferior.
44eaed12 5391
506fb367
DJ
5392 This function issues a strict subset of all possible vCont commands at the
5393 moment. */
44eaed12 5394
506fb367 5395static int
2ea28649 5396remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5397{
5398 struct remote_state *rs = get_remote_state ();
82f73884
PA
5399 char *p;
5400 char *endp;
44eaed12 5401
4082afcc 5402 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5403 remote_vcont_probe (rs);
44eaed12 5404
4082afcc 5405 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5406 return 0;
44eaed12 5407
82f73884
PA
5408 p = rs->buf;
5409 endp = rs->buf + get_remote_packet_size ();
5410
506fb367
DJ
5411 /* If we could generate a wider range of packets, we'd have to worry
5412 about overflowing BUF. Should there be a generic
5413 "multi-part-packet" packet? */
5414
0d8f58ca
PA
5415 p += xsnprintf (p, endp - p, "vCont");
5416
79d7f229 5417 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5418 {
79d7f229
PA
5419 /* MAGIC_NULL_PTID means that we don't have any active threads,
5420 so we don't have any TID numbers the inferior will
5421 understand. Make sure to only send forms that do not specify
5422 a TID. */
a9cbf802 5423 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5424 }
0d8f58ca 5425 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5426 {
0d8f58ca
PA
5427 /* Resume all threads (of all processes, or of a single
5428 process), with preference for INFERIOR_PTID. This assumes
5429 inferior_ptid belongs to the set of all threads we are about
5430 to resume. */
a493e3e2 5431 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5432 {
0d8f58ca
PA
5433 /* Step inferior_ptid, with or without signal. */
5434 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5435 }
0d8f58ca 5436
e5ef252a
PA
5437 /* Also pass down any pending signaled resumption for other
5438 threads not the current. */
5439 p = append_pending_thread_resumptions (p, endp, ptid);
5440
0d8f58ca 5441 /* And continue others without a signal. */
a493e3e2 5442 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5443 }
5444 else
506fb367
DJ
5445 {
5446 /* Scheduler locking; resume only PTID. */
a9cbf802 5447 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5448 }
c906108c 5449
82f73884
PA
5450 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5451 putpkt (rs->buf);
506fb367 5452
6efcd9a8 5453 if (target_is_non_stop_p ())
74531fed
PA
5454 {
5455 /* In non-stop, the stub replies to vCont with "OK". The stop
5456 reply will be reported asynchronously by means of a `%Stop'
5457 notification. */
5458 getpkt (&rs->buf, &rs->buf_size, 0);
5459 if (strcmp (rs->buf, "OK") != 0)
5460 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5461 }
5462
506fb367 5463 return 1;
c906108c 5464}
43ff13b4 5465
506fb367
DJ
5466/* Tell the remote machine to resume. */
5467
43ff13b4 5468static void
28439f5e 5469remote_resume (struct target_ops *ops,
2ea28649 5470 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5471{
d01949b6 5472 struct remote_state *rs = get_remote_state ();
2e9f7625 5473 char *buf;
799a2abe 5474 struct thread_info *thread;
43ff13b4 5475
722247f1
YQ
5476 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5477 (explained in remote-notif.c:handle_notification) so
5478 remote_notif_process is not called. We need find a place where
5479 it is safe to start a 'vNotif' sequence. It is good to do it
5480 before resuming inferior, because inferior was stopped and no RSP
5481 traffic at that moment. */
6efcd9a8 5482 if (!target_is_non_stop_p ())
5965e028 5483 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5484
b73be471 5485 rs->last_sent_signal = siggnal;
280ceea3 5486 rs->last_sent_step = step;
43ff13b4 5487
506fb367 5488 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5489 /* No reverse support (yet) for vCont. */
5490 if (execution_direction != EXEC_REVERSE)
5491 if (remote_vcont_resume (ptid, step, siggnal))
5492 goto done;
506fb367 5493
79d7f229
PA
5494 /* All other supported resume packets do use Hc, so set the continue
5495 thread. */
5496 if (ptid_equal (ptid, minus_one_ptid))
5497 set_continue_thread (any_thread_ptid);
506fb367 5498 else
79d7f229 5499 set_continue_thread (ptid);
506fb367 5500
799a2abe
PA
5501 ALL_NON_EXITED_THREADS (thread)
5502 resume_clear_thread_private_info (thread);
5503
2e9f7625 5504 buf = rs->buf;
b2175913
MS
5505 if (execution_direction == EXEC_REVERSE)
5506 {
5507 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5508 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5509 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5510 siggnal);
40ab02ce 5511
4082afcc 5512 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5513 error (_("Remote reverse-step not supported."));
4082afcc 5514 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5515 error (_("Remote reverse-continue not supported."));
40ab02ce 5516
b2175913
MS
5517 strcpy (buf, step ? "bs" : "bc");
5518 }
a493e3e2 5519 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5520 {
5521 buf[0] = step ? 'S' : 'C';
c5aa993b 5522 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5523 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5524 buf[3] = '\0';
5525 }
5526 else
c5aa993b 5527 strcpy (buf, step ? "s" : "c");
506fb367 5528
44eaed12 5529 putpkt (buf);
43ff13b4 5530
75c99385 5531 done:
2acceee2 5532 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5533 with the event loop. NOTE: this is the one place where all the
5534 execution commands end up. We could alternatively do this in each
23860348 5535 of the execution commands in infcmd.c. */
2acceee2
JM
5536 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5537 into infcmd.c in order to allow inferior function calls to work
23860348 5538 NOT asynchronously. */
362646f5 5539 if (target_can_async_p ())
6a3753b3 5540 target_async (1);
e24a49d8
PA
5541
5542 /* We've just told the target to resume. The remote server will
5543 wait for the inferior to stop, and then send a stop reply. In
5544 the mean time, we can't start another command/query ourselves
74531fed
PA
5545 because the stub wouldn't be ready to process it. This applies
5546 only to the base all-stop protocol, however. In non-stop (which
5547 only supports vCont), the stub replies with an "OK", and is
5548 immediate able to process further serial input. */
6efcd9a8 5549 if (!target_is_non_stop_p ())
74531fed 5550 rs->waiting_for_stop_reply = 1;
43ff13b4 5551}
c906108c 5552\f
43ff13b4
JM
5553
5554/* Set up the signal handler for SIGINT, while the target is
23860348 5555 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5556static void
934b9bac 5557async_initialize_sigint_signal_handler (void)
43ff13b4 5558{
934b9bac 5559 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5560}
5561
23860348 5562/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5563static void
934b9bac 5564async_handle_remote_sigint (int sig)
43ff13b4 5565{
934b9bac 5566 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5567 /* Note we need to go through gdb_call_async_signal_handler in order
5568 to wake up the event loop on Windows. */
5569 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5570}
5571
5572/* Signal handler for SIGINT, installed after SIGINT has already been
5573 sent once. It will take effect the second time that the user sends
23860348 5574 a ^C. */
43ff13b4 5575static void
934b9bac 5576async_handle_remote_sigint_twice (int sig)
43ff13b4 5577{
934b9bac 5578 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5579 /* See note in async_handle_remote_sigint. */
5580 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5581}
5582
abc56d60
PA
5583/* Implementation of to_check_pending_interrupt. */
5584
5585static void
5586remote_check_pending_interrupt (struct target_ops *self)
5587{
5588 struct async_signal_handler *token = async_sigint_remote_twice_token;
5589
5590 if (async_signal_handler_is_marked (token))
5591 {
5592 clear_async_signal_handler (token);
5593 call_async_signal_handler (token);
5594 }
5595}
5596
6426a772 5597/* Perform the real interruption of the target execution, in response
23860348 5598 to a ^C. */
c5aa993b 5599static void
fba45db2 5600async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5601{
5602 if (remote_debug)
248fd3bf 5603 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5604
de979965 5605 target_interrupt (inferior_ptid);
43ff13b4
JM
5606}
5607
0df8b418 5608/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5609 up on the target alltogether. */
47e1ce27 5610static void
fba45db2 5611async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5612{
2df3850c 5613 if (remote_debug)
248fd3bf 5614 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5615
5616 interrupt_query ();
43ff13b4
JM
5617}
5618
5619/* Reinstall the usual SIGINT handlers, after the target has
23860348 5620 stopped. */
6426a772 5621static void
934b9bac 5622async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5623{
5624 signal (SIGINT, handle_sigint);
43ff13b4
JM
5625}
5626
c906108c
SS
5627/* Send ^C to target to halt it. Target will respond, and send us a
5628 packet. */
507f3c78 5629static void (*ofunc) (int);
c906108c 5630
bfedc46a
PA
5631/* The command line interface's interrupt routine. This function is installed
5632 as a signal handler for SIGINT. The first time a user requests an
5633 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5634 response from the target (it didn't stop when the user requested it),
23860348 5635 we ask the user if he'd like to detach from the target. */
bfedc46a 5636
c906108c 5637static void
934b9bac 5638sync_remote_interrupt (int signo)
c906108c 5639{
23860348 5640 /* If this doesn't work, try more severe steps. */
934b9bac 5641 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5642
934b9bac 5643 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5644}
5645
5646/* The user typed ^C twice. */
5647
5648static void
934b9bac 5649sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5650{
5651 signal (signo, ofunc);
934b9bac
JK
5652 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5653 signal (signo, sync_remote_interrupt);
c906108c 5654}
7a292a7a 5655
74531fed
PA
5656/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5657 thread, all threads of a remote process, or all threads of all
5658 processes. */
5659
5660static void
5661remote_stop_ns (ptid_t ptid)
5662{
5663 struct remote_state *rs = get_remote_state ();
5664 char *p = rs->buf;
5665 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5666
4082afcc 5667 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5668 remote_vcont_probe (rs);
5669
d458bd84 5670 if (!rs->supports_vCont.t)
74531fed
PA
5671 error (_("Remote server does not support stopping threads"));
5672
f91d3df5
PA
5673 if (ptid_equal (ptid, minus_one_ptid)
5674 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5675 p += xsnprintf (p, endp - p, "vCont;t");
5676 else
5677 {
5678 ptid_t nptid;
5679
74531fed
PA
5680 p += xsnprintf (p, endp - p, "vCont;t:");
5681
5682 if (ptid_is_pid (ptid))
5683 /* All (-1) threads of process. */
ba348170 5684 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5685 else
5686 {
5687 /* Small optimization: if we already have a stop reply for
5688 this thread, no use in telling the stub we want this
5689 stopped. */
5690 if (peek_stop_reply (ptid))
5691 return;
5692
5693 nptid = ptid;
5694 }
5695
a9cbf802 5696 write_ptid (p, endp, nptid);
74531fed
PA
5697 }
5698
5699 /* In non-stop, we get an immediate OK reply. The stop reply will
5700 come in asynchronously by notification. */
5701 putpkt (rs->buf);
5702 getpkt (&rs->buf, &rs->buf_size, 0);
5703 if (strcmp (rs->buf, "OK") != 0)
5704 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5705}
5706
bfedc46a
PA
5707/* All-stop version of target_interrupt. Sends a break or a ^C to
5708 interrupt the remote target. It is undefined which thread of which
5709 process reports the interrupt. */
74531fed
PA
5710
5711static void
de979965 5712remote_interrupt_as (void)
74531fed
PA
5713{
5714 struct remote_state *rs = get_remote_state ();
5715
3a29589a
DJ
5716 rs->ctrlc_pending_p = 1;
5717
74531fed
PA
5718 /* If the inferior is stopped already, but the core didn't know
5719 about it yet, just ignore the request. The cached wait status
5720 will be collected in remote_wait. */
5721 if (rs->cached_wait_status)
5722 return;
5723
9a7071a8
JB
5724 /* Send interrupt_sequence to remote target. */
5725 send_interrupt_sequence ();
74531fed
PA
5726}
5727
de979965
PA
5728/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5729 the remote target. It is undefined which thread of which process
5730 reports the interrupt. Returns true if the packet is supported by
5731 the server, false otherwise. */
5732
5733static int
5734remote_interrupt_ns (void)
5735{
5736 struct remote_state *rs = get_remote_state ();
5737 char *p = rs->buf;
5738 char *endp = rs->buf + get_remote_packet_size ();
5739
5740 xsnprintf (p, endp - p, "vCtrlC");
5741
5742 /* In non-stop, we get an immediate OK reply. The stop reply will
5743 come in asynchronously by notification. */
5744 putpkt (rs->buf);
5745 getpkt (&rs->buf, &rs->buf_size, 0);
5746
5747 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5748 {
5749 case PACKET_OK:
5750 break;
5751 case PACKET_UNKNOWN:
5752 return 0;
5753 case PACKET_ERROR:
5754 error (_("Interrupting target failed: %s"), rs->buf);
5755 }
5756
5757 return 1;
5758}
5759
bfedc46a 5760/* Implement the to_stop function for the remote targets. */
74531fed 5761
c906108c 5762static void
1eab8a48 5763remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5764{
7a292a7a 5765 if (remote_debug)
0f71a2f6 5766 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5767
6efcd9a8 5768 if (target_is_non_stop_p ())
74531fed 5769 remote_stop_ns (ptid);
c906108c 5770 else
bfedc46a
PA
5771 {
5772 /* We don't currently have a way to transparently pause the
5773 remote target in all-stop mode. Interrupt it instead. */
de979965 5774 remote_interrupt_as ();
bfedc46a
PA
5775 }
5776}
5777
5778/* Implement the to_interrupt function for the remote targets. */
5779
5780static void
5781remote_interrupt (struct target_ops *self, ptid_t ptid)
5782{
5783 if (remote_debug)
5784 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5785
de979965 5786 if (non_stop)
bfedc46a 5787 {
de979965 5788 /* In non-stop mode, we always stop with no signal instead. */
bfedc46a
PA
5789 remote_stop_ns (ptid);
5790 }
5791 else
de979965
PA
5792 {
5793 /* In all-stop, we emulate ^C-ing the remote target's
5794 terminal. */
5795 if (target_is_non_stop_p ())
5796 {
5797 if (!remote_interrupt_ns ())
5798 {
5799 /* No support for ^C-ing the remote target. Stop it
5800 (with no signal) instead. */
5801 remote_stop_ns (ptid);
5802 }
5803 }
5804 else
5805 remote_interrupt_as ();
5806 }
c906108c
SS
5807}
5808
5809/* Ask the user what to do when an interrupt is received. */
5810
5811static void
fba45db2 5812interrupt_query (void)
c906108c 5813{
abc56d60
PA
5814 struct remote_state *rs = get_remote_state ();
5815 struct cleanup *old_chain;
5816
5817 old_chain = make_cleanup_restore_target_terminal ();
c906108c
SS
5818 target_terminal_ours ();
5819
abc56d60 5820 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5821 {
abc56d60
PA
5822 if (query (_("The target is not responding to interrupt requests.\n"
5823 "Stop debugging it? ")))
74531fed 5824 {
78a095c3 5825 remote_unpush_target ();
abc56d60 5826 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5827 }
5828 }
abc56d60
PA
5829 else
5830 {
5831 if (query (_("Interrupted while waiting for the program.\n"
5832 "Give up waiting? ")))
5833 quit ();
5834 }
c906108c 5835
abc56d60 5836 do_cleanups (old_chain);
c906108c
SS
5837}
5838
6426a772
JM
5839/* Enable/disable target terminal ownership. Most targets can use
5840 terminal groups to control terminal ownership. Remote targets are
5841 different in that explicit transfer of ownership to/from GDB/target
23860348 5842 is required. */
6426a772
JM
5843
5844static void
d2f640d4 5845remote_terminal_inferior (struct target_ops *self)
6426a772 5846{
c6ebd6cf 5847 if (!target_async_permitted)
75c99385
PA
5848 /* Nothing to do. */
5849 return;
5850
d9d2d8b6
PA
5851 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5852 idempotent. The event-loop GDB talking to an asynchronous target
5853 with a synchronous command calls this function from both
5854 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5855 transfer the terminal to the target when it shouldn't this guard
5856 can go away. */
6426a772
JM
5857 if (!remote_async_terminal_ours_p)
5858 return;
5859 delete_file_handler (input_fd);
5860 remote_async_terminal_ours_p = 0;
934b9bac 5861 async_initialize_sigint_signal_handler ();
6426a772
JM
5862 /* NOTE: At this point we could also register our selves as the
5863 recipient of all input. Any characters typed could then be
23860348 5864 passed on down to the target. */
6426a772
JM
5865}
5866
5867static void
e3594fd1 5868remote_terminal_ours (struct target_ops *self)
6426a772 5869{
c6ebd6cf 5870 if (!target_async_permitted)
75c99385
PA
5871 /* Nothing to do. */
5872 return;
5873
5874 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5875 if (remote_async_terminal_ours_p)
5876 return;
934b9bac 5877 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5878 add_file_handler (input_fd, stdin_event_handler, 0);
5879 remote_async_terminal_ours_p = 1;
5880}
5881
176a6961 5882static void
917317f4 5883remote_console_output (char *msg)
c906108c
SS
5884{
5885 char *p;
5886
c5aa993b 5887 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5888 {
5889 char tb[2];
5890 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5891
c906108c
SS
5892 tb[0] = c;
5893 tb[1] = 0;
43ff13b4 5894 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5895 }
00db5b94
PA
5896 gdb_flush (gdb_stdtarg);
5897}
74531fed
PA
5898
5899typedef struct cached_reg
5900{
5901 int num;
5902 gdb_byte data[MAX_REGISTER_SIZE];
5903} cached_reg_t;
5904
5905DEF_VEC_O(cached_reg_t);
5906
722247f1 5907typedef struct stop_reply
74531fed 5908{
722247f1 5909 struct notif_event base;
74531fed 5910
722247f1 5911 /* The identifier of the thread about this event */
74531fed
PA
5912 ptid_t ptid;
5913
340e3c99 5914 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5915 connection, represented by a remote_state object, is closed,
5916 all the associated stop_reply events should be released. */
5917 struct remote_state *rs;
5918
74531fed
PA
5919 struct target_waitstatus ws;
5920
15148d6a
PA
5921 /* Expedited registers. This makes remote debugging a bit more
5922 efficient for those targets that provide critical registers as
5923 part of their normal status mechanism (as another roundtrip to
5924 fetch them is avoided). */
74531fed
PA
5925 VEC(cached_reg_t) *regcache;
5926
f7e6eed5
PA
5927 enum target_stop_reason stop_reason;
5928
74531fed
PA
5929 CORE_ADDR watch_data_address;
5930
dc146f7c 5931 int core;
722247f1 5932} *stop_reply_p;
a744cf53 5933
722247f1
YQ
5934DECLARE_QUEUE_P (stop_reply_p);
5935DEFINE_QUEUE_P (stop_reply_p);
5936/* The list of already fetched and acknowledged stop events. This
5937 queue is used for notification Stop, and other notifications
5938 don't need queue for their events, because the notification events
5939 of Stop can't be consumed immediately, so that events should be
5940 queued first, and be consumed by remote_wait_{ns,as} one per
5941 time. Other notifications can consume their events immediately,
5942 so queue is not needed for them. */
5943static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5944
5945static void
5946stop_reply_xfree (struct stop_reply *r)
5947{
f48ff2a7 5948 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5949}
5950
221e1a37
PA
5951/* Return the length of the stop reply queue. */
5952
5953static int
5954stop_reply_queue_length (void)
5955{
5956 return QUEUE_length (stop_reply_p, stop_reply_queue);
5957}
5958
722247f1
YQ
5959static void
5960remote_notif_stop_parse (struct notif_client *self, char *buf,
5961 struct notif_event *event)
5962{
5963 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5964}
5965
5966static void
5967remote_notif_stop_ack (struct notif_client *self, char *buf,
5968 struct notif_event *event)
5969{
5970 struct stop_reply *stop_reply = (struct stop_reply *) event;
5971
5972 /* acknowledge */
5973 putpkt ((char *) self->ack_command);
5974
5975 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5976 /* We got an unknown stop reply. */
5977 error (_("Unknown stop reply"));
5978
5979 push_stop_reply (stop_reply);
5980}
5981
5982static int
5983remote_notif_stop_can_get_pending_events (struct notif_client *self)
5984{
5985 /* We can't get pending events in remote_notif_process for
5986 notification stop, and we have to do this in remote_wait_ns
5987 instead. If we fetch all queued events from stub, remote stub
5988 may exit and we have no chance to process them back in
5989 remote_wait_ns. */
5990 mark_async_event_handler (remote_async_inferior_event_token);
5991 return 0;
5992}
5993
5994static void
5995stop_reply_dtr (struct notif_event *event)
5996{
5997 struct stop_reply *r = (struct stop_reply *) event;
5998
5999 VEC_free (cached_reg_t, r->regcache);
6000}
6001
6002static struct notif_event *
6003remote_notif_stop_alloc_reply (void)
6004{
8d749320
SM
6005 /* We cast to a pointer to the "base class". */
6006 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6007
6008 r->dtr = stop_reply_dtr;
6009
6010 return r;
6011}
6012
6013/* A client of notification Stop. */
6014
6015struct notif_client notif_client_stop =
6016{
6017 "Stop",
6018 "vStopped",
6019 remote_notif_stop_parse,
6020 remote_notif_stop_ack,
6021 remote_notif_stop_can_get_pending_events,
6022 remote_notif_stop_alloc_reply,
f48ff2a7 6023 REMOTE_NOTIF_STOP,
722247f1
YQ
6024};
6025
6026/* A parameter to pass data in and out. */
6027
6028struct queue_iter_param
6029{
6030 void *input;
6031 struct stop_reply *output;
6032};
6033
cbb8991c
DB
6034/* Determine if THREAD is a pending fork parent thread. ARG contains
6035 the pid of the process that owns the threads we want to check, or
6036 -1 if we want to check all threads. */
6037
6038static int
6039is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6040 ptid_t thread_ptid)
6041{
6042 if (ws->kind == TARGET_WAITKIND_FORKED
6043 || ws->kind == TARGET_WAITKIND_VFORKED)
6044 {
6045 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6046 return 1;
6047 }
6048
6049 return 0;
6050}
6051
6052/* Check whether EVENT is a fork event, and if it is, remove the
6053 fork child from the context list passed in DATA. */
6054
6055static int
6056remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6057 QUEUE_ITER (stop_reply_p) *iter,
6058 stop_reply_p event,
6059 void *data)
6060{
19ba03f4
SM
6061 struct queue_iter_param *param = (struct queue_iter_param *) data;
6062 struct threads_listing_context *context
6063 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6064
6065 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6066 || event->ws.kind == TARGET_WAITKIND_VFORKED
6067 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6068 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6069
6070 return 1;
6071}
6072
6073/* If CONTEXT contains any fork child threads that have not been
6074 reported yet, remove them from the CONTEXT list. If such a
6075 thread exists it is because we are stopped at a fork catchpoint
6076 and have not yet called follow_fork, which will set up the
6077 host-side data structures for the new process. */
6078
6079static void
6080remove_new_fork_children (struct threads_listing_context *context)
6081{
6082 struct thread_info * thread;
6083 int pid = -1;
6084 struct notif_client *notif = &notif_client_stop;
6085 struct queue_iter_param param;
6086
6087 /* For any threads stopped at a fork event, remove the corresponding
6088 fork child threads from the CONTEXT list. */
6089 ALL_NON_EXITED_THREADS (thread)
6090 {
6091 struct target_waitstatus *ws = &thread->pending_follow;
6092
6093 if (is_pending_fork_parent (ws, pid, thread->ptid))
6094 {
6095 threads_listing_context_remove (ws, context);
6096 }
6097 }
6098
6099 /* Check for any pending fork events (not reported or processed yet)
6100 in process PID and remove those fork child threads from the
6101 CONTEXT list as well. */
6102 remote_notif_get_pending_events (notif);
6103 param.input = context;
6104 param.output = NULL;
6105 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6106 remove_child_of_pending_fork, &param);
6107}
6108
f48ff2a7
YQ
6109/* Remove stop replies in the queue if its pid is equal to the given
6110 inferior's pid. */
722247f1
YQ
6111
6112static int
f48ff2a7
YQ
6113remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6114 QUEUE_ITER (stop_reply_p) *iter,
6115 stop_reply_p event,
6116 void *data)
722247f1 6117{
19ba03f4
SM
6118 struct queue_iter_param *param = (struct queue_iter_param *) data;
6119 struct inferior *inf = (struct inferior *) param->input;
722247f1 6120
f48ff2a7 6121 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6122 {
6123 stop_reply_xfree (event);
6124 QUEUE_remove_elem (stop_reply_p, q, iter);
6125 }
6126
6127 return 1;
6128}
6129
f48ff2a7 6130/* Discard all pending stop replies of inferior INF. */
c906108c 6131
74531fed 6132static void
5f4cf0bb 6133discard_pending_stop_replies (struct inferior *inf)
c906108c 6134{
722247f1
YQ
6135 int i;
6136 struct queue_iter_param param;
f48ff2a7
YQ
6137 struct stop_reply *reply;
6138 struct remote_state *rs = get_remote_state ();
6139 struct remote_notif_state *rns = rs->notif_state;
6140
6141 /* This function can be notified when an inferior exists. When the
6142 target is not remote, the notification state is NULL. */
6143 if (rs->remote_desc == NULL)
6144 return;
6145
6146 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6147
74531fed 6148 /* Discard the in-flight notification. */
f48ff2a7 6149 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6150 {
722247f1 6151 stop_reply_xfree (reply);
f48ff2a7 6152 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6153 }
c906108c 6154
722247f1
YQ
6155 param.input = inf;
6156 param.output = NULL;
74531fed
PA
6157 /* Discard the stop replies we have already pulled with
6158 vStopped. */
722247f1 6159 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6160 remove_stop_reply_for_inferior, &param);
6161}
6162
bcc75809
YQ
6163/* If its remote state is equal to the given remote state,
6164 remove EVENT from the stop reply queue. */
6165
6166static int
6167remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6168 QUEUE_ITER (stop_reply_p) *iter,
6169 stop_reply_p event,
6170 void *data)
6171{
19ba03f4
SM
6172 struct queue_iter_param *param = (struct queue_iter_param *) data;
6173 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6174
6175 if (event->rs == rs)
6176 {
6177 stop_reply_xfree (event);
6178 QUEUE_remove_elem (stop_reply_p, q, iter);
6179 }
6180
6181 return 1;
6182}
6183
6184/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6185
6186static void
bcc75809 6187discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6188{
6189 struct queue_iter_param param;
6190
bcc75809 6191 param.input = rs;
f48ff2a7
YQ
6192 param.output = NULL;
6193 /* Discard the stop replies we have already pulled with
6194 vStopped. */
6195 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6196 remove_stop_reply_of_remote_state, &param);
722247f1 6197}
74531fed 6198
722247f1
YQ
6199/* A parameter to pass data in and out. */
6200
6201static int
6202remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6203 QUEUE_ITER (stop_reply_p) *iter,
6204 stop_reply_p event,
6205 void *data)
6206{
19ba03f4
SM
6207 struct queue_iter_param *param = (struct queue_iter_param *) data;
6208 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6209
6210 if (ptid_match (event->ptid, *ptid))
6211 {
6212 param->output = event;
6213 QUEUE_remove_elem (stop_reply_p, q, iter);
6214 return 0;
c8e38a49 6215 }
722247f1
YQ
6216
6217 return 1;
74531fed 6218}
43ff13b4 6219
722247f1
YQ
6220/* Remove the first reply in 'stop_reply_queue' which matches
6221 PTID. */
2e9f7625 6222
722247f1
YQ
6223static struct stop_reply *
6224remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6225{
722247f1
YQ
6226 struct queue_iter_param param;
6227
6228 param.input = &ptid;
6229 param.output = NULL;
6230
6231 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6232 remote_notif_remove_once_on_match, &param);
6233 if (notif_debug)
6234 fprintf_unfiltered (gdb_stdlog,
6235 "notif: discard queued event: 'Stop' in %s\n",
6236 target_pid_to_str (ptid));
a744cf53 6237
722247f1 6238 return param.output;
74531fed 6239}
75c99385 6240
74531fed
PA
6241/* Look for a queued stop reply belonging to PTID. If one is found,
6242 remove it from the queue, and return it. Returns NULL if none is
6243 found. If there are still queued events left to process, tell the
6244 event loop to get back to target_wait soon. */
e24a49d8 6245
74531fed
PA
6246static struct stop_reply *
6247queued_stop_reply (ptid_t ptid)
6248{
722247f1 6249 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6250
722247f1 6251 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6252 /* There's still at least an event left. */
6253 mark_async_event_handler (remote_async_inferior_event_token);
6254
722247f1 6255 return r;
74531fed
PA
6256}
6257
6258/* Push a fully parsed stop reply in the stop reply queue. Since we
6259 know that we now have at least one queued event left to pass to the
6260 core side, tell the event loop to get back to target_wait soon. */
6261
6262static void
6263push_stop_reply (struct stop_reply *new_event)
6264{
722247f1 6265 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6266
722247f1
YQ
6267 if (notif_debug)
6268 fprintf_unfiltered (gdb_stdlog,
6269 "notif: push 'Stop' %s to queue %d\n",
6270 target_pid_to_str (new_event->ptid),
6271 QUEUE_length (stop_reply_p,
6272 stop_reply_queue));
74531fed
PA
6273
6274 mark_async_event_handler (remote_async_inferior_event_token);
6275}
6276
722247f1
YQ
6277static int
6278stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6279 QUEUE_ITER (stop_reply_p) *iter,
6280 struct stop_reply *event,
6281 void *data)
6282{
19ba03f4 6283 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6284
6285 return !(ptid_equal (*ptid, event->ptid)
6286 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6287}
6288
74531fed
PA
6289/* Returns true if we have a stop reply for PTID. */
6290
6291static int
6292peek_stop_reply (ptid_t ptid)
6293{
722247f1
YQ
6294 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6295 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6296}
6297
1f10ba14
PA
6298/* Skip PACKET until the next semi-colon (or end of string). */
6299
6300static char *
6301skip_to_semicolon (char *p)
6302{
6303 while (*p != '\0' && *p != ';')
6304 p++;
6305 return p;
6306}
6307
26d56a93
SL
6308/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6309 starting with P and ending with PEND matches PREFIX. */
6310
6311static int
6312strprefix (const char *p, const char *pend, const char *prefix)
6313{
6314 for ( ; p < pend; p++, prefix++)
6315 if (*p != *prefix)
6316 return 0;
6317 return *prefix == '\0';
6318}
6319
74531fed
PA
6320/* Parse the stop reply in BUF. Either the function succeeds, and the
6321 result is stored in EVENT, or throws an error. */
6322
6323static void
6324remote_parse_stop_reply (char *buf, struct stop_reply *event)
6325{
6326 struct remote_arch_state *rsa = get_remote_arch_state ();
6327 ULONGEST addr;
6328 char *p;
94585166 6329 int skipregs = 0;
74531fed
PA
6330
6331 event->ptid = null_ptid;
bcc75809 6332 event->rs = get_remote_state ();
74531fed
PA
6333 event->ws.kind = TARGET_WAITKIND_IGNORE;
6334 event->ws.value.integer = 0;
f7e6eed5 6335 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6336 event->regcache = NULL;
dc146f7c 6337 event->core = -1;
74531fed
PA
6338
6339 switch (buf[0])
6340 {
6341 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6342 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6343 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6344 ss = signal number
6345 n... = register number
6346 r... = register contents
6347 */
6348
6349 p = &buf[3]; /* after Txx */
6350 while (*p)
6351 {
6352 char *p1;
cea39f65 6353 int fieldsize;
43ff13b4 6354
1f10ba14
PA
6355 p1 = strchr (p, ':');
6356 if (p1 == NULL)
6357 error (_("Malformed packet(a) (missing colon): %s\n\
6358Packet: '%s'\n"),
6359 p, buf);
6360 if (p == p1)
6361 error (_("Malformed packet(a) (missing register number): %s\n\
6362Packet: '%s'\n"),
6363 p, buf);
3c3bea1c 6364
1f10ba14
PA
6365 /* Some "registers" are actually extended stop information.
6366 Note if you're adding a new entry here: GDB 7.9 and
6367 earlier assume that all register "numbers" that start
6368 with an hex digit are real register numbers. Make sure
6369 the server only sends such a packet if it knows the
6370 client understands it. */
c8e38a49 6371
26d56a93 6372 if (strprefix (p, p1, "thread"))
1f10ba14 6373 event->ptid = read_ptid (++p1, &p);
26d56a93
SL
6374 else if (strprefix (p, p1, "watch")
6375 || strprefix (p, p1, "rwatch")
6376 || strprefix (p, p1, "awatch"))
cea39f65 6377 {
f7e6eed5 6378 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6379 p = unpack_varlen_hex (++p1, &addr);
6380 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6381 }
26d56a93 6382 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6383 {
6384 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6385
6386 /* Make sure the stub doesn't forget to indicate support
6387 with qSupported. */
6388 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6389 error (_("Unexpected swbreak stop reason"));
6390
6391 /* The value part is documented as "must be empty",
6392 though we ignore it, in case we ever decide to make
6393 use of it in a backward compatible way. */
6394 p = skip_to_semicolon (p1 + 1);
6395 }
26d56a93 6396 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6397 {
6398 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6399
6400 /* Make sure the stub doesn't forget to indicate support
6401 with qSupported. */
6402 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6403 error (_("Unexpected hwbreak stop reason"));
6404
6405 /* See above. */
6406 p = skip_to_semicolon (p1 + 1);
6407 }
26d56a93 6408 else if (strprefix (p, p1, "library"))
cea39f65 6409 {
1f10ba14
PA
6410 event->ws.kind = TARGET_WAITKIND_LOADED;
6411 p = skip_to_semicolon (p1 + 1);
6412 }
26d56a93 6413 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6414 {
6415 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6416 /* p1 will indicate "begin" or "end", but it makes
6417 no difference for now, so ignore it. */
6418 p = skip_to_semicolon (p1 + 1);
6419 }
26d56a93 6420 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6421 {
6422 ULONGEST c;
a744cf53 6423
1f10ba14
PA
6424 p = unpack_varlen_hex (++p1, &c);
6425 event->core = c;
cea39f65 6426 }
26d56a93 6427 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6428 {
6429 event->ws.value.related_pid = read_ptid (++p1, &p);
6430 event->ws.kind = TARGET_WAITKIND_FORKED;
6431 }
26d56a93 6432 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6433 {
6434 event->ws.value.related_pid = read_ptid (++p1, &p);
6435 event->ws.kind = TARGET_WAITKIND_VFORKED;
6436 }
26d56a93 6437 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6438 {
6439 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6440 p = skip_to_semicolon (p1 + 1);
6441 }
6ab24463 6442 else if (strprefix (p, p1, "exec"))
94585166
DB
6443 {
6444 ULONGEST ignored;
6445 char pathname[PATH_MAX];
6446 int pathlen;
6447
6448 /* Determine the length of the execd pathname. */
6449 p = unpack_varlen_hex (++p1, &ignored);
6450 pathlen = (p - p1) / 2;
6451
6452 /* Save the pathname for event reporting and for
6453 the next run command. */
6454 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6455 pathname[pathlen] = '\0';
6456
6457 /* This is freed during event handling. */
6458 event->ws.value.execd_pathname = xstrdup (pathname);
6459 event->ws.kind = TARGET_WAITKIND_EXECD;
6460
6461 /* Skip the registers included in this packet, since
6462 they may be for an architecture different from the
6463 one used by the original program. */
6464 skipregs = 1;
6465 }
65706a29
PA
6466 else if (strprefix (p, p1, "create"))
6467 {
6468 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6469 p = skip_to_semicolon (p1 + 1);
6470 }
cea39f65
MS
6471 else
6472 {
1f10ba14
PA
6473 ULONGEST pnum;
6474 char *p_temp;
6475
94585166
DB
6476 if (skipregs)
6477 {
6478 p = skip_to_semicolon (p1 + 1);
6479 p++;
6480 continue;
6481 }
6482
1f10ba14
PA
6483 /* Maybe a real ``P'' register number. */
6484 p_temp = unpack_varlen_hex (p, &pnum);
6485 /* If the first invalid character is the colon, we got a
6486 register number. Otherwise, it's an unknown stop
6487 reason. */
6488 if (p_temp == p1)
6489 {
6490 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6491 cached_reg_t cached_reg;
43ff13b4 6492
1f10ba14
PA
6493 if (reg == NULL)
6494 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6495Packet: '%s'\n"),
1f10ba14 6496 hex_string (pnum), p, buf);
c8e38a49 6497
1f10ba14 6498 cached_reg.num = reg->regnum;
4100683b 6499
1f10ba14
PA
6500 p = p1 + 1;
6501 fieldsize = hex2bin (p, cached_reg.data,
6502 register_size (target_gdbarch (),
6503 reg->regnum));
6504 p += 2 * fieldsize;
6505 if (fieldsize < register_size (target_gdbarch (),
6506 reg->regnum))
6507 warning (_("Remote reply is too short: %s"), buf);
74531fed 6508
1f10ba14
PA
6509 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6510 }
6511 else
6512 {
6513 /* Not a number. Silently skip unknown optional
6514 info. */
6515 p = skip_to_semicolon (p1 + 1);
6516 }
cea39f65 6517 }
c8e38a49 6518
cea39f65
MS
6519 if (*p != ';')
6520 error (_("Remote register badly formatted: %s\nhere: %s"),
6521 buf, p);
6522 ++p;
6523 }
5b5596ff
PA
6524
6525 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6526 break;
6527
c8e38a49
PA
6528 /* fall through */
6529 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6530 {
6531 int sig;
6532
6533 event->ws.kind = TARGET_WAITKIND_STOPPED;
6534 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6535 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6536 event->ws.value.sig = (enum gdb_signal) sig;
6537 else
6538 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6539 }
c8e38a49 6540 break;
65706a29
PA
6541 case 'w': /* Thread exited. */
6542 {
6543 char *p;
6544 ULONGEST value;
6545
6546 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6547 p = unpack_varlen_hex (&buf[1], &value);
6548 event->ws.value.integer = value;
6549 if (*p != ';')
6550 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 6551 event->ptid = read_ptid (++p, NULL);
65706a29
PA
6552 break;
6553 }
c8e38a49
PA
6554 case 'W': /* Target exited. */
6555 case 'X':
6556 {
6557 char *p;
6558 int pid;
6559 ULONGEST value;
82f73884 6560
c8e38a49
PA
6561 /* GDB used to accept only 2 hex chars here. Stubs should
6562 only send more if they detect GDB supports multi-process
6563 support. */
6564 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6565
c8e38a49
PA
6566 if (buf[0] == 'W')
6567 {
6568 /* The remote process exited. */
74531fed
PA
6569 event->ws.kind = TARGET_WAITKIND_EXITED;
6570 event->ws.value.integer = value;
c8e38a49
PA
6571 }
6572 else
6573 {
6574 /* The remote process exited with a signal. */
74531fed 6575 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6576 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6577 event->ws.value.sig = (enum gdb_signal) value;
6578 else
6579 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6580 }
82f73884 6581
c8e38a49
PA
6582 /* If no process is specified, assume inferior_ptid. */
6583 pid = ptid_get_pid (inferior_ptid);
6584 if (*p == '\0')
6585 ;
6586 else if (*p == ';')
6587 {
6588 p++;
6589
0b24eb2d 6590 if (*p == '\0')
82f73884 6591 ;
61012eef 6592 else if (startswith (p, "process:"))
82f73884 6593 {
c8e38a49 6594 ULONGEST upid;
a744cf53 6595
c8e38a49
PA
6596 p += sizeof ("process:") - 1;
6597 unpack_varlen_hex (p, &upid);
6598 pid = upid;
82f73884
PA
6599 }
6600 else
6601 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6602 }
c8e38a49
PA
6603 else
6604 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6605 event->ptid = pid_to_ptid (pid);
6606 }
6607 break;
f2faf941
PA
6608 case 'N':
6609 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6610 event->ptid = minus_one_ptid;
6611 break;
74531fed
PA
6612 }
6613
6efcd9a8 6614 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
6615 error (_("No process or thread specified in stop reply: %s"), buf);
6616}
6617
722247f1
YQ
6618/* When the stub wants to tell GDB about a new notification reply, it
6619 sends a notification (%Stop, for example). Those can come it at
6620 any time, hence, we have to make sure that any pending
6621 putpkt/getpkt sequence we're making is finished, before querying
6622 the stub for more events with the corresponding ack command
6623 (vStopped, for example). E.g., if we started a vStopped sequence
6624 immediately upon receiving the notification, something like this
6625 could happen:
74531fed
PA
6626
6627 1.1) --> Hg 1
6628 1.2) <-- OK
6629 1.3) --> g
6630 1.4) <-- %Stop
6631 1.5) --> vStopped
6632 1.6) <-- (registers reply to step #1.3)
6633
6634 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6635 query.
6636
796cb314 6637 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6638 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6639 doing whatever we were doing:
6640
6641 2.1) --> Hg 1
6642 2.2) <-- OK
6643 2.3) --> g
6644 2.4) <-- %Stop
6645 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6646 2.5) <-- (registers reply to step #2.3)
6647
6648 Eventualy after step #2.5, we return to the event loop, which
6649 notices there's an event on the
6650 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6651 associated callback --- the function below. At this point, we're
6652 always safe to start a vStopped sequence. :
6653
6654 2.6) --> vStopped
6655 2.7) <-- T05 thread:2
6656 2.8) --> vStopped
6657 2.9) --> OK
6658*/
6659
722247f1
YQ
6660void
6661remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6662{
6663 struct remote_state *rs = get_remote_state ();
74531fed 6664
f48ff2a7 6665 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6666 {
722247f1
YQ
6667 if (notif_debug)
6668 fprintf_unfiltered (gdb_stdlog,
6669 "notif: process: '%s' ack pending event\n",
6670 nc->name);
74531fed 6671
722247f1 6672 /* acknowledge */
f48ff2a7
YQ
6673 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6674 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6675
6676 while (1)
6677 {
6678 getpkt (&rs->buf, &rs->buf_size, 0);
6679 if (strcmp (rs->buf, "OK") == 0)
6680 break;
6681 else
722247f1 6682 remote_notif_ack (nc, rs->buf);
74531fed
PA
6683 }
6684 }
722247f1
YQ
6685 else
6686 {
6687 if (notif_debug)
6688 fprintf_unfiltered (gdb_stdlog,
6689 "notif: process: '%s' no pending reply\n",
6690 nc->name);
6691 }
74531fed
PA
6692}
6693
74531fed
PA
6694/* Called when it is decided that STOP_REPLY holds the info of the
6695 event that is to be returned to the core. This function always
6696 destroys STOP_REPLY. */
6697
6698static ptid_t
6699process_stop_reply (struct stop_reply *stop_reply,
6700 struct target_waitstatus *status)
6701{
6702 ptid_t ptid;
6703
6704 *status = stop_reply->ws;
6705 ptid = stop_reply->ptid;
6706
6707 /* If no thread/process was reported by the stub, assume the current
6708 inferior. */
6709 if (ptid_equal (ptid, null_ptid))
6710 ptid = inferior_ptid;
6711
5f3563ea 6712 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
6713 && status->kind != TARGET_WAITKIND_SIGNALLED
6714 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 6715 {
ee154bee 6716 struct remote_state *rs = get_remote_state ();
799a2abe 6717 struct private_thread_info *remote_thr;
ee154bee 6718
5f3563ea
PA
6719 /* Expedited registers. */
6720 if (stop_reply->regcache)
6721 {
217f1f79 6722 struct regcache *regcache
f5656ead 6723 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6724 cached_reg_t *reg;
6725 int ix;
6726
6727 for (ix = 0;
6728 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6729 ix++)
217f1f79 6730 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6731 VEC_free (cached_reg_t, stop_reply->regcache);
6732 }
74531fed 6733
1941c569 6734 remote_notice_new_inferior (ptid, 0);
799a2abe
PA
6735 remote_thr = demand_private_info (ptid);
6736 remote_thr->core = stop_reply->core;
6737 remote_thr->stop_reason = stop_reply->stop_reason;
6738 remote_thr->watch_data_address = stop_reply->watch_data_address;
74531fed
PA
6739 }
6740
74531fed
PA
6741 stop_reply_xfree (stop_reply);
6742 return ptid;
6743}
6744
6745/* The non-stop mode version of target_wait. */
6746
6747static ptid_t
47608cb1 6748remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6749{
6750 struct remote_state *rs = get_remote_state ();
74531fed
PA
6751 struct stop_reply *stop_reply;
6752 int ret;
fee9eda9 6753 int is_notif = 0;
74531fed
PA
6754
6755 /* If in non-stop mode, get out of getpkt even if a
6756 notification is received. */
6757
6758 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6759 0 /* forever */, &is_notif);
74531fed
PA
6760 while (1)
6761 {
fee9eda9 6762 if (ret != -1 && !is_notif)
74531fed
PA
6763 switch (rs->buf[0])
6764 {
6765 case 'E': /* Error of some sort. */
6766 /* We're out of sync with the target now. Did it continue
6767 or not? We can't tell which thread it was in non-stop,
6768 so just ignore this. */
6769 warning (_("Remote failure reply: %s"), rs->buf);
6770 break;
6771 case 'O': /* Console output. */
6772 remote_console_output (rs->buf + 1);
6773 break;
6774 default:
6775 warning (_("Invalid remote reply: %s"), rs->buf);
6776 break;
6777 }
6778
6779 /* Acknowledge a pending stop reply that may have arrived in the
6780 mean time. */
f48ff2a7 6781 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6782 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6783
6784 /* If indeed we noticed a stop reply, we're done. */
6785 stop_reply = queued_stop_reply (ptid);
6786 if (stop_reply != NULL)
6787 return process_stop_reply (stop_reply, status);
6788
47608cb1 6789 /* Still no event. If we're just polling for an event, then
74531fed 6790 return to the event loop. */
47608cb1 6791 if (options & TARGET_WNOHANG)
74531fed
PA
6792 {
6793 status->kind = TARGET_WAITKIND_IGNORE;
6794 return minus_one_ptid;
6795 }
6796
47608cb1 6797 /* Otherwise do a blocking wait. */
74531fed 6798 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6799 1 /* forever */, &is_notif);
74531fed
PA
6800 }
6801}
6802
6803/* Wait until the remote machine stops, then return, storing status in
6804 STATUS just as `wait' would. */
6805
6806static ptid_t
47608cb1 6807remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6808{
6809 struct remote_state *rs = get_remote_state ();
74531fed 6810 ptid_t event_ptid = null_ptid;
cea39f65 6811 char *buf;
74531fed
PA
6812 struct stop_reply *stop_reply;
6813
47608cb1
PA
6814 again:
6815
74531fed
PA
6816 status->kind = TARGET_WAITKIND_IGNORE;
6817 status->value.integer = 0;
6818
6819 stop_reply = queued_stop_reply (ptid);
6820 if (stop_reply != NULL)
6821 return process_stop_reply (stop_reply, status);
6822
6823 if (rs->cached_wait_status)
6824 /* Use the cached wait status, but only once. */
6825 rs->cached_wait_status = 0;
6826 else
6827 {
6828 int ret;
722247f1 6829 int is_notif;
567420d1
PA
6830 int forever = ((options & TARGET_WNOHANG) == 0
6831 && wait_forever_enabled_p);
6832
6833 if (!rs->waiting_for_stop_reply)
6834 {
6835 status->kind = TARGET_WAITKIND_NO_RESUMED;
6836 return minus_one_ptid;
6837 }
74531fed
PA
6838
6839 if (!target_is_async_p ())
6840 {
934b9bac 6841 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6842 /* If the user hit C-c before this packet, or between packets,
6843 pretend that it was hit right here. */
522002f9 6844 if (check_quit_flag ())
74531fed 6845 {
522002f9 6846 clear_quit_flag ();
934b9bac 6847 sync_remote_interrupt (SIGINT);
74531fed
PA
6848 }
6849 }
6850
6851 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6852 _never_ wait for ever -> test on target_is_async_p().
6853 However, before we do that we need to ensure that the caller
6854 knows how to take the target into/out of async mode. */
722247f1 6855 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6856 forever, &is_notif);
722247f1 6857
5e1b953b
SDJ
6858 if (!target_is_async_p ())
6859 signal (SIGINT, ofunc);
6860
722247f1
YQ
6861 /* GDB gets a notification. Return to core as this event is
6862 not interesting. */
6863 if (ret != -1 && is_notif)
6864 return minus_one_ptid;
567420d1
PA
6865
6866 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6867 return minus_one_ptid;
74531fed
PA
6868 }
6869
6870 buf = rs->buf;
6871
3a29589a
DJ
6872 /* Assume that the target has acknowledged Ctrl-C unless we receive
6873 an 'F' or 'O' packet. */
6874 if (buf[0] != 'F' && buf[0] != 'O')
6875 rs->ctrlc_pending_p = 0;
6876
74531fed
PA
6877 switch (buf[0])
6878 {
6879 case 'E': /* Error of some sort. */
6880 /* We're out of sync with the target now. Did it continue or
6881 not? Not is more likely, so report a stop. */
29090fb6
LM
6882 rs->waiting_for_stop_reply = 0;
6883
74531fed
PA
6884 warning (_("Remote failure reply: %s"), buf);
6885 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6886 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6887 break;
6888 case 'F': /* File-I/O request. */
3a29589a
DJ
6889 remote_fileio_request (buf, rs->ctrlc_pending_p);
6890 rs->ctrlc_pending_p = 0;
74531fed 6891 break;
f2faf941 6892 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 6893 {
29090fb6
LM
6894 struct stop_reply *stop_reply;
6895
6896 /* There is a stop reply to handle. */
6897 rs->waiting_for_stop_reply = 0;
6898
6899 stop_reply
722247f1
YQ
6900 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6901 rs->buf);
74531fed 6902
74531fed 6903 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6904 break;
6905 }
6906 case 'O': /* Console output. */
6907 remote_console_output (buf + 1);
c8e38a49
PA
6908 break;
6909 case '\0':
b73be471 6910 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6911 {
6912 /* Zero length reply means that we tried 'S' or 'C' and the
6913 remote system doesn't support it. */
6914 target_terminal_ours_for_output ();
6915 printf_filtered
6916 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6917 gdb_signal_to_name (rs->last_sent_signal));
6918 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6919 target_terminal_inferior ();
6920
280ceea3 6921 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49 6922 putpkt ((char *) buf);
c8e38a49 6923 break;
43ff13b4 6924 }
c8e38a49
PA
6925 /* else fallthrough */
6926 default:
6927 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 6928 break;
43ff13b4 6929 }
c8e38a49 6930
f2faf941
PA
6931 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
6932 return minus_one_ptid;
6933 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6934 {
6935 /* Nothing interesting happened. If we're doing a non-blocking
6936 poll, we're done. Otherwise, go back to waiting. */
6937 if (options & TARGET_WNOHANG)
6938 return minus_one_ptid;
6939 else
6940 goto again;
6941 }
74531fed
PA
6942 else if (status->kind != TARGET_WAITKIND_EXITED
6943 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6944 {
6945 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6946 record_currthread (rs, event_ptid);
82f73884
PA
6947 else
6948 event_ptid = inferior_ptid;
43ff13b4 6949 }
74531fed
PA
6950 else
6951 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6952 record_currthread (rs, minus_one_ptid);
79d7f229 6953
82f73884 6954 return event_ptid;
43ff13b4
JM
6955}
6956
74531fed
PA
6957/* Wait until the remote machine stops, then return, storing status in
6958 STATUS just as `wait' would. */
6959
c8e38a49 6960static ptid_t
117de6a9 6961remote_wait (struct target_ops *ops,
47608cb1 6962 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6963{
6964 ptid_t event_ptid;
6965
6efcd9a8 6966 if (target_is_non_stop_p ())
47608cb1 6967 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6968 else
47608cb1 6969 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6970
d9d41e78 6971 if (target_is_async_p ())
c8e38a49 6972 {
74531fed
PA
6973 /* If there are are events left in the queue tell the event loop
6974 to return here. */
722247f1 6975 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6976 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6977 }
c8e38a49
PA
6978
6979 return event_ptid;
6980}
6981
74ca34ce 6982/* Fetch a single register using a 'p' packet. */
c906108c 6983
b96ec7ac 6984static int
56be3814 6985fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6986{
6987 struct remote_state *rs = get_remote_state ();
2e9f7625 6988 char *buf, *p;
b96ec7ac
AC
6989 char regp[MAX_REGISTER_SIZE];
6990 int i;
6991
4082afcc 6992 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6993 return 0;
6994
6995 if (reg->pnum == -1)
6996 return 0;
6997
2e9f7625 6998 p = rs->buf;
fcad0fa4 6999 *p++ = 'p';
74ca34ce 7000 p += hexnumstr (p, reg->pnum);
fcad0fa4 7001 *p++ = '\0';
1f4437a4
MS
7002 putpkt (rs->buf);
7003 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7004
2e9f7625
DJ
7005 buf = rs->buf;
7006
74ca34ce
DJ
7007 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7008 {
7009 case PACKET_OK:
7010 break;
7011 case PACKET_UNKNOWN:
7012 return 0;
7013 case PACKET_ERROR:
27a9c0bf
MS
7014 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7015 gdbarch_register_name (get_regcache_arch (regcache),
7016 reg->regnum),
7017 buf);
74ca34ce 7018 }
3f9a994c
JB
7019
7020 /* If this register is unfetchable, tell the regcache. */
7021 if (buf[0] == 'x')
8480adf2 7022 {
56be3814 7023 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7024 return 1;
b96ec7ac 7025 }
b96ec7ac 7026
3f9a994c
JB
7027 /* Otherwise, parse and supply the value. */
7028 p = buf;
7029 i = 0;
7030 while (p[0] != 0)
7031 {
7032 if (p[1] == 0)
74ca34ce 7033 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7034
7035 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7036 p += 2;
7037 }
56be3814 7038 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7039 return 1;
b96ec7ac
AC
7040}
7041
74ca34ce
DJ
7042/* Fetch the registers included in the target's 'g' packet. */
7043
29709017
DJ
7044static int
7045send_g_packet (void)
c906108c 7046{
d01949b6 7047 struct remote_state *rs = get_remote_state ();
cea39f65 7048 int buf_len;
c906108c 7049
bba74b36 7050 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7051 remote_send (&rs->buf, &rs->buf_size);
c906108c 7052
29709017
DJ
7053 /* We can get out of synch in various cases. If the first character
7054 in the buffer is not a hex character, assume that has happened
7055 and try to fetch another packet to read. */
7056 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7057 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7058 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7059 && rs->buf[0] != 'x') /* New: unavailable register value. */
7060 {
7061 if (remote_debug)
7062 fprintf_unfiltered (gdb_stdlog,
7063 "Bad register packet; fetching a new packet\n");
7064 getpkt (&rs->buf, &rs->buf_size, 0);
7065 }
7066
74ca34ce
DJ
7067 buf_len = strlen (rs->buf);
7068
7069 /* Sanity check the received packet. */
7070 if (buf_len % 2 != 0)
7071 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7072
7073 return buf_len / 2;
7074}
7075
7076static void
56be3814 7077process_g_packet (struct regcache *regcache)
29709017 7078{
4a22f64d 7079 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7080 struct remote_state *rs = get_remote_state ();
7081 struct remote_arch_state *rsa = get_remote_arch_state ();
7082 int i, buf_len;
7083 char *p;
7084 char *regs;
7085
7086 buf_len = strlen (rs->buf);
7087
7088 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7089 if (buf_len > 2 * rsa->sizeof_g_packet)
7090 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7091
7092 /* Save the size of the packet sent to us by the target. It is used
7093 as a heuristic when determining the max size of packets that the
7094 target can safely receive. */
7095 if (rsa->actual_register_packet_size == 0)
7096 rsa->actual_register_packet_size = buf_len;
7097
7098 /* If this is smaller than we guessed the 'g' packet would be,
7099 update our records. A 'g' reply that doesn't include a register's
7100 value implies either that the register is not available, or that
7101 the 'p' packet must be used. */
7102 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7103 {
74ca34ce
DJ
7104 rsa->sizeof_g_packet = buf_len / 2;
7105
4a22f64d 7106 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7107 {
74ca34ce
DJ
7108 if (rsa->regs[i].pnum == -1)
7109 continue;
7110
7111 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7112 rsa->regs[i].in_g_packet = 0;
b96ec7ac 7113 else
74ca34ce 7114 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7115 }
74ca34ce 7116 }
b323314b 7117
224c3ddb 7118 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7119
7120 /* Unimplemented registers read as all bits zero. */
ea9c271d 7121 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7122
c906108c
SS
7123 /* Reply describes registers byte by byte, each byte encoded as two
7124 hex characters. Suck them all up, then supply them to the
7125 register cacheing/storage mechanism. */
7126
74ca34ce 7127 p = rs->buf;
ea9c271d 7128 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7129 {
74ca34ce
DJ
7130 if (p[0] == 0 || p[1] == 0)
7131 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7132 internal_error (__FILE__, __LINE__,
9b20d036 7133 _("unexpected end of 'g' packet reply"));
74ca34ce 7134
c906108c 7135 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7136 regs[i] = 0; /* 'x' */
c906108c
SS
7137 else
7138 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7139 p += 2;
7140 }
7141
a744cf53
MS
7142 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7143 {
7144 struct packet_reg *r = &rsa->regs[i];
7145
7146 if (r->in_g_packet)
7147 {
7148 if (r->offset * 2 >= strlen (rs->buf))
7149 /* This shouldn't happen - we adjusted in_g_packet above. */
7150 internal_error (__FILE__, __LINE__,
9b20d036 7151 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7152 else if (rs->buf[r->offset * 2] == 'x')
7153 {
7154 gdb_assert (r->offset * 2 < strlen (rs->buf));
7155 /* The register isn't available, mark it as such (at
7156 the same time setting the value to zero). */
7157 regcache_raw_supply (regcache, r->regnum, NULL);
7158 }
7159 else
7160 regcache_raw_supply (regcache, r->regnum,
7161 regs + r->offset);
7162 }
7163 }
c906108c
SS
7164}
7165
29709017 7166static void
56be3814 7167fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7168{
7169 send_g_packet ();
56be3814 7170 process_g_packet (regcache);
29709017
DJ
7171}
7172
e6e4e701
PA
7173/* Make the remote selected traceframe match GDB's selected
7174 traceframe. */
7175
7176static void
7177set_remote_traceframe (void)
7178{
7179 int newnum;
262e1174 7180 struct remote_state *rs = get_remote_state ();
e6e4e701 7181
262e1174 7182 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7183 return;
7184
7185 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7186 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7187
7188 newnum = target_trace_find (tfind_number,
7189 get_traceframe_number (), 0, 0, NULL);
7190
7191 /* Should not happen. If it does, all bets are off. */
7192 if (newnum != get_traceframe_number ())
7193 warning (_("could not set remote traceframe"));
7194}
7195
74ca34ce 7196static void
28439f5e
PA
7197remote_fetch_registers (struct target_ops *ops,
7198 struct regcache *regcache, int regnum)
74ca34ce 7199{
74ca34ce
DJ
7200 struct remote_arch_state *rsa = get_remote_arch_state ();
7201 int i;
7202
e6e4e701 7203 set_remote_traceframe ();
79d7f229 7204 set_general_thread (inferior_ptid);
74ca34ce
DJ
7205
7206 if (regnum >= 0)
7207 {
7208 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7209
74ca34ce
DJ
7210 gdb_assert (reg != NULL);
7211
7212 /* If this register might be in the 'g' packet, try that first -
7213 we are likely to read more than one register. If this is the
7214 first 'g' packet, we might be overly optimistic about its
7215 contents, so fall back to 'p'. */
7216 if (reg->in_g_packet)
7217 {
56be3814 7218 fetch_registers_using_g (regcache);
74ca34ce
DJ
7219 if (reg->in_g_packet)
7220 return;
7221 }
7222
56be3814 7223 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7224 return;
7225
7226 /* This register is not available. */
56be3814 7227 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7228
7229 return;
7230 }
7231
56be3814 7232 fetch_registers_using_g (regcache);
74ca34ce 7233
4a22f64d 7234 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7235 if (!rsa->regs[i].in_g_packet)
56be3814 7236 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7237 {
7238 /* This register is not available. */
56be3814 7239 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7240 }
7241}
7242
c906108c
SS
7243/* Prepare to store registers. Since we may send them all (using a
7244 'G' request), we have to read out the ones we don't want to change
7245 first. */
7246
c5aa993b 7247static void
f32dbf8c 7248remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7249{
ea9c271d 7250 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7251 int i;
cfd77fa1 7252 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7253
c906108c 7254 /* Make sure the entire registers array is valid. */
4082afcc 7255 switch (packet_support (PACKET_P))
5a2468f5
JM
7256 {
7257 case PACKET_DISABLE:
7258 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7259 /* Make sure all the necessary registers are cached. */
4a22f64d 7260 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7261 if (rsa->regs[i].in_g_packet)
316f2060 7262 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7263 break;
7264 case PACKET_ENABLE:
7265 break;
7266 }
7267}
7268
ad10f812 7269/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7270 packet was not recognized. */
5a2468f5
JM
7271
7272static int
1f4437a4
MS
7273store_register_using_P (const struct regcache *regcache,
7274 struct packet_reg *reg)
5a2468f5 7275{
4a22f64d 7276 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7277 struct remote_state *rs = get_remote_state ();
5a2468f5 7278 /* Try storing a single register. */
6d820c5c 7279 char *buf = rs->buf;
cfd77fa1 7280 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7281 char *p;
5a2468f5 7282
4082afcc 7283 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7284 return 0;
7285
7286 if (reg->pnum == -1)
7287 return 0;
7288
ea9c271d 7289 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7290 p = buf + strlen (buf);
56be3814 7291 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7292 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7293 putpkt (rs->buf);
7294 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7295
74ca34ce
DJ
7296 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7297 {
7298 case PACKET_OK:
7299 return 1;
7300 case PACKET_ERROR:
27a9c0bf
MS
7301 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7302 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7303 case PACKET_UNKNOWN:
7304 return 0;
7305 default:
7306 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7307 }
c906108c
SS
7308}
7309
23860348
MS
7310/* Store register REGNUM, or all registers if REGNUM == -1, from the
7311 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7312
7313static void
56be3814 7314store_registers_using_G (const struct regcache *regcache)
c906108c 7315{
d01949b6 7316 struct remote_state *rs = get_remote_state ();
ea9c271d 7317 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7318 gdb_byte *regs;
c906108c
SS
7319 char *p;
7320
193cb69f
AC
7321 /* Extract all the registers in the regcache copying them into a
7322 local buffer. */
7323 {
b323314b 7324 int i;
a744cf53 7325
224c3ddb 7326 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7327 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7328 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7329 {
ea9c271d 7330 struct packet_reg *r = &rsa->regs[i];
a744cf53 7331
b323314b 7332 if (r->in_g_packet)
56be3814 7333 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7334 }
7335 }
c906108c
SS
7336
7337 /* Command describes registers byte by byte,
7338 each byte encoded as two hex characters. */
6d820c5c 7339 p = rs->buf;
193cb69f 7340 *p++ = 'G';
74ca34ce
DJ
7341 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7342 updated. */
7343 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7344 putpkt (rs->buf);
7345 getpkt (&rs->buf, &rs->buf_size, 0);
7346 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7347 error (_("Could not write registers; remote failure reply '%s'"),
7348 rs->buf);
c906108c 7349}
74ca34ce
DJ
7350
7351/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7352 of the register cache buffer. FIXME: ignores errors. */
7353
7354static void
28439f5e
PA
7355remote_store_registers (struct target_ops *ops,
7356 struct regcache *regcache, int regnum)
74ca34ce 7357{
74ca34ce
DJ
7358 struct remote_arch_state *rsa = get_remote_arch_state ();
7359 int i;
7360
e6e4e701 7361 set_remote_traceframe ();
79d7f229 7362 set_general_thread (inferior_ptid);
74ca34ce
DJ
7363
7364 if (regnum >= 0)
7365 {
7366 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7367
74ca34ce
DJ
7368 gdb_assert (reg != NULL);
7369
7370 /* Always prefer to store registers using the 'P' packet if
7371 possible; we often change only a small number of registers.
7372 Sometimes we change a larger number; we'd need help from a
7373 higher layer to know to use 'G'. */
56be3814 7374 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7375 return;
7376
7377 /* For now, don't complain if we have no way to write the
7378 register. GDB loses track of unavailable registers too
7379 easily. Some day, this may be an error. We don't have
0df8b418 7380 any way to read the register, either... */
74ca34ce
DJ
7381 if (!reg->in_g_packet)
7382 return;
7383
56be3814 7384 store_registers_using_G (regcache);
74ca34ce
DJ
7385 return;
7386 }
7387
56be3814 7388 store_registers_using_G (regcache);
74ca34ce 7389
4a22f64d 7390 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7391 if (!rsa->regs[i].in_g_packet)
56be3814 7392 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7393 /* See above for why we do not issue an error here. */
7394 continue;
7395}
c906108c
SS
7396\f
7397
7398/* Return the number of hex digits in num. */
7399
7400static int
fba45db2 7401hexnumlen (ULONGEST num)
c906108c
SS
7402{
7403 int i;
7404
7405 for (i = 0; num != 0; i++)
7406 num >>= 4;
7407
7408 return max (i, 1);
7409}
7410
2df3850c 7411/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7412
7413static int
fba45db2 7414hexnumstr (char *buf, ULONGEST num)
c906108c 7415{
c906108c 7416 int len = hexnumlen (num);
a744cf53 7417
2df3850c
JM
7418 return hexnumnstr (buf, num, len);
7419}
7420
c906108c 7421
2df3850c 7422/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7423
2df3850c 7424static int
fba45db2 7425hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7426{
7427 int i;
7428
7429 buf[width] = '\0';
7430
7431 for (i = width - 1; i >= 0; i--)
c906108c 7432 {
c5aa993b 7433 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7434 num >>= 4;
7435 }
7436
2df3850c 7437 return width;
c906108c
SS
7438}
7439
23860348 7440/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7441
7442static CORE_ADDR
fba45db2 7443remote_address_masked (CORE_ADDR addr)
c906108c 7444{
883b9c6c 7445 unsigned int address_size = remote_address_size;
a744cf53 7446
911c95a5
UW
7447 /* If "remoteaddresssize" was not set, default to target address size. */
7448 if (!address_size)
f5656ead 7449 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7450
7451 if (address_size > 0
7452 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7453 {
7454 /* Only create a mask when that mask can safely be constructed
23860348 7455 in a ULONGEST variable. */
c906108c 7456 ULONGEST mask = 1;
a744cf53 7457
911c95a5 7458 mask = (mask << address_size) - 1;
c906108c
SS
7459 addr &= mask;
7460 }
7461 return addr;
7462}
7463
7464/* Determine whether the remote target supports binary downloading.
7465 This is accomplished by sending a no-op memory write of zero length
7466 to the target at the specified address. It does not suffice to send
23860348
MS
7467 the whole packet, since many stubs strip the eighth bit and
7468 subsequently compute a wrong checksum, which causes real havoc with
7469 remote_write_bytes.
7a292a7a 7470
96baa820 7471 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7472 clean. In cases like this, the user should clear "remote
23860348 7473 X-packet". */
96baa820 7474
c906108c 7475static void
fba45db2 7476check_binary_download (CORE_ADDR addr)
c906108c 7477{
d01949b6 7478 struct remote_state *rs = get_remote_state ();
24b06219 7479
4082afcc 7480 switch (packet_support (PACKET_X))
c906108c 7481 {
96baa820
JM
7482 case PACKET_DISABLE:
7483 break;
7484 case PACKET_ENABLE:
7485 break;
7486 case PACKET_SUPPORT_UNKNOWN:
7487 {
96baa820 7488 char *p;
802188a7 7489
2e9f7625 7490 p = rs->buf;
96baa820
JM
7491 *p++ = 'X';
7492 p += hexnumstr (p, (ULONGEST) addr);
7493 *p++ = ',';
7494 p += hexnumstr (p, (ULONGEST) 0);
7495 *p++ = ':';
7496 *p = '\0';
802188a7 7497
2e9f7625 7498 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7499 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7500
2e9f7625 7501 if (rs->buf[0] == '\0')
96baa820
JM
7502 {
7503 if (remote_debug)
7504 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7505 "binary downloading NOT "
7506 "supported by target\n");
444abaca 7507 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7508 }
7509 else
7510 {
7511 if (remote_debug)
7512 fprintf_unfiltered (gdb_stdlog,
64b9b334 7513 "binary downloading supported by target\n");
444abaca 7514 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7515 }
7516 break;
7517 }
c906108c
SS
7518 }
7519}
7520
124e13d9
SM
7521/* Helper function to resize the payload in order to try to get a good
7522 alignment. We try to write an amount of data such that the next write will
7523 start on an address aligned on REMOTE_ALIGN_WRITES. */
7524
7525static int
7526align_for_efficient_write (int todo, CORE_ADDR memaddr)
7527{
7528 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7529}
7530
c906108c
SS
7531/* Write memory data directly to the remote machine.
7532 This does not inform the data cache; the data cache uses this.
a76d924d 7533 HEADER is the starting part of the packet.
c906108c
SS
7534 MEMADDR is the address in the remote memory space.
7535 MYADDR is the address of the buffer in our space.
124e13d9
SM
7536 LEN_UNITS is the number of addressable units to write.
7537 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7538 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7539 should send data as binary ('X'), or hex-encoded ('M').
7540
7541 The function creates packet of the form
7542 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7543
124e13d9 7544 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7545
7546 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7547 are omitted.
7548
9b409511 7549 Return the transferred status, error or OK (an
124e13d9
SM
7550 'enum target_xfer_status' value). Save the number of addressable units
7551 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7552
7553 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7554 exchange between gdb and the stub could look like (?? in place of the
7555 checksum):
7556
7557 -> $m1000,4#??
7558 <- aaaabbbbccccdddd
7559
7560 -> $M1000,3:eeeeffffeeee#??
7561 <- OK
7562
7563 -> $m1000,4#??
7564 <- eeeeffffeeeedddd */
c906108c 7565
9b409511 7566static enum target_xfer_status
a76d924d 7567remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7568 const gdb_byte *myaddr, ULONGEST len_units,
7569 int unit_size, ULONGEST *xfered_len_units,
7570 char packet_format, int use_length)
c906108c 7571{
6d820c5c 7572 struct remote_state *rs = get_remote_state ();
cfd77fa1 7573 char *p;
a76d924d
DJ
7574 char *plen = NULL;
7575 int plenlen = 0;
124e13d9
SM
7576 int todo_units;
7577 int units_written;
7578 int payload_capacity_bytes;
7579 int payload_length_bytes;
a76d924d
DJ
7580
7581 if (packet_format != 'X' && packet_format != 'M')
7582 internal_error (__FILE__, __LINE__,
9b20d036 7583 _("remote_write_bytes_aux: bad packet format"));
c906108c 7584
124e13d9 7585 if (len_units == 0)
9b409511 7586 return TARGET_XFER_EOF;
b2182ed2 7587
124e13d9 7588 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7589
6d820c5c
DJ
7590 /* The packet buffer will be large enough for the payload;
7591 get_memory_packet_size ensures this. */
a76d924d 7592 rs->buf[0] = '\0';
c906108c 7593
a257b5bb 7594 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7595 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7596
124e13d9 7597 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7598 if (!use_length)
0df8b418 7599 /* The comma won't be used. */
124e13d9
SM
7600 payload_capacity_bytes += 1;
7601 payload_capacity_bytes -= strlen (header);
7602 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7603
a76d924d 7604 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7605
a76d924d
DJ
7606 strcat (rs->buf, header);
7607 p = rs->buf + strlen (header);
7608
7609 /* Compute a best guess of the number of bytes actually transfered. */
7610 if (packet_format == 'X')
c906108c 7611 {
23860348 7612 /* Best guess at number of bytes that will fit. */
124e13d9 7613 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7614 if (use_length)
124e13d9
SM
7615 payload_capacity_bytes -= hexnumlen (todo_units);
7616 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7617 }
7618 else
7619 {
124e13d9
SM
7620 /* Number of bytes that will fit. */
7621 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7622 if (use_length)
124e13d9
SM
7623 payload_capacity_bytes -= hexnumlen (todo_units);
7624 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7625 }
a76d924d 7626
124e13d9 7627 if (todo_units <= 0)
3de11b2e 7628 internal_error (__FILE__, __LINE__,
405f8e94 7629 _("minimum packet size too small to write data"));
802188a7 7630
6765f3e5
DJ
7631 /* If we already need another packet, then try to align the end
7632 of this packet to a useful boundary. */
124e13d9
SM
7633 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7634 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7635
a257b5bb 7636 /* Append "<memaddr>". */
917317f4
JM
7637 memaddr = remote_address_masked (memaddr);
7638 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7639
a76d924d
DJ
7640 if (use_length)
7641 {
7642 /* Append ",". */
7643 *p++ = ',';
802188a7 7644
124e13d9
SM
7645 /* Append the length and retain its location and size. It may need to be
7646 adjusted once the packet body has been created. */
a76d924d 7647 plen = p;
124e13d9 7648 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7649 p += plenlen;
7650 }
a257b5bb
AC
7651
7652 /* Append ":". */
917317f4
JM
7653 *p++ = ':';
7654 *p = '\0';
802188a7 7655
a257b5bb 7656 /* Append the packet body. */
a76d924d 7657 if (packet_format == 'X')
917317f4 7658 {
917317f4
JM
7659 /* Binary mode. Send target system values byte by byte, in
7660 increasing byte addresses. Only escape certain critical
7661 characters. */
124e13d9
SM
7662 payload_length_bytes =
7663 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7664 &units_written, payload_capacity_bytes);
6765f3e5 7665
124e13d9 7666 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7667 a second try to keep the end of the packet aligned. Don't do
7668 this if the packet is tiny. */
124e13d9 7669 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7670 {
124e13d9
SM
7671 int new_todo_units;
7672
7673 new_todo_units = align_for_efficient_write (units_written, memaddr);
7674
7675 if (new_todo_units != units_written)
7676 payload_length_bytes =
7677 remote_escape_output (myaddr, new_todo_units, unit_size,
7678 (gdb_byte *) p, &units_written,
7679 payload_capacity_bytes);
6765f3e5
DJ
7680 }
7681
124e13d9
SM
7682 p += payload_length_bytes;
7683 if (use_length && units_written < todo_units)
c906108c 7684 {
802188a7 7685 /* Escape chars have filled up the buffer prematurely,
124e13d9 7686 and we have actually sent fewer units than planned.
917317f4
JM
7687 Fix-up the length field of the packet. Use the same
7688 number of characters as before. */
124e13d9
SM
7689 plen += hexnumnstr (plen, (ULONGEST) units_written,
7690 plenlen);
917317f4 7691 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7692 }
a76d924d
DJ
7693 }
7694 else
7695 {
917317f4
JM
7696 /* Normal mode: Send target system values byte by byte, in
7697 increasing byte addresses. Each byte is encoded as a two hex
7698 value. */
124e13d9
SM
7699 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7700 units_written = todo_units;
c906108c 7701 }
802188a7 7702
2e9f7625 7703 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7704 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7705
2e9f7625 7706 if (rs->buf[0] == 'E')
00d84524 7707 return TARGET_XFER_E_IO;
802188a7 7708
124e13d9
SM
7709 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7710 send fewer units than we'd planned. */
7711 *xfered_len_units = (ULONGEST) units_written;
9b409511 7712 return TARGET_XFER_OK;
c906108c
SS
7713}
7714
a76d924d
DJ
7715/* Write memory data directly to the remote machine.
7716 This does not inform the data cache; the data cache uses this.
7717 MEMADDR is the address in the remote memory space.
7718 MYADDR is the address of the buffer in our space.
7719 LEN is the number of bytes.
7720
9b409511
YQ
7721 Return the transferred status, error or OK (an
7722 'enum target_xfer_status' value). Save the number of bytes
7723 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7724
9b409511
YQ
7725static enum target_xfer_status
7726remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7727 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7728{
7729 char *packet_format = 0;
7730
7731 /* Check whether the target supports binary download. */
7732 check_binary_download (memaddr);
7733
4082afcc 7734 switch (packet_support (PACKET_X))
a76d924d
DJ
7735 {
7736 case PACKET_ENABLE:
7737 packet_format = "X";
7738 break;
7739 case PACKET_DISABLE:
7740 packet_format = "M";
7741 break;
7742 case PACKET_SUPPORT_UNKNOWN:
7743 internal_error (__FILE__, __LINE__,
7744 _("remote_write_bytes: bad internal state"));
7745 default:
7746 internal_error (__FILE__, __LINE__, _("bad switch"));
7747 }
7748
7749 return remote_write_bytes_aux (packet_format,
124e13d9 7750 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7751 packet_format[0], 1);
a76d924d
DJ
7752}
7753
9217e74e
YQ
7754/* Read memory data directly from the remote machine.
7755 This does not use the data cache; the data cache uses this.
7756 MEMADDR is the address in the remote memory space.
7757 MYADDR is the address of the buffer in our space.
124e13d9
SM
7758 LEN_UNITS is the number of addressable memory units to read..
7759 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7760
7761 Return the transferred status, error or OK (an
7762 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7763 transferred in *XFERED_LEN_UNITS.
7764
7765 See the comment of remote_write_bytes_aux for an example of
7766 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7767
7768static enum target_xfer_status
124e13d9
SM
7769remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7770 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7771{
7772 struct remote_state *rs = get_remote_state ();
124e13d9 7773 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7774 char *p;
124e13d9
SM
7775 int todo_units;
7776 int decoded_bytes;
9217e74e 7777
124e13d9 7778 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7779 /* The packet buffer will be large enough for the payload;
7780 get_memory_packet_size ensures this. */
7781
124e13d9
SM
7782 /* Number of units that will fit. */
7783 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7784
7785 /* Construct "m"<memaddr>","<len>". */
7786 memaddr = remote_address_masked (memaddr);
7787 p = rs->buf;
7788 *p++ = 'm';
7789 p += hexnumstr (p, (ULONGEST) memaddr);
7790 *p++ = ',';
124e13d9 7791 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7792 *p = '\0';
7793 putpkt (rs->buf);
7794 getpkt (&rs->buf, &rs->buf_size, 0);
7795 if (rs->buf[0] == 'E'
7796 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7797 && rs->buf[3] == '\0')
7798 return TARGET_XFER_E_IO;
7799 /* Reply describes memory byte by byte, each byte encoded as two hex
7800 characters. */
7801 p = rs->buf;
124e13d9 7802 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7803 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7804 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7805 return TARGET_XFER_OK;
7806}
7807
b55fbac4
YQ
7808/* Using the set of read-only target sections of remote, read live
7809 read-only memory.
8acf9577
YQ
7810
7811 For interface/parameters/return description see target.h,
7812 to_xfer_partial. */
7813
7814static enum target_xfer_status
b55fbac4
YQ
7815remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7816 ULONGEST memaddr, ULONGEST len,
124e13d9 7817 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7818{
7819 struct target_section *secp;
7820 struct target_section_table *table;
7821
7822 secp = target_section_by_addr (ops, memaddr);
7823 if (secp != NULL
7824 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7825 secp->the_bfd_section)
7826 & SEC_READONLY))
7827 {
7828 struct target_section *p;
7829 ULONGEST memend = memaddr + len;
7830
7831 table = target_get_section_table (ops);
7832
7833 for (p = table->sections; p < table->sections_end; p++)
7834 {
7835 if (memaddr >= p->addr)
7836 {
7837 if (memend <= p->endaddr)
7838 {
7839 /* Entire transfer is within this section. */
124e13d9 7840 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7841 xfered_len);
8acf9577
YQ
7842 }
7843 else if (memaddr >= p->endaddr)
7844 {
7845 /* This section ends before the transfer starts. */
7846 continue;
7847 }
7848 else
7849 {
7850 /* This section overlaps the transfer. Just do half. */
7851 len = p->endaddr - memaddr;
124e13d9 7852 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7853 xfered_len);
8acf9577
YQ
7854 }
7855 }
7856 }
7857 }
7858
7859 return TARGET_XFER_EOF;
7860}
7861
9217e74e
YQ
7862/* Similar to remote_read_bytes_1, but it reads from the remote stub
7863 first if the requested memory is unavailable in traceframe.
7864 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7865
9b409511 7866static enum target_xfer_status
8acf9577 7867remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7868 gdb_byte *myaddr, ULONGEST len, int unit_size,
7869 ULONGEST *xfered_len)
c906108c 7870{
6b6aa828 7871 if (len == 0)
96c4f946 7872 return TARGET_XFER_EOF;
b2182ed2 7873
8acf9577
YQ
7874 if (get_traceframe_number () != -1)
7875 {
7876 VEC(mem_range_s) *available;
7877
7878 /* If we fail to get the set of available memory, then the
7879 target does not support querying traceframe info, and so we
7880 attempt reading from the traceframe anyway (assuming the
7881 target implements the old QTro packet then). */
7882 if (traceframe_available_memory (&available, memaddr, len))
7883 {
7884 struct cleanup *old_chain;
7885
7886 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7887
7888 if (VEC_empty (mem_range_s, available)
7889 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7890 {
7891 enum target_xfer_status res;
7892
7893 /* Don't read into the traceframe's available
7894 memory. */
7895 if (!VEC_empty (mem_range_s, available))
7896 {
7897 LONGEST oldlen = len;
7898
7899 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7900 gdb_assert (len <= oldlen);
7901 }
7902
7903 do_cleanups (old_chain);
7904
7905 /* This goes through the topmost target again. */
b55fbac4 7906 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7907 len, unit_size, xfered_len);
8acf9577
YQ
7908 if (res == TARGET_XFER_OK)
7909 return TARGET_XFER_OK;
7910 else
7911 {
7912 /* No use trying further, we know some memory starting
7913 at MEMADDR isn't available. */
7914 *xfered_len = len;
7915 return TARGET_XFER_UNAVAILABLE;
7916 }
7917 }
7918
7919 /* Don't try to read more than how much is available, in
7920 case the target implements the deprecated QTro packet to
7921 cater for older GDBs (the target's knowledge of read-only
7922 sections may be outdated by now). */
7923 len = VEC_index (mem_range_s, available, 0)->length;
7924
7925 do_cleanups (old_chain);
7926 }
7927 }
7928
124e13d9 7929 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7930}
74531fed 7931
c906108c 7932\f
c906108c 7933
a76d924d
DJ
7934/* Sends a packet with content determined by the printf format string
7935 FORMAT and the remaining arguments, then gets the reply. Returns
7936 whether the packet was a success, a failure, or unknown. */
7937
77b64a49
PA
7938static enum packet_result remote_send_printf (const char *format, ...)
7939 ATTRIBUTE_PRINTF (1, 2);
7940
2c0b251b 7941static enum packet_result
a76d924d
DJ
7942remote_send_printf (const char *format, ...)
7943{
7944 struct remote_state *rs = get_remote_state ();
7945 int max_size = get_remote_packet_size ();
a76d924d 7946 va_list ap;
a744cf53 7947
a76d924d
DJ
7948 va_start (ap, format);
7949
7950 rs->buf[0] = '\0';
7951 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7952 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7953
7954 if (putpkt (rs->buf) < 0)
7955 error (_("Communication problem with target."));
7956
7957 rs->buf[0] = '\0';
7958 getpkt (&rs->buf, &rs->buf_size, 0);
7959
7960 return packet_check_result (rs->buf);
7961}
7962
7963static void
7964restore_remote_timeout (void *p)
7965{
7966 int value = *(int *)p;
a744cf53 7967
a76d924d
DJ
7968 remote_timeout = value;
7969}
7970
7971/* Flash writing can take quite some time. We'll set
7972 effectively infinite timeout for flash operations.
7973 In future, we'll need to decide on a better approach. */
7974static const int remote_flash_timeout = 1000;
7975
7976static void
7977remote_flash_erase (struct target_ops *ops,
7978 ULONGEST address, LONGEST length)
7979{
f5656ead 7980 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7981 int saved_remote_timeout = remote_timeout;
7982 enum packet_result ret;
a76d924d
DJ
7983 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7984 &saved_remote_timeout);
a744cf53 7985
a76d924d
DJ
7986 remote_timeout = remote_flash_timeout;
7987
7988 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7989 phex (address, addr_size),
a76d924d
DJ
7990 phex (length, 4));
7991 switch (ret)
7992 {
7993 case PACKET_UNKNOWN:
7994 error (_("Remote target does not support flash erase"));
7995 case PACKET_ERROR:
7996 error (_("Error erasing flash with vFlashErase packet"));
7997 default:
7998 break;
7999 }
8000
8001 do_cleanups (back_to);
8002}
8003
9b409511
YQ
8004static enum target_xfer_status
8005remote_flash_write (struct target_ops *ops, ULONGEST address,
8006 ULONGEST length, ULONGEST *xfered_len,
8007 const gdb_byte *data)
a76d924d
DJ
8008{
8009 int saved_remote_timeout = remote_timeout;
9b409511 8010 enum target_xfer_status ret;
a76d924d 8011 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 8012 &saved_remote_timeout);
a76d924d
DJ
8013
8014 remote_timeout = remote_flash_timeout;
124e13d9 8015 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 8016 xfered_len,'X', 0);
a76d924d
DJ
8017 do_cleanups (back_to);
8018
8019 return ret;
8020}
8021
8022static void
8023remote_flash_done (struct target_ops *ops)
8024{
8025 int saved_remote_timeout = remote_timeout;
8026 int ret;
8027 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8028 &saved_remote_timeout);
8029
8030 remote_timeout = remote_flash_timeout;
8031 ret = remote_send_printf ("vFlashDone");
8032 do_cleanups (back_to);
8033
8034 switch (ret)
8035 {
8036 case PACKET_UNKNOWN:
8037 error (_("Remote target does not support vFlashDone"));
8038 case PACKET_ERROR:
8039 error (_("Error finishing flash operation"));
8040 default:
8041 break;
8042 }
8043}
8044
c906108c 8045static void
fba45db2 8046remote_files_info (struct target_ops *ignore)
c906108c
SS
8047{
8048 puts_filtered ("Debugging a target over a serial line.\n");
8049}
8050\f
8051/* Stuff for dealing with the packets which are part of this protocol.
8052 See comment at top of file for details. */
8053
1927e618
PA
8054/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8055 error to higher layers. Called when a serial error is detected.
8056 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8057 the system error message for errno at function entry and final dot
8058 for output compatibility with throw_perror_with_name. */
1927e618
PA
8059
8060static void
8061unpush_and_perror (const char *string)
8062{
d6cb50a2 8063 int saved_errno = errno;
1927e618
PA
8064
8065 remote_unpush_target ();
d6cb50a2
JK
8066 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8067 safe_strerror (saved_errno));
1927e618
PA
8068}
8069
0876f84a 8070/* Read a single character from the remote end. */
c906108c
SS
8071
8072static int
fba45db2 8073readchar (int timeout)
c906108c
SS
8074{
8075 int ch;
5d93a237 8076 struct remote_state *rs = get_remote_state ();
c906108c 8077
5d93a237 8078 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 8079
2acceee2 8080 if (ch >= 0)
0876f84a 8081 return ch;
2acceee2
JM
8082
8083 switch ((enum serial_rc) ch)
c906108c
SS
8084 {
8085 case SERIAL_EOF:
78a095c3 8086 remote_unpush_target ();
598d3636 8087 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8088 /* no return */
c906108c 8089 case SERIAL_ERROR:
1927e618
PA
8090 unpush_and_perror (_("Remote communication error. "
8091 "Target disconnected."));
2acceee2 8092 /* no return */
c906108c 8093 case SERIAL_TIMEOUT:
2acceee2 8094 break;
c906108c 8095 }
2acceee2 8096 return ch;
c906108c
SS
8097}
8098
c33e31fd
PA
8099/* Wrapper for serial_write that closes the target and throws if
8100 writing fails. */
8101
8102static void
8103remote_serial_write (const char *str, int len)
8104{
5d93a237
TT
8105 struct remote_state *rs = get_remote_state ();
8106
8107 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8108 {
1927e618
PA
8109 unpush_and_perror (_("Remote communication error. "
8110 "Target disconnected."));
c33e31fd
PA
8111 }
8112}
8113
6d820c5c
DJ
8114/* Send the command in *BUF to the remote machine, and read the reply
8115 into *BUF. Report an error if we get an error reply. Resize
8116 *BUF using xrealloc if necessary to hold the result, and update
8117 *SIZEOF_BUF. */
c906108c
SS
8118
8119static void
6d820c5c
DJ
8120remote_send (char **buf,
8121 long *sizeof_buf)
c906108c 8122{
6d820c5c 8123 putpkt (*buf);
c2d11a7d 8124 getpkt (buf, sizeof_buf, 0);
c906108c 8125
6d820c5c
DJ
8126 if ((*buf)[0] == 'E')
8127 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8128}
8129
6e5abd65
PA
8130/* Return a pointer to an xmalloc'ed string representing an escaped
8131 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8132 etc. The caller is responsible for releasing the returned
8133 memory. */
8134
8135static char *
8136escape_buffer (const char *buf, int n)
8137{
8138 struct cleanup *old_chain;
8139 struct ui_file *stb;
8140 char *str;
6e5abd65
PA
8141
8142 stb = mem_fileopen ();
8143 old_chain = make_cleanup_ui_file_delete (stb);
8144
6ef284bd 8145 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 8146 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
8147 do_cleanups (old_chain);
8148 return str;
8149}
8150
c906108c
SS
8151/* Display a null-terminated packet on stdout, for debugging, using C
8152 string notation. */
8153
8154static void
baa336ce 8155print_packet (const char *buf)
c906108c
SS
8156{
8157 puts_filtered ("\"");
43e526b9 8158 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8159 puts_filtered ("\"");
8160}
8161
8162int
baa336ce 8163putpkt (const char *buf)
c906108c
SS
8164{
8165 return putpkt_binary (buf, strlen (buf));
8166}
8167
8168/* Send a packet to the remote machine, with error checking. The data
23860348 8169 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8170 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8171 and for a possible /0 if we are debugging (remote_debug) and want
8172 to print the sent packet as a string. */
c906108c
SS
8173
8174static int
baa336ce 8175putpkt_binary (const char *buf, int cnt)
c906108c 8176{
2d717e4f 8177 struct remote_state *rs = get_remote_state ();
c906108c
SS
8178 int i;
8179 unsigned char csum = 0;
224c3ddb 8180 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8181 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8182
c906108c
SS
8183 int ch;
8184 int tcount = 0;
8185 char *p;
dd61ec5c 8186 char *message;
c906108c 8187
e24a49d8
PA
8188 /* Catch cases like trying to read memory or listing threads while
8189 we're waiting for a stop reply. The remote server wouldn't be
8190 ready to handle this request, so we'd hang and timeout. We don't
8191 have to worry about this in synchronous mode, because in that
8192 case it's not possible to issue a command while the target is
74531fed
PA
8193 running. This is not a problem in non-stop mode, because in that
8194 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8195 if (!target_is_non_stop_p ()
8196 && target_is_async_p ()
8197 && rs->waiting_for_stop_reply)
9597b22a
DE
8198 {
8199 error (_("Cannot execute this command while the target is running.\n"
8200 "Use the \"interrupt\" command to stop the target\n"
8201 "and then try again."));
8202 }
e24a49d8 8203
2d717e4f
DJ
8204 /* We're sending out a new packet. Make sure we don't look at a
8205 stale cached response. */
8206 rs->cached_wait_status = 0;
8207
c906108c
SS
8208 /* Copy the packet into buffer BUF2, encapsulating it
8209 and giving it a checksum. */
8210
c906108c
SS
8211 p = buf2;
8212 *p++ = '$';
8213
8214 for (i = 0; i < cnt; i++)
8215 {
8216 csum += buf[i];
8217 *p++ = buf[i];
8218 }
8219 *p++ = '#';
8220 *p++ = tohex ((csum >> 4) & 0xf);
8221 *p++ = tohex (csum & 0xf);
8222
8223 /* Send it over and over until we get a positive ack. */
8224
8225 while (1)
8226 {
8227 int started_error_output = 0;
8228
8229 if (remote_debug)
8230 {
6e5abd65
PA
8231 struct cleanup *old_chain;
8232 char *str;
8233
c906108c 8234 *p = '\0';
6e5abd65
PA
8235 str = escape_buffer (buf2, p - buf2);
8236 old_chain = make_cleanup (xfree, str);
8237 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8238 gdb_flush (gdb_stdlog);
6e5abd65 8239 do_cleanups (old_chain);
c906108c 8240 }
c33e31fd 8241 remote_serial_write (buf2, p - buf2);
c906108c 8242
a6f3e723
SL
8243 /* If this is a no acks version of the remote protocol, send the
8244 packet and move on. */
8245 if (rs->noack_mode)
8246 break;
8247
74531fed
PA
8248 /* Read until either a timeout occurs (-2) or '+' is read.
8249 Handle any notification that arrives in the mean time. */
c906108c
SS
8250 while (1)
8251 {
8252 ch = readchar (remote_timeout);
8253
c5aa993b 8254 if (remote_debug)
c906108c
SS
8255 {
8256 switch (ch)
8257 {
8258 case '+':
1216fa2c 8259 case '-':
c906108c
SS
8260 case SERIAL_TIMEOUT:
8261 case '$':
74531fed 8262 case '%':
c906108c
SS
8263 if (started_error_output)
8264 {
8265 putchar_unfiltered ('\n');
8266 started_error_output = 0;
8267 }
8268 }
8269 }
8270
8271 switch (ch)
8272 {
8273 case '+':
8274 if (remote_debug)
0f71a2f6 8275 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8276 do_cleanups (old_chain);
c906108c 8277 return 1;
1216fa2c
AC
8278 case '-':
8279 if (remote_debug)
8280 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8281 /* FALLTHROUGH */
c906108c 8282 case SERIAL_TIMEOUT:
c5aa993b 8283 tcount++;
c906108c 8284 if (tcount > 3)
a5c0808e
PA
8285 {
8286 do_cleanups (old_chain);
8287 return 0;
8288 }
23860348 8289 break; /* Retransmit buffer. */
c906108c
SS
8290 case '$':
8291 {
40e3f985 8292 if (remote_debug)
2bc416ba 8293 fprintf_unfiltered (gdb_stdlog,
23860348 8294 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8295 /* It's probably an old response sent because an ACK
8296 was lost. Gobble up the packet and ack it so it
8297 doesn't get retransmitted when we resend this
8298 packet. */
6d820c5c 8299 skip_frame ();
c33e31fd 8300 remote_serial_write ("+", 1);
23860348 8301 continue; /* Now, go look for +. */
c906108c 8302 }
74531fed
PA
8303
8304 case '%':
8305 {
8306 int val;
8307
8308 /* If we got a notification, handle it, and go back to looking
8309 for an ack. */
8310 /* We've found the start of a notification. Now
8311 collect the data. */
8312 val = read_frame (&rs->buf, &rs->buf_size);
8313 if (val >= 0)
8314 {
8315 if (remote_debug)
8316 {
6e5abd65
PA
8317 struct cleanup *old_chain;
8318 char *str;
8319
8320 str = escape_buffer (rs->buf, val);
8321 old_chain = make_cleanup (xfree, str);
8322 fprintf_unfiltered (gdb_stdlog,
8323 " Notification received: %s\n",
8324 str);
8325 do_cleanups (old_chain);
74531fed 8326 }
5965e028 8327 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8328 /* We're in sync now, rewait for the ack. */
8329 tcount = 0;
8330 }
8331 else
8332 {
8333 if (remote_debug)
8334 {
8335 if (!started_error_output)
8336 {
8337 started_error_output = 1;
8338 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8339 }
8340 fputc_unfiltered (ch & 0177, gdb_stdlog);
8341 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8342 }
8343 }
8344 continue;
8345 }
8346 /* fall-through */
c906108c
SS
8347 default:
8348 if (remote_debug)
8349 {
8350 if (!started_error_output)
8351 {
8352 started_error_output = 1;
0f71a2f6 8353 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8354 }
0f71a2f6 8355 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8356 }
8357 continue;
8358 }
23860348 8359 break; /* Here to retransmit. */
c906108c
SS
8360 }
8361
8362#if 0
8363 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8364 able to get out next time we call QUIT, without anything as
8365 violent as interrupt_query. If we want to provide a way out of
8366 here without getting to the next QUIT, it should be based on
8367 hitting ^C twice as in remote_wait. */
c906108c
SS
8368 if (quit_flag)
8369 {
8370 quit_flag = 0;
8371 interrupt_query ();
8372 }
8373#endif
8374 }
a5c0808e
PA
8375
8376 do_cleanups (old_chain);
a6f3e723 8377 return 0;
c906108c
SS
8378}
8379
6d820c5c
DJ
8380/* Come here after finding the start of a frame when we expected an
8381 ack. Do our best to discard the rest of this packet. */
8382
8383static void
8384skip_frame (void)
8385{
8386 int c;
8387
8388 while (1)
8389 {
8390 c = readchar (remote_timeout);
8391 switch (c)
8392 {
8393 case SERIAL_TIMEOUT:
8394 /* Nothing we can do. */
8395 return;
8396 case '#':
8397 /* Discard the two bytes of checksum and stop. */
8398 c = readchar (remote_timeout);
8399 if (c >= 0)
8400 c = readchar (remote_timeout);
8401
8402 return;
8403 case '*': /* Run length encoding. */
8404 /* Discard the repeat count. */
8405 c = readchar (remote_timeout);
8406 if (c < 0)
8407 return;
8408 break;
8409 default:
8410 /* A regular character. */
8411 break;
8412 }
8413 }
8414}
8415
c906108c 8416/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8417 into *BUF, verifying the checksum, length, and handling run-length
8418 compression. NUL terminate the buffer. If there is not enough room,
8419 expand *BUF using xrealloc.
c906108c 8420
c2d11a7d
JM
8421 Returns -1 on error, number of characters in buffer (ignoring the
8422 trailing NULL) on success. (could be extended to return one of the
23860348 8423 SERIAL status indications). */
c2d11a7d
JM
8424
8425static long
6d820c5c
DJ
8426read_frame (char **buf_p,
8427 long *sizeof_buf)
c906108c
SS
8428{
8429 unsigned char csum;
c2d11a7d 8430 long bc;
c906108c 8431 int c;
6d820c5c 8432 char *buf = *buf_p;
a6f3e723 8433 struct remote_state *rs = get_remote_state ();
c906108c
SS
8434
8435 csum = 0;
c2d11a7d 8436 bc = 0;
c906108c
SS
8437
8438 while (1)
8439 {
8440 c = readchar (remote_timeout);
c906108c
SS
8441 switch (c)
8442 {
8443 case SERIAL_TIMEOUT:
8444 if (remote_debug)
0f71a2f6 8445 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8446 return -1;
c906108c
SS
8447 case '$':
8448 if (remote_debug)
0f71a2f6
JM
8449 fputs_filtered ("Saw new packet start in middle of old one\n",
8450 gdb_stdlog);
23860348 8451 return -1; /* Start a new packet, count retries. */
c906108c
SS
8452 case '#':
8453 {
8454 unsigned char pktcsum;
e1b09194
AC
8455 int check_0 = 0;
8456 int check_1 = 0;
c906108c 8457
c2d11a7d 8458 buf[bc] = '\0';
c906108c 8459
e1b09194
AC
8460 check_0 = readchar (remote_timeout);
8461 if (check_0 >= 0)
8462 check_1 = readchar (remote_timeout);
802188a7 8463
e1b09194
AC
8464 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8465 {
8466 if (remote_debug)
2bc416ba 8467 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8468 gdb_stdlog);
e1b09194
AC
8469 return -1;
8470 }
8471 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8472 {
8473 if (remote_debug)
2bc416ba 8474 fputs_filtered ("Communication error in checksum\n",
23860348 8475 gdb_stdlog);
40e3f985
FN
8476 return -1;
8477 }
c906108c 8478
a6f3e723
SL
8479 /* Don't recompute the checksum; with no ack packets we
8480 don't have any way to indicate a packet retransmission
8481 is necessary. */
8482 if (rs->noack_mode)
8483 return bc;
8484
e1b09194 8485 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8486 if (csum == pktcsum)
c2d11a7d 8487 return bc;
c906108c 8488
c5aa993b 8489 if (remote_debug)
c906108c 8490 {
6e5abd65
PA
8491 struct cleanup *old_chain;
8492 char *str;
8493
8494 str = escape_buffer (buf, bc);
8495 old_chain = make_cleanup (xfree, str);
8496 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8497 "Bad checksum, sentsum=0x%x, "
8498 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8499 pktcsum, csum, str);
8500 do_cleanups (old_chain);
c906108c 8501 }
c2d11a7d 8502 /* Number of characters in buffer ignoring trailing
23860348 8503 NULL. */
c2d11a7d 8504 return -1;
c906108c 8505 }
23860348 8506 case '*': /* Run length encoding. */
c2c6d25f
JM
8507 {
8508 int repeat;
c906108c 8509
a744cf53 8510 csum += c;
b4501125
AC
8511 c = readchar (remote_timeout);
8512 csum += c;
23860348 8513 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8514
23860348 8515 /* The character before ``*'' is repeated. */
c2d11a7d 8516
6d820c5c 8517 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8518 {
6d820c5c
DJ
8519 if (bc + repeat - 1 >= *sizeof_buf - 1)
8520 {
8521 /* Make some more room in the buffer. */
8522 *sizeof_buf += repeat;
224c3ddb 8523 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
8524 buf = *buf_p;
8525 }
8526
c2d11a7d
JM
8527 memset (&buf[bc], buf[bc - 1], repeat);
8528 bc += repeat;
c2c6d25f
JM
8529 continue;
8530 }
8531
c2d11a7d 8532 buf[bc] = '\0';
6d820c5c 8533 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8534 return -1;
c2c6d25f 8535 }
c906108c 8536 default:
6d820c5c 8537 if (bc >= *sizeof_buf - 1)
c906108c 8538 {
6d820c5c
DJ
8539 /* Make some more room in the buffer. */
8540 *sizeof_buf *= 2;
224c3ddb 8541 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 8542 buf = *buf_p;
c906108c
SS
8543 }
8544
6d820c5c
DJ
8545 buf[bc++] = c;
8546 csum += c;
8547 continue;
c906108c
SS
8548 }
8549 }
8550}
8551
8552/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8553 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8554 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8555 rather than timing out; this is used (in synchronous mode) to wait
8556 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8557/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8558 don't have to change all the calls to getpkt to deal with the
8559 return value, because at the moment I don't know what the right
23860348 8560 thing to do it for those. */
c906108c 8561void
6d820c5c
DJ
8562getpkt (char **buf,
8563 long *sizeof_buf,
c2d11a7d 8564 int forever)
d9fcf2fb
JM
8565{
8566 int timed_out;
8567
8568 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8569}
8570
8571
8572/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8573 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8574 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8575 rather than timing out; this is used (in synchronous mode) to wait
8576 for a target that is is executing user code to stop. If FOREVER ==
8577 0, this function is allowed to time out gracefully and return an
74531fed
PA
8578 indication of this to the caller. Otherwise return the number of
8579 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8580 enough reason to return to the caller. *IS_NOTIF is an output
8581 boolean that indicates whether *BUF holds a notification or not
8582 (a regular packet). */
74531fed 8583
3172dc30 8584static int
74531fed 8585getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8586 int expecting_notif, int *is_notif)
c906108c 8587{
2d717e4f 8588 struct remote_state *rs = get_remote_state ();
c906108c
SS
8589 int c;
8590 int tries;
8591 int timeout;
df4b58fe 8592 int val = -1;
c906108c 8593
2d717e4f
DJ
8594 /* We're reading a new response. Make sure we don't look at a
8595 previously cached response. */
8596 rs->cached_wait_status = 0;
8597
6d820c5c 8598 strcpy (*buf, "timeout");
c906108c
SS
8599
8600 if (forever)
74531fed
PA
8601 timeout = watchdog > 0 ? watchdog : -1;
8602 else if (expecting_notif)
8603 timeout = 0; /* There should already be a char in the buffer. If
8604 not, bail out. */
c906108c
SS
8605 else
8606 timeout = remote_timeout;
8607
8608#define MAX_TRIES 3
8609
74531fed
PA
8610 /* Process any number of notifications, and then return when
8611 we get a packet. */
8612 for (;;)
c906108c 8613 {
d9c43928 8614 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8615 times. */
8616 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8617 {
74531fed
PA
8618 /* This can loop forever if the remote side sends us
8619 characters continuously, but if it pauses, we'll get
8620 SERIAL_TIMEOUT from readchar because of timeout. Then
8621 we'll count that as a retry.
8622
8623 Note that even when forever is set, we will only wait
8624 forever prior to the start of a packet. After that, we
8625 expect characters to arrive at a brisk pace. They should
8626 show up within remote_timeout intervals. */
8627 do
8628 c = readchar (timeout);
8629 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8630
8631 if (c == SERIAL_TIMEOUT)
8632 {
74531fed
PA
8633 if (expecting_notif)
8634 return -1; /* Don't complain, it's normal to not get
8635 anything in this case. */
8636
23860348 8637 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8638 {
2acceee2 8639 QUIT;
78a095c3 8640 remote_unpush_target ();
598d3636
JK
8641 throw_error (TARGET_CLOSE_ERROR,
8642 _("Watchdog timeout has expired. "
8643 "Target detached."));
c906108c 8644 }
c906108c 8645 if (remote_debug)
0f71a2f6 8646 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8647 }
74531fed
PA
8648 else
8649 {
8650 /* We've found the start of a packet or notification.
8651 Now collect the data. */
8652 val = read_frame (buf, sizeof_buf);
8653 if (val >= 0)
8654 break;
8655 }
8656
c33e31fd 8657 remote_serial_write ("-", 1);
c906108c 8658 }
c906108c 8659
74531fed
PA
8660 if (tries > MAX_TRIES)
8661 {
8662 /* We have tried hard enough, and just can't receive the
8663 packet/notification. Give up. */
8664 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8665
74531fed
PA
8666 /* Skip the ack char if we're in no-ack mode. */
8667 if (!rs->noack_mode)
c33e31fd 8668 remote_serial_write ("+", 1);
74531fed
PA
8669 return -1;
8670 }
c906108c 8671
74531fed
PA
8672 /* If we got an ordinary packet, return that to our caller. */
8673 if (c == '$')
c906108c
SS
8674 {
8675 if (remote_debug)
43e526b9 8676 {
6e5abd65
PA
8677 struct cleanup *old_chain;
8678 char *str;
8679
8680 str = escape_buffer (*buf, val);
8681 old_chain = make_cleanup (xfree, str);
8682 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8683 do_cleanups (old_chain);
43e526b9 8684 }
a6f3e723
SL
8685
8686 /* Skip the ack char if we're in no-ack mode. */
8687 if (!rs->noack_mode)
c33e31fd 8688 remote_serial_write ("+", 1);
fee9eda9
YQ
8689 if (is_notif != NULL)
8690 *is_notif = 0;
0876f84a 8691 return val;
c906108c
SS
8692 }
8693
74531fed
PA
8694 /* If we got a notification, handle it, and go back to looking
8695 for a packet. */
8696 else
8697 {
8698 gdb_assert (c == '%');
8699
8700 if (remote_debug)
8701 {
6e5abd65
PA
8702 struct cleanup *old_chain;
8703 char *str;
8704
8705 str = escape_buffer (*buf, val);
8706 old_chain = make_cleanup (xfree, str);
8707 fprintf_unfiltered (gdb_stdlog,
8708 " Notification received: %s\n",
8709 str);
8710 do_cleanups (old_chain);
74531fed 8711 }
fee9eda9
YQ
8712 if (is_notif != NULL)
8713 *is_notif = 1;
c906108c 8714
5965e028 8715 handle_notification (rs->notif_state, *buf);
c906108c 8716
74531fed 8717 /* Notifications require no acknowledgement. */
a6f3e723 8718
74531fed 8719 if (expecting_notif)
fee9eda9 8720 return val;
74531fed
PA
8721 }
8722 }
8723}
8724
8725static int
8726getpkt_sane (char **buf, long *sizeof_buf, int forever)
8727{
fee9eda9 8728 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8729}
8730
8731static int
fee9eda9
YQ
8732getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8733 int *is_notif)
74531fed 8734{
fee9eda9
YQ
8735 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8736 is_notif);
c906108c 8737}
74531fed 8738
cbb8991c
DB
8739/* Check whether EVENT is a fork event for the process specified
8740 by the pid passed in DATA, and if it is, kill the fork child. */
8741
8742static int
8743kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8744 QUEUE_ITER (stop_reply_p) *iter,
8745 stop_reply_p event,
8746 void *data)
8747{
19ba03f4 8748 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
8749 int parent_pid = *(int *) param->input;
8750
8751 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8752 {
8753 struct remote_state *rs = get_remote_state ();
8754 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8755 int res;
8756
8757 res = remote_vkill (child_pid, rs);
8758 if (res != 0)
8759 error (_("Can't kill fork child process %d"), child_pid);
8760 }
8761
8762 return 1;
8763}
8764
8765/* Kill any new fork children of process PID that haven't been
8766 processed by follow_fork. */
8767
8768static void
8769kill_new_fork_children (int pid, struct remote_state *rs)
8770{
8771 struct thread_info *thread;
8772 struct notif_client *notif = &notif_client_stop;
8773 struct queue_iter_param param;
8774
8775 /* Kill the fork child threads of any threads in process PID
8776 that are stopped at a fork event. */
8777 ALL_NON_EXITED_THREADS (thread)
8778 {
8779 struct target_waitstatus *ws = &thread->pending_follow;
8780
8781 if (is_pending_fork_parent (ws, pid, thread->ptid))
8782 {
8783 struct remote_state *rs = get_remote_state ();
8784 int child_pid = ptid_get_pid (ws->value.related_pid);
8785 int res;
8786
8787 res = remote_vkill (child_pid, rs);
8788 if (res != 0)
8789 error (_("Can't kill fork child process %d"), child_pid);
8790 }
8791 }
8792
8793 /* Check for any pending fork events (not reported or processed yet)
8794 in process PID and kill those fork child threads as well. */
8795 remote_notif_get_pending_events (notif);
8796 param.input = &pid;
8797 param.output = NULL;
8798 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8799 kill_child_of_pending_fork, &param);
8800}
8801
c906108c
SS
8802\f
8803static void
7d85a9c0 8804remote_kill (struct target_ops *ops)
43ff13b4 8805{
0fdf84ca
PA
8806
8807 /* Catch errors so the user can quit from gdb even when we
23860348 8808 aren't on speaking terms with the remote system. */
492d29ea 8809 TRY
0fdf84ca
PA
8810 {
8811 putpkt ("k");
8812 }
492d29ea 8813 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
8814 {
8815 if (ex.error == TARGET_CLOSE_ERROR)
8816 {
8817 /* If we got an (EOF) error that caused the target
8818 to go away, then we're done, that's what we wanted.
8819 "k" is susceptible to cause a premature EOF, given
8820 that the remote server isn't actually required to
8821 reply to "k", and it can happen that it doesn't
8822 even get to reply ACK to the "k". */
8823 return;
8824 }
8825
8826 /* Otherwise, something went wrong. We didn't actually kill
8827 the target. Just propagate the exception, and let the
8828 user or higher layers decide what to do. */
8829 throw_exception (ex);
8830 }
492d29ea 8831 END_CATCH
43ff13b4 8832
0fdf84ca
PA
8833 /* We've killed the remote end, we get to mourn it. Since this is
8834 target remote, single-process, mourning the inferior also
8835 unpushes remote_ops. */
43ff13b4
JM
8836 target_mourn_inferior ();
8837}
8838
82f73884
PA
8839static int
8840remote_vkill (int pid, struct remote_state *rs)
8841{
4082afcc 8842 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8843 return -1;
8844
8845 /* Tell the remote target to detach. */
bba74b36 8846 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8847 putpkt (rs->buf);
8848 getpkt (&rs->buf, &rs->buf_size, 0);
8849
4082afcc
PA
8850 switch (packet_ok (rs->buf,
8851 &remote_protocol_packets[PACKET_vKill]))
8852 {
8853 case PACKET_OK:
8854 return 0;
8855 case PACKET_ERROR:
8856 return 1;
8857 case PACKET_UNKNOWN:
8858 return -1;
8859 default:
8860 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8861 }
82f73884
PA
8862}
8863
8864static void
7d85a9c0 8865extended_remote_kill (struct target_ops *ops)
82f73884
PA
8866{
8867 int res;
8868 int pid = ptid_get_pid (inferior_ptid);
8869 struct remote_state *rs = get_remote_state ();
8870
cbb8991c
DB
8871 /* If we're stopped while forking and we haven't followed yet, kill the
8872 child task. We need to do this before killing the parent task
8873 because if this is a vfork then the parent will be sleeping. */
8874 kill_new_fork_children (pid, rs);
8875
82f73884 8876 res = remote_vkill (pid, rs);
901f9912 8877 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
8878 {
8879 /* Don't try 'k' on a multi-process aware stub -- it has no way
8880 to specify the pid. */
8881
8882 putpkt ("k");
8883#if 0
8884 getpkt (&rs->buf, &rs->buf_size, 0);
8885 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8886 res = 1;
8887#else
8888 /* Don't wait for it to die. I'm not really sure it matters whether
8889 we do or not. For the existing stubs, kill is a noop. */
8890 res = 0;
8891#endif
8892 }
8893
8894 if (res != 0)
8895 error (_("Can't kill process"));
8896
82f73884
PA
8897 target_mourn_inferior ();
8898}
8899
c906108c 8900static void
20f796c9 8901remote_mourn (struct target_ops *target)
c906108c
SS
8902{
8903 unpush_target (target);
ce5ce7ed 8904
8a2492ee
PA
8905 /* remote_close takes care of doing most of the clean up. */
8906 generic_mourn_inferior ();
c906108c
SS
8907}
8908
2d717e4f 8909static void
20f796c9 8910extended_remote_mourn (struct target_ops *target)
2d717e4f
DJ
8911{
8912 struct remote_state *rs = get_remote_state ();
c906108c 8913
e24a49d8
PA
8914 /* In case we got here due to an error, but we're going to stay
8915 connected. */
8916 rs->waiting_for_stop_reply = 0;
8917
dc1981d7
PA
8918 /* If the current general thread belonged to the process we just
8919 detached from or has exited, the remote side current general
8920 thread becomes undefined. Considering a case like this:
8921
8922 - We just got here due to a detach.
8923 - The process that we're detaching from happens to immediately
8924 report a global breakpoint being hit in non-stop mode, in the
8925 same thread we had selected before.
8926 - GDB attaches to this process again.
8927 - This event happens to be the next event we handle.
8928
8929 GDB would consider that the current general thread didn't need to
8930 be set on the stub side (with Hg), since for all it knew,
8931 GENERAL_THREAD hadn't changed.
8932
8933 Notice that although in all-stop mode, the remote server always
8934 sets the current thread to the thread reporting the stop event,
8935 that doesn't happen in non-stop mode; in non-stop, the stub *must
8936 not* change the current thread when reporting a breakpoint hit,
8937 due to the decoupling of event reporting and event handling.
8938
8939 To keep things simple, we always invalidate our notion of the
8940 current thread. */
47f8a51d 8941 record_currthread (rs, minus_one_ptid);
dc1981d7 8942
2d717e4f
DJ
8943 /* Unlike "target remote", we do not want to unpush the target; then
8944 the next time the user says "run", we won't be connected. */
8945
48aa3c27
PA
8946 /* Call common code to mark the inferior as not running. */
8947 generic_mourn_inferior ();
8948
d729566a 8949 if (!have_inferiors ())
2d717e4f 8950 {
82f73884
PA
8951 if (!remote_multi_process_p (rs))
8952 {
8953 /* Check whether the target is running now - some remote stubs
8954 automatically restart after kill. */
8955 putpkt ("?");
8956 getpkt (&rs->buf, &rs->buf_size, 0);
8957
8958 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8959 {
3e43a32a
MS
8960 /* Assume that the target has been restarted. Set
8961 inferior_ptid so that bits of core GDB realizes
8962 there's something here, e.g., so that the user can
8963 say "kill" again. */
82f73884
PA
8964 inferior_ptid = magic_null_ptid;
8965 }
82f73884 8966 }
2d717e4f
DJ
8967 }
8968}
c906108c 8969
03583c20 8970static int
2bfc0540 8971extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8972{
4082afcc 8973 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8974}
8975
8976static void
8977extended_remote_disable_randomization (int val)
8978{
8979 struct remote_state *rs = get_remote_state ();
8980 char *reply;
8981
bba74b36
YQ
8982 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8983 val);
03583c20
UW
8984 putpkt (rs->buf);
8985 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8986 if (*reply == '\0')
8987 error (_("Target does not support QDisableRandomization."));
8988 if (strcmp (reply, "OK") != 0)
8989 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8990}
8991
2d717e4f
DJ
8992static int
8993extended_remote_run (char *args)
8994{
8995 struct remote_state *rs = get_remote_state ();
2d717e4f 8996 int len;
94585166 8997 const char *remote_exec_file = get_remote_exec_file ();
c906108c 8998
2d717e4f
DJ
8999 /* If the user has disabled vRun support, or we have detected that
9000 support is not available, do not try it. */
4082afcc 9001 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9002 return -1;
424163ea 9003
2d717e4f
DJ
9004 strcpy (rs->buf, "vRun;");
9005 len = strlen (rs->buf);
c906108c 9006
2d717e4f
DJ
9007 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9008 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9009 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9010 strlen (remote_exec_file));
2d717e4f 9011
d1a41061 9012 gdb_assert (args != NULL);
2d717e4f
DJ
9013 if (*args)
9014 {
9015 struct cleanup *back_to;
9016 int i;
9017 char **argv;
9018
d1a41061 9019 argv = gdb_buildargv (args);
6e366df1 9020 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
9021 for (i = 0; argv[i] != NULL; i++)
9022 {
9023 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9024 error (_("Argument list too long for run packet"));
9025 rs->buf[len++] = ';';
9f1b45b0
TT
9026 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9027 strlen (argv[i]));
2d717e4f
DJ
9028 }
9029 do_cleanups (back_to);
9030 }
9031
9032 rs->buf[len++] = '\0';
9033
9034 putpkt (rs->buf);
9035 getpkt (&rs->buf, &rs->buf_size, 0);
9036
4082afcc 9037 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9038 {
4082afcc 9039 case PACKET_OK:
3405876a 9040 /* We have a wait response. All is well. */
2d717e4f 9041 return 0;
4082afcc
PA
9042 case PACKET_UNKNOWN:
9043 return -1;
9044 case PACKET_ERROR:
2d717e4f
DJ
9045 if (remote_exec_file[0] == '\0')
9046 error (_("Running the default executable on the remote target failed; "
9047 "try \"set remote exec-file\"?"));
9048 else
9049 error (_("Running \"%s\" on the remote target failed"),
9050 remote_exec_file);
4082afcc
PA
9051 default:
9052 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9053 }
c906108c
SS
9054}
9055
2d717e4f
DJ
9056/* In the extended protocol we want to be able to do things like
9057 "run" and have them basically work as expected. So we need
9058 a special create_inferior function. We support changing the
9059 executable file and the command line arguments, but not the
9060 environment. */
9061
43ff13b4 9062static void
77a19445
TT
9063extended_remote_create_inferior (struct target_ops *ops,
9064 char *exec_file, char *args,
9065 char **env, int from_tty)
43ff13b4 9066{
3405876a
PA
9067 int run_worked;
9068 char *stop_reply;
9069 struct remote_state *rs = get_remote_state ();
94585166 9070 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9071
43ff13b4 9072 /* If running asynchronously, register the target file descriptor
23860348 9073 with the event loop. */
75c99385 9074 if (target_can_async_p ())
6a3753b3 9075 target_async (1);
43ff13b4 9076
03583c20 9077 /* Disable address space randomization if requested (and supported). */
2bfc0540 9078 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9079 extended_remote_disable_randomization (disable_randomization);
9080
43ff13b4 9081 /* Now restart the remote server. */
3405876a
PA
9082 run_worked = extended_remote_run (args) != -1;
9083 if (!run_worked)
2d717e4f
DJ
9084 {
9085 /* vRun was not supported. Fail if we need it to do what the
9086 user requested. */
9087 if (remote_exec_file[0])
9088 error (_("Remote target does not support \"set remote exec-file\""));
9089 if (args[0])
9090 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9091
2d717e4f
DJ
9092 /* Fall back to "R". */
9093 extended_remote_restart ();
9094 }
424163ea 9095
6c95b8df
PA
9096 if (!have_inferiors ())
9097 {
9098 /* Clean up from the last time we ran, before we mark the target
9099 running again. This will mark breakpoints uninserted, and
9100 get_offsets may insert breakpoints. */
9101 init_thread_list ();
9102 init_wait_for_inferior ();
9103 }
45280a52 9104
3405876a
PA
9105 /* vRun's success return is a stop reply. */
9106 stop_reply = run_worked ? rs->buf : NULL;
9107 add_current_inferior_and_thread (stop_reply);
c0a2216e 9108
2d717e4f
DJ
9109 /* Get updated offsets, if the stub uses qOffsets. */
9110 get_offsets ();
2d717e4f 9111}
c906108c 9112\f
c5aa993b 9113
b775012e
LM
9114/* Given a location's target info BP_TGT and the packet buffer BUF, output
9115 the list of conditions (in agent expression bytecode format), if any, the
9116 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9117 started from BUF and ended at BUF_END. */
b775012e
LM
9118
9119static int
9120remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9121 struct bp_target_info *bp_tgt, char *buf,
9122 char *buf_end)
b775012e
LM
9123{
9124 struct agent_expr *aexpr = NULL;
9125 int i, ix;
9126 char *pkt;
9127 char *buf_start = buf;
9128
9129 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9130 return 0;
9131
9132 buf += strlen (buf);
bba74b36 9133 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9134 buf++;
9135
9136 /* Send conditions to the target and free the vector. */
9137 for (ix = 0;
9138 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9139 ix++)
9140 {
bba74b36 9141 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
9142 buf += strlen (buf);
9143 for (i = 0; i < aexpr->len; ++i)
9144 buf = pack_hex_byte (buf, aexpr->buf[i]);
9145 *buf = '\0';
9146 }
b775012e
LM
9147 return 0;
9148}
9149
d3ce09f5
SS
9150static void
9151remote_add_target_side_commands (struct gdbarch *gdbarch,
9152 struct bp_target_info *bp_tgt, char *buf)
9153{
9154 struct agent_expr *aexpr = NULL;
9155 int i, ix;
9156
9157 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9158 return;
9159
9160 buf += strlen (buf);
9161
9162 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9163 buf += strlen (buf);
9164
9165 /* Concatenate all the agent expressions that are commands into the
9166 cmds parameter. */
9167 for (ix = 0;
9168 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9169 ix++)
9170 {
9171 sprintf (buf, "X%x,", aexpr->len);
9172 buf += strlen (buf);
9173 for (i = 0; i < aexpr->len; ++i)
9174 buf = pack_hex_byte (buf, aexpr->buf[i]);
9175 *buf = '\0';
9176 }
d3ce09f5
SS
9177}
9178
8181d85f
DJ
9179/* Insert a breakpoint. On targets that have software breakpoint
9180 support, we ask the remote target to do the work; on targets
9181 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9182
9183static int
3db08215
MM
9184remote_insert_breakpoint (struct target_ops *ops,
9185 struct gdbarch *gdbarch,
a6d9a66e 9186 struct bp_target_info *bp_tgt)
c906108c 9187{
d471ea57
AC
9188 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9189 If it succeeds, then set the support to PACKET_ENABLE. If it
9190 fails, and the user has explicitly requested the Z support then
23860348 9191 report an error, otherwise, mark it disabled and go on. */
802188a7 9192
4082afcc 9193 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9194 {
0d5ed153 9195 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9196 struct remote_state *rs;
bba74b36 9197 char *p, *endbuf;
7c0f6dcc 9198 int bpsize;
b775012e 9199 struct condition_list *cond = NULL;
4fff2411 9200
28439a30
PA
9201 /* Make sure the remote is pointing at the right process, if
9202 necessary. */
9203 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9204 set_general_process ();
9205
a1dcb23a 9206 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
9207
9208 rs = get_remote_state ();
9209 p = rs->buf;
bba74b36 9210 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9211
96baa820
JM
9212 *(p++) = 'Z';
9213 *(p++) = '0';
9214 *(p++) = ',';
7c0f6dcc 9215 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9216 p += hexnumstr (p, addr);
bba74b36 9217 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 9218
efcc2da7 9219 if (remote_supports_cond_breakpoints (ops))
bba74b36 9220 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9221
78eff0ec 9222 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9223 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9224
6d820c5c
DJ
9225 putpkt (rs->buf);
9226 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9227
6d820c5c 9228 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9229 {
d471ea57
AC
9230 case PACKET_ERROR:
9231 return -1;
9232 case PACKET_OK:
7c0f6dcc
JL
9233 bp_tgt->placed_address = addr;
9234 bp_tgt->placed_size = bpsize;
d471ea57
AC
9235 return 0;
9236 case PACKET_UNKNOWN:
9237 break;
96baa820
JM
9238 }
9239 }
c906108c 9240
0000e5cc
PA
9241 /* If this breakpoint has target-side commands but this stub doesn't
9242 support Z0 packets, throw error. */
9243 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9244 throw_error (NOT_SUPPORTED_ERROR, _("\
9245Target doesn't support breakpoints that have target side commands."));
9246
3db08215 9247 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9248}
9249
9250static int
3db08215
MM
9251remote_remove_breakpoint (struct target_ops *ops,
9252 struct gdbarch *gdbarch,
a6d9a66e 9253 struct bp_target_info *bp_tgt)
c906108c 9254{
8181d85f 9255 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9256 struct remote_state *rs = get_remote_state ();
96baa820 9257
4082afcc 9258 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9259 {
6d820c5c 9260 char *p = rs->buf;
bba74b36 9261 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9262
28439a30
PA
9263 /* Make sure the remote is pointing at the right process, if
9264 necessary. */
9265 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9266 set_general_process ();
9267
96baa820
JM
9268 *(p++) = 'z';
9269 *(p++) = '0';
9270 *(p++) = ',';
9271
8181d85f
DJ
9272 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9273 p += hexnumstr (p, addr);
bba74b36 9274 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9275
6d820c5c
DJ
9276 putpkt (rs->buf);
9277 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9278
6d820c5c 9279 return (rs->buf[0] == 'E');
96baa820
JM
9280 }
9281
3db08215 9282 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9283}
9284
f486487f 9285static enum Z_packet_type
d471ea57
AC
9286watchpoint_to_Z_packet (int type)
9287{
9288 switch (type)
9289 {
9290 case hw_write:
bb858e6a 9291 return Z_PACKET_WRITE_WP;
d471ea57
AC
9292 break;
9293 case hw_read:
bb858e6a 9294 return Z_PACKET_READ_WP;
d471ea57
AC
9295 break;
9296 case hw_access:
bb858e6a 9297 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9298 break;
9299 default:
8e65ff28 9300 internal_error (__FILE__, __LINE__,
e2e0b3e5 9301 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9302 }
9303}
9304
3c3bea1c 9305static int
f486487f
SM
9306remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9307 enum target_hw_bp_type type, struct expression *cond)
96baa820 9308{
d01949b6 9309 struct remote_state *rs = get_remote_state ();
bba74b36 9310 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9311 char *p;
d471ea57 9312 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9313
4082afcc 9314 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9315 return 1;
802188a7 9316
28439a30
PA
9317 /* Make sure the remote is pointing at the right process, if
9318 necessary. */
9319 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9320 set_general_process ();
9321
bba74b36 9322 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9323 p = strchr (rs->buf, '\0');
96baa820
JM
9324 addr = remote_address_masked (addr);
9325 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9326 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9327
6d820c5c
DJ
9328 putpkt (rs->buf);
9329 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9330
6d820c5c 9331 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9332 {
9333 case PACKET_ERROR:
d471ea57 9334 return -1;
85d721b8
PA
9335 case PACKET_UNKNOWN:
9336 return 1;
d471ea57
AC
9337 case PACKET_OK:
9338 return 0;
9339 }
8e65ff28 9340 internal_error (__FILE__, __LINE__,
e2e0b3e5 9341 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9342}
9343
283002cf
MR
9344static int
9345remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9346 CORE_ADDR start, int length)
9347{
9348 CORE_ADDR diff = remote_address_masked (addr - start);
9349
9350 return diff < length;
9351}
9352
d471ea57 9353
3c3bea1c 9354static int
f486487f
SM
9355remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9356 enum target_hw_bp_type type, struct expression *cond)
96baa820 9357{
d01949b6 9358 struct remote_state *rs = get_remote_state ();
bba74b36 9359 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9360 char *p;
d471ea57
AC
9361 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9362
4082afcc 9363 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9364 return -1;
802188a7 9365
28439a30
PA
9366 /* Make sure the remote is pointing at the right process, if
9367 necessary. */
9368 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9369 set_general_process ();
9370
bba74b36 9371 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9372 p = strchr (rs->buf, '\0');
96baa820
JM
9373 addr = remote_address_masked (addr);
9374 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9375 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9376 putpkt (rs->buf);
9377 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9378
6d820c5c 9379 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9380 {
9381 case PACKET_ERROR:
9382 case PACKET_UNKNOWN:
9383 return -1;
9384 case PACKET_OK:
9385 return 0;
9386 }
8e65ff28 9387 internal_error (__FILE__, __LINE__,
e2e0b3e5 9388 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9389}
9390
3c3bea1c 9391
501eef12 9392int remote_hw_watchpoint_limit = -1;
480a3f21 9393int remote_hw_watchpoint_length_limit = -1;
501eef12 9394int remote_hw_breakpoint_limit = -1;
d471ea57 9395
480a3f21 9396static int
31568a15
TT
9397remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9398 CORE_ADDR addr, int len)
480a3f21
PW
9399{
9400 if (remote_hw_watchpoint_length_limit == 0)
9401 return 0;
9402 else if (remote_hw_watchpoint_length_limit < 0)
9403 return 1;
9404 else if (len <= remote_hw_watchpoint_length_limit)
9405 return 1;
9406 else
9407 return 0;
9408}
9409
b9362cc7 9410static int
5461485a 9411remote_check_watch_resources (struct target_ops *self,
f486487f 9412 enum bptype type, int cnt, int ot)
96baa820 9413{
3c3bea1c
GS
9414 if (type == bp_hardware_breakpoint)
9415 {
9416 if (remote_hw_breakpoint_limit == 0)
9417 return 0;
501eef12
AC
9418 else if (remote_hw_breakpoint_limit < 0)
9419 return 1;
3c3bea1c
GS
9420 else if (cnt <= remote_hw_breakpoint_limit)
9421 return 1;
9422 }
9423 else
9424 {
9425 if (remote_hw_watchpoint_limit == 0)
9426 return 0;
501eef12
AC
9427 else if (remote_hw_watchpoint_limit < 0)
9428 return 1;
3c3bea1c
GS
9429 else if (ot)
9430 return -1;
9431 else if (cnt <= remote_hw_watchpoint_limit)
9432 return 1;
9433 }
9434 return -1;
9435}
9436
f7e6eed5
PA
9437/* The to_stopped_by_sw_breakpoint method of target remote. */
9438
9439static int
9440remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9441{
799a2abe 9442 struct thread_info *thread = inferior_thread ();
f7e6eed5 9443
799a2abe
PA
9444 return (thread->priv != NULL
9445 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9446}
9447
9448/* The to_supports_stopped_by_sw_breakpoint method of target
9449 remote. */
9450
9451static int
9452remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9453{
9454 struct remote_state *rs = get_remote_state ();
9455
9456 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9457}
9458
9459/* The to_stopped_by_hw_breakpoint method of target remote. */
9460
9461static int
9462remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9463{
799a2abe 9464 struct thread_info *thread = inferior_thread ();
f7e6eed5 9465
799a2abe
PA
9466 return (thread->priv != NULL
9467 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9468}
9469
9470/* The to_supports_stopped_by_hw_breakpoint method of target
9471 remote. */
9472
9473static int
9474remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9475{
9476 struct remote_state *rs = get_remote_state ();
9477
9478 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9479}
9480
b9362cc7 9481static int
6a109b6b 9482remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9483{
799a2abe 9484 struct thread_info *thread = inferior_thread ();
ee154bee 9485
799a2abe
PA
9486 return (thread->priv != NULL
9487 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9488}
9489
4aa7a7f5
JJ
9490static int
9491remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9492{
799a2abe 9493 struct thread_info *thread = inferior_thread ();
a744cf53 9494
799a2abe
PA
9495 if (thread->priv != NULL
9496 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9497 {
799a2abe
PA
9498 *addr_p = thread->priv->watch_data_address;
9499 return 1;
4aa7a7f5
JJ
9500 }
9501
799a2abe 9502 return 0;
3c3bea1c
GS
9503}
9504
9505
9506static int
23a26771 9507remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9508 struct bp_target_info *bp_tgt)
3c3bea1c 9509{
0d5ed153 9510 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9511 struct remote_state *rs;
bba74b36 9512 char *p, *endbuf;
dd61ec5c 9513 char *message;
0d5ed153 9514 int bpsize;
802188a7 9515
c8189ed1 9516 /* The length field should be set to the size of a breakpoint
8181d85f 9517 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9518
0d5ed153 9519 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9520
4082afcc 9521 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9522 return -1;
2bc416ba 9523
28439a30
PA
9524 /* Make sure the remote is pointing at the right process, if
9525 necessary. */
9526 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9527 set_general_process ();
9528
4fff2411
JZ
9529 rs = get_remote_state ();
9530 p = rs->buf;
bba74b36 9531 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9532
96baa820
JM
9533 *(p++) = 'Z';
9534 *(p++) = '1';
9535 *(p++) = ',';
802188a7 9536
0d5ed153 9537 addr = remote_address_masked (addr);
96baa820 9538 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9539 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9540
efcc2da7 9541 if (remote_supports_cond_breakpoints (self))
bba74b36 9542 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9543
78eff0ec 9544 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9545 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9546
6d820c5c
DJ
9547 putpkt (rs->buf);
9548 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9549
6d820c5c 9550 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9551 {
9552 case PACKET_ERROR:
dd61ec5c
MW
9553 if (rs->buf[1] == '.')
9554 {
9555 message = strchr (rs->buf + 2, '.');
9556 if (message)
0316657e 9557 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9558 }
9559 return -1;
d471ea57
AC
9560 case PACKET_UNKNOWN:
9561 return -1;
9562 case PACKET_OK:
0d5ed153
MR
9563 bp_tgt->placed_address = addr;
9564 bp_tgt->placed_size = bpsize;
d471ea57
AC
9565 return 0;
9566 }
8e65ff28 9567 internal_error (__FILE__, __LINE__,
e2e0b3e5 9568 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9569}
9570
d471ea57 9571
802188a7 9572static int
a64dc96c 9573remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9574 struct bp_target_info *bp_tgt)
96baa820 9575{
8181d85f 9576 CORE_ADDR addr;
d01949b6 9577 struct remote_state *rs = get_remote_state ();
6d820c5c 9578 char *p = rs->buf;
bba74b36 9579 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9580
4082afcc 9581 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9582 return -1;
802188a7 9583
28439a30
PA
9584 /* Make sure the remote is pointing at the right process, if
9585 necessary. */
9586 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9587 set_general_process ();
9588
96baa820
JM
9589 *(p++) = 'z';
9590 *(p++) = '1';
9591 *(p++) = ',';
802188a7 9592
8181d85f 9593 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9594 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9595 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9596
6d820c5c
DJ
9597 putpkt (rs->buf);
9598 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9599
6d820c5c 9600 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9601 {
9602 case PACKET_ERROR:
9603 case PACKET_UNKNOWN:
9604 return -1;
9605 case PACKET_OK:
9606 return 0;
9607 }
8e65ff28 9608 internal_error (__FILE__, __LINE__,
e2e0b3e5 9609 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9610}
96baa820 9611
4a5e7a5b
PA
9612/* Verify memory using the "qCRC:" request. */
9613
9614static int
9615remote_verify_memory (struct target_ops *ops,
9616 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9617{
9618 struct remote_state *rs = get_remote_state ();
9619 unsigned long host_crc, target_crc;
9620 char *tmp;
9621
936d2992
PA
9622 /* It doesn't make sense to use qCRC if the remote target is
9623 connected but not running. */
9624 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9625 {
9626 enum packet_result result;
28439a30 9627
936d2992
PA
9628 /* Make sure the remote is pointing at the right process. */
9629 set_general_process ();
4a5e7a5b 9630
936d2992
PA
9631 /* FIXME: assumes lma can fit into long. */
9632 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9633 (long) lma, (long) size);
9634 putpkt (rs->buf);
4a5e7a5b 9635
936d2992
PA
9636 /* Be clever; compute the host_crc before waiting for target
9637 reply. */
9638 host_crc = xcrc32 (data, size, 0xffffffff);
9639
9640 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9641
936d2992
PA
9642 result = packet_ok (rs->buf,
9643 &remote_protocol_packets[PACKET_qCRC]);
9644 if (result == PACKET_ERROR)
9645 return -1;
9646 else if (result == PACKET_OK)
9647 {
9648 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9649 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9650
936d2992
PA
9651 return (host_crc == target_crc);
9652 }
9653 }
4a5e7a5b 9654
936d2992 9655 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9656}
9657
c906108c
SS
9658/* compare-sections command
9659
9660 With no arguments, compares each loadable section in the exec bfd
9661 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9662 Useful for verifying the image on the target against the exec file. */
e514a9d6 9663
c906108c 9664static void
fba45db2 9665compare_sections_command (char *args, int from_tty)
c906108c
SS
9666{
9667 asection *s;
c906108c 9668 struct cleanup *old_chain;
948f8e3d 9669 gdb_byte *sectdata;
ce359b09 9670 const char *sectname;
c906108c
SS
9671 bfd_size_type size;
9672 bfd_vma lma;
9673 int matched = 0;
9674 int mismatched = 0;
4a5e7a5b 9675 int res;
95cf3b38 9676 int read_only = 0;
c906108c
SS
9677
9678 if (!exec_bfd)
8a3fe4f8 9679 error (_("command cannot be used without an exec file"));
c906108c 9680
28439a30
PA
9681 /* Make sure the remote is pointing at the right process. */
9682 set_general_process ();
9683
95cf3b38
DT
9684 if (args != NULL && strcmp (args, "-r") == 0)
9685 {
9686 read_only = 1;
9687 args = NULL;
9688 }
9689
c5aa993b 9690 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9691 {
9692 if (!(s->flags & SEC_LOAD))
0df8b418 9693 continue; /* Skip non-loadable section. */
c906108c 9694
95cf3b38
DT
9695 if (read_only && (s->flags & SEC_READONLY) == 0)
9696 continue; /* Skip writeable sections */
9697
2c500098 9698 size = bfd_get_section_size (s);
c906108c 9699 if (size == 0)
0df8b418 9700 continue; /* Skip zero-length section. */
c906108c 9701
ce359b09 9702 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9703 if (args && strcmp (args, sectname) != 0)
0df8b418 9704 continue; /* Not the section selected by user. */
c906108c 9705
0df8b418 9706 matched = 1; /* Do this section. */
c906108c 9707 lma = s->lma;
c906108c 9708
224c3ddb 9709 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9710 old_chain = make_cleanup (xfree, sectdata);
c906108c 9711 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9712
4a5e7a5b
PA
9713 res = target_verify_memory (sectdata, lma, size);
9714
9715 if (res == -1)
5af949e3 9716 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9717 paddress (target_gdbarch (), lma),
9718 paddress (target_gdbarch (), lma + size));
c906108c 9719
5af949e3 9720 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9721 paddress (target_gdbarch (), lma),
9722 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9723 if (res)
c906108c
SS
9724 printf_filtered ("matched.\n");
9725 else
c5aa993b
JM
9726 {
9727 printf_filtered ("MIS-MATCHED!\n");
9728 mismatched++;
9729 }
c906108c
SS
9730
9731 do_cleanups (old_chain);
9732 }
9733 if (mismatched > 0)
936d2992 9734 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9735the loaded file\n"));
c906108c 9736 if (args && !matched)
a3f17187 9737 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9738}
9739
0e7f50da
UW
9740/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9741 into remote target. The number of bytes written to the remote
9742 target is returned, or -1 for error. */
9743
9b409511 9744static enum target_xfer_status
0e7f50da
UW
9745remote_write_qxfer (struct target_ops *ops, const char *object_name,
9746 const char *annex, const gdb_byte *writebuf,
9b409511 9747 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9748 struct packet_config *packet)
9749{
9750 int i, buf_len;
9751 ULONGEST n;
0e7f50da
UW
9752 struct remote_state *rs = get_remote_state ();
9753 int max_size = get_memory_write_packet_size ();
9754
9755 if (packet->support == PACKET_DISABLE)
2ed4b548 9756 return TARGET_XFER_E_IO;
0e7f50da
UW
9757
9758 /* Insert header. */
9759 i = snprintf (rs->buf, max_size,
9760 "qXfer:%s:write:%s:%s:",
9761 object_name, annex ? annex : "",
9762 phex_nz (offset, sizeof offset));
9763 max_size -= (i + 1);
9764
9765 /* Escape as much data as fits into rs->buf. */
9766 buf_len = remote_escape_output
124e13d9 9767 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9768
9769 if (putpkt_binary (rs->buf, i + buf_len) < 0
9770 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9771 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9772 return TARGET_XFER_E_IO;
0e7f50da
UW
9773
9774 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9775
9776 *xfered_len = n;
9777 return TARGET_XFER_OK;
0e7f50da
UW
9778}
9779
0876f84a
DJ
9780/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9781 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9782 number of bytes read is returned, or 0 for EOF, or -1 for error.
9783 The number of bytes read may be less than LEN without indicating an
9784 EOF. PACKET is checked and updated to indicate whether the remote
9785 target supports this object. */
9786
9b409511 9787static enum target_xfer_status
0876f84a
DJ
9788remote_read_qxfer (struct target_ops *ops, const char *object_name,
9789 const char *annex,
9790 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9791 ULONGEST *xfered_len,
0876f84a
DJ
9792 struct packet_config *packet)
9793{
0876f84a 9794 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9795 LONGEST i, n, packet_len;
9796
9797 if (packet->support == PACKET_DISABLE)
2ed4b548 9798 return TARGET_XFER_E_IO;
0876f84a
DJ
9799
9800 /* Check whether we've cached an end-of-object packet that matches
9801 this request. */
8e88304f 9802 if (rs->finished_object)
0876f84a 9803 {
8e88304f
TT
9804 if (strcmp (object_name, rs->finished_object) == 0
9805 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9806 && offset == rs->finished_offset)
9b409511
YQ
9807 return TARGET_XFER_EOF;
9808
0876f84a
DJ
9809
9810 /* Otherwise, we're now reading something different. Discard
9811 the cache. */
8e88304f
TT
9812 xfree (rs->finished_object);
9813 xfree (rs->finished_annex);
9814 rs->finished_object = NULL;
9815 rs->finished_annex = NULL;
0876f84a
DJ
9816 }
9817
9818 /* Request only enough to fit in a single packet. The actual data
9819 may not, since we don't know how much of it will need to be escaped;
9820 the target is free to respond with slightly less data. We subtract
9821 five to account for the response type and the protocol frame. */
9822 n = min (get_remote_packet_size () - 5, len);
9823 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9824 object_name, annex ? annex : "",
9825 phex_nz (offset, sizeof offset),
9826 phex_nz (n, sizeof n));
9827 i = putpkt (rs->buf);
9828 if (i < 0)
2ed4b548 9829 return TARGET_XFER_E_IO;
0876f84a
DJ
9830
9831 rs->buf[0] = '\0';
9832 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9833 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9834 return TARGET_XFER_E_IO;
0876f84a
DJ
9835
9836 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9837 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9838
9839 /* 'm' means there is (or at least might be) more data after this
9840 batch. That does not make sense unless there's at least one byte
9841 of data in this reply. */
9842 if (rs->buf[0] == 'm' && packet_len == 1)
9843 error (_("Remote qXfer reply contained no data."));
9844
9845 /* Got some data. */
bc20a4af
PA
9846 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9847 packet_len - 1, readbuf, n);
0876f84a
DJ
9848
9849 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9850 or possibly empty. If we have the final block of a non-empty
9851 object, record this fact to bypass a subsequent partial read. */
9852 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9853 {
8e88304f
TT
9854 rs->finished_object = xstrdup (object_name);
9855 rs->finished_annex = xstrdup (annex ? annex : "");
9856 rs->finished_offset = offset + i;
0876f84a
DJ
9857 }
9858
9b409511
YQ
9859 if (i == 0)
9860 return TARGET_XFER_EOF;
9861 else
9862 {
9863 *xfered_len = i;
9864 return TARGET_XFER_OK;
9865 }
0876f84a
DJ
9866}
9867
9b409511 9868static enum target_xfer_status
4b8a223f 9869remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9870 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9871 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9872 ULONGEST *xfered_len)
c906108c 9873{
82f73884 9874 struct remote_state *rs;
c906108c 9875 int i;
6d820c5c 9876 char *p2;
1e3ff5ad 9877 char query_type;
124e13d9 9878 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9879
e6e4e701 9880 set_remote_traceframe ();
82f73884
PA
9881 set_general_thread (inferior_ptid);
9882
9883 rs = get_remote_state ();
9884
b2182ed2 9885 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9886 if (object == TARGET_OBJECT_MEMORY)
9887 {
2d717e4f
DJ
9888 /* If the remote target is connected but not running, we should
9889 pass this request down to a lower stratum (e.g. the executable
9890 file). */
9891 if (!target_has_execution)
9b409511 9892 return TARGET_XFER_EOF;
2d717e4f 9893
21e3b9b9 9894 if (writebuf != NULL)
124e13d9
SM
9895 return remote_write_bytes (offset, writebuf, len, unit_size,
9896 xfered_len);
21e3b9b9 9897 else
124e13d9
SM
9898 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9899 xfered_len);
21e3b9b9
DJ
9900 }
9901
0df8b418 9902 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9903 if (object == TARGET_OBJECT_SPU)
9904 {
9905 if (readbuf)
9906 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9907 xfered_len, &remote_protocol_packets
9908 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9909 else
9910 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9911 xfered_len, &remote_protocol_packets
9912 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9913 }
9914
4aa995e1
PA
9915 /* Handle extra signal info using qxfer packets. */
9916 if (object == TARGET_OBJECT_SIGNAL_INFO)
9917 {
9918 if (readbuf)
9919 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 9920 xfered_len, &remote_protocol_packets
4aa995e1
PA
9921 [PACKET_qXfer_siginfo_read]);
9922 else
3e43a32a 9923 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 9924 writebuf, offset, len, xfered_len,
4aa995e1
PA
9925 &remote_protocol_packets
9926 [PACKET_qXfer_siginfo_write]);
9927 }
9928
0fb4aa4b
PA
9929 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9930 {
9931 if (readbuf)
3e43a32a 9932 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 9933 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
9934 &remote_protocol_packets
9935 [PACKET_qXfer_statictrace_read]);
9936 else
2ed4b548 9937 return TARGET_XFER_E_IO;
0fb4aa4b
PA
9938 }
9939
a76d924d
DJ
9940 /* Only handle flash writes. */
9941 if (writebuf != NULL)
9942 {
9943 LONGEST xfered;
9944
9945 switch (object)
9946 {
9947 case TARGET_OBJECT_FLASH:
9b409511
YQ
9948 return remote_flash_write (ops, offset, len, xfered_len,
9949 writebuf);
a76d924d
DJ
9950
9951 default:
2ed4b548 9952 return TARGET_XFER_E_IO;
a76d924d
DJ
9953 }
9954 }
4b8a223f 9955
1e3ff5ad
AC
9956 /* Map pre-existing objects onto letters. DO NOT do this for new
9957 objects!!! Instead specify new query packets. */
9958 switch (object)
c906108c 9959 {
1e3ff5ad
AC
9960 case TARGET_OBJECT_AVR:
9961 query_type = 'R';
9962 break;
802188a7
RM
9963
9964 case TARGET_OBJECT_AUXV:
0876f84a
DJ
9965 gdb_assert (annex == NULL);
9966 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9967 xfered_len,
0876f84a 9968 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9969
23181151
DJ
9970 case TARGET_OBJECT_AVAILABLE_FEATURES:
9971 return remote_read_qxfer
9b409511 9972 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9973 &remote_protocol_packets[PACKET_qXfer_features]);
9974
cfa9d6d9
DJ
9975 case TARGET_OBJECT_LIBRARIES:
9976 return remote_read_qxfer
9b409511 9977 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9978 &remote_protocol_packets[PACKET_qXfer_libraries]);
9979
2268b414
JK
9980 case TARGET_OBJECT_LIBRARIES_SVR4:
9981 return remote_read_qxfer
9b409511 9982 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9983 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9984
fd79ecee
DJ
9985 case TARGET_OBJECT_MEMORY_MAP:
9986 gdb_assert (annex == NULL);
9987 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9988 xfered_len,
fd79ecee
DJ
9989 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9990
07e059b5
VP
9991 case TARGET_OBJECT_OSDATA:
9992 /* Should only get here if we're connected. */
5d93a237 9993 gdb_assert (rs->remote_desc);
07e059b5 9994 return remote_read_qxfer
9b409511 9995 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9996 &remote_protocol_packets[PACKET_qXfer_osdata]);
9997
dc146f7c
VP
9998 case TARGET_OBJECT_THREADS:
9999 gdb_assert (annex == NULL);
10000 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10001 xfered_len,
dc146f7c
VP
10002 &remote_protocol_packets[PACKET_qXfer_threads]);
10003
b3b9301e
PA
10004 case TARGET_OBJECT_TRACEFRAME_INFO:
10005 gdb_assert (annex == NULL);
10006 return remote_read_qxfer
9b409511 10007 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10008 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10009
10010 case TARGET_OBJECT_FDPIC:
10011 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10012 xfered_len,
78d85199 10013 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10014
10015 case TARGET_OBJECT_OPENVMS_UIB:
10016 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10017 xfered_len,
169081d0
TG
10018 &remote_protocol_packets[PACKET_qXfer_uib]);
10019
9accd112
MM
10020 case TARGET_OBJECT_BTRACE:
10021 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10022 xfered_len,
9accd112
MM
10023 &remote_protocol_packets[PACKET_qXfer_btrace]);
10024
f4abbc16
MM
10025 case TARGET_OBJECT_BTRACE_CONF:
10026 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10027 len, xfered_len,
10028 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10029
c78fa86a
GB
10030 case TARGET_OBJECT_EXEC_FILE:
10031 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10032 len, xfered_len,
10033 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10034
1e3ff5ad 10035 default:
2ed4b548 10036 return TARGET_XFER_E_IO;
c906108c
SS
10037 }
10038
0df8b418 10039 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10040 large enough let the caller deal with it. */
ea9c271d 10041 if (len < get_remote_packet_size ())
2ed4b548 10042 return TARGET_XFER_E_IO;
ea9c271d 10043 len = get_remote_packet_size ();
1e3ff5ad 10044
23860348 10045 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10046 if (!rs->remote_desc)
8a3fe4f8 10047 error (_("remote query is only available after target open"));
c906108c 10048
1e3ff5ad 10049 gdb_assert (annex != NULL);
4b8a223f 10050 gdb_assert (readbuf != NULL);
c906108c 10051
6d820c5c 10052 p2 = rs->buf;
c906108c
SS
10053 *p2++ = 'q';
10054 *p2++ = query_type;
10055
23860348
MS
10056 /* We used one buffer char for the remote protocol q command and
10057 another for the query type. As the remote protocol encapsulation
10058 uses 4 chars plus one extra in case we are debugging
10059 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10060 string. */
c906108c 10061 i = 0;
ea9c271d 10062 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10063 {
1e3ff5ad
AC
10064 /* Bad caller may have sent forbidden characters. */
10065 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10066 *p2++ = annex[i];
c906108c
SS
10067 i++;
10068 }
1e3ff5ad
AC
10069 *p2 = '\0';
10070 gdb_assert (annex[i] == '\0');
c906108c 10071
6d820c5c 10072 i = putpkt (rs->buf);
c5aa993b 10073 if (i < 0)
2ed4b548 10074 return TARGET_XFER_E_IO;
c906108c 10075
6d820c5c
DJ
10076 getpkt (&rs->buf, &rs->buf_size, 0);
10077 strcpy ((char *) readbuf, rs->buf);
c906108c 10078
9b409511
YQ
10079 *xfered_len = strlen ((char *) readbuf);
10080 return TARGET_XFER_OK;
c906108c
SS
10081}
10082
08388c79
DE
10083static int
10084remote_search_memory (struct target_ops* ops,
10085 CORE_ADDR start_addr, ULONGEST search_space_len,
10086 const gdb_byte *pattern, ULONGEST pattern_len,
10087 CORE_ADDR *found_addrp)
10088{
f5656ead 10089 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10090 struct remote_state *rs = get_remote_state ();
10091 int max_size = get_memory_write_packet_size ();
10092 struct packet_config *packet =
10093 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10094 /* Number of packet bytes used to encode the pattern;
10095 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10096 int escaped_pattern_len;
0df8b418 10097 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10098 int used_pattern_len;
10099 int i;
10100 int found;
10101 ULONGEST found_addr;
10102
10103 /* Don't go to the target if we don't have to.
10104 This is done before checking packet->support to avoid the possibility that
10105 a success for this edge case means the facility works in general. */
10106 if (pattern_len > search_space_len)
10107 return 0;
10108 if (pattern_len == 0)
10109 {
10110 *found_addrp = start_addr;
10111 return 1;
10112 }
10113
10114 /* If we already know the packet isn't supported, fall back to the simple
10115 way of searching memory. */
10116
4082afcc 10117 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10118 {
10119 /* Target doesn't provided special support, fall back and use the
10120 standard support (copy memory and do the search here). */
10121 return simple_search_memory (ops, start_addr, search_space_len,
10122 pattern, pattern_len, found_addrp);
10123 }
10124
28439a30
PA
10125 /* Make sure the remote is pointing at the right process. */
10126 set_general_process ();
10127
08388c79
DE
10128 /* Insert header. */
10129 i = snprintf (rs->buf, max_size,
10130 "qSearch:memory:%s;%s;",
5af949e3 10131 phex_nz (start_addr, addr_size),
08388c79
DE
10132 phex_nz (search_space_len, sizeof (search_space_len)));
10133 max_size -= (i + 1);
10134
10135 /* Escape as much data as fits into rs->buf. */
10136 escaped_pattern_len =
124e13d9 10137 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10138 &used_pattern_len, max_size);
10139
10140 /* Bail if the pattern is too large. */
10141 if (used_pattern_len != pattern_len)
9b20d036 10142 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10143
10144 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10145 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10146 || packet_ok (rs->buf, packet) != PACKET_OK)
10147 {
10148 /* The request may not have worked because the command is not
10149 supported. If so, fall back to the simple way. */
10150 if (packet->support == PACKET_DISABLE)
10151 {
10152 return simple_search_memory (ops, start_addr, search_space_len,
10153 pattern, pattern_len, found_addrp);
10154 }
10155 return -1;
10156 }
10157
10158 if (rs->buf[0] == '0')
10159 found = 0;
10160 else if (rs->buf[0] == '1')
10161 {
10162 found = 1;
10163 if (rs->buf[1] != ',')
10e0fa18 10164 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10165 unpack_varlen_hex (rs->buf + 2, &found_addr);
10166 *found_addrp = found_addr;
10167 }
10168 else
10e0fa18 10169 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10170
10171 return found;
10172}
10173
96baa820 10174static void
a30bf1f1 10175remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10176 struct ui_file *outbuf)
96baa820 10177{
d01949b6 10178 struct remote_state *rs = get_remote_state ();
2e9f7625 10179 char *p = rs->buf;
96baa820 10180
5d93a237 10181 if (!rs->remote_desc)
8a3fe4f8 10182 error (_("remote rcmd is only available after target open"));
96baa820 10183
23860348 10184 /* Send a NULL command across as an empty command. */
7be570e7
JM
10185 if (command == NULL)
10186 command = "";
10187
23860348 10188 /* The query prefix. */
2e9f7625
DJ
10189 strcpy (rs->buf, "qRcmd,");
10190 p = strchr (rs->buf, '\0');
96baa820 10191
3e43a32a
MS
10192 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10193 > get_remote_packet_size ())
8a3fe4f8 10194 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10195
23860348 10196 /* Encode the actual command. */
a30bf1f1 10197 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10198
6d820c5c 10199 if (putpkt (rs->buf) < 0)
8a3fe4f8 10200 error (_("Communication problem with target."));
96baa820
JM
10201
10202 /* get/display the response */
10203 while (1)
10204 {
2e9f7625
DJ
10205 char *buf;
10206
00bf0b85 10207 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10208 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10209 rs->buf[0] = '\0';
5b37825d
PW
10210 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10211 {
10212 /* Timeout. Continue to (try to) read responses.
10213 This is better than stopping with an error, assuming the stub
10214 is still executing the (long) monitor command.
10215 If needed, the user can interrupt gdb using C-c, obtaining
10216 an effect similar to stop on timeout. */
10217 continue;
10218 }
2e9f7625 10219 buf = rs->buf;
96baa820 10220 if (buf[0] == '\0')
8a3fe4f8 10221 error (_("Target does not support this command."));
96baa820
JM
10222 if (buf[0] == 'O' && buf[1] != 'K')
10223 {
23860348 10224 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10225 continue;
10226 }
10227 if (strcmp (buf, "OK") == 0)
10228 break;
7be570e7
JM
10229 if (strlen (buf) == 3 && buf[0] == 'E'
10230 && isdigit (buf[1]) && isdigit (buf[2]))
10231 {
8a3fe4f8 10232 error (_("Protocol error with Rcmd"));
7be570e7 10233 }
96baa820
JM
10234 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10235 {
10236 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10237
96baa820
JM
10238 fputc_unfiltered (c, outbuf);
10239 }
10240 break;
10241 }
10242}
10243
fd79ecee
DJ
10244static VEC(mem_region_s) *
10245remote_memory_map (struct target_ops *ops)
10246{
10247 VEC(mem_region_s) *result = NULL;
10248 char *text = target_read_stralloc (&current_target,
10249 TARGET_OBJECT_MEMORY_MAP, NULL);
10250
10251 if (text)
10252 {
10253 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10254
fd79ecee
DJ
10255 result = parse_memory_map (text);
10256 do_cleanups (back_to);
10257 }
10258
10259 return result;
10260}
10261
c906108c 10262static void
fba45db2 10263packet_command (char *args, int from_tty)
c906108c 10264{
d01949b6 10265 struct remote_state *rs = get_remote_state ();
c906108c 10266
5d93a237 10267 if (!rs->remote_desc)
8a3fe4f8 10268 error (_("command can only be used with remote target"));
c906108c 10269
c5aa993b 10270 if (!args)
8a3fe4f8 10271 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10272
10273 puts_filtered ("sending: ");
10274 print_packet (args);
10275 puts_filtered ("\n");
10276 putpkt (args);
10277
6d820c5c 10278 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10279 puts_filtered ("received: ");
6d820c5c 10280 print_packet (rs->buf);
c906108c
SS
10281 puts_filtered ("\n");
10282}
10283
10284#if 0
23860348 10285/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10286
a14ed312 10287static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10288
a14ed312 10289static void threadset_test_cmd (char *cmd, int tty);
c906108c 10290
a14ed312 10291static void threadalive_test (char *cmd, int tty);
c906108c 10292
a14ed312 10293static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10294
23860348 10295int get_and_display_threadinfo (threadref *ref);
c906108c 10296
a14ed312 10297static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10298
23860348 10299static int thread_display_step (threadref *ref, void *context);
c906108c 10300
a14ed312 10301static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10302
a14ed312 10303static void init_remote_threadtests (void);
c906108c 10304
23860348 10305#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10306
10307static void
fba45db2 10308threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10309{
10310 int sample_thread = SAMPLE_THREAD;
10311
a3f17187 10312 printf_filtered (_("Remote threadset test\n"));
79d7f229 10313 set_general_thread (sample_thread);
c906108c
SS
10314}
10315
10316
10317static void
fba45db2 10318threadalive_test (char *cmd, int tty)
c906108c
SS
10319{
10320 int sample_thread = SAMPLE_THREAD;
79d7f229 10321 int pid = ptid_get_pid (inferior_ptid);
ba348170 10322 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10323
79d7f229 10324 if (remote_thread_alive (ptid))
c906108c
SS
10325 printf_filtered ("PASS: Thread alive test\n");
10326 else
10327 printf_filtered ("FAIL: Thread alive test\n");
10328}
10329
23860348 10330void output_threadid (char *title, threadref *ref);
c906108c
SS
10331
10332void
fba45db2 10333output_threadid (char *title, threadref *ref)
c906108c
SS
10334{
10335 char hexid[20];
10336
23860348 10337 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10338 hexid[16] = 0;
10339 printf_filtered ("%s %s\n", title, (&hexid[0]));
10340}
10341
10342static void
fba45db2 10343threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10344{
10345 int startflag = 1;
10346 threadref nextthread;
10347 int done, result_count;
10348 threadref threadlist[3];
10349
10350 printf_filtered ("Remote Threadlist test\n");
10351 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10352 &result_count, &threadlist[0]))
10353 printf_filtered ("FAIL: threadlist test\n");
10354 else
10355 {
10356 threadref *scan = threadlist;
10357 threadref *limit = scan + result_count;
10358
10359 while (scan < limit)
10360 output_threadid (" thread ", scan++);
10361 }
10362}
10363
10364void
fba45db2 10365display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10366{
10367 output_threadid ("Threadid: ", &info->threadid);
10368 printf_filtered ("Name: %s\n ", info->shortname);
10369 printf_filtered ("State: %s\n", info->display);
10370 printf_filtered ("other: %s\n\n", info->more_display);
10371}
10372
10373int
fba45db2 10374get_and_display_threadinfo (threadref *ref)
c906108c
SS
10375{
10376 int result;
10377 int set;
10378 struct gdb_ext_thread_info threadinfo;
10379
10380 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10381 | TAG_MOREDISPLAY | TAG_DISPLAY;
10382 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10383 display_thread_info (&threadinfo);
10384 return result;
10385}
10386
10387static void
fba45db2 10388threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10389{
10390 int athread = SAMPLE_THREAD;
10391 threadref thread;
10392 int set;
10393
10394 int_to_threadref (&thread, athread);
10395 printf_filtered ("Remote Threadinfo test\n");
10396 if (!get_and_display_threadinfo (&thread))
10397 printf_filtered ("FAIL cannot get thread info\n");
10398}
10399
10400static int
fba45db2 10401thread_display_step (threadref *ref, void *context)
c906108c
SS
10402{
10403 /* output_threadid(" threadstep ",ref); *//* simple test */
10404 return get_and_display_threadinfo (ref);
10405}
10406
10407static void
fba45db2 10408threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10409{
10410 printf_filtered ("Remote Threadlist update test\n");
10411 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10412}
10413
10414static void
10415init_remote_threadtests (void)
10416{
3e43a32a
MS
10417 add_com ("tlist", class_obscure, threadlist_test_cmd,
10418 _("Fetch and print the remote list of "
10419 "thread identifiers, one pkt only"));
c906108c 10420 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10421 _("Fetch and display info about one thread"));
c906108c 10422 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10423 _("Test setting to a different thread"));
c906108c 10424 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10425 _("Iterate through updating all remote thread info"));
c906108c 10426 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10427 _(" Remote thread alive test "));
c906108c
SS
10428}
10429
10430#endif /* 0 */
10431
f3fb8c85
MS
10432/* Convert a thread ID to a string. Returns the string in a static
10433 buffer. */
10434
10435static char *
117de6a9 10436remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10437{
79d7f229 10438 static char buf[64];
82f73884 10439 struct remote_state *rs = get_remote_state ();
f3fb8c85 10440
7cee1e54
PA
10441 if (ptid_equal (ptid, null_ptid))
10442 return normal_pid_to_str (ptid);
10443 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10444 {
10445 /* Printing an inferior target id. */
10446
10447 /* When multi-process extensions are off, there's no way in the
10448 remote protocol to know the remote process id, if there's any
10449 at all. There's one exception --- when we're connected with
10450 target extended-remote, and we manually attached to a process
10451 with "attach PID". We don't record anywhere a flag that
10452 allows us to distinguish that case from the case of
10453 connecting with extended-remote and the stub already being
10454 attached to a process, and reporting yes to qAttached, hence
10455 no smart special casing here. */
10456 if (!remote_multi_process_p (rs))
10457 {
10458 xsnprintf (buf, sizeof buf, "Remote target");
10459 return buf;
10460 }
10461
10462 return normal_pid_to_str (ptid);
82f73884 10463 }
ecd0ada5 10464 else
79d7f229 10465 {
ecd0ada5
PA
10466 if (ptid_equal (magic_null_ptid, ptid))
10467 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 10468 else if (rs->extended && remote_multi_process_p (rs))
de0d863e
DB
10469 if (ptid_get_lwp (ptid) == 0)
10470 return normal_pid_to_str (ptid);
10471 else
10472 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10473 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10474 else
10475 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10476 ptid_get_lwp (ptid));
79d7f229
PA
10477 return buf;
10478 }
f3fb8c85
MS
10479}
10480
38691318
KB
10481/* Get the address of the thread local variable in OBJFILE which is
10482 stored at OFFSET within the thread local storage for thread PTID. */
10483
10484static CORE_ADDR
117de6a9
PA
10485remote_get_thread_local_address (struct target_ops *ops,
10486 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10487{
4082afcc 10488 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10489 {
10490 struct remote_state *rs = get_remote_state ();
6d820c5c 10491 char *p = rs->buf;
82f73884 10492 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10493 enum packet_result result;
38691318
KB
10494
10495 strcpy (p, "qGetTLSAddr:");
10496 p += strlen (p);
82f73884 10497 p = write_ptid (p, endp, ptid);
38691318
KB
10498 *p++ = ',';
10499 p += hexnumstr (p, offset);
10500 *p++ = ',';
10501 p += hexnumstr (p, lm);
10502 *p++ = '\0';
10503
6d820c5c
DJ
10504 putpkt (rs->buf);
10505 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10506 result = packet_ok (rs->buf,
10507 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10508 if (result == PACKET_OK)
38691318
KB
10509 {
10510 ULONGEST result;
10511
6d820c5c 10512 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10513 return result;
10514 }
571dd617 10515 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10516 throw_error (TLS_GENERIC_ERROR,
10517 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10518 else
109c3e39
AC
10519 throw_error (TLS_GENERIC_ERROR,
10520 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10521 }
10522 else
109c3e39
AC
10523 throw_error (TLS_GENERIC_ERROR,
10524 _("TLS not supported or disabled on this target"));
38691318
KB
10525 /* Not reached. */
10526 return 0;
10527}
10528
711e434b
PM
10529/* Provide thread local base, i.e. Thread Information Block address.
10530 Returns 1 if ptid is found and thread_local_base is non zero. */
10531
70221824 10532static int
bd7ae0f5 10533remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10534{
4082afcc 10535 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10536 {
10537 struct remote_state *rs = get_remote_state ();
10538 char *p = rs->buf;
10539 char *endp = rs->buf + get_remote_packet_size ();
10540 enum packet_result result;
10541
10542 strcpy (p, "qGetTIBAddr:");
10543 p += strlen (p);
10544 p = write_ptid (p, endp, ptid);
10545 *p++ = '\0';
10546
10547 putpkt (rs->buf);
10548 getpkt (&rs->buf, &rs->buf_size, 0);
10549 result = packet_ok (rs->buf,
10550 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10551 if (result == PACKET_OK)
10552 {
10553 ULONGEST result;
10554
10555 unpack_varlen_hex (rs->buf, &result);
10556 if (addr)
10557 *addr = (CORE_ADDR) result;
10558 return 1;
10559 }
10560 else if (result == PACKET_UNKNOWN)
10561 error (_("Remote target doesn't support qGetTIBAddr packet"));
10562 else
10563 error (_("Remote target failed to process qGetTIBAddr request"));
10564 }
10565 else
10566 error (_("qGetTIBAddr not supported or disabled on this target"));
10567 /* Not reached. */
10568 return 0;
10569}
10570
29709017
DJ
10571/* Support for inferring a target description based on the current
10572 architecture and the size of a 'g' packet. While the 'g' packet
10573 can have any size (since optional registers can be left off the
10574 end), some sizes are easily recognizable given knowledge of the
10575 approximate architecture. */
10576
10577struct remote_g_packet_guess
10578{
10579 int bytes;
10580 const struct target_desc *tdesc;
10581};
10582typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10583DEF_VEC_O(remote_g_packet_guess_s);
10584
10585struct remote_g_packet_data
10586{
10587 VEC(remote_g_packet_guess_s) *guesses;
10588};
10589
10590static struct gdbarch_data *remote_g_packet_data_handle;
10591
10592static void *
10593remote_g_packet_data_init (struct obstack *obstack)
10594{
10595 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10596}
10597
10598void
10599register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10600 const struct target_desc *tdesc)
10601{
10602 struct remote_g_packet_data *data
19ba03f4
SM
10603 = ((struct remote_g_packet_data *)
10604 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10605 struct remote_g_packet_guess new_guess, *guess;
10606 int ix;
10607
10608 gdb_assert (tdesc != NULL);
10609
10610 for (ix = 0;
10611 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10612 ix++)
10613 if (guess->bytes == bytes)
10614 internal_error (__FILE__, __LINE__,
9b20d036 10615 _("Duplicate g packet description added for size %d"),
29709017
DJ
10616 bytes);
10617
10618 new_guess.bytes = bytes;
10619 new_guess.tdesc = tdesc;
10620 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10621}
10622
d962ef82
DJ
10623/* Return 1 if remote_read_description would do anything on this target
10624 and architecture, 0 otherwise. */
10625
10626static int
10627remote_read_description_p (struct target_ops *target)
10628{
10629 struct remote_g_packet_data *data
19ba03f4
SM
10630 = ((struct remote_g_packet_data *)
10631 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10632
10633 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10634 return 1;
10635
10636 return 0;
10637}
10638
29709017
DJ
10639static const struct target_desc *
10640remote_read_description (struct target_ops *target)
10641{
10642 struct remote_g_packet_data *data
19ba03f4
SM
10643 = ((struct remote_g_packet_data *)
10644 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10645
d962ef82
DJ
10646 /* Do not try this during initial connection, when we do not know
10647 whether there is a running but stopped thread. */
10648 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10649 return target->beneath->to_read_description (target->beneath);
d962ef82 10650
29709017
DJ
10651 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10652 {
10653 struct remote_g_packet_guess *guess;
10654 int ix;
10655 int bytes = send_g_packet ();
10656
10657 for (ix = 0;
10658 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10659 ix++)
10660 if (guess->bytes == bytes)
10661 return guess->tdesc;
10662
10663 /* We discard the g packet. A minor optimization would be to
10664 hold on to it, and fill the register cache once we have selected
10665 an architecture, but it's too tricky to do safely. */
10666 }
10667
2117c711 10668 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10669}
10670
a6b151f1
DJ
10671/* Remote file transfer support. This is host-initiated I/O, not
10672 target-initiated; for target-initiated, see remote-fileio.c. */
10673
10674/* If *LEFT is at least the length of STRING, copy STRING to
10675 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10676 decrease *LEFT. Otherwise raise an error. */
10677
10678static void
10679remote_buffer_add_string (char **buffer, int *left, char *string)
10680{
10681 int len = strlen (string);
10682
10683 if (len > *left)
10684 error (_("Packet too long for target."));
10685
10686 memcpy (*buffer, string, len);
10687 *buffer += len;
10688 *left -= len;
10689
10690 /* NUL-terminate the buffer as a convenience, if there is
10691 room. */
10692 if (*left)
10693 **buffer = '\0';
10694}
10695
10696/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10697 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10698 decrease *LEFT. Otherwise raise an error. */
10699
10700static void
10701remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10702 int len)
10703{
10704 if (2 * len > *left)
10705 error (_("Packet too long for target."));
10706
10707 bin2hex (bytes, *buffer, len);
10708 *buffer += 2 * len;
10709 *left -= 2 * len;
10710
10711 /* NUL-terminate the buffer as a convenience, if there is
10712 room. */
10713 if (*left)
10714 **buffer = '\0';
10715}
10716
10717/* If *LEFT is large enough, convert VALUE to hex and add it to
10718 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10719 decrease *LEFT. Otherwise raise an error. */
10720
10721static void
10722remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10723{
10724 int len = hexnumlen (value);
10725
10726 if (len > *left)
10727 error (_("Packet too long for target."));
10728
10729 hexnumstr (*buffer, value);
10730 *buffer += len;
10731 *left -= len;
10732
10733 /* NUL-terminate the buffer as a convenience, if there is
10734 room. */
10735 if (*left)
10736 **buffer = '\0';
10737}
10738
10739/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10740 value, *REMOTE_ERRNO to the remote error number or zero if none
10741 was included, and *ATTACHMENT to point to the start of the annex
10742 if any. The length of the packet isn't needed here; there may
10743 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10744
10745 Return 0 if the packet could be parsed, -1 if it could not. If
10746 -1 is returned, the other variables may not be initialized. */
10747
10748static int
10749remote_hostio_parse_result (char *buffer, int *retcode,
10750 int *remote_errno, char **attachment)
10751{
10752 char *p, *p2;
10753
10754 *remote_errno = 0;
10755 *attachment = NULL;
10756
10757 if (buffer[0] != 'F')
10758 return -1;
10759
10760 errno = 0;
10761 *retcode = strtol (&buffer[1], &p, 16);
10762 if (errno != 0 || p == &buffer[1])
10763 return -1;
10764
10765 /* Check for ",errno". */
10766 if (*p == ',')
10767 {
10768 errno = 0;
10769 *remote_errno = strtol (p + 1, &p2, 16);
10770 if (errno != 0 || p + 1 == p2)
10771 return -1;
10772 p = p2;
10773 }
10774
10775 /* Check for ";attachment". If there is no attachment, the
10776 packet should end here. */
10777 if (*p == ';')
10778 {
10779 *attachment = p + 1;
10780 return 0;
10781 }
10782 else if (*p == '\0')
10783 return 0;
10784 else
10785 return -1;
10786}
10787
10788/* Send a prepared I/O packet to the target and read its response.
10789 The prepared packet is in the global RS->BUF before this function
10790 is called, and the answer is there when we return.
10791
10792 COMMAND_BYTES is the length of the request to send, which may include
10793 binary data. WHICH_PACKET is the packet configuration to check
10794 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10795 is set to the error number and -1 is returned. Otherwise the value
10796 returned by the function is returned.
10797
10798 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10799 attachment is expected; an error will be reported if there's a
10800 mismatch. If one is found, *ATTACHMENT will be set to point into
10801 the packet buffer and *ATTACHMENT_LEN will be set to the
10802 attachment's length. */
10803
10804static int
10805remote_hostio_send_command (int command_bytes, int which_packet,
10806 int *remote_errno, char **attachment,
10807 int *attachment_len)
10808{
10809 struct remote_state *rs = get_remote_state ();
10810 int ret, bytes_read;
10811 char *attachment_tmp;
10812
5d93a237 10813 if (!rs->remote_desc
4082afcc 10814 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10815 {
10816 *remote_errno = FILEIO_ENOSYS;
10817 return -1;
10818 }
10819
10820 putpkt_binary (rs->buf, command_bytes);
10821 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10822
10823 /* If it timed out, something is wrong. Don't try to parse the
10824 buffer. */
10825 if (bytes_read < 0)
10826 {
10827 *remote_errno = FILEIO_EINVAL;
10828 return -1;
10829 }
10830
10831 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10832 {
10833 case PACKET_ERROR:
10834 *remote_errno = FILEIO_EINVAL;
10835 return -1;
10836 case PACKET_UNKNOWN:
10837 *remote_errno = FILEIO_ENOSYS;
10838 return -1;
10839 case PACKET_OK:
10840 break;
10841 }
10842
10843 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10844 &attachment_tmp))
10845 {
10846 *remote_errno = FILEIO_EINVAL;
10847 return -1;
10848 }
10849
10850 /* Make sure we saw an attachment if and only if we expected one. */
10851 if ((attachment_tmp == NULL && attachment != NULL)
10852 || (attachment_tmp != NULL && attachment == NULL))
10853 {
10854 *remote_errno = FILEIO_EINVAL;
10855 return -1;
10856 }
10857
10858 /* If an attachment was found, it must point into the packet buffer;
10859 work out how many bytes there were. */
10860 if (attachment_tmp != NULL)
10861 {
10862 *attachment = attachment_tmp;
10863 *attachment_len = bytes_read - (*attachment - rs->buf);
10864 }
10865
10866 return ret;
10867}
10868
80152258
PA
10869/* Invalidate the readahead cache. */
10870
10871static void
10872readahead_cache_invalidate (void)
10873{
10874 struct remote_state *rs = get_remote_state ();
10875
10876 rs->readahead_cache.fd = -1;
10877}
10878
10879/* Invalidate the readahead cache if it is holding data for FD. */
10880
10881static void
10882readahead_cache_invalidate_fd (int fd)
10883{
10884 struct remote_state *rs = get_remote_state ();
10885
10886 if (rs->readahead_cache.fd == fd)
10887 rs->readahead_cache.fd = -1;
10888}
10889
15a201c8
GB
10890/* Set the filesystem remote_hostio functions that take FILENAME
10891 arguments will use. Return 0 on success, or -1 if an error
10892 occurs (and set *REMOTE_ERRNO). */
10893
10894static int
10895remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10896{
10897 struct remote_state *rs = get_remote_state ();
10898 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10899 char *p = rs->buf;
10900 int left = get_remote_packet_size () - 1;
10901 char arg[9];
10902 int ret;
10903
10904 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10905 return 0;
10906
10907 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10908 return 0;
10909
10910 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10911
10912 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10913 remote_buffer_add_string (&p, &left, arg);
10914
10915 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10916 remote_errno, NULL, NULL);
10917
10918 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10919 return 0;
10920
10921 if (ret == 0)
10922 rs->fs_pid = required_pid;
10923
10924 return ret;
10925}
10926
12e2a5fd 10927/* Implementation of to_fileio_open. */
a6b151f1
DJ
10928
10929static int
cd897586 10930remote_hostio_open (struct target_ops *self,
07c138c8 10931 struct inferior *inf, const char *filename,
4313b8c0
GB
10932 int flags, int mode, int warn_if_slow,
10933 int *remote_errno)
a6b151f1
DJ
10934{
10935 struct remote_state *rs = get_remote_state ();
10936 char *p = rs->buf;
10937 int left = get_remote_packet_size () - 1;
10938
4313b8c0
GB
10939 if (warn_if_slow)
10940 {
10941 static int warning_issued = 0;
10942
10943 printf_unfiltered (_("Reading %s from remote target...\n"),
10944 filename);
10945
10946 if (!warning_issued)
10947 {
10948 warning (_("File transfers from remote targets can be slow."
10949 " Use \"set sysroot\" to access files locally"
10950 " instead."));
10951 warning_issued = 1;
10952 }
10953 }
10954
15a201c8
GB
10955 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10956 return -1;
10957
a6b151f1
DJ
10958 remote_buffer_add_string (&p, &left, "vFile:open:");
10959
10960 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10961 strlen (filename));
10962 remote_buffer_add_string (&p, &left, ",");
10963
10964 remote_buffer_add_int (&p, &left, flags);
10965 remote_buffer_add_string (&p, &left, ",");
10966
10967 remote_buffer_add_int (&p, &left, mode);
10968
10969 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10970 remote_errno, NULL, NULL);
10971}
10972
12e2a5fd 10973/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
10974
10975static int
0d866f62
TT
10976remote_hostio_pwrite (struct target_ops *self,
10977 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
10978 ULONGEST offset, int *remote_errno)
10979{
10980 struct remote_state *rs = get_remote_state ();
10981 char *p = rs->buf;
10982 int left = get_remote_packet_size ();
10983 int out_len;
10984
80152258
PA
10985 readahead_cache_invalidate_fd (fd);
10986
a6b151f1
DJ
10987 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10988
10989 remote_buffer_add_int (&p, &left, fd);
10990 remote_buffer_add_string (&p, &left, ",");
10991
10992 remote_buffer_add_int (&p, &left, offset);
10993 remote_buffer_add_string (&p, &left, ",");
10994
124e13d9 10995 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
10996 get_remote_packet_size () - (p - rs->buf));
10997
10998 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10999 remote_errno, NULL, NULL);
11000}
11001
80152258
PA
11002/* Helper for the implementation of to_fileio_pread. Read the file
11003 from the remote side with vFile:pread. */
a6b151f1
DJ
11004
11005static int
80152258
PA
11006remote_hostio_pread_vFile (struct target_ops *self,
11007 int fd, gdb_byte *read_buf, int len,
11008 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11009{
11010 struct remote_state *rs = get_remote_state ();
11011 char *p = rs->buf;
11012 char *attachment;
11013 int left = get_remote_packet_size ();
11014 int ret, attachment_len;
11015 int read_len;
11016
11017 remote_buffer_add_string (&p, &left, "vFile:pread:");
11018
11019 remote_buffer_add_int (&p, &left, fd);
11020 remote_buffer_add_string (&p, &left, ",");
11021
11022 remote_buffer_add_int (&p, &left, len);
11023 remote_buffer_add_string (&p, &left, ",");
11024
11025 remote_buffer_add_int (&p, &left, offset);
11026
11027 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11028 remote_errno, &attachment,
11029 &attachment_len);
11030
11031 if (ret < 0)
11032 return ret;
11033
bc20a4af 11034 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11035 read_buf, len);
11036 if (read_len != ret)
11037 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11038
11039 return ret;
11040}
11041
80152258
PA
11042/* Serve pread from the readahead cache. Returns number of bytes
11043 read, or 0 if the request can't be served from the cache. */
11044
11045static int
11046remote_hostio_pread_from_cache (struct remote_state *rs,
11047 int fd, gdb_byte *read_buf, size_t len,
11048 ULONGEST offset)
11049{
11050 struct readahead_cache *cache = &rs->readahead_cache;
11051
11052 if (cache->fd == fd
11053 && cache->offset <= offset
11054 && offset < cache->offset + cache->bufsize)
11055 {
11056 ULONGEST max = cache->offset + cache->bufsize;
11057
11058 if (offset + len > max)
11059 len = max - offset;
11060
11061 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11062 return len;
11063 }
11064
11065 return 0;
11066}
11067
11068/* Implementation of to_fileio_pread. */
11069
11070static int
11071remote_hostio_pread (struct target_ops *self,
11072 int fd, gdb_byte *read_buf, int len,
11073 ULONGEST offset, int *remote_errno)
11074{
11075 int ret;
11076 struct remote_state *rs = get_remote_state ();
11077 struct readahead_cache *cache = &rs->readahead_cache;
11078
11079 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11080 if (ret > 0)
11081 {
11082 cache->hit_count++;
11083
11084 if (remote_debug)
11085 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11086 pulongest (cache->hit_count));
11087 return ret;
11088 }
11089
11090 cache->miss_count++;
11091 if (remote_debug)
11092 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11093 pulongest (cache->miss_count));
11094
11095 cache->fd = fd;
11096 cache->offset = offset;
11097 cache->bufsize = get_remote_packet_size ();
224c3ddb 11098 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11099
11100 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11101 cache->offset, remote_errno);
11102 if (ret <= 0)
11103 {
11104 readahead_cache_invalidate_fd (fd);
11105 return ret;
11106 }
11107
11108 cache->bufsize = ret;
11109 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11110}
11111
12e2a5fd 11112/* Implementation of to_fileio_close. */
a6b151f1
DJ
11113
11114static int
df39ea25 11115remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11116{
11117 struct remote_state *rs = get_remote_state ();
11118 char *p = rs->buf;
11119 int left = get_remote_packet_size () - 1;
11120
80152258
PA
11121 readahead_cache_invalidate_fd (fd);
11122
a6b151f1
DJ
11123 remote_buffer_add_string (&p, &left, "vFile:close:");
11124
11125 remote_buffer_add_int (&p, &left, fd);
11126
11127 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11128 remote_errno, NULL, NULL);
11129}
11130
12e2a5fd 11131/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11132
11133static int
dbbca37d 11134remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11135 struct inferior *inf, const char *filename,
11136 int *remote_errno)
a6b151f1
DJ
11137{
11138 struct remote_state *rs = get_remote_state ();
11139 char *p = rs->buf;
11140 int left = get_remote_packet_size () - 1;
11141
15a201c8
GB
11142 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11143 return -1;
11144
a6b151f1
DJ
11145 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11146
11147 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11148 strlen (filename));
11149
11150 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11151 remote_errno, NULL, NULL);
11152}
11153
12e2a5fd 11154/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11155
11156static char *
fab5aa7c 11157remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11158 struct inferior *inf, const char *filename,
11159 int *remote_errno)
b9e7b9c3
UW
11160{
11161 struct remote_state *rs = get_remote_state ();
11162 char *p = rs->buf;
11163 char *attachment;
11164 int left = get_remote_packet_size ();
11165 int len, attachment_len;
11166 int read_len;
11167 char *ret;
11168
15a201c8
GB
11169 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11170 return NULL;
11171
b9e7b9c3
UW
11172 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11173
11174 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11175 strlen (filename));
11176
11177 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11178 remote_errno, &attachment,
11179 &attachment_len);
11180
11181 if (len < 0)
11182 return NULL;
11183
224c3ddb 11184 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11185
bc20a4af
PA
11186 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11187 (gdb_byte *) ret, len);
b9e7b9c3
UW
11188 if (read_len != len)
11189 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11190
11191 ret[len] = '\0';
11192 return ret;
11193}
11194
12e2a5fd 11195/* Implementation of to_fileio_fstat. */
0a93529c
GB
11196
11197static int
11198remote_hostio_fstat (struct target_ops *self,
11199 int fd, struct stat *st,
11200 int *remote_errno)
11201{
11202 struct remote_state *rs = get_remote_state ();
11203 char *p = rs->buf;
11204 int left = get_remote_packet_size ();
11205 int attachment_len, ret;
11206 char *attachment;
11207 struct fio_stat fst;
11208 int read_len;
11209
464b0089
GB
11210 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11211
11212 remote_buffer_add_int (&p, &left, fd);
11213
11214 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11215 remote_errno, &attachment,
11216 &attachment_len);
11217 if (ret < 0)
0a93529c 11218 {
464b0089
GB
11219 if (*remote_errno != FILEIO_ENOSYS)
11220 return ret;
11221
0a93529c
GB
11222 /* Strictly we should return -1, ENOSYS here, but when
11223 "set sysroot remote:" was implemented in August 2008
11224 BFD's need for a stat function was sidestepped with
11225 this hack. This was not remedied until March 2015
11226 so we retain the previous behavior to avoid breaking
11227 compatibility.
11228
11229 Note that the memset is a March 2015 addition; older
11230 GDBs set st_size *and nothing else* so the structure
11231 would have garbage in all other fields. This might
11232 break something but retaining the previous behavior
11233 here would be just too wrong. */
11234
11235 memset (st, 0, sizeof (struct stat));
11236 st->st_size = INT_MAX;
11237 return 0;
11238 }
11239
0a93529c
GB
11240 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11241 (gdb_byte *) &fst, sizeof (fst));
11242
11243 if (read_len != ret)
11244 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11245
11246 if (read_len != sizeof (fst))
11247 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11248 read_len, (int) sizeof (fst));
11249
11250 remote_fileio_to_host_stat (&fst, st);
11251
11252 return 0;
11253}
11254
12e2a5fd 11255/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11256
11257static int
11258remote_filesystem_is_local (struct target_ops *self)
11259{
11260 /* Valgrind GDB presents itself as a remote target but works
11261 on the local filesystem: it does not implement remote get
11262 and users are not expected to set a sysroot. To handle
11263 this case we treat the remote filesystem as local if the
11264 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11265 does not support vFile:open. */
a3be80c3 11266 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11267 {
11268 enum packet_support ps = packet_support (PACKET_vFile_open);
11269
11270 if (ps == PACKET_SUPPORT_UNKNOWN)
11271 {
11272 int fd, remote_errno;
11273
11274 /* Try opening a file to probe support. The supplied
11275 filename is irrelevant, we only care about whether
11276 the stub recognizes the packet or not. */
07c138c8 11277 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11278 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11279 &remote_errno);
11280
11281 if (fd >= 0)
11282 remote_hostio_close (self, fd, &remote_errno);
11283
11284 ps = packet_support (PACKET_vFile_open);
11285 }
11286
11287 if (ps == PACKET_DISABLE)
11288 {
11289 static int warning_issued = 0;
11290
11291 if (!warning_issued)
11292 {
11293 warning (_("remote target does not support file"
11294 " transfer, attempting to access files"
11295 " from local filesystem."));
11296 warning_issued = 1;
11297 }
11298
11299 return 1;
11300 }
11301 }
11302
11303 return 0;
11304}
11305
a6b151f1
DJ
11306static int
11307remote_fileio_errno_to_host (int errnum)
11308{
11309 switch (errnum)
11310 {
11311 case FILEIO_EPERM:
11312 return EPERM;
11313 case FILEIO_ENOENT:
11314 return ENOENT;
11315 case FILEIO_EINTR:
11316 return EINTR;
11317 case FILEIO_EIO:
11318 return EIO;
11319 case FILEIO_EBADF:
11320 return EBADF;
11321 case FILEIO_EACCES:
11322 return EACCES;
11323 case FILEIO_EFAULT:
11324 return EFAULT;
11325 case FILEIO_EBUSY:
11326 return EBUSY;
11327 case FILEIO_EEXIST:
11328 return EEXIST;
11329 case FILEIO_ENODEV:
11330 return ENODEV;
11331 case FILEIO_ENOTDIR:
11332 return ENOTDIR;
11333 case FILEIO_EISDIR:
11334 return EISDIR;
11335 case FILEIO_EINVAL:
11336 return EINVAL;
11337 case FILEIO_ENFILE:
11338 return ENFILE;
11339 case FILEIO_EMFILE:
11340 return EMFILE;
11341 case FILEIO_EFBIG:
11342 return EFBIG;
11343 case FILEIO_ENOSPC:
11344 return ENOSPC;
11345 case FILEIO_ESPIPE:
11346 return ESPIPE;
11347 case FILEIO_EROFS:
11348 return EROFS;
11349 case FILEIO_ENOSYS:
11350 return ENOSYS;
11351 case FILEIO_ENAMETOOLONG:
11352 return ENAMETOOLONG;
11353 }
11354 return -1;
11355}
11356
11357static char *
11358remote_hostio_error (int errnum)
11359{
11360 int host_error = remote_fileio_errno_to_host (errnum);
11361
11362 if (host_error == -1)
11363 error (_("Unknown remote I/O error %d"), errnum);
11364 else
11365 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11366}
11367
a6b151f1
DJ
11368static void
11369remote_hostio_close_cleanup (void *opaque)
11370{
11371 int fd = *(int *) opaque;
11372 int remote_errno;
11373
df39ea25 11374 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11375}
11376
11377void
11378remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11379{
11380 struct cleanup *back_to, *close_cleanup;
11381 int retcode, fd, remote_errno, bytes, io_size;
11382 FILE *file;
11383 gdb_byte *buffer;
11384 int bytes_in_buffer;
11385 int saw_eof;
11386 ULONGEST offset;
5d93a237 11387 struct remote_state *rs = get_remote_state ();
a6b151f1 11388
5d93a237 11389 if (!rs->remote_desc)
a6b151f1
DJ
11390 error (_("command can only be used with remote target"));
11391
614c279d 11392 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11393 if (file == NULL)
11394 perror_with_name (local_file);
7c8a8b04 11395 back_to = make_cleanup_fclose (file);
a6b151f1 11396
07c138c8 11397 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11398 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11399 | FILEIO_O_TRUNC),
4313b8c0 11400 0700, 0, &remote_errno);
a6b151f1
DJ
11401 if (fd == -1)
11402 remote_hostio_error (remote_errno);
11403
11404 /* Send up to this many bytes at once. They won't all fit in the
11405 remote packet limit, so we'll transfer slightly fewer. */
11406 io_size = get_remote_packet_size ();
224c3ddb 11407 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11408 make_cleanup (xfree, buffer);
11409
11410 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11411
11412 bytes_in_buffer = 0;
11413 saw_eof = 0;
11414 offset = 0;
11415 while (bytes_in_buffer || !saw_eof)
11416 {
11417 if (!saw_eof)
11418 {
3e43a32a
MS
11419 bytes = fread (buffer + bytes_in_buffer, 1,
11420 io_size - bytes_in_buffer,
a6b151f1
DJ
11421 file);
11422 if (bytes == 0)
11423 {
11424 if (ferror (file))
11425 error (_("Error reading %s."), local_file);
11426 else
11427 {
11428 /* EOF. Unless there is something still in the
11429 buffer from the last iteration, we are done. */
11430 saw_eof = 1;
11431 if (bytes_in_buffer == 0)
11432 break;
11433 }
11434 }
11435 }
11436 else
11437 bytes = 0;
11438
11439 bytes += bytes_in_buffer;
11440 bytes_in_buffer = 0;
11441
0d866f62
TT
11442 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11443 fd, buffer, bytes,
3e43a32a 11444 offset, &remote_errno);
a6b151f1
DJ
11445
11446 if (retcode < 0)
11447 remote_hostio_error (remote_errno);
11448 else if (retcode == 0)
11449 error (_("Remote write of %d bytes returned 0!"), bytes);
11450 else if (retcode < bytes)
11451 {
11452 /* Short write. Save the rest of the read data for the next
11453 write. */
11454 bytes_in_buffer = bytes - retcode;
11455 memmove (buffer, buffer + retcode, bytes_in_buffer);
11456 }
11457
11458 offset += retcode;
11459 }
11460
11461 discard_cleanups (close_cleanup);
df39ea25 11462 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11463 remote_hostio_error (remote_errno);
11464
11465 if (from_tty)
11466 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11467 do_cleanups (back_to);
11468}
11469
11470void
11471remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11472{
11473 struct cleanup *back_to, *close_cleanup;
cea39f65 11474 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11475 FILE *file;
11476 gdb_byte *buffer;
11477 ULONGEST offset;
5d93a237 11478 struct remote_state *rs = get_remote_state ();
a6b151f1 11479
5d93a237 11480 if (!rs->remote_desc)
a6b151f1
DJ
11481 error (_("command can only be used with remote target"));
11482
07c138c8 11483 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11484 remote_file, FILEIO_O_RDONLY, 0, 0,
11485 &remote_errno);
a6b151f1
DJ
11486 if (fd == -1)
11487 remote_hostio_error (remote_errno);
11488
614c279d 11489 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11490 if (file == NULL)
11491 perror_with_name (local_file);
7c8a8b04 11492 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11493
11494 /* Send up to this many bytes at once. They won't all fit in the
11495 remote packet limit, so we'll transfer slightly fewer. */
11496 io_size = get_remote_packet_size ();
224c3ddb 11497 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11498 make_cleanup (xfree, buffer);
11499
11500 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11501
11502 offset = 0;
11503 while (1)
11504 {
a3be983c
TT
11505 bytes = remote_hostio_pread (find_target_at (process_stratum),
11506 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11507 if (bytes == 0)
11508 /* Success, but no bytes, means end-of-file. */
11509 break;
11510 if (bytes == -1)
11511 remote_hostio_error (remote_errno);
11512
11513 offset += bytes;
11514
11515 bytes = fwrite (buffer, 1, bytes, file);
11516 if (bytes == 0)
11517 perror_with_name (local_file);
11518 }
11519
11520 discard_cleanups (close_cleanup);
df39ea25 11521 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11522 remote_hostio_error (remote_errno);
11523
11524 if (from_tty)
11525 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11526 do_cleanups (back_to);
11527}
11528
11529void
11530remote_file_delete (const char *remote_file, int from_tty)
11531{
11532 int retcode, remote_errno;
5d93a237 11533 struct remote_state *rs = get_remote_state ();
a6b151f1 11534
5d93a237 11535 if (!rs->remote_desc)
a6b151f1
DJ
11536 error (_("command can only be used with remote target"));
11537
dbbca37d 11538 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11539 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11540 if (retcode == -1)
11541 remote_hostio_error (remote_errno);
11542
11543 if (from_tty)
11544 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11545}
11546
11547static void
11548remote_put_command (char *args, int from_tty)
11549{
11550 struct cleanup *back_to;
11551 char **argv;
11552
d1a41061
PP
11553 if (args == NULL)
11554 error_no_arg (_("file to put"));
11555
11556 argv = gdb_buildargv (args);
a6b151f1
DJ
11557 back_to = make_cleanup_freeargv (argv);
11558 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11559 error (_("Invalid parameters to remote put"));
11560
11561 remote_file_put (argv[0], argv[1], from_tty);
11562
11563 do_cleanups (back_to);
11564}
11565
11566static void
11567remote_get_command (char *args, int from_tty)
11568{
11569 struct cleanup *back_to;
11570 char **argv;
11571
d1a41061
PP
11572 if (args == NULL)
11573 error_no_arg (_("file to get"));
11574
11575 argv = gdb_buildargv (args);
a6b151f1
DJ
11576 back_to = make_cleanup_freeargv (argv);
11577 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11578 error (_("Invalid parameters to remote get"));
11579
11580 remote_file_get (argv[0], argv[1], from_tty);
11581
11582 do_cleanups (back_to);
11583}
11584
11585static void
11586remote_delete_command (char *args, int from_tty)
11587{
11588 struct cleanup *back_to;
11589 char **argv;
11590
d1a41061
PP
11591 if (args == NULL)
11592 error_no_arg (_("file to delete"));
11593
11594 argv = gdb_buildargv (args);
a6b151f1
DJ
11595 back_to = make_cleanup_freeargv (argv);
11596 if (argv[0] == NULL || argv[1] != NULL)
11597 error (_("Invalid parameters to remote delete"));
11598
11599 remote_file_delete (argv[0], from_tty);
11600
11601 do_cleanups (back_to);
11602}
11603
11604static void
11605remote_command (char *args, int from_tty)
11606{
635c7e8a 11607 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11608}
11609
b2175913 11610static int
19db3e69 11611remote_can_execute_reverse (struct target_ops *self)
b2175913 11612{
4082afcc
PA
11613 if (packet_support (PACKET_bs) == PACKET_ENABLE
11614 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11615 return 1;
11616 else
11617 return 0;
b2175913
MS
11618}
11619
74531fed 11620static int
2a9a2795 11621remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11622{
11623 return 1;
11624}
11625
03583c20 11626static int
2bfc0540 11627remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11628{
11629 /* Only supported in extended mode. */
11630 return 0;
11631}
11632
8a305172 11633static int
86ce2668 11634remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11635{
11636 struct remote_state *rs = get_remote_state ();
a744cf53 11637
901f9912
UW
11638 /* Only extended-remote handles being attached to multiple
11639 processes, even though plain remote can use the multi-process
11640 thread id extensions, so that GDB knows the target process's
11641 PID. */
11642 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
11643}
11644
70221824 11645static int
782b2b07
SS
11646remote_supports_cond_tracepoints (void)
11647{
4082afcc 11648 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11649}
11650
3788aec7 11651static int
efcc2da7 11652remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11653{
4082afcc 11654 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11655}
11656
70221824 11657static int
7a697b8d
SS
11658remote_supports_fast_tracepoints (void)
11659{
4082afcc 11660 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11661}
11662
0fb4aa4b
PA
11663static int
11664remote_supports_static_tracepoints (void)
11665{
4082afcc 11666 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11667}
11668
1e4d1764
YQ
11669static int
11670remote_supports_install_in_trace (void)
11671{
4082afcc 11672 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11673}
11674
d248b706 11675static int
7d178d6a 11676remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11677{
4082afcc
PA
11678 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11679 == PACKET_ENABLE);
d248b706
KY
11680}
11681
3065dfb6 11682static int
6de37a3a 11683remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11684{
4082afcc 11685 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11686}
11687
d3ce09f5 11688static int
78eff0ec 11689remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11690{
4082afcc 11691 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11692}
11693
35b1e5cc 11694static void
ecae04e1 11695remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11696{
11697 putpkt ("QTinit");
11698 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11699 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11700 error (_("Target does not support this command."));
11701}
11702
11703static void free_actions_list (char **actions_list);
11704static void free_actions_list_cleanup_wrapper (void *);
11705static void
11706free_actions_list_cleanup_wrapper (void *al)
11707{
19ba03f4 11708 free_actions_list ((char **) al);
35b1e5cc
SS
11709}
11710
11711static void
11712free_actions_list (char **actions_list)
11713{
11714 int ndx;
11715
11716 if (actions_list == 0)
11717 return;
11718
11719 for (ndx = 0; actions_list[ndx]; ndx++)
11720 xfree (actions_list[ndx]);
11721
11722 xfree (actions_list);
11723}
11724
409873ef
SS
11725/* Recursive routine to walk through command list including loops, and
11726 download packets for each command. */
11727
11728static void
11729remote_download_command_source (int num, ULONGEST addr,
11730 struct command_line *cmds)
11731{
11732 struct remote_state *rs = get_remote_state ();
11733 struct command_line *cmd;
11734
11735 for (cmd = cmds; cmd; cmd = cmd->next)
11736 {
0df8b418 11737 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11738 strcpy (rs->buf, "QTDPsrc:");
11739 encode_source_string (num, addr, "cmd", cmd->line,
11740 rs->buf + strlen (rs->buf),
11741 rs->buf_size - strlen (rs->buf));
11742 putpkt (rs->buf);
11743 remote_get_noisy_reply (&target_buf, &target_buf_size);
11744 if (strcmp (target_buf, "OK"))
11745 warning (_("Target does not support source download."));
11746
11747 if (cmd->control_type == while_control
11748 || cmd->control_type == while_stepping_control)
11749 {
11750 remote_download_command_source (num, addr, *cmd->body_list);
11751
0df8b418 11752 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11753 strcpy (rs->buf, "QTDPsrc:");
11754 encode_source_string (num, addr, "cmd", "end",
11755 rs->buf + strlen (rs->buf),
11756 rs->buf_size - strlen (rs->buf));
11757 putpkt (rs->buf);
11758 remote_get_noisy_reply (&target_buf, &target_buf_size);
11759 if (strcmp (target_buf, "OK"))
11760 warning (_("Target does not support source download."));
11761 }
11762 }
11763}
11764
35b1e5cc 11765static void
548f7808 11766remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11767{
bba74b36 11768#define BUF_SIZE 2048
e8ba3115 11769
35b1e5cc 11770 CORE_ADDR tpaddr;
409873ef 11771 char addrbuf[40];
bba74b36 11772 char buf[BUF_SIZE];
35b1e5cc
SS
11773 char **tdp_actions;
11774 char **stepping_actions;
11775 int ndx;
11776 struct cleanup *old_chain = NULL;
11777 struct agent_expr *aexpr;
11778 struct cleanup *aexpr_chain = NULL;
11779 char *pkt;
e8ba3115 11780 struct breakpoint *b = loc->owner;
d9b3f62e 11781 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11782
dc673c81 11783 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11784 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11785 tdp_actions);
11786 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11787 stepping_actions);
11788
11789 tpaddr = loc->address;
11790 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11791 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11792 addrbuf, /* address */
11793 (b->enable_state == bp_enabled ? 'E' : 'D'),
11794 t->step_count, t->pass_count);
e8ba3115
YQ
11795 /* Fast tracepoints are mostly handled by the target, but we can
11796 tell the target how big of an instruction block should be moved
11797 around. */
11798 if (b->type == bp_fast_tracepoint)
11799 {
11800 /* Only test for support at download time; we may not know
11801 target capabilities at definition time. */
11802 if (remote_supports_fast_tracepoints ())
35b1e5cc 11803 {
6b940e6a
PL
11804 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11805 NULL))
bba74b36 11806 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11807 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11808 else
e8ba3115
YQ
11809 /* If it passed validation at definition but fails now,
11810 something is very wrong. */
11811 internal_error (__FILE__, __LINE__,
11812 _("Fast tracepoint not "
11813 "valid during download"));
35b1e5cc 11814 }
e8ba3115
YQ
11815 else
11816 /* Fast tracepoints are functionally identical to regular
11817 tracepoints, so don't take lack of support as a reason to
11818 give up on the trace run. */
11819 warning (_("Target does not support fast tracepoints, "
11820 "downloading %d as regular tracepoint"), b->number);
11821 }
11822 else if (b->type == bp_static_tracepoint)
11823 {
11824 /* Only test for support at download time; we may not know
11825 target capabilities at definition time. */
11826 if (remote_supports_static_tracepoints ())
0fb4aa4b 11827 {
e8ba3115 11828 struct static_tracepoint_marker marker;
0fb4aa4b 11829
e8ba3115
YQ
11830 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11831 strcat (buf, ":S");
0fb4aa4b 11832 else
e8ba3115 11833 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11834 }
e8ba3115
YQ
11835 else
11836 /* Fast tracepoints are functionally identical to regular
11837 tracepoints, so don't take lack of support as a reason
11838 to give up on the trace run. */
11839 error (_("Target does not support static tracepoints"));
11840 }
11841 /* If the tracepoint has a conditional, make it into an agent
11842 expression and append to the definition. */
11843 if (loc->cond)
11844 {
11845 /* Only test support at download time, we may not know target
11846 capabilities at definition time. */
11847 if (remote_supports_cond_tracepoints ())
35b1e5cc 11848 {
e8ba3115
YQ
11849 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11850 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11851 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11852 aexpr->len);
e8ba3115
YQ
11853 pkt = buf + strlen (buf);
11854 for (ndx = 0; ndx < aexpr->len; ++ndx)
11855 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11856 *pkt = '\0';
11857 do_cleanups (aexpr_chain);
35b1e5cc 11858 }
e8ba3115
YQ
11859 else
11860 warning (_("Target does not support conditional tracepoints, "
11861 "ignoring tp %d cond"), b->number);
11862 }
35b1e5cc 11863
d9b3f62e 11864 if (b->commands || *default_collect)
e8ba3115
YQ
11865 strcat (buf, "-");
11866 putpkt (buf);
11867 remote_get_noisy_reply (&target_buf, &target_buf_size);
11868 if (strcmp (target_buf, "OK"))
11869 error (_("Target does not support tracepoints."));
35b1e5cc 11870
e8ba3115
YQ
11871 /* do_single_steps (t); */
11872 if (tdp_actions)
11873 {
11874 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11875 {
e8ba3115 11876 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11877 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11878 b->number, addrbuf, /* address */
11879 tdp_actions[ndx],
11880 ((tdp_actions[ndx + 1] || stepping_actions)
11881 ? '-' : 0));
e8ba3115
YQ
11882 putpkt (buf);
11883 remote_get_noisy_reply (&target_buf,
11884 &target_buf_size);
11885 if (strcmp (target_buf, "OK"))
11886 error (_("Error on target while setting tracepoints."));
35b1e5cc 11887 }
e8ba3115
YQ
11888 }
11889 if (stepping_actions)
11890 {
11891 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11892 {
e8ba3115 11893 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11894 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11895 b->number, addrbuf, /* address */
11896 ((ndx == 0) ? "S" : ""),
11897 stepping_actions[ndx],
11898 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11899 putpkt (buf);
11900 remote_get_noisy_reply (&target_buf,
11901 &target_buf_size);
11902 if (strcmp (target_buf, "OK"))
11903 error (_("Error on target while setting tracepoints."));
35b1e5cc 11904 }
e8ba3115 11905 }
409873ef 11906
4082afcc 11907 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11908 {
f00aae0f 11909 if (b->location != NULL)
409873ef 11910 {
e8ba3115 11911 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11912 encode_source_string (b->number, loc->address, "at",
11913 event_location_to_string (b->location),
11914 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11915 putpkt (buf);
11916 remote_get_noisy_reply (&target_buf, &target_buf_size);
11917 if (strcmp (target_buf, "OK"))
11918 warning (_("Target does not support source download."));
409873ef 11919 }
e8ba3115
YQ
11920 if (b->cond_string)
11921 {
11922 strcpy (buf, "QTDPsrc:");
11923 encode_source_string (b->number, loc->address,
11924 "cond", b->cond_string, buf + strlen (buf),
11925 2048 - strlen (buf));
11926 putpkt (buf);
11927 remote_get_noisy_reply (&target_buf, &target_buf_size);
11928 if (strcmp (target_buf, "OK"))
11929 warning (_("Target does not support source download."));
11930 }
11931 remote_download_command_source (b->number, loc->address,
11932 breakpoint_commands (b));
35b1e5cc 11933 }
e8ba3115
YQ
11934
11935 do_cleanups (old_chain);
35b1e5cc
SS
11936}
11937
1e4d1764 11938static int
a52a8357 11939remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 11940{
1e51243a
PA
11941 struct remote_state *rs = get_remote_state ();
11942 struct trace_status *ts;
11943 int status;
11944
11945 /* Don't try to install tracepoints until we've relocated our
11946 symbols, and fetched and merged the target's tracepoint list with
11947 ours. */
11948 if (rs->starting_up)
11949 return 0;
11950
11951 ts = current_trace_status ();
8bd200f1 11952 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
11953
11954 if (status == -1 || !ts->running_known || !ts->running)
11955 return 0;
11956
11957 /* If we are in a tracing experiment, but remote stub doesn't support
11958 installing tracepoint in trace, we have to return. */
11959 if (!remote_supports_install_in_trace ())
11960 return 0;
11961
11962 return 1;
11963}
11964
11965
35b1e5cc 11966static void
559d2b81
TT
11967remote_download_trace_state_variable (struct target_ops *self,
11968 struct trace_state_variable *tsv)
35b1e5cc
SS
11969{
11970 struct remote_state *rs = get_remote_state ();
00bf0b85 11971 char *p;
35b1e5cc 11972
bba74b36
YQ
11973 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11974 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11975 tsv->builtin);
00bf0b85
SS
11976 p = rs->buf + strlen (rs->buf);
11977 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11978 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 11979 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 11980 *p++ = '\0';
35b1e5cc
SS
11981 putpkt (rs->buf);
11982 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11983 if (*target_buf == '\0')
11984 error (_("Target does not support this command."));
11985 if (strcmp (target_buf, "OK") != 0)
11986 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
11987}
11988
d248b706 11989static void
46670d57
TT
11990remote_enable_tracepoint (struct target_ops *self,
11991 struct bp_location *location)
d248b706
KY
11992{
11993 struct remote_state *rs = get_remote_state ();
11994 char addr_buf[40];
11995
11996 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11997 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11998 location->owner->number, addr_buf);
d248b706
KY
11999 putpkt (rs->buf);
12000 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12001 if (*rs->buf == '\0')
12002 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12003 if (strcmp (rs->buf, "OK") != 0)
12004 error (_("Error on target while enabling tracepoint."));
12005}
12006
12007static void
780b049c
TT
12008remote_disable_tracepoint (struct target_ops *self,
12009 struct bp_location *location)
d248b706
KY
12010{
12011 struct remote_state *rs = get_remote_state ();
12012 char addr_buf[40];
12013
12014 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12015 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12016 location->owner->number, addr_buf);
d248b706
KY
12017 putpkt (rs->buf);
12018 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12019 if (*rs->buf == '\0')
12020 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12021 if (strcmp (rs->buf, "OK") != 0)
12022 error (_("Error on target while disabling tracepoint."));
12023}
12024
35b1e5cc 12025static void
583f9a86 12026remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12027{
12028 asection *s;
81b9b86e 12029 bfd *abfd = NULL;
35b1e5cc 12030 bfd_size_type size;
608bcef2 12031 bfd_vma vma;
35b1e5cc 12032 int anysecs = 0;
c2fa21f1 12033 int offset = 0;
35b1e5cc
SS
12034
12035 if (!exec_bfd)
12036 return; /* No information to give. */
12037
12038 strcpy (target_buf, "QTro");
9779ab84 12039 offset = strlen (target_buf);
35b1e5cc
SS
12040 for (s = exec_bfd->sections; s; s = s->next)
12041 {
12042 char tmp1[40], tmp2[40];
c2fa21f1 12043 int sec_length;
35b1e5cc
SS
12044
12045 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12046 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12047 (s->flags & SEC_READONLY) == 0)
12048 continue;
12049
12050 anysecs = 1;
81b9b86e 12051 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12052 size = bfd_get_section_size (s);
608bcef2
HZ
12053 sprintf_vma (tmp1, vma);
12054 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12055 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12056 if (offset + sec_length + 1 > target_buf_size)
12057 {
4082afcc 12058 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12059 warning (_("\
c2fa21f1
HZ
12060Too many sections for read-only sections definition packet."));
12061 break;
12062 }
bba74b36
YQ
12063 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12064 tmp1, tmp2);
c2fa21f1 12065 offset += sec_length;
35b1e5cc
SS
12066 }
12067 if (anysecs)
12068 {
12069 putpkt (target_buf);
12070 getpkt (&target_buf, &target_buf_size, 0);
12071 }
12072}
12073
12074static void
e2d1aae3 12075remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12076{
12077 putpkt ("QTStart");
12078 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12079 if (*target_buf == '\0')
12080 error (_("Target does not support this command."));
12081 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12082 error (_("Bogus reply from target: %s"), target_buf);
12083}
12084
12085static int
8bd200f1 12086remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12087{
953b98d1 12088 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12089 char *p = NULL;
0df8b418 12090 /* FIXME we need to get register block size some other way. */
00bf0b85 12091 extern int trace_regblock_size;
bd3eecc3
PA
12092 enum packet_result result;
12093
4082afcc 12094 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12095 return -1;
a744cf53 12096
00bf0b85
SS
12097 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12098
049dc89b
JK
12099 putpkt ("qTStatus");
12100
492d29ea 12101 TRY
67f41397
JK
12102 {
12103 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12104 }
492d29ea 12105 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12106 {
598d3636
JK
12107 if (ex.error != TARGET_CLOSE_ERROR)
12108 {
12109 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12110 return -1;
12111 }
12112 throw_exception (ex);
67f41397 12113 }
492d29ea 12114 END_CATCH
00bf0b85 12115
bd3eecc3
PA
12116 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12117
00bf0b85 12118 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12119 if (result == PACKET_UNKNOWN)
00bf0b85 12120 return -1;
35b1e5cc 12121
00bf0b85 12122 /* We're working with a live target. */
f5911ea1 12123 ts->filename = NULL;
00bf0b85 12124
00bf0b85 12125 if (*p++ != 'T')
35b1e5cc
SS
12126 error (_("Bogus trace status reply from target: %s"), target_buf);
12127
84cebc4a
YQ
12128 /* Function 'parse_trace_status' sets default value of each field of
12129 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12130 parse_trace_status (p, ts);
12131
12132 return ts->running;
35b1e5cc
SS
12133}
12134
70221824 12135static void
db90e85c 12136remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12137 struct uploaded_tp *utp)
12138{
12139 struct remote_state *rs = get_remote_state ();
f196051f
SS
12140 char *reply;
12141 struct bp_location *loc;
12142 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12143 size_t size = get_remote_packet_size ();
f196051f
SS
12144
12145 if (tp)
12146 {
12147 tp->base.hit_count = 0;
12148 tp->traceframe_usage = 0;
12149 for (loc = tp->base.loc; loc; loc = loc->next)
12150 {
12151 /* If the tracepoint was never downloaded, don't go asking for
12152 any status. */
12153 if (tp->number_on_target == 0)
12154 continue;
bba74b36
YQ
12155 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12156 phex_nz (loc->address, 0));
f196051f
SS
12157 putpkt (rs->buf);
12158 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12159 if (reply && *reply)
12160 {
12161 if (*reply == 'V')
12162 parse_tracepoint_status (reply + 1, bp, utp);
12163 }
12164 }
12165 }
12166 else if (utp)
12167 {
12168 utp->hit_count = 0;
12169 utp->traceframe_usage = 0;
bba74b36
YQ
12170 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12171 phex_nz (utp->addr, 0));
f196051f
SS
12172 putpkt (rs->buf);
12173 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12174 if (reply && *reply)
12175 {
12176 if (*reply == 'V')
12177 parse_tracepoint_status (reply + 1, bp, utp);
12178 }
12179 }
12180}
12181
35b1e5cc 12182static void
74499f1b 12183remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12184{
12185 putpkt ("QTStop");
12186 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12187 if (*target_buf == '\0')
12188 error (_("Target does not support this command."));
12189 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12190 error (_("Bogus reply from target: %s"), target_buf);
12191}
12192
12193static int
bd4c6793
TT
12194remote_trace_find (struct target_ops *self,
12195 enum trace_find_type type, int num,
cc5925ad 12196 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12197 int *tpp)
12198{
12199 struct remote_state *rs = get_remote_state ();
bba74b36 12200 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12201 char *p, *reply;
12202 int target_frameno = -1, target_tracept = -1;
12203
e6e4e701
PA
12204 /* Lookups other than by absolute frame number depend on the current
12205 trace selected, so make sure it is correct on the remote end
12206 first. */
12207 if (type != tfind_number)
12208 set_remote_traceframe ();
12209
35b1e5cc
SS
12210 p = rs->buf;
12211 strcpy (p, "QTFrame:");
12212 p = strchr (p, '\0');
12213 switch (type)
12214 {
12215 case tfind_number:
bba74b36 12216 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12217 break;
12218 case tfind_pc:
bba74b36 12219 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12220 break;
12221 case tfind_tp:
bba74b36 12222 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12223 break;
12224 case tfind_range:
bba74b36
YQ
12225 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12226 phex_nz (addr2, 0));
35b1e5cc
SS
12227 break;
12228 case tfind_outside:
bba74b36
YQ
12229 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12230 phex_nz (addr2, 0));
35b1e5cc
SS
12231 break;
12232 default:
9b20d036 12233 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12234 }
12235
12236 putpkt (rs->buf);
2f65bcb7 12237 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12238 if (*reply == '\0')
12239 error (_("Target does not support this command."));
35b1e5cc
SS
12240
12241 while (reply && *reply)
12242 switch (*reply)
12243 {
12244 case 'F':
f197e0f1
VP
12245 p = ++reply;
12246 target_frameno = (int) strtol (p, &reply, 16);
12247 if (reply == p)
12248 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12249 /* Don't update our remote traceframe number cache on failure
12250 to select a remote traceframe. */
f197e0f1
VP
12251 if (target_frameno == -1)
12252 return -1;
35b1e5cc
SS
12253 break;
12254 case 'T':
f197e0f1
VP
12255 p = ++reply;
12256 target_tracept = (int) strtol (p, &reply, 16);
12257 if (reply == p)
12258 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12259 break;
12260 case 'O': /* "OK"? */
12261 if (reply[1] == 'K' && reply[2] == '\0')
12262 reply += 2;
12263 else
12264 error (_("Bogus reply from target: %s"), reply);
12265 break;
12266 default:
12267 error (_("Bogus reply from target: %s"), reply);
12268 }
12269 if (tpp)
12270 *tpp = target_tracept;
e6e4e701 12271
262e1174 12272 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12273 return target_frameno;
12274}
12275
12276static int
4011015b
TT
12277remote_get_trace_state_variable_value (struct target_ops *self,
12278 int tsvnum, LONGEST *val)
35b1e5cc
SS
12279{
12280 struct remote_state *rs = get_remote_state ();
12281 char *reply;
12282 ULONGEST uval;
12283
e6e4e701
PA
12284 set_remote_traceframe ();
12285
bba74b36 12286 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12287 putpkt (rs->buf);
12288 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12289 if (reply && *reply)
12290 {
12291 if (*reply == 'V')
12292 {
12293 unpack_varlen_hex (reply + 1, &uval);
12294 *val = (LONGEST) uval;
12295 return 1;
12296 }
12297 }
12298 return 0;
12299}
12300
00bf0b85 12301static int
dc3decaf 12302remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12303{
12304 struct remote_state *rs = get_remote_state ();
12305 char *p, *reply;
12306
12307 p = rs->buf;
12308 strcpy (p, "QTSave:");
12309 p += strlen (p);
12310 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12311 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12312 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12313 *p++ = '\0';
12314 putpkt (rs->buf);
ad91cd99 12315 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12316 if (*reply == '\0')
ad91cd99
PA
12317 error (_("Target does not support this command."));
12318 if (strcmp (reply, "OK") != 0)
12319 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12320 return 0;
12321}
12322
12323/* This is basically a memory transfer, but needs to be its own packet
12324 because we don't know how the target actually organizes its trace
12325 memory, plus we want to be able to ask for as much as possible, but
12326 not be unhappy if we don't get as much as we ask for. */
12327
12328static LONGEST
88ee6f45
TT
12329remote_get_raw_trace_data (struct target_ops *self,
12330 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12331{
12332 struct remote_state *rs = get_remote_state ();
12333 char *reply;
12334 char *p;
12335 int rslt;
12336
12337 p = rs->buf;
12338 strcpy (p, "qTBuffer:");
12339 p += strlen (p);
12340 p += hexnumstr (p, offset);
12341 *p++ = ',';
12342 p += hexnumstr (p, len);
12343 *p++ = '\0';
12344
12345 putpkt (rs->buf);
12346 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12347 if (reply && *reply)
12348 {
12349 /* 'l' by itself means we're at the end of the buffer and
12350 there is nothing more to get. */
12351 if (*reply == 'l')
12352 return 0;
12353
12354 /* Convert the reply into binary. Limit the number of bytes to
12355 convert according to our passed-in buffer size, rather than
12356 what was returned in the packet; if the target is
12357 unexpectedly generous and gives us a bigger reply than we
12358 asked for, we don't want to crash. */
12359 rslt = hex2bin (target_buf, buf, len);
12360 return rslt;
12361 }
12362
12363 /* Something went wrong, flag as an error. */
12364 return -1;
12365}
12366
35b1e5cc 12367static void
37b25738 12368remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12369{
12370 struct remote_state *rs = get_remote_state ();
12371
4082afcc 12372 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12373 {
ad91cd99
PA
12374 char *reply;
12375
bba74b36 12376 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12377 putpkt (rs->buf);
ad91cd99
PA
12378 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12379 if (*reply == '\0')
33da3f1c 12380 error (_("Target does not support this command."));
ad91cd99
PA
12381 if (strcmp (reply, "OK") != 0)
12382 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12383 }
12384 else if (val)
12385 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12386}
12387
dc146f7c
VP
12388static int
12389remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12390{
12391 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12392
fe978cb0
PA
12393 if (info && info->priv)
12394 return info->priv->core;
dc146f7c
VP
12395 return -1;
12396}
12397
4daf5ac0 12398static void
736d5b1f 12399remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12400{
12401 struct remote_state *rs = get_remote_state ();
ad91cd99 12402 char *reply;
4daf5ac0 12403
bba74b36 12404 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12405 putpkt (rs->buf);
ad91cd99
PA
12406 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12407 if (*reply == '\0')
4daf5ac0 12408 error (_("Target does not support this command."));
ad91cd99
PA
12409 if (strcmp (reply, "OK") != 0)
12410 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12411}
12412
b3b9301e 12413static struct traceframe_info *
a893e81f 12414remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12415{
12416 char *text;
12417
12418 text = target_read_stralloc (&current_target,
12419 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12420 if (text != NULL)
12421 {
12422 struct traceframe_info *info;
12423 struct cleanup *back_to = make_cleanup (xfree, text);
12424
12425 info = parse_traceframe_info (text);
12426 do_cleanups (back_to);
12427 return info;
12428 }
12429
12430 return NULL;
12431}
12432
405f8e94
SS
12433/* Handle the qTMinFTPILen packet. Returns the minimum length of
12434 instruction on which a fast tracepoint may be placed. Returns -1
12435 if the packet is not supported, and 0 if the minimum instruction
12436 length is unknown. */
12437
12438static int
0e67620a 12439remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12440{
12441 struct remote_state *rs = get_remote_state ();
12442 char *reply;
12443
e886a173
PA
12444 /* If we're not debugging a process yet, the IPA can't be
12445 loaded. */
12446 if (!target_has_execution)
12447 return 0;
12448
12449 /* Make sure the remote is pointing at the right process. */
12450 set_general_process ();
12451
bba74b36 12452 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12453 putpkt (rs->buf);
12454 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12455 if (*reply == '\0')
12456 return -1;
12457 else
12458 {
12459 ULONGEST min_insn_len;
12460
12461 unpack_varlen_hex (reply, &min_insn_len);
12462
12463 return (int) min_insn_len;
12464 }
12465}
12466
f6f899bf 12467static void
4da384be 12468remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12469{
4082afcc 12470 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12471 {
12472 struct remote_state *rs = get_remote_state ();
12473 char *buf = rs->buf;
12474 char *endbuf = rs->buf + get_remote_packet_size ();
12475 enum packet_result result;
12476
12477 gdb_assert (val >= 0 || val == -1);
12478 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12479 /* Send -1 as literal "-1" to avoid host size dependency. */
12480 if (val < 0)
12481 {
12482 *buf++ = '-';
12483 buf += hexnumstr (buf, (ULONGEST) -val);
12484 }
12485 else
12486 buf += hexnumstr (buf, (ULONGEST) val);
12487
12488 putpkt (rs->buf);
12489 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12490 result = packet_ok (rs->buf,
12491 &remote_protocol_packets[PACKET_QTBuffer_size]);
12492
12493 if (result != PACKET_OK)
12494 warning (_("Bogus reply from target: %s"), rs->buf);
12495 }
12496}
12497
f196051f 12498static int
d9e68a2c
TT
12499remote_set_trace_notes (struct target_ops *self,
12500 const char *user, const char *notes,
ca623f82 12501 const char *stop_notes)
f196051f
SS
12502{
12503 struct remote_state *rs = get_remote_state ();
12504 char *reply;
12505 char *buf = rs->buf;
12506 char *endbuf = rs->buf + get_remote_packet_size ();
12507 int nbytes;
12508
12509 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12510 if (user)
12511 {
12512 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12513 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12514 buf += 2 * nbytes;
12515 *buf++ = ';';
12516 }
12517 if (notes)
12518 {
12519 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12520 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12521 buf += 2 * nbytes;
12522 *buf++ = ';';
12523 }
12524 if (stop_notes)
12525 {
12526 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12527 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12528 buf += 2 * nbytes;
12529 *buf++ = ';';
12530 }
12531 /* Ensure the buffer is terminated. */
12532 *buf = '\0';
12533
12534 putpkt (rs->buf);
12535 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12536 if (*reply == '\0')
12537 return 0;
12538
12539 if (strcmp (reply, "OK") != 0)
12540 error (_("Bogus reply from target: %s"), reply);
12541
12542 return 1;
12543}
12544
d1feda86 12545static int
2c152180 12546remote_use_agent (struct target_ops *self, int use)
d1feda86 12547{
4082afcc 12548 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12549 {
12550 struct remote_state *rs = get_remote_state ();
12551
12552 /* If the stub supports QAgent. */
bba74b36 12553 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12554 putpkt (rs->buf);
12555 getpkt (&rs->buf, &rs->buf_size, 0);
12556
12557 if (strcmp (rs->buf, "OK") == 0)
12558 {
12559 use_agent = use;
12560 return 1;
12561 }
12562 }
12563
12564 return 0;
12565}
12566
12567static int
fe38f897 12568remote_can_use_agent (struct target_ops *self)
d1feda86 12569{
4082afcc 12570 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12571}
12572
9accd112
MM
12573struct btrace_target_info
12574{
12575 /* The ptid of the traced thread. */
12576 ptid_t ptid;
f4abbc16
MM
12577
12578 /* The obtained branch trace configuration. */
12579 struct btrace_config conf;
9accd112
MM
12580};
12581
f4abbc16
MM
12582/* Reset our idea of our target's btrace configuration. */
12583
12584static void
12585remote_btrace_reset (void)
12586{
12587 struct remote_state *rs = get_remote_state ();
12588
12589 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12590}
12591
9accd112
MM
12592/* Check whether the target supports branch tracing. */
12593
12594static int
043c3577 12595remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12596{
4082afcc 12597 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12598 return 0;
4082afcc 12599 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12600 return 0;
12601
043c3577
MM
12602 switch (format)
12603 {
12604 case BTRACE_FORMAT_NONE:
12605 return 0;
12606
12607 case BTRACE_FORMAT_BTS:
12608 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12609
12610 case BTRACE_FORMAT_PT:
12611 /* The trace is decoded on the host. Even if our target supports it,
12612 we still need to have libipt to decode the trace. */
12613#if defined (HAVE_LIBIPT)
12614 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12615#else /* !defined (HAVE_LIBIPT) */
12616 return 0;
12617#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12618 }
12619
12620 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12621}
12622
f4abbc16
MM
12623/* Synchronize the configuration with the target. */
12624
12625static void
12626btrace_sync_conf (const struct btrace_config *conf)
12627{
d33501a5
MM
12628 struct packet_config *packet;
12629 struct remote_state *rs;
12630 char *buf, *pos, *endbuf;
12631
12632 rs = get_remote_state ();
12633 buf = rs->buf;
12634 endbuf = buf + get_remote_packet_size ();
12635
12636 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12637 if (packet_config_support (packet) == PACKET_ENABLE
12638 && conf->bts.size != rs->btrace_config.bts.size)
12639 {
12640 pos = buf;
12641 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12642 conf->bts.size);
12643
12644 putpkt (buf);
12645 getpkt (&buf, &rs->buf_size, 0);
12646
12647 if (packet_ok (buf, packet) == PACKET_ERROR)
12648 {
12649 if (buf[0] == 'E' && buf[1] == '.')
12650 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12651 else
12652 error (_("Failed to configure the BTS buffer size."));
12653 }
12654
12655 rs->btrace_config.bts.size = conf->bts.size;
12656 }
b20a6524
MM
12657
12658 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12659 if (packet_config_support (packet) == PACKET_ENABLE
12660 && conf->pt.size != rs->btrace_config.pt.size)
12661 {
12662 pos = buf;
12663 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12664 conf->pt.size);
12665
12666 putpkt (buf);
12667 getpkt (&buf, &rs->buf_size, 0);
12668
12669 if (packet_ok (buf, packet) == PACKET_ERROR)
12670 {
12671 if (buf[0] == 'E' && buf[1] == '.')
12672 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12673 else
12674 error (_("Failed to configure the trace buffer size."));
12675 }
12676
12677 rs->btrace_config.pt.size = conf->pt.size;
12678 }
f4abbc16
MM
12679}
12680
12681/* Read the current thread's btrace configuration from the target and
12682 store it into CONF. */
12683
12684static void
12685btrace_read_config (struct btrace_config *conf)
12686{
12687 char *xml;
12688
12689 xml = target_read_stralloc (&current_target,
b20a6524 12690 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12691 if (xml != NULL)
12692 {
12693 struct cleanup *cleanup;
12694
12695 cleanup = make_cleanup (xfree, xml);
12696 parse_xml_btrace_conf (conf, xml);
12697 do_cleanups (cleanup);
12698 }
12699}
12700
9accd112
MM
12701/* Enable branch tracing. */
12702
12703static struct btrace_target_info *
f4abbc16
MM
12704remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12705 const struct btrace_config *conf)
9accd112
MM
12706{
12707 struct btrace_target_info *tinfo = NULL;
b20a6524 12708 struct packet_config *packet = NULL;
9accd112
MM
12709 struct remote_state *rs = get_remote_state ();
12710 char *buf = rs->buf;
12711 char *endbuf = rs->buf + get_remote_packet_size ();
12712
b20a6524
MM
12713 switch (conf->format)
12714 {
12715 case BTRACE_FORMAT_BTS:
12716 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12717 break;
12718
12719 case BTRACE_FORMAT_PT:
12720 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12721 break;
12722 }
12723
12724 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12725 error (_("Target does not support branch tracing."));
12726
f4abbc16
MM
12727 btrace_sync_conf (conf);
12728
9accd112
MM
12729 set_general_thread (ptid);
12730
12731 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12732 putpkt (rs->buf);
12733 getpkt (&rs->buf, &rs->buf_size, 0);
12734
12735 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12736 {
12737 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12738 error (_("Could not enable branch tracing for %s: %s"),
12739 target_pid_to_str (ptid), rs->buf + 2);
12740 else
12741 error (_("Could not enable branch tracing for %s."),
12742 target_pid_to_str (ptid));
12743 }
12744
8d749320 12745 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12746 tinfo->ptid = ptid;
12747
f4abbc16
MM
12748 /* If we fail to read the configuration, we lose some information, but the
12749 tracing itself is not impacted. */
492d29ea
PA
12750 TRY
12751 {
12752 btrace_read_config (&tinfo->conf);
12753 }
12754 CATCH (err, RETURN_MASK_ERROR)
12755 {
12756 if (err.message != NULL)
12757 warning ("%s", err.message);
12758 }
12759 END_CATCH
f4abbc16 12760
9accd112
MM
12761 return tinfo;
12762}
12763
12764/* Disable branch tracing. */
12765
12766static void
25e95349
TT
12767remote_disable_btrace (struct target_ops *self,
12768 struct btrace_target_info *tinfo)
9accd112
MM
12769{
12770 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12771 struct remote_state *rs = get_remote_state ();
12772 char *buf = rs->buf;
12773 char *endbuf = rs->buf + get_remote_packet_size ();
12774
4082afcc 12775 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12776 error (_("Target does not support branch tracing."));
12777
12778 set_general_thread (tinfo->ptid);
12779
12780 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12781 putpkt (rs->buf);
12782 getpkt (&rs->buf, &rs->buf_size, 0);
12783
12784 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12785 {
12786 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12787 error (_("Could not disable branch tracing for %s: %s"),
12788 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12789 else
12790 error (_("Could not disable branch tracing for %s."),
12791 target_pid_to_str (tinfo->ptid));
12792 }
12793
12794 xfree (tinfo);
12795}
12796
12797/* Teardown branch tracing. */
12798
12799static void
1777056d
TT
12800remote_teardown_btrace (struct target_ops *self,
12801 struct btrace_target_info *tinfo)
9accd112
MM
12802{
12803 /* We must not talk to the target during teardown. */
12804 xfree (tinfo);
12805}
12806
12807/* Read the branch trace. */
12808
969c39fb 12809static enum btrace_error
39c49f83 12810remote_read_btrace (struct target_ops *self,
734b0e4b 12811 struct btrace_data *btrace,
969c39fb 12812 struct btrace_target_info *tinfo,
9accd112
MM
12813 enum btrace_read_type type)
12814{
12815 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12816 struct remote_state *rs = get_remote_state ();
969c39fb 12817 struct cleanup *cleanup;
9accd112
MM
12818 const char *annex;
12819 char *xml;
12820
4082afcc 12821 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12822 error (_("Target does not support branch tracing."));
12823
12824#if !defined(HAVE_LIBEXPAT)
12825 error (_("Cannot process branch tracing result. XML parsing not supported."));
12826#endif
12827
12828 switch (type)
12829 {
864089d2 12830 case BTRACE_READ_ALL:
9accd112
MM
12831 annex = "all";
12832 break;
864089d2 12833 case BTRACE_READ_NEW:
9accd112
MM
12834 annex = "new";
12835 break;
969c39fb
MM
12836 case BTRACE_READ_DELTA:
12837 annex = "delta";
12838 break;
9accd112
MM
12839 default:
12840 internal_error (__FILE__, __LINE__,
12841 _("Bad branch tracing read type: %u."),
12842 (unsigned int) type);
12843 }
12844
12845 xml = target_read_stralloc (&current_target,
b20a6524 12846 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12847 if (xml == NULL)
12848 return BTRACE_ERR_UNKNOWN;
9accd112 12849
969c39fb 12850 cleanup = make_cleanup (xfree, xml);
734b0e4b 12851 parse_xml_btrace (btrace, xml);
969c39fb 12852 do_cleanups (cleanup);
9accd112 12853
969c39fb 12854 return BTRACE_ERR_NONE;
9accd112
MM
12855}
12856
f4abbc16
MM
12857static const struct btrace_config *
12858remote_btrace_conf (struct target_ops *self,
12859 const struct btrace_target_info *tinfo)
12860{
12861 return &tinfo->conf;
12862}
12863
ced63ec0 12864static int
5436ff03 12865remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12866{
4082afcc
PA
12867 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12868 == PACKET_ENABLE);
ced63ec0
GB
12869}
12870
9dd130a0
TT
12871/* Implementation of to_load. */
12872
12873static void
9cbe5fff 12874remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12875{
12876 generic_load (name, from_tty);
12877}
12878
c78fa86a
GB
12879/* Accepts an integer PID; returns a string representing a file that
12880 can be opened on the remote side to get the symbols for the child
12881 process. Returns NULL if the operation is not supported. */
12882
12883static char *
12884remote_pid_to_exec_file (struct target_ops *self, int pid)
12885{
12886 static char *filename = NULL;
835205d0
GB
12887 struct inferior *inf;
12888 char *annex = NULL;
c78fa86a
GB
12889
12890 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12891 return NULL;
12892
12893 if (filename != NULL)
12894 xfree (filename);
12895
835205d0
GB
12896 inf = find_inferior_pid (pid);
12897 if (inf == NULL)
12898 internal_error (__FILE__, __LINE__,
12899 _("not currently attached to process %d"), pid);
12900
12901 if (!inf->fake_pid_p)
12902 {
12903 const int annex_size = 9;
12904
224c3ddb 12905 annex = (char *) alloca (annex_size);
835205d0
GB
12906 xsnprintf (annex, annex_size, "%x", pid);
12907 }
12908
c78fa86a
GB
12909 filename = target_read_stralloc (&current_target,
12910 TARGET_OBJECT_EXEC_FILE, annex);
12911
12912 return filename;
12913}
12914
750ce8d1
YQ
12915/* Implement the to_can_do_single_step target_ops method. */
12916
12917static int
12918remote_can_do_single_step (struct target_ops *ops)
12919{
12920 /* We can only tell whether target supports single step or not by
12921 supported s and S vCont actions if the stub supports vContSupported
12922 feature. If the stub doesn't support vContSupported feature,
12923 we have conservatively to think target doesn't supports single
12924 step. */
12925 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12926 {
12927 struct remote_state *rs = get_remote_state ();
12928
12929 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12930 remote_vcont_probe (rs);
12931
12932 return rs->supports_vCont.s && rs->supports_vCont.S;
12933 }
12934 else
12935 return 0;
12936}
12937
c906108c 12938static void
fba45db2 12939init_remote_ops (void)
c906108c 12940{
c5aa993b 12941 remote_ops.to_shortname = "remote";
c906108c 12942 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 12943 remote_ops.to_doc =
c906108c 12944 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
12945Specify the serial device it is connected to\n\
12946(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
12947 remote_ops.to_open = remote_open;
12948 remote_ops.to_close = remote_close;
c906108c 12949 remote_ops.to_detach = remote_detach;
6ad8ae5c 12950 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 12951 remote_ops.to_resume = remote_resume;
c906108c
SS
12952 remote_ops.to_wait = remote_wait;
12953 remote_ops.to_fetch_registers = remote_fetch_registers;
12954 remote_ops.to_store_registers = remote_store_registers;
12955 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 12956 remote_ops.to_files_info = remote_files_info;
c906108c
SS
12957 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12958 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
12959 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12960 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12961 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12962 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
12963 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12964 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
12965 remote_ops.to_watchpoint_addr_within_range =
12966 remote_watchpoint_addr_within_range;
3c3bea1c
GS
12967 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12968 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12969 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
12970 remote_ops.to_region_ok_for_hw_watchpoint
12971 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
12972 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12973 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 12974 remote_ops.to_kill = remote_kill;
9dd130a0 12975 remote_ops.to_load = remote_load;
c906108c 12976 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 12977 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 12978 remote_ops.to_program_signals = remote_program_signals;
c906108c 12979 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 12980 remote_ops.to_thread_name = remote_thread_name;
e8032dde 12981 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 12982 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 12983 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 12984 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 12985 remote_ops.to_stop = remote_stop;
bfedc46a 12986 remote_ops.to_interrupt = remote_interrupt;
abc56d60 12987 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
4b8a223f 12988 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 12989 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 12990 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 12991 remote_ops.to_log_command = serial_log_command;
38691318 12992 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 12993 remote_ops.to_stratum = process_stratum;
c35b1492
PA
12994 remote_ops.to_has_all_memory = default_child_has_all_memory;
12995 remote_ops.to_has_memory = default_child_has_memory;
12996 remote_ops.to_has_stack = default_child_has_stack;
12997 remote_ops.to_has_registers = default_child_has_registers;
12998 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 12999 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13000 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13001 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13002 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13003 remote_ops.to_flash_erase = remote_flash_erase;
13004 remote_ops.to_flash_done = remote_flash_done;
29709017 13005 remote_ops.to_read_description = remote_read_description;
08388c79 13006 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13007 remote_ops.to_can_async_p = remote_can_async_p;
13008 remote_ops.to_is_async_p = remote_is_async_p;
13009 remote_ops.to_async = remote_async;
65706a29 13010 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13011 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13012 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13013 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13014 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13015 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13016 remote_ops.to_supports_disable_randomization
13017 = remote_supports_disable_randomization;
4bd7dc42 13018 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13019 remote_ops.to_fileio_open = remote_hostio_open;
13020 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13021 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13022 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13023 remote_ops.to_fileio_close = remote_hostio_close;
13024 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13025 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13026 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13027 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13028 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13029 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13030 remote_ops.to_trace_init = remote_trace_init;
13031 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13032 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13033 remote_ops.to_download_trace_state_variable
13034 = remote_download_trace_state_variable;
d248b706
KY
13035 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13036 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13037 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13038 remote_ops.to_trace_start = remote_trace_start;
13039 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13040 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13041 remote_ops.to_trace_stop = remote_trace_stop;
13042 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13043 remote_ops.to_get_trace_state_variable_value
13044 = remote_get_trace_state_variable_value;
00bf0b85
SS
13045 remote_ops.to_save_trace_data = remote_save_trace_data;
13046 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13047 remote_ops.to_upload_trace_state_variables
13048 = remote_upload_trace_state_variables;
00bf0b85 13049 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13050 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13051 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13052 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13053 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13054 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13055 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13056 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13057 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13058 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13059 remote_ops.to_static_tracepoint_marker_at
13060 = remote_static_tracepoint_marker_at;
13061 remote_ops.to_static_tracepoint_markers_by_strid
13062 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13063 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13064 remote_ops.to_use_agent = remote_use_agent;
13065 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13066 remote_ops.to_supports_btrace = remote_supports_btrace;
13067 remote_ops.to_enable_btrace = remote_enable_btrace;
13068 remote_ops.to_disable_btrace = remote_disable_btrace;
13069 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13070 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13071 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13072 remote_ops.to_augmented_libraries_svr4_read =
13073 remote_augmented_libraries_svr4_read;
c906108c
SS
13074}
13075
13076/* Set up the extended remote vector by making a copy of the standard
13077 remote vector and adding to it. */
13078
13079static void
fba45db2 13080init_extended_remote_ops (void)
c906108c
SS
13081{
13082 extended_remote_ops = remote_ops;
13083
0f71a2f6 13084 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13085 extended_remote_ops.to_longname =
c906108c 13086 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13087 extended_remote_ops.to_doc =
c906108c 13088 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13089Specify the serial device it is connected to (e.g. /dev/ttya).";
13090 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
13091 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13092 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
13093 extended_remote_ops.to_detach = extended_remote_detach;
13094 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13095 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 13096 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
13097 extended_remote_ops.to_supports_disable_randomization
13098 = extended_remote_supports_disable_randomization;
de0d863e 13099 extended_remote_ops.to_follow_fork = remote_follow_fork;
94585166 13100 extended_remote_ops.to_follow_exec = remote_follow_exec;
cbb8991c
DB
13101 extended_remote_ops.to_insert_fork_catchpoint
13102 = remote_insert_fork_catchpoint;
13103 extended_remote_ops.to_remove_fork_catchpoint
13104 = remote_remove_fork_catchpoint;
13105 extended_remote_ops.to_insert_vfork_catchpoint
13106 = remote_insert_vfork_catchpoint;
13107 extended_remote_ops.to_remove_vfork_catchpoint
13108 = remote_remove_vfork_catchpoint;
d46addbb
DB
13109 extended_remote_ops.to_insert_exec_catchpoint
13110 = remote_insert_exec_catchpoint;
13111 extended_remote_ops.to_remove_exec_catchpoint
13112 = remote_remove_exec_catchpoint;
0f71a2f6
JM
13113}
13114
6426a772 13115static int
6a109b6b 13116remote_can_async_p (struct target_ops *ops)
6426a772 13117{
5d93a237
TT
13118 struct remote_state *rs = get_remote_state ();
13119
c6ebd6cf 13120 if (!target_async_permitted)
75c99385
PA
13121 /* We only enable async when the user specifically asks for it. */
13122 return 0;
13123
23860348 13124 /* We're async whenever the serial device is. */
5d93a237 13125 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13126}
13127
13128static int
6a109b6b 13129remote_is_async_p (struct target_ops *ops)
6426a772 13130{
5d93a237
TT
13131 struct remote_state *rs = get_remote_state ();
13132
c6ebd6cf 13133 if (!target_async_permitted)
75c99385
PA
13134 /* We only enable async when the user specifically asks for it. */
13135 return 0;
13136
23860348 13137 /* We're async whenever the serial device is. */
5d93a237 13138 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13139}
13140
2acceee2
JM
13141/* Pass the SERIAL event on and up to the client. One day this code
13142 will be able to delay notifying the client of an event until the
23860348 13143 point where an entire packet has been received. */
2acceee2 13144
2acceee2
JM
13145static serial_event_ftype remote_async_serial_handler;
13146
6426a772 13147static void
819cc324 13148remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13149{
19ba03f4 13150 struct remote_state *rs = (struct remote_state *) context;
88b496c3 13151
2acceee2
JM
13152 /* Don't propogate error information up to the client. Instead let
13153 the client find out about the error by querying the target. */
6a3753b3 13154 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13155}
13156
74531fed
PA
13157static void
13158remote_async_inferior_event_handler (gdb_client_data data)
13159{
13160 inferior_event_handler (INF_REG_EVENT, NULL);
13161}
13162
2acceee2 13163static void
6a3753b3 13164remote_async (struct target_ops *ops, int enable)
2acceee2 13165{
5d93a237
TT
13166 struct remote_state *rs = get_remote_state ();
13167
6a3753b3 13168 if (enable)
2acceee2 13169 {
88b496c3 13170 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13171
13172 /* If there are pending events in the stop reply queue tell the
13173 event loop to process them. */
13174 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13175 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13176 /* For simplicity, below we clear the pending events token
13177 without remembering whether it is marked, so here we always
13178 mark it. If there's actually no pending notification to
13179 process, this ends up being a no-op (other than a spurious
13180 event-loop wakeup). */
13181 if (target_is_non_stop_p ())
13182 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13183 }
13184 else
b7d2e916
PA
13185 {
13186 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13187 /* If the core is disabling async, it doesn't want to be
13188 disturbed with target events. Clear all async event sources
13189 too. */
b7d2e916 13190 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13191 if (target_is_non_stop_p ())
13192 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13193 }
6426a772
JM
13194}
13195
65706a29
PA
13196/* Implementation of the to_thread_events method. */
13197
13198static void
13199remote_thread_events (struct target_ops *ops, int enable)
13200{
13201 struct remote_state *rs = get_remote_state ();
13202 size_t size = get_remote_packet_size ();
13203 char *p = rs->buf;
13204
13205 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13206 return;
13207
13208 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13209 putpkt (rs->buf);
13210 getpkt (&rs->buf, &rs->buf_size, 0);
13211
13212 switch (packet_ok (rs->buf,
13213 &remote_protocol_packets[PACKET_QThreadEvents]))
13214 {
13215 case PACKET_OK:
13216 if (strcmp (rs->buf, "OK") != 0)
13217 error (_("Remote refused setting thread events: %s"), rs->buf);
13218 break;
13219 case PACKET_ERROR:
13220 warning (_("Remote failure reply: %s"), rs->buf);
13221 break;
13222 case PACKET_UNKNOWN:
13223 break;
13224 }
13225}
13226
5a2468f5 13227static void
c2d11a7d 13228set_remote_cmd (char *args, int from_tty)
5a2468f5 13229{
635c7e8a 13230 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13231}
13232
d471ea57
AC
13233static void
13234show_remote_cmd (char *args, int from_tty)
13235{
37a105a1 13236 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13237 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13238 struct cleanup *showlist_chain;
13239 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13240 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13241
13242 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13243 for (; list != NULL; list = list->next)
13244 if (strcmp (list->name, "Z-packet") == 0)
13245 continue;
427c3a89
DJ
13246 else if (list->type == not_set_cmd)
13247 /* Alias commands are exactly like the original, except they
13248 don't have the normal type. */
13249 continue;
13250 else
37a105a1
DJ
13251 {
13252 struct cleanup *option_chain
13253 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13254
37a105a1
DJ
13255 ui_out_field_string (uiout, "name", list->name);
13256 ui_out_text (uiout, ": ");
427c3a89 13257 if (list->type == show_cmd)
5b9afe8a 13258 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
13259 else
13260 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13261 /* Close the tuple. */
13262 do_cleanups (option_chain);
13263 }
427c3a89
DJ
13264
13265 /* Close the tuple. */
13266 do_cleanups (showlist_chain);
d471ea57 13267}
5a2468f5 13268
0f71a2f6 13269
23860348 13270/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13271static void
13272remote_new_objfile (struct objfile *objfile)
13273{
5d93a237
TT
13274 struct remote_state *rs = get_remote_state ();
13275
13276 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13277 remote_check_symbols ();
dc8acb97
MS
13278}
13279
00bf0b85
SS
13280/* Pull all the tracepoints defined on the target and create local
13281 data structures representing them. We don't want to create real
13282 tracepoints yet, we don't want to mess up the user's existing
13283 collection. */
13284
13285static int
ab6617cc 13286remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13287{
00bf0b85
SS
13288 struct remote_state *rs = get_remote_state ();
13289 char *p;
d5551862 13290
00bf0b85
SS
13291 /* Ask for a first packet of tracepoint definition. */
13292 putpkt ("qTfP");
13293 getpkt (&rs->buf, &rs->buf_size, 0);
13294 p = rs->buf;
13295 while (*p && *p != 'l')
d5551862 13296 {
00bf0b85
SS
13297 parse_tracepoint_definition (p, utpp);
13298 /* Ask for another packet of tracepoint definition. */
13299 putpkt ("qTsP");
13300 getpkt (&rs->buf, &rs->buf_size, 0);
13301 p = rs->buf;
d5551862 13302 }
00bf0b85 13303 return 0;
d5551862
SS
13304}
13305
00bf0b85 13306static int
181e3713
TT
13307remote_upload_trace_state_variables (struct target_ops *self,
13308 struct uploaded_tsv **utsvp)
d5551862 13309{
00bf0b85 13310 struct remote_state *rs = get_remote_state ();
d5551862 13311 char *p;
d5551862 13312
00bf0b85
SS
13313 /* Ask for a first packet of variable definition. */
13314 putpkt ("qTfV");
d5551862
SS
13315 getpkt (&rs->buf, &rs->buf_size, 0);
13316 p = rs->buf;
00bf0b85 13317 while (*p && *p != 'l')
d5551862 13318 {
00bf0b85
SS
13319 parse_tsv_definition (p, utsvp);
13320 /* Ask for another packet of variable definition. */
13321 putpkt ("qTsV");
d5551862
SS
13322 getpkt (&rs->buf, &rs->buf_size, 0);
13323 p = rs->buf;
13324 }
00bf0b85 13325 return 0;
d5551862
SS
13326}
13327
c1e36e3e
PA
13328/* The "set/show range-stepping" show hook. */
13329
13330static void
13331show_range_stepping (struct ui_file *file, int from_tty,
13332 struct cmd_list_element *c,
13333 const char *value)
13334{
13335 fprintf_filtered (file,
13336 _("Debugger's willingness to use range stepping "
13337 "is %s.\n"), value);
13338}
13339
13340/* The "set/show range-stepping" set hook. */
13341
13342static void
13343set_range_stepping (char *ignore_args, int from_tty,
13344 struct cmd_list_element *c)
13345{
5d93a237
TT
13346 struct remote_state *rs = get_remote_state ();
13347
c1e36e3e
PA
13348 /* Whene enabling, check whether range stepping is actually
13349 supported by the target, and warn if not. */
13350 if (use_range_stepping)
13351 {
5d93a237 13352 if (rs->remote_desc != NULL)
c1e36e3e 13353 {
4082afcc 13354 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13355 remote_vcont_probe (rs);
13356
4082afcc 13357 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13358 && rs->supports_vCont.r)
13359 return;
13360 }
13361
13362 warning (_("Range stepping is not supported by the current target"));
13363 }
13364}
13365
c906108c 13366void
fba45db2 13367_initialize_remote (void)
c906108c 13368{
ea9c271d 13369 struct remote_state *rs;
9a7071a8 13370 struct cmd_list_element *cmd;
6f937416 13371 const char *cmd_name;
ea9c271d 13372
0f71a2f6 13373 /* architecture specific data */
2bc416ba 13374 remote_gdbarch_data_handle =
23860348 13375 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13376 remote_g_packet_data_handle =
13377 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13378
94585166
DB
13379 remote_pspace_data
13380 = register_program_space_data_with_cleanup (NULL,
13381 remote_pspace_data_cleanup);
13382
ea9c271d
DJ
13383 /* Initialize the per-target state. At the moment there is only one
13384 of these, not one per target. Only one target is active at a
cf792862
TT
13385 time. */
13386 remote_state = new_remote_state ();
ea9c271d 13387
c906108c
SS
13388 init_remote_ops ();
13389 add_target (&remote_ops);
13390
13391 init_extended_remote_ops ();
13392 add_target (&extended_remote_ops);
cce74817 13393
dc8acb97 13394 /* Hook into new objfile notification. */
06d3b283 13395 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13396 /* We're no longer interested in notification events of an inferior
13397 when it exits. */
13398 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13399
b803fb0f 13400 /* Set up signal handlers. */
934b9bac 13401 async_sigint_remote_token =
b803fb0f 13402 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 13403 async_sigint_remote_twice_token =
6d549500 13404 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 13405
c906108c
SS
13406#if 0
13407 init_remote_threadtests ();
13408#endif
13409
722247f1 13410 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13411 /* set/show remote ... */
d471ea57 13412
1bedd215 13413 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13414Remote protocol specific variables\n\
13415Configure various remote-protocol specific variables such as\n\
1bedd215 13416the packets being used"),
cff3e48b 13417 &remote_set_cmdlist, "set remote ",
23860348 13418 0 /* allow-unknown */, &setlist);
1bedd215 13419 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13420Remote protocol specific variables\n\
13421Configure various remote-protocol specific variables such as\n\
1bedd215 13422the packets being used"),
cff3e48b 13423 &remote_show_cmdlist, "show remote ",
23860348 13424 0 /* allow-unknown */, &showlist);
5a2468f5 13425
1a966eab
AC
13426 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13427Compare section data on target to the exec file.\n\
95cf3b38
DT
13428Argument is a single section name (default: all loaded sections).\n\
13429To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13430 &cmdlist);
13431
1a966eab
AC
13432 add_cmd ("packet", class_maintenance, packet_command, _("\
13433Send an arbitrary packet to a remote target.\n\
c906108c
SS
13434 maintenance packet TEXT\n\
13435If GDB is talking to an inferior via the GDB serial protocol, then\n\
13436this command sends the string TEXT to the inferior, and displays the\n\
13437response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13438terminating `#' character and checksum."),
c906108c
SS
13439 &maintenancelist);
13440
7915a72c
AC
13441 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13442Set whether to send break if interrupted."), _("\
13443Show whether to send break if interrupted."), _("\
13444If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13445 set_remotebreak, show_remotebreak,
e707bbc2 13446 &setlist, &showlist);
9a7071a8
JB
13447 cmd_name = "remotebreak";
13448 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13449 deprecate_cmd (cmd, "set remote interrupt-sequence");
13450 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13451 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13452 deprecate_cmd (cmd, "show remote interrupt-sequence");
13453
13454 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13455 interrupt_sequence_modes, &interrupt_sequence_mode,
13456 _("\
9a7071a8
JB
13457Set interrupt sequence to remote target."), _("\
13458Show interrupt sequence to remote target."), _("\
13459Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13460 NULL, show_interrupt_sequence,
13461 &remote_set_cmdlist,
13462 &remote_show_cmdlist);
13463
13464 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13465 &interrupt_on_connect, _("\
13466Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13467Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13468If set, interrupt sequence is sent to remote target."),
13469 NULL, NULL,
13470 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13471
23860348 13472 /* Install commands for configuring memory read/write packets. */
11cf8741 13473
1a966eab
AC
13474 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13475Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13476 &setlist);
1a966eab
AC
13477 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13478Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13479 &showlist);
13480 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13481 set_memory_write_packet_size, _("\
13482Set the maximum number of bytes per memory-write packet.\n\
13483Specify the number of bytes in a packet or 0 (zero) for the\n\
13484default packet size. The actual limit is further reduced\n\
13485dependent on the target. Specify ``fixed'' to disable the\n\
13486further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13487 &remote_set_cmdlist);
13488 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13489 set_memory_read_packet_size, _("\
13490Set the maximum number of bytes per memory-read packet.\n\
13491Specify the number of bytes in a packet or 0 (zero) for the\n\
13492default packet size. The actual limit is further reduced\n\
13493dependent on the target. Specify ``fixed'' to disable the\n\
13494further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13495 &remote_set_cmdlist);
13496 add_cmd ("memory-write-packet-size", no_class,
13497 show_memory_write_packet_size,
1a966eab 13498 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13499 &remote_show_cmdlist);
13500 add_cmd ("memory-read-packet-size", no_class,
13501 show_memory_read_packet_size,
1a966eab 13502 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13503 &remote_show_cmdlist);
c906108c 13504
b3f42336 13505 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13506 &remote_hw_watchpoint_limit, _("\
13507Set the maximum number of target hardware watchpoints."), _("\
13508Show the maximum number of target hardware watchpoints."), _("\
13509Specify a negative limit for unlimited."),
3e43a32a
MS
13510 NULL, NULL, /* FIXME: i18n: The maximum
13511 number of target hardware
13512 watchpoints is %s. */
b3f42336 13513 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13514 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13515 &remote_hw_watchpoint_length_limit, _("\
13516Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13517Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13518Specify a negative limit for unlimited."),
13519 NULL, NULL, /* FIXME: i18n: The maximum
13520 length (in bytes) of a target
13521 hardware watchpoint is %s. */
13522 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13523 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13524 &remote_hw_breakpoint_limit, _("\
13525Set the maximum number of target hardware breakpoints."), _("\
13526Show the maximum number of target hardware breakpoints."), _("\
13527Specify a negative limit for unlimited."),
3e43a32a
MS
13528 NULL, NULL, /* FIXME: i18n: The maximum
13529 number of target hardware
13530 breakpoints is %s. */
b3f42336 13531 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13532
1b493192
PA
13533 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13534 &remote_address_size, _("\
4d28ad1e
AC
13535Set the maximum size of the address (in bits) in a memory packet."), _("\
13536Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13537 NULL,
13538 NULL, /* FIXME: i18n: */
13539 &setlist, &showlist);
c906108c 13540
ca4f7f8b
PA
13541 init_all_packet_configs ();
13542
444abaca 13543 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13544 "X", "binary-download", 1);
0f71a2f6 13545
444abaca 13546 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13547 "vCont", "verbose-resume", 0);
506fb367 13548
89be2091
DJ
13549 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13550 "QPassSignals", "pass-signals", 0);
13551
9b224c5e
PA
13552 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13553 "QProgramSignals", "program-signals", 0);
13554
444abaca 13555 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13556 "qSymbol", "symbol-lookup", 0);
dc8acb97 13557
444abaca 13558 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13559 "P", "set-register", 1);
d471ea57 13560
444abaca 13561 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13562 "p", "fetch-register", 1);
b96ec7ac 13563
444abaca 13564 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13565 "Z0", "software-breakpoint", 0);
d471ea57 13566
444abaca 13567 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13568 "Z1", "hardware-breakpoint", 0);
d471ea57 13569
444abaca 13570 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13571 "Z2", "write-watchpoint", 0);
d471ea57 13572
444abaca 13573 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13574 "Z3", "read-watchpoint", 0);
d471ea57 13575
444abaca 13576 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13577 "Z4", "access-watchpoint", 0);
d471ea57 13578
0876f84a
DJ
13579 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13580 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13581
c78fa86a
GB
13582 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13583 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13584
23181151
DJ
13585 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13586 "qXfer:features:read", "target-features", 0);
13587
cfa9d6d9
DJ
13588 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13589 "qXfer:libraries:read", "library-info", 0);
13590
2268b414
JK
13591 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13592 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13593
fd79ecee
DJ
13594 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13595 "qXfer:memory-map:read", "memory-map", 0);
13596
0e7f50da
UW
13597 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13598 "qXfer:spu:read", "read-spu-object", 0);
13599
13600 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13601 "qXfer:spu:write", "write-spu-object", 0);
13602
07e059b5
VP
13603 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13604 "qXfer:osdata:read", "osdata", 0);
13605
dc146f7c
VP
13606 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13607 "qXfer:threads:read", "threads", 0);
13608
4aa995e1
PA
13609 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13610 "qXfer:siginfo:read", "read-siginfo-object", 0);
13611
13612 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13613 "qXfer:siginfo:write", "write-siginfo-object", 0);
13614
b3b9301e
PA
13615 add_packet_config_cmd
13616 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13617 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13618
169081d0
TG
13619 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13620 "qXfer:uib:read", "unwind-info-block", 0);
13621
444abaca 13622 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13623 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13624 0);
13625
711e434b
PM
13626 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13627 "qGetTIBAddr", "get-thread-information-block-address",
13628 0);
13629
40ab02ce
MS
13630 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13631 "bc", "reverse-continue", 0);
13632
13633 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13634 "bs", "reverse-step", 0);
13635
be2a5f71
DJ
13636 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13637 "qSupported", "supported-packets", 0);
13638
08388c79
DE
13639 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13640 "qSearch:memory", "search-memory", 0);
13641
bd3eecc3
PA
13642 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13643 "qTStatus", "trace-status", 0);
13644
15a201c8
GB
13645 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13646 "vFile:setfs", "hostio-setfs", 0);
13647
a6b151f1
DJ
13648 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13649 "vFile:open", "hostio-open", 0);
13650
13651 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13652 "vFile:pread", "hostio-pread", 0);
13653
13654 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13655 "vFile:pwrite", "hostio-pwrite", 0);
13656
13657 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13658 "vFile:close", "hostio-close", 0);
13659
13660 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13661 "vFile:unlink", "hostio-unlink", 0);
13662
b9e7b9c3
UW
13663 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13664 "vFile:readlink", "hostio-readlink", 0);
13665
0a93529c
GB
13666 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13667 "vFile:fstat", "hostio-fstat", 0);
13668
2d717e4f
DJ
13669 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13670 "vAttach", "attach", 0);
13671
13672 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13673 "vRun", "run", 0);
13674
a6f3e723
SL
13675 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13676 "QStartNoAckMode", "noack", 0);
13677
82f73884
PA
13678 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13679 "vKill", "kill", 0);
13680
0b16c5cf
PA
13681 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13682 "qAttached", "query-attached", 0);
13683
782b2b07 13684 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13685 "ConditionalTracepoints",
13686 "conditional-tracepoints", 0);
3788aec7
LM
13687
13688 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13689 "ConditionalBreakpoints",
13690 "conditional-breakpoints", 0);
13691
d3ce09f5
SS
13692 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13693 "BreakpointCommands",
13694 "breakpoint-commands", 0);
13695
7a697b8d
SS
13696 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13697 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13698
409873ef
SS
13699 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13700 "TracepointSource", "TracepointSource", 0);
13701
d914c394
SS
13702 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13703 "QAllow", "allow", 0);
13704
0fb4aa4b
PA
13705 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13706 "StaticTracepoints", "static-tracepoints", 0);
13707
1e4d1764
YQ
13708 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13709 "InstallInTrace", "install-in-trace", 0);
13710
0fb4aa4b
PA
13711 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13712 "qXfer:statictrace:read", "read-sdata-object", 0);
13713
78d85199
YQ
13714 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13715 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13716
03583c20
UW
13717 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13718 "QDisableRandomization", "disable-randomization", 0);
13719
d1feda86
YQ
13720 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13721 "QAgent", "agent", 0);
13722
f6f899bf
HAQ
13723 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13724 "QTBuffer:size", "trace-buffer-size", 0);
13725
9accd112
MM
13726 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13727 "Qbtrace:off", "disable-btrace", 0);
13728
13729 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13730 "Qbtrace:bts", "enable-btrace-bts", 0);
13731
13732 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13733 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13734
13735 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13736 "qXfer:btrace", "read-btrace", 0);
13737
f4abbc16
MM
13738 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13739 "qXfer:btrace-conf", "read-btrace-conf", 0);
13740
d33501a5
MM
13741 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13742 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13743
73b8c1fd
PA
13744 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13745 "multiprocess-feature", "multiprocess-feature", 0);
13746
f7e6eed5
PA
13747 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13748 "swbreak-feature", "swbreak-feature", 0);
13749
13750 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13751 "hwbreak-feature", "hwbreak-feature", 0);
13752
89245bc0
DB
13753 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13754 "fork-event-feature", "fork-event-feature", 0);
13755
13756 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13757 "vfork-event-feature", "vfork-event-feature", 0);
13758
b20a6524
MM
13759 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13760 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13761
750ce8d1
YQ
13762 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13763 "vContSupported", "verbose-resume-supported", 0);
13764
94585166
DB
13765 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13766 "exec-event-feature", "exec-event-feature", 0);
13767
de979965
PA
13768 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13769 "vCtrlC", "ctrl-c", 0);
13770
65706a29
PA
13771 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13772 "QThreadEvents", "thread-events", 0);
13773
f2faf941
PA
13774 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13775 "N stop reply", "no-resumed-stop-reply", 0);
13776
0b736949
DB
13777 /* Assert that we've registered "set remote foo-packet" commands
13778 for all packet configs. */
ca4f7f8b
PA
13779 {
13780 int i;
13781
13782 for (i = 0; i < PACKET_MAX; i++)
13783 {
13784 /* Ideally all configs would have a command associated. Some
13785 still don't though. */
13786 int excepted;
13787
13788 switch (i)
13789 {
13790 case PACKET_QNonStop:
ca4f7f8b
PA
13791 case PACKET_EnableDisableTracepoints_feature:
13792 case PACKET_tracenz_feature:
13793 case PACKET_DisconnectedTracing_feature:
13794 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13795 case PACKET_qCRC:
13796 /* Additions to this list need to be well justified:
13797 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13798 excepted = 1;
13799 break;
13800 default:
13801 excepted = 0;
13802 break;
13803 }
13804
13805 /* This catches both forgetting to add a config command, and
13806 forgetting to remove a packet from the exception list. */
13807 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13808 }
13809 }
13810
37a105a1
DJ
13811 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13812 Z sub-packet has its own set and show commands, but users may
13813 have sets to this variable in their .gdbinit files (or in their
13814 documentation). */
e9e68a56 13815 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13816 &remote_Z_packet_detect, _("\
13817Set use of remote protocol `Z' packets"), _("\
13818Show use of remote protocol `Z' packets "), _("\
3b64bf98 13819When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13820packets."),
e9e68a56 13821 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13822 show_remote_protocol_Z_packet_cmd,
13823 /* FIXME: i18n: Use of remote protocol
13824 `Z' packets is %s. */
e9e68a56 13825 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13826
a6b151f1
DJ
13827 add_prefix_cmd ("remote", class_files, remote_command, _("\
13828Manipulate files on the remote system\n\
13829Transfer files to and from the remote target system."),
13830 &remote_cmdlist, "remote ",
13831 0 /* allow-unknown */, &cmdlist);
13832
13833 add_cmd ("put", class_files, remote_put_command,
13834 _("Copy a local file to the remote system."),
13835 &remote_cmdlist);
13836
13837 add_cmd ("get", class_files, remote_get_command,
13838 _("Copy a remote file to the local system."),
13839 &remote_cmdlist);
13840
13841 add_cmd ("delete", class_files, remote_delete_command,
13842 _("Delete a remote file."),
13843 &remote_cmdlist);
13844
2d717e4f 13845 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13846 &remote_exec_file_var, _("\
2d717e4f 13847Set the remote pathname for \"run\""), _("\
94585166
DB
13848Show the remote pathname for \"run\""), NULL,
13849 set_remote_exec_file,
13850 show_remote_exec_file,
13851 &remote_set_cmdlist,
13852 &remote_show_cmdlist);
2d717e4f 13853
c1e36e3e
PA
13854 add_setshow_boolean_cmd ("range-stepping", class_run,
13855 &use_range_stepping, _("\
13856Enable or disable range stepping."), _("\
13857Show whether target-assisted range stepping is enabled."), _("\
13858If on, and the target supports it, when stepping a source line, GDB\n\
13859tells the target to step the corresponding range of addresses itself instead\n\
13860of issuing multiple single-steps. This speeds up source level\n\
13861stepping. If off, GDB always issues single-steps, even if range\n\
13862stepping is supported by the target. The default is on."),
13863 set_range_stepping,
13864 show_range_stepping,
13865 &setlist,
13866 &showlist);
13867
449092f6
CV
13868 /* Eventually initialize fileio. See fileio.c */
13869 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13870
ba348170 13871 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13872 special ptids with it set to != 0. */
ba348170
PA
13873 magic_null_ptid = ptid_build (42000, -1, 1);
13874 not_sent_ptid = ptid_build (42000, -2, 1);
13875 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13876
13877 target_buf_size = 2048;
224c3ddb 13878 target_buf = (char *) xmalloc (target_buf_size);
c906108c 13879}
10760264 13880
This page took 3.903242 seconds and 4 git commands to generate.