infrun: Fix TARGET_WAITKIND_NO_RESUMED handling in non-stop mode
[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
444abaca
DJ
1491 PACKET_MAX
1492};
506fb367 1493
444abaca 1494static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1495
f7e6eed5
PA
1496/* Returns the packet's corresponding "set remote foo-packet" command
1497 state. See struct packet_config for more details. */
1498
1499static enum auto_boolean
1500packet_set_cmd_state (int packet)
1501{
1502 return remote_protocol_packets[packet].detect;
1503}
1504
4082afcc
PA
1505/* Returns whether a given packet or feature is supported. This takes
1506 into account the state of the corresponding "set remote foo-packet"
1507 command, which may be used to bypass auto-detection. */
dc8acb97 1508
4082afcc
PA
1509static enum packet_support
1510packet_config_support (struct packet_config *config)
1511{
1512 switch (config->detect)
444abaca 1513 {
4082afcc
PA
1514 case AUTO_BOOLEAN_TRUE:
1515 return PACKET_ENABLE;
1516 case AUTO_BOOLEAN_FALSE:
1517 return PACKET_DISABLE;
1518 case AUTO_BOOLEAN_AUTO:
1519 return config->support;
1520 default:
1521 gdb_assert_not_reached (_("bad switch"));
444abaca 1522 }
4082afcc
PA
1523}
1524
1525/* Same as packet_config_support, but takes the packet's enum value as
1526 argument. */
1527
1528static enum packet_support
1529packet_support (int packet)
1530{
1531 struct packet_config *config = &remote_protocol_packets[packet];
1532
1533 return packet_config_support (config);
dc8acb97
MS
1534}
1535
5a2468f5 1536static void
444abaca
DJ
1537show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1538 struct cmd_list_element *c,
1539 const char *value)
5a2468f5 1540{
444abaca 1541 struct packet_config *packet;
5a2468f5 1542
444abaca
DJ
1543 for (packet = remote_protocol_packets;
1544 packet < &remote_protocol_packets[PACKET_MAX];
1545 packet++)
1546 {
1547 if (&packet->detect == c->var)
1548 {
1549 show_packet_config_cmd (packet);
1550 return;
1551 }
1552 }
9b20d036 1553 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1554 c->name);
5a2468f5
JM
1555}
1556
d471ea57
AC
1557/* Should we try one of the 'Z' requests? */
1558
1559enum Z_packet_type
1560{
1561 Z_PACKET_SOFTWARE_BP,
1562 Z_PACKET_HARDWARE_BP,
1563 Z_PACKET_WRITE_WP,
1564 Z_PACKET_READ_WP,
1565 Z_PACKET_ACCESS_WP,
1566 NR_Z_PACKET_TYPES
1567};
96baa820 1568
d471ea57 1569/* For compatibility with older distributions. Provide a ``set remote
23860348 1570 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1571
7f19b9a2 1572static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1573
1574static void
fba45db2
KB
1575set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1576 struct cmd_list_element *c)
96baa820 1577{
d471ea57 1578 int i;
a744cf53 1579
d471ea57 1580 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1581 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1582}
1583
1584static void
08546159
AC
1585show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1586 struct cmd_list_element *c,
1587 const char *value)
96baa820 1588{
d471ea57 1589 int i;
a744cf53 1590
d471ea57
AC
1591 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1592 {
444abaca 1593 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1594 }
96baa820
JM
1595}
1596
4082afcc
PA
1597/* Returns true if the multi-process extensions are in effect. */
1598
1599static int
1600remote_multi_process_p (struct remote_state *rs)
1601{
1602 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1603}
1604
de0d863e
DB
1605/* Returns true if fork events are supported. */
1606
1607static int
1608remote_fork_event_p (struct remote_state *rs)
1609{
1610 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1611}
1612
c269dbdb
DB
1613/* Returns true if vfork events are supported. */
1614
1615static int
1616remote_vfork_event_p (struct remote_state *rs)
1617{
1618 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1619}
1620
d46addbb
DB
1621/* Returns true if exec events are supported. */
1622
1623static int
1624remote_exec_event_p (struct remote_state *rs)
1625{
1626 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1627}
1628
cbb8991c
DB
1629/* Insert fork catchpoint target routine. If fork events are enabled
1630 then return success, nothing more to do. */
1631
1632static int
1633remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1634{
1635 struct remote_state *rs = get_remote_state ();
1636
1637 return !remote_fork_event_p (rs);
1638}
1639
1640/* Remove fork catchpoint target routine. Nothing to do, just
1641 return success. */
1642
1643static int
1644remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1645{
1646 return 0;
1647}
1648
1649/* Insert vfork catchpoint target routine. If vfork events are enabled
1650 then return success, nothing more to do. */
1651
1652static int
1653remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1654{
1655 struct remote_state *rs = get_remote_state ();
1656
1657 return !remote_vfork_event_p (rs);
1658}
1659
1660/* Remove vfork catchpoint target routine. Nothing to do, just
1661 return success. */
1662
1663static int
1664remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1665{
1666 return 0;
1667}
1668
d46addbb
DB
1669/* Insert exec catchpoint target routine. If exec events are
1670 enabled, just return success. */
1671
1672static int
1673remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1674{
1675 struct remote_state *rs = get_remote_state ();
1676
1677 return !remote_exec_event_p (rs);
1678}
1679
1680/* Remove exec catchpoint target routine. Nothing to do, just
1681 return success. */
1682
1683static int
1684remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1685{
1686 return 0;
1687}
1688
23860348 1689/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1690static struct async_signal_handler *async_sigint_remote_twice_token;
1691static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1692
74531fed
PA
1693\f
1694/* Asynchronous signal handle registered as event loop source for
1695 when we have pending events ready to be passed to the core. */
1696
1697static struct async_event_handler *remote_async_inferior_event_token;
1698
c906108c
SS
1699\f
1700
79d7f229
PA
1701static ptid_t magic_null_ptid;
1702static ptid_t not_sent_ptid;
1703static ptid_t any_thread_ptid;
1704
0b16c5cf
PA
1705/* Find out if the stub attached to PID (and hence GDB should offer to
1706 detach instead of killing it when bailing out). */
1707
1708static int
1709remote_query_attached (int pid)
1710{
1711 struct remote_state *rs = get_remote_state ();
bba74b36 1712 size_t size = get_remote_packet_size ();
0b16c5cf 1713
4082afcc 1714 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1715 return 0;
1716
1717 if (remote_multi_process_p (rs))
bba74b36 1718 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1719 else
bba74b36 1720 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1721
1722 putpkt (rs->buf);
1723 getpkt (&rs->buf, &rs->buf_size, 0);
1724
1725 switch (packet_ok (rs->buf,
1554e9be 1726 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1727 {
1728 case PACKET_OK:
1729 if (strcmp (rs->buf, "1") == 0)
1730 return 1;
1731 break;
1732 case PACKET_ERROR:
1733 warning (_("Remote failure reply: %s"), rs->buf);
1734 break;
1735 case PACKET_UNKNOWN:
1736 break;
1737 }
1738
1739 return 0;
1740}
1741
49c62f2e
PA
1742/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1743 has been invented by GDB, instead of reported by the target. Since
1744 we can be connected to a remote system before before knowing about
1745 any inferior, mark the target with execution when we find the first
1746 inferior. If ATTACHED is 1, then we had just attached to this
1747 inferior. If it is 0, then we just created this inferior. If it
1748 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1749 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1750 attempt to open this inferior's executable as the main executable
1751 if no main executable is open already. */
1941c569
PA
1752
1753static struct inferior *
1b6e6f5c
GB
1754remote_add_inferior (int fake_pid_p, int pid, int attached,
1755 int try_open_exec)
1941c569 1756{
1941c569
PA
1757 struct inferior *inf;
1758
0b16c5cf
PA
1759 /* Check whether this process we're learning about is to be
1760 considered attached, or if is to be considered to have been
1761 spawned by the stub. */
1762 if (attached == -1)
1763 attached = remote_query_attached (pid);
1764
f5656ead 1765 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1766 {
1767 /* If the target shares code across all inferiors, then every
1768 attach adds a new inferior. */
1769 inf = add_inferior (pid);
1770
1771 /* ... and every inferior is bound to the same program space.
1772 However, each inferior may still have its own address
1773 space. */
1774 inf->aspace = maybe_new_address_space ();
1775 inf->pspace = current_program_space;
1776 }
1777 else
1778 {
1779 /* In the traditional debugging scenario, there's a 1-1 match
1780 between program/address spaces. We simply bind the inferior
1781 to the program space's address space. */
1782 inf = current_inferior ();
1783 inferior_appeared (inf, pid);
1784 }
1941c569 1785
0b16c5cf 1786 inf->attach_flag = attached;
49c62f2e 1787 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1788
1b6e6f5c
GB
1789 /* If no main executable is currently open then attempt to
1790 open the file that was executed to create this inferior. */
835205d0 1791 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1792 exec_file_locate_attach (pid, 1);
1793
1941c569
PA
1794 return inf;
1795}
1796
1797/* Add thread PTID to GDB's thread list. Tag it as executing/running
1798 according to RUNNING. */
1799
c906108c 1800static void
1941c569 1801remote_add_thread (ptid_t ptid, int running)
c906108c 1802{
b7ea362b
PA
1803 struct remote_state *rs = get_remote_state ();
1804
1805 /* GDB historically didn't pull threads in the initial connection
1806 setup. If the remote target doesn't even have a concept of
1807 threads (e.g., a bare-metal target), even if internally we
1808 consider that a single-threaded target, mentioning a new thread
1809 might be confusing to the user. Be silent then, preserving the
1810 age old behavior. */
1811 if (rs->starting_up)
1812 add_thread_silent (ptid);
1813 else
1814 add_thread (ptid);
1941c569
PA
1815
1816 set_executing (ptid, running);
1817 set_running (ptid, running);
1818}
1819
1820/* Come here when we learn about a thread id from the remote target.
1821 It may be the first time we hear about such thread, so take the
1822 opportunity to add it to GDB's thread list. In case this is the
1823 first time we're noticing its corresponding inferior, add it to
1824 GDB's inferior list as well. */
1825
1826static void
1827remote_notice_new_inferior (ptid_t currthread, int running)
1828{
c906108c
SS
1829 /* If this is a new thread, add it to GDB's thread list.
1830 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1831
1832 if (in_thread_list (currthread) && is_exited (currthread))
1833 {
1834 /* We're seeing an event on a thread id we knew had exited.
1835 This has to be a new thread reusing the old id. Add it. */
1941c569 1836 remote_add_thread (currthread, running);
82f73884
PA
1837 return;
1838 }
1839
79d7f229 1840 if (!in_thread_list (currthread))
c0a2216e 1841 {
1941c569 1842 struct inferior *inf = NULL;
bad34192 1843 int pid = ptid_get_pid (currthread);
1941c569 1844
bad34192
PA
1845 if (ptid_is_pid (inferior_ptid)
1846 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1847 {
1848 /* inferior_ptid has no thread member yet. This can happen
1849 with the vAttach -> remote_wait,"TAAthread:" path if the
1850 stub doesn't support qC. This is the first stop reported
1851 after an attach, so this is the main thread. Update the
1852 ptid in the thread list. */
bad34192
PA
1853 if (in_thread_list (pid_to_ptid (pid)))
1854 thread_change_ptid (inferior_ptid, currthread);
1855 else
1856 {
1857 remote_add_thread (currthread, running);
1858 inferior_ptid = currthread;
1859 }
dc146f7c 1860 return;
c0a2216e 1861 }
82f73884
PA
1862
1863 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1864 {
1865 /* inferior_ptid is not set yet. This can happen with the
1866 vRun -> remote_wait,"TAAthread:" path if the stub
1867 doesn't support qC. This is the first stop reported
1868 after an attach, so this is the main thread. Update the
1869 ptid in the thread list. */
dc146f7c 1870 thread_change_ptid (inferior_ptid, currthread);
82f73884 1871 return;
c0a2216e 1872 }
82f73884 1873
29c87f7f
PA
1874 /* When connecting to a target remote, or to a target
1875 extended-remote which already was debugging an inferior, we
1876 may not know about it yet. Add it before adding its child
1877 thread, so notifications are emitted in a sensible order. */
1878 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1879 {
1880 struct remote_state *rs = get_remote_state ();
1881 int fake_pid_p = !remote_multi_process_p (rs);
1882
1883 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1884 ptid_get_pid (currthread), -1, 1);
49c62f2e 1885 }
29c87f7f 1886
82f73884 1887 /* This is really a new thread. Add it. */
1941c569
PA
1888 remote_add_thread (currthread, running);
1889
1890 /* If we found a new inferior, let the common code do whatever
1891 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1892 breakpoints), unless we're just setting up an all-stop
1893 connection. */
1941c569 1894 if (inf != NULL)
b7ea362b
PA
1895 {
1896 struct remote_state *rs = get_remote_state ();
1897
6efcd9a8 1898 if (!rs->starting_up)
b7ea362b
PA
1899 notice_new_inferior (currthread, running, 0);
1900 }
c0a2216e 1901 }
c906108c
SS
1902}
1903
dc146f7c
VP
1904/* Return the private thread data, creating it if necessary. */
1905
70221824 1906static struct private_thread_info *
dc146f7c
VP
1907demand_private_info (ptid_t ptid)
1908{
1909 struct thread_info *info = find_thread_ptid (ptid);
1910
1911 gdb_assert (info);
1912
fe978cb0 1913 if (!info->priv)
dc146f7c 1914 {
8d749320 1915 info->priv = XNEW (struct private_thread_info);
dc146f7c 1916 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1917 info->priv->core = -1;
1918 info->priv->extra = 0;
dc146f7c
VP
1919 }
1920
fe978cb0 1921 return info->priv;
dc146f7c
VP
1922}
1923
74531fed
PA
1924/* Call this function as a result of
1925 1) A halt indication (T packet) containing a thread id
1926 2) A direct query of currthread
0df8b418 1927 3) Successful execution of set thread */
74531fed
PA
1928
1929static void
47f8a51d 1930record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1931{
47f8a51d 1932 rs->general_thread = currthread;
74531fed
PA
1933}
1934
89be2091
DJ
1935/* If 'QPassSignals' is supported, tell the remote stub what signals
1936 it can simply pass through to the inferior without reporting. */
1937
1938static void
94bedb42
TT
1939remote_pass_signals (struct target_ops *self,
1940 int numsigs, unsigned char *pass_signals)
89be2091 1941{
4082afcc 1942 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1943 {
1944 char *pass_packet, *p;
89be2091 1945 int count = 0, i;
747dc59d 1946 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1947
1948 gdb_assert (numsigs < 256);
1949 for (i = 0; i < numsigs; i++)
1950 {
2455069d 1951 if (pass_signals[i])
89be2091
DJ
1952 count++;
1953 }
224c3ddb 1954 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
1955 strcpy (pass_packet, "QPassSignals:");
1956 p = pass_packet + strlen (pass_packet);
1957 for (i = 0; i < numsigs; i++)
1958 {
2455069d 1959 if (pass_signals[i])
89be2091
DJ
1960 {
1961 if (i >= 16)
1962 *p++ = tohex (i >> 4);
1963 *p++ = tohex (i & 15);
1964 if (count)
1965 *p++ = ';';
1966 else
1967 break;
1968 count--;
1969 }
1970 }
1971 *p = 0;
747dc59d 1972 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1973 {
89be2091
DJ
1974 putpkt (pass_packet);
1975 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1976 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1977 if (rs->last_pass_packet)
1978 xfree (rs->last_pass_packet);
1979 rs->last_pass_packet = pass_packet;
89be2091
DJ
1980 }
1981 else
1982 xfree (pass_packet);
1983 }
1984}
1985
9b224c5e
PA
1986/* If 'QProgramSignals' is supported, tell the remote stub what
1987 signals it should pass through to the inferior when detaching. */
1988
1989static void
daf5e9b6
TT
1990remote_program_signals (struct target_ops *self,
1991 int numsigs, unsigned char *signals)
9b224c5e 1992{
4082afcc 1993 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1994 {
1995 char *packet, *p;
1996 int count = 0, i;
5e4a05c4 1997 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1998
1999 gdb_assert (numsigs < 256);
2000 for (i = 0; i < numsigs; i++)
2001 {
2002 if (signals[i])
2003 count++;
2004 }
224c3ddb 2005 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2006 strcpy (packet, "QProgramSignals:");
2007 p = packet + strlen (packet);
2008 for (i = 0; i < numsigs; i++)
2009 {
2010 if (signal_pass_state (i))
2011 {
2012 if (i >= 16)
2013 *p++ = tohex (i >> 4);
2014 *p++ = tohex (i & 15);
2015 if (count)
2016 *p++ = ';';
2017 else
2018 break;
2019 count--;
2020 }
2021 }
2022 *p = 0;
5e4a05c4
TT
2023 if (!rs->last_program_signals_packet
2024 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2025 {
9b224c5e
PA
2026 putpkt (packet);
2027 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2028 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2029 xfree (rs->last_program_signals_packet);
2030 rs->last_program_signals_packet = packet;
9b224c5e
PA
2031 }
2032 else
2033 xfree (packet);
2034 }
2035}
2036
79d7f229
PA
2037/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2038 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2039 thread. If GEN is set, set the general thread, if not, then set
2040 the step/continue thread. */
c906108c 2041static void
79d7f229 2042set_thread (struct ptid ptid, int gen)
c906108c 2043{
d01949b6 2044 struct remote_state *rs = get_remote_state ();
47f8a51d 2045 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2046 char *buf = rs->buf;
79d7f229 2047 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2048
79d7f229 2049 if (ptid_equal (state, ptid))
c906108c
SS
2050 return;
2051
79d7f229
PA
2052 *buf++ = 'H';
2053 *buf++ = gen ? 'g' : 'c';
2054 if (ptid_equal (ptid, magic_null_ptid))
2055 xsnprintf (buf, endbuf - buf, "0");
2056 else if (ptid_equal (ptid, any_thread_ptid))
2057 xsnprintf (buf, endbuf - buf, "0");
2058 else if (ptid_equal (ptid, minus_one_ptid))
2059 xsnprintf (buf, endbuf - buf, "-1");
2060 else
82f73884 2061 write_ptid (buf, endbuf, ptid);
79d7f229 2062 putpkt (rs->buf);
6d820c5c 2063 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2064 if (gen)
47f8a51d 2065 rs->general_thread = ptid;
c906108c 2066 else
47f8a51d 2067 rs->continue_thread = ptid;
c906108c 2068}
79d7f229
PA
2069
2070static void
2071set_general_thread (struct ptid ptid)
2072{
2073 set_thread (ptid, 1);
2074}
2075
2076static void
2077set_continue_thread (struct ptid ptid)
2078{
2079 set_thread (ptid, 0);
2080}
2081
3c9c4b83
PA
2082/* Change the remote current process. Which thread within the process
2083 ends up selected isn't important, as long as it is the same process
2084 as what INFERIOR_PTID points to.
2085
2086 This comes from that fact that there is no explicit notion of
2087 "selected process" in the protocol. The selected process for
2088 general operations is the process the selected general thread
2089 belongs to. */
2090
2091static void
2092set_general_process (void)
2093{
2094 struct remote_state *rs = get_remote_state ();
2095
2096 /* If the remote can't handle multiple processes, don't bother. */
901f9912 2097 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
2098 return;
2099
2100 /* We only need to change the remote current thread if it's pointing
2101 at some other process. */
47f8a51d 2102 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2103 set_general_thread (inferior_ptid);
2104}
2105
c906108c 2106\f
7d1a114c
PA
2107/* Return nonzero if this is the main thread that we made up ourselves
2108 to model non-threaded targets as single-threaded. */
c906108c
SS
2109
2110static int
7d1a114c 2111remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2112{
6d820c5c 2113 struct remote_state *rs = get_remote_state ();
82f73884 2114 char *p, *endp;
c906108c 2115
c0a2216e
PA
2116 if (ptid_equal (ptid, magic_null_ptid))
2117 /* The main thread is always alive. */
2118 return 1;
2119
ba348170 2120 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2121 /* The main thread is always alive. This can happen after a
2122 vAttach, if the remote side doesn't support
2123 multi-threading. */
2124 return 1;
2125
7d1a114c
PA
2126 return 0;
2127}
2128
2129/* Return nonzero if the thread PTID is still alive on the remote
2130 system. */
2131
2132static int
2133remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2134{
2135 struct remote_state *rs = get_remote_state ();
2136 char *p, *endp;
2137
2138 /* Check if this is a thread that we made up ourselves to model
2139 non-threaded targets as single-threaded. */
2140 if (remote_thread_always_alive (ops, ptid))
2141 return 1;
2142
82f73884
PA
2143 p = rs->buf;
2144 endp = rs->buf + get_remote_packet_size ();
2145
2146 *p++ = 'T';
2147 write_ptid (p, endp, ptid);
2148
2e9f7625 2149 putpkt (rs->buf);
6d820c5c 2150 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2151 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2152}
2153
79efa585
SM
2154/* Return a pointer to a thread name if we know it and NULL otherwise.
2155 The thread_info object owns the memory for the name. */
2156
2157static const char *
2158remote_thread_name (struct target_ops *ops, struct thread_info *info)
2159{
2160 if (info->priv != NULL)
2161 return info->priv->name;
2162
2163 return NULL;
2164}
2165
c906108c
SS
2166/* About these extended threadlist and threadinfo packets. They are
2167 variable length packets but, the fields within them are often fixed
2168 length. They are redundent enough to send over UDP as is the
2169 remote protocol in general. There is a matching unit test module
2170 in libstub. */
2171
23860348 2172/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2173 libstub protocol encoding, and remote.c. It is not particularly
23860348 2174 changable. */
cce74817
JM
2175
2176/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2177 Plan to fix this. */
cce74817 2178
23860348 2179typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2180
9d1f7ab2 2181/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2182 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2183
2184struct gdb_ext_thread_info
c5aa993b 2185 {
23860348 2186 threadref threadid; /* External form of thread reference. */
2bc416ba 2187 int active; /* Has state interesting to GDB?
23860348 2188 regs, stack. */
2bc416ba 2189 char display[256]; /* Brief state display, name,
cedea757 2190 blocked/suspended. */
23860348 2191 char shortname[32]; /* To be used to name threads. */
2bc416ba 2192 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2193 whatever. */
c5aa993b 2194 };
cce74817
JM
2195
2196/* The volume of remote transfers can be limited by submitting
2197 a mask containing bits specifying the desired information.
2198 Use a union of these values as the 'selection' parameter to
0df8b418 2199 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2200
2201#define TAG_THREADID 1
2202#define TAG_EXISTS 2
2203#define TAG_DISPLAY 4
2204#define TAG_THREADNAME 8
c5aa993b 2205#define TAG_MOREDISPLAY 16
cce74817 2206
23860348 2207#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2208
a14ed312 2209static char *unpack_nibble (char *buf, int *val);
cce74817 2210
a14ed312 2211static char *unpack_byte (char *buf, int *value);
cce74817 2212
a14ed312 2213static char *pack_int (char *buf, int value);
cce74817 2214
a14ed312 2215static char *unpack_int (char *buf, int *value);
cce74817 2216
a14ed312 2217static char *unpack_string (char *src, char *dest, int length);
cce74817 2218
23860348 2219static char *pack_threadid (char *pkt, threadref *id);
cce74817 2220
23860348 2221static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2222
23860348 2223void int_to_threadref (threadref *id, int value);
cce74817 2224
23860348 2225static int threadref_to_int (threadref *ref);
cce74817 2226
23860348 2227static void copy_threadref (threadref *dest, threadref *src);
cce74817 2228
23860348 2229static int threadmatch (threadref *dest, threadref *src);
cce74817 2230
2bc416ba 2231static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2232 threadref *id);
cce74817 2233
a14ed312 2234static int remote_unpack_thread_info_response (char *pkt,
23860348 2235 threadref *expectedref,
a14ed312
KB
2236 struct gdb_ext_thread_info
2237 *info);
cce74817
JM
2238
2239
2bc416ba 2240static int remote_get_threadinfo (threadref *threadid,
23860348 2241 int fieldset, /*TAG mask */
a14ed312 2242 struct gdb_ext_thread_info *info);
cce74817 2243
a14ed312
KB
2244static char *pack_threadlist_request (char *pkt, int startflag,
2245 int threadcount,
23860348 2246 threadref *nextthread);
cce74817 2247
a14ed312
KB
2248static int parse_threadlist_response (char *pkt,
2249 int result_limit,
23860348 2250 threadref *original_echo,
2bc416ba 2251 threadref *resultlist,
23860348 2252 int *doneflag);
cce74817 2253
a14ed312 2254static int remote_get_threadlist (int startflag,
23860348 2255 threadref *nextthread,
a14ed312
KB
2256 int result_limit,
2257 int *done,
2bc416ba 2258 int *result_count,
23860348 2259 threadref *threadlist);
cce74817 2260
23860348 2261typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2262
a14ed312
KB
2263static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2264 void *context, int looplimit);
cce74817 2265
23860348 2266static int remote_newthread_step (threadref *ref, void *context);
cce74817 2267
82f73884
PA
2268
2269/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2270 buffer we're allowed to write to. Returns
2271 BUF+CHARACTERS_WRITTEN. */
2272
2273static char *
2274write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2275{
2276 int pid, tid;
2277 struct remote_state *rs = get_remote_state ();
2278
2279 if (remote_multi_process_p (rs))
2280 {
2281 pid = ptid_get_pid (ptid);
2282 if (pid < 0)
2283 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2284 else
2285 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2286 }
ba348170 2287 tid = ptid_get_lwp (ptid);
82f73884
PA
2288 if (tid < 0)
2289 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2290 else
2291 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2292
2293 return buf;
2294}
2295
2296/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2297 passed the last parsed char. Returns null_ptid on error. */
2298
2299static ptid_t
2300read_ptid (char *buf, char **obuf)
2301{
2302 char *p = buf;
2303 char *pp;
2304 ULONGEST pid = 0, tid = 0;
82f73884
PA
2305
2306 if (*p == 'p')
2307 {
2308 /* Multi-process ptid. */
2309 pp = unpack_varlen_hex (p + 1, &pid);
2310 if (*pp != '.')
b37520b6 2311 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2312
2313 p = pp;
2314 pp = unpack_varlen_hex (p + 1, &tid);
2315 if (obuf)
2316 *obuf = pp;
ba348170 2317 return ptid_build (pid, tid, 0);
82f73884
PA
2318 }
2319
2320 /* No multi-process. Just a tid. */
2321 pp = unpack_varlen_hex (p, &tid);
2322
c9f35b34
KB
2323 /* Return null_ptid when no thread id is found. */
2324 if (p == pp)
2325 {
2326 if (obuf)
2327 *obuf = pp;
2328 return null_ptid;
2329 }
2330
82f73884 2331 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2332 what's in inferior_ptid, unless it's null at this point. If so,
2333 then since there's no way to know the pid of the reported
2334 threads, use the magic number. */
2335 if (ptid_equal (inferior_ptid, null_ptid))
2336 pid = ptid_get_pid (magic_null_ptid);
2337 else
2338 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2339
2340 if (obuf)
2341 *obuf = pp;
ba348170 2342 return ptid_build (pid, tid, 0);
82f73884
PA
2343}
2344
c906108c 2345static int
fba45db2 2346stubhex (int ch)
c906108c
SS
2347{
2348 if (ch >= 'a' && ch <= 'f')
2349 return ch - 'a' + 10;
2350 if (ch >= '0' && ch <= '9')
2351 return ch - '0';
2352 if (ch >= 'A' && ch <= 'F')
2353 return ch - 'A' + 10;
2354 return -1;
2355}
2356
2357static int
fba45db2 2358stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2359{
2360 int nibble;
2361 int retval = 0;
2362
2363 while (fieldlength)
2364 {
2365 nibble = stubhex (*buff++);
2366 retval |= nibble;
2367 fieldlength--;
2368 if (fieldlength)
2369 retval = retval << 4;
2370 }
2371 return retval;
2372}
2373
c906108c 2374static char *
fba45db2 2375unpack_nibble (char *buf, int *val)
c906108c 2376{
b7589f7d 2377 *val = fromhex (*buf++);
c906108c
SS
2378 return buf;
2379}
2380
c906108c 2381static char *
fba45db2 2382unpack_byte (char *buf, int *value)
c906108c
SS
2383{
2384 *value = stub_unpack_int (buf, 2);
2385 return buf + 2;
2386}
2387
2388static char *
fba45db2 2389pack_int (char *buf, int value)
c906108c
SS
2390{
2391 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2392 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2393 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2394 buf = pack_hex_byte (buf, (value & 0xff));
2395 return buf;
2396}
2397
2398static char *
fba45db2 2399unpack_int (char *buf, int *value)
c906108c
SS
2400{
2401 *value = stub_unpack_int (buf, 8);
2402 return buf + 8;
2403}
2404
23860348 2405#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2406static char *pack_string (char *pkt, char *string);
c906108c
SS
2407
2408static char *
fba45db2 2409pack_string (char *pkt, char *string)
c906108c
SS
2410{
2411 char ch;
2412 int len;
2413
2414 len = strlen (string);
2415 if (len > 200)
23860348 2416 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2417 pkt = pack_hex_byte (pkt, len);
2418 while (len-- > 0)
2419 {
2420 ch = *string++;
2421 if ((ch == '\0') || (ch == '#'))
23860348 2422 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2423 *pkt++ = ch;
2424 }
2425 return pkt;
2426}
2427#endif /* 0 (unused) */
2428
2429static char *
fba45db2 2430unpack_string (char *src, char *dest, int length)
c906108c
SS
2431{
2432 while (length--)
2433 *dest++ = *src++;
2434 *dest = '\0';
2435 return src;
2436}
2437
2438static char *
fba45db2 2439pack_threadid (char *pkt, threadref *id)
c906108c
SS
2440{
2441 char *limit;
2442 unsigned char *altid;
2443
2444 altid = (unsigned char *) id;
2445 limit = pkt + BUF_THREAD_ID_SIZE;
2446 while (pkt < limit)
2447 pkt = pack_hex_byte (pkt, *altid++);
2448 return pkt;
2449}
2450
2451
2452static char *
fba45db2 2453unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2454{
2455 char *altref;
2456 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2457 int x, y;
2458
2459 altref = (char *) id;
2460
2461 while (inbuf < limit)
2462 {
2463 x = stubhex (*inbuf++);
2464 y = stubhex (*inbuf++);
2465 *altref++ = (x << 4) | y;
2466 }
2467 return inbuf;
2468}
2469
2470/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2471 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2472 to use 64bit thread references internally. This is an adapter
2473 function. */
2474
2475void
fba45db2 2476int_to_threadref (threadref *id, int value)
c906108c
SS
2477{
2478 unsigned char *scan;
2479
2480 scan = (unsigned char *) id;
2481 {
2482 int i = 4;
2483 while (i--)
2484 *scan++ = 0;
2485 }
2486 *scan++ = (value >> 24) & 0xff;
2487 *scan++ = (value >> 16) & 0xff;
2488 *scan++ = (value >> 8) & 0xff;
2489 *scan++ = (value & 0xff);
2490}
2491
2492static int
fba45db2 2493threadref_to_int (threadref *ref)
c906108c
SS
2494{
2495 int i, value = 0;
2496 unsigned char *scan;
2497
cfd77fa1 2498 scan = *ref;
c906108c
SS
2499 scan += 4;
2500 i = 4;
2501 while (i-- > 0)
2502 value = (value << 8) | ((*scan++) & 0xff);
2503 return value;
2504}
2505
2506static void
fba45db2 2507copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2508{
2509 int i;
2510 unsigned char *csrc, *cdest;
2511
2512 csrc = (unsigned char *) src;
2513 cdest = (unsigned char *) dest;
2514 i = 8;
2515 while (i--)
2516 *cdest++ = *csrc++;
2517}
2518
2519static int
fba45db2 2520threadmatch (threadref *dest, threadref *src)
c906108c 2521{
23860348 2522 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2523#if 0
2524 unsigned char *srcp, *destp;
2525 int i, result;
2526 srcp = (char *) src;
2527 destp = (char *) dest;
2528
2529 result = 1;
2530 while (i-- > 0)
2531 result &= (*srcp++ == *destp++) ? 1 : 0;
2532 return result;
2533#endif
2534 return 1;
2535}
2536
2537/*
c5aa993b
JM
2538 threadid:1, # always request threadid
2539 context_exists:2,
2540 display:4,
2541 unique_name:8,
2542 more_display:16
2543 */
c906108c
SS
2544
2545/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2546
2547static char *
fba45db2 2548pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2549{
23860348
MS
2550 *pkt++ = 'q'; /* Info Query */
2551 *pkt++ = 'P'; /* process or thread info */
2552 pkt = pack_int (pkt, mode); /* mode */
c906108c 2553 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2554 *pkt = '\0'; /* terminate */
c906108c
SS
2555 return pkt;
2556}
2557
23860348 2558/* These values tag the fields in a thread info response packet. */
c906108c 2559/* Tagging the fields allows us to request specific fields and to
23860348 2560 add more fields as time goes by. */
c906108c 2561
23860348 2562#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2563#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2564 fetch registers and its stack? */
c5aa993b 2565#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2566#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2567#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2568 the process. */
c906108c
SS
2569
2570static int
fba45db2
KB
2571remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2572 struct gdb_ext_thread_info *info)
c906108c 2573{
d01949b6 2574 struct remote_state *rs = get_remote_state ();
c906108c 2575 int mask, length;
cfd77fa1 2576 int tag;
c906108c 2577 threadref ref;
6d820c5c 2578 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2579 int retval = 1;
2580
23860348 2581 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2582 info->active = 0;
2583 info->display[0] = '\0';
2584 info->shortname[0] = '\0';
2585 info->more_display[0] = '\0';
2586
23860348
MS
2587 /* Assume the characters indicating the packet type have been
2588 stripped. */
c906108c
SS
2589 pkt = unpack_int (pkt, &mask); /* arg mask */
2590 pkt = unpack_threadid (pkt, &ref);
2591
2592 if (mask == 0)
8a3fe4f8 2593 warning (_("Incomplete response to threadinfo request."));
c906108c 2594 if (!threadmatch (&ref, expectedref))
23860348 2595 { /* This is an answer to a different request. */
8a3fe4f8 2596 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2597 return 0;
2598 }
2599 copy_threadref (&info->threadid, &ref);
2600
23860348 2601 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2602
23860348
MS
2603 /* Packets are terminated with nulls. */
2604 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2605 {
2606 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2607 pkt = unpack_byte (pkt, &length); /* length */
2608 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2609 {
8a3fe4f8 2610 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2611 retval = 0;
2612 break;
2613 }
2614 if (tag == TAG_THREADID)
2615 {
2616 if (length != 16)
2617 {
8a3fe4f8 2618 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2619 retval = 0;
2620 break;
2621 }
2622 pkt = unpack_threadid (pkt, &ref);
2623 mask = mask & ~TAG_THREADID;
2624 continue;
2625 }
2626 if (tag == TAG_EXISTS)
2627 {
2628 info->active = stub_unpack_int (pkt, length);
2629 pkt += length;
2630 mask = mask & ~(TAG_EXISTS);
2631 if (length > 8)
2632 {
8a3fe4f8 2633 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2634 retval = 0;
2635 break;
2636 }
2637 continue;
2638 }
2639 if (tag == TAG_THREADNAME)
2640 {
2641 pkt = unpack_string (pkt, &info->shortname[0], length);
2642 mask = mask & ~TAG_THREADNAME;
2643 continue;
2644 }
2645 if (tag == TAG_DISPLAY)
2646 {
2647 pkt = unpack_string (pkt, &info->display[0], length);
2648 mask = mask & ~TAG_DISPLAY;
2649 continue;
2650 }
2651 if (tag == TAG_MOREDISPLAY)
2652 {
2653 pkt = unpack_string (pkt, &info->more_display[0], length);
2654 mask = mask & ~TAG_MOREDISPLAY;
2655 continue;
2656 }
8a3fe4f8 2657 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2658 break; /* Not a tag we know about. */
c906108c
SS
2659 }
2660 return retval;
2661}
2662
2663static int
fba45db2
KB
2664remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2665 struct gdb_ext_thread_info *info)
c906108c 2666{
d01949b6 2667 struct remote_state *rs = get_remote_state ();
c906108c 2668 int result;
c906108c 2669
2e9f7625
DJ
2670 pack_threadinfo_request (rs->buf, fieldset, threadid);
2671 putpkt (rs->buf);
6d820c5c 2672 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2673
2674 if (rs->buf[0] == '\0')
2675 return 0;
2676
2e9f7625 2677 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2678 threadid, info);
c906108c
SS
2679 return result;
2680}
2681
c906108c
SS
2682/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2683
2684static char *
fba45db2
KB
2685pack_threadlist_request (char *pkt, int startflag, int threadcount,
2686 threadref *nextthread)
c906108c
SS
2687{
2688 *pkt++ = 'q'; /* info query packet */
2689 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2690 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2691 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2692 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2693 *pkt = '\0';
2694 return pkt;
2695}
2696
2697/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2698
2699static int
fba45db2
KB
2700parse_threadlist_response (char *pkt, int result_limit,
2701 threadref *original_echo, threadref *resultlist,
2702 int *doneflag)
c906108c 2703{
d01949b6 2704 struct remote_state *rs = get_remote_state ();
c906108c
SS
2705 char *limit;
2706 int count, resultcount, done;
2707
2708 resultcount = 0;
2709 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2710 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2711 /* done parse past here */
c906108c
SS
2712 pkt = unpack_byte (pkt, &count); /* count field */
2713 pkt = unpack_nibble (pkt, &done);
2714 /* The first threadid is the argument threadid. */
2715 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2716 while ((count-- > 0) && (pkt < limit))
2717 {
2718 pkt = unpack_threadid (pkt, resultlist++);
2719 if (resultcount++ >= result_limit)
2720 break;
2721 }
2722 if (doneflag)
2723 *doneflag = done;
2724 return resultcount;
2725}
2726
6dc54d91
PA
2727/* Fetch the next batch of threads from the remote. Returns -1 if the
2728 qL packet is not supported, 0 on error and 1 on success. */
2729
c906108c 2730static int
fba45db2
KB
2731remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2732 int *done, int *result_count, threadref *threadlist)
c906108c 2733{
d01949b6 2734 struct remote_state *rs = get_remote_state ();
c906108c
SS
2735 int result = 1;
2736
23860348 2737 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2738 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2739 >= get_remote_packet_size ())
ea9c271d 2740 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2741
6d820c5c
DJ
2742 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2743 putpkt (rs->buf);
2744 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2745 if (*rs->buf == '\0')
6dc54d91
PA
2746 {
2747 /* Packet not supported. */
2748 return -1;
2749 }
2750
2751 *result_count =
2752 parse_threadlist_response (rs->buf + 2, result_limit,
2753 &rs->echo_nextthread, threadlist, done);
c906108c 2754
0d031856 2755 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2756 {
23860348
MS
2757 /* FIXME: This is a good reason to drop the packet. */
2758 /* Possably, there is a duplicate response. */
c906108c
SS
2759 /* Possabilities :
2760 retransmit immediatly - race conditions
2761 retransmit after timeout - yes
2762 exit
2763 wait for packet, then exit
2764 */
8a3fe4f8 2765 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2766 return 0; /* I choose simply exiting. */
c906108c
SS
2767 }
2768 if (*result_count <= 0)
2769 {
2770 if (*done != 1)
2771 {
8a3fe4f8 2772 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2773 result = 0;
2774 }
2775 return result; /* break; */
2776 }
2777 if (*result_count > result_limit)
2778 {
2779 *result_count = 0;
8a3fe4f8 2780 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2781 return 0;
2782 }
2783 return result;
2784}
2785
6dc54d91
PA
2786/* Fetch the list of remote threads, with the qL packet, and call
2787 STEPFUNCTION for each thread found. Stops iterating and returns 1
2788 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2789 STEPFUNCTION returns false. If the packet is not supported,
2790 returns -1. */
c906108c 2791
c906108c 2792static int
fba45db2
KB
2793remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2794 int looplimit)
c906108c 2795{
0d031856 2796 struct remote_state *rs = get_remote_state ();
c906108c
SS
2797 int done, i, result_count;
2798 int startflag = 1;
2799 int result = 1;
2800 int loopcount = 0;
c906108c
SS
2801
2802 done = 0;
2803 while (!done)
2804 {
2805 if (loopcount++ > looplimit)
2806 {
2807 result = 0;
8a3fe4f8 2808 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2809 break;
2810 }
6dc54d91
PA
2811 result = remote_get_threadlist (startflag, &rs->nextthread,
2812 MAXTHREADLISTRESULTS,
2813 &done, &result_count,
2814 rs->resultthreadlist);
2815 if (result <= 0)
2816 break;
23860348 2817 /* Clear for later iterations. */
c906108c
SS
2818 startflag = 0;
2819 /* Setup to resume next batch of thread references, set nextthread. */
2820 if (result_count >= 1)
0d031856
TT
2821 copy_threadref (&rs->nextthread,
2822 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2823 i = 0;
2824 while (result_count--)
6dc54d91
PA
2825 {
2826 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2827 {
2828 result = 0;
2829 break;
2830 }
2831 }
c906108c
SS
2832 }
2833 return result;
2834}
2835
6dc54d91
PA
2836/* A thread found on the remote target. */
2837
2838typedef struct thread_item
2839{
2840 /* The thread's PTID. */
2841 ptid_t ptid;
2842
2843 /* The thread's extra info. May be NULL. */
2844 char *extra;
2845
79efa585
SM
2846 /* The thread's name. May be NULL. */
2847 char *name;
2848
6dc54d91
PA
2849 /* The core the thread was running on. -1 if not known. */
2850 int core;
2851} thread_item_t;
2852DEF_VEC_O(thread_item_t);
2853
2854/* Context passed around to the various methods listing remote
2855 threads. As new threads are found, they're added to the ITEMS
2856 vector. */
2857
2858struct threads_listing_context
2859{
2860 /* The threads found on the remote target. */
2861 VEC (thread_item_t) *items;
2862};
2863
80134cf5
PA
2864/* Discard the contents of the constructed thread listing context. */
2865
2866static void
2867clear_threads_listing_context (void *p)
2868{
19ba03f4
SM
2869 struct threads_listing_context *context
2870 = (struct threads_listing_context *) p;
80134cf5
PA
2871 int i;
2872 struct thread_item *item;
2873
2874 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
2875 {
2876 xfree (item->extra);
2877 xfree (item->name);
2878 }
80134cf5
PA
2879
2880 VEC_free (thread_item_t, context->items);
2881}
2882
cbb8991c
DB
2883/* Remove the thread specified as the related_pid field of WS
2884 from the CONTEXT list. */
2885
2886static void
2887threads_listing_context_remove (struct target_waitstatus *ws,
2888 struct threads_listing_context *context)
2889{
2890 struct thread_item *item;
2891 int i;
2892 ptid_t child_ptid = ws->value.related_pid;
2893
2894 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2895 {
2896 if (ptid_equal (item->ptid, child_ptid))
2897 {
2898 VEC_ordered_remove (thread_item_t, context->items, i);
2899 break;
2900 }
2901 }
2902}
2903
c906108c 2904static int
6dc54d91 2905remote_newthread_step (threadref *ref, void *data)
c906108c 2906{
19ba03f4
SM
2907 struct threads_listing_context *context
2908 = (struct threads_listing_context *) data;
6dc54d91 2909 struct thread_item item;
79d7f229 2910 int pid = ptid_get_pid (inferior_ptid);
39f77062 2911
6dc54d91
PA
2912 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2913 item.core = -1;
2914 item.extra = NULL;
2915
2916 VEC_safe_push (thread_item_t, context->items, &item);
2917
c906108c
SS
2918 return 1; /* continue iterator */
2919}
2920
2921#define CRAZY_MAX_THREADS 1000
2922
39f77062
KB
2923static ptid_t
2924remote_current_thread (ptid_t oldpid)
c906108c 2925{
d01949b6 2926 struct remote_state *rs = get_remote_state ();
c906108c
SS
2927
2928 putpkt ("qC");
6d820c5c 2929 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2930 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
2931 {
2932 char *obuf;
2933 ptid_t result;
2934
2935 result = read_ptid (&rs->buf[2], &obuf);
2936 if (*obuf != '\0' && remote_debug)
2937 fprintf_unfiltered (gdb_stdlog,
2938 "warning: garbage in qC reply\n");
2939
2940 return result;
2941 }
c906108c
SS
2942 else
2943 return oldpid;
2944}
2945
6dc54d91 2946/* List remote threads using the deprecated qL packet. */
cce74817 2947
6dc54d91
PA
2948static int
2949remote_get_threads_with_ql (struct target_ops *ops,
2950 struct threads_listing_context *context)
c906108c 2951{
6dc54d91
PA
2952 if (remote_threadlist_iterator (remote_newthread_step, context,
2953 CRAZY_MAX_THREADS) >= 0)
2954 return 1;
2955
2956 return 0;
c906108c
SS
2957}
2958
dc146f7c
VP
2959#if defined(HAVE_LIBEXPAT)
2960
dc146f7c
VP
2961static void
2962start_thread (struct gdb_xml_parser *parser,
2963 const struct gdb_xml_element *element,
2964 void *user_data, VEC(gdb_xml_value_s) *attributes)
2965{
19ba03f4
SM
2966 struct threads_listing_context *data
2967 = (struct threads_listing_context *) user_data;
dc146f7c
VP
2968
2969 struct thread_item item;
2970 char *id;
3d2c1d41 2971 struct gdb_xml_value *attr;
dc146f7c 2972
19ba03f4 2973 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2974 item.ptid = read_ptid (id, NULL);
2975
3d2c1d41
PA
2976 attr = xml_find_attribute (attributes, "core");
2977 if (attr != NULL)
2978 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2979 else
2980 item.core = -1;
2981
79efa585 2982 attr = xml_find_attribute (attributes, "name");
e1961661 2983 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 2984
dc146f7c
VP
2985 item.extra = 0;
2986
2987 VEC_safe_push (thread_item_t, data->items, &item);
2988}
2989
2990static void
2991end_thread (struct gdb_xml_parser *parser,
2992 const struct gdb_xml_element *element,
2993 void *user_data, const char *body_text)
2994{
19ba03f4
SM
2995 struct threads_listing_context *data
2996 = (struct threads_listing_context *) user_data;
dc146f7c
VP
2997
2998 if (body_text && *body_text)
2ae2a0b7 2999 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3000}
3001
3002const struct gdb_xml_attribute thread_attributes[] = {
3003 { "id", GDB_XML_AF_NONE, NULL, NULL },
3004 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3005 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3006 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3007};
3008
3009const struct gdb_xml_element thread_children[] = {
3010 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3011};
3012
3013const struct gdb_xml_element threads_children[] = {
3014 { "thread", thread_attributes, thread_children,
3015 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3016 start_thread, end_thread },
3017 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3018};
3019
3020const struct gdb_xml_element threads_elements[] = {
3021 { "threads", NULL, threads_children,
3022 GDB_XML_EF_NONE, NULL, NULL },
3023 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3024};
3025
3026#endif
3027
6dc54d91 3028/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3029
6dc54d91
PA
3030static int
3031remote_get_threads_with_qxfer (struct target_ops *ops,
3032 struct threads_listing_context *context)
0f71a2f6 3033{
dc146f7c 3034#if defined(HAVE_LIBEXPAT)
4082afcc 3035 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3036 {
6dc54d91 3037 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3038 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3039
6dc54d91 3040 if (xml != NULL && *xml != '\0')
dc146f7c 3041 {
6dc54d91
PA
3042 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3043 threads_elements, xml, context);
dc146f7c
VP
3044 }
3045
3046 do_cleanups (back_to);
6dc54d91 3047 return 1;
dc146f7c
VP
3048 }
3049#endif
3050
6dc54d91
PA
3051 return 0;
3052}
3053
3054/* List remote threads using qfThreadInfo/qsThreadInfo. */
3055
3056static int
3057remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3058 struct threads_listing_context *context)
3059{
3060 struct remote_state *rs = get_remote_state ();
3061
b80fafe3 3062 if (rs->use_threadinfo_query)
9d1f7ab2 3063 {
6dc54d91
PA
3064 char *bufp;
3065
9d1f7ab2 3066 putpkt ("qfThreadInfo");
6d820c5c 3067 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3068 bufp = rs->buf;
9d1f7ab2 3069 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3070 {
9d1f7ab2
MS
3071 while (*bufp++ == 'm') /* reply contains one or more TID */
3072 {
3073 do
3074 {
6dc54d91
PA
3075 struct thread_item item;
3076
3077 item.ptid = read_ptid (bufp, &bufp);
3078 item.core = -1;
3079 item.extra = NULL;
3080
3081 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3082 }
3083 while (*bufp++ == ','); /* comma-separated list */
3084 putpkt ("qsThreadInfo");
6d820c5c 3085 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3086 bufp = rs->buf;
9d1f7ab2 3087 }
6dc54d91
PA
3088 return 1;
3089 }
3090 else
3091 {
3092 /* Packet not recognized. */
3093 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3094 }
3095 }
3096
6dc54d91
PA
3097 return 0;
3098}
3099
e8032dde 3100/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3101 targets. */
3102
3103static void
e8032dde 3104remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
3105{
3106 struct remote_state *rs = get_remote_state ();
3107 struct threads_listing_context context;
3108 struct cleanup *old_chain;
ab970af1 3109 int got_list = 0;
e8032dde 3110
6dc54d91
PA
3111 context.items = NULL;
3112 old_chain = make_cleanup (clear_threads_listing_context, &context);
3113
3114 /* We have a few different mechanisms to fetch the thread list. Try
3115 them all, starting with the most preferred one first, falling
3116 back to older methods. */
3117 if (remote_get_threads_with_qxfer (ops, &context)
3118 || remote_get_threads_with_qthreadinfo (ops, &context)
3119 || remote_get_threads_with_ql (ops, &context))
3120 {
3121 int i;
3122 struct thread_item *item;
ab970af1
PA
3123 struct thread_info *tp, *tmp;
3124
3125 got_list = 1;
3126
7d1a114c
PA
3127 if (VEC_empty (thread_item_t, context.items)
3128 && remote_thread_always_alive (ops, inferior_ptid))
3129 {
3130 /* Some targets don't really support threads, but still
3131 reply an (empty) thread list in response to the thread
3132 listing packets, instead of replying "packet not
3133 supported". Exit early so we don't delete the main
3134 thread. */
3135 do_cleanups (old_chain);
3136 return;
3137 }
3138
ab970af1
PA
3139 /* CONTEXT now holds the current thread list on the remote
3140 target end. Delete GDB-side threads no longer found on the
3141 target. */
8a06aea7 3142 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3143 {
ab970af1
PA
3144 for (i = 0;
3145 VEC_iterate (thread_item_t, context.items, i, item);
3146 ++i)
3147 {
3148 if (ptid_equal (item->ptid, tp->ptid))
3149 break;
3150 }
3151
3152 if (i == VEC_length (thread_item_t, context.items))
3153 {
3154 /* Not found. */
3155 delete_thread (tp->ptid);
3156 }
cbb8991c
DB
3157 }
3158
3159 /* Remove any unreported fork child threads from CONTEXT so
3160 that we don't interfere with follow fork, which is where
3161 creation of such threads is handled. */
3162 remove_new_fork_children (&context);
74531fed 3163
ab970af1 3164 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3165 for (i = 0;
3166 VEC_iterate (thread_item_t, context.items, i, item);
3167 ++i)
3168 {
3169 if (!ptid_equal (item->ptid, null_ptid))
3170 {
3171 struct private_thread_info *info;
3172 /* In non-stop mode, we assume new found threads are
3173 running until proven otherwise with a stop reply. In
3174 all-stop, we can only get here if all threads are
3175 stopped. */
6efcd9a8 3176 int running = target_is_non_stop_p () ? 1 : 0;
6dc54d91
PA
3177
3178 remote_notice_new_inferior (item->ptid, running);
3179
3180 info = demand_private_info (item->ptid);
3181 info->core = item->core;
3182 info->extra = item->extra;
3183 item->extra = NULL;
79efa585
SM
3184 info->name = item->name;
3185 item->name = NULL;
6dc54d91
PA
3186 }
3187 }
3188 }
3189
ab970af1
PA
3190 if (!got_list)
3191 {
3192 /* If no thread listing method is supported, then query whether
3193 each known thread is alive, one by one, with the T packet.
3194 If the target doesn't support threads at all, then this is a
3195 no-op. See remote_thread_alive. */
3196 prune_threads ();
3197 }
3198
6dc54d91 3199 do_cleanups (old_chain);
9d1f7ab2
MS
3200}
3201
802188a7 3202/*
9d1f7ab2
MS
3203 * Collect a descriptive string about the given thread.
3204 * The target may say anything it wants to about the thread
3205 * (typically info about its blocked / runnable state, name, etc.).
3206 * This string will appear in the info threads display.
802188a7 3207 *
9d1f7ab2
MS
3208 * Optional: targets are not required to implement this function.
3209 */
3210
3211static char *
c15906d8 3212remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3213{
d01949b6 3214 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3215 int result;
3216 int set;
3217 threadref id;
3218 struct gdb_ext_thread_info threadinfo;
23860348 3219 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3220 int n = 0; /* position in display_buf */
3221
5d93a237 3222 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3223 internal_error (__FILE__, __LINE__,
e2e0b3e5 3224 _("remote_threads_extra_info"));
9d1f7ab2 3225
60e569b9 3226 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3227 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3228 /* This is the main thread which was added by GDB. The remote
3229 server doesn't know about it. */
3230 return NULL;
3231
4082afcc 3232 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3233 {
3234 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3235
fe978cb0
PA
3236 if (info && info->priv)
3237 return info->priv->extra;
dc146f7c
VP
3238 else
3239 return NULL;
3240 }
3241
b80fafe3 3242 if (rs->use_threadextra_query)
9d1f7ab2 3243 {
82f73884
PA
3244 char *b = rs->buf;
3245 char *endb = rs->buf + get_remote_packet_size ();
3246
3247 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3248 b += strlen (b);
3249 write_ptid (b, endb, tp->ptid);
3250
2e9f7625 3251 putpkt (rs->buf);
6d820c5c 3252 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3253 if (rs->buf[0] != 0)
9d1f7ab2 3254 {
2e9f7625
DJ
3255 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3256 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3257 display_buf [result] = '\0';
9d1f7ab2
MS
3258 return display_buf;
3259 }
0f71a2f6 3260 }
9d1f7ab2
MS
3261
3262 /* If the above query fails, fall back to the old method. */
b80fafe3 3263 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3264 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3265 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3266 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3267 if (remote_get_threadinfo (&id, set, &threadinfo))
3268 if (threadinfo.active)
0f71a2f6 3269 {
9d1f7ab2 3270 if (*threadinfo.shortname)
2bc416ba 3271 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3272 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3273 if (*threadinfo.display)
2bc416ba 3274 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3275 " State: %s,", threadinfo.display);
9d1f7ab2 3276 if (*threadinfo.more_display)
2bc416ba 3277 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3278 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3279
3280 if (n > 0)
c5aa993b 3281 {
23860348 3282 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3283 if (',' == display_buf[n-1])
3284 display_buf[n-1] = ' ';
3285 return display_buf;
c5aa993b 3286 }
0f71a2f6 3287 }
9d1f7ab2 3288 return NULL;
0f71a2f6 3289}
c906108c 3290\f
c5aa993b 3291
0fb4aa4b 3292static int
61fc905d 3293remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3294 struct static_tracepoint_marker *marker)
3295{
3296 struct remote_state *rs = get_remote_state ();
3297 char *p = rs->buf;
3298
bba74b36 3299 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3300 p += strlen (p);
3301 p += hexnumstr (p, addr);
3302 putpkt (rs->buf);
3303 getpkt (&rs->buf, &rs->buf_size, 0);
3304 p = rs->buf;
3305
3306 if (*p == 'E')
3307 error (_("Remote failure reply: %s"), p);
3308
3309 if (*p++ == 'm')
3310 {
3311 parse_static_tracepoint_marker_definition (p, &p, marker);
3312 return 1;
3313 }
3314
3315 return 0;
3316}
3317
0fb4aa4b 3318static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3319remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3320 const char *strid)
0fb4aa4b
PA
3321{
3322 struct remote_state *rs = get_remote_state ();
3323 VEC(static_tracepoint_marker_p) *markers = NULL;
3324 struct static_tracepoint_marker *marker = NULL;
3325 struct cleanup *old_chain;
3326 char *p;
3327
3328 /* Ask for a first packet of static tracepoint marker
3329 definition. */
3330 putpkt ("qTfSTM");
3331 getpkt (&rs->buf, &rs->buf_size, 0);
3332 p = rs->buf;
3333 if (*p == 'E')
3334 error (_("Remote failure reply: %s"), p);
3335
3336 old_chain = make_cleanup (free_current_marker, &marker);
3337
3338 while (*p++ == 'm')
3339 {
3340 if (marker == NULL)
3341 marker = XCNEW (struct static_tracepoint_marker);
3342
3343 do
3344 {
3345 parse_static_tracepoint_marker_definition (p, &p, marker);
3346
3347 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3348 {
3349 VEC_safe_push (static_tracepoint_marker_p,
3350 markers, marker);
3351 marker = NULL;
3352 }
3353 else
3354 {
3355 release_static_tracepoint_marker (marker);
3356 memset (marker, 0, sizeof (*marker));
3357 }
3358 }
3359 while (*p++ == ','); /* comma-separated list */
3360 /* Ask for another packet of static tracepoint definition. */
3361 putpkt ("qTsSTM");
3362 getpkt (&rs->buf, &rs->buf_size, 0);
3363 p = rs->buf;
3364 }
3365
3366 do_cleanups (old_chain);
3367 return markers;
3368}
3369
3370\f
10760264
JB
3371/* Implement the to_get_ada_task_ptid function for the remote targets. */
3372
3373static ptid_t
1e6b91a4 3374remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3375{
ba348170 3376 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3377}
3378\f
3379
24b06219 3380/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3381
3382static void
fba45db2 3383extended_remote_restart (void)
c906108c 3384{
d01949b6 3385 struct remote_state *rs = get_remote_state ();
c906108c
SS
3386
3387 /* Send the restart command; for reasons I don't understand the
3388 remote side really expects a number after the "R". */
ea9c271d 3389 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3390 putpkt (rs->buf);
c906108c 3391
ad9a8f3f 3392 remote_fileio_reset ();
c906108c
SS
3393}
3394\f
3395/* Clean up connection to a remote debugger. */
3396
c906108c 3397static void
de90e03d 3398remote_close (struct target_ops *self)
c906108c 3399{
5d93a237
TT
3400 struct remote_state *rs = get_remote_state ();
3401
3402 if (rs->remote_desc == NULL)
d3fd5342
PA
3403 return; /* already closed */
3404
3405 /* Make sure we leave stdin registered in the event loop, and we
3406 don't leave the async SIGINT signal handler installed. */
e3594fd1 3407 remote_terminal_ours (self);
ce5ce7ed 3408
5d93a237
TT
3409 serial_close (rs->remote_desc);
3410 rs->remote_desc = NULL;
ce5ce7ed
PA
3411
3412 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3413 of all the inferiors and their threads we were controlling.
3414 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3415 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3416 inferior_ptid = null_ptid;
f67fd822 3417 discard_all_inferiors ();
ce5ce7ed 3418
f48ff2a7
YQ
3419 /* We are closing the remote target, so we should discard
3420 everything of this target. */
bcc75809 3421 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3422
3423 if (remote_async_inferior_event_token)
3424 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3425
5965e028 3426 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3427
3428 trace_reset_local_state ();
c906108c
SS
3429}
3430
23860348 3431/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3432
3433static void
fba45db2 3434get_offsets (void)
c906108c 3435{
d01949b6 3436 struct remote_state *rs = get_remote_state ();
2e9f7625 3437 char *buf;
085dd6e6 3438 char *ptr;
31d99776
DJ
3439 int lose, num_segments = 0, do_sections, do_segments;
3440 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3441 struct section_offsets *offs;
31d99776
DJ
3442 struct symfile_segment_data *data;
3443
3444 if (symfile_objfile == NULL)
3445 return;
c906108c
SS
3446
3447 putpkt ("qOffsets");
6d820c5c 3448 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3449 buf = rs->buf;
c906108c
SS
3450
3451 if (buf[0] == '\000')
3452 return; /* Return silently. Stub doesn't support
23860348 3453 this command. */
c906108c
SS
3454 if (buf[0] == 'E')
3455 {
8a3fe4f8 3456 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3457 return;
3458 }
3459
3460 /* Pick up each field in turn. This used to be done with scanf, but
3461 scanf will make trouble if CORE_ADDR size doesn't match
3462 conversion directives correctly. The following code will work
3463 with any size of CORE_ADDR. */
3464 text_addr = data_addr = bss_addr = 0;
3465 ptr = buf;
3466 lose = 0;
3467
61012eef 3468 if (startswith (ptr, "Text="))
c906108c
SS
3469 {
3470 ptr += 5;
3471 /* Don't use strtol, could lose on big values. */
3472 while (*ptr && *ptr != ';')
3473 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3474
61012eef 3475 if (startswith (ptr, ";Data="))
31d99776
DJ
3476 {
3477 ptr += 6;
3478 while (*ptr && *ptr != ';')
3479 data_addr = (data_addr << 4) + fromhex (*ptr++);
3480 }
3481 else
3482 lose = 1;
3483
61012eef 3484 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3485 {
3486 ptr += 5;
3487 while (*ptr && *ptr != ';')
3488 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3489
31d99776
DJ
3490 if (bss_addr != data_addr)
3491 warning (_("Target reported unsupported offsets: %s"), buf);
3492 }
3493 else
3494 lose = 1;
3495 }
61012eef 3496 else if (startswith (ptr, "TextSeg="))
c906108c 3497 {
31d99776
DJ
3498 ptr += 8;
3499 /* Don't use strtol, could lose on big values. */
c906108c 3500 while (*ptr && *ptr != ';')
31d99776
DJ
3501 text_addr = (text_addr << 4) + fromhex (*ptr++);
3502 num_segments = 1;
3503
61012eef 3504 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3505 {
3506 ptr += 9;
3507 while (*ptr && *ptr != ';')
3508 data_addr = (data_addr << 4) + fromhex (*ptr++);
3509 num_segments++;
3510 }
c906108c
SS
3511 }
3512 else
3513 lose = 1;
3514
3515 if (lose)
8a3fe4f8 3516 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3517 else if (*ptr != '\0')
3518 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3519
802188a7 3520 offs = ((struct section_offsets *)
a39a16c4 3521 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3522 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3523 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3524
31d99776
DJ
3525 data = get_symfile_segment_data (symfile_objfile->obfd);
3526 do_segments = (data != NULL);
3527 do_sections = num_segments == 0;
c906108c 3528
28c32713 3529 if (num_segments > 0)
31d99776 3530 {
31d99776
DJ
3531 segments[0] = text_addr;
3532 segments[1] = data_addr;
3533 }
28c32713
JB
3534 /* If we have two segments, we can still try to relocate everything
3535 by assuming that the .text and .data offsets apply to the whole
3536 text and data segments. Convert the offsets given in the packet
3537 to base addresses for symfile_map_offsets_to_segments. */
3538 else if (data && data->num_segments == 2)
3539 {
3540 segments[0] = data->segment_bases[0] + text_addr;
3541 segments[1] = data->segment_bases[1] + data_addr;
3542 num_segments = 2;
3543 }
8d385431
DJ
3544 /* If the object file has only one segment, assume that it is text
3545 rather than data; main programs with no writable data are rare,
3546 but programs with no code are useless. Of course the code might
3547 have ended up in the data segment... to detect that we would need
3548 the permissions here. */
3549 else if (data && data->num_segments == 1)
3550 {
3551 segments[0] = data->segment_bases[0] + text_addr;
3552 num_segments = 1;
3553 }
28c32713
JB
3554 /* There's no way to relocate by segment. */
3555 else
3556 do_segments = 0;
31d99776
DJ
3557
3558 if (do_segments)
3559 {
3560 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3561 offs, num_segments, segments);
3562
3563 if (ret == 0 && !do_sections)
3e43a32a
MS
3564 error (_("Can not handle qOffsets TextSeg "
3565 "response with this symbol file"));
31d99776
DJ
3566
3567 if (ret > 0)
3568 do_sections = 0;
3569 }
c906108c 3570
9ef895d6
DJ
3571 if (data)
3572 free_symfile_segment_data (data);
31d99776
DJ
3573
3574 if (do_sections)
3575 {
3576 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3577
3e43a32a
MS
3578 /* This is a temporary kludge to force data and bss to use the
3579 same offsets because that's what nlmconv does now. The real
3580 solution requires changes to the stub and remote.c that I
3581 don't have time to do right now. */
31d99776
DJ
3582
3583 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3584 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3585 }
c906108c
SS
3586
3587 objfile_relocate (symfile_objfile, offs);
3588}
3589
9a7071a8
JB
3590/* Send interrupt_sequence to remote target. */
3591static void
eeae04df 3592send_interrupt_sequence (void)
9a7071a8 3593{
5d93a237
TT
3594 struct remote_state *rs = get_remote_state ();
3595
9a7071a8 3596 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3597 remote_serial_write ("\x03", 1);
9a7071a8 3598 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3599 serial_send_break (rs->remote_desc);
9a7071a8
JB
3600 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3601 {
5d93a237 3602 serial_send_break (rs->remote_desc);
c33e31fd 3603 remote_serial_write ("g", 1);
9a7071a8
JB
3604 }
3605 else
3606 internal_error (__FILE__, __LINE__,
3607 _("Invalid value for interrupt_sequence_mode: %s."),
3608 interrupt_sequence_mode);
3609}
3610
3405876a
PA
3611
3612/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3613 and extract the PTID. Returns NULL_PTID if not found. */
3614
3615static ptid_t
3616stop_reply_extract_thread (char *stop_reply)
3617{
3618 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3619 {
3620 char *p;
3621
3622 /* Txx r:val ; r:val (...) */
3623 p = &stop_reply[3];
3624
3625 /* Look for "register" named "thread". */
3626 while (*p != '\0')
3627 {
3628 char *p1;
3629
3630 p1 = strchr (p, ':');
3631 if (p1 == NULL)
3632 return null_ptid;
3633
3634 if (strncmp (p, "thread", p1 - p) == 0)
3635 return read_ptid (++p1, &p);
3636
3637 p1 = strchr (p, ';');
3638 if (p1 == NULL)
3639 return null_ptid;
3640 p1++;
3641
3642 p = p1;
3643 }
3644 }
3645
3646 return null_ptid;
3647}
3648
b7ea362b
PA
3649/* Determine the remote side's current thread. If we have a stop
3650 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3651 "thread" register we can extract the current thread from. If not,
3652 ask the remote which is the current thread with qC. The former
3653 method avoids a roundtrip. */
3654
3655static ptid_t
3656get_current_thread (char *wait_status)
3657{
6a49a997 3658 ptid_t ptid = null_ptid;
b7ea362b
PA
3659
3660 /* Note we don't use remote_parse_stop_reply as that makes use of
3661 the target architecture, which we haven't yet fully determined at
3662 this point. */
3663 if (wait_status != NULL)
3664 ptid = stop_reply_extract_thread (wait_status);
3665 if (ptid_equal (ptid, null_ptid))
3666 ptid = remote_current_thread (inferior_ptid);
3667
3668 return ptid;
3669}
3670
49c62f2e
PA
3671/* Query the remote target for which is the current thread/process,
3672 add it to our tables, and update INFERIOR_PTID. The caller is
3673 responsible for setting the state such that the remote end is ready
3405876a
PA
3674 to return the current thread.
3675
3676 This function is called after handling the '?' or 'vRun' packets,
3677 whose response is a stop reply from which we can also try
3678 extracting the thread. If the target doesn't support the explicit
3679 qC query, we infer the current thread from that stop reply, passed
3680 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3681
3682static void
3405876a 3683add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3684{
3685 struct remote_state *rs = get_remote_state ();
3686 int fake_pid_p = 0;
6a49a997 3687 ptid_t ptid;
49c62f2e
PA
3688
3689 inferior_ptid = null_ptid;
3690
b7ea362b
PA
3691 /* Now, if we have thread information, update inferior_ptid. */
3692 ptid = get_current_thread (wait_status);
3405876a 3693
49c62f2e
PA
3694 if (!ptid_equal (ptid, null_ptid))
3695 {
3696 if (!remote_multi_process_p (rs))
3697 fake_pid_p = 1;
3698
3699 inferior_ptid = ptid;
3700 }
3701 else
3702 {
3703 /* Without this, some commands which require an active target
3704 (such as kill) won't work. This variable serves (at least)
3705 double duty as both the pid of the target process (if it has
3706 such), and as a flag indicating that a target is active. */
3707 inferior_ptid = magic_null_ptid;
3708 fake_pid_p = 1;
3709 }
3710
1b6e6f5c 3711 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3712
3713 /* Add the main thread. */
3714 add_thread_silent (inferior_ptid);
3715}
3716
6efcd9a8
PA
3717/* Print info about a thread that was found already stopped on
3718 connection. */
3719
3720static void
3721print_one_stopped_thread (struct thread_info *thread)
3722{
3723 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3724
3725 switch_to_thread (thread->ptid);
3726 stop_pc = get_frame_pc (get_current_frame ());
3727 set_current_sal_from_frame (get_current_frame ());
3728
3729 thread->suspend.waitstatus_pending_p = 0;
3730
3731 if (ws->kind == TARGET_WAITKIND_STOPPED)
3732 {
3733 enum gdb_signal sig = ws->value.sig;
3734
3735 if (signal_print_state (sig))
3736 observer_notify_signal_received (sig);
3737 }
3738 observer_notify_normal_stop (NULL, 1);
3739}
3740
221e1a37
PA
3741/* Process all initial stop replies the remote side sent in response
3742 to the ? packet. These indicate threads that were already stopped
3743 on initial connection. We mark these threads as stopped and print
3744 their current frame before giving the user the prompt. */
3745
3746static void
6efcd9a8 3747process_initial_stop_replies (int from_tty)
221e1a37
PA
3748{
3749 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3750 struct inferior *inf;
3751 struct thread_info *thread;
3752 struct thread_info *selected = NULL;
3753 struct thread_info *lowest_stopped = NULL;
3754 struct thread_info *first = NULL;
221e1a37
PA
3755
3756 /* Consume the initial pending events. */
3757 while (pending_stop_replies-- > 0)
3758 {
3759 ptid_t waiton_ptid = minus_one_ptid;
3760 ptid_t event_ptid;
3761 struct target_waitstatus ws;
3762 int ignore_event = 0;
6efcd9a8 3763 struct thread_info *thread;
221e1a37
PA
3764
3765 memset (&ws, 0, sizeof (ws));
3766 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3767 if (remote_debug)
3768 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3769
3770 switch (ws.kind)
3771 {
3772 case TARGET_WAITKIND_IGNORE:
3773 case TARGET_WAITKIND_NO_RESUMED:
3774 case TARGET_WAITKIND_SIGNALLED:
3775 case TARGET_WAITKIND_EXITED:
3776 /* We shouldn't see these, but if we do, just ignore. */
3777 if (remote_debug)
3778 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3779 ignore_event = 1;
3780 break;
3781
3782 case TARGET_WAITKIND_EXECD:
3783 xfree (ws.value.execd_pathname);
3784 break;
3785 default:
3786 break;
3787 }
3788
3789 if (ignore_event)
3790 continue;
3791
6efcd9a8 3792 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3793
3794 if (ws.kind == TARGET_WAITKIND_STOPPED)
3795 {
3796 enum gdb_signal sig = ws.value.sig;
3797
3798 /* Stubs traditionally report SIGTRAP as initial signal,
3799 instead of signal 0. Suppress it. */
3800 if (sig == GDB_SIGNAL_TRAP)
3801 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3802 thread->suspend.stop_signal = sig;
3803 ws.value.sig = sig;
3804 }
221e1a37 3805
6efcd9a8
PA
3806 thread->suspend.waitstatus = ws;
3807
3808 if (ws.kind != TARGET_WAITKIND_STOPPED
3809 || ws.value.sig != GDB_SIGNAL_0)
3810 thread->suspend.waitstatus_pending_p = 1;
3811
3812 set_executing (event_ptid, 0);
3813 set_running (event_ptid, 0);
3814 }
3815
3816 /* "Notice" the new inferiors before anything related to
3817 registers/memory. */
3818 ALL_INFERIORS (inf)
3819 {
3820 if (inf->pid == 0)
3821 continue;
3822
3823 inf->needs_setup = 1;
3824
3825 if (non_stop)
3826 {
3827 thread = any_live_thread_of_process (inf->pid);
3828 notice_new_inferior (thread->ptid,
3829 thread->state == THREAD_RUNNING,
3830 from_tty);
3831 }
3832 }
3833
3834 /* If all-stop on top of non-stop, pause all threads. Note this
3835 records the threads' stop pc, so must be done after "noticing"
3836 the inferiors. */
3837 if (!non_stop)
3838 {
3839 stop_all_threads ();
3840
3841 /* If all threads of an inferior were already stopped, we
3842 haven't setup the inferior yet. */
3843 ALL_INFERIORS (inf)
3844 {
3845 if (inf->pid == 0)
3846 continue;
221e1a37 3847
6efcd9a8
PA
3848 if (inf->needs_setup)
3849 {
3850 thread = any_live_thread_of_process (inf->pid);
3851 switch_to_thread_no_regs (thread);
3852 setup_inferior (0);
3853 }
3854 }
221e1a37 3855 }
6efcd9a8
PA
3856
3857 /* Now go over all threads that are stopped, and print their current
3858 frame. If all-stop, then if there's a signalled thread, pick
3859 that as current. */
3860 ALL_NON_EXITED_THREADS (thread)
3861 {
3862 struct target_waitstatus *ws;
3863
3864 if (first == NULL)
3865 first = thread;
3866
3867 if (!non_stop)
3868 set_running (thread->ptid, 0);
3869 else if (thread->state != THREAD_STOPPED)
3870 continue;
3871
3872 ws = &thread->suspend.waitstatus;
3873
3874 if (selected == NULL
3875 && thread->suspend.waitstatus_pending_p)
3876 selected = thread;
3877
3878 if (lowest_stopped == NULL || thread->num < lowest_stopped->num)
3879 lowest_stopped = thread;
3880
3881 if (non_stop)
3882 print_one_stopped_thread (thread);
3883 }
3884
3885 /* In all-stop, we only print the status of one thread, and leave
3886 others with their status pending. */
3887 if (!non_stop)
3888 {
3889 thread = selected;
3890 if (thread == NULL)
3891 thread = lowest_stopped;
3892 if (thread == NULL)
3893 thread = first;
3894
3895 print_one_stopped_thread (thread);
3896 }
3897
3898 /* For "info program". */
3899 thread = inferior_thread ();
3900 if (thread->state == THREAD_STOPPED)
3901 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
3902}
3903
9cbc821d 3904static void
04bd08de 3905remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3906{
c8d104ad
PA
3907 struct remote_state *rs = get_remote_state ();
3908 struct packet_config *noack_config;
2d717e4f 3909 char *wait_status = NULL;
8621d6a9 3910
23860348 3911 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3912 QUIT;
c906108c 3913
9a7071a8
JB
3914 if (interrupt_on_connect)
3915 send_interrupt_sequence ();
3916
57e12211 3917 /* Ack any packet which the remote side has already sent. */
5d93a237 3918 serial_write (rs->remote_desc, "+", 1);
57e12211 3919
1e51243a
PA
3920 /* Signal other parts that we're going through the initial setup,
3921 and so things may not be stable yet. */
3922 rs->starting_up = 1;
3923
c8d104ad
PA
3924 /* The first packet we send to the target is the optional "supported
3925 packets" request. If the target can answer this, it will tell us
3926 which later probes to skip. */
3927 remote_query_supported ();
3928
d914c394 3929 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3930 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3931 remote_set_permissions (target);
d914c394 3932
c8d104ad
PA
3933 /* Next, we possibly activate noack mode.
3934
3935 If the QStartNoAckMode packet configuration is set to AUTO,
3936 enable noack mode if the stub reported a wish for it with
3937 qSupported.
3938
3939 If set to TRUE, then enable noack mode even if the stub didn't
3940 report it in qSupported. If the stub doesn't reply OK, the
3941 session ends with an error.
3942
3943 If FALSE, then don't activate noack mode, regardless of what the
3944 stub claimed should be the default with qSupported. */
3945
3946 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3947 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3948 {
3949 putpkt ("QStartNoAckMode");
3950 getpkt (&rs->buf, &rs->buf_size, 0);
3951 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3952 rs->noack_mode = 1;
3953 }
3954
04bd08de 3955 if (extended_p)
5fe04517
PA
3956 {
3957 /* Tell the remote that we are using the extended protocol. */
3958 putpkt ("!");
3959 getpkt (&rs->buf, &rs->buf_size, 0);
3960 }
3961
9b224c5e
PA
3962 /* Let the target know which signals it is allowed to pass down to
3963 the program. */
3964 update_signals_program_target ();
3965
d962ef82
DJ
3966 /* Next, if the target can specify a description, read it. We do
3967 this before anything involving memory or registers. */
3968 target_find_description ();
3969
6c95b8df
PA
3970 /* Next, now that we know something about the target, update the
3971 address spaces in the program spaces. */
3972 update_address_spaces ();
3973
50c71eaf
PA
3974 /* On OSs where the list of libraries is global to all
3975 processes, we fetch them early. */
f5656ead 3976 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3977 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3978
6efcd9a8 3979 if (target_is_non_stop_p ())
74531fed 3980 {
4082afcc 3981 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3982 error (_("Non-stop mode requested, but remote "
3983 "does not support non-stop"));
74531fed
PA
3984
3985 putpkt ("QNonStop:1");
3986 getpkt (&rs->buf, &rs->buf_size, 0);
3987
3988 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3989 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3990
3991 /* Find about threads and processes the stub is already
3992 controlling. We default to adding them in the running state.
3993 The '?' query below will then tell us about which threads are
3994 stopped. */
e8032dde 3995 remote_update_thread_list (target);
74531fed 3996 }
4082afcc 3997 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3998 {
3999 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4000 Request it explicitly. */
74531fed
PA
4001 putpkt ("QNonStop:0");
4002 getpkt (&rs->buf, &rs->buf_size, 0);
4003
4004 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4005 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4006 }
4007
a0743c90
YQ
4008 /* Upload TSVs regardless of whether the target is running or not. The
4009 remote stub, such as GDBserver, may have some predefined or builtin
4010 TSVs, even if the target is not running. */
8bd200f1 4011 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4012 {
4013 struct uploaded_tsv *uploaded_tsvs = NULL;
4014
181e3713 4015 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4016 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4017 }
4018
2d717e4f
DJ
4019 /* Check whether the target is running now. */
4020 putpkt ("?");
4021 getpkt (&rs->buf, &rs->buf_size, 0);
4022
6efcd9a8 4023 if (!target_is_non_stop_p ())
2d717e4f 4024 {
e714e1bf
UW
4025 ptid_t ptid;
4026 int fake_pid_p = 0;
4027 struct inferior *inf;
4028
74531fed 4029 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4030 {
04bd08de 4031 if (!extended_p)
74531fed 4032 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4033
4034 /* We're connected, but not running. Drop out before we
4035 call start_remote. */
e278ad5b 4036 rs->starting_up = 0;
c35b1492 4037 return;
2d717e4f
DJ
4038 }
4039 else
74531fed 4040 {
74531fed 4041 /* Save the reply for later. */
224c3ddb 4042 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4043 strcpy (wait_status, rs->buf);
4044 }
4045
b7ea362b 4046 /* Fetch thread list. */
e8032dde 4047 target_update_thread_list ();
b7ea362b 4048
74531fed
PA
4049 /* Let the stub know that we want it to return the thread. */
4050 set_continue_thread (minus_one_ptid);
4051
b7ea362b
PA
4052 if (thread_count () == 0)
4053 {
4054 /* Target has no concept of threads at all. GDB treats
4055 non-threaded target as single-threaded; add a main
4056 thread. */
4057 add_current_inferior_and_thread (wait_status);
4058 }
4059 else
4060 {
4061 /* We have thread information; select the thread the target
4062 says should be current. If we're reconnecting to a
4063 multi-threaded program, this will ideally be the thread
4064 that last reported an event before GDB disconnected. */
4065 inferior_ptid = get_current_thread (wait_status);
4066 if (ptid_equal (inferior_ptid, null_ptid))
4067 {
4068 /* Odd... The target was able to list threads, but not
4069 tell us which thread was current (no "thread"
4070 register in T stop reply?). Just pick the first
4071 thread in the thread list then. */
c9f35b34
KB
4072
4073 if (remote_debug)
4074 fprintf_unfiltered (gdb_stdlog,
4075 "warning: couldn't determine remote "
4076 "current thread; picking first in list.\n");
4077
b7ea362b
PA
4078 inferior_ptid = thread_list->ptid;
4079 }
4080 }
74531fed 4081
6e586cc5
YQ
4082 /* init_wait_for_inferior should be called before get_offsets in order
4083 to manage `inserted' flag in bp loc in a correct state.
4084 breakpoint_init_inferior, called from init_wait_for_inferior, set
4085 `inserted' flag to 0, while before breakpoint_re_set, called from
4086 start_remote, set `inserted' flag to 1. In the initialization of
4087 inferior, breakpoint_init_inferior should be called first, and then
4088 breakpoint_re_set can be called. If this order is broken, state of
4089 `inserted' flag is wrong, and cause some problems on breakpoint
4090 manipulation. */
4091 init_wait_for_inferior ();
4092
74531fed
PA
4093 get_offsets (); /* Get text, data & bss offsets. */
4094
d962ef82
DJ
4095 /* If we could not find a description using qXfer, and we know
4096 how to do it some other way, try again. This is not
4097 supported for non-stop; it could be, but it is tricky if
4098 there are no stopped threads when we connect. */
04bd08de 4099 if (remote_read_description_p (target)
f5656ead 4100 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4101 {
4102 target_clear_description ();
4103 target_find_description ();
4104 }
4105
74531fed
PA
4106 /* Use the previously fetched status. */
4107 gdb_assert (wait_status != NULL);
4108 strcpy (rs->buf, wait_status);
4109 rs->cached_wait_status = 1;
4110
4111 immediate_quit--;
04bd08de 4112 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4113 }
4114 else
4115 {
68c97600
PA
4116 /* Clear WFI global state. Do this before finding about new
4117 threads and inferiors, and setting the current inferior.
4118 Otherwise we would clear the proceed status of the current
4119 inferior when we want its stop_soon state to be preserved
4120 (see notice_new_inferior). */
4121 init_wait_for_inferior ();
4122
74531fed
PA
4123 /* In non-stop, we will either get an "OK", meaning that there
4124 are no stopped threads at this time; or, a regular stop
4125 reply. In the latter case, there may be more than one thread
4126 stopped --- we pull them all out using the vStopped
4127 mechanism. */
4128 if (strcmp (rs->buf, "OK") != 0)
4129 {
722247f1 4130 struct notif_client *notif = &notif_client_stop;
2d717e4f 4131
722247f1
YQ
4132 /* remote_notif_get_pending_replies acks this one, and gets
4133 the rest out. */
f48ff2a7 4134 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4135 = remote_notif_parse (notif, rs->buf);
4136 remote_notif_get_pending_events (notif);
74531fed 4137 }
2d717e4f 4138
74531fed
PA
4139 if (thread_count () == 0)
4140 {
04bd08de 4141 if (!extended_p)
74531fed 4142 error (_("The target is not running (try extended-remote?)"));
82f73884 4143
c35b1492
PA
4144 /* We're connected, but not running. Drop out before we
4145 call start_remote. */
e278ad5b 4146 rs->starting_up = 0;
c35b1492
PA
4147 return;
4148 }
74531fed 4149
74531fed
PA
4150 /* In non-stop mode, any cached wait status will be stored in
4151 the stop reply queue. */
4152 gdb_assert (wait_status == NULL);
f0223081 4153
2455069d 4154 /* Report all signals during attach/startup. */
94bedb42 4155 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4156
4157 /* If there are already stopped threads, mark them stopped and
4158 report their stops before giving the prompt to the user. */
6efcd9a8 4159 process_initial_stop_replies (from_tty);
221e1a37
PA
4160
4161 if (target_can_async_p ())
4162 target_async (1);
74531fed 4163 }
c8d104ad 4164
c8d104ad
PA
4165 /* If we connected to a live target, do some additional setup. */
4166 if (target_has_execution)
4167 {
f4ccffad 4168 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4169 remote_check_symbols ();
c8d104ad 4170 }
50c71eaf 4171
d5551862
SS
4172 /* Possibly the target has been engaged in a trace run started
4173 previously; find out where things are at. */
8bd200f1 4174 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4175 {
00bf0b85 4176 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4177
00bf0b85
SS
4178 if (current_trace_status ()->running)
4179 printf_filtered (_("Trace is already running on the target.\n"));
4180
ab6617cc 4181 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4182
4183 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4184 }
4185
1e51243a
PA
4186 /* The thread and inferior lists are now synchronized with the
4187 target, our symbols have been relocated, and we're merged the
4188 target's tracepoints with ours. We're done with basic start
4189 up. */
4190 rs->starting_up = 0;
4191
a25a5a45
PA
4192 /* Maybe breakpoints are global and need to be inserted now. */
4193 if (breakpoints_should_be_inserted_now ())
50c71eaf 4194 insert_breakpoints ();
c906108c
SS
4195}
4196
4197/* Open a connection to a remote debugger.
4198 NAME is the filename used for communication. */
4199
4200static void
014f9477 4201remote_open (const char *name, int from_tty)
c906108c 4202{
75c99385 4203 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4204}
4205
c906108c
SS
4206/* Open a connection to a remote debugger using the extended
4207 remote gdb protocol. NAME is the filename used for communication. */
4208
4209static void
014f9477 4210extended_remote_open (const char *name, int from_tty)
c906108c 4211{
75c99385 4212 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4213}
4214
ca4f7f8b
PA
4215/* Reset all packets back to "unknown support". Called when opening a
4216 new connection to a remote target. */
c906108c 4217
d471ea57 4218static void
ca4f7f8b 4219reset_all_packet_configs_support (void)
d471ea57
AC
4220{
4221 int i;
a744cf53 4222
444abaca 4223 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4224 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4225}
4226
ca4f7f8b
PA
4227/* Initialize all packet configs. */
4228
4229static void
4230init_all_packet_configs (void)
4231{
4232 int i;
4233
4234 for (i = 0; i < PACKET_MAX; i++)
4235 {
4236 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4237 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4238 }
4239}
4240
23860348 4241/* Symbol look-up. */
dc8acb97
MS
4242
4243static void
36d25514 4244remote_check_symbols (void)
dc8acb97 4245{
d01949b6 4246 struct remote_state *rs = get_remote_state ();
dc8acb97 4247 char *msg, *reply, *tmp;
3b7344d5 4248 struct bound_minimal_symbol sym;
dc8acb97 4249 int end;
a5c0808e 4250 struct cleanup *old_chain;
dc8acb97 4251
63154eca
PA
4252 /* The remote side has no concept of inferiors that aren't running
4253 yet, it only knows about running processes. If we're connected
4254 but our current inferior is not running, we should not invite the
4255 remote target to request symbol lookups related to its
4256 (unrelated) current process. */
4257 if (!target_has_execution)
4258 return;
4259
4082afcc 4260 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4261 return;
4262
63154eca
PA
4263 /* Make sure the remote is pointing at the right process. Note
4264 there's no way to select "no process". */
3c9c4b83
PA
4265 set_general_process ();
4266
6d820c5c
DJ
4267 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4268 because we need both at the same time. */
224c3ddb 4269 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4270 old_chain = make_cleanup (xfree, msg);
6d820c5c 4271
23860348 4272 /* Invite target to request symbol lookups. */
dc8acb97
MS
4273
4274 putpkt ("qSymbol::");
6d820c5c
DJ
4275 getpkt (&rs->buf, &rs->buf_size, 0);
4276 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 4277 reply = rs->buf;
dc8acb97 4278
61012eef 4279 while (startswith (reply, "qSymbol:"))
dc8acb97 4280 {
77e371c0
TT
4281 struct bound_minimal_symbol sym;
4282
dc8acb97 4283 tmp = &reply[8];
cfd77fa1 4284 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4285 msg[end] = '\0';
4286 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4287 if (sym.minsym == NULL)
ea9c271d 4288 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4289 else
2bbe3cc1 4290 {
f5656ead 4291 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4292 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4293
4294 /* If this is a function address, return the start of code
4295 instead of any data function descriptor. */
f5656ead 4296 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4297 sym_addr,
4298 &current_target);
4299
4300 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4301 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4302 }
4303
dc8acb97 4304 putpkt (msg);
6d820c5c 4305 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4306 reply = rs->buf;
dc8acb97 4307 }
a5c0808e
PA
4308
4309 do_cleanups (old_chain);
dc8acb97
MS
4310}
4311
9db8d71f 4312static struct serial *
baa336ce 4313remote_serial_open (const char *name)
9db8d71f
DJ
4314{
4315 static int udp_warning = 0;
4316
4317 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4318 of in ser-tcp.c, because it is the remote protocol assuming that the
4319 serial connection is reliable and not the serial connection promising
4320 to be. */
61012eef 4321 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4322 {
3e43a32a
MS
4323 warning (_("The remote protocol may be unreliable over UDP.\n"
4324 "Some events may be lost, rendering further debugging "
4325 "impossible."));
9db8d71f
DJ
4326 udp_warning = 1;
4327 }
4328
4329 return serial_open (name);
4330}
4331
d914c394
SS
4332/* Inform the target of our permission settings. The permission flags
4333 work without this, but if the target knows the settings, it can do
4334 a couple things. First, it can add its own check, to catch cases
4335 that somehow manage to get by the permissions checks in target
4336 methods. Second, if the target is wired to disallow particular
4337 settings (for instance, a system in the field that is not set up to
4338 be able to stop at a breakpoint), it can object to any unavailable
4339 permissions. */
4340
4341void
c378d69d 4342remote_set_permissions (struct target_ops *self)
d914c394
SS
4343{
4344 struct remote_state *rs = get_remote_state ();
4345
bba74b36
YQ
4346 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4347 "WriteReg:%x;WriteMem:%x;"
4348 "InsertBreak:%x;InsertTrace:%x;"
4349 "InsertFastTrace:%x;Stop:%x",
4350 may_write_registers, may_write_memory,
4351 may_insert_breakpoints, may_insert_tracepoints,
4352 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4353 putpkt (rs->buf);
4354 getpkt (&rs->buf, &rs->buf_size, 0);
4355
4356 /* If the target didn't like the packet, warn the user. Do not try
4357 to undo the user's settings, that would just be maddening. */
4358 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4359 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4360}
4361
be2a5f71
DJ
4362/* This type describes each known response to the qSupported
4363 packet. */
4364struct protocol_feature
4365{
4366 /* The name of this protocol feature. */
4367 const char *name;
4368
4369 /* The default for this protocol feature. */
4370 enum packet_support default_support;
4371
4372 /* The function to call when this feature is reported, or after
4373 qSupported processing if the feature is not supported.
4374 The first argument points to this structure. The second
4375 argument indicates whether the packet requested support be
4376 enabled, disabled, or probed (or the default, if this function
4377 is being called at the end of processing and this feature was
4378 not reported). The third argument may be NULL; if not NULL, it
4379 is a NUL-terminated string taken from the packet following
4380 this feature's name and an equals sign. */
4381 void (*func) (const struct protocol_feature *, enum packet_support,
4382 const char *);
4383
4384 /* The corresponding packet for this feature. Only used if
4385 FUNC is remote_supported_packet. */
4386 int packet;
4387};
4388
be2a5f71
DJ
4389static void
4390remote_supported_packet (const struct protocol_feature *feature,
4391 enum packet_support support,
4392 const char *argument)
4393{
4394 if (argument)
4395 {
4396 warning (_("Remote qSupported response supplied an unexpected value for"
4397 " \"%s\"."), feature->name);
4398 return;
4399 }
4400
4082afcc 4401 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4402}
be2a5f71
DJ
4403
4404static void
4405remote_packet_size (const struct protocol_feature *feature,
4406 enum packet_support support, const char *value)
4407{
4408 struct remote_state *rs = get_remote_state ();
4409
4410 int packet_size;
4411 char *value_end;
4412
4413 if (support != PACKET_ENABLE)
4414 return;
4415
4416 if (value == NULL || *value == '\0')
4417 {
4418 warning (_("Remote target reported \"%s\" without a size."),
4419 feature->name);
4420 return;
4421 }
4422
4423 errno = 0;
4424 packet_size = strtol (value, &value_end, 16);
4425 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4426 {
4427 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4428 feature->name, value);
4429 return;
4430 }
4431
be2a5f71
DJ
4432 /* Record the new maximum packet size. */
4433 rs->explicit_packet_size = packet_size;
4434}
4435
dc473cfb 4436static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4437 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4438 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4439 PACKET_qXfer_auxv },
c78fa86a
GB
4440 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4441 PACKET_qXfer_exec_file },
23181151
DJ
4442 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4443 PACKET_qXfer_features },
cfa9d6d9
DJ
4444 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4445 PACKET_qXfer_libraries },
2268b414
JK
4446 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4447 PACKET_qXfer_libraries_svr4 },
ced63ec0 4448 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4449 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4450 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4451 PACKET_qXfer_memory_map },
4de6483e
UW
4452 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4453 PACKET_qXfer_spu_read },
4454 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4455 PACKET_qXfer_spu_write },
07e059b5
VP
4456 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4457 PACKET_qXfer_osdata },
dc146f7c
VP
4458 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4459 PACKET_qXfer_threads },
b3b9301e
PA
4460 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4461 PACKET_qXfer_traceframe_info },
89be2091
DJ
4462 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4463 PACKET_QPassSignals },
9b224c5e
PA
4464 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4465 PACKET_QProgramSignals },
a6f3e723
SL
4466 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4467 PACKET_QStartNoAckMode },
4082afcc
PA
4468 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4469 PACKET_multiprocess_feature },
4470 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4471 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4472 PACKET_qXfer_siginfo_read },
4473 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4474 PACKET_qXfer_siginfo_write },
4082afcc 4475 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4476 PACKET_ConditionalTracepoints },
4082afcc 4477 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4478 PACKET_ConditionalBreakpoints },
4082afcc 4479 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4480 PACKET_BreakpointCommands },
4082afcc 4481 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4482 PACKET_FastTracepoints },
4082afcc 4483 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4484 PACKET_StaticTracepoints },
4082afcc 4485 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4486 PACKET_InstallInTrace},
4082afcc
PA
4487 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4488 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4489 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4490 PACKET_bc },
4491 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4492 PACKET_bs },
409873ef
SS
4493 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4494 PACKET_TracepointSource },
d914c394
SS
4495 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4496 PACKET_QAllow },
4082afcc
PA
4497 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4498 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4499 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4500 PACKET_qXfer_fdpic },
169081d0
TG
4501 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4502 PACKET_qXfer_uib },
03583c20
UW
4503 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4504 PACKET_QDisableRandomization },
d1feda86 4505 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4506 { "QTBuffer:size", PACKET_DISABLE,
4507 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4508 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4509 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4510 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4511 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4512 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4513 PACKET_qXfer_btrace },
4514 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4515 PACKET_qXfer_btrace_conf },
4516 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4517 PACKET_Qbtrace_conf_bts_size },
4518 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4519 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4520 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4521 PACKET_fork_event_feature },
4522 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4523 PACKET_vfork_event_feature },
94585166
DB
4524 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4525 PACKET_exec_event_feature },
b20a6524 4526 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4527 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4528 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4529 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
be2a5f71
DJ
4530};
4531
c8d5aac9
L
4532static char *remote_support_xml;
4533
4534/* Register string appended to "xmlRegisters=" in qSupported query. */
4535
4536void
6e39997a 4537register_remote_support_xml (const char *xml)
c8d5aac9
L
4538{
4539#if defined(HAVE_LIBEXPAT)
4540 if (remote_support_xml == NULL)
c4f7c687 4541 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4542 else
4543 {
4544 char *copy = xstrdup (remote_support_xml + 13);
4545 char *p = strtok (copy, ",");
4546
4547 do
4548 {
4549 if (strcmp (p, xml) == 0)
4550 {
4551 /* already there */
4552 xfree (copy);
4553 return;
4554 }
4555 }
4556 while ((p = strtok (NULL, ",")) != NULL);
4557 xfree (copy);
4558
94b0dee1
PA
4559 remote_support_xml = reconcat (remote_support_xml,
4560 remote_support_xml, ",", xml,
4561 (char *) NULL);
c8d5aac9
L
4562 }
4563#endif
4564}
4565
4566static char *
4567remote_query_supported_append (char *msg, const char *append)
4568{
4569 if (msg)
94b0dee1 4570 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4571 else
4572 return xstrdup (append);
4573}
4574
be2a5f71
DJ
4575static void
4576remote_query_supported (void)
4577{
4578 struct remote_state *rs = get_remote_state ();
4579 char *next;
4580 int i;
4581 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4582
4583 /* The packet support flags are handled differently for this packet
4584 than for most others. We treat an error, a disabled packet, and
4585 an empty response identically: any features which must be reported
4586 to be used will be automatically disabled. An empty buffer
4587 accomplishes this, since that is also the representation for a list
4588 containing no features. */
4589
4590 rs->buf[0] = 0;
4082afcc 4591 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4592 {
c8d5aac9 4593 char *q = NULL;
94b0dee1 4594 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4595
73b8c1fd
PA
4596 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4597 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4598
f7e6eed5
PA
4599 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4600 q = remote_query_supported_append (q, "swbreak+");
4601 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4602 q = remote_query_supported_append (q, "hwbreak+");
4603
dde08ee1
PA
4604 q = remote_query_supported_append (q, "qRelocInsn+");
4605
89245bc0
DB
4606 if (rs->extended)
4607 {
4608 if (packet_set_cmd_state (PACKET_fork_event_feature)
4609 != AUTO_BOOLEAN_FALSE)
4610 q = remote_query_supported_append (q, "fork-events+");
4611 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4612 != AUTO_BOOLEAN_FALSE)
4613 q = remote_query_supported_append (q, "vfork-events+");
94585166
DB
4614 if (packet_set_cmd_state (PACKET_exec_event_feature)
4615 != AUTO_BOOLEAN_FALSE)
4616 q = remote_query_supported_append (q, "exec-events+");
89245bc0
DB
4617 }
4618
750ce8d1
YQ
4619 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4620 q = remote_query_supported_append (q, "vContSupported+");
4621
65706a29
PA
4622 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4623 q = remote_query_supported_append (q, "QThreadEvents+");
4624
b35d5edb
PA
4625 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4626 the qSupported:xmlRegisters=i386 handling. */
4627 if (remote_support_xml != NULL)
4628 q = remote_query_supported_append (q, remote_support_xml);
4629
dde08ee1
PA
4630 q = reconcat (q, "qSupported:", q, (char *) NULL);
4631 putpkt (q);
82f73884 4632
94b0dee1
PA
4633 do_cleanups (old_chain);
4634
be2a5f71
DJ
4635 getpkt (&rs->buf, &rs->buf_size, 0);
4636
4637 /* If an error occured, warn, but do not return - just reset the
4638 buffer to empty and go on to disable features. */
4639 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4640 == PACKET_ERROR)
4641 {
4642 warning (_("Remote failure reply: %s"), rs->buf);
4643 rs->buf[0] = 0;
4644 }
4645 }
4646
4647 memset (seen, 0, sizeof (seen));
4648
4649 next = rs->buf;
4650 while (*next)
4651 {
4652 enum packet_support is_supported;
4653 char *p, *end, *name_end, *value;
4654
4655 /* First separate out this item from the rest of the packet. If
4656 there's another item after this, we overwrite the separator
4657 (terminated strings are much easier to work with). */
4658 p = next;
4659 end = strchr (p, ';');
4660 if (end == NULL)
4661 {
4662 end = p + strlen (p);
4663 next = end;
4664 }
4665 else
4666 {
89be2091
DJ
4667 *end = '\0';
4668 next = end + 1;
4669
be2a5f71
DJ
4670 if (end == p)
4671 {
4672 warning (_("empty item in \"qSupported\" response"));
4673 continue;
4674 }
be2a5f71
DJ
4675 }
4676
4677 name_end = strchr (p, '=');
4678 if (name_end)
4679 {
4680 /* This is a name=value entry. */
4681 is_supported = PACKET_ENABLE;
4682 value = name_end + 1;
4683 *name_end = '\0';
4684 }
4685 else
4686 {
4687 value = NULL;
4688 switch (end[-1])
4689 {
4690 case '+':
4691 is_supported = PACKET_ENABLE;
4692 break;
4693
4694 case '-':
4695 is_supported = PACKET_DISABLE;
4696 break;
4697
4698 case '?':
4699 is_supported = PACKET_SUPPORT_UNKNOWN;
4700 break;
4701
4702 default:
3e43a32a
MS
4703 warning (_("unrecognized item \"%s\" "
4704 "in \"qSupported\" response"), p);
be2a5f71
DJ
4705 continue;
4706 }
4707 end[-1] = '\0';
4708 }
4709
4710 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4711 if (strcmp (remote_protocol_features[i].name, p) == 0)
4712 {
4713 const struct protocol_feature *feature;
4714
4715 seen[i] = 1;
4716 feature = &remote_protocol_features[i];
4717 feature->func (feature, is_supported, value);
4718 break;
4719 }
4720 }
4721
4722 /* If we increased the packet size, make sure to increase the global
4723 buffer size also. We delay this until after parsing the entire
4724 qSupported packet, because this is the same buffer we were
4725 parsing. */
4726 if (rs->buf_size < rs->explicit_packet_size)
4727 {
4728 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4729 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4730 }
4731
4732 /* Handle the defaults for unmentioned features. */
4733 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4734 if (!seen[i])
4735 {
4736 const struct protocol_feature *feature;
4737
4738 feature = &remote_protocol_features[i];
4739 feature->func (feature, feature->default_support, NULL);
4740 }
4741}
4742
78a095c3
JK
4743/* Remove any of the remote.c targets from target stack. Upper targets depend
4744 on it so remove them first. */
4745
4746static void
4747remote_unpush_target (void)
4748{
915ef8b1 4749 pop_all_targets_at_and_above (process_stratum);
78a095c3 4750}
be2a5f71 4751
c906108c 4752static void
014f9477 4753remote_open_1 (const char *name, int from_tty,
3e43a32a 4754 struct target_ops *target, int extended_p)
c906108c 4755{
d01949b6 4756 struct remote_state *rs = get_remote_state ();
a6f3e723 4757
c906108c 4758 if (name == 0)
8a3fe4f8 4759 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4760 "serial device is attached to the remote system\n"
8a3fe4f8 4761 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4762
23860348 4763 /* See FIXME above. */
c6ebd6cf 4764 if (!target_async_permitted)
92d1e331 4765 wait_forever_enabled_p = 1;
6426a772 4766
2d717e4f 4767 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4768 Ask this question first, before target_preopen has a chance to kill
4769 anything. */
5d93a237 4770 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4771 {
78a095c3
JK
4772 if (from_tty
4773 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4774 error (_("Still connected."));
4775 }
4776
78a095c3 4777 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4778 target_preopen (from_tty);
4779
89be2091 4780 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4781 xfree (rs->last_pass_packet);
4782 rs->last_pass_packet = NULL;
89be2091 4783
9b224c5e
PA
4784 /* Make sure we send the program signals list the next time we
4785 resume. */
5e4a05c4
TT
4786 xfree (rs->last_program_signals_packet);
4787 rs->last_program_signals_packet = NULL;
9b224c5e 4788
ad9a8f3f 4789 remote_fileio_reset ();
1dd41f16
NS
4790 reopen_exec_file ();
4791 reread_symbols ();
4792
5d93a237
TT
4793 rs->remote_desc = remote_serial_open (name);
4794 if (!rs->remote_desc)
c906108c
SS
4795 perror_with_name (name);
4796
4797 if (baud_rate != -1)
4798 {
5d93a237 4799 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4800 {
9b74d5d3
KB
4801 /* The requested speed could not be set. Error out to
4802 top level after closing remote_desc. Take care to
4803 set remote_desc to NULL to avoid closing remote_desc
4804 more than once. */
5d93a237
TT
4805 serial_close (rs->remote_desc);
4806 rs->remote_desc = NULL;
c906108c
SS
4807 perror_with_name (name);
4808 }
4809 }
4810
236af5e3 4811 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4812 serial_raw (rs->remote_desc);
c906108c
SS
4813
4814 /* If there is something sitting in the buffer we might take it as a
4815 response to a command, which would be bad. */
5d93a237 4816 serial_flush_input (rs->remote_desc);
c906108c
SS
4817
4818 if (from_tty)
4819 {
4820 puts_filtered ("Remote debugging using ");
4821 puts_filtered (name);
4822 puts_filtered ("\n");
4823 }
23860348 4824 push_target (target); /* Switch to using remote target now. */
c906108c 4825
74531fed
PA
4826 /* Register extra event sources in the event loop. */
4827 remote_async_inferior_event_token
4828 = create_async_event_handler (remote_async_inferior_event_handler,
4829 NULL);
5965e028 4830 rs->notif_state = remote_notif_state_allocate ();
74531fed 4831
be2a5f71
DJ
4832 /* Reset the target state; these things will be queried either by
4833 remote_query_supported or as they are needed. */
ca4f7f8b 4834 reset_all_packet_configs_support ();
74531fed 4835 rs->cached_wait_status = 0;
be2a5f71 4836 rs->explicit_packet_size = 0;
a6f3e723 4837 rs->noack_mode = 0;
82f73884 4838 rs->extended = extended_p;
e24a49d8 4839 rs->waiting_for_stop_reply = 0;
3a29589a 4840 rs->ctrlc_pending_p = 0;
802188a7 4841
47f8a51d
TT
4842 rs->general_thread = not_sent_ptid;
4843 rs->continue_thread = not_sent_ptid;
262e1174 4844 rs->remote_traceframe_number = -1;
c906108c 4845
9d1f7ab2 4846 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4847 rs->use_threadinfo_query = 1;
4848 rs->use_threadextra_query = 1;
9d1f7ab2 4849
80152258
PA
4850 readahead_cache_invalidate ();
4851
c6ebd6cf 4852 if (target_async_permitted)
92d1e331 4853 {
23860348 4854 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4855 remote_async_terminal_ours_p = 1;
4856
4857 /* FIXME: cagney/1999-09-23: During the initial connection it is
4858 assumed that the target is already ready and able to respond to
0df8b418 4859 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4860 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4861 around this. Eventually a mechanism that allows
92d1e331 4862 wait_for_inferior() to expect/get timeouts will be
23860348 4863 implemented. */
92d1e331
DJ
4864 wait_forever_enabled_p = 0;
4865 }
4866
23860348 4867 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4868 no_shared_libraries (NULL, 0);
f78f6cf1 4869
74531fed
PA
4870 /* Start afresh. */
4871 init_thread_list ();
4872
36918e70 4873 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4874 target (we'd otherwise be in an inconsistent state) and then
4875 propogate the error on up the exception chain. This ensures that
4876 the caller doesn't stumble along blindly assuming that the
4877 function succeeded. The CLI doesn't have this problem but other
4878 UI's, such as MI do.
36918e70
AC
4879
4880 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4881 this function should return an error indication letting the
ce2826aa 4882 caller restore the previous state. Unfortunately the command
36918e70
AC
4883 ``target remote'' is directly wired to this function making that
4884 impossible. On a positive note, the CLI side of this problem has
4885 been fixed - the function set_cmd_context() makes it possible for
4886 all the ``target ....'' commands to share a common callback
4887 function. See cli-dump.c. */
109c3e39 4888 {
2d717e4f 4889
492d29ea 4890 TRY
04bd08de
TT
4891 {
4892 remote_start_remote (from_tty, target, extended_p);
4893 }
492d29ea 4894 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4895 {
c8d104ad
PA
4896 /* Pop the partially set up target - unless something else did
4897 already before throwing the exception. */
5d93a237 4898 if (rs->remote_desc != NULL)
78a095c3 4899 remote_unpush_target ();
c6ebd6cf 4900 if (target_async_permitted)
109c3e39
AC
4901 wait_forever_enabled_p = 1;
4902 throw_exception (ex);
4903 }
492d29ea 4904 END_CATCH
109c3e39 4905 }
c906108c 4906
f4abbc16
MM
4907 remote_btrace_reset ();
4908
c6ebd6cf 4909 if (target_async_permitted)
92d1e331 4910 wait_forever_enabled_p = 1;
43ff13b4
JM
4911}
4912
de0d863e
DB
4913/* Detach the specified process. */
4914
4915static void
4916remote_detach_pid (int pid)
4917{
4918 struct remote_state *rs = get_remote_state ();
4919
4920 if (remote_multi_process_p (rs))
4921 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4922 else
4923 strcpy (rs->buf, "D");
4924
4925 putpkt (rs->buf);
4926 getpkt (&rs->buf, &rs->buf_size, 0);
4927
4928 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4929 ;
4930 else if (rs->buf[0] == '\0')
4931 error (_("Remote doesn't know how to detach"));
4932 else
4933 error (_("Can't detach process."));
4934}
4935
4936/* This detaches a program to which we previously attached, using
4937 inferior_ptid to identify the process. After this is done, GDB
4938 can be used to debug some other program. We better not have left
4939 any breakpoints in the target program or it'll die when it hits
4940 one. */
c906108c
SS
4941
4942static void
de0d863e 4943remote_detach_1 (const char *args, int from_tty)
c906108c 4944{
82f73884 4945 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4946 struct remote_state *rs = get_remote_state ();
de0d863e
DB
4947 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4948 int is_fork_parent;
c906108c
SS
4949
4950 if (args)
8a3fe4f8 4951 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4952
2d717e4f
DJ
4953 if (!target_has_execution)
4954 error (_("No process to detach from."));
4955
7cee1e54
PA
4956 if (from_tty)
4957 {
4958 char *exec_file = get_exec_file (0);
4959 if (exec_file == NULL)
4960 exec_file = "";
4961 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4962 target_pid_to_str (pid_to_ptid (pid)));
4963 gdb_flush (gdb_stdout);
4964 }
4965
c906108c 4966 /* Tell the remote target to detach. */
de0d863e 4967 remote_detach_pid (pid);
82f73884 4968
de0d863e 4969 if (from_tty && !rs->extended)
7cee1e54 4970 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4971
de0d863e
DB
4972 /* Check to see if we are detaching a fork parent. Note that if we
4973 are detaching a fork child, tp == NULL. */
4974 is_fork_parent = (tp != NULL
4975 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4976
4977 /* If doing detach-on-fork, we don't mourn, because that will delete
4978 breakpoints that should be available for the followed inferior. */
4979 if (!is_fork_parent)
4980 target_mourn_inferior ();
4981 else
4982 {
4983 inferior_ptid = null_ptid;
4984 detach_inferior (pid);
4985 }
2d717e4f
DJ
4986}
4987
4988static void
52554a0e 4989remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4990{
de0d863e 4991 remote_detach_1 (args, from_tty);
2d717e4f
DJ
4992}
4993
4994static void
52554a0e 4995extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4996{
de0d863e
DB
4997 remote_detach_1 (args, from_tty);
4998}
4999
5000/* Target follow-fork function for remote targets. On entry, and
5001 at return, the current inferior is the fork parent.
5002
5003 Note that although this is currently only used for extended-remote,
5004 it is named remote_follow_fork in anticipation of using it for the
5005 remote target as well. */
5006
5007static int
5008remote_follow_fork (struct target_ops *ops, int follow_child,
5009 int detach_fork)
5010{
5011 struct remote_state *rs = get_remote_state ();
c269dbdb 5012 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5013
c269dbdb
DB
5014 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5015 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5016 {
5017 /* When following the parent and detaching the child, we detach
5018 the child here. For the case of following the child and
5019 detaching the parent, the detach is done in the target-
5020 independent follow fork code in infrun.c. We can't use
5021 target_detach when detaching an unfollowed child because
5022 the client side doesn't know anything about the child. */
5023 if (detach_fork && !follow_child)
5024 {
5025 /* Detach the fork child. */
5026 ptid_t child_ptid;
5027 pid_t child_pid;
5028
5029 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5030 child_pid = ptid_get_pid (child_ptid);
5031
5032 remote_detach_pid (child_pid);
5033 detach_inferior (child_pid);
5034 }
5035 }
5036 return 0;
c906108c
SS
5037}
5038
94585166
DB
5039/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5040 in the program space of the new inferior. On entry and at return the
5041 current inferior is the exec'ing inferior. INF is the new exec'd
5042 inferior, which may be the same as the exec'ing inferior unless
5043 follow-exec-mode is "new". */
5044
5045static void
5046remote_follow_exec (struct target_ops *ops,
5047 struct inferior *inf, char *execd_pathname)
5048{
5049 /* We know that this is a target file name, so if it has the "target:"
5050 prefix we strip it off before saving it in the program space. */
5051 if (is_target_filename (execd_pathname))
5052 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5053
5054 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5055}
5056
6ad8ae5c
DJ
5057/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5058
43ff13b4 5059static void
fee354ee 5060remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5061{
43ff13b4 5062 if (args)
2d717e4f 5063 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5064
2d717e4f 5065 /* Make sure we unpush even the extended remote targets; mourn
20f796c9 5066 won't do it. So call remote_mourn directly instead of
2d717e4f 5067 target_mourn_inferior. */
20f796c9 5068 remote_mourn (target);
2d717e4f 5069
43ff13b4
JM
5070 if (from_tty)
5071 puts_filtered ("Ending remote debugging.\n");
5072}
5073
2d717e4f
DJ
5074/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5075 be chatty about it. */
5076
5077static void
20f796c9
GB
5078extended_remote_attach (struct target_ops *target, const char *args,
5079 int from_tty)
2d717e4f
DJ
5080{
5081 struct remote_state *rs = get_remote_state ();
be86555c 5082 int pid;
96ef3384 5083 char *wait_status = NULL;
2d717e4f 5084
74164c56 5085 pid = parse_pid_to_attach (args);
2d717e4f 5086
74164c56
JK
5087 /* Remote PID can be freely equal to getpid, do not check it here the same
5088 way as in other targets. */
2d717e4f 5089
4082afcc 5090 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5091 error (_("This target does not support attaching to a process"));
5092
7cee1e54
PA
5093 if (from_tty)
5094 {
5095 char *exec_file = get_exec_file (0);
5096
5097 if (exec_file)
5098 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5099 target_pid_to_str (pid_to_ptid (pid)));
5100 else
5101 printf_unfiltered (_("Attaching to %s\n"),
5102 target_pid_to_str (pid_to_ptid (pid)));
5103
5104 gdb_flush (gdb_stdout);
5105 }
5106
bba74b36 5107 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5108 putpkt (rs->buf);
5109 getpkt (&rs->buf, &rs->buf_size, 0);
5110
4082afcc
PA
5111 switch (packet_ok (rs->buf,
5112 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5113 {
4082afcc 5114 case PACKET_OK:
6efcd9a8 5115 if (!target_is_non_stop_p ())
74531fed
PA
5116 {
5117 /* Save the reply for later. */
224c3ddb 5118 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5119 strcpy (wait_status, rs->buf);
5120 }
5121 else if (strcmp (rs->buf, "OK") != 0)
5122 error (_("Attaching to %s failed with: %s"),
5123 target_pid_to_str (pid_to_ptid (pid)),
5124 rs->buf);
4082afcc
PA
5125 break;
5126 case PACKET_UNKNOWN:
5127 error (_("This target does not support attaching to a process"));
5128 default:
5129 error (_("Attaching to %s failed"),
5130 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5131 }
2d717e4f 5132
1b6e6f5c 5133 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5134
2d717e4f 5135 inferior_ptid = pid_to_ptid (pid);
79d7f229 5136
6efcd9a8 5137 if (target_is_non_stop_p ())
bad34192
PA
5138 {
5139 struct thread_info *thread;
79d7f229 5140
bad34192 5141 /* Get list of threads. */
e8032dde 5142 remote_update_thread_list (target);
82f73884 5143
bad34192
PA
5144 thread = first_thread_of_process (pid);
5145 if (thread)
5146 inferior_ptid = thread->ptid;
5147 else
5148 inferior_ptid = pid_to_ptid (pid);
5149
5150 /* Invalidate our notion of the remote current thread. */
47f8a51d 5151 record_currthread (rs, minus_one_ptid);
bad34192 5152 }
74531fed 5153 else
bad34192
PA
5154 {
5155 /* Now, if we have thread information, update inferior_ptid. */
5156 inferior_ptid = remote_current_thread (inferior_ptid);
5157
5158 /* Add the main thread to the thread list. */
5159 add_thread_silent (inferior_ptid);
5160 }
c0a2216e 5161
96ef3384
UW
5162 /* Next, if the target can specify a description, read it. We do
5163 this before anything involving memory or registers. */
5164 target_find_description ();
5165
6efcd9a8 5166 if (!target_is_non_stop_p ())
74531fed
PA
5167 {
5168 /* Use the previously fetched status. */
5169 gdb_assert (wait_status != NULL);
5170
5171 if (target_can_async_p ())
5172 {
722247f1
YQ
5173 struct notif_event *reply
5174 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5175
722247f1 5176 push_stop_reply ((struct stop_reply *) reply);
74531fed 5177
6a3753b3 5178 target_async (1);
74531fed
PA
5179 }
5180 else
5181 {
5182 gdb_assert (wait_status != NULL);
5183 strcpy (rs->buf, wait_status);
5184 rs->cached_wait_status = 1;
5185 }
5186 }
5187 else
5188 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5189}
5190
b9c1d481
AS
5191/* Implementation of the to_post_attach method. */
5192
5193static void
5194extended_remote_post_attach (struct target_ops *ops, int pid)
5195{
6efcd9a8
PA
5196 /* Get text, data & bss offsets. */
5197 get_offsets ();
5198
b9c1d481
AS
5199 /* In certain cases GDB might not have had the chance to start
5200 symbol lookup up until now. This could happen if the debugged
5201 binary is not using shared libraries, the vsyscall page is not
5202 present (on Linux) and the binary itself hadn't changed since the
5203 debugging process was started. */
5204 if (symfile_objfile != NULL)
5205 remote_check_symbols();
5206}
5207
c906108c 5208\f
506fb367
DJ
5209/* Check for the availability of vCont. This function should also check
5210 the response. */
c906108c
SS
5211
5212static void
6d820c5c 5213remote_vcont_probe (struct remote_state *rs)
c906108c 5214{
2e9f7625 5215 char *buf;
6d820c5c 5216
2e9f7625
DJ
5217 strcpy (rs->buf, "vCont?");
5218 putpkt (rs->buf);
6d820c5c 5219 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5220 buf = rs->buf;
c906108c 5221
506fb367 5222 /* Make sure that the features we assume are supported. */
61012eef 5223 if (startswith (buf, "vCont"))
506fb367
DJ
5224 {
5225 char *p = &buf[5];
750ce8d1 5226 int support_c, support_C;
506fb367 5227
750ce8d1
YQ
5228 rs->supports_vCont.s = 0;
5229 rs->supports_vCont.S = 0;
506fb367
DJ
5230 support_c = 0;
5231 support_C = 0;
d458bd84 5232 rs->supports_vCont.t = 0;
c1e36e3e 5233 rs->supports_vCont.r = 0;
506fb367
DJ
5234 while (p && *p == ';')
5235 {
5236 p++;
5237 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5238 rs->supports_vCont.s = 1;
506fb367 5239 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5240 rs->supports_vCont.S = 1;
506fb367
DJ
5241 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5242 support_c = 1;
5243 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5244 support_C = 1;
74531fed 5245 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5246 rs->supports_vCont.t = 1;
c1e36e3e
PA
5247 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5248 rs->supports_vCont.r = 1;
506fb367
DJ
5249
5250 p = strchr (p, ';');
5251 }
c906108c 5252
750ce8d1
YQ
5253 /* If c, and C are not all supported, we can't use vCont. Clearing
5254 BUF will make packet_ok disable the packet. */
5255 if (!support_c || !support_C)
506fb367
DJ
5256 buf[0] = 0;
5257 }
c906108c 5258
444abaca 5259 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5260}
c906108c 5261
0d8f58ca
PA
5262/* Helper function for building "vCont" resumptions. Write a
5263 resumption to P. ENDP points to one-passed-the-end of the buffer
5264 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5265 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5266 resumed thread should be single-stepped and/or signalled. If PTID
5267 equals minus_one_ptid, then all threads are resumed; if PTID
5268 represents a process, then all threads of the process are resumed;
5269 the thread to be stepped and/or signalled is given in the global
5270 INFERIOR_PTID. */
5271
5272static char *
5273append_resumption (char *p, char *endp,
2ea28649 5274 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5275{
5276 struct remote_state *rs = get_remote_state ();
5277
a493e3e2 5278 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5279 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5280 else if (step
5281 /* GDB is willing to range step. */
5282 && use_range_stepping
5283 /* Target supports range stepping. */
5284 && rs->supports_vCont.r
5285 /* We don't currently support range stepping multiple
5286 threads with a wildcard (though the protocol allows it,
5287 so stubs shouldn't make an active effort to forbid
5288 it). */
5289 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5290 {
5291 struct thread_info *tp;
5292
5293 if (ptid_equal (ptid, minus_one_ptid))
5294 {
5295 /* If we don't know about the target thread's tid, then
5296 we're resuming magic_null_ptid (see caller). */
5297 tp = find_thread_ptid (magic_null_ptid);
5298 }
5299 else
5300 tp = find_thread_ptid (ptid);
5301 gdb_assert (tp != NULL);
5302
5303 if (tp->control.may_range_step)
5304 {
5305 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5306
5307 p += xsnprintf (p, endp - p, ";r%s,%s",
5308 phex_nz (tp->control.step_range_start,
5309 addr_size),
5310 phex_nz (tp->control.step_range_end,
5311 addr_size));
5312 }
5313 else
5314 p += xsnprintf (p, endp - p, ";s");
5315 }
0d8f58ca
PA
5316 else if (step)
5317 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5318 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5319 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5320 else
5321 p += xsnprintf (p, endp - p, ";c");
5322
5323 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5324 {
5325 ptid_t nptid;
5326
5327 /* All (-1) threads of process. */
ba348170 5328 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5329
5330 p += xsnprintf (p, endp - p, ":");
5331 p = write_ptid (p, endp, nptid);
5332 }
5333 else if (!ptid_equal (ptid, minus_one_ptid))
5334 {
5335 p += xsnprintf (p, endp - p, ":");
5336 p = write_ptid (p, endp, ptid);
5337 }
5338
5339 return p;
5340}
5341
799a2abe
PA
5342/* Clear the thread's private info on resume. */
5343
5344static void
5345resume_clear_thread_private_info (struct thread_info *thread)
5346{
5347 if (thread->priv != NULL)
5348 {
5349 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5350 thread->priv->watch_data_address = 0;
5351 }
5352}
5353
e5ef252a
PA
5354/* Append a vCont continue-with-signal action for threads that have a
5355 non-zero stop signal. */
5356
5357static char *
5358append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5359{
5360 struct thread_info *thread;
5361
034f788c 5362 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5363 if (ptid_match (thread->ptid, ptid)
5364 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5365 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5366 {
5367 p = append_resumption (p, endp, thread->ptid,
5368 0, thread->suspend.stop_signal);
5369 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5370 resume_clear_thread_private_info (thread);
e5ef252a
PA
5371 }
5372
5373 return p;
5374}
5375
506fb367
DJ
5376/* Resume the remote inferior by using a "vCont" packet. The thread
5377 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5378 resumed thread should be single-stepped and/or signalled. If PTID
5379 equals minus_one_ptid, then all threads are resumed; the thread to
5380 be stepped and/or signalled is given in the global INFERIOR_PTID.
5381 This function returns non-zero iff it resumes the inferior.
44eaed12 5382
506fb367
DJ
5383 This function issues a strict subset of all possible vCont commands at the
5384 moment. */
44eaed12 5385
506fb367 5386static int
2ea28649 5387remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5388{
5389 struct remote_state *rs = get_remote_state ();
82f73884
PA
5390 char *p;
5391 char *endp;
44eaed12 5392
4082afcc 5393 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5394 remote_vcont_probe (rs);
44eaed12 5395
4082afcc 5396 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5397 return 0;
44eaed12 5398
82f73884
PA
5399 p = rs->buf;
5400 endp = rs->buf + get_remote_packet_size ();
5401
506fb367
DJ
5402 /* If we could generate a wider range of packets, we'd have to worry
5403 about overflowing BUF. Should there be a generic
5404 "multi-part-packet" packet? */
5405
0d8f58ca
PA
5406 p += xsnprintf (p, endp - p, "vCont");
5407
79d7f229 5408 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5409 {
79d7f229
PA
5410 /* MAGIC_NULL_PTID means that we don't have any active threads,
5411 so we don't have any TID numbers the inferior will
5412 understand. Make sure to only send forms that do not specify
5413 a TID. */
a9cbf802 5414 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5415 }
0d8f58ca 5416 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5417 {
0d8f58ca
PA
5418 /* Resume all threads (of all processes, or of a single
5419 process), with preference for INFERIOR_PTID. This assumes
5420 inferior_ptid belongs to the set of all threads we are about
5421 to resume. */
a493e3e2 5422 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5423 {
0d8f58ca
PA
5424 /* Step inferior_ptid, with or without signal. */
5425 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5426 }
0d8f58ca 5427
e5ef252a
PA
5428 /* Also pass down any pending signaled resumption for other
5429 threads not the current. */
5430 p = append_pending_thread_resumptions (p, endp, ptid);
5431
0d8f58ca 5432 /* And continue others without a signal. */
a493e3e2 5433 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5434 }
5435 else
506fb367
DJ
5436 {
5437 /* Scheduler locking; resume only PTID. */
a9cbf802 5438 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5439 }
c906108c 5440
82f73884
PA
5441 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5442 putpkt (rs->buf);
506fb367 5443
6efcd9a8 5444 if (target_is_non_stop_p ())
74531fed
PA
5445 {
5446 /* In non-stop, the stub replies to vCont with "OK". The stop
5447 reply will be reported asynchronously by means of a `%Stop'
5448 notification. */
5449 getpkt (&rs->buf, &rs->buf_size, 0);
5450 if (strcmp (rs->buf, "OK") != 0)
5451 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5452 }
5453
506fb367 5454 return 1;
c906108c 5455}
43ff13b4 5456
506fb367
DJ
5457/* Tell the remote machine to resume. */
5458
43ff13b4 5459static void
28439f5e 5460remote_resume (struct target_ops *ops,
2ea28649 5461 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5462{
d01949b6 5463 struct remote_state *rs = get_remote_state ();
2e9f7625 5464 char *buf;
799a2abe 5465 struct thread_info *thread;
43ff13b4 5466
722247f1
YQ
5467 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5468 (explained in remote-notif.c:handle_notification) so
5469 remote_notif_process is not called. We need find a place where
5470 it is safe to start a 'vNotif' sequence. It is good to do it
5471 before resuming inferior, because inferior was stopped and no RSP
5472 traffic at that moment. */
6efcd9a8 5473 if (!target_is_non_stop_p ())
5965e028 5474 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5475
b73be471 5476 rs->last_sent_signal = siggnal;
280ceea3 5477 rs->last_sent_step = step;
43ff13b4 5478
506fb367 5479 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5480 /* No reverse support (yet) for vCont. */
5481 if (execution_direction != EXEC_REVERSE)
5482 if (remote_vcont_resume (ptid, step, siggnal))
5483 goto done;
506fb367 5484
79d7f229
PA
5485 /* All other supported resume packets do use Hc, so set the continue
5486 thread. */
5487 if (ptid_equal (ptid, minus_one_ptid))
5488 set_continue_thread (any_thread_ptid);
506fb367 5489 else
79d7f229 5490 set_continue_thread (ptid);
506fb367 5491
799a2abe
PA
5492 ALL_NON_EXITED_THREADS (thread)
5493 resume_clear_thread_private_info (thread);
5494
2e9f7625 5495 buf = rs->buf;
b2175913
MS
5496 if (execution_direction == EXEC_REVERSE)
5497 {
5498 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5499 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5500 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5501 siggnal);
40ab02ce 5502
4082afcc 5503 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5504 error (_("Remote reverse-step not supported."));
4082afcc 5505 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5506 error (_("Remote reverse-continue not supported."));
40ab02ce 5507
b2175913
MS
5508 strcpy (buf, step ? "bs" : "bc");
5509 }
a493e3e2 5510 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5511 {
5512 buf[0] = step ? 'S' : 'C';
c5aa993b 5513 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5514 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5515 buf[3] = '\0';
5516 }
5517 else
c5aa993b 5518 strcpy (buf, step ? "s" : "c");
506fb367 5519
44eaed12 5520 putpkt (buf);
43ff13b4 5521
75c99385 5522 done:
2acceee2 5523 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5524 with the event loop. NOTE: this is the one place where all the
5525 execution commands end up. We could alternatively do this in each
23860348 5526 of the execution commands in infcmd.c. */
2acceee2
JM
5527 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5528 into infcmd.c in order to allow inferior function calls to work
23860348 5529 NOT asynchronously. */
362646f5 5530 if (target_can_async_p ())
6a3753b3 5531 target_async (1);
e24a49d8
PA
5532
5533 /* We've just told the target to resume. The remote server will
5534 wait for the inferior to stop, and then send a stop reply. In
5535 the mean time, we can't start another command/query ourselves
74531fed
PA
5536 because the stub wouldn't be ready to process it. This applies
5537 only to the base all-stop protocol, however. In non-stop (which
5538 only supports vCont), the stub replies with an "OK", and is
5539 immediate able to process further serial input. */
6efcd9a8 5540 if (!target_is_non_stop_p ())
74531fed 5541 rs->waiting_for_stop_reply = 1;
43ff13b4 5542}
c906108c 5543\f
43ff13b4
JM
5544
5545/* Set up the signal handler for SIGINT, while the target is
23860348 5546 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5547static void
934b9bac 5548async_initialize_sigint_signal_handler (void)
43ff13b4 5549{
934b9bac 5550 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5551}
5552
23860348 5553/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5554static void
934b9bac 5555async_handle_remote_sigint (int sig)
43ff13b4 5556{
934b9bac 5557 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5558 /* Note we need to go through gdb_call_async_signal_handler in order
5559 to wake up the event loop on Windows. */
5560 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5561}
5562
5563/* Signal handler for SIGINT, installed after SIGINT has already been
5564 sent once. It will take effect the second time that the user sends
23860348 5565 a ^C. */
43ff13b4 5566static void
934b9bac 5567async_handle_remote_sigint_twice (int sig)
43ff13b4 5568{
934b9bac 5569 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5570 /* See note in async_handle_remote_sigint. */
5571 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5572}
5573
abc56d60
PA
5574/* Implementation of to_check_pending_interrupt. */
5575
5576static void
5577remote_check_pending_interrupt (struct target_ops *self)
5578{
5579 struct async_signal_handler *token = async_sigint_remote_twice_token;
5580
5581 if (async_signal_handler_is_marked (token))
5582 {
5583 clear_async_signal_handler (token);
5584 call_async_signal_handler (token);
5585 }
5586}
5587
6426a772 5588/* Perform the real interruption of the target execution, in response
23860348 5589 to a ^C. */
c5aa993b 5590static void
fba45db2 5591async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5592{
5593 if (remote_debug)
248fd3bf 5594 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5595
de979965 5596 target_interrupt (inferior_ptid);
43ff13b4
JM
5597}
5598
0df8b418 5599/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5600 up on the target alltogether. */
47e1ce27 5601static void
fba45db2 5602async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5603{
2df3850c 5604 if (remote_debug)
248fd3bf 5605 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5606
5607 interrupt_query ();
43ff13b4
JM
5608}
5609
5610/* Reinstall the usual SIGINT handlers, after the target has
23860348 5611 stopped. */
6426a772 5612static void
934b9bac 5613async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5614{
5615 signal (SIGINT, handle_sigint);
43ff13b4
JM
5616}
5617
c906108c
SS
5618/* Send ^C to target to halt it. Target will respond, and send us a
5619 packet. */
507f3c78 5620static void (*ofunc) (int);
c906108c 5621
bfedc46a
PA
5622/* The command line interface's interrupt routine. This function is installed
5623 as a signal handler for SIGINT. The first time a user requests an
5624 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5625 response from the target (it didn't stop when the user requested it),
23860348 5626 we ask the user if he'd like to detach from the target. */
bfedc46a 5627
c906108c 5628static void
934b9bac 5629sync_remote_interrupt (int signo)
c906108c 5630{
23860348 5631 /* If this doesn't work, try more severe steps. */
934b9bac 5632 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5633
934b9bac 5634 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5635}
5636
5637/* The user typed ^C twice. */
5638
5639static void
934b9bac 5640sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5641{
5642 signal (signo, ofunc);
934b9bac
JK
5643 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5644 signal (signo, sync_remote_interrupt);
c906108c 5645}
7a292a7a 5646
74531fed
PA
5647/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5648 thread, all threads of a remote process, or all threads of all
5649 processes. */
5650
5651static void
5652remote_stop_ns (ptid_t ptid)
5653{
5654 struct remote_state *rs = get_remote_state ();
5655 char *p = rs->buf;
5656 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5657
4082afcc 5658 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5659 remote_vcont_probe (rs);
5660
d458bd84 5661 if (!rs->supports_vCont.t)
74531fed
PA
5662 error (_("Remote server does not support stopping threads"));
5663
f91d3df5
PA
5664 if (ptid_equal (ptid, minus_one_ptid)
5665 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5666 p += xsnprintf (p, endp - p, "vCont;t");
5667 else
5668 {
5669 ptid_t nptid;
5670
74531fed
PA
5671 p += xsnprintf (p, endp - p, "vCont;t:");
5672
5673 if (ptid_is_pid (ptid))
5674 /* All (-1) threads of process. */
ba348170 5675 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5676 else
5677 {
5678 /* Small optimization: if we already have a stop reply for
5679 this thread, no use in telling the stub we want this
5680 stopped. */
5681 if (peek_stop_reply (ptid))
5682 return;
5683
5684 nptid = ptid;
5685 }
5686
a9cbf802 5687 write_ptid (p, endp, nptid);
74531fed
PA
5688 }
5689
5690 /* In non-stop, we get an immediate OK reply. The stop reply will
5691 come in asynchronously by notification. */
5692 putpkt (rs->buf);
5693 getpkt (&rs->buf, &rs->buf_size, 0);
5694 if (strcmp (rs->buf, "OK") != 0)
5695 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5696}
5697
bfedc46a
PA
5698/* All-stop version of target_interrupt. Sends a break or a ^C to
5699 interrupt the remote target. It is undefined which thread of which
5700 process reports the interrupt. */
74531fed
PA
5701
5702static void
de979965 5703remote_interrupt_as (void)
74531fed
PA
5704{
5705 struct remote_state *rs = get_remote_state ();
5706
3a29589a
DJ
5707 rs->ctrlc_pending_p = 1;
5708
74531fed
PA
5709 /* If the inferior is stopped already, but the core didn't know
5710 about it yet, just ignore the request. The cached wait status
5711 will be collected in remote_wait. */
5712 if (rs->cached_wait_status)
5713 return;
5714
9a7071a8
JB
5715 /* Send interrupt_sequence to remote target. */
5716 send_interrupt_sequence ();
74531fed
PA
5717}
5718
de979965
PA
5719/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5720 the remote target. It is undefined which thread of which process
5721 reports the interrupt. Returns true if the packet is supported by
5722 the server, false otherwise. */
5723
5724static int
5725remote_interrupt_ns (void)
5726{
5727 struct remote_state *rs = get_remote_state ();
5728 char *p = rs->buf;
5729 char *endp = rs->buf + get_remote_packet_size ();
5730
5731 xsnprintf (p, endp - p, "vCtrlC");
5732
5733 /* In non-stop, we get an immediate OK reply. The stop reply will
5734 come in asynchronously by notification. */
5735 putpkt (rs->buf);
5736 getpkt (&rs->buf, &rs->buf_size, 0);
5737
5738 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5739 {
5740 case PACKET_OK:
5741 break;
5742 case PACKET_UNKNOWN:
5743 return 0;
5744 case PACKET_ERROR:
5745 error (_("Interrupting target failed: %s"), rs->buf);
5746 }
5747
5748 return 1;
5749}
5750
bfedc46a 5751/* Implement the to_stop function for the remote targets. */
74531fed 5752
c906108c 5753static void
1eab8a48 5754remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5755{
7a292a7a 5756 if (remote_debug)
0f71a2f6 5757 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5758
6efcd9a8 5759 if (target_is_non_stop_p ())
74531fed 5760 remote_stop_ns (ptid);
c906108c 5761 else
bfedc46a
PA
5762 {
5763 /* We don't currently have a way to transparently pause the
5764 remote target in all-stop mode. Interrupt it instead. */
de979965 5765 remote_interrupt_as ();
bfedc46a
PA
5766 }
5767}
5768
5769/* Implement the to_interrupt function for the remote targets. */
5770
5771static void
5772remote_interrupt (struct target_ops *self, ptid_t ptid)
5773{
5774 if (remote_debug)
5775 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5776
de979965 5777 if (non_stop)
bfedc46a 5778 {
de979965 5779 /* In non-stop mode, we always stop with no signal instead. */
bfedc46a
PA
5780 remote_stop_ns (ptid);
5781 }
5782 else
de979965
PA
5783 {
5784 /* In all-stop, we emulate ^C-ing the remote target's
5785 terminal. */
5786 if (target_is_non_stop_p ())
5787 {
5788 if (!remote_interrupt_ns ())
5789 {
5790 /* No support for ^C-ing the remote target. Stop it
5791 (with no signal) instead. */
5792 remote_stop_ns (ptid);
5793 }
5794 }
5795 else
5796 remote_interrupt_as ();
5797 }
c906108c
SS
5798}
5799
5800/* Ask the user what to do when an interrupt is received. */
5801
5802static void
fba45db2 5803interrupt_query (void)
c906108c 5804{
abc56d60
PA
5805 struct remote_state *rs = get_remote_state ();
5806 struct cleanup *old_chain;
5807
5808 old_chain = make_cleanup_restore_target_terminal ();
c906108c
SS
5809 target_terminal_ours ();
5810
abc56d60 5811 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5812 {
abc56d60
PA
5813 if (query (_("The target is not responding to interrupt requests.\n"
5814 "Stop debugging it? ")))
74531fed 5815 {
78a095c3 5816 remote_unpush_target ();
abc56d60 5817 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5818 }
5819 }
abc56d60
PA
5820 else
5821 {
5822 if (query (_("Interrupted while waiting for the program.\n"
5823 "Give up waiting? ")))
5824 quit ();
5825 }
c906108c 5826
abc56d60 5827 do_cleanups (old_chain);
c906108c
SS
5828}
5829
6426a772
JM
5830/* Enable/disable target terminal ownership. Most targets can use
5831 terminal groups to control terminal ownership. Remote targets are
5832 different in that explicit transfer of ownership to/from GDB/target
23860348 5833 is required. */
6426a772
JM
5834
5835static void
d2f640d4 5836remote_terminal_inferior (struct target_ops *self)
6426a772 5837{
c6ebd6cf 5838 if (!target_async_permitted)
75c99385
PA
5839 /* Nothing to do. */
5840 return;
5841
d9d2d8b6
PA
5842 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5843 idempotent. The event-loop GDB talking to an asynchronous target
5844 with a synchronous command calls this function from both
5845 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5846 transfer the terminal to the target when it shouldn't this guard
5847 can go away. */
6426a772
JM
5848 if (!remote_async_terminal_ours_p)
5849 return;
5850 delete_file_handler (input_fd);
5851 remote_async_terminal_ours_p = 0;
934b9bac 5852 async_initialize_sigint_signal_handler ();
6426a772
JM
5853 /* NOTE: At this point we could also register our selves as the
5854 recipient of all input. Any characters typed could then be
23860348 5855 passed on down to the target. */
6426a772
JM
5856}
5857
5858static void
e3594fd1 5859remote_terminal_ours (struct target_ops *self)
6426a772 5860{
c6ebd6cf 5861 if (!target_async_permitted)
75c99385
PA
5862 /* Nothing to do. */
5863 return;
5864
5865 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5866 if (remote_async_terminal_ours_p)
5867 return;
934b9bac 5868 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5869 add_file_handler (input_fd, stdin_event_handler, 0);
5870 remote_async_terminal_ours_p = 1;
5871}
5872
176a6961 5873static void
917317f4 5874remote_console_output (char *msg)
c906108c
SS
5875{
5876 char *p;
5877
c5aa993b 5878 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5879 {
5880 char tb[2];
5881 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5882
c906108c
SS
5883 tb[0] = c;
5884 tb[1] = 0;
43ff13b4 5885 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5886 }
00db5b94
PA
5887 gdb_flush (gdb_stdtarg);
5888}
74531fed
PA
5889
5890typedef struct cached_reg
5891{
5892 int num;
5893 gdb_byte data[MAX_REGISTER_SIZE];
5894} cached_reg_t;
5895
5896DEF_VEC_O(cached_reg_t);
5897
722247f1 5898typedef struct stop_reply
74531fed 5899{
722247f1 5900 struct notif_event base;
74531fed 5901
722247f1 5902 /* The identifier of the thread about this event */
74531fed
PA
5903 ptid_t ptid;
5904
340e3c99 5905 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5906 connection, represented by a remote_state object, is closed,
5907 all the associated stop_reply events should be released. */
5908 struct remote_state *rs;
5909
74531fed
PA
5910 struct target_waitstatus ws;
5911
15148d6a
PA
5912 /* Expedited registers. This makes remote debugging a bit more
5913 efficient for those targets that provide critical registers as
5914 part of their normal status mechanism (as another roundtrip to
5915 fetch them is avoided). */
74531fed
PA
5916 VEC(cached_reg_t) *regcache;
5917
f7e6eed5
PA
5918 enum target_stop_reason stop_reason;
5919
74531fed
PA
5920 CORE_ADDR watch_data_address;
5921
dc146f7c 5922 int core;
722247f1 5923} *stop_reply_p;
a744cf53 5924
722247f1
YQ
5925DECLARE_QUEUE_P (stop_reply_p);
5926DEFINE_QUEUE_P (stop_reply_p);
5927/* The list of already fetched and acknowledged stop events. This
5928 queue is used for notification Stop, and other notifications
5929 don't need queue for their events, because the notification events
5930 of Stop can't be consumed immediately, so that events should be
5931 queued first, and be consumed by remote_wait_{ns,as} one per
5932 time. Other notifications can consume their events immediately,
5933 so queue is not needed for them. */
5934static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5935
5936static void
5937stop_reply_xfree (struct stop_reply *r)
5938{
f48ff2a7 5939 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5940}
5941
221e1a37
PA
5942/* Return the length of the stop reply queue. */
5943
5944static int
5945stop_reply_queue_length (void)
5946{
5947 return QUEUE_length (stop_reply_p, stop_reply_queue);
5948}
5949
722247f1
YQ
5950static void
5951remote_notif_stop_parse (struct notif_client *self, char *buf,
5952 struct notif_event *event)
5953{
5954 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5955}
5956
5957static void
5958remote_notif_stop_ack (struct notif_client *self, char *buf,
5959 struct notif_event *event)
5960{
5961 struct stop_reply *stop_reply = (struct stop_reply *) event;
5962
5963 /* acknowledge */
5964 putpkt ((char *) self->ack_command);
5965
5966 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5967 /* We got an unknown stop reply. */
5968 error (_("Unknown stop reply"));
5969
5970 push_stop_reply (stop_reply);
5971}
5972
5973static int
5974remote_notif_stop_can_get_pending_events (struct notif_client *self)
5975{
5976 /* We can't get pending events in remote_notif_process for
5977 notification stop, and we have to do this in remote_wait_ns
5978 instead. If we fetch all queued events from stub, remote stub
5979 may exit and we have no chance to process them back in
5980 remote_wait_ns. */
5981 mark_async_event_handler (remote_async_inferior_event_token);
5982 return 0;
5983}
5984
5985static void
5986stop_reply_dtr (struct notif_event *event)
5987{
5988 struct stop_reply *r = (struct stop_reply *) event;
5989
5990 VEC_free (cached_reg_t, r->regcache);
5991}
5992
5993static struct notif_event *
5994remote_notif_stop_alloc_reply (void)
5995{
8d749320
SM
5996 /* We cast to a pointer to the "base class". */
5997 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5998
5999 r->dtr = stop_reply_dtr;
6000
6001 return r;
6002}
6003
6004/* A client of notification Stop. */
6005
6006struct notif_client notif_client_stop =
6007{
6008 "Stop",
6009 "vStopped",
6010 remote_notif_stop_parse,
6011 remote_notif_stop_ack,
6012 remote_notif_stop_can_get_pending_events,
6013 remote_notif_stop_alloc_reply,
f48ff2a7 6014 REMOTE_NOTIF_STOP,
722247f1
YQ
6015};
6016
6017/* A parameter to pass data in and out. */
6018
6019struct queue_iter_param
6020{
6021 void *input;
6022 struct stop_reply *output;
6023};
6024
cbb8991c
DB
6025/* Determine if THREAD is a pending fork parent thread. ARG contains
6026 the pid of the process that owns the threads we want to check, or
6027 -1 if we want to check all threads. */
6028
6029static int
6030is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6031 ptid_t thread_ptid)
6032{
6033 if (ws->kind == TARGET_WAITKIND_FORKED
6034 || ws->kind == TARGET_WAITKIND_VFORKED)
6035 {
6036 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6037 return 1;
6038 }
6039
6040 return 0;
6041}
6042
6043/* Check whether EVENT is a fork event, and if it is, remove the
6044 fork child from the context list passed in DATA. */
6045
6046static int
6047remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6048 QUEUE_ITER (stop_reply_p) *iter,
6049 stop_reply_p event,
6050 void *data)
6051{
19ba03f4
SM
6052 struct queue_iter_param *param = (struct queue_iter_param *) data;
6053 struct threads_listing_context *context
6054 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6055
6056 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6057 || event->ws.kind == TARGET_WAITKIND_VFORKED
6058 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6059 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6060
6061 return 1;
6062}
6063
6064/* If CONTEXT contains any fork child threads that have not been
6065 reported yet, remove them from the CONTEXT list. If such a
6066 thread exists it is because we are stopped at a fork catchpoint
6067 and have not yet called follow_fork, which will set up the
6068 host-side data structures for the new process. */
6069
6070static void
6071remove_new_fork_children (struct threads_listing_context *context)
6072{
6073 struct thread_info * thread;
6074 int pid = -1;
6075 struct notif_client *notif = &notif_client_stop;
6076 struct queue_iter_param param;
6077
6078 /* For any threads stopped at a fork event, remove the corresponding
6079 fork child threads from the CONTEXT list. */
6080 ALL_NON_EXITED_THREADS (thread)
6081 {
6082 struct target_waitstatus *ws = &thread->pending_follow;
6083
6084 if (is_pending_fork_parent (ws, pid, thread->ptid))
6085 {
6086 threads_listing_context_remove (ws, context);
6087 }
6088 }
6089
6090 /* Check for any pending fork events (not reported or processed yet)
6091 in process PID and remove those fork child threads from the
6092 CONTEXT list as well. */
6093 remote_notif_get_pending_events (notif);
6094 param.input = context;
6095 param.output = NULL;
6096 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6097 remove_child_of_pending_fork, &param);
6098}
6099
f48ff2a7
YQ
6100/* Remove stop replies in the queue if its pid is equal to the given
6101 inferior's pid. */
722247f1
YQ
6102
6103static int
f48ff2a7
YQ
6104remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6105 QUEUE_ITER (stop_reply_p) *iter,
6106 stop_reply_p event,
6107 void *data)
722247f1 6108{
19ba03f4
SM
6109 struct queue_iter_param *param = (struct queue_iter_param *) data;
6110 struct inferior *inf = (struct inferior *) param->input;
722247f1 6111
f48ff2a7 6112 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6113 {
6114 stop_reply_xfree (event);
6115 QUEUE_remove_elem (stop_reply_p, q, iter);
6116 }
6117
6118 return 1;
6119}
6120
f48ff2a7 6121/* Discard all pending stop replies of inferior INF. */
c906108c 6122
74531fed 6123static void
5f4cf0bb 6124discard_pending_stop_replies (struct inferior *inf)
c906108c 6125{
722247f1
YQ
6126 int i;
6127 struct queue_iter_param param;
f48ff2a7
YQ
6128 struct stop_reply *reply;
6129 struct remote_state *rs = get_remote_state ();
6130 struct remote_notif_state *rns = rs->notif_state;
6131
6132 /* This function can be notified when an inferior exists. When the
6133 target is not remote, the notification state is NULL. */
6134 if (rs->remote_desc == NULL)
6135 return;
6136
6137 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6138
74531fed 6139 /* Discard the in-flight notification. */
f48ff2a7 6140 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6141 {
722247f1 6142 stop_reply_xfree (reply);
f48ff2a7 6143 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6144 }
c906108c 6145
722247f1
YQ
6146 param.input = inf;
6147 param.output = NULL;
74531fed
PA
6148 /* Discard the stop replies we have already pulled with
6149 vStopped. */
722247f1 6150 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6151 remove_stop_reply_for_inferior, &param);
6152}
6153
bcc75809
YQ
6154/* If its remote state is equal to the given remote state,
6155 remove EVENT from the stop reply queue. */
6156
6157static int
6158remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6159 QUEUE_ITER (stop_reply_p) *iter,
6160 stop_reply_p event,
6161 void *data)
6162{
19ba03f4
SM
6163 struct queue_iter_param *param = (struct queue_iter_param *) data;
6164 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6165
6166 if (event->rs == rs)
6167 {
6168 stop_reply_xfree (event);
6169 QUEUE_remove_elem (stop_reply_p, q, iter);
6170 }
6171
6172 return 1;
6173}
6174
6175/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6176
6177static void
bcc75809 6178discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6179{
6180 struct queue_iter_param param;
6181
bcc75809 6182 param.input = rs;
f48ff2a7
YQ
6183 param.output = NULL;
6184 /* Discard the stop replies we have already pulled with
6185 vStopped. */
6186 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6187 remove_stop_reply_of_remote_state, &param);
722247f1 6188}
74531fed 6189
722247f1
YQ
6190/* A parameter to pass data in and out. */
6191
6192static int
6193remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6194 QUEUE_ITER (stop_reply_p) *iter,
6195 stop_reply_p event,
6196 void *data)
6197{
19ba03f4
SM
6198 struct queue_iter_param *param = (struct queue_iter_param *) data;
6199 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6200
6201 if (ptid_match (event->ptid, *ptid))
6202 {
6203 param->output = event;
6204 QUEUE_remove_elem (stop_reply_p, q, iter);
6205 return 0;
c8e38a49 6206 }
722247f1
YQ
6207
6208 return 1;
74531fed 6209}
43ff13b4 6210
722247f1
YQ
6211/* Remove the first reply in 'stop_reply_queue' which matches
6212 PTID. */
2e9f7625 6213
722247f1
YQ
6214static struct stop_reply *
6215remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6216{
722247f1
YQ
6217 struct queue_iter_param param;
6218
6219 param.input = &ptid;
6220 param.output = NULL;
6221
6222 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6223 remote_notif_remove_once_on_match, &param);
6224 if (notif_debug)
6225 fprintf_unfiltered (gdb_stdlog,
6226 "notif: discard queued event: 'Stop' in %s\n",
6227 target_pid_to_str (ptid));
a744cf53 6228
722247f1 6229 return param.output;
74531fed 6230}
75c99385 6231
74531fed
PA
6232/* Look for a queued stop reply belonging to PTID. If one is found,
6233 remove it from the queue, and return it. Returns NULL if none is
6234 found. If there are still queued events left to process, tell the
6235 event loop to get back to target_wait soon. */
e24a49d8 6236
74531fed
PA
6237static struct stop_reply *
6238queued_stop_reply (ptid_t ptid)
6239{
722247f1 6240 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6241
722247f1 6242 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6243 /* There's still at least an event left. */
6244 mark_async_event_handler (remote_async_inferior_event_token);
6245
722247f1 6246 return r;
74531fed
PA
6247}
6248
6249/* Push a fully parsed stop reply in the stop reply queue. Since we
6250 know that we now have at least one queued event left to pass to the
6251 core side, tell the event loop to get back to target_wait soon. */
6252
6253static void
6254push_stop_reply (struct stop_reply *new_event)
6255{
722247f1 6256 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6257
722247f1
YQ
6258 if (notif_debug)
6259 fprintf_unfiltered (gdb_stdlog,
6260 "notif: push 'Stop' %s to queue %d\n",
6261 target_pid_to_str (new_event->ptid),
6262 QUEUE_length (stop_reply_p,
6263 stop_reply_queue));
74531fed
PA
6264
6265 mark_async_event_handler (remote_async_inferior_event_token);
6266}
6267
722247f1
YQ
6268static int
6269stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6270 QUEUE_ITER (stop_reply_p) *iter,
6271 struct stop_reply *event,
6272 void *data)
6273{
19ba03f4 6274 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6275
6276 return !(ptid_equal (*ptid, event->ptid)
6277 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6278}
6279
74531fed
PA
6280/* Returns true if we have a stop reply for PTID. */
6281
6282static int
6283peek_stop_reply (ptid_t ptid)
6284{
722247f1
YQ
6285 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6286 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6287}
6288
1f10ba14
PA
6289/* Skip PACKET until the next semi-colon (or end of string). */
6290
6291static char *
6292skip_to_semicolon (char *p)
6293{
6294 while (*p != '\0' && *p != ';')
6295 p++;
6296 return p;
6297}
6298
26d56a93
SL
6299/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6300 starting with P and ending with PEND matches PREFIX. */
6301
6302static int
6303strprefix (const char *p, const char *pend, const char *prefix)
6304{
6305 for ( ; p < pend; p++, prefix++)
6306 if (*p != *prefix)
6307 return 0;
6308 return *prefix == '\0';
6309}
6310
74531fed
PA
6311/* Parse the stop reply in BUF. Either the function succeeds, and the
6312 result is stored in EVENT, or throws an error. */
6313
6314static void
6315remote_parse_stop_reply (char *buf, struct stop_reply *event)
6316{
6317 struct remote_arch_state *rsa = get_remote_arch_state ();
6318 ULONGEST addr;
6319 char *p;
94585166 6320 int skipregs = 0;
74531fed
PA
6321
6322 event->ptid = null_ptid;
bcc75809 6323 event->rs = get_remote_state ();
74531fed
PA
6324 event->ws.kind = TARGET_WAITKIND_IGNORE;
6325 event->ws.value.integer = 0;
f7e6eed5 6326 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6327 event->regcache = NULL;
dc146f7c 6328 event->core = -1;
74531fed
PA
6329
6330 switch (buf[0])
6331 {
6332 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6333 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6334 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6335 ss = signal number
6336 n... = register number
6337 r... = register contents
6338 */
6339
6340 p = &buf[3]; /* after Txx */
6341 while (*p)
6342 {
6343 char *p1;
cea39f65 6344 int fieldsize;
43ff13b4 6345
1f10ba14
PA
6346 p1 = strchr (p, ':');
6347 if (p1 == NULL)
6348 error (_("Malformed packet(a) (missing colon): %s\n\
6349Packet: '%s'\n"),
6350 p, buf);
6351 if (p == p1)
6352 error (_("Malformed packet(a) (missing register number): %s\n\
6353Packet: '%s'\n"),
6354 p, buf);
3c3bea1c 6355
1f10ba14
PA
6356 /* Some "registers" are actually extended stop information.
6357 Note if you're adding a new entry here: GDB 7.9 and
6358 earlier assume that all register "numbers" that start
6359 with an hex digit are real register numbers. Make sure
6360 the server only sends such a packet if it knows the
6361 client understands it. */
c8e38a49 6362
26d56a93 6363 if (strprefix (p, p1, "thread"))
1f10ba14 6364 event->ptid = read_ptid (++p1, &p);
26d56a93
SL
6365 else if (strprefix (p, p1, "watch")
6366 || strprefix (p, p1, "rwatch")
6367 || strprefix (p, p1, "awatch"))
cea39f65 6368 {
f7e6eed5 6369 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6370 p = unpack_varlen_hex (++p1, &addr);
6371 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6372 }
26d56a93 6373 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6374 {
6375 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6376
6377 /* Make sure the stub doesn't forget to indicate support
6378 with qSupported. */
6379 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6380 error (_("Unexpected swbreak stop reason"));
6381
6382 /* The value part is documented as "must be empty",
6383 though we ignore it, in case we ever decide to make
6384 use of it in a backward compatible way. */
6385 p = skip_to_semicolon (p1 + 1);
6386 }
26d56a93 6387 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6388 {
6389 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6390
6391 /* Make sure the stub doesn't forget to indicate support
6392 with qSupported. */
6393 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6394 error (_("Unexpected hwbreak stop reason"));
6395
6396 /* See above. */
6397 p = skip_to_semicolon (p1 + 1);
6398 }
26d56a93 6399 else if (strprefix (p, p1, "library"))
cea39f65 6400 {
1f10ba14
PA
6401 event->ws.kind = TARGET_WAITKIND_LOADED;
6402 p = skip_to_semicolon (p1 + 1);
6403 }
26d56a93 6404 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6405 {
6406 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6407 /* p1 will indicate "begin" or "end", but it makes
6408 no difference for now, so ignore it. */
6409 p = skip_to_semicolon (p1 + 1);
6410 }
26d56a93 6411 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6412 {
6413 ULONGEST c;
a744cf53 6414
1f10ba14
PA
6415 p = unpack_varlen_hex (++p1, &c);
6416 event->core = c;
cea39f65 6417 }
26d56a93 6418 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6419 {
6420 event->ws.value.related_pid = read_ptid (++p1, &p);
6421 event->ws.kind = TARGET_WAITKIND_FORKED;
6422 }
26d56a93 6423 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6424 {
6425 event->ws.value.related_pid = read_ptid (++p1, &p);
6426 event->ws.kind = TARGET_WAITKIND_VFORKED;
6427 }
26d56a93 6428 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6429 {
6430 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6431 p = skip_to_semicolon (p1 + 1);
6432 }
6ab24463 6433 else if (strprefix (p, p1, "exec"))
94585166
DB
6434 {
6435 ULONGEST ignored;
6436 char pathname[PATH_MAX];
6437 int pathlen;
6438
6439 /* Determine the length of the execd pathname. */
6440 p = unpack_varlen_hex (++p1, &ignored);
6441 pathlen = (p - p1) / 2;
6442
6443 /* Save the pathname for event reporting and for
6444 the next run command. */
6445 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6446 pathname[pathlen] = '\0';
6447
6448 /* This is freed during event handling. */
6449 event->ws.value.execd_pathname = xstrdup (pathname);
6450 event->ws.kind = TARGET_WAITKIND_EXECD;
6451
6452 /* Skip the registers included in this packet, since
6453 they may be for an architecture different from the
6454 one used by the original program. */
6455 skipregs = 1;
6456 }
65706a29
PA
6457 else if (strprefix (p, p1, "create"))
6458 {
6459 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6460 p = skip_to_semicolon (p1 + 1);
6461 }
cea39f65
MS
6462 else
6463 {
1f10ba14
PA
6464 ULONGEST pnum;
6465 char *p_temp;
6466
94585166
DB
6467 if (skipregs)
6468 {
6469 p = skip_to_semicolon (p1 + 1);
6470 p++;
6471 continue;
6472 }
6473
1f10ba14
PA
6474 /* Maybe a real ``P'' register number. */
6475 p_temp = unpack_varlen_hex (p, &pnum);
6476 /* If the first invalid character is the colon, we got a
6477 register number. Otherwise, it's an unknown stop
6478 reason. */
6479 if (p_temp == p1)
6480 {
6481 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6482 cached_reg_t cached_reg;
43ff13b4 6483
1f10ba14
PA
6484 if (reg == NULL)
6485 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6486Packet: '%s'\n"),
1f10ba14 6487 hex_string (pnum), p, buf);
c8e38a49 6488
1f10ba14 6489 cached_reg.num = reg->regnum;
4100683b 6490
1f10ba14
PA
6491 p = p1 + 1;
6492 fieldsize = hex2bin (p, cached_reg.data,
6493 register_size (target_gdbarch (),
6494 reg->regnum));
6495 p += 2 * fieldsize;
6496 if (fieldsize < register_size (target_gdbarch (),
6497 reg->regnum))
6498 warning (_("Remote reply is too short: %s"), buf);
74531fed 6499
1f10ba14
PA
6500 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6501 }
6502 else
6503 {
6504 /* Not a number. Silently skip unknown optional
6505 info. */
6506 p = skip_to_semicolon (p1 + 1);
6507 }
cea39f65 6508 }
c8e38a49 6509
cea39f65
MS
6510 if (*p != ';')
6511 error (_("Remote register badly formatted: %s\nhere: %s"),
6512 buf, p);
6513 ++p;
6514 }
5b5596ff
PA
6515
6516 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6517 break;
6518
c8e38a49
PA
6519 /* fall through */
6520 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6521 {
6522 int sig;
6523
6524 event->ws.kind = TARGET_WAITKIND_STOPPED;
6525 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6526 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6527 event->ws.value.sig = (enum gdb_signal) sig;
6528 else
6529 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6530 }
c8e38a49 6531 break;
65706a29
PA
6532 case 'w': /* Thread exited. */
6533 {
6534 char *p;
6535 ULONGEST value;
6536
6537 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6538 p = unpack_varlen_hex (&buf[1], &value);
6539 event->ws.value.integer = value;
6540 if (*p != ';')
6541 error (_("stop reply packet badly formatted: %s"), buf);
6542 event->ptid = read_ptid (++p, &p);
6543 break;
6544 }
c8e38a49
PA
6545 case 'W': /* Target exited. */
6546 case 'X':
6547 {
6548 char *p;
6549 int pid;
6550 ULONGEST value;
82f73884 6551
c8e38a49
PA
6552 /* GDB used to accept only 2 hex chars here. Stubs should
6553 only send more if they detect GDB supports multi-process
6554 support. */
6555 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6556
c8e38a49
PA
6557 if (buf[0] == 'W')
6558 {
6559 /* The remote process exited. */
74531fed
PA
6560 event->ws.kind = TARGET_WAITKIND_EXITED;
6561 event->ws.value.integer = value;
c8e38a49
PA
6562 }
6563 else
6564 {
6565 /* The remote process exited with a signal. */
74531fed 6566 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6567 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6568 event->ws.value.sig = (enum gdb_signal) value;
6569 else
6570 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6571 }
82f73884 6572
c8e38a49
PA
6573 /* If no process is specified, assume inferior_ptid. */
6574 pid = ptid_get_pid (inferior_ptid);
6575 if (*p == '\0')
6576 ;
6577 else if (*p == ';')
6578 {
6579 p++;
6580
0b24eb2d 6581 if (*p == '\0')
82f73884 6582 ;
61012eef 6583 else if (startswith (p, "process:"))
82f73884 6584 {
c8e38a49 6585 ULONGEST upid;
a744cf53 6586
c8e38a49
PA
6587 p += sizeof ("process:") - 1;
6588 unpack_varlen_hex (p, &upid);
6589 pid = upid;
82f73884
PA
6590 }
6591 else
6592 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6593 }
c8e38a49
PA
6594 else
6595 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6596 event->ptid = pid_to_ptid (pid);
6597 }
6598 break;
6599 }
6600
6efcd9a8 6601 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
6602 error (_("No process or thread specified in stop reply: %s"), buf);
6603}
6604
722247f1
YQ
6605/* When the stub wants to tell GDB about a new notification reply, it
6606 sends a notification (%Stop, for example). Those can come it at
6607 any time, hence, we have to make sure that any pending
6608 putpkt/getpkt sequence we're making is finished, before querying
6609 the stub for more events with the corresponding ack command
6610 (vStopped, for example). E.g., if we started a vStopped sequence
6611 immediately upon receiving the notification, something like this
6612 could happen:
74531fed
PA
6613
6614 1.1) --> Hg 1
6615 1.2) <-- OK
6616 1.3) --> g
6617 1.4) <-- %Stop
6618 1.5) --> vStopped
6619 1.6) <-- (registers reply to step #1.3)
6620
6621 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6622 query.
6623
796cb314 6624 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6625 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6626 doing whatever we were doing:
6627
6628 2.1) --> Hg 1
6629 2.2) <-- OK
6630 2.3) --> g
6631 2.4) <-- %Stop
6632 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6633 2.5) <-- (registers reply to step #2.3)
6634
6635 Eventualy after step #2.5, we return to the event loop, which
6636 notices there's an event on the
6637 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6638 associated callback --- the function below. At this point, we're
6639 always safe to start a vStopped sequence. :
6640
6641 2.6) --> vStopped
6642 2.7) <-- T05 thread:2
6643 2.8) --> vStopped
6644 2.9) --> OK
6645*/
6646
722247f1
YQ
6647void
6648remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6649{
6650 struct remote_state *rs = get_remote_state ();
74531fed 6651
f48ff2a7 6652 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6653 {
722247f1
YQ
6654 if (notif_debug)
6655 fprintf_unfiltered (gdb_stdlog,
6656 "notif: process: '%s' ack pending event\n",
6657 nc->name);
74531fed 6658
722247f1 6659 /* acknowledge */
f48ff2a7
YQ
6660 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6661 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6662
6663 while (1)
6664 {
6665 getpkt (&rs->buf, &rs->buf_size, 0);
6666 if (strcmp (rs->buf, "OK") == 0)
6667 break;
6668 else
722247f1 6669 remote_notif_ack (nc, rs->buf);
74531fed
PA
6670 }
6671 }
722247f1
YQ
6672 else
6673 {
6674 if (notif_debug)
6675 fprintf_unfiltered (gdb_stdlog,
6676 "notif: process: '%s' no pending reply\n",
6677 nc->name);
6678 }
74531fed
PA
6679}
6680
74531fed
PA
6681/* Called when it is decided that STOP_REPLY holds the info of the
6682 event that is to be returned to the core. This function always
6683 destroys STOP_REPLY. */
6684
6685static ptid_t
6686process_stop_reply (struct stop_reply *stop_reply,
6687 struct target_waitstatus *status)
6688{
6689 ptid_t ptid;
6690
6691 *status = stop_reply->ws;
6692 ptid = stop_reply->ptid;
6693
6694 /* If no thread/process was reported by the stub, assume the current
6695 inferior. */
6696 if (ptid_equal (ptid, null_ptid))
6697 ptid = inferior_ptid;
6698
5f3563ea
PA
6699 if (status->kind != TARGET_WAITKIND_EXITED
6700 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 6701 {
ee154bee 6702 struct remote_state *rs = get_remote_state ();
799a2abe 6703 struct private_thread_info *remote_thr;
ee154bee 6704
5f3563ea
PA
6705 /* Expedited registers. */
6706 if (stop_reply->regcache)
6707 {
217f1f79 6708 struct regcache *regcache
f5656ead 6709 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6710 cached_reg_t *reg;
6711 int ix;
6712
6713 for (ix = 0;
6714 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6715 ix++)
217f1f79 6716 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6717 VEC_free (cached_reg_t, stop_reply->regcache);
6718 }
74531fed 6719
1941c569 6720 remote_notice_new_inferior (ptid, 0);
799a2abe
PA
6721 remote_thr = demand_private_info (ptid);
6722 remote_thr->core = stop_reply->core;
6723 remote_thr->stop_reason = stop_reply->stop_reason;
6724 remote_thr->watch_data_address = stop_reply->watch_data_address;
74531fed
PA
6725 }
6726
74531fed
PA
6727 stop_reply_xfree (stop_reply);
6728 return ptid;
6729}
6730
6731/* The non-stop mode version of target_wait. */
6732
6733static ptid_t
47608cb1 6734remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6735{
6736 struct remote_state *rs = get_remote_state ();
74531fed
PA
6737 struct stop_reply *stop_reply;
6738 int ret;
fee9eda9 6739 int is_notif = 0;
74531fed
PA
6740
6741 /* If in non-stop mode, get out of getpkt even if a
6742 notification is received. */
6743
6744 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6745 0 /* forever */, &is_notif);
74531fed
PA
6746 while (1)
6747 {
fee9eda9 6748 if (ret != -1 && !is_notif)
74531fed
PA
6749 switch (rs->buf[0])
6750 {
6751 case 'E': /* Error of some sort. */
6752 /* We're out of sync with the target now. Did it continue
6753 or not? We can't tell which thread it was in non-stop,
6754 so just ignore this. */
6755 warning (_("Remote failure reply: %s"), rs->buf);
6756 break;
6757 case 'O': /* Console output. */
6758 remote_console_output (rs->buf + 1);
6759 break;
6760 default:
6761 warning (_("Invalid remote reply: %s"), rs->buf);
6762 break;
6763 }
6764
6765 /* Acknowledge a pending stop reply that may have arrived in the
6766 mean time. */
f48ff2a7 6767 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6768 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6769
6770 /* If indeed we noticed a stop reply, we're done. */
6771 stop_reply = queued_stop_reply (ptid);
6772 if (stop_reply != NULL)
6773 return process_stop_reply (stop_reply, status);
6774
47608cb1 6775 /* Still no event. If we're just polling for an event, then
74531fed 6776 return to the event loop. */
47608cb1 6777 if (options & TARGET_WNOHANG)
74531fed
PA
6778 {
6779 status->kind = TARGET_WAITKIND_IGNORE;
6780 return minus_one_ptid;
6781 }
6782
47608cb1 6783 /* Otherwise do a blocking wait. */
74531fed 6784 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6785 1 /* forever */, &is_notif);
74531fed
PA
6786 }
6787}
6788
6789/* Wait until the remote machine stops, then return, storing status in
6790 STATUS just as `wait' would. */
6791
6792static ptid_t
47608cb1 6793remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6794{
6795 struct remote_state *rs = get_remote_state ();
74531fed 6796 ptid_t event_ptid = null_ptid;
cea39f65 6797 char *buf;
74531fed
PA
6798 struct stop_reply *stop_reply;
6799
47608cb1
PA
6800 again:
6801
74531fed
PA
6802 status->kind = TARGET_WAITKIND_IGNORE;
6803 status->value.integer = 0;
6804
6805 stop_reply = queued_stop_reply (ptid);
6806 if (stop_reply != NULL)
6807 return process_stop_reply (stop_reply, status);
6808
6809 if (rs->cached_wait_status)
6810 /* Use the cached wait status, but only once. */
6811 rs->cached_wait_status = 0;
6812 else
6813 {
6814 int ret;
722247f1 6815 int is_notif;
567420d1
PA
6816 int forever = ((options & TARGET_WNOHANG) == 0
6817 && wait_forever_enabled_p);
6818
6819 if (!rs->waiting_for_stop_reply)
6820 {
6821 status->kind = TARGET_WAITKIND_NO_RESUMED;
6822 return minus_one_ptid;
6823 }
74531fed
PA
6824
6825 if (!target_is_async_p ())
6826 {
934b9bac 6827 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6828 /* If the user hit C-c before this packet, or between packets,
6829 pretend that it was hit right here. */
522002f9 6830 if (check_quit_flag ())
74531fed 6831 {
522002f9 6832 clear_quit_flag ();
934b9bac 6833 sync_remote_interrupt (SIGINT);
74531fed
PA
6834 }
6835 }
6836
6837 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6838 _never_ wait for ever -> test on target_is_async_p().
6839 However, before we do that we need to ensure that the caller
6840 knows how to take the target into/out of async mode. */
722247f1 6841 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6842 forever, &is_notif);
722247f1 6843
5e1b953b
SDJ
6844 if (!target_is_async_p ())
6845 signal (SIGINT, ofunc);
6846
722247f1
YQ
6847 /* GDB gets a notification. Return to core as this event is
6848 not interesting. */
6849 if (ret != -1 && is_notif)
6850 return minus_one_ptid;
567420d1
PA
6851
6852 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6853 return minus_one_ptid;
74531fed
PA
6854 }
6855
6856 buf = rs->buf;
6857
3a29589a
DJ
6858 /* Assume that the target has acknowledged Ctrl-C unless we receive
6859 an 'F' or 'O' packet. */
6860 if (buf[0] != 'F' && buf[0] != 'O')
6861 rs->ctrlc_pending_p = 0;
6862
74531fed
PA
6863 switch (buf[0])
6864 {
6865 case 'E': /* Error of some sort. */
6866 /* We're out of sync with the target now. Did it continue or
6867 not? Not is more likely, so report a stop. */
29090fb6
LM
6868 rs->waiting_for_stop_reply = 0;
6869
74531fed
PA
6870 warning (_("Remote failure reply: %s"), buf);
6871 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6872 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6873 break;
6874 case 'F': /* File-I/O request. */
3a29589a
DJ
6875 remote_fileio_request (buf, rs->ctrlc_pending_p);
6876 rs->ctrlc_pending_p = 0;
74531fed
PA
6877 break;
6878 case 'T': case 'S': case 'X': case 'W':
6879 {
29090fb6
LM
6880 struct stop_reply *stop_reply;
6881
6882 /* There is a stop reply to handle. */
6883 rs->waiting_for_stop_reply = 0;
6884
6885 stop_reply
722247f1
YQ
6886 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6887 rs->buf);
74531fed 6888
74531fed 6889 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6890 break;
6891 }
6892 case 'O': /* Console output. */
6893 remote_console_output (buf + 1);
c8e38a49
PA
6894 break;
6895 case '\0':
b73be471 6896 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6897 {
6898 /* Zero length reply means that we tried 'S' or 'C' and the
6899 remote system doesn't support it. */
6900 target_terminal_ours_for_output ();
6901 printf_filtered
6902 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6903 gdb_signal_to_name (rs->last_sent_signal));
6904 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6905 target_terminal_inferior ();
6906
280ceea3 6907 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49 6908 putpkt ((char *) buf);
c8e38a49 6909 break;
43ff13b4 6910 }
c8e38a49
PA
6911 /* else fallthrough */
6912 default:
6913 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 6914 break;
43ff13b4 6915 }
c8e38a49 6916
c8e38a49 6917 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6918 {
6919 /* Nothing interesting happened. If we're doing a non-blocking
6920 poll, we're done. Otherwise, go back to waiting. */
6921 if (options & TARGET_WNOHANG)
6922 return minus_one_ptid;
6923 else
6924 goto again;
6925 }
74531fed
PA
6926 else if (status->kind != TARGET_WAITKIND_EXITED
6927 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6928 {
6929 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6930 record_currthread (rs, event_ptid);
82f73884
PA
6931 else
6932 event_ptid = inferior_ptid;
43ff13b4 6933 }
74531fed
PA
6934 else
6935 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6936 record_currthread (rs, minus_one_ptid);
79d7f229 6937
82f73884 6938 return event_ptid;
43ff13b4
JM
6939}
6940
74531fed
PA
6941/* Wait until the remote machine stops, then return, storing status in
6942 STATUS just as `wait' would. */
6943
c8e38a49 6944static ptid_t
117de6a9 6945remote_wait (struct target_ops *ops,
47608cb1 6946 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6947{
6948 ptid_t event_ptid;
6949
6efcd9a8 6950 if (target_is_non_stop_p ())
47608cb1 6951 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6952 else
47608cb1 6953 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6954
d9d41e78 6955 if (target_is_async_p ())
c8e38a49 6956 {
74531fed
PA
6957 /* If there are are events left in the queue tell the event loop
6958 to return here. */
722247f1 6959 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6960 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6961 }
c8e38a49
PA
6962
6963 return event_ptid;
6964}
6965
74ca34ce 6966/* Fetch a single register using a 'p' packet. */
c906108c 6967
b96ec7ac 6968static int
56be3814 6969fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6970{
6971 struct remote_state *rs = get_remote_state ();
2e9f7625 6972 char *buf, *p;
b96ec7ac
AC
6973 char regp[MAX_REGISTER_SIZE];
6974 int i;
6975
4082afcc 6976 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6977 return 0;
6978
6979 if (reg->pnum == -1)
6980 return 0;
6981
2e9f7625 6982 p = rs->buf;
fcad0fa4 6983 *p++ = 'p';
74ca34ce 6984 p += hexnumstr (p, reg->pnum);
fcad0fa4 6985 *p++ = '\0';
1f4437a4
MS
6986 putpkt (rs->buf);
6987 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6988
2e9f7625
DJ
6989 buf = rs->buf;
6990
74ca34ce
DJ
6991 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6992 {
6993 case PACKET_OK:
6994 break;
6995 case PACKET_UNKNOWN:
6996 return 0;
6997 case PACKET_ERROR:
27a9c0bf
MS
6998 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6999 gdbarch_register_name (get_regcache_arch (regcache),
7000 reg->regnum),
7001 buf);
74ca34ce 7002 }
3f9a994c
JB
7003
7004 /* If this register is unfetchable, tell the regcache. */
7005 if (buf[0] == 'x')
8480adf2 7006 {
56be3814 7007 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7008 return 1;
b96ec7ac 7009 }
b96ec7ac 7010
3f9a994c
JB
7011 /* Otherwise, parse and supply the value. */
7012 p = buf;
7013 i = 0;
7014 while (p[0] != 0)
7015 {
7016 if (p[1] == 0)
74ca34ce 7017 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7018
7019 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7020 p += 2;
7021 }
56be3814 7022 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7023 return 1;
b96ec7ac
AC
7024}
7025
74ca34ce
DJ
7026/* Fetch the registers included in the target's 'g' packet. */
7027
29709017
DJ
7028static int
7029send_g_packet (void)
c906108c 7030{
d01949b6 7031 struct remote_state *rs = get_remote_state ();
cea39f65 7032 int buf_len;
c906108c 7033
bba74b36 7034 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7035 remote_send (&rs->buf, &rs->buf_size);
c906108c 7036
29709017
DJ
7037 /* We can get out of synch in various cases. If the first character
7038 in the buffer is not a hex character, assume that has happened
7039 and try to fetch another packet to read. */
7040 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7041 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7042 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7043 && rs->buf[0] != 'x') /* New: unavailable register value. */
7044 {
7045 if (remote_debug)
7046 fprintf_unfiltered (gdb_stdlog,
7047 "Bad register packet; fetching a new packet\n");
7048 getpkt (&rs->buf, &rs->buf_size, 0);
7049 }
7050
74ca34ce
DJ
7051 buf_len = strlen (rs->buf);
7052
7053 /* Sanity check the received packet. */
7054 if (buf_len % 2 != 0)
7055 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7056
7057 return buf_len / 2;
7058}
7059
7060static void
56be3814 7061process_g_packet (struct regcache *regcache)
29709017 7062{
4a22f64d 7063 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7064 struct remote_state *rs = get_remote_state ();
7065 struct remote_arch_state *rsa = get_remote_arch_state ();
7066 int i, buf_len;
7067 char *p;
7068 char *regs;
7069
7070 buf_len = strlen (rs->buf);
7071
7072 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7073 if (buf_len > 2 * rsa->sizeof_g_packet)
7074 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7075
7076 /* Save the size of the packet sent to us by the target. It is used
7077 as a heuristic when determining the max size of packets that the
7078 target can safely receive. */
7079 if (rsa->actual_register_packet_size == 0)
7080 rsa->actual_register_packet_size = buf_len;
7081
7082 /* If this is smaller than we guessed the 'g' packet would be,
7083 update our records. A 'g' reply that doesn't include a register's
7084 value implies either that the register is not available, or that
7085 the 'p' packet must be used. */
7086 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7087 {
74ca34ce
DJ
7088 rsa->sizeof_g_packet = buf_len / 2;
7089
4a22f64d 7090 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7091 {
74ca34ce
DJ
7092 if (rsa->regs[i].pnum == -1)
7093 continue;
7094
7095 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7096 rsa->regs[i].in_g_packet = 0;
b96ec7ac 7097 else
74ca34ce 7098 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7099 }
74ca34ce 7100 }
b323314b 7101
224c3ddb 7102 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7103
7104 /* Unimplemented registers read as all bits zero. */
ea9c271d 7105 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7106
c906108c
SS
7107 /* Reply describes registers byte by byte, each byte encoded as two
7108 hex characters. Suck them all up, then supply them to the
7109 register cacheing/storage mechanism. */
7110
74ca34ce 7111 p = rs->buf;
ea9c271d 7112 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7113 {
74ca34ce
DJ
7114 if (p[0] == 0 || p[1] == 0)
7115 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7116 internal_error (__FILE__, __LINE__,
9b20d036 7117 _("unexpected end of 'g' packet reply"));
74ca34ce 7118
c906108c 7119 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7120 regs[i] = 0; /* 'x' */
c906108c
SS
7121 else
7122 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7123 p += 2;
7124 }
7125
a744cf53
MS
7126 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7127 {
7128 struct packet_reg *r = &rsa->regs[i];
7129
7130 if (r->in_g_packet)
7131 {
7132 if (r->offset * 2 >= strlen (rs->buf))
7133 /* This shouldn't happen - we adjusted in_g_packet above. */
7134 internal_error (__FILE__, __LINE__,
9b20d036 7135 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7136 else if (rs->buf[r->offset * 2] == 'x')
7137 {
7138 gdb_assert (r->offset * 2 < strlen (rs->buf));
7139 /* The register isn't available, mark it as such (at
7140 the same time setting the value to zero). */
7141 regcache_raw_supply (regcache, r->regnum, NULL);
7142 }
7143 else
7144 regcache_raw_supply (regcache, r->regnum,
7145 regs + r->offset);
7146 }
7147 }
c906108c
SS
7148}
7149
29709017 7150static void
56be3814 7151fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7152{
7153 send_g_packet ();
56be3814 7154 process_g_packet (regcache);
29709017
DJ
7155}
7156
e6e4e701
PA
7157/* Make the remote selected traceframe match GDB's selected
7158 traceframe. */
7159
7160static void
7161set_remote_traceframe (void)
7162{
7163 int newnum;
262e1174 7164 struct remote_state *rs = get_remote_state ();
e6e4e701 7165
262e1174 7166 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7167 return;
7168
7169 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7170 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7171
7172 newnum = target_trace_find (tfind_number,
7173 get_traceframe_number (), 0, 0, NULL);
7174
7175 /* Should not happen. If it does, all bets are off. */
7176 if (newnum != get_traceframe_number ())
7177 warning (_("could not set remote traceframe"));
7178}
7179
74ca34ce 7180static void
28439f5e
PA
7181remote_fetch_registers (struct target_ops *ops,
7182 struct regcache *regcache, int regnum)
74ca34ce 7183{
74ca34ce
DJ
7184 struct remote_arch_state *rsa = get_remote_arch_state ();
7185 int i;
7186
e6e4e701 7187 set_remote_traceframe ();
79d7f229 7188 set_general_thread (inferior_ptid);
74ca34ce
DJ
7189
7190 if (regnum >= 0)
7191 {
7192 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7193
74ca34ce
DJ
7194 gdb_assert (reg != NULL);
7195
7196 /* If this register might be in the 'g' packet, try that first -
7197 we are likely to read more than one register. If this is the
7198 first 'g' packet, we might be overly optimistic about its
7199 contents, so fall back to 'p'. */
7200 if (reg->in_g_packet)
7201 {
56be3814 7202 fetch_registers_using_g (regcache);
74ca34ce
DJ
7203 if (reg->in_g_packet)
7204 return;
7205 }
7206
56be3814 7207 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7208 return;
7209
7210 /* This register is not available. */
56be3814 7211 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7212
7213 return;
7214 }
7215
56be3814 7216 fetch_registers_using_g (regcache);
74ca34ce 7217
4a22f64d 7218 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7219 if (!rsa->regs[i].in_g_packet)
56be3814 7220 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7221 {
7222 /* This register is not available. */
56be3814 7223 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7224 }
7225}
7226
c906108c
SS
7227/* Prepare to store registers. Since we may send them all (using a
7228 'G' request), we have to read out the ones we don't want to change
7229 first. */
7230
c5aa993b 7231static void
f32dbf8c 7232remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7233{
ea9c271d 7234 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7235 int i;
cfd77fa1 7236 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7237
c906108c 7238 /* Make sure the entire registers array is valid. */
4082afcc 7239 switch (packet_support (PACKET_P))
5a2468f5
JM
7240 {
7241 case PACKET_DISABLE:
7242 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7243 /* Make sure all the necessary registers are cached. */
4a22f64d 7244 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7245 if (rsa->regs[i].in_g_packet)
316f2060 7246 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7247 break;
7248 case PACKET_ENABLE:
7249 break;
7250 }
7251}
7252
ad10f812 7253/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7254 packet was not recognized. */
5a2468f5
JM
7255
7256static int
1f4437a4
MS
7257store_register_using_P (const struct regcache *regcache,
7258 struct packet_reg *reg)
5a2468f5 7259{
4a22f64d 7260 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7261 struct remote_state *rs = get_remote_state ();
5a2468f5 7262 /* Try storing a single register. */
6d820c5c 7263 char *buf = rs->buf;
cfd77fa1 7264 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7265 char *p;
5a2468f5 7266
4082afcc 7267 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7268 return 0;
7269
7270 if (reg->pnum == -1)
7271 return 0;
7272
ea9c271d 7273 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7274 p = buf + strlen (buf);
56be3814 7275 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7276 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7277 putpkt (rs->buf);
7278 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7279
74ca34ce
DJ
7280 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7281 {
7282 case PACKET_OK:
7283 return 1;
7284 case PACKET_ERROR:
27a9c0bf
MS
7285 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7286 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7287 case PACKET_UNKNOWN:
7288 return 0;
7289 default:
7290 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7291 }
c906108c
SS
7292}
7293
23860348
MS
7294/* Store register REGNUM, or all registers if REGNUM == -1, from the
7295 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7296
7297static void
56be3814 7298store_registers_using_G (const struct regcache *regcache)
c906108c 7299{
d01949b6 7300 struct remote_state *rs = get_remote_state ();
ea9c271d 7301 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7302 gdb_byte *regs;
c906108c
SS
7303 char *p;
7304
193cb69f
AC
7305 /* Extract all the registers in the regcache copying them into a
7306 local buffer. */
7307 {
b323314b 7308 int i;
a744cf53 7309
224c3ddb 7310 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7311 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7312 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7313 {
ea9c271d 7314 struct packet_reg *r = &rsa->regs[i];
a744cf53 7315
b323314b 7316 if (r->in_g_packet)
56be3814 7317 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7318 }
7319 }
c906108c
SS
7320
7321 /* Command describes registers byte by byte,
7322 each byte encoded as two hex characters. */
6d820c5c 7323 p = rs->buf;
193cb69f 7324 *p++ = 'G';
74ca34ce
DJ
7325 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7326 updated. */
7327 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7328 putpkt (rs->buf);
7329 getpkt (&rs->buf, &rs->buf_size, 0);
7330 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7331 error (_("Could not write registers; remote failure reply '%s'"),
7332 rs->buf);
c906108c 7333}
74ca34ce
DJ
7334
7335/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7336 of the register cache buffer. FIXME: ignores errors. */
7337
7338static void
28439f5e
PA
7339remote_store_registers (struct target_ops *ops,
7340 struct regcache *regcache, int regnum)
74ca34ce 7341{
74ca34ce
DJ
7342 struct remote_arch_state *rsa = get_remote_arch_state ();
7343 int i;
7344
e6e4e701 7345 set_remote_traceframe ();
79d7f229 7346 set_general_thread (inferior_ptid);
74ca34ce
DJ
7347
7348 if (regnum >= 0)
7349 {
7350 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7351
74ca34ce
DJ
7352 gdb_assert (reg != NULL);
7353
7354 /* Always prefer to store registers using the 'P' packet if
7355 possible; we often change only a small number of registers.
7356 Sometimes we change a larger number; we'd need help from a
7357 higher layer to know to use 'G'. */
56be3814 7358 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7359 return;
7360
7361 /* For now, don't complain if we have no way to write the
7362 register. GDB loses track of unavailable registers too
7363 easily. Some day, this may be an error. We don't have
0df8b418 7364 any way to read the register, either... */
74ca34ce
DJ
7365 if (!reg->in_g_packet)
7366 return;
7367
56be3814 7368 store_registers_using_G (regcache);
74ca34ce
DJ
7369 return;
7370 }
7371
56be3814 7372 store_registers_using_G (regcache);
74ca34ce 7373
4a22f64d 7374 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7375 if (!rsa->regs[i].in_g_packet)
56be3814 7376 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7377 /* See above for why we do not issue an error here. */
7378 continue;
7379}
c906108c
SS
7380\f
7381
7382/* Return the number of hex digits in num. */
7383
7384static int
fba45db2 7385hexnumlen (ULONGEST num)
c906108c
SS
7386{
7387 int i;
7388
7389 for (i = 0; num != 0; i++)
7390 num >>= 4;
7391
7392 return max (i, 1);
7393}
7394
2df3850c 7395/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7396
7397static int
fba45db2 7398hexnumstr (char *buf, ULONGEST num)
c906108c 7399{
c906108c 7400 int len = hexnumlen (num);
a744cf53 7401
2df3850c
JM
7402 return hexnumnstr (buf, num, len);
7403}
7404
c906108c 7405
2df3850c 7406/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7407
2df3850c 7408static int
fba45db2 7409hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7410{
7411 int i;
7412
7413 buf[width] = '\0';
7414
7415 for (i = width - 1; i >= 0; i--)
c906108c 7416 {
c5aa993b 7417 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7418 num >>= 4;
7419 }
7420
2df3850c 7421 return width;
c906108c
SS
7422}
7423
23860348 7424/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7425
7426static CORE_ADDR
fba45db2 7427remote_address_masked (CORE_ADDR addr)
c906108c 7428{
883b9c6c 7429 unsigned int address_size = remote_address_size;
a744cf53 7430
911c95a5
UW
7431 /* If "remoteaddresssize" was not set, default to target address size. */
7432 if (!address_size)
f5656ead 7433 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7434
7435 if (address_size > 0
7436 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7437 {
7438 /* Only create a mask when that mask can safely be constructed
23860348 7439 in a ULONGEST variable. */
c906108c 7440 ULONGEST mask = 1;
a744cf53 7441
911c95a5 7442 mask = (mask << address_size) - 1;
c906108c
SS
7443 addr &= mask;
7444 }
7445 return addr;
7446}
7447
7448/* Determine whether the remote target supports binary downloading.
7449 This is accomplished by sending a no-op memory write of zero length
7450 to the target at the specified address. It does not suffice to send
23860348
MS
7451 the whole packet, since many stubs strip the eighth bit and
7452 subsequently compute a wrong checksum, which causes real havoc with
7453 remote_write_bytes.
7a292a7a 7454
96baa820 7455 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7456 clean. In cases like this, the user should clear "remote
23860348 7457 X-packet". */
96baa820 7458
c906108c 7459static void
fba45db2 7460check_binary_download (CORE_ADDR addr)
c906108c 7461{
d01949b6 7462 struct remote_state *rs = get_remote_state ();
24b06219 7463
4082afcc 7464 switch (packet_support (PACKET_X))
c906108c 7465 {
96baa820
JM
7466 case PACKET_DISABLE:
7467 break;
7468 case PACKET_ENABLE:
7469 break;
7470 case PACKET_SUPPORT_UNKNOWN:
7471 {
96baa820 7472 char *p;
802188a7 7473
2e9f7625 7474 p = rs->buf;
96baa820
JM
7475 *p++ = 'X';
7476 p += hexnumstr (p, (ULONGEST) addr);
7477 *p++ = ',';
7478 p += hexnumstr (p, (ULONGEST) 0);
7479 *p++ = ':';
7480 *p = '\0';
802188a7 7481
2e9f7625 7482 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7483 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7484
2e9f7625 7485 if (rs->buf[0] == '\0')
96baa820
JM
7486 {
7487 if (remote_debug)
7488 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7489 "binary downloading NOT "
7490 "supported by target\n");
444abaca 7491 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7492 }
7493 else
7494 {
7495 if (remote_debug)
7496 fprintf_unfiltered (gdb_stdlog,
64b9b334 7497 "binary downloading supported by target\n");
444abaca 7498 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7499 }
7500 break;
7501 }
c906108c
SS
7502 }
7503}
7504
124e13d9
SM
7505/* Helper function to resize the payload in order to try to get a good
7506 alignment. We try to write an amount of data such that the next write will
7507 start on an address aligned on REMOTE_ALIGN_WRITES. */
7508
7509static int
7510align_for_efficient_write (int todo, CORE_ADDR memaddr)
7511{
7512 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7513}
7514
c906108c
SS
7515/* Write memory data directly to the remote machine.
7516 This does not inform the data cache; the data cache uses this.
a76d924d 7517 HEADER is the starting part of the packet.
c906108c
SS
7518 MEMADDR is the address in the remote memory space.
7519 MYADDR is the address of the buffer in our space.
124e13d9
SM
7520 LEN_UNITS is the number of addressable units to write.
7521 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7522 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7523 should send data as binary ('X'), or hex-encoded ('M').
7524
7525 The function creates packet of the form
7526 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7527
124e13d9 7528 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7529
7530 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7531 are omitted.
7532
9b409511 7533 Return the transferred status, error or OK (an
124e13d9
SM
7534 'enum target_xfer_status' value). Save the number of addressable units
7535 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7536
7537 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7538 exchange between gdb and the stub could look like (?? in place of the
7539 checksum):
7540
7541 -> $m1000,4#??
7542 <- aaaabbbbccccdddd
7543
7544 -> $M1000,3:eeeeffffeeee#??
7545 <- OK
7546
7547 -> $m1000,4#??
7548 <- eeeeffffeeeedddd */
c906108c 7549
9b409511 7550static enum target_xfer_status
a76d924d 7551remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7552 const gdb_byte *myaddr, ULONGEST len_units,
7553 int unit_size, ULONGEST *xfered_len_units,
7554 char packet_format, int use_length)
c906108c 7555{
6d820c5c 7556 struct remote_state *rs = get_remote_state ();
cfd77fa1 7557 char *p;
a76d924d
DJ
7558 char *plen = NULL;
7559 int plenlen = 0;
124e13d9
SM
7560 int todo_units;
7561 int units_written;
7562 int payload_capacity_bytes;
7563 int payload_length_bytes;
a76d924d
DJ
7564
7565 if (packet_format != 'X' && packet_format != 'M')
7566 internal_error (__FILE__, __LINE__,
9b20d036 7567 _("remote_write_bytes_aux: bad packet format"));
c906108c 7568
124e13d9 7569 if (len_units == 0)
9b409511 7570 return TARGET_XFER_EOF;
b2182ed2 7571
124e13d9 7572 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7573
6d820c5c
DJ
7574 /* The packet buffer will be large enough for the payload;
7575 get_memory_packet_size ensures this. */
a76d924d 7576 rs->buf[0] = '\0';
c906108c 7577
a257b5bb 7578 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7579 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7580
124e13d9 7581 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7582 if (!use_length)
0df8b418 7583 /* The comma won't be used. */
124e13d9
SM
7584 payload_capacity_bytes += 1;
7585 payload_capacity_bytes -= strlen (header);
7586 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7587
a76d924d 7588 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7589
a76d924d
DJ
7590 strcat (rs->buf, header);
7591 p = rs->buf + strlen (header);
7592
7593 /* Compute a best guess of the number of bytes actually transfered. */
7594 if (packet_format == 'X')
c906108c 7595 {
23860348 7596 /* Best guess at number of bytes that will fit. */
124e13d9 7597 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7598 if (use_length)
124e13d9
SM
7599 payload_capacity_bytes -= hexnumlen (todo_units);
7600 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7601 }
7602 else
7603 {
124e13d9
SM
7604 /* Number of bytes that will fit. */
7605 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7606 if (use_length)
124e13d9
SM
7607 payload_capacity_bytes -= hexnumlen (todo_units);
7608 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7609 }
a76d924d 7610
124e13d9 7611 if (todo_units <= 0)
3de11b2e 7612 internal_error (__FILE__, __LINE__,
405f8e94 7613 _("minimum packet size too small to write data"));
802188a7 7614
6765f3e5
DJ
7615 /* If we already need another packet, then try to align the end
7616 of this packet to a useful boundary. */
124e13d9
SM
7617 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7618 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7619
a257b5bb 7620 /* Append "<memaddr>". */
917317f4
JM
7621 memaddr = remote_address_masked (memaddr);
7622 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7623
a76d924d
DJ
7624 if (use_length)
7625 {
7626 /* Append ",". */
7627 *p++ = ',';
802188a7 7628
124e13d9
SM
7629 /* Append the length and retain its location and size. It may need to be
7630 adjusted once the packet body has been created. */
a76d924d 7631 plen = p;
124e13d9 7632 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7633 p += plenlen;
7634 }
a257b5bb
AC
7635
7636 /* Append ":". */
917317f4
JM
7637 *p++ = ':';
7638 *p = '\0';
802188a7 7639
a257b5bb 7640 /* Append the packet body. */
a76d924d 7641 if (packet_format == 'X')
917317f4 7642 {
917317f4
JM
7643 /* Binary mode. Send target system values byte by byte, in
7644 increasing byte addresses. Only escape certain critical
7645 characters. */
124e13d9
SM
7646 payload_length_bytes =
7647 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7648 &units_written, payload_capacity_bytes);
6765f3e5 7649
124e13d9 7650 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7651 a second try to keep the end of the packet aligned. Don't do
7652 this if the packet is tiny. */
124e13d9 7653 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7654 {
124e13d9
SM
7655 int new_todo_units;
7656
7657 new_todo_units = align_for_efficient_write (units_written, memaddr);
7658
7659 if (new_todo_units != units_written)
7660 payload_length_bytes =
7661 remote_escape_output (myaddr, new_todo_units, unit_size,
7662 (gdb_byte *) p, &units_written,
7663 payload_capacity_bytes);
6765f3e5
DJ
7664 }
7665
124e13d9
SM
7666 p += payload_length_bytes;
7667 if (use_length && units_written < todo_units)
c906108c 7668 {
802188a7 7669 /* Escape chars have filled up the buffer prematurely,
124e13d9 7670 and we have actually sent fewer units than planned.
917317f4
JM
7671 Fix-up the length field of the packet. Use the same
7672 number of characters as before. */
124e13d9
SM
7673 plen += hexnumnstr (plen, (ULONGEST) units_written,
7674 plenlen);
917317f4 7675 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7676 }
a76d924d
DJ
7677 }
7678 else
7679 {
917317f4
JM
7680 /* Normal mode: Send target system values byte by byte, in
7681 increasing byte addresses. Each byte is encoded as a two hex
7682 value. */
124e13d9
SM
7683 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7684 units_written = todo_units;
c906108c 7685 }
802188a7 7686
2e9f7625 7687 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7688 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7689
2e9f7625 7690 if (rs->buf[0] == 'E')
00d84524 7691 return TARGET_XFER_E_IO;
802188a7 7692
124e13d9
SM
7693 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7694 send fewer units than we'd planned. */
7695 *xfered_len_units = (ULONGEST) units_written;
9b409511 7696 return TARGET_XFER_OK;
c906108c
SS
7697}
7698
a76d924d
DJ
7699/* Write memory data directly to the remote machine.
7700 This does not inform the data cache; the data cache uses this.
7701 MEMADDR is the address in the remote memory space.
7702 MYADDR is the address of the buffer in our space.
7703 LEN is the number of bytes.
7704
9b409511
YQ
7705 Return the transferred status, error or OK (an
7706 'enum target_xfer_status' value). Save the number of bytes
7707 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7708
9b409511
YQ
7709static enum target_xfer_status
7710remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7711 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7712{
7713 char *packet_format = 0;
7714
7715 /* Check whether the target supports binary download. */
7716 check_binary_download (memaddr);
7717
4082afcc 7718 switch (packet_support (PACKET_X))
a76d924d
DJ
7719 {
7720 case PACKET_ENABLE:
7721 packet_format = "X";
7722 break;
7723 case PACKET_DISABLE:
7724 packet_format = "M";
7725 break;
7726 case PACKET_SUPPORT_UNKNOWN:
7727 internal_error (__FILE__, __LINE__,
7728 _("remote_write_bytes: bad internal state"));
7729 default:
7730 internal_error (__FILE__, __LINE__, _("bad switch"));
7731 }
7732
7733 return remote_write_bytes_aux (packet_format,
124e13d9 7734 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7735 packet_format[0], 1);
a76d924d
DJ
7736}
7737
9217e74e
YQ
7738/* Read memory data directly from the remote machine.
7739 This does not use the data cache; the data cache uses this.
7740 MEMADDR is the address in the remote memory space.
7741 MYADDR is the address of the buffer in our space.
124e13d9
SM
7742 LEN_UNITS is the number of addressable memory units to read..
7743 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7744
7745 Return the transferred status, error or OK (an
7746 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7747 transferred in *XFERED_LEN_UNITS.
7748
7749 See the comment of remote_write_bytes_aux for an example of
7750 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7751
7752static enum target_xfer_status
124e13d9
SM
7753remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7754 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7755{
7756 struct remote_state *rs = get_remote_state ();
124e13d9 7757 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7758 char *p;
124e13d9
SM
7759 int todo_units;
7760 int decoded_bytes;
9217e74e 7761
124e13d9 7762 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7763 /* The packet buffer will be large enough for the payload;
7764 get_memory_packet_size ensures this. */
7765
124e13d9
SM
7766 /* Number of units that will fit. */
7767 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7768
7769 /* Construct "m"<memaddr>","<len>". */
7770 memaddr = remote_address_masked (memaddr);
7771 p = rs->buf;
7772 *p++ = 'm';
7773 p += hexnumstr (p, (ULONGEST) memaddr);
7774 *p++ = ',';
124e13d9 7775 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7776 *p = '\0';
7777 putpkt (rs->buf);
7778 getpkt (&rs->buf, &rs->buf_size, 0);
7779 if (rs->buf[0] == 'E'
7780 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7781 && rs->buf[3] == '\0')
7782 return TARGET_XFER_E_IO;
7783 /* Reply describes memory byte by byte, each byte encoded as two hex
7784 characters. */
7785 p = rs->buf;
124e13d9 7786 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7787 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7788 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7789 return TARGET_XFER_OK;
7790}
7791
b55fbac4
YQ
7792/* Using the set of read-only target sections of remote, read live
7793 read-only memory.
8acf9577
YQ
7794
7795 For interface/parameters/return description see target.h,
7796 to_xfer_partial. */
7797
7798static enum target_xfer_status
b55fbac4
YQ
7799remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7800 ULONGEST memaddr, ULONGEST len,
124e13d9 7801 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7802{
7803 struct target_section *secp;
7804 struct target_section_table *table;
7805
7806 secp = target_section_by_addr (ops, memaddr);
7807 if (secp != NULL
7808 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7809 secp->the_bfd_section)
7810 & SEC_READONLY))
7811 {
7812 struct target_section *p;
7813 ULONGEST memend = memaddr + len;
7814
7815 table = target_get_section_table (ops);
7816
7817 for (p = table->sections; p < table->sections_end; p++)
7818 {
7819 if (memaddr >= p->addr)
7820 {
7821 if (memend <= p->endaddr)
7822 {
7823 /* Entire transfer is within this section. */
124e13d9 7824 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7825 xfered_len);
8acf9577
YQ
7826 }
7827 else if (memaddr >= p->endaddr)
7828 {
7829 /* This section ends before the transfer starts. */
7830 continue;
7831 }
7832 else
7833 {
7834 /* This section overlaps the transfer. Just do half. */
7835 len = p->endaddr - memaddr;
124e13d9 7836 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7837 xfered_len);
8acf9577
YQ
7838 }
7839 }
7840 }
7841 }
7842
7843 return TARGET_XFER_EOF;
7844}
7845
9217e74e
YQ
7846/* Similar to remote_read_bytes_1, but it reads from the remote stub
7847 first if the requested memory is unavailable in traceframe.
7848 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7849
9b409511 7850static enum target_xfer_status
8acf9577 7851remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7852 gdb_byte *myaddr, ULONGEST len, int unit_size,
7853 ULONGEST *xfered_len)
c906108c 7854{
6b6aa828 7855 if (len == 0)
96c4f946 7856 return TARGET_XFER_EOF;
b2182ed2 7857
8acf9577
YQ
7858 if (get_traceframe_number () != -1)
7859 {
7860 VEC(mem_range_s) *available;
7861
7862 /* If we fail to get the set of available memory, then the
7863 target does not support querying traceframe info, and so we
7864 attempt reading from the traceframe anyway (assuming the
7865 target implements the old QTro packet then). */
7866 if (traceframe_available_memory (&available, memaddr, len))
7867 {
7868 struct cleanup *old_chain;
7869
7870 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7871
7872 if (VEC_empty (mem_range_s, available)
7873 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7874 {
7875 enum target_xfer_status res;
7876
7877 /* Don't read into the traceframe's available
7878 memory. */
7879 if (!VEC_empty (mem_range_s, available))
7880 {
7881 LONGEST oldlen = len;
7882
7883 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7884 gdb_assert (len <= oldlen);
7885 }
7886
7887 do_cleanups (old_chain);
7888
7889 /* This goes through the topmost target again. */
b55fbac4 7890 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7891 len, unit_size, xfered_len);
8acf9577
YQ
7892 if (res == TARGET_XFER_OK)
7893 return TARGET_XFER_OK;
7894 else
7895 {
7896 /* No use trying further, we know some memory starting
7897 at MEMADDR isn't available. */
7898 *xfered_len = len;
7899 return TARGET_XFER_UNAVAILABLE;
7900 }
7901 }
7902
7903 /* Don't try to read more than how much is available, in
7904 case the target implements the deprecated QTro packet to
7905 cater for older GDBs (the target's knowledge of read-only
7906 sections may be outdated by now). */
7907 len = VEC_index (mem_range_s, available, 0)->length;
7908
7909 do_cleanups (old_chain);
7910 }
7911 }
7912
124e13d9 7913 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7914}
74531fed 7915
c906108c 7916\f
c906108c 7917
a76d924d
DJ
7918/* Sends a packet with content determined by the printf format string
7919 FORMAT and the remaining arguments, then gets the reply. Returns
7920 whether the packet was a success, a failure, or unknown. */
7921
77b64a49
PA
7922static enum packet_result remote_send_printf (const char *format, ...)
7923 ATTRIBUTE_PRINTF (1, 2);
7924
2c0b251b 7925static enum packet_result
a76d924d
DJ
7926remote_send_printf (const char *format, ...)
7927{
7928 struct remote_state *rs = get_remote_state ();
7929 int max_size = get_remote_packet_size ();
a76d924d 7930 va_list ap;
a744cf53 7931
a76d924d
DJ
7932 va_start (ap, format);
7933
7934 rs->buf[0] = '\0';
7935 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7936 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7937
7938 if (putpkt (rs->buf) < 0)
7939 error (_("Communication problem with target."));
7940
7941 rs->buf[0] = '\0';
7942 getpkt (&rs->buf, &rs->buf_size, 0);
7943
7944 return packet_check_result (rs->buf);
7945}
7946
7947static void
7948restore_remote_timeout (void *p)
7949{
7950 int value = *(int *)p;
a744cf53 7951
a76d924d
DJ
7952 remote_timeout = value;
7953}
7954
7955/* Flash writing can take quite some time. We'll set
7956 effectively infinite timeout for flash operations.
7957 In future, we'll need to decide on a better approach. */
7958static const int remote_flash_timeout = 1000;
7959
7960static void
7961remote_flash_erase (struct target_ops *ops,
7962 ULONGEST address, LONGEST length)
7963{
f5656ead 7964 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7965 int saved_remote_timeout = remote_timeout;
7966 enum packet_result ret;
a76d924d
DJ
7967 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7968 &saved_remote_timeout);
a744cf53 7969
a76d924d
DJ
7970 remote_timeout = remote_flash_timeout;
7971
7972 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7973 phex (address, addr_size),
a76d924d
DJ
7974 phex (length, 4));
7975 switch (ret)
7976 {
7977 case PACKET_UNKNOWN:
7978 error (_("Remote target does not support flash erase"));
7979 case PACKET_ERROR:
7980 error (_("Error erasing flash with vFlashErase packet"));
7981 default:
7982 break;
7983 }
7984
7985 do_cleanups (back_to);
7986}
7987
9b409511
YQ
7988static enum target_xfer_status
7989remote_flash_write (struct target_ops *ops, ULONGEST address,
7990 ULONGEST length, ULONGEST *xfered_len,
7991 const gdb_byte *data)
a76d924d
DJ
7992{
7993 int saved_remote_timeout = remote_timeout;
9b409511 7994 enum target_xfer_status ret;
a76d924d 7995 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7996 &saved_remote_timeout);
a76d924d
DJ
7997
7998 remote_timeout = remote_flash_timeout;
124e13d9 7999 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 8000 xfered_len,'X', 0);
a76d924d
DJ
8001 do_cleanups (back_to);
8002
8003 return ret;
8004}
8005
8006static void
8007remote_flash_done (struct target_ops *ops)
8008{
8009 int saved_remote_timeout = remote_timeout;
8010 int ret;
8011 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8012 &saved_remote_timeout);
8013
8014 remote_timeout = remote_flash_timeout;
8015 ret = remote_send_printf ("vFlashDone");
8016 do_cleanups (back_to);
8017
8018 switch (ret)
8019 {
8020 case PACKET_UNKNOWN:
8021 error (_("Remote target does not support vFlashDone"));
8022 case PACKET_ERROR:
8023 error (_("Error finishing flash operation"));
8024 default:
8025 break;
8026 }
8027}
8028
c906108c 8029static void
fba45db2 8030remote_files_info (struct target_ops *ignore)
c906108c
SS
8031{
8032 puts_filtered ("Debugging a target over a serial line.\n");
8033}
8034\f
8035/* Stuff for dealing with the packets which are part of this protocol.
8036 See comment at top of file for details. */
8037
1927e618
PA
8038/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8039 error to higher layers. Called when a serial error is detected.
8040 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8041 the system error message for errno at function entry and final dot
8042 for output compatibility with throw_perror_with_name. */
1927e618
PA
8043
8044static void
8045unpush_and_perror (const char *string)
8046{
d6cb50a2 8047 int saved_errno = errno;
1927e618
PA
8048
8049 remote_unpush_target ();
d6cb50a2
JK
8050 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8051 safe_strerror (saved_errno));
1927e618
PA
8052}
8053
0876f84a 8054/* Read a single character from the remote end. */
c906108c
SS
8055
8056static int
fba45db2 8057readchar (int timeout)
c906108c
SS
8058{
8059 int ch;
5d93a237 8060 struct remote_state *rs = get_remote_state ();
c906108c 8061
5d93a237 8062 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 8063
2acceee2 8064 if (ch >= 0)
0876f84a 8065 return ch;
2acceee2
JM
8066
8067 switch ((enum serial_rc) ch)
c906108c
SS
8068 {
8069 case SERIAL_EOF:
78a095c3 8070 remote_unpush_target ();
598d3636 8071 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8072 /* no return */
c906108c 8073 case SERIAL_ERROR:
1927e618
PA
8074 unpush_and_perror (_("Remote communication error. "
8075 "Target disconnected."));
2acceee2 8076 /* no return */
c906108c 8077 case SERIAL_TIMEOUT:
2acceee2 8078 break;
c906108c 8079 }
2acceee2 8080 return ch;
c906108c
SS
8081}
8082
c33e31fd
PA
8083/* Wrapper for serial_write that closes the target and throws if
8084 writing fails. */
8085
8086static void
8087remote_serial_write (const char *str, int len)
8088{
5d93a237
TT
8089 struct remote_state *rs = get_remote_state ();
8090
8091 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8092 {
1927e618
PA
8093 unpush_and_perror (_("Remote communication error. "
8094 "Target disconnected."));
c33e31fd
PA
8095 }
8096}
8097
6d820c5c
DJ
8098/* Send the command in *BUF to the remote machine, and read the reply
8099 into *BUF. Report an error if we get an error reply. Resize
8100 *BUF using xrealloc if necessary to hold the result, and update
8101 *SIZEOF_BUF. */
c906108c
SS
8102
8103static void
6d820c5c
DJ
8104remote_send (char **buf,
8105 long *sizeof_buf)
c906108c 8106{
6d820c5c 8107 putpkt (*buf);
c2d11a7d 8108 getpkt (buf, sizeof_buf, 0);
c906108c 8109
6d820c5c
DJ
8110 if ((*buf)[0] == 'E')
8111 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8112}
8113
6e5abd65
PA
8114/* Return a pointer to an xmalloc'ed string representing an escaped
8115 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8116 etc. The caller is responsible for releasing the returned
8117 memory. */
8118
8119static char *
8120escape_buffer (const char *buf, int n)
8121{
8122 struct cleanup *old_chain;
8123 struct ui_file *stb;
8124 char *str;
6e5abd65
PA
8125
8126 stb = mem_fileopen ();
8127 old_chain = make_cleanup_ui_file_delete (stb);
8128
6ef284bd 8129 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 8130 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
8131 do_cleanups (old_chain);
8132 return str;
8133}
8134
c906108c
SS
8135/* Display a null-terminated packet on stdout, for debugging, using C
8136 string notation. */
8137
8138static void
baa336ce 8139print_packet (const char *buf)
c906108c
SS
8140{
8141 puts_filtered ("\"");
43e526b9 8142 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8143 puts_filtered ("\"");
8144}
8145
8146int
baa336ce 8147putpkt (const char *buf)
c906108c
SS
8148{
8149 return putpkt_binary (buf, strlen (buf));
8150}
8151
8152/* Send a packet to the remote machine, with error checking. The data
23860348 8153 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8154 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8155 and for a possible /0 if we are debugging (remote_debug) and want
8156 to print the sent packet as a string. */
c906108c
SS
8157
8158static int
baa336ce 8159putpkt_binary (const char *buf, int cnt)
c906108c 8160{
2d717e4f 8161 struct remote_state *rs = get_remote_state ();
c906108c
SS
8162 int i;
8163 unsigned char csum = 0;
224c3ddb 8164 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8165 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8166
c906108c
SS
8167 int ch;
8168 int tcount = 0;
8169 char *p;
dd61ec5c 8170 char *message;
c906108c 8171
e24a49d8
PA
8172 /* Catch cases like trying to read memory or listing threads while
8173 we're waiting for a stop reply. The remote server wouldn't be
8174 ready to handle this request, so we'd hang and timeout. We don't
8175 have to worry about this in synchronous mode, because in that
8176 case it's not possible to issue a command while the target is
74531fed
PA
8177 running. This is not a problem in non-stop mode, because in that
8178 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8179 if (!target_is_non_stop_p ()
8180 && target_is_async_p ()
8181 && rs->waiting_for_stop_reply)
9597b22a
DE
8182 {
8183 error (_("Cannot execute this command while the target is running.\n"
8184 "Use the \"interrupt\" command to stop the target\n"
8185 "and then try again."));
8186 }
e24a49d8 8187
2d717e4f
DJ
8188 /* We're sending out a new packet. Make sure we don't look at a
8189 stale cached response. */
8190 rs->cached_wait_status = 0;
8191
c906108c
SS
8192 /* Copy the packet into buffer BUF2, encapsulating it
8193 and giving it a checksum. */
8194
c906108c
SS
8195 p = buf2;
8196 *p++ = '$';
8197
8198 for (i = 0; i < cnt; i++)
8199 {
8200 csum += buf[i];
8201 *p++ = buf[i];
8202 }
8203 *p++ = '#';
8204 *p++ = tohex ((csum >> 4) & 0xf);
8205 *p++ = tohex (csum & 0xf);
8206
8207 /* Send it over and over until we get a positive ack. */
8208
8209 while (1)
8210 {
8211 int started_error_output = 0;
8212
8213 if (remote_debug)
8214 {
6e5abd65
PA
8215 struct cleanup *old_chain;
8216 char *str;
8217
c906108c 8218 *p = '\0';
6e5abd65
PA
8219 str = escape_buffer (buf2, p - buf2);
8220 old_chain = make_cleanup (xfree, str);
8221 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8222 gdb_flush (gdb_stdlog);
6e5abd65 8223 do_cleanups (old_chain);
c906108c 8224 }
c33e31fd 8225 remote_serial_write (buf2, p - buf2);
c906108c 8226
a6f3e723
SL
8227 /* If this is a no acks version of the remote protocol, send the
8228 packet and move on. */
8229 if (rs->noack_mode)
8230 break;
8231
74531fed
PA
8232 /* Read until either a timeout occurs (-2) or '+' is read.
8233 Handle any notification that arrives in the mean time. */
c906108c
SS
8234 while (1)
8235 {
8236 ch = readchar (remote_timeout);
8237
c5aa993b 8238 if (remote_debug)
c906108c
SS
8239 {
8240 switch (ch)
8241 {
8242 case '+':
1216fa2c 8243 case '-':
c906108c
SS
8244 case SERIAL_TIMEOUT:
8245 case '$':
74531fed 8246 case '%':
c906108c
SS
8247 if (started_error_output)
8248 {
8249 putchar_unfiltered ('\n');
8250 started_error_output = 0;
8251 }
8252 }
8253 }
8254
8255 switch (ch)
8256 {
8257 case '+':
8258 if (remote_debug)
0f71a2f6 8259 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8260 do_cleanups (old_chain);
c906108c 8261 return 1;
1216fa2c
AC
8262 case '-':
8263 if (remote_debug)
8264 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8265 /* FALLTHROUGH */
c906108c 8266 case SERIAL_TIMEOUT:
c5aa993b 8267 tcount++;
c906108c 8268 if (tcount > 3)
a5c0808e
PA
8269 {
8270 do_cleanups (old_chain);
8271 return 0;
8272 }
23860348 8273 break; /* Retransmit buffer. */
c906108c
SS
8274 case '$':
8275 {
40e3f985 8276 if (remote_debug)
2bc416ba 8277 fprintf_unfiltered (gdb_stdlog,
23860348 8278 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8279 /* It's probably an old response sent because an ACK
8280 was lost. Gobble up the packet and ack it so it
8281 doesn't get retransmitted when we resend this
8282 packet. */
6d820c5c 8283 skip_frame ();
c33e31fd 8284 remote_serial_write ("+", 1);
23860348 8285 continue; /* Now, go look for +. */
c906108c 8286 }
74531fed
PA
8287
8288 case '%':
8289 {
8290 int val;
8291
8292 /* If we got a notification, handle it, and go back to looking
8293 for an ack. */
8294 /* We've found the start of a notification. Now
8295 collect the data. */
8296 val = read_frame (&rs->buf, &rs->buf_size);
8297 if (val >= 0)
8298 {
8299 if (remote_debug)
8300 {
6e5abd65
PA
8301 struct cleanup *old_chain;
8302 char *str;
8303
8304 str = escape_buffer (rs->buf, val);
8305 old_chain = make_cleanup (xfree, str);
8306 fprintf_unfiltered (gdb_stdlog,
8307 " Notification received: %s\n",
8308 str);
8309 do_cleanups (old_chain);
74531fed 8310 }
5965e028 8311 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8312 /* We're in sync now, rewait for the ack. */
8313 tcount = 0;
8314 }
8315 else
8316 {
8317 if (remote_debug)
8318 {
8319 if (!started_error_output)
8320 {
8321 started_error_output = 1;
8322 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8323 }
8324 fputc_unfiltered (ch & 0177, gdb_stdlog);
8325 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8326 }
8327 }
8328 continue;
8329 }
8330 /* fall-through */
c906108c
SS
8331 default:
8332 if (remote_debug)
8333 {
8334 if (!started_error_output)
8335 {
8336 started_error_output = 1;
0f71a2f6 8337 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8338 }
0f71a2f6 8339 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8340 }
8341 continue;
8342 }
23860348 8343 break; /* Here to retransmit. */
c906108c
SS
8344 }
8345
8346#if 0
8347 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8348 able to get out next time we call QUIT, without anything as
8349 violent as interrupt_query. If we want to provide a way out of
8350 here without getting to the next QUIT, it should be based on
8351 hitting ^C twice as in remote_wait. */
c906108c
SS
8352 if (quit_flag)
8353 {
8354 quit_flag = 0;
8355 interrupt_query ();
8356 }
8357#endif
8358 }
a5c0808e
PA
8359
8360 do_cleanups (old_chain);
a6f3e723 8361 return 0;
c906108c
SS
8362}
8363
6d820c5c
DJ
8364/* Come here after finding the start of a frame when we expected an
8365 ack. Do our best to discard the rest of this packet. */
8366
8367static void
8368skip_frame (void)
8369{
8370 int c;
8371
8372 while (1)
8373 {
8374 c = readchar (remote_timeout);
8375 switch (c)
8376 {
8377 case SERIAL_TIMEOUT:
8378 /* Nothing we can do. */
8379 return;
8380 case '#':
8381 /* Discard the two bytes of checksum and stop. */
8382 c = readchar (remote_timeout);
8383 if (c >= 0)
8384 c = readchar (remote_timeout);
8385
8386 return;
8387 case '*': /* Run length encoding. */
8388 /* Discard the repeat count. */
8389 c = readchar (remote_timeout);
8390 if (c < 0)
8391 return;
8392 break;
8393 default:
8394 /* A regular character. */
8395 break;
8396 }
8397 }
8398}
8399
c906108c 8400/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8401 into *BUF, verifying the checksum, length, and handling run-length
8402 compression. NUL terminate the buffer. If there is not enough room,
8403 expand *BUF using xrealloc.
c906108c 8404
c2d11a7d
JM
8405 Returns -1 on error, number of characters in buffer (ignoring the
8406 trailing NULL) on success. (could be extended to return one of the
23860348 8407 SERIAL status indications). */
c2d11a7d
JM
8408
8409static long
6d820c5c
DJ
8410read_frame (char **buf_p,
8411 long *sizeof_buf)
c906108c
SS
8412{
8413 unsigned char csum;
c2d11a7d 8414 long bc;
c906108c 8415 int c;
6d820c5c 8416 char *buf = *buf_p;
a6f3e723 8417 struct remote_state *rs = get_remote_state ();
c906108c
SS
8418
8419 csum = 0;
c2d11a7d 8420 bc = 0;
c906108c
SS
8421
8422 while (1)
8423 {
8424 c = readchar (remote_timeout);
c906108c
SS
8425 switch (c)
8426 {
8427 case SERIAL_TIMEOUT:
8428 if (remote_debug)
0f71a2f6 8429 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8430 return -1;
c906108c
SS
8431 case '$':
8432 if (remote_debug)
0f71a2f6
JM
8433 fputs_filtered ("Saw new packet start in middle of old one\n",
8434 gdb_stdlog);
23860348 8435 return -1; /* Start a new packet, count retries. */
c906108c
SS
8436 case '#':
8437 {
8438 unsigned char pktcsum;
e1b09194
AC
8439 int check_0 = 0;
8440 int check_1 = 0;
c906108c 8441
c2d11a7d 8442 buf[bc] = '\0';
c906108c 8443
e1b09194
AC
8444 check_0 = readchar (remote_timeout);
8445 if (check_0 >= 0)
8446 check_1 = readchar (remote_timeout);
802188a7 8447
e1b09194
AC
8448 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8449 {
8450 if (remote_debug)
2bc416ba 8451 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8452 gdb_stdlog);
e1b09194
AC
8453 return -1;
8454 }
8455 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8456 {
8457 if (remote_debug)
2bc416ba 8458 fputs_filtered ("Communication error in checksum\n",
23860348 8459 gdb_stdlog);
40e3f985
FN
8460 return -1;
8461 }
c906108c 8462
a6f3e723
SL
8463 /* Don't recompute the checksum; with no ack packets we
8464 don't have any way to indicate a packet retransmission
8465 is necessary. */
8466 if (rs->noack_mode)
8467 return bc;
8468
e1b09194 8469 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8470 if (csum == pktcsum)
c2d11a7d 8471 return bc;
c906108c 8472
c5aa993b 8473 if (remote_debug)
c906108c 8474 {
6e5abd65
PA
8475 struct cleanup *old_chain;
8476 char *str;
8477
8478 str = escape_buffer (buf, bc);
8479 old_chain = make_cleanup (xfree, str);
8480 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8481 "Bad checksum, sentsum=0x%x, "
8482 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8483 pktcsum, csum, str);
8484 do_cleanups (old_chain);
c906108c 8485 }
c2d11a7d 8486 /* Number of characters in buffer ignoring trailing
23860348 8487 NULL. */
c2d11a7d 8488 return -1;
c906108c 8489 }
23860348 8490 case '*': /* Run length encoding. */
c2c6d25f
JM
8491 {
8492 int repeat;
c906108c 8493
a744cf53 8494 csum += c;
b4501125
AC
8495 c = readchar (remote_timeout);
8496 csum += c;
23860348 8497 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8498
23860348 8499 /* The character before ``*'' is repeated. */
c2d11a7d 8500
6d820c5c 8501 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8502 {
6d820c5c
DJ
8503 if (bc + repeat - 1 >= *sizeof_buf - 1)
8504 {
8505 /* Make some more room in the buffer. */
8506 *sizeof_buf += repeat;
224c3ddb 8507 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
8508 buf = *buf_p;
8509 }
8510
c2d11a7d
JM
8511 memset (&buf[bc], buf[bc - 1], repeat);
8512 bc += repeat;
c2c6d25f
JM
8513 continue;
8514 }
8515
c2d11a7d 8516 buf[bc] = '\0';
6d820c5c 8517 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8518 return -1;
c2c6d25f 8519 }
c906108c 8520 default:
6d820c5c 8521 if (bc >= *sizeof_buf - 1)
c906108c 8522 {
6d820c5c
DJ
8523 /* Make some more room in the buffer. */
8524 *sizeof_buf *= 2;
224c3ddb 8525 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 8526 buf = *buf_p;
c906108c
SS
8527 }
8528
6d820c5c
DJ
8529 buf[bc++] = c;
8530 csum += c;
8531 continue;
c906108c
SS
8532 }
8533 }
8534}
8535
8536/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8537 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8538 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8539 rather than timing out; this is used (in synchronous mode) to wait
8540 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8541/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8542 don't have to change all the calls to getpkt to deal with the
8543 return value, because at the moment I don't know what the right
23860348 8544 thing to do it for those. */
c906108c 8545void
6d820c5c
DJ
8546getpkt (char **buf,
8547 long *sizeof_buf,
c2d11a7d 8548 int forever)
d9fcf2fb
JM
8549{
8550 int timed_out;
8551
8552 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8553}
8554
8555
8556/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8557 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8558 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8559 rather than timing out; this is used (in synchronous mode) to wait
8560 for a target that is is executing user code to stop. If FOREVER ==
8561 0, this function is allowed to time out gracefully and return an
74531fed
PA
8562 indication of this to the caller. Otherwise return the number of
8563 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8564 enough reason to return to the caller. *IS_NOTIF is an output
8565 boolean that indicates whether *BUF holds a notification or not
8566 (a regular packet). */
74531fed 8567
3172dc30 8568static int
74531fed 8569getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8570 int expecting_notif, int *is_notif)
c906108c 8571{
2d717e4f 8572 struct remote_state *rs = get_remote_state ();
c906108c
SS
8573 int c;
8574 int tries;
8575 int timeout;
df4b58fe 8576 int val = -1;
c906108c 8577
2d717e4f
DJ
8578 /* We're reading a new response. Make sure we don't look at a
8579 previously cached response. */
8580 rs->cached_wait_status = 0;
8581
6d820c5c 8582 strcpy (*buf, "timeout");
c906108c
SS
8583
8584 if (forever)
74531fed
PA
8585 timeout = watchdog > 0 ? watchdog : -1;
8586 else if (expecting_notif)
8587 timeout = 0; /* There should already be a char in the buffer. If
8588 not, bail out. */
c906108c
SS
8589 else
8590 timeout = remote_timeout;
8591
8592#define MAX_TRIES 3
8593
74531fed
PA
8594 /* Process any number of notifications, and then return when
8595 we get a packet. */
8596 for (;;)
c906108c 8597 {
d9c43928 8598 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8599 times. */
8600 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8601 {
74531fed
PA
8602 /* This can loop forever if the remote side sends us
8603 characters continuously, but if it pauses, we'll get
8604 SERIAL_TIMEOUT from readchar because of timeout. Then
8605 we'll count that as a retry.
8606
8607 Note that even when forever is set, we will only wait
8608 forever prior to the start of a packet. After that, we
8609 expect characters to arrive at a brisk pace. They should
8610 show up within remote_timeout intervals. */
8611 do
8612 c = readchar (timeout);
8613 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8614
8615 if (c == SERIAL_TIMEOUT)
8616 {
74531fed
PA
8617 if (expecting_notif)
8618 return -1; /* Don't complain, it's normal to not get
8619 anything in this case. */
8620
23860348 8621 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8622 {
2acceee2 8623 QUIT;
78a095c3 8624 remote_unpush_target ();
598d3636
JK
8625 throw_error (TARGET_CLOSE_ERROR,
8626 _("Watchdog timeout has expired. "
8627 "Target detached."));
c906108c 8628 }
c906108c 8629 if (remote_debug)
0f71a2f6 8630 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8631 }
74531fed
PA
8632 else
8633 {
8634 /* We've found the start of a packet or notification.
8635 Now collect the data. */
8636 val = read_frame (buf, sizeof_buf);
8637 if (val >= 0)
8638 break;
8639 }
8640
c33e31fd 8641 remote_serial_write ("-", 1);
c906108c 8642 }
c906108c 8643
74531fed
PA
8644 if (tries > MAX_TRIES)
8645 {
8646 /* We have tried hard enough, and just can't receive the
8647 packet/notification. Give up. */
8648 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8649
74531fed
PA
8650 /* Skip the ack char if we're in no-ack mode. */
8651 if (!rs->noack_mode)
c33e31fd 8652 remote_serial_write ("+", 1);
74531fed
PA
8653 return -1;
8654 }
c906108c 8655
74531fed
PA
8656 /* If we got an ordinary packet, return that to our caller. */
8657 if (c == '$')
c906108c
SS
8658 {
8659 if (remote_debug)
43e526b9 8660 {
6e5abd65
PA
8661 struct cleanup *old_chain;
8662 char *str;
8663
8664 str = escape_buffer (*buf, val);
8665 old_chain = make_cleanup (xfree, str);
8666 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8667 do_cleanups (old_chain);
43e526b9 8668 }
a6f3e723
SL
8669
8670 /* Skip the ack char if we're in no-ack mode. */
8671 if (!rs->noack_mode)
c33e31fd 8672 remote_serial_write ("+", 1);
fee9eda9
YQ
8673 if (is_notif != NULL)
8674 *is_notif = 0;
0876f84a 8675 return val;
c906108c
SS
8676 }
8677
74531fed
PA
8678 /* If we got a notification, handle it, and go back to looking
8679 for a packet. */
8680 else
8681 {
8682 gdb_assert (c == '%');
8683
8684 if (remote_debug)
8685 {
6e5abd65
PA
8686 struct cleanup *old_chain;
8687 char *str;
8688
8689 str = escape_buffer (*buf, val);
8690 old_chain = make_cleanup (xfree, str);
8691 fprintf_unfiltered (gdb_stdlog,
8692 " Notification received: %s\n",
8693 str);
8694 do_cleanups (old_chain);
74531fed 8695 }
fee9eda9
YQ
8696 if (is_notif != NULL)
8697 *is_notif = 1;
c906108c 8698
5965e028 8699 handle_notification (rs->notif_state, *buf);
c906108c 8700
74531fed 8701 /* Notifications require no acknowledgement. */
a6f3e723 8702
74531fed 8703 if (expecting_notif)
fee9eda9 8704 return val;
74531fed
PA
8705 }
8706 }
8707}
8708
8709static int
8710getpkt_sane (char **buf, long *sizeof_buf, int forever)
8711{
fee9eda9 8712 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8713}
8714
8715static int
fee9eda9
YQ
8716getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8717 int *is_notif)
74531fed 8718{
fee9eda9
YQ
8719 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8720 is_notif);
c906108c 8721}
74531fed 8722
cbb8991c
DB
8723/* Check whether EVENT is a fork event for the process specified
8724 by the pid passed in DATA, and if it is, kill the fork child. */
8725
8726static int
8727kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8728 QUEUE_ITER (stop_reply_p) *iter,
8729 stop_reply_p event,
8730 void *data)
8731{
19ba03f4 8732 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
8733 int parent_pid = *(int *) param->input;
8734
8735 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8736 {
8737 struct remote_state *rs = get_remote_state ();
8738 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8739 int res;
8740
8741 res = remote_vkill (child_pid, rs);
8742 if (res != 0)
8743 error (_("Can't kill fork child process %d"), child_pid);
8744 }
8745
8746 return 1;
8747}
8748
8749/* Kill any new fork children of process PID that haven't been
8750 processed by follow_fork. */
8751
8752static void
8753kill_new_fork_children (int pid, struct remote_state *rs)
8754{
8755 struct thread_info *thread;
8756 struct notif_client *notif = &notif_client_stop;
8757 struct queue_iter_param param;
8758
8759 /* Kill the fork child threads of any threads in process PID
8760 that are stopped at a fork event. */
8761 ALL_NON_EXITED_THREADS (thread)
8762 {
8763 struct target_waitstatus *ws = &thread->pending_follow;
8764
8765 if (is_pending_fork_parent (ws, pid, thread->ptid))
8766 {
8767 struct remote_state *rs = get_remote_state ();
8768 int child_pid = ptid_get_pid (ws->value.related_pid);
8769 int res;
8770
8771 res = remote_vkill (child_pid, rs);
8772 if (res != 0)
8773 error (_("Can't kill fork child process %d"), child_pid);
8774 }
8775 }
8776
8777 /* Check for any pending fork events (not reported or processed yet)
8778 in process PID and kill those fork child threads as well. */
8779 remote_notif_get_pending_events (notif);
8780 param.input = &pid;
8781 param.output = NULL;
8782 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8783 kill_child_of_pending_fork, &param);
8784}
8785
c906108c
SS
8786\f
8787static void
7d85a9c0 8788remote_kill (struct target_ops *ops)
43ff13b4 8789{
0fdf84ca
PA
8790
8791 /* Catch errors so the user can quit from gdb even when we
23860348 8792 aren't on speaking terms with the remote system. */
492d29ea 8793 TRY
0fdf84ca
PA
8794 {
8795 putpkt ("k");
8796 }
492d29ea 8797 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
8798 {
8799 if (ex.error == TARGET_CLOSE_ERROR)
8800 {
8801 /* If we got an (EOF) error that caused the target
8802 to go away, then we're done, that's what we wanted.
8803 "k" is susceptible to cause a premature EOF, given
8804 that the remote server isn't actually required to
8805 reply to "k", and it can happen that it doesn't
8806 even get to reply ACK to the "k". */
8807 return;
8808 }
8809
8810 /* Otherwise, something went wrong. We didn't actually kill
8811 the target. Just propagate the exception, and let the
8812 user or higher layers decide what to do. */
8813 throw_exception (ex);
8814 }
492d29ea 8815 END_CATCH
43ff13b4 8816
0fdf84ca
PA
8817 /* We've killed the remote end, we get to mourn it. Since this is
8818 target remote, single-process, mourning the inferior also
8819 unpushes remote_ops. */
43ff13b4
JM
8820 target_mourn_inferior ();
8821}
8822
82f73884
PA
8823static int
8824remote_vkill (int pid, struct remote_state *rs)
8825{
4082afcc 8826 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8827 return -1;
8828
8829 /* Tell the remote target to detach. */
bba74b36 8830 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8831 putpkt (rs->buf);
8832 getpkt (&rs->buf, &rs->buf_size, 0);
8833
4082afcc
PA
8834 switch (packet_ok (rs->buf,
8835 &remote_protocol_packets[PACKET_vKill]))
8836 {
8837 case PACKET_OK:
8838 return 0;
8839 case PACKET_ERROR:
8840 return 1;
8841 case PACKET_UNKNOWN:
8842 return -1;
8843 default:
8844 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8845 }
82f73884
PA
8846}
8847
8848static void
7d85a9c0 8849extended_remote_kill (struct target_ops *ops)
82f73884
PA
8850{
8851 int res;
8852 int pid = ptid_get_pid (inferior_ptid);
8853 struct remote_state *rs = get_remote_state ();
8854
cbb8991c
DB
8855 /* If we're stopped while forking and we haven't followed yet, kill the
8856 child task. We need to do this before killing the parent task
8857 because if this is a vfork then the parent will be sleeping. */
8858 kill_new_fork_children (pid, rs);
8859
82f73884 8860 res = remote_vkill (pid, rs);
901f9912 8861 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
8862 {
8863 /* Don't try 'k' on a multi-process aware stub -- it has no way
8864 to specify the pid. */
8865
8866 putpkt ("k");
8867#if 0
8868 getpkt (&rs->buf, &rs->buf_size, 0);
8869 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8870 res = 1;
8871#else
8872 /* Don't wait for it to die. I'm not really sure it matters whether
8873 we do or not. For the existing stubs, kill is a noop. */
8874 res = 0;
8875#endif
8876 }
8877
8878 if (res != 0)
8879 error (_("Can't kill process"));
8880
82f73884
PA
8881 target_mourn_inferior ();
8882}
8883
c906108c 8884static void
20f796c9 8885remote_mourn (struct target_ops *target)
c906108c
SS
8886{
8887 unpush_target (target);
ce5ce7ed 8888
8a2492ee
PA
8889 /* remote_close takes care of doing most of the clean up. */
8890 generic_mourn_inferior ();
c906108c
SS
8891}
8892
2d717e4f 8893static void
20f796c9 8894extended_remote_mourn (struct target_ops *target)
2d717e4f
DJ
8895{
8896 struct remote_state *rs = get_remote_state ();
c906108c 8897
e24a49d8
PA
8898 /* In case we got here due to an error, but we're going to stay
8899 connected. */
8900 rs->waiting_for_stop_reply = 0;
8901
dc1981d7
PA
8902 /* If the current general thread belonged to the process we just
8903 detached from or has exited, the remote side current general
8904 thread becomes undefined. Considering a case like this:
8905
8906 - We just got here due to a detach.
8907 - The process that we're detaching from happens to immediately
8908 report a global breakpoint being hit in non-stop mode, in the
8909 same thread we had selected before.
8910 - GDB attaches to this process again.
8911 - This event happens to be the next event we handle.
8912
8913 GDB would consider that the current general thread didn't need to
8914 be set on the stub side (with Hg), since for all it knew,
8915 GENERAL_THREAD hadn't changed.
8916
8917 Notice that although in all-stop mode, the remote server always
8918 sets the current thread to the thread reporting the stop event,
8919 that doesn't happen in non-stop mode; in non-stop, the stub *must
8920 not* change the current thread when reporting a breakpoint hit,
8921 due to the decoupling of event reporting and event handling.
8922
8923 To keep things simple, we always invalidate our notion of the
8924 current thread. */
47f8a51d 8925 record_currthread (rs, minus_one_ptid);
dc1981d7 8926
2d717e4f
DJ
8927 /* Unlike "target remote", we do not want to unpush the target; then
8928 the next time the user says "run", we won't be connected. */
8929
48aa3c27
PA
8930 /* Call common code to mark the inferior as not running. */
8931 generic_mourn_inferior ();
8932
d729566a 8933 if (!have_inferiors ())
2d717e4f 8934 {
82f73884
PA
8935 if (!remote_multi_process_p (rs))
8936 {
8937 /* Check whether the target is running now - some remote stubs
8938 automatically restart after kill. */
8939 putpkt ("?");
8940 getpkt (&rs->buf, &rs->buf_size, 0);
8941
8942 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8943 {
3e43a32a
MS
8944 /* Assume that the target has been restarted. Set
8945 inferior_ptid so that bits of core GDB realizes
8946 there's something here, e.g., so that the user can
8947 say "kill" again. */
82f73884
PA
8948 inferior_ptid = magic_null_ptid;
8949 }
82f73884 8950 }
2d717e4f
DJ
8951 }
8952}
c906108c 8953
03583c20 8954static int
2bfc0540 8955extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8956{
4082afcc 8957 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8958}
8959
8960static void
8961extended_remote_disable_randomization (int val)
8962{
8963 struct remote_state *rs = get_remote_state ();
8964 char *reply;
8965
bba74b36
YQ
8966 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8967 val);
03583c20
UW
8968 putpkt (rs->buf);
8969 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8970 if (*reply == '\0')
8971 error (_("Target does not support QDisableRandomization."));
8972 if (strcmp (reply, "OK") != 0)
8973 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8974}
8975
2d717e4f
DJ
8976static int
8977extended_remote_run (char *args)
8978{
8979 struct remote_state *rs = get_remote_state ();
2d717e4f 8980 int len;
94585166 8981 const char *remote_exec_file = get_remote_exec_file ();
c906108c 8982
2d717e4f
DJ
8983 /* If the user has disabled vRun support, or we have detected that
8984 support is not available, do not try it. */
4082afcc 8985 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8986 return -1;
424163ea 8987
2d717e4f
DJ
8988 strcpy (rs->buf, "vRun;");
8989 len = strlen (rs->buf);
c906108c 8990
2d717e4f
DJ
8991 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8992 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8993 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8994 strlen (remote_exec_file));
2d717e4f 8995
d1a41061 8996 gdb_assert (args != NULL);
2d717e4f
DJ
8997 if (*args)
8998 {
8999 struct cleanup *back_to;
9000 int i;
9001 char **argv;
9002
d1a41061 9003 argv = gdb_buildargv (args);
6e366df1 9004 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
9005 for (i = 0; argv[i] != NULL; i++)
9006 {
9007 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9008 error (_("Argument list too long for run packet"));
9009 rs->buf[len++] = ';';
9f1b45b0
TT
9010 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9011 strlen (argv[i]));
2d717e4f
DJ
9012 }
9013 do_cleanups (back_to);
9014 }
9015
9016 rs->buf[len++] = '\0';
9017
9018 putpkt (rs->buf);
9019 getpkt (&rs->buf, &rs->buf_size, 0);
9020
4082afcc 9021 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9022 {
4082afcc 9023 case PACKET_OK:
3405876a 9024 /* We have a wait response. All is well. */
2d717e4f 9025 return 0;
4082afcc
PA
9026 case PACKET_UNKNOWN:
9027 return -1;
9028 case PACKET_ERROR:
2d717e4f
DJ
9029 if (remote_exec_file[0] == '\0')
9030 error (_("Running the default executable on the remote target failed; "
9031 "try \"set remote exec-file\"?"));
9032 else
9033 error (_("Running \"%s\" on the remote target failed"),
9034 remote_exec_file);
4082afcc
PA
9035 default:
9036 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9037 }
c906108c
SS
9038}
9039
2d717e4f
DJ
9040/* In the extended protocol we want to be able to do things like
9041 "run" and have them basically work as expected. So we need
9042 a special create_inferior function. We support changing the
9043 executable file and the command line arguments, but not the
9044 environment. */
9045
43ff13b4 9046static void
77a19445
TT
9047extended_remote_create_inferior (struct target_ops *ops,
9048 char *exec_file, char *args,
9049 char **env, int from_tty)
43ff13b4 9050{
3405876a
PA
9051 int run_worked;
9052 char *stop_reply;
9053 struct remote_state *rs = get_remote_state ();
94585166 9054 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9055
43ff13b4 9056 /* If running asynchronously, register the target file descriptor
23860348 9057 with the event loop. */
75c99385 9058 if (target_can_async_p ())
6a3753b3 9059 target_async (1);
43ff13b4 9060
03583c20 9061 /* Disable address space randomization if requested (and supported). */
2bfc0540 9062 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9063 extended_remote_disable_randomization (disable_randomization);
9064
43ff13b4 9065 /* Now restart the remote server. */
3405876a
PA
9066 run_worked = extended_remote_run (args) != -1;
9067 if (!run_worked)
2d717e4f
DJ
9068 {
9069 /* vRun was not supported. Fail if we need it to do what the
9070 user requested. */
9071 if (remote_exec_file[0])
9072 error (_("Remote target does not support \"set remote exec-file\""));
9073 if (args[0])
9074 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9075
2d717e4f
DJ
9076 /* Fall back to "R". */
9077 extended_remote_restart ();
9078 }
424163ea 9079
6c95b8df
PA
9080 if (!have_inferiors ())
9081 {
9082 /* Clean up from the last time we ran, before we mark the target
9083 running again. This will mark breakpoints uninserted, and
9084 get_offsets may insert breakpoints. */
9085 init_thread_list ();
9086 init_wait_for_inferior ();
9087 }
45280a52 9088
3405876a
PA
9089 /* vRun's success return is a stop reply. */
9090 stop_reply = run_worked ? rs->buf : NULL;
9091 add_current_inferior_and_thread (stop_reply);
c0a2216e 9092
2d717e4f
DJ
9093 /* Get updated offsets, if the stub uses qOffsets. */
9094 get_offsets ();
2d717e4f 9095}
c906108c 9096\f
c5aa993b 9097
b775012e
LM
9098/* Given a location's target info BP_TGT and the packet buffer BUF, output
9099 the list of conditions (in agent expression bytecode format), if any, the
9100 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9101 started from BUF and ended at BUF_END. */
b775012e
LM
9102
9103static int
9104remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9105 struct bp_target_info *bp_tgt, char *buf,
9106 char *buf_end)
b775012e
LM
9107{
9108 struct agent_expr *aexpr = NULL;
9109 int i, ix;
9110 char *pkt;
9111 char *buf_start = buf;
9112
9113 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9114 return 0;
9115
9116 buf += strlen (buf);
bba74b36 9117 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9118 buf++;
9119
9120 /* Send conditions to the target and free the vector. */
9121 for (ix = 0;
9122 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9123 ix++)
9124 {
bba74b36 9125 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
9126 buf += strlen (buf);
9127 for (i = 0; i < aexpr->len; ++i)
9128 buf = pack_hex_byte (buf, aexpr->buf[i]);
9129 *buf = '\0';
9130 }
b775012e
LM
9131 return 0;
9132}
9133
d3ce09f5
SS
9134static void
9135remote_add_target_side_commands (struct gdbarch *gdbarch,
9136 struct bp_target_info *bp_tgt, char *buf)
9137{
9138 struct agent_expr *aexpr = NULL;
9139 int i, ix;
9140
9141 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9142 return;
9143
9144 buf += strlen (buf);
9145
9146 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9147 buf += strlen (buf);
9148
9149 /* Concatenate all the agent expressions that are commands into the
9150 cmds parameter. */
9151 for (ix = 0;
9152 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9153 ix++)
9154 {
9155 sprintf (buf, "X%x,", aexpr->len);
9156 buf += strlen (buf);
9157 for (i = 0; i < aexpr->len; ++i)
9158 buf = pack_hex_byte (buf, aexpr->buf[i]);
9159 *buf = '\0';
9160 }
d3ce09f5
SS
9161}
9162
8181d85f
DJ
9163/* Insert a breakpoint. On targets that have software breakpoint
9164 support, we ask the remote target to do the work; on targets
9165 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9166
9167static int
3db08215
MM
9168remote_insert_breakpoint (struct target_ops *ops,
9169 struct gdbarch *gdbarch,
a6d9a66e 9170 struct bp_target_info *bp_tgt)
c906108c 9171{
d471ea57
AC
9172 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9173 If it succeeds, then set the support to PACKET_ENABLE. If it
9174 fails, and the user has explicitly requested the Z support then
23860348 9175 report an error, otherwise, mark it disabled and go on. */
802188a7 9176
4082afcc 9177 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9178 {
0d5ed153 9179 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9180 struct remote_state *rs;
bba74b36 9181 char *p, *endbuf;
7c0f6dcc 9182 int bpsize;
b775012e 9183 struct condition_list *cond = NULL;
4fff2411 9184
28439a30
PA
9185 /* Make sure the remote is pointing at the right process, if
9186 necessary. */
9187 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9188 set_general_process ();
9189
a1dcb23a 9190 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
9191
9192 rs = get_remote_state ();
9193 p = rs->buf;
bba74b36 9194 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9195
96baa820
JM
9196 *(p++) = 'Z';
9197 *(p++) = '0';
9198 *(p++) = ',';
7c0f6dcc 9199 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9200 p += hexnumstr (p, addr);
bba74b36 9201 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 9202
efcc2da7 9203 if (remote_supports_cond_breakpoints (ops))
bba74b36 9204 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9205
78eff0ec 9206 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9207 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9208
6d820c5c
DJ
9209 putpkt (rs->buf);
9210 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9211
6d820c5c 9212 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9213 {
d471ea57
AC
9214 case PACKET_ERROR:
9215 return -1;
9216 case PACKET_OK:
7c0f6dcc
JL
9217 bp_tgt->placed_address = addr;
9218 bp_tgt->placed_size = bpsize;
d471ea57
AC
9219 return 0;
9220 case PACKET_UNKNOWN:
9221 break;
96baa820
JM
9222 }
9223 }
c906108c 9224
0000e5cc
PA
9225 /* If this breakpoint has target-side commands but this stub doesn't
9226 support Z0 packets, throw error. */
9227 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9228 throw_error (NOT_SUPPORTED_ERROR, _("\
9229Target doesn't support breakpoints that have target side commands."));
9230
3db08215 9231 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9232}
9233
9234static int
3db08215
MM
9235remote_remove_breakpoint (struct target_ops *ops,
9236 struct gdbarch *gdbarch,
a6d9a66e 9237 struct bp_target_info *bp_tgt)
c906108c 9238{
8181d85f 9239 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9240 struct remote_state *rs = get_remote_state ();
96baa820 9241
4082afcc 9242 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9243 {
6d820c5c 9244 char *p = rs->buf;
bba74b36 9245 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9246
28439a30
PA
9247 /* Make sure the remote is pointing at the right process, if
9248 necessary. */
9249 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9250 set_general_process ();
9251
96baa820
JM
9252 *(p++) = 'z';
9253 *(p++) = '0';
9254 *(p++) = ',';
9255
8181d85f
DJ
9256 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9257 p += hexnumstr (p, addr);
bba74b36 9258 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9259
6d820c5c
DJ
9260 putpkt (rs->buf);
9261 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9262
6d820c5c 9263 return (rs->buf[0] == 'E');
96baa820
JM
9264 }
9265
3db08215 9266 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9267}
9268
f486487f 9269static enum Z_packet_type
d471ea57
AC
9270watchpoint_to_Z_packet (int type)
9271{
9272 switch (type)
9273 {
9274 case hw_write:
bb858e6a 9275 return Z_PACKET_WRITE_WP;
d471ea57
AC
9276 break;
9277 case hw_read:
bb858e6a 9278 return Z_PACKET_READ_WP;
d471ea57
AC
9279 break;
9280 case hw_access:
bb858e6a 9281 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9282 break;
9283 default:
8e65ff28 9284 internal_error (__FILE__, __LINE__,
e2e0b3e5 9285 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9286 }
9287}
9288
3c3bea1c 9289static int
f486487f
SM
9290remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9291 enum target_hw_bp_type type, struct expression *cond)
96baa820 9292{
d01949b6 9293 struct remote_state *rs = get_remote_state ();
bba74b36 9294 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9295 char *p;
d471ea57 9296 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9297
4082afcc 9298 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9299 return 1;
802188a7 9300
28439a30
PA
9301 /* Make sure the remote is pointing at the right process, if
9302 necessary. */
9303 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9304 set_general_process ();
9305
bba74b36 9306 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9307 p = strchr (rs->buf, '\0');
96baa820
JM
9308 addr = remote_address_masked (addr);
9309 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9310 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9311
6d820c5c
DJ
9312 putpkt (rs->buf);
9313 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9314
6d820c5c 9315 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9316 {
9317 case PACKET_ERROR:
d471ea57 9318 return -1;
85d721b8
PA
9319 case PACKET_UNKNOWN:
9320 return 1;
d471ea57
AC
9321 case PACKET_OK:
9322 return 0;
9323 }
8e65ff28 9324 internal_error (__FILE__, __LINE__,
e2e0b3e5 9325 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9326}
9327
283002cf
MR
9328static int
9329remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9330 CORE_ADDR start, int length)
9331{
9332 CORE_ADDR diff = remote_address_masked (addr - start);
9333
9334 return diff < length;
9335}
9336
d471ea57 9337
3c3bea1c 9338static int
f486487f
SM
9339remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9340 enum target_hw_bp_type type, struct expression *cond)
96baa820 9341{
d01949b6 9342 struct remote_state *rs = get_remote_state ();
bba74b36 9343 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9344 char *p;
d471ea57
AC
9345 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9346
4082afcc 9347 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9348 return -1;
802188a7 9349
28439a30
PA
9350 /* Make sure the remote is pointing at the right process, if
9351 necessary. */
9352 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9353 set_general_process ();
9354
bba74b36 9355 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9356 p = strchr (rs->buf, '\0');
96baa820
JM
9357 addr = remote_address_masked (addr);
9358 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9359 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9360 putpkt (rs->buf);
9361 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9362
6d820c5c 9363 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9364 {
9365 case PACKET_ERROR:
9366 case PACKET_UNKNOWN:
9367 return -1;
9368 case PACKET_OK:
9369 return 0;
9370 }
8e65ff28 9371 internal_error (__FILE__, __LINE__,
e2e0b3e5 9372 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9373}
9374
3c3bea1c 9375
501eef12 9376int remote_hw_watchpoint_limit = -1;
480a3f21 9377int remote_hw_watchpoint_length_limit = -1;
501eef12 9378int remote_hw_breakpoint_limit = -1;
d471ea57 9379
480a3f21 9380static int
31568a15
TT
9381remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9382 CORE_ADDR addr, int len)
480a3f21
PW
9383{
9384 if (remote_hw_watchpoint_length_limit == 0)
9385 return 0;
9386 else if (remote_hw_watchpoint_length_limit < 0)
9387 return 1;
9388 else if (len <= remote_hw_watchpoint_length_limit)
9389 return 1;
9390 else
9391 return 0;
9392}
9393
b9362cc7 9394static int
5461485a 9395remote_check_watch_resources (struct target_ops *self,
f486487f 9396 enum bptype type, int cnt, int ot)
96baa820 9397{
3c3bea1c
GS
9398 if (type == bp_hardware_breakpoint)
9399 {
9400 if (remote_hw_breakpoint_limit == 0)
9401 return 0;
501eef12
AC
9402 else if (remote_hw_breakpoint_limit < 0)
9403 return 1;
3c3bea1c
GS
9404 else if (cnt <= remote_hw_breakpoint_limit)
9405 return 1;
9406 }
9407 else
9408 {
9409 if (remote_hw_watchpoint_limit == 0)
9410 return 0;
501eef12
AC
9411 else if (remote_hw_watchpoint_limit < 0)
9412 return 1;
3c3bea1c
GS
9413 else if (ot)
9414 return -1;
9415 else if (cnt <= remote_hw_watchpoint_limit)
9416 return 1;
9417 }
9418 return -1;
9419}
9420
f7e6eed5
PA
9421/* The to_stopped_by_sw_breakpoint method of target remote. */
9422
9423static int
9424remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9425{
799a2abe 9426 struct thread_info *thread = inferior_thread ();
f7e6eed5 9427
799a2abe
PA
9428 return (thread->priv != NULL
9429 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9430}
9431
9432/* The to_supports_stopped_by_sw_breakpoint method of target
9433 remote. */
9434
9435static int
9436remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9437{
9438 struct remote_state *rs = get_remote_state ();
9439
9440 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9441}
9442
9443/* The to_stopped_by_hw_breakpoint method of target remote. */
9444
9445static int
9446remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9447{
799a2abe 9448 struct thread_info *thread = inferior_thread ();
f7e6eed5 9449
799a2abe
PA
9450 return (thread->priv != NULL
9451 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9452}
9453
9454/* The to_supports_stopped_by_hw_breakpoint method of target
9455 remote. */
9456
9457static int
9458remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9459{
9460 struct remote_state *rs = get_remote_state ();
9461
9462 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9463}
9464
b9362cc7 9465static int
6a109b6b 9466remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9467{
799a2abe 9468 struct thread_info *thread = inferior_thread ();
ee154bee 9469
799a2abe
PA
9470 return (thread->priv != NULL
9471 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9472}
9473
4aa7a7f5
JJ
9474static int
9475remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9476{
799a2abe 9477 struct thread_info *thread = inferior_thread ();
a744cf53 9478
799a2abe
PA
9479 if (thread->priv != NULL
9480 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9481 {
799a2abe
PA
9482 *addr_p = thread->priv->watch_data_address;
9483 return 1;
4aa7a7f5
JJ
9484 }
9485
799a2abe 9486 return 0;
3c3bea1c
GS
9487}
9488
9489
9490static int
23a26771 9491remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9492 struct bp_target_info *bp_tgt)
3c3bea1c 9493{
0d5ed153 9494 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9495 struct remote_state *rs;
bba74b36 9496 char *p, *endbuf;
dd61ec5c 9497 char *message;
0d5ed153 9498 int bpsize;
802188a7 9499
c8189ed1 9500 /* The length field should be set to the size of a breakpoint
8181d85f 9501 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9502
0d5ed153 9503 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9504
4082afcc 9505 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9506 return -1;
2bc416ba 9507
28439a30
PA
9508 /* Make sure the remote is pointing at the right process, if
9509 necessary. */
9510 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9511 set_general_process ();
9512
4fff2411
JZ
9513 rs = get_remote_state ();
9514 p = rs->buf;
bba74b36 9515 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9516
96baa820
JM
9517 *(p++) = 'Z';
9518 *(p++) = '1';
9519 *(p++) = ',';
802188a7 9520
0d5ed153 9521 addr = remote_address_masked (addr);
96baa820 9522 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9523 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9524
efcc2da7 9525 if (remote_supports_cond_breakpoints (self))
bba74b36 9526 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9527
78eff0ec 9528 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9529 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9530
6d820c5c
DJ
9531 putpkt (rs->buf);
9532 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9533
6d820c5c 9534 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9535 {
9536 case PACKET_ERROR:
dd61ec5c
MW
9537 if (rs->buf[1] == '.')
9538 {
9539 message = strchr (rs->buf + 2, '.');
9540 if (message)
0316657e 9541 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9542 }
9543 return -1;
d471ea57
AC
9544 case PACKET_UNKNOWN:
9545 return -1;
9546 case PACKET_OK:
0d5ed153
MR
9547 bp_tgt->placed_address = addr;
9548 bp_tgt->placed_size = bpsize;
d471ea57
AC
9549 return 0;
9550 }
8e65ff28 9551 internal_error (__FILE__, __LINE__,
e2e0b3e5 9552 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9553}
9554
d471ea57 9555
802188a7 9556static int
a64dc96c 9557remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9558 struct bp_target_info *bp_tgt)
96baa820 9559{
8181d85f 9560 CORE_ADDR addr;
d01949b6 9561 struct remote_state *rs = get_remote_state ();
6d820c5c 9562 char *p = rs->buf;
bba74b36 9563 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9564
4082afcc 9565 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9566 return -1;
802188a7 9567
28439a30
PA
9568 /* Make sure the remote is pointing at the right process, if
9569 necessary. */
9570 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9571 set_general_process ();
9572
96baa820
JM
9573 *(p++) = 'z';
9574 *(p++) = '1';
9575 *(p++) = ',';
802188a7 9576
8181d85f 9577 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9578 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9579 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9580
6d820c5c
DJ
9581 putpkt (rs->buf);
9582 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9583
6d820c5c 9584 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9585 {
9586 case PACKET_ERROR:
9587 case PACKET_UNKNOWN:
9588 return -1;
9589 case PACKET_OK:
9590 return 0;
9591 }
8e65ff28 9592 internal_error (__FILE__, __LINE__,
e2e0b3e5 9593 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9594}
96baa820 9595
4a5e7a5b
PA
9596/* Verify memory using the "qCRC:" request. */
9597
9598static int
9599remote_verify_memory (struct target_ops *ops,
9600 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9601{
9602 struct remote_state *rs = get_remote_state ();
9603 unsigned long host_crc, target_crc;
9604 char *tmp;
9605
936d2992
PA
9606 /* It doesn't make sense to use qCRC if the remote target is
9607 connected but not running. */
9608 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9609 {
9610 enum packet_result result;
28439a30 9611
936d2992
PA
9612 /* Make sure the remote is pointing at the right process. */
9613 set_general_process ();
4a5e7a5b 9614
936d2992
PA
9615 /* FIXME: assumes lma can fit into long. */
9616 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9617 (long) lma, (long) size);
9618 putpkt (rs->buf);
4a5e7a5b 9619
936d2992
PA
9620 /* Be clever; compute the host_crc before waiting for target
9621 reply. */
9622 host_crc = xcrc32 (data, size, 0xffffffff);
9623
9624 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9625
936d2992
PA
9626 result = packet_ok (rs->buf,
9627 &remote_protocol_packets[PACKET_qCRC]);
9628 if (result == PACKET_ERROR)
9629 return -1;
9630 else if (result == PACKET_OK)
9631 {
9632 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9633 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9634
936d2992
PA
9635 return (host_crc == target_crc);
9636 }
9637 }
4a5e7a5b 9638
936d2992 9639 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9640}
9641
c906108c
SS
9642/* compare-sections command
9643
9644 With no arguments, compares each loadable section in the exec bfd
9645 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9646 Useful for verifying the image on the target against the exec file. */
e514a9d6 9647
c906108c 9648static void
fba45db2 9649compare_sections_command (char *args, int from_tty)
c906108c
SS
9650{
9651 asection *s;
c906108c 9652 struct cleanup *old_chain;
948f8e3d 9653 gdb_byte *sectdata;
ce359b09 9654 const char *sectname;
c906108c
SS
9655 bfd_size_type size;
9656 bfd_vma lma;
9657 int matched = 0;
9658 int mismatched = 0;
4a5e7a5b 9659 int res;
95cf3b38 9660 int read_only = 0;
c906108c
SS
9661
9662 if (!exec_bfd)
8a3fe4f8 9663 error (_("command cannot be used without an exec file"));
c906108c 9664
28439a30
PA
9665 /* Make sure the remote is pointing at the right process. */
9666 set_general_process ();
9667
95cf3b38
DT
9668 if (args != NULL && strcmp (args, "-r") == 0)
9669 {
9670 read_only = 1;
9671 args = NULL;
9672 }
9673
c5aa993b 9674 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9675 {
9676 if (!(s->flags & SEC_LOAD))
0df8b418 9677 continue; /* Skip non-loadable section. */
c906108c 9678
95cf3b38
DT
9679 if (read_only && (s->flags & SEC_READONLY) == 0)
9680 continue; /* Skip writeable sections */
9681
2c500098 9682 size = bfd_get_section_size (s);
c906108c 9683 if (size == 0)
0df8b418 9684 continue; /* Skip zero-length section. */
c906108c 9685
ce359b09 9686 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9687 if (args && strcmp (args, sectname) != 0)
0df8b418 9688 continue; /* Not the section selected by user. */
c906108c 9689
0df8b418 9690 matched = 1; /* Do this section. */
c906108c 9691 lma = s->lma;
c906108c 9692
224c3ddb 9693 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9694 old_chain = make_cleanup (xfree, sectdata);
c906108c 9695 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9696
4a5e7a5b
PA
9697 res = target_verify_memory (sectdata, lma, size);
9698
9699 if (res == -1)
5af949e3 9700 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9701 paddress (target_gdbarch (), lma),
9702 paddress (target_gdbarch (), lma + size));
c906108c 9703
5af949e3 9704 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9705 paddress (target_gdbarch (), lma),
9706 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9707 if (res)
c906108c
SS
9708 printf_filtered ("matched.\n");
9709 else
c5aa993b
JM
9710 {
9711 printf_filtered ("MIS-MATCHED!\n");
9712 mismatched++;
9713 }
c906108c
SS
9714
9715 do_cleanups (old_chain);
9716 }
9717 if (mismatched > 0)
936d2992 9718 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9719the loaded file\n"));
c906108c 9720 if (args && !matched)
a3f17187 9721 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9722}
9723
0e7f50da
UW
9724/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9725 into remote target. The number of bytes written to the remote
9726 target is returned, or -1 for error. */
9727
9b409511 9728static enum target_xfer_status
0e7f50da
UW
9729remote_write_qxfer (struct target_ops *ops, const char *object_name,
9730 const char *annex, const gdb_byte *writebuf,
9b409511 9731 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9732 struct packet_config *packet)
9733{
9734 int i, buf_len;
9735 ULONGEST n;
0e7f50da
UW
9736 struct remote_state *rs = get_remote_state ();
9737 int max_size = get_memory_write_packet_size ();
9738
9739 if (packet->support == PACKET_DISABLE)
2ed4b548 9740 return TARGET_XFER_E_IO;
0e7f50da
UW
9741
9742 /* Insert header. */
9743 i = snprintf (rs->buf, max_size,
9744 "qXfer:%s:write:%s:%s:",
9745 object_name, annex ? annex : "",
9746 phex_nz (offset, sizeof offset));
9747 max_size -= (i + 1);
9748
9749 /* Escape as much data as fits into rs->buf. */
9750 buf_len = remote_escape_output
124e13d9 9751 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9752
9753 if (putpkt_binary (rs->buf, i + buf_len) < 0
9754 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9755 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9756 return TARGET_XFER_E_IO;
0e7f50da
UW
9757
9758 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9759
9760 *xfered_len = n;
9761 return TARGET_XFER_OK;
0e7f50da
UW
9762}
9763
0876f84a
DJ
9764/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9765 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9766 number of bytes read is returned, or 0 for EOF, or -1 for error.
9767 The number of bytes read may be less than LEN without indicating an
9768 EOF. PACKET is checked and updated to indicate whether the remote
9769 target supports this object. */
9770
9b409511 9771static enum target_xfer_status
0876f84a
DJ
9772remote_read_qxfer (struct target_ops *ops, const char *object_name,
9773 const char *annex,
9774 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9775 ULONGEST *xfered_len,
0876f84a
DJ
9776 struct packet_config *packet)
9777{
0876f84a 9778 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9779 LONGEST i, n, packet_len;
9780
9781 if (packet->support == PACKET_DISABLE)
2ed4b548 9782 return TARGET_XFER_E_IO;
0876f84a
DJ
9783
9784 /* Check whether we've cached an end-of-object packet that matches
9785 this request. */
8e88304f 9786 if (rs->finished_object)
0876f84a 9787 {
8e88304f
TT
9788 if (strcmp (object_name, rs->finished_object) == 0
9789 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9790 && offset == rs->finished_offset)
9b409511
YQ
9791 return TARGET_XFER_EOF;
9792
0876f84a
DJ
9793
9794 /* Otherwise, we're now reading something different. Discard
9795 the cache. */
8e88304f
TT
9796 xfree (rs->finished_object);
9797 xfree (rs->finished_annex);
9798 rs->finished_object = NULL;
9799 rs->finished_annex = NULL;
0876f84a
DJ
9800 }
9801
9802 /* Request only enough to fit in a single packet. The actual data
9803 may not, since we don't know how much of it will need to be escaped;
9804 the target is free to respond with slightly less data. We subtract
9805 five to account for the response type and the protocol frame. */
9806 n = min (get_remote_packet_size () - 5, len);
9807 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9808 object_name, annex ? annex : "",
9809 phex_nz (offset, sizeof offset),
9810 phex_nz (n, sizeof n));
9811 i = putpkt (rs->buf);
9812 if (i < 0)
2ed4b548 9813 return TARGET_XFER_E_IO;
0876f84a
DJ
9814
9815 rs->buf[0] = '\0';
9816 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9817 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9818 return TARGET_XFER_E_IO;
0876f84a
DJ
9819
9820 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9821 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9822
9823 /* 'm' means there is (or at least might be) more data after this
9824 batch. That does not make sense unless there's at least one byte
9825 of data in this reply. */
9826 if (rs->buf[0] == 'm' && packet_len == 1)
9827 error (_("Remote qXfer reply contained no data."));
9828
9829 /* Got some data. */
bc20a4af
PA
9830 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9831 packet_len - 1, readbuf, n);
0876f84a
DJ
9832
9833 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9834 or possibly empty. If we have the final block of a non-empty
9835 object, record this fact to bypass a subsequent partial read. */
9836 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9837 {
8e88304f
TT
9838 rs->finished_object = xstrdup (object_name);
9839 rs->finished_annex = xstrdup (annex ? annex : "");
9840 rs->finished_offset = offset + i;
0876f84a
DJ
9841 }
9842
9b409511
YQ
9843 if (i == 0)
9844 return TARGET_XFER_EOF;
9845 else
9846 {
9847 *xfered_len = i;
9848 return TARGET_XFER_OK;
9849 }
0876f84a
DJ
9850}
9851
9b409511 9852static enum target_xfer_status
4b8a223f 9853remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9854 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9855 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9856 ULONGEST *xfered_len)
c906108c 9857{
82f73884 9858 struct remote_state *rs;
c906108c 9859 int i;
6d820c5c 9860 char *p2;
1e3ff5ad 9861 char query_type;
124e13d9 9862 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9863
e6e4e701 9864 set_remote_traceframe ();
82f73884
PA
9865 set_general_thread (inferior_ptid);
9866
9867 rs = get_remote_state ();
9868
b2182ed2 9869 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9870 if (object == TARGET_OBJECT_MEMORY)
9871 {
2d717e4f
DJ
9872 /* If the remote target is connected but not running, we should
9873 pass this request down to a lower stratum (e.g. the executable
9874 file). */
9875 if (!target_has_execution)
9b409511 9876 return TARGET_XFER_EOF;
2d717e4f 9877
21e3b9b9 9878 if (writebuf != NULL)
124e13d9
SM
9879 return remote_write_bytes (offset, writebuf, len, unit_size,
9880 xfered_len);
21e3b9b9 9881 else
124e13d9
SM
9882 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9883 xfered_len);
21e3b9b9
DJ
9884 }
9885
0df8b418 9886 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9887 if (object == TARGET_OBJECT_SPU)
9888 {
9889 if (readbuf)
9890 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9891 xfered_len, &remote_protocol_packets
9892 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9893 else
9894 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9895 xfered_len, &remote_protocol_packets
9896 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9897 }
9898
4aa995e1
PA
9899 /* Handle extra signal info using qxfer packets. */
9900 if (object == TARGET_OBJECT_SIGNAL_INFO)
9901 {
9902 if (readbuf)
9903 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 9904 xfered_len, &remote_protocol_packets
4aa995e1
PA
9905 [PACKET_qXfer_siginfo_read]);
9906 else
3e43a32a 9907 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 9908 writebuf, offset, len, xfered_len,
4aa995e1
PA
9909 &remote_protocol_packets
9910 [PACKET_qXfer_siginfo_write]);
9911 }
9912
0fb4aa4b
PA
9913 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9914 {
9915 if (readbuf)
3e43a32a 9916 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 9917 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
9918 &remote_protocol_packets
9919 [PACKET_qXfer_statictrace_read]);
9920 else
2ed4b548 9921 return TARGET_XFER_E_IO;
0fb4aa4b
PA
9922 }
9923
a76d924d
DJ
9924 /* Only handle flash writes. */
9925 if (writebuf != NULL)
9926 {
9927 LONGEST xfered;
9928
9929 switch (object)
9930 {
9931 case TARGET_OBJECT_FLASH:
9b409511
YQ
9932 return remote_flash_write (ops, offset, len, xfered_len,
9933 writebuf);
a76d924d
DJ
9934
9935 default:
2ed4b548 9936 return TARGET_XFER_E_IO;
a76d924d
DJ
9937 }
9938 }
4b8a223f 9939
1e3ff5ad
AC
9940 /* Map pre-existing objects onto letters. DO NOT do this for new
9941 objects!!! Instead specify new query packets. */
9942 switch (object)
c906108c 9943 {
1e3ff5ad
AC
9944 case TARGET_OBJECT_AVR:
9945 query_type = 'R';
9946 break;
802188a7
RM
9947
9948 case TARGET_OBJECT_AUXV:
0876f84a
DJ
9949 gdb_assert (annex == NULL);
9950 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9951 xfered_len,
0876f84a 9952 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9953
23181151
DJ
9954 case TARGET_OBJECT_AVAILABLE_FEATURES:
9955 return remote_read_qxfer
9b409511 9956 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9957 &remote_protocol_packets[PACKET_qXfer_features]);
9958
cfa9d6d9
DJ
9959 case TARGET_OBJECT_LIBRARIES:
9960 return remote_read_qxfer
9b409511 9961 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9962 &remote_protocol_packets[PACKET_qXfer_libraries]);
9963
2268b414
JK
9964 case TARGET_OBJECT_LIBRARIES_SVR4:
9965 return remote_read_qxfer
9b409511 9966 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9967 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9968
fd79ecee
DJ
9969 case TARGET_OBJECT_MEMORY_MAP:
9970 gdb_assert (annex == NULL);
9971 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9972 xfered_len,
fd79ecee
DJ
9973 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9974
07e059b5
VP
9975 case TARGET_OBJECT_OSDATA:
9976 /* Should only get here if we're connected. */
5d93a237 9977 gdb_assert (rs->remote_desc);
07e059b5 9978 return remote_read_qxfer
9b409511 9979 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9980 &remote_protocol_packets[PACKET_qXfer_osdata]);
9981
dc146f7c
VP
9982 case TARGET_OBJECT_THREADS:
9983 gdb_assert (annex == NULL);
9984 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9985 xfered_len,
dc146f7c
VP
9986 &remote_protocol_packets[PACKET_qXfer_threads]);
9987
b3b9301e
PA
9988 case TARGET_OBJECT_TRACEFRAME_INFO:
9989 gdb_assert (annex == NULL);
9990 return remote_read_qxfer
9b409511 9991 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9992 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9993
9994 case TARGET_OBJECT_FDPIC:
9995 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9996 xfered_len,
78d85199 9997 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9998
9999 case TARGET_OBJECT_OPENVMS_UIB:
10000 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10001 xfered_len,
169081d0
TG
10002 &remote_protocol_packets[PACKET_qXfer_uib]);
10003
9accd112
MM
10004 case TARGET_OBJECT_BTRACE:
10005 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10006 xfered_len,
9accd112
MM
10007 &remote_protocol_packets[PACKET_qXfer_btrace]);
10008
f4abbc16
MM
10009 case TARGET_OBJECT_BTRACE_CONF:
10010 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10011 len, xfered_len,
10012 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10013
c78fa86a
GB
10014 case TARGET_OBJECT_EXEC_FILE:
10015 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10016 len, xfered_len,
10017 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10018
1e3ff5ad 10019 default:
2ed4b548 10020 return TARGET_XFER_E_IO;
c906108c
SS
10021 }
10022
0df8b418 10023 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10024 large enough let the caller deal with it. */
ea9c271d 10025 if (len < get_remote_packet_size ())
2ed4b548 10026 return TARGET_XFER_E_IO;
ea9c271d 10027 len = get_remote_packet_size ();
1e3ff5ad 10028
23860348 10029 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10030 if (!rs->remote_desc)
8a3fe4f8 10031 error (_("remote query is only available after target open"));
c906108c 10032
1e3ff5ad 10033 gdb_assert (annex != NULL);
4b8a223f 10034 gdb_assert (readbuf != NULL);
c906108c 10035
6d820c5c 10036 p2 = rs->buf;
c906108c
SS
10037 *p2++ = 'q';
10038 *p2++ = query_type;
10039
23860348
MS
10040 /* We used one buffer char for the remote protocol q command and
10041 another for the query type. As the remote protocol encapsulation
10042 uses 4 chars plus one extra in case we are debugging
10043 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10044 string. */
c906108c 10045 i = 0;
ea9c271d 10046 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10047 {
1e3ff5ad
AC
10048 /* Bad caller may have sent forbidden characters. */
10049 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10050 *p2++ = annex[i];
c906108c
SS
10051 i++;
10052 }
1e3ff5ad
AC
10053 *p2 = '\0';
10054 gdb_assert (annex[i] == '\0');
c906108c 10055
6d820c5c 10056 i = putpkt (rs->buf);
c5aa993b 10057 if (i < 0)
2ed4b548 10058 return TARGET_XFER_E_IO;
c906108c 10059
6d820c5c
DJ
10060 getpkt (&rs->buf, &rs->buf_size, 0);
10061 strcpy ((char *) readbuf, rs->buf);
c906108c 10062
9b409511
YQ
10063 *xfered_len = strlen ((char *) readbuf);
10064 return TARGET_XFER_OK;
c906108c
SS
10065}
10066
08388c79
DE
10067static int
10068remote_search_memory (struct target_ops* ops,
10069 CORE_ADDR start_addr, ULONGEST search_space_len,
10070 const gdb_byte *pattern, ULONGEST pattern_len,
10071 CORE_ADDR *found_addrp)
10072{
f5656ead 10073 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10074 struct remote_state *rs = get_remote_state ();
10075 int max_size = get_memory_write_packet_size ();
10076 struct packet_config *packet =
10077 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10078 /* Number of packet bytes used to encode the pattern;
10079 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10080 int escaped_pattern_len;
0df8b418 10081 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10082 int used_pattern_len;
10083 int i;
10084 int found;
10085 ULONGEST found_addr;
10086
10087 /* Don't go to the target if we don't have to.
10088 This is done before checking packet->support to avoid the possibility that
10089 a success for this edge case means the facility works in general. */
10090 if (pattern_len > search_space_len)
10091 return 0;
10092 if (pattern_len == 0)
10093 {
10094 *found_addrp = start_addr;
10095 return 1;
10096 }
10097
10098 /* If we already know the packet isn't supported, fall back to the simple
10099 way of searching memory. */
10100
4082afcc 10101 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10102 {
10103 /* Target doesn't provided special support, fall back and use the
10104 standard support (copy memory and do the search here). */
10105 return simple_search_memory (ops, start_addr, search_space_len,
10106 pattern, pattern_len, found_addrp);
10107 }
10108
28439a30
PA
10109 /* Make sure the remote is pointing at the right process. */
10110 set_general_process ();
10111
08388c79
DE
10112 /* Insert header. */
10113 i = snprintf (rs->buf, max_size,
10114 "qSearch:memory:%s;%s;",
5af949e3 10115 phex_nz (start_addr, addr_size),
08388c79
DE
10116 phex_nz (search_space_len, sizeof (search_space_len)));
10117 max_size -= (i + 1);
10118
10119 /* Escape as much data as fits into rs->buf. */
10120 escaped_pattern_len =
124e13d9 10121 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10122 &used_pattern_len, max_size);
10123
10124 /* Bail if the pattern is too large. */
10125 if (used_pattern_len != pattern_len)
9b20d036 10126 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10127
10128 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10129 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10130 || packet_ok (rs->buf, packet) != PACKET_OK)
10131 {
10132 /* The request may not have worked because the command is not
10133 supported. If so, fall back to the simple way. */
10134 if (packet->support == PACKET_DISABLE)
10135 {
10136 return simple_search_memory (ops, start_addr, search_space_len,
10137 pattern, pattern_len, found_addrp);
10138 }
10139 return -1;
10140 }
10141
10142 if (rs->buf[0] == '0')
10143 found = 0;
10144 else if (rs->buf[0] == '1')
10145 {
10146 found = 1;
10147 if (rs->buf[1] != ',')
10e0fa18 10148 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10149 unpack_varlen_hex (rs->buf + 2, &found_addr);
10150 *found_addrp = found_addr;
10151 }
10152 else
10e0fa18 10153 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10154
10155 return found;
10156}
10157
96baa820 10158static void
a30bf1f1 10159remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10160 struct ui_file *outbuf)
96baa820 10161{
d01949b6 10162 struct remote_state *rs = get_remote_state ();
2e9f7625 10163 char *p = rs->buf;
96baa820 10164
5d93a237 10165 if (!rs->remote_desc)
8a3fe4f8 10166 error (_("remote rcmd is only available after target open"));
96baa820 10167
23860348 10168 /* Send a NULL command across as an empty command. */
7be570e7
JM
10169 if (command == NULL)
10170 command = "";
10171
23860348 10172 /* The query prefix. */
2e9f7625
DJ
10173 strcpy (rs->buf, "qRcmd,");
10174 p = strchr (rs->buf, '\0');
96baa820 10175
3e43a32a
MS
10176 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10177 > get_remote_packet_size ())
8a3fe4f8 10178 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10179
23860348 10180 /* Encode the actual command. */
a30bf1f1 10181 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10182
6d820c5c 10183 if (putpkt (rs->buf) < 0)
8a3fe4f8 10184 error (_("Communication problem with target."));
96baa820
JM
10185
10186 /* get/display the response */
10187 while (1)
10188 {
2e9f7625
DJ
10189 char *buf;
10190
00bf0b85 10191 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10192 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10193 rs->buf[0] = '\0';
5b37825d
PW
10194 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10195 {
10196 /* Timeout. Continue to (try to) read responses.
10197 This is better than stopping with an error, assuming the stub
10198 is still executing the (long) monitor command.
10199 If needed, the user can interrupt gdb using C-c, obtaining
10200 an effect similar to stop on timeout. */
10201 continue;
10202 }
2e9f7625 10203 buf = rs->buf;
96baa820 10204 if (buf[0] == '\0')
8a3fe4f8 10205 error (_("Target does not support this command."));
96baa820
JM
10206 if (buf[0] == 'O' && buf[1] != 'K')
10207 {
23860348 10208 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10209 continue;
10210 }
10211 if (strcmp (buf, "OK") == 0)
10212 break;
7be570e7
JM
10213 if (strlen (buf) == 3 && buf[0] == 'E'
10214 && isdigit (buf[1]) && isdigit (buf[2]))
10215 {
8a3fe4f8 10216 error (_("Protocol error with Rcmd"));
7be570e7 10217 }
96baa820
JM
10218 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10219 {
10220 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10221
96baa820
JM
10222 fputc_unfiltered (c, outbuf);
10223 }
10224 break;
10225 }
10226}
10227
fd79ecee
DJ
10228static VEC(mem_region_s) *
10229remote_memory_map (struct target_ops *ops)
10230{
10231 VEC(mem_region_s) *result = NULL;
10232 char *text = target_read_stralloc (&current_target,
10233 TARGET_OBJECT_MEMORY_MAP, NULL);
10234
10235 if (text)
10236 {
10237 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10238
fd79ecee
DJ
10239 result = parse_memory_map (text);
10240 do_cleanups (back_to);
10241 }
10242
10243 return result;
10244}
10245
c906108c 10246static void
fba45db2 10247packet_command (char *args, int from_tty)
c906108c 10248{
d01949b6 10249 struct remote_state *rs = get_remote_state ();
c906108c 10250
5d93a237 10251 if (!rs->remote_desc)
8a3fe4f8 10252 error (_("command can only be used with remote target"));
c906108c 10253
c5aa993b 10254 if (!args)
8a3fe4f8 10255 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10256
10257 puts_filtered ("sending: ");
10258 print_packet (args);
10259 puts_filtered ("\n");
10260 putpkt (args);
10261
6d820c5c 10262 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10263 puts_filtered ("received: ");
6d820c5c 10264 print_packet (rs->buf);
c906108c
SS
10265 puts_filtered ("\n");
10266}
10267
10268#if 0
23860348 10269/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10270
a14ed312 10271static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10272
a14ed312 10273static void threadset_test_cmd (char *cmd, int tty);
c906108c 10274
a14ed312 10275static void threadalive_test (char *cmd, int tty);
c906108c 10276
a14ed312 10277static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10278
23860348 10279int get_and_display_threadinfo (threadref *ref);
c906108c 10280
a14ed312 10281static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10282
23860348 10283static int thread_display_step (threadref *ref, void *context);
c906108c 10284
a14ed312 10285static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10286
a14ed312 10287static void init_remote_threadtests (void);
c906108c 10288
23860348 10289#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10290
10291static void
fba45db2 10292threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10293{
10294 int sample_thread = SAMPLE_THREAD;
10295
a3f17187 10296 printf_filtered (_("Remote threadset test\n"));
79d7f229 10297 set_general_thread (sample_thread);
c906108c
SS
10298}
10299
10300
10301static void
fba45db2 10302threadalive_test (char *cmd, int tty)
c906108c
SS
10303{
10304 int sample_thread = SAMPLE_THREAD;
79d7f229 10305 int pid = ptid_get_pid (inferior_ptid);
ba348170 10306 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10307
79d7f229 10308 if (remote_thread_alive (ptid))
c906108c
SS
10309 printf_filtered ("PASS: Thread alive test\n");
10310 else
10311 printf_filtered ("FAIL: Thread alive test\n");
10312}
10313
23860348 10314void output_threadid (char *title, threadref *ref);
c906108c
SS
10315
10316void
fba45db2 10317output_threadid (char *title, threadref *ref)
c906108c
SS
10318{
10319 char hexid[20];
10320
23860348 10321 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10322 hexid[16] = 0;
10323 printf_filtered ("%s %s\n", title, (&hexid[0]));
10324}
10325
10326static void
fba45db2 10327threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10328{
10329 int startflag = 1;
10330 threadref nextthread;
10331 int done, result_count;
10332 threadref threadlist[3];
10333
10334 printf_filtered ("Remote Threadlist test\n");
10335 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10336 &result_count, &threadlist[0]))
10337 printf_filtered ("FAIL: threadlist test\n");
10338 else
10339 {
10340 threadref *scan = threadlist;
10341 threadref *limit = scan + result_count;
10342
10343 while (scan < limit)
10344 output_threadid (" thread ", scan++);
10345 }
10346}
10347
10348void
fba45db2 10349display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10350{
10351 output_threadid ("Threadid: ", &info->threadid);
10352 printf_filtered ("Name: %s\n ", info->shortname);
10353 printf_filtered ("State: %s\n", info->display);
10354 printf_filtered ("other: %s\n\n", info->more_display);
10355}
10356
10357int
fba45db2 10358get_and_display_threadinfo (threadref *ref)
c906108c
SS
10359{
10360 int result;
10361 int set;
10362 struct gdb_ext_thread_info threadinfo;
10363
10364 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10365 | TAG_MOREDISPLAY | TAG_DISPLAY;
10366 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10367 display_thread_info (&threadinfo);
10368 return result;
10369}
10370
10371static void
fba45db2 10372threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10373{
10374 int athread = SAMPLE_THREAD;
10375 threadref thread;
10376 int set;
10377
10378 int_to_threadref (&thread, athread);
10379 printf_filtered ("Remote Threadinfo test\n");
10380 if (!get_and_display_threadinfo (&thread))
10381 printf_filtered ("FAIL cannot get thread info\n");
10382}
10383
10384static int
fba45db2 10385thread_display_step (threadref *ref, void *context)
c906108c
SS
10386{
10387 /* output_threadid(" threadstep ",ref); *//* simple test */
10388 return get_and_display_threadinfo (ref);
10389}
10390
10391static void
fba45db2 10392threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10393{
10394 printf_filtered ("Remote Threadlist update test\n");
10395 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10396}
10397
10398static void
10399init_remote_threadtests (void)
10400{
3e43a32a
MS
10401 add_com ("tlist", class_obscure, threadlist_test_cmd,
10402 _("Fetch and print the remote list of "
10403 "thread identifiers, one pkt only"));
c906108c 10404 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10405 _("Fetch and display info about one thread"));
c906108c 10406 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10407 _("Test setting to a different thread"));
c906108c 10408 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10409 _("Iterate through updating all remote thread info"));
c906108c 10410 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10411 _(" Remote thread alive test "));
c906108c
SS
10412}
10413
10414#endif /* 0 */
10415
f3fb8c85
MS
10416/* Convert a thread ID to a string. Returns the string in a static
10417 buffer. */
10418
10419static char *
117de6a9 10420remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10421{
79d7f229 10422 static char buf[64];
82f73884 10423 struct remote_state *rs = get_remote_state ();
f3fb8c85 10424
7cee1e54
PA
10425 if (ptid_equal (ptid, null_ptid))
10426 return normal_pid_to_str (ptid);
10427 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10428 {
10429 /* Printing an inferior target id. */
10430
10431 /* When multi-process extensions are off, there's no way in the
10432 remote protocol to know the remote process id, if there's any
10433 at all. There's one exception --- when we're connected with
10434 target extended-remote, and we manually attached to a process
10435 with "attach PID". We don't record anywhere a flag that
10436 allows us to distinguish that case from the case of
10437 connecting with extended-remote and the stub already being
10438 attached to a process, and reporting yes to qAttached, hence
10439 no smart special casing here. */
10440 if (!remote_multi_process_p (rs))
10441 {
10442 xsnprintf (buf, sizeof buf, "Remote target");
10443 return buf;
10444 }
10445
10446 return normal_pid_to_str (ptid);
82f73884 10447 }
ecd0ada5 10448 else
79d7f229 10449 {
ecd0ada5
PA
10450 if (ptid_equal (magic_null_ptid, ptid))
10451 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 10452 else if (rs->extended && remote_multi_process_p (rs))
de0d863e
DB
10453 if (ptid_get_lwp (ptid) == 0)
10454 return normal_pid_to_str (ptid);
10455 else
10456 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10457 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10458 else
10459 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10460 ptid_get_lwp (ptid));
79d7f229
PA
10461 return buf;
10462 }
f3fb8c85
MS
10463}
10464
38691318
KB
10465/* Get the address of the thread local variable in OBJFILE which is
10466 stored at OFFSET within the thread local storage for thread PTID. */
10467
10468static CORE_ADDR
117de6a9
PA
10469remote_get_thread_local_address (struct target_ops *ops,
10470 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10471{
4082afcc 10472 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10473 {
10474 struct remote_state *rs = get_remote_state ();
6d820c5c 10475 char *p = rs->buf;
82f73884 10476 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10477 enum packet_result result;
38691318
KB
10478
10479 strcpy (p, "qGetTLSAddr:");
10480 p += strlen (p);
82f73884 10481 p = write_ptid (p, endp, ptid);
38691318
KB
10482 *p++ = ',';
10483 p += hexnumstr (p, offset);
10484 *p++ = ',';
10485 p += hexnumstr (p, lm);
10486 *p++ = '\0';
10487
6d820c5c
DJ
10488 putpkt (rs->buf);
10489 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10490 result = packet_ok (rs->buf,
10491 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10492 if (result == PACKET_OK)
38691318
KB
10493 {
10494 ULONGEST result;
10495
6d820c5c 10496 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10497 return result;
10498 }
571dd617 10499 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10500 throw_error (TLS_GENERIC_ERROR,
10501 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10502 else
109c3e39
AC
10503 throw_error (TLS_GENERIC_ERROR,
10504 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10505 }
10506 else
109c3e39
AC
10507 throw_error (TLS_GENERIC_ERROR,
10508 _("TLS not supported or disabled on this target"));
38691318
KB
10509 /* Not reached. */
10510 return 0;
10511}
10512
711e434b
PM
10513/* Provide thread local base, i.e. Thread Information Block address.
10514 Returns 1 if ptid is found and thread_local_base is non zero. */
10515
70221824 10516static int
bd7ae0f5 10517remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10518{
4082afcc 10519 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10520 {
10521 struct remote_state *rs = get_remote_state ();
10522 char *p = rs->buf;
10523 char *endp = rs->buf + get_remote_packet_size ();
10524 enum packet_result result;
10525
10526 strcpy (p, "qGetTIBAddr:");
10527 p += strlen (p);
10528 p = write_ptid (p, endp, ptid);
10529 *p++ = '\0';
10530
10531 putpkt (rs->buf);
10532 getpkt (&rs->buf, &rs->buf_size, 0);
10533 result = packet_ok (rs->buf,
10534 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10535 if (result == PACKET_OK)
10536 {
10537 ULONGEST result;
10538
10539 unpack_varlen_hex (rs->buf, &result);
10540 if (addr)
10541 *addr = (CORE_ADDR) result;
10542 return 1;
10543 }
10544 else if (result == PACKET_UNKNOWN)
10545 error (_("Remote target doesn't support qGetTIBAddr packet"));
10546 else
10547 error (_("Remote target failed to process qGetTIBAddr request"));
10548 }
10549 else
10550 error (_("qGetTIBAddr not supported or disabled on this target"));
10551 /* Not reached. */
10552 return 0;
10553}
10554
29709017
DJ
10555/* Support for inferring a target description based on the current
10556 architecture and the size of a 'g' packet. While the 'g' packet
10557 can have any size (since optional registers can be left off the
10558 end), some sizes are easily recognizable given knowledge of the
10559 approximate architecture. */
10560
10561struct remote_g_packet_guess
10562{
10563 int bytes;
10564 const struct target_desc *tdesc;
10565};
10566typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10567DEF_VEC_O(remote_g_packet_guess_s);
10568
10569struct remote_g_packet_data
10570{
10571 VEC(remote_g_packet_guess_s) *guesses;
10572};
10573
10574static struct gdbarch_data *remote_g_packet_data_handle;
10575
10576static void *
10577remote_g_packet_data_init (struct obstack *obstack)
10578{
10579 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10580}
10581
10582void
10583register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10584 const struct target_desc *tdesc)
10585{
10586 struct remote_g_packet_data *data
19ba03f4
SM
10587 = ((struct remote_g_packet_data *)
10588 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10589 struct remote_g_packet_guess new_guess, *guess;
10590 int ix;
10591
10592 gdb_assert (tdesc != NULL);
10593
10594 for (ix = 0;
10595 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10596 ix++)
10597 if (guess->bytes == bytes)
10598 internal_error (__FILE__, __LINE__,
9b20d036 10599 _("Duplicate g packet description added for size %d"),
29709017
DJ
10600 bytes);
10601
10602 new_guess.bytes = bytes;
10603 new_guess.tdesc = tdesc;
10604 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10605}
10606
d962ef82
DJ
10607/* Return 1 if remote_read_description would do anything on this target
10608 and architecture, 0 otherwise. */
10609
10610static int
10611remote_read_description_p (struct target_ops *target)
10612{
10613 struct remote_g_packet_data *data
19ba03f4
SM
10614 = ((struct remote_g_packet_data *)
10615 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10616
10617 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10618 return 1;
10619
10620 return 0;
10621}
10622
29709017
DJ
10623static const struct target_desc *
10624remote_read_description (struct target_ops *target)
10625{
10626 struct remote_g_packet_data *data
19ba03f4
SM
10627 = ((struct remote_g_packet_data *)
10628 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10629
d962ef82
DJ
10630 /* Do not try this during initial connection, when we do not know
10631 whether there is a running but stopped thread. */
10632 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10633 return target->beneath->to_read_description (target->beneath);
d962ef82 10634
29709017
DJ
10635 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10636 {
10637 struct remote_g_packet_guess *guess;
10638 int ix;
10639 int bytes = send_g_packet ();
10640
10641 for (ix = 0;
10642 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10643 ix++)
10644 if (guess->bytes == bytes)
10645 return guess->tdesc;
10646
10647 /* We discard the g packet. A minor optimization would be to
10648 hold on to it, and fill the register cache once we have selected
10649 an architecture, but it's too tricky to do safely. */
10650 }
10651
2117c711 10652 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10653}
10654
a6b151f1
DJ
10655/* Remote file transfer support. This is host-initiated I/O, not
10656 target-initiated; for target-initiated, see remote-fileio.c. */
10657
10658/* If *LEFT is at least the length of STRING, copy STRING to
10659 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10660 decrease *LEFT. Otherwise raise an error. */
10661
10662static void
10663remote_buffer_add_string (char **buffer, int *left, char *string)
10664{
10665 int len = strlen (string);
10666
10667 if (len > *left)
10668 error (_("Packet too long for target."));
10669
10670 memcpy (*buffer, string, len);
10671 *buffer += len;
10672 *left -= len;
10673
10674 /* NUL-terminate the buffer as a convenience, if there is
10675 room. */
10676 if (*left)
10677 **buffer = '\0';
10678}
10679
10680/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10681 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10682 decrease *LEFT. Otherwise raise an error. */
10683
10684static void
10685remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10686 int len)
10687{
10688 if (2 * len > *left)
10689 error (_("Packet too long for target."));
10690
10691 bin2hex (bytes, *buffer, len);
10692 *buffer += 2 * len;
10693 *left -= 2 * len;
10694
10695 /* NUL-terminate the buffer as a convenience, if there is
10696 room. */
10697 if (*left)
10698 **buffer = '\0';
10699}
10700
10701/* If *LEFT is large enough, convert VALUE to hex and add it to
10702 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10703 decrease *LEFT. Otherwise raise an error. */
10704
10705static void
10706remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10707{
10708 int len = hexnumlen (value);
10709
10710 if (len > *left)
10711 error (_("Packet too long for target."));
10712
10713 hexnumstr (*buffer, value);
10714 *buffer += len;
10715 *left -= len;
10716
10717 /* NUL-terminate the buffer as a convenience, if there is
10718 room. */
10719 if (*left)
10720 **buffer = '\0';
10721}
10722
10723/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10724 value, *REMOTE_ERRNO to the remote error number or zero if none
10725 was included, and *ATTACHMENT to point to the start of the annex
10726 if any. The length of the packet isn't needed here; there may
10727 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10728
10729 Return 0 if the packet could be parsed, -1 if it could not. If
10730 -1 is returned, the other variables may not be initialized. */
10731
10732static int
10733remote_hostio_parse_result (char *buffer, int *retcode,
10734 int *remote_errno, char **attachment)
10735{
10736 char *p, *p2;
10737
10738 *remote_errno = 0;
10739 *attachment = NULL;
10740
10741 if (buffer[0] != 'F')
10742 return -1;
10743
10744 errno = 0;
10745 *retcode = strtol (&buffer[1], &p, 16);
10746 if (errno != 0 || p == &buffer[1])
10747 return -1;
10748
10749 /* Check for ",errno". */
10750 if (*p == ',')
10751 {
10752 errno = 0;
10753 *remote_errno = strtol (p + 1, &p2, 16);
10754 if (errno != 0 || p + 1 == p2)
10755 return -1;
10756 p = p2;
10757 }
10758
10759 /* Check for ";attachment". If there is no attachment, the
10760 packet should end here. */
10761 if (*p == ';')
10762 {
10763 *attachment = p + 1;
10764 return 0;
10765 }
10766 else if (*p == '\0')
10767 return 0;
10768 else
10769 return -1;
10770}
10771
10772/* Send a prepared I/O packet to the target and read its response.
10773 The prepared packet is in the global RS->BUF before this function
10774 is called, and the answer is there when we return.
10775
10776 COMMAND_BYTES is the length of the request to send, which may include
10777 binary data. WHICH_PACKET is the packet configuration to check
10778 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10779 is set to the error number and -1 is returned. Otherwise the value
10780 returned by the function is returned.
10781
10782 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10783 attachment is expected; an error will be reported if there's a
10784 mismatch. If one is found, *ATTACHMENT will be set to point into
10785 the packet buffer and *ATTACHMENT_LEN will be set to the
10786 attachment's length. */
10787
10788static int
10789remote_hostio_send_command (int command_bytes, int which_packet,
10790 int *remote_errno, char **attachment,
10791 int *attachment_len)
10792{
10793 struct remote_state *rs = get_remote_state ();
10794 int ret, bytes_read;
10795 char *attachment_tmp;
10796
5d93a237 10797 if (!rs->remote_desc
4082afcc 10798 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10799 {
10800 *remote_errno = FILEIO_ENOSYS;
10801 return -1;
10802 }
10803
10804 putpkt_binary (rs->buf, command_bytes);
10805 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10806
10807 /* If it timed out, something is wrong. Don't try to parse the
10808 buffer. */
10809 if (bytes_read < 0)
10810 {
10811 *remote_errno = FILEIO_EINVAL;
10812 return -1;
10813 }
10814
10815 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10816 {
10817 case PACKET_ERROR:
10818 *remote_errno = FILEIO_EINVAL;
10819 return -1;
10820 case PACKET_UNKNOWN:
10821 *remote_errno = FILEIO_ENOSYS;
10822 return -1;
10823 case PACKET_OK:
10824 break;
10825 }
10826
10827 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10828 &attachment_tmp))
10829 {
10830 *remote_errno = FILEIO_EINVAL;
10831 return -1;
10832 }
10833
10834 /* Make sure we saw an attachment if and only if we expected one. */
10835 if ((attachment_tmp == NULL && attachment != NULL)
10836 || (attachment_tmp != NULL && attachment == NULL))
10837 {
10838 *remote_errno = FILEIO_EINVAL;
10839 return -1;
10840 }
10841
10842 /* If an attachment was found, it must point into the packet buffer;
10843 work out how many bytes there were. */
10844 if (attachment_tmp != NULL)
10845 {
10846 *attachment = attachment_tmp;
10847 *attachment_len = bytes_read - (*attachment - rs->buf);
10848 }
10849
10850 return ret;
10851}
10852
80152258
PA
10853/* Invalidate the readahead cache. */
10854
10855static void
10856readahead_cache_invalidate (void)
10857{
10858 struct remote_state *rs = get_remote_state ();
10859
10860 rs->readahead_cache.fd = -1;
10861}
10862
10863/* Invalidate the readahead cache if it is holding data for FD. */
10864
10865static void
10866readahead_cache_invalidate_fd (int fd)
10867{
10868 struct remote_state *rs = get_remote_state ();
10869
10870 if (rs->readahead_cache.fd == fd)
10871 rs->readahead_cache.fd = -1;
10872}
10873
15a201c8
GB
10874/* Set the filesystem remote_hostio functions that take FILENAME
10875 arguments will use. Return 0 on success, or -1 if an error
10876 occurs (and set *REMOTE_ERRNO). */
10877
10878static int
10879remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10880{
10881 struct remote_state *rs = get_remote_state ();
10882 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10883 char *p = rs->buf;
10884 int left = get_remote_packet_size () - 1;
10885 char arg[9];
10886 int ret;
10887
10888 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10889 return 0;
10890
10891 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10892 return 0;
10893
10894 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10895
10896 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10897 remote_buffer_add_string (&p, &left, arg);
10898
10899 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10900 remote_errno, NULL, NULL);
10901
10902 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10903 return 0;
10904
10905 if (ret == 0)
10906 rs->fs_pid = required_pid;
10907
10908 return ret;
10909}
10910
12e2a5fd 10911/* Implementation of to_fileio_open. */
a6b151f1
DJ
10912
10913static int
cd897586 10914remote_hostio_open (struct target_ops *self,
07c138c8 10915 struct inferior *inf, const char *filename,
4313b8c0
GB
10916 int flags, int mode, int warn_if_slow,
10917 int *remote_errno)
a6b151f1
DJ
10918{
10919 struct remote_state *rs = get_remote_state ();
10920 char *p = rs->buf;
10921 int left = get_remote_packet_size () - 1;
10922
4313b8c0
GB
10923 if (warn_if_slow)
10924 {
10925 static int warning_issued = 0;
10926
10927 printf_unfiltered (_("Reading %s from remote target...\n"),
10928 filename);
10929
10930 if (!warning_issued)
10931 {
10932 warning (_("File transfers from remote targets can be slow."
10933 " Use \"set sysroot\" to access files locally"
10934 " instead."));
10935 warning_issued = 1;
10936 }
10937 }
10938
15a201c8
GB
10939 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10940 return -1;
10941
a6b151f1
DJ
10942 remote_buffer_add_string (&p, &left, "vFile:open:");
10943
10944 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10945 strlen (filename));
10946 remote_buffer_add_string (&p, &left, ",");
10947
10948 remote_buffer_add_int (&p, &left, flags);
10949 remote_buffer_add_string (&p, &left, ",");
10950
10951 remote_buffer_add_int (&p, &left, mode);
10952
10953 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10954 remote_errno, NULL, NULL);
10955}
10956
12e2a5fd 10957/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
10958
10959static int
0d866f62
TT
10960remote_hostio_pwrite (struct target_ops *self,
10961 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
10962 ULONGEST offset, int *remote_errno)
10963{
10964 struct remote_state *rs = get_remote_state ();
10965 char *p = rs->buf;
10966 int left = get_remote_packet_size ();
10967 int out_len;
10968
80152258
PA
10969 readahead_cache_invalidate_fd (fd);
10970
a6b151f1
DJ
10971 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10972
10973 remote_buffer_add_int (&p, &left, fd);
10974 remote_buffer_add_string (&p, &left, ",");
10975
10976 remote_buffer_add_int (&p, &left, offset);
10977 remote_buffer_add_string (&p, &left, ",");
10978
124e13d9 10979 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
10980 get_remote_packet_size () - (p - rs->buf));
10981
10982 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10983 remote_errno, NULL, NULL);
10984}
10985
80152258
PA
10986/* Helper for the implementation of to_fileio_pread. Read the file
10987 from the remote side with vFile:pread. */
a6b151f1
DJ
10988
10989static int
80152258
PA
10990remote_hostio_pread_vFile (struct target_ops *self,
10991 int fd, gdb_byte *read_buf, int len,
10992 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
10993{
10994 struct remote_state *rs = get_remote_state ();
10995 char *p = rs->buf;
10996 char *attachment;
10997 int left = get_remote_packet_size ();
10998 int ret, attachment_len;
10999 int read_len;
11000
11001 remote_buffer_add_string (&p, &left, "vFile:pread:");
11002
11003 remote_buffer_add_int (&p, &left, fd);
11004 remote_buffer_add_string (&p, &left, ",");
11005
11006 remote_buffer_add_int (&p, &left, len);
11007 remote_buffer_add_string (&p, &left, ",");
11008
11009 remote_buffer_add_int (&p, &left, offset);
11010
11011 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11012 remote_errno, &attachment,
11013 &attachment_len);
11014
11015 if (ret < 0)
11016 return ret;
11017
bc20a4af 11018 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11019 read_buf, len);
11020 if (read_len != ret)
11021 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11022
11023 return ret;
11024}
11025
80152258
PA
11026/* Serve pread from the readahead cache. Returns number of bytes
11027 read, or 0 if the request can't be served from the cache. */
11028
11029static int
11030remote_hostio_pread_from_cache (struct remote_state *rs,
11031 int fd, gdb_byte *read_buf, size_t len,
11032 ULONGEST offset)
11033{
11034 struct readahead_cache *cache = &rs->readahead_cache;
11035
11036 if (cache->fd == fd
11037 && cache->offset <= offset
11038 && offset < cache->offset + cache->bufsize)
11039 {
11040 ULONGEST max = cache->offset + cache->bufsize;
11041
11042 if (offset + len > max)
11043 len = max - offset;
11044
11045 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11046 return len;
11047 }
11048
11049 return 0;
11050}
11051
11052/* Implementation of to_fileio_pread. */
11053
11054static int
11055remote_hostio_pread (struct target_ops *self,
11056 int fd, gdb_byte *read_buf, int len,
11057 ULONGEST offset, int *remote_errno)
11058{
11059 int ret;
11060 struct remote_state *rs = get_remote_state ();
11061 struct readahead_cache *cache = &rs->readahead_cache;
11062
11063 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11064 if (ret > 0)
11065 {
11066 cache->hit_count++;
11067
11068 if (remote_debug)
11069 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11070 pulongest (cache->hit_count));
11071 return ret;
11072 }
11073
11074 cache->miss_count++;
11075 if (remote_debug)
11076 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11077 pulongest (cache->miss_count));
11078
11079 cache->fd = fd;
11080 cache->offset = offset;
11081 cache->bufsize = get_remote_packet_size ();
224c3ddb 11082 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11083
11084 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11085 cache->offset, remote_errno);
11086 if (ret <= 0)
11087 {
11088 readahead_cache_invalidate_fd (fd);
11089 return ret;
11090 }
11091
11092 cache->bufsize = ret;
11093 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11094}
11095
12e2a5fd 11096/* Implementation of to_fileio_close. */
a6b151f1
DJ
11097
11098static int
df39ea25 11099remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11100{
11101 struct remote_state *rs = get_remote_state ();
11102 char *p = rs->buf;
11103 int left = get_remote_packet_size () - 1;
11104
80152258
PA
11105 readahead_cache_invalidate_fd (fd);
11106
a6b151f1
DJ
11107 remote_buffer_add_string (&p, &left, "vFile:close:");
11108
11109 remote_buffer_add_int (&p, &left, fd);
11110
11111 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11112 remote_errno, NULL, NULL);
11113}
11114
12e2a5fd 11115/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11116
11117static int
dbbca37d 11118remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11119 struct inferior *inf, const char *filename,
11120 int *remote_errno)
a6b151f1
DJ
11121{
11122 struct remote_state *rs = get_remote_state ();
11123 char *p = rs->buf;
11124 int left = get_remote_packet_size () - 1;
11125
15a201c8
GB
11126 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11127 return -1;
11128
a6b151f1
DJ
11129 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11130
11131 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11132 strlen (filename));
11133
11134 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11135 remote_errno, NULL, NULL);
11136}
11137
12e2a5fd 11138/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11139
11140static char *
fab5aa7c 11141remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11142 struct inferior *inf, const char *filename,
11143 int *remote_errno)
b9e7b9c3
UW
11144{
11145 struct remote_state *rs = get_remote_state ();
11146 char *p = rs->buf;
11147 char *attachment;
11148 int left = get_remote_packet_size ();
11149 int len, attachment_len;
11150 int read_len;
11151 char *ret;
11152
15a201c8
GB
11153 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11154 return NULL;
11155
b9e7b9c3
UW
11156 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11157
11158 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11159 strlen (filename));
11160
11161 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11162 remote_errno, &attachment,
11163 &attachment_len);
11164
11165 if (len < 0)
11166 return NULL;
11167
224c3ddb 11168 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11169
bc20a4af
PA
11170 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11171 (gdb_byte *) ret, len);
b9e7b9c3
UW
11172 if (read_len != len)
11173 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11174
11175 ret[len] = '\0';
11176 return ret;
11177}
11178
12e2a5fd 11179/* Implementation of to_fileio_fstat. */
0a93529c
GB
11180
11181static int
11182remote_hostio_fstat (struct target_ops *self,
11183 int fd, struct stat *st,
11184 int *remote_errno)
11185{
11186 struct remote_state *rs = get_remote_state ();
11187 char *p = rs->buf;
11188 int left = get_remote_packet_size ();
11189 int attachment_len, ret;
11190 char *attachment;
11191 struct fio_stat fst;
11192 int read_len;
11193
464b0089
GB
11194 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11195
11196 remote_buffer_add_int (&p, &left, fd);
11197
11198 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11199 remote_errno, &attachment,
11200 &attachment_len);
11201 if (ret < 0)
0a93529c 11202 {
464b0089
GB
11203 if (*remote_errno != FILEIO_ENOSYS)
11204 return ret;
11205
0a93529c
GB
11206 /* Strictly we should return -1, ENOSYS here, but when
11207 "set sysroot remote:" was implemented in August 2008
11208 BFD's need for a stat function was sidestepped with
11209 this hack. This was not remedied until March 2015
11210 so we retain the previous behavior to avoid breaking
11211 compatibility.
11212
11213 Note that the memset is a March 2015 addition; older
11214 GDBs set st_size *and nothing else* so the structure
11215 would have garbage in all other fields. This might
11216 break something but retaining the previous behavior
11217 here would be just too wrong. */
11218
11219 memset (st, 0, sizeof (struct stat));
11220 st->st_size = INT_MAX;
11221 return 0;
11222 }
11223
0a93529c
GB
11224 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11225 (gdb_byte *) &fst, sizeof (fst));
11226
11227 if (read_len != ret)
11228 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11229
11230 if (read_len != sizeof (fst))
11231 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11232 read_len, (int) sizeof (fst));
11233
11234 remote_fileio_to_host_stat (&fst, st);
11235
11236 return 0;
11237}
11238
12e2a5fd 11239/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11240
11241static int
11242remote_filesystem_is_local (struct target_ops *self)
11243{
11244 /* Valgrind GDB presents itself as a remote target but works
11245 on the local filesystem: it does not implement remote get
11246 and users are not expected to set a sysroot. To handle
11247 this case we treat the remote filesystem as local if the
11248 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11249 does not support vFile:open. */
a3be80c3 11250 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11251 {
11252 enum packet_support ps = packet_support (PACKET_vFile_open);
11253
11254 if (ps == PACKET_SUPPORT_UNKNOWN)
11255 {
11256 int fd, remote_errno;
11257
11258 /* Try opening a file to probe support. The supplied
11259 filename is irrelevant, we only care about whether
11260 the stub recognizes the packet or not. */
07c138c8 11261 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11262 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11263 &remote_errno);
11264
11265 if (fd >= 0)
11266 remote_hostio_close (self, fd, &remote_errno);
11267
11268 ps = packet_support (PACKET_vFile_open);
11269 }
11270
11271 if (ps == PACKET_DISABLE)
11272 {
11273 static int warning_issued = 0;
11274
11275 if (!warning_issued)
11276 {
11277 warning (_("remote target does not support file"
11278 " transfer, attempting to access files"
11279 " from local filesystem."));
11280 warning_issued = 1;
11281 }
11282
11283 return 1;
11284 }
11285 }
11286
11287 return 0;
11288}
11289
a6b151f1
DJ
11290static int
11291remote_fileio_errno_to_host (int errnum)
11292{
11293 switch (errnum)
11294 {
11295 case FILEIO_EPERM:
11296 return EPERM;
11297 case FILEIO_ENOENT:
11298 return ENOENT;
11299 case FILEIO_EINTR:
11300 return EINTR;
11301 case FILEIO_EIO:
11302 return EIO;
11303 case FILEIO_EBADF:
11304 return EBADF;
11305 case FILEIO_EACCES:
11306 return EACCES;
11307 case FILEIO_EFAULT:
11308 return EFAULT;
11309 case FILEIO_EBUSY:
11310 return EBUSY;
11311 case FILEIO_EEXIST:
11312 return EEXIST;
11313 case FILEIO_ENODEV:
11314 return ENODEV;
11315 case FILEIO_ENOTDIR:
11316 return ENOTDIR;
11317 case FILEIO_EISDIR:
11318 return EISDIR;
11319 case FILEIO_EINVAL:
11320 return EINVAL;
11321 case FILEIO_ENFILE:
11322 return ENFILE;
11323 case FILEIO_EMFILE:
11324 return EMFILE;
11325 case FILEIO_EFBIG:
11326 return EFBIG;
11327 case FILEIO_ENOSPC:
11328 return ENOSPC;
11329 case FILEIO_ESPIPE:
11330 return ESPIPE;
11331 case FILEIO_EROFS:
11332 return EROFS;
11333 case FILEIO_ENOSYS:
11334 return ENOSYS;
11335 case FILEIO_ENAMETOOLONG:
11336 return ENAMETOOLONG;
11337 }
11338 return -1;
11339}
11340
11341static char *
11342remote_hostio_error (int errnum)
11343{
11344 int host_error = remote_fileio_errno_to_host (errnum);
11345
11346 if (host_error == -1)
11347 error (_("Unknown remote I/O error %d"), errnum);
11348 else
11349 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11350}
11351
a6b151f1
DJ
11352static void
11353remote_hostio_close_cleanup (void *opaque)
11354{
11355 int fd = *(int *) opaque;
11356 int remote_errno;
11357
df39ea25 11358 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11359}
11360
11361void
11362remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11363{
11364 struct cleanup *back_to, *close_cleanup;
11365 int retcode, fd, remote_errno, bytes, io_size;
11366 FILE *file;
11367 gdb_byte *buffer;
11368 int bytes_in_buffer;
11369 int saw_eof;
11370 ULONGEST offset;
5d93a237 11371 struct remote_state *rs = get_remote_state ();
a6b151f1 11372
5d93a237 11373 if (!rs->remote_desc)
a6b151f1
DJ
11374 error (_("command can only be used with remote target"));
11375
614c279d 11376 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11377 if (file == NULL)
11378 perror_with_name (local_file);
7c8a8b04 11379 back_to = make_cleanup_fclose (file);
a6b151f1 11380
07c138c8 11381 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11382 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11383 | FILEIO_O_TRUNC),
4313b8c0 11384 0700, 0, &remote_errno);
a6b151f1
DJ
11385 if (fd == -1)
11386 remote_hostio_error (remote_errno);
11387
11388 /* Send up to this many bytes at once. They won't all fit in the
11389 remote packet limit, so we'll transfer slightly fewer. */
11390 io_size = get_remote_packet_size ();
224c3ddb 11391 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11392 make_cleanup (xfree, buffer);
11393
11394 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11395
11396 bytes_in_buffer = 0;
11397 saw_eof = 0;
11398 offset = 0;
11399 while (bytes_in_buffer || !saw_eof)
11400 {
11401 if (!saw_eof)
11402 {
3e43a32a
MS
11403 bytes = fread (buffer + bytes_in_buffer, 1,
11404 io_size - bytes_in_buffer,
a6b151f1
DJ
11405 file);
11406 if (bytes == 0)
11407 {
11408 if (ferror (file))
11409 error (_("Error reading %s."), local_file);
11410 else
11411 {
11412 /* EOF. Unless there is something still in the
11413 buffer from the last iteration, we are done. */
11414 saw_eof = 1;
11415 if (bytes_in_buffer == 0)
11416 break;
11417 }
11418 }
11419 }
11420 else
11421 bytes = 0;
11422
11423 bytes += bytes_in_buffer;
11424 bytes_in_buffer = 0;
11425
0d866f62
TT
11426 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11427 fd, buffer, bytes,
3e43a32a 11428 offset, &remote_errno);
a6b151f1
DJ
11429
11430 if (retcode < 0)
11431 remote_hostio_error (remote_errno);
11432 else if (retcode == 0)
11433 error (_("Remote write of %d bytes returned 0!"), bytes);
11434 else if (retcode < bytes)
11435 {
11436 /* Short write. Save the rest of the read data for the next
11437 write. */
11438 bytes_in_buffer = bytes - retcode;
11439 memmove (buffer, buffer + retcode, bytes_in_buffer);
11440 }
11441
11442 offset += retcode;
11443 }
11444
11445 discard_cleanups (close_cleanup);
df39ea25 11446 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11447 remote_hostio_error (remote_errno);
11448
11449 if (from_tty)
11450 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11451 do_cleanups (back_to);
11452}
11453
11454void
11455remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11456{
11457 struct cleanup *back_to, *close_cleanup;
cea39f65 11458 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11459 FILE *file;
11460 gdb_byte *buffer;
11461 ULONGEST offset;
5d93a237 11462 struct remote_state *rs = get_remote_state ();
a6b151f1 11463
5d93a237 11464 if (!rs->remote_desc)
a6b151f1
DJ
11465 error (_("command can only be used with remote target"));
11466
07c138c8 11467 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11468 remote_file, FILEIO_O_RDONLY, 0, 0,
11469 &remote_errno);
a6b151f1
DJ
11470 if (fd == -1)
11471 remote_hostio_error (remote_errno);
11472
614c279d 11473 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11474 if (file == NULL)
11475 perror_with_name (local_file);
7c8a8b04 11476 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11477
11478 /* Send up to this many bytes at once. They won't all fit in the
11479 remote packet limit, so we'll transfer slightly fewer. */
11480 io_size = get_remote_packet_size ();
224c3ddb 11481 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11482 make_cleanup (xfree, buffer);
11483
11484 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11485
11486 offset = 0;
11487 while (1)
11488 {
a3be983c
TT
11489 bytes = remote_hostio_pread (find_target_at (process_stratum),
11490 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11491 if (bytes == 0)
11492 /* Success, but no bytes, means end-of-file. */
11493 break;
11494 if (bytes == -1)
11495 remote_hostio_error (remote_errno);
11496
11497 offset += bytes;
11498
11499 bytes = fwrite (buffer, 1, bytes, file);
11500 if (bytes == 0)
11501 perror_with_name (local_file);
11502 }
11503
11504 discard_cleanups (close_cleanup);
df39ea25 11505 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11506 remote_hostio_error (remote_errno);
11507
11508 if (from_tty)
11509 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11510 do_cleanups (back_to);
11511}
11512
11513void
11514remote_file_delete (const char *remote_file, int from_tty)
11515{
11516 int retcode, remote_errno;
5d93a237 11517 struct remote_state *rs = get_remote_state ();
a6b151f1 11518
5d93a237 11519 if (!rs->remote_desc)
a6b151f1
DJ
11520 error (_("command can only be used with remote target"));
11521
dbbca37d 11522 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11523 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11524 if (retcode == -1)
11525 remote_hostio_error (remote_errno);
11526
11527 if (from_tty)
11528 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11529}
11530
11531static void
11532remote_put_command (char *args, int from_tty)
11533{
11534 struct cleanup *back_to;
11535 char **argv;
11536
d1a41061
PP
11537 if (args == NULL)
11538 error_no_arg (_("file to put"));
11539
11540 argv = gdb_buildargv (args);
a6b151f1
DJ
11541 back_to = make_cleanup_freeargv (argv);
11542 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11543 error (_("Invalid parameters to remote put"));
11544
11545 remote_file_put (argv[0], argv[1], from_tty);
11546
11547 do_cleanups (back_to);
11548}
11549
11550static void
11551remote_get_command (char *args, int from_tty)
11552{
11553 struct cleanup *back_to;
11554 char **argv;
11555
d1a41061
PP
11556 if (args == NULL)
11557 error_no_arg (_("file to get"));
11558
11559 argv = gdb_buildargv (args);
a6b151f1
DJ
11560 back_to = make_cleanup_freeargv (argv);
11561 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11562 error (_("Invalid parameters to remote get"));
11563
11564 remote_file_get (argv[0], argv[1], from_tty);
11565
11566 do_cleanups (back_to);
11567}
11568
11569static void
11570remote_delete_command (char *args, int from_tty)
11571{
11572 struct cleanup *back_to;
11573 char **argv;
11574
d1a41061
PP
11575 if (args == NULL)
11576 error_no_arg (_("file to delete"));
11577
11578 argv = gdb_buildargv (args);
a6b151f1
DJ
11579 back_to = make_cleanup_freeargv (argv);
11580 if (argv[0] == NULL || argv[1] != NULL)
11581 error (_("Invalid parameters to remote delete"));
11582
11583 remote_file_delete (argv[0], from_tty);
11584
11585 do_cleanups (back_to);
11586}
11587
11588static void
11589remote_command (char *args, int from_tty)
11590{
635c7e8a 11591 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11592}
11593
b2175913 11594static int
19db3e69 11595remote_can_execute_reverse (struct target_ops *self)
b2175913 11596{
4082afcc
PA
11597 if (packet_support (PACKET_bs) == PACKET_ENABLE
11598 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11599 return 1;
11600 else
11601 return 0;
b2175913
MS
11602}
11603
74531fed 11604static int
2a9a2795 11605remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11606{
11607 return 1;
11608}
11609
03583c20 11610static int
2bfc0540 11611remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11612{
11613 /* Only supported in extended mode. */
11614 return 0;
11615}
11616
8a305172 11617static int
86ce2668 11618remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11619{
11620 struct remote_state *rs = get_remote_state ();
a744cf53 11621
901f9912
UW
11622 /* Only extended-remote handles being attached to multiple
11623 processes, even though plain remote can use the multi-process
11624 thread id extensions, so that GDB knows the target process's
11625 PID. */
11626 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
11627}
11628
70221824 11629static int
782b2b07
SS
11630remote_supports_cond_tracepoints (void)
11631{
4082afcc 11632 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11633}
11634
3788aec7 11635static int
efcc2da7 11636remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11637{
4082afcc 11638 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11639}
11640
70221824 11641static int
7a697b8d
SS
11642remote_supports_fast_tracepoints (void)
11643{
4082afcc 11644 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11645}
11646
0fb4aa4b
PA
11647static int
11648remote_supports_static_tracepoints (void)
11649{
4082afcc 11650 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11651}
11652
1e4d1764
YQ
11653static int
11654remote_supports_install_in_trace (void)
11655{
4082afcc 11656 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11657}
11658
d248b706 11659static int
7d178d6a 11660remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11661{
4082afcc
PA
11662 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11663 == PACKET_ENABLE);
d248b706
KY
11664}
11665
3065dfb6 11666static int
6de37a3a 11667remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11668{
4082afcc 11669 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11670}
11671
d3ce09f5 11672static int
78eff0ec 11673remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11674{
4082afcc 11675 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11676}
11677
35b1e5cc 11678static void
ecae04e1 11679remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11680{
11681 putpkt ("QTinit");
11682 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11683 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11684 error (_("Target does not support this command."));
11685}
11686
11687static void free_actions_list (char **actions_list);
11688static void free_actions_list_cleanup_wrapper (void *);
11689static void
11690free_actions_list_cleanup_wrapper (void *al)
11691{
19ba03f4 11692 free_actions_list ((char **) al);
35b1e5cc
SS
11693}
11694
11695static void
11696free_actions_list (char **actions_list)
11697{
11698 int ndx;
11699
11700 if (actions_list == 0)
11701 return;
11702
11703 for (ndx = 0; actions_list[ndx]; ndx++)
11704 xfree (actions_list[ndx]);
11705
11706 xfree (actions_list);
11707}
11708
409873ef
SS
11709/* Recursive routine to walk through command list including loops, and
11710 download packets for each command. */
11711
11712static void
11713remote_download_command_source (int num, ULONGEST addr,
11714 struct command_line *cmds)
11715{
11716 struct remote_state *rs = get_remote_state ();
11717 struct command_line *cmd;
11718
11719 for (cmd = cmds; cmd; cmd = cmd->next)
11720 {
0df8b418 11721 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11722 strcpy (rs->buf, "QTDPsrc:");
11723 encode_source_string (num, addr, "cmd", cmd->line,
11724 rs->buf + strlen (rs->buf),
11725 rs->buf_size - strlen (rs->buf));
11726 putpkt (rs->buf);
11727 remote_get_noisy_reply (&target_buf, &target_buf_size);
11728 if (strcmp (target_buf, "OK"))
11729 warning (_("Target does not support source download."));
11730
11731 if (cmd->control_type == while_control
11732 || cmd->control_type == while_stepping_control)
11733 {
11734 remote_download_command_source (num, addr, *cmd->body_list);
11735
0df8b418 11736 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11737 strcpy (rs->buf, "QTDPsrc:");
11738 encode_source_string (num, addr, "cmd", "end",
11739 rs->buf + strlen (rs->buf),
11740 rs->buf_size - strlen (rs->buf));
11741 putpkt (rs->buf);
11742 remote_get_noisy_reply (&target_buf, &target_buf_size);
11743 if (strcmp (target_buf, "OK"))
11744 warning (_("Target does not support source download."));
11745 }
11746 }
11747}
11748
35b1e5cc 11749static void
548f7808 11750remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11751{
bba74b36 11752#define BUF_SIZE 2048
e8ba3115 11753
35b1e5cc 11754 CORE_ADDR tpaddr;
409873ef 11755 char addrbuf[40];
bba74b36 11756 char buf[BUF_SIZE];
35b1e5cc
SS
11757 char **tdp_actions;
11758 char **stepping_actions;
11759 int ndx;
11760 struct cleanup *old_chain = NULL;
11761 struct agent_expr *aexpr;
11762 struct cleanup *aexpr_chain = NULL;
11763 char *pkt;
e8ba3115 11764 struct breakpoint *b = loc->owner;
d9b3f62e 11765 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11766
dc673c81 11767 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11768 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11769 tdp_actions);
11770 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11771 stepping_actions);
11772
11773 tpaddr = loc->address;
11774 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11775 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11776 addrbuf, /* address */
11777 (b->enable_state == bp_enabled ? 'E' : 'D'),
11778 t->step_count, t->pass_count);
e8ba3115
YQ
11779 /* Fast tracepoints are mostly handled by the target, but we can
11780 tell the target how big of an instruction block should be moved
11781 around. */
11782 if (b->type == bp_fast_tracepoint)
11783 {
11784 /* Only test for support at download time; we may not know
11785 target capabilities at definition time. */
11786 if (remote_supports_fast_tracepoints ())
35b1e5cc 11787 {
6b940e6a
PL
11788 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11789 NULL))
bba74b36 11790 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11791 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11792 else
e8ba3115
YQ
11793 /* If it passed validation at definition but fails now,
11794 something is very wrong. */
11795 internal_error (__FILE__, __LINE__,
11796 _("Fast tracepoint not "
11797 "valid during download"));
35b1e5cc 11798 }
e8ba3115
YQ
11799 else
11800 /* Fast tracepoints are functionally identical to regular
11801 tracepoints, so don't take lack of support as a reason to
11802 give up on the trace run. */
11803 warning (_("Target does not support fast tracepoints, "
11804 "downloading %d as regular tracepoint"), b->number);
11805 }
11806 else if (b->type == bp_static_tracepoint)
11807 {
11808 /* Only test for support at download time; we may not know
11809 target capabilities at definition time. */
11810 if (remote_supports_static_tracepoints ())
0fb4aa4b 11811 {
e8ba3115 11812 struct static_tracepoint_marker marker;
0fb4aa4b 11813
e8ba3115
YQ
11814 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11815 strcat (buf, ":S");
0fb4aa4b 11816 else
e8ba3115 11817 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11818 }
e8ba3115
YQ
11819 else
11820 /* Fast tracepoints are functionally identical to regular
11821 tracepoints, so don't take lack of support as a reason
11822 to give up on the trace run. */
11823 error (_("Target does not support static tracepoints"));
11824 }
11825 /* If the tracepoint has a conditional, make it into an agent
11826 expression and append to the definition. */
11827 if (loc->cond)
11828 {
11829 /* Only test support at download time, we may not know target
11830 capabilities at definition time. */
11831 if (remote_supports_cond_tracepoints ())
35b1e5cc 11832 {
e8ba3115
YQ
11833 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11834 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11835 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11836 aexpr->len);
e8ba3115
YQ
11837 pkt = buf + strlen (buf);
11838 for (ndx = 0; ndx < aexpr->len; ++ndx)
11839 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11840 *pkt = '\0';
11841 do_cleanups (aexpr_chain);
35b1e5cc 11842 }
e8ba3115
YQ
11843 else
11844 warning (_("Target does not support conditional tracepoints, "
11845 "ignoring tp %d cond"), b->number);
11846 }
35b1e5cc 11847
d9b3f62e 11848 if (b->commands || *default_collect)
e8ba3115
YQ
11849 strcat (buf, "-");
11850 putpkt (buf);
11851 remote_get_noisy_reply (&target_buf, &target_buf_size);
11852 if (strcmp (target_buf, "OK"))
11853 error (_("Target does not support tracepoints."));
35b1e5cc 11854
e8ba3115
YQ
11855 /* do_single_steps (t); */
11856 if (tdp_actions)
11857 {
11858 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11859 {
e8ba3115 11860 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11861 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11862 b->number, addrbuf, /* address */
11863 tdp_actions[ndx],
11864 ((tdp_actions[ndx + 1] || stepping_actions)
11865 ? '-' : 0));
e8ba3115
YQ
11866 putpkt (buf);
11867 remote_get_noisy_reply (&target_buf,
11868 &target_buf_size);
11869 if (strcmp (target_buf, "OK"))
11870 error (_("Error on target while setting tracepoints."));
35b1e5cc 11871 }
e8ba3115
YQ
11872 }
11873 if (stepping_actions)
11874 {
11875 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11876 {
e8ba3115 11877 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11878 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11879 b->number, addrbuf, /* address */
11880 ((ndx == 0) ? "S" : ""),
11881 stepping_actions[ndx],
11882 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11883 putpkt (buf);
11884 remote_get_noisy_reply (&target_buf,
11885 &target_buf_size);
11886 if (strcmp (target_buf, "OK"))
11887 error (_("Error on target while setting tracepoints."));
35b1e5cc 11888 }
e8ba3115 11889 }
409873ef 11890
4082afcc 11891 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11892 {
f00aae0f 11893 if (b->location != NULL)
409873ef 11894 {
e8ba3115 11895 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11896 encode_source_string (b->number, loc->address, "at",
11897 event_location_to_string (b->location),
11898 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11899 putpkt (buf);
11900 remote_get_noisy_reply (&target_buf, &target_buf_size);
11901 if (strcmp (target_buf, "OK"))
11902 warning (_("Target does not support source download."));
409873ef 11903 }
e8ba3115
YQ
11904 if (b->cond_string)
11905 {
11906 strcpy (buf, "QTDPsrc:");
11907 encode_source_string (b->number, loc->address,
11908 "cond", b->cond_string, buf + strlen (buf),
11909 2048 - strlen (buf));
11910 putpkt (buf);
11911 remote_get_noisy_reply (&target_buf, &target_buf_size);
11912 if (strcmp (target_buf, "OK"))
11913 warning (_("Target does not support source download."));
11914 }
11915 remote_download_command_source (b->number, loc->address,
11916 breakpoint_commands (b));
35b1e5cc 11917 }
e8ba3115
YQ
11918
11919 do_cleanups (old_chain);
35b1e5cc
SS
11920}
11921
1e4d1764 11922static int
a52a8357 11923remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 11924{
1e51243a
PA
11925 struct remote_state *rs = get_remote_state ();
11926 struct trace_status *ts;
11927 int status;
11928
11929 /* Don't try to install tracepoints until we've relocated our
11930 symbols, and fetched and merged the target's tracepoint list with
11931 ours. */
11932 if (rs->starting_up)
11933 return 0;
11934
11935 ts = current_trace_status ();
8bd200f1 11936 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
11937
11938 if (status == -1 || !ts->running_known || !ts->running)
11939 return 0;
11940
11941 /* If we are in a tracing experiment, but remote stub doesn't support
11942 installing tracepoint in trace, we have to return. */
11943 if (!remote_supports_install_in_trace ())
11944 return 0;
11945
11946 return 1;
11947}
11948
11949
35b1e5cc 11950static void
559d2b81
TT
11951remote_download_trace_state_variable (struct target_ops *self,
11952 struct trace_state_variable *tsv)
35b1e5cc
SS
11953{
11954 struct remote_state *rs = get_remote_state ();
00bf0b85 11955 char *p;
35b1e5cc 11956
bba74b36
YQ
11957 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11958 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11959 tsv->builtin);
00bf0b85
SS
11960 p = rs->buf + strlen (rs->buf);
11961 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11962 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 11963 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 11964 *p++ = '\0';
35b1e5cc
SS
11965 putpkt (rs->buf);
11966 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11967 if (*target_buf == '\0')
11968 error (_("Target does not support this command."));
11969 if (strcmp (target_buf, "OK") != 0)
11970 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
11971}
11972
d248b706 11973static void
46670d57
TT
11974remote_enable_tracepoint (struct target_ops *self,
11975 struct bp_location *location)
d248b706
KY
11976{
11977 struct remote_state *rs = get_remote_state ();
11978 char addr_buf[40];
11979
11980 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11981 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11982 location->owner->number, addr_buf);
d248b706
KY
11983 putpkt (rs->buf);
11984 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11985 if (*rs->buf == '\0')
11986 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11987 if (strcmp (rs->buf, "OK") != 0)
11988 error (_("Error on target while enabling tracepoint."));
11989}
11990
11991static void
780b049c
TT
11992remote_disable_tracepoint (struct target_ops *self,
11993 struct bp_location *location)
d248b706
KY
11994{
11995 struct remote_state *rs = get_remote_state ();
11996 char addr_buf[40];
11997
11998 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11999 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12000 location->owner->number, addr_buf);
d248b706
KY
12001 putpkt (rs->buf);
12002 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12003 if (*rs->buf == '\0')
12004 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12005 if (strcmp (rs->buf, "OK") != 0)
12006 error (_("Error on target while disabling tracepoint."));
12007}
12008
35b1e5cc 12009static void
583f9a86 12010remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12011{
12012 asection *s;
81b9b86e 12013 bfd *abfd = NULL;
35b1e5cc 12014 bfd_size_type size;
608bcef2 12015 bfd_vma vma;
35b1e5cc 12016 int anysecs = 0;
c2fa21f1 12017 int offset = 0;
35b1e5cc
SS
12018
12019 if (!exec_bfd)
12020 return; /* No information to give. */
12021
12022 strcpy (target_buf, "QTro");
9779ab84 12023 offset = strlen (target_buf);
35b1e5cc
SS
12024 for (s = exec_bfd->sections; s; s = s->next)
12025 {
12026 char tmp1[40], tmp2[40];
c2fa21f1 12027 int sec_length;
35b1e5cc
SS
12028
12029 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12030 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12031 (s->flags & SEC_READONLY) == 0)
12032 continue;
12033
12034 anysecs = 1;
81b9b86e 12035 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12036 size = bfd_get_section_size (s);
608bcef2
HZ
12037 sprintf_vma (tmp1, vma);
12038 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12039 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12040 if (offset + sec_length + 1 > target_buf_size)
12041 {
4082afcc 12042 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12043 warning (_("\
c2fa21f1
HZ
12044Too many sections for read-only sections definition packet."));
12045 break;
12046 }
bba74b36
YQ
12047 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12048 tmp1, tmp2);
c2fa21f1 12049 offset += sec_length;
35b1e5cc
SS
12050 }
12051 if (anysecs)
12052 {
12053 putpkt (target_buf);
12054 getpkt (&target_buf, &target_buf_size, 0);
12055 }
12056}
12057
12058static void
e2d1aae3 12059remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12060{
12061 putpkt ("QTStart");
12062 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12063 if (*target_buf == '\0')
12064 error (_("Target does not support this command."));
12065 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12066 error (_("Bogus reply from target: %s"), target_buf);
12067}
12068
12069static int
8bd200f1 12070remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12071{
953b98d1 12072 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12073 char *p = NULL;
0df8b418 12074 /* FIXME we need to get register block size some other way. */
00bf0b85 12075 extern int trace_regblock_size;
bd3eecc3
PA
12076 enum packet_result result;
12077
4082afcc 12078 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12079 return -1;
a744cf53 12080
00bf0b85
SS
12081 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12082
049dc89b
JK
12083 putpkt ("qTStatus");
12084
492d29ea 12085 TRY
67f41397
JK
12086 {
12087 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12088 }
492d29ea 12089 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12090 {
598d3636
JK
12091 if (ex.error != TARGET_CLOSE_ERROR)
12092 {
12093 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12094 return -1;
12095 }
12096 throw_exception (ex);
67f41397 12097 }
492d29ea 12098 END_CATCH
00bf0b85 12099
bd3eecc3
PA
12100 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12101
00bf0b85 12102 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12103 if (result == PACKET_UNKNOWN)
00bf0b85 12104 return -1;
35b1e5cc 12105
00bf0b85 12106 /* We're working with a live target. */
f5911ea1 12107 ts->filename = NULL;
00bf0b85 12108
00bf0b85 12109 if (*p++ != 'T')
35b1e5cc
SS
12110 error (_("Bogus trace status reply from target: %s"), target_buf);
12111
84cebc4a
YQ
12112 /* Function 'parse_trace_status' sets default value of each field of
12113 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12114 parse_trace_status (p, ts);
12115
12116 return ts->running;
35b1e5cc
SS
12117}
12118
70221824 12119static void
db90e85c 12120remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12121 struct uploaded_tp *utp)
12122{
12123 struct remote_state *rs = get_remote_state ();
f196051f
SS
12124 char *reply;
12125 struct bp_location *loc;
12126 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12127 size_t size = get_remote_packet_size ();
f196051f
SS
12128
12129 if (tp)
12130 {
12131 tp->base.hit_count = 0;
12132 tp->traceframe_usage = 0;
12133 for (loc = tp->base.loc; loc; loc = loc->next)
12134 {
12135 /* If the tracepoint was never downloaded, don't go asking for
12136 any status. */
12137 if (tp->number_on_target == 0)
12138 continue;
bba74b36
YQ
12139 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12140 phex_nz (loc->address, 0));
f196051f
SS
12141 putpkt (rs->buf);
12142 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12143 if (reply && *reply)
12144 {
12145 if (*reply == 'V')
12146 parse_tracepoint_status (reply + 1, bp, utp);
12147 }
12148 }
12149 }
12150 else if (utp)
12151 {
12152 utp->hit_count = 0;
12153 utp->traceframe_usage = 0;
bba74b36
YQ
12154 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12155 phex_nz (utp->addr, 0));
f196051f
SS
12156 putpkt (rs->buf);
12157 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12158 if (reply && *reply)
12159 {
12160 if (*reply == 'V')
12161 parse_tracepoint_status (reply + 1, bp, utp);
12162 }
12163 }
12164}
12165
35b1e5cc 12166static void
74499f1b 12167remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12168{
12169 putpkt ("QTStop");
12170 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12171 if (*target_buf == '\0')
12172 error (_("Target does not support this command."));
12173 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12174 error (_("Bogus reply from target: %s"), target_buf);
12175}
12176
12177static int
bd4c6793
TT
12178remote_trace_find (struct target_ops *self,
12179 enum trace_find_type type, int num,
cc5925ad 12180 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12181 int *tpp)
12182{
12183 struct remote_state *rs = get_remote_state ();
bba74b36 12184 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12185 char *p, *reply;
12186 int target_frameno = -1, target_tracept = -1;
12187
e6e4e701
PA
12188 /* Lookups other than by absolute frame number depend on the current
12189 trace selected, so make sure it is correct on the remote end
12190 first. */
12191 if (type != tfind_number)
12192 set_remote_traceframe ();
12193
35b1e5cc
SS
12194 p = rs->buf;
12195 strcpy (p, "QTFrame:");
12196 p = strchr (p, '\0');
12197 switch (type)
12198 {
12199 case tfind_number:
bba74b36 12200 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12201 break;
12202 case tfind_pc:
bba74b36 12203 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12204 break;
12205 case tfind_tp:
bba74b36 12206 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12207 break;
12208 case tfind_range:
bba74b36
YQ
12209 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12210 phex_nz (addr2, 0));
35b1e5cc
SS
12211 break;
12212 case tfind_outside:
bba74b36
YQ
12213 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12214 phex_nz (addr2, 0));
35b1e5cc
SS
12215 break;
12216 default:
9b20d036 12217 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12218 }
12219
12220 putpkt (rs->buf);
2f65bcb7 12221 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12222 if (*reply == '\0')
12223 error (_("Target does not support this command."));
35b1e5cc
SS
12224
12225 while (reply && *reply)
12226 switch (*reply)
12227 {
12228 case 'F':
f197e0f1
VP
12229 p = ++reply;
12230 target_frameno = (int) strtol (p, &reply, 16);
12231 if (reply == p)
12232 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12233 /* Don't update our remote traceframe number cache on failure
12234 to select a remote traceframe. */
f197e0f1
VP
12235 if (target_frameno == -1)
12236 return -1;
35b1e5cc
SS
12237 break;
12238 case 'T':
f197e0f1
VP
12239 p = ++reply;
12240 target_tracept = (int) strtol (p, &reply, 16);
12241 if (reply == p)
12242 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12243 break;
12244 case 'O': /* "OK"? */
12245 if (reply[1] == 'K' && reply[2] == '\0')
12246 reply += 2;
12247 else
12248 error (_("Bogus reply from target: %s"), reply);
12249 break;
12250 default:
12251 error (_("Bogus reply from target: %s"), reply);
12252 }
12253 if (tpp)
12254 *tpp = target_tracept;
e6e4e701 12255
262e1174 12256 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12257 return target_frameno;
12258}
12259
12260static int
4011015b
TT
12261remote_get_trace_state_variable_value (struct target_ops *self,
12262 int tsvnum, LONGEST *val)
35b1e5cc
SS
12263{
12264 struct remote_state *rs = get_remote_state ();
12265 char *reply;
12266 ULONGEST uval;
12267
e6e4e701
PA
12268 set_remote_traceframe ();
12269
bba74b36 12270 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12271 putpkt (rs->buf);
12272 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12273 if (reply && *reply)
12274 {
12275 if (*reply == 'V')
12276 {
12277 unpack_varlen_hex (reply + 1, &uval);
12278 *val = (LONGEST) uval;
12279 return 1;
12280 }
12281 }
12282 return 0;
12283}
12284
00bf0b85 12285static int
dc3decaf 12286remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12287{
12288 struct remote_state *rs = get_remote_state ();
12289 char *p, *reply;
12290
12291 p = rs->buf;
12292 strcpy (p, "QTSave:");
12293 p += strlen (p);
12294 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12295 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12296 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12297 *p++ = '\0';
12298 putpkt (rs->buf);
ad91cd99 12299 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12300 if (*reply == '\0')
ad91cd99
PA
12301 error (_("Target does not support this command."));
12302 if (strcmp (reply, "OK") != 0)
12303 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12304 return 0;
12305}
12306
12307/* This is basically a memory transfer, but needs to be its own packet
12308 because we don't know how the target actually organizes its trace
12309 memory, plus we want to be able to ask for as much as possible, but
12310 not be unhappy if we don't get as much as we ask for. */
12311
12312static LONGEST
88ee6f45
TT
12313remote_get_raw_trace_data (struct target_ops *self,
12314 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12315{
12316 struct remote_state *rs = get_remote_state ();
12317 char *reply;
12318 char *p;
12319 int rslt;
12320
12321 p = rs->buf;
12322 strcpy (p, "qTBuffer:");
12323 p += strlen (p);
12324 p += hexnumstr (p, offset);
12325 *p++ = ',';
12326 p += hexnumstr (p, len);
12327 *p++ = '\0';
12328
12329 putpkt (rs->buf);
12330 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12331 if (reply && *reply)
12332 {
12333 /* 'l' by itself means we're at the end of the buffer and
12334 there is nothing more to get. */
12335 if (*reply == 'l')
12336 return 0;
12337
12338 /* Convert the reply into binary. Limit the number of bytes to
12339 convert according to our passed-in buffer size, rather than
12340 what was returned in the packet; if the target is
12341 unexpectedly generous and gives us a bigger reply than we
12342 asked for, we don't want to crash. */
12343 rslt = hex2bin (target_buf, buf, len);
12344 return rslt;
12345 }
12346
12347 /* Something went wrong, flag as an error. */
12348 return -1;
12349}
12350
35b1e5cc 12351static void
37b25738 12352remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12353{
12354 struct remote_state *rs = get_remote_state ();
12355
4082afcc 12356 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12357 {
ad91cd99
PA
12358 char *reply;
12359
bba74b36 12360 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12361 putpkt (rs->buf);
ad91cd99
PA
12362 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12363 if (*reply == '\0')
33da3f1c 12364 error (_("Target does not support this command."));
ad91cd99
PA
12365 if (strcmp (reply, "OK") != 0)
12366 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12367 }
12368 else if (val)
12369 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12370}
12371
dc146f7c
VP
12372static int
12373remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12374{
12375 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12376
fe978cb0
PA
12377 if (info && info->priv)
12378 return info->priv->core;
dc146f7c
VP
12379 return -1;
12380}
12381
4daf5ac0 12382static void
736d5b1f 12383remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12384{
12385 struct remote_state *rs = get_remote_state ();
ad91cd99 12386 char *reply;
4daf5ac0 12387
bba74b36 12388 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12389 putpkt (rs->buf);
ad91cd99
PA
12390 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12391 if (*reply == '\0')
4daf5ac0 12392 error (_("Target does not support this command."));
ad91cd99
PA
12393 if (strcmp (reply, "OK") != 0)
12394 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12395}
12396
b3b9301e 12397static struct traceframe_info *
a893e81f 12398remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12399{
12400 char *text;
12401
12402 text = target_read_stralloc (&current_target,
12403 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12404 if (text != NULL)
12405 {
12406 struct traceframe_info *info;
12407 struct cleanup *back_to = make_cleanup (xfree, text);
12408
12409 info = parse_traceframe_info (text);
12410 do_cleanups (back_to);
12411 return info;
12412 }
12413
12414 return NULL;
12415}
12416
405f8e94
SS
12417/* Handle the qTMinFTPILen packet. Returns the minimum length of
12418 instruction on which a fast tracepoint may be placed. Returns -1
12419 if the packet is not supported, and 0 if the minimum instruction
12420 length is unknown. */
12421
12422static int
0e67620a 12423remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12424{
12425 struct remote_state *rs = get_remote_state ();
12426 char *reply;
12427
e886a173
PA
12428 /* If we're not debugging a process yet, the IPA can't be
12429 loaded. */
12430 if (!target_has_execution)
12431 return 0;
12432
12433 /* Make sure the remote is pointing at the right process. */
12434 set_general_process ();
12435
bba74b36 12436 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12437 putpkt (rs->buf);
12438 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12439 if (*reply == '\0')
12440 return -1;
12441 else
12442 {
12443 ULONGEST min_insn_len;
12444
12445 unpack_varlen_hex (reply, &min_insn_len);
12446
12447 return (int) min_insn_len;
12448 }
12449}
12450
f6f899bf 12451static void
4da384be 12452remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12453{
4082afcc 12454 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12455 {
12456 struct remote_state *rs = get_remote_state ();
12457 char *buf = rs->buf;
12458 char *endbuf = rs->buf + get_remote_packet_size ();
12459 enum packet_result result;
12460
12461 gdb_assert (val >= 0 || val == -1);
12462 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12463 /* Send -1 as literal "-1" to avoid host size dependency. */
12464 if (val < 0)
12465 {
12466 *buf++ = '-';
12467 buf += hexnumstr (buf, (ULONGEST) -val);
12468 }
12469 else
12470 buf += hexnumstr (buf, (ULONGEST) val);
12471
12472 putpkt (rs->buf);
12473 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12474 result = packet_ok (rs->buf,
12475 &remote_protocol_packets[PACKET_QTBuffer_size]);
12476
12477 if (result != PACKET_OK)
12478 warning (_("Bogus reply from target: %s"), rs->buf);
12479 }
12480}
12481
f196051f 12482static int
d9e68a2c
TT
12483remote_set_trace_notes (struct target_ops *self,
12484 const char *user, const char *notes,
ca623f82 12485 const char *stop_notes)
f196051f
SS
12486{
12487 struct remote_state *rs = get_remote_state ();
12488 char *reply;
12489 char *buf = rs->buf;
12490 char *endbuf = rs->buf + get_remote_packet_size ();
12491 int nbytes;
12492
12493 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12494 if (user)
12495 {
12496 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12497 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12498 buf += 2 * nbytes;
12499 *buf++ = ';';
12500 }
12501 if (notes)
12502 {
12503 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12504 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12505 buf += 2 * nbytes;
12506 *buf++ = ';';
12507 }
12508 if (stop_notes)
12509 {
12510 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12511 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12512 buf += 2 * nbytes;
12513 *buf++ = ';';
12514 }
12515 /* Ensure the buffer is terminated. */
12516 *buf = '\0';
12517
12518 putpkt (rs->buf);
12519 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12520 if (*reply == '\0')
12521 return 0;
12522
12523 if (strcmp (reply, "OK") != 0)
12524 error (_("Bogus reply from target: %s"), reply);
12525
12526 return 1;
12527}
12528
d1feda86 12529static int
2c152180 12530remote_use_agent (struct target_ops *self, int use)
d1feda86 12531{
4082afcc 12532 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12533 {
12534 struct remote_state *rs = get_remote_state ();
12535
12536 /* If the stub supports QAgent. */
bba74b36 12537 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12538 putpkt (rs->buf);
12539 getpkt (&rs->buf, &rs->buf_size, 0);
12540
12541 if (strcmp (rs->buf, "OK") == 0)
12542 {
12543 use_agent = use;
12544 return 1;
12545 }
12546 }
12547
12548 return 0;
12549}
12550
12551static int
fe38f897 12552remote_can_use_agent (struct target_ops *self)
d1feda86 12553{
4082afcc 12554 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12555}
12556
9accd112
MM
12557struct btrace_target_info
12558{
12559 /* The ptid of the traced thread. */
12560 ptid_t ptid;
f4abbc16
MM
12561
12562 /* The obtained branch trace configuration. */
12563 struct btrace_config conf;
9accd112
MM
12564};
12565
f4abbc16
MM
12566/* Reset our idea of our target's btrace configuration. */
12567
12568static void
12569remote_btrace_reset (void)
12570{
12571 struct remote_state *rs = get_remote_state ();
12572
12573 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12574}
12575
9accd112
MM
12576/* Check whether the target supports branch tracing. */
12577
12578static int
043c3577 12579remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12580{
4082afcc 12581 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12582 return 0;
4082afcc 12583 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12584 return 0;
12585
043c3577
MM
12586 switch (format)
12587 {
12588 case BTRACE_FORMAT_NONE:
12589 return 0;
12590
12591 case BTRACE_FORMAT_BTS:
12592 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12593
12594 case BTRACE_FORMAT_PT:
12595 /* The trace is decoded on the host. Even if our target supports it,
12596 we still need to have libipt to decode the trace. */
12597#if defined (HAVE_LIBIPT)
12598 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12599#else /* !defined (HAVE_LIBIPT) */
12600 return 0;
12601#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12602 }
12603
12604 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12605}
12606
f4abbc16
MM
12607/* Synchronize the configuration with the target. */
12608
12609static void
12610btrace_sync_conf (const struct btrace_config *conf)
12611{
d33501a5
MM
12612 struct packet_config *packet;
12613 struct remote_state *rs;
12614 char *buf, *pos, *endbuf;
12615
12616 rs = get_remote_state ();
12617 buf = rs->buf;
12618 endbuf = buf + get_remote_packet_size ();
12619
12620 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12621 if (packet_config_support (packet) == PACKET_ENABLE
12622 && conf->bts.size != rs->btrace_config.bts.size)
12623 {
12624 pos = buf;
12625 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12626 conf->bts.size);
12627
12628 putpkt (buf);
12629 getpkt (&buf, &rs->buf_size, 0);
12630
12631 if (packet_ok (buf, packet) == PACKET_ERROR)
12632 {
12633 if (buf[0] == 'E' && buf[1] == '.')
12634 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12635 else
12636 error (_("Failed to configure the BTS buffer size."));
12637 }
12638
12639 rs->btrace_config.bts.size = conf->bts.size;
12640 }
b20a6524
MM
12641
12642 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12643 if (packet_config_support (packet) == PACKET_ENABLE
12644 && conf->pt.size != rs->btrace_config.pt.size)
12645 {
12646 pos = buf;
12647 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12648 conf->pt.size);
12649
12650 putpkt (buf);
12651 getpkt (&buf, &rs->buf_size, 0);
12652
12653 if (packet_ok (buf, packet) == PACKET_ERROR)
12654 {
12655 if (buf[0] == 'E' && buf[1] == '.')
12656 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12657 else
12658 error (_("Failed to configure the trace buffer size."));
12659 }
12660
12661 rs->btrace_config.pt.size = conf->pt.size;
12662 }
f4abbc16
MM
12663}
12664
12665/* Read the current thread's btrace configuration from the target and
12666 store it into CONF. */
12667
12668static void
12669btrace_read_config (struct btrace_config *conf)
12670{
12671 char *xml;
12672
12673 xml = target_read_stralloc (&current_target,
b20a6524 12674 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12675 if (xml != NULL)
12676 {
12677 struct cleanup *cleanup;
12678
12679 cleanup = make_cleanup (xfree, xml);
12680 parse_xml_btrace_conf (conf, xml);
12681 do_cleanups (cleanup);
12682 }
12683}
12684
9accd112
MM
12685/* Enable branch tracing. */
12686
12687static struct btrace_target_info *
f4abbc16
MM
12688remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12689 const struct btrace_config *conf)
9accd112
MM
12690{
12691 struct btrace_target_info *tinfo = NULL;
b20a6524 12692 struct packet_config *packet = NULL;
9accd112
MM
12693 struct remote_state *rs = get_remote_state ();
12694 char *buf = rs->buf;
12695 char *endbuf = rs->buf + get_remote_packet_size ();
12696
b20a6524
MM
12697 switch (conf->format)
12698 {
12699 case BTRACE_FORMAT_BTS:
12700 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12701 break;
12702
12703 case BTRACE_FORMAT_PT:
12704 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12705 break;
12706 }
12707
12708 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12709 error (_("Target does not support branch tracing."));
12710
f4abbc16
MM
12711 btrace_sync_conf (conf);
12712
9accd112
MM
12713 set_general_thread (ptid);
12714
12715 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12716 putpkt (rs->buf);
12717 getpkt (&rs->buf, &rs->buf_size, 0);
12718
12719 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12720 {
12721 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12722 error (_("Could not enable branch tracing for %s: %s"),
12723 target_pid_to_str (ptid), rs->buf + 2);
12724 else
12725 error (_("Could not enable branch tracing for %s."),
12726 target_pid_to_str (ptid));
12727 }
12728
8d749320 12729 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12730 tinfo->ptid = ptid;
12731
f4abbc16
MM
12732 /* If we fail to read the configuration, we lose some information, but the
12733 tracing itself is not impacted. */
492d29ea
PA
12734 TRY
12735 {
12736 btrace_read_config (&tinfo->conf);
12737 }
12738 CATCH (err, RETURN_MASK_ERROR)
12739 {
12740 if (err.message != NULL)
12741 warning ("%s", err.message);
12742 }
12743 END_CATCH
f4abbc16 12744
9accd112
MM
12745 return tinfo;
12746}
12747
12748/* Disable branch tracing. */
12749
12750static void
25e95349
TT
12751remote_disable_btrace (struct target_ops *self,
12752 struct btrace_target_info *tinfo)
9accd112
MM
12753{
12754 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12755 struct remote_state *rs = get_remote_state ();
12756 char *buf = rs->buf;
12757 char *endbuf = rs->buf + get_remote_packet_size ();
12758
4082afcc 12759 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12760 error (_("Target does not support branch tracing."));
12761
12762 set_general_thread (tinfo->ptid);
12763
12764 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12765 putpkt (rs->buf);
12766 getpkt (&rs->buf, &rs->buf_size, 0);
12767
12768 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12769 {
12770 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12771 error (_("Could not disable branch tracing for %s: %s"),
12772 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12773 else
12774 error (_("Could not disable branch tracing for %s."),
12775 target_pid_to_str (tinfo->ptid));
12776 }
12777
12778 xfree (tinfo);
12779}
12780
12781/* Teardown branch tracing. */
12782
12783static void
1777056d
TT
12784remote_teardown_btrace (struct target_ops *self,
12785 struct btrace_target_info *tinfo)
9accd112
MM
12786{
12787 /* We must not talk to the target during teardown. */
12788 xfree (tinfo);
12789}
12790
12791/* Read the branch trace. */
12792
969c39fb 12793static enum btrace_error
39c49f83 12794remote_read_btrace (struct target_ops *self,
734b0e4b 12795 struct btrace_data *btrace,
969c39fb 12796 struct btrace_target_info *tinfo,
9accd112
MM
12797 enum btrace_read_type type)
12798{
12799 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12800 struct remote_state *rs = get_remote_state ();
969c39fb 12801 struct cleanup *cleanup;
9accd112
MM
12802 const char *annex;
12803 char *xml;
12804
4082afcc 12805 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12806 error (_("Target does not support branch tracing."));
12807
12808#if !defined(HAVE_LIBEXPAT)
12809 error (_("Cannot process branch tracing result. XML parsing not supported."));
12810#endif
12811
12812 switch (type)
12813 {
864089d2 12814 case BTRACE_READ_ALL:
9accd112
MM
12815 annex = "all";
12816 break;
864089d2 12817 case BTRACE_READ_NEW:
9accd112
MM
12818 annex = "new";
12819 break;
969c39fb
MM
12820 case BTRACE_READ_DELTA:
12821 annex = "delta";
12822 break;
9accd112
MM
12823 default:
12824 internal_error (__FILE__, __LINE__,
12825 _("Bad branch tracing read type: %u."),
12826 (unsigned int) type);
12827 }
12828
12829 xml = target_read_stralloc (&current_target,
b20a6524 12830 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12831 if (xml == NULL)
12832 return BTRACE_ERR_UNKNOWN;
9accd112 12833
969c39fb 12834 cleanup = make_cleanup (xfree, xml);
734b0e4b 12835 parse_xml_btrace (btrace, xml);
969c39fb 12836 do_cleanups (cleanup);
9accd112 12837
969c39fb 12838 return BTRACE_ERR_NONE;
9accd112
MM
12839}
12840
f4abbc16
MM
12841static const struct btrace_config *
12842remote_btrace_conf (struct target_ops *self,
12843 const struct btrace_target_info *tinfo)
12844{
12845 return &tinfo->conf;
12846}
12847
ced63ec0 12848static int
5436ff03 12849remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12850{
4082afcc
PA
12851 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12852 == PACKET_ENABLE);
ced63ec0
GB
12853}
12854
9dd130a0
TT
12855/* Implementation of to_load. */
12856
12857static void
9cbe5fff 12858remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12859{
12860 generic_load (name, from_tty);
12861}
12862
c78fa86a
GB
12863/* Accepts an integer PID; returns a string representing a file that
12864 can be opened on the remote side to get the symbols for the child
12865 process. Returns NULL if the operation is not supported. */
12866
12867static char *
12868remote_pid_to_exec_file (struct target_ops *self, int pid)
12869{
12870 static char *filename = NULL;
835205d0
GB
12871 struct inferior *inf;
12872 char *annex = NULL;
c78fa86a
GB
12873
12874 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12875 return NULL;
12876
12877 if (filename != NULL)
12878 xfree (filename);
12879
835205d0
GB
12880 inf = find_inferior_pid (pid);
12881 if (inf == NULL)
12882 internal_error (__FILE__, __LINE__,
12883 _("not currently attached to process %d"), pid);
12884
12885 if (!inf->fake_pid_p)
12886 {
12887 const int annex_size = 9;
12888
224c3ddb 12889 annex = (char *) alloca (annex_size);
835205d0
GB
12890 xsnprintf (annex, annex_size, "%x", pid);
12891 }
12892
c78fa86a
GB
12893 filename = target_read_stralloc (&current_target,
12894 TARGET_OBJECT_EXEC_FILE, annex);
12895
12896 return filename;
12897}
12898
750ce8d1
YQ
12899/* Implement the to_can_do_single_step target_ops method. */
12900
12901static int
12902remote_can_do_single_step (struct target_ops *ops)
12903{
12904 /* We can only tell whether target supports single step or not by
12905 supported s and S vCont actions if the stub supports vContSupported
12906 feature. If the stub doesn't support vContSupported feature,
12907 we have conservatively to think target doesn't supports single
12908 step. */
12909 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12910 {
12911 struct remote_state *rs = get_remote_state ();
12912
12913 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12914 remote_vcont_probe (rs);
12915
12916 return rs->supports_vCont.s && rs->supports_vCont.S;
12917 }
12918 else
12919 return 0;
12920}
12921
c906108c 12922static void
fba45db2 12923init_remote_ops (void)
c906108c 12924{
c5aa993b 12925 remote_ops.to_shortname = "remote";
c906108c 12926 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 12927 remote_ops.to_doc =
c906108c 12928 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
12929Specify the serial device it is connected to\n\
12930(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
12931 remote_ops.to_open = remote_open;
12932 remote_ops.to_close = remote_close;
c906108c 12933 remote_ops.to_detach = remote_detach;
6ad8ae5c 12934 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 12935 remote_ops.to_resume = remote_resume;
c906108c
SS
12936 remote_ops.to_wait = remote_wait;
12937 remote_ops.to_fetch_registers = remote_fetch_registers;
12938 remote_ops.to_store_registers = remote_store_registers;
12939 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 12940 remote_ops.to_files_info = remote_files_info;
c906108c
SS
12941 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12942 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
12943 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12944 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12945 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12946 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
12947 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12948 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
12949 remote_ops.to_watchpoint_addr_within_range =
12950 remote_watchpoint_addr_within_range;
3c3bea1c
GS
12951 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12952 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12953 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
12954 remote_ops.to_region_ok_for_hw_watchpoint
12955 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
12956 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12957 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 12958 remote_ops.to_kill = remote_kill;
9dd130a0 12959 remote_ops.to_load = remote_load;
c906108c 12960 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 12961 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 12962 remote_ops.to_program_signals = remote_program_signals;
c906108c 12963 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 12964 remote_ops.to_thread_name = remote_thread_name;
e8032dde 12965 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 12966 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 12967 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 12968 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 12969 remote_ops.to_stop = remote_stop;
bfedc46a 12970 remote_ops.to_interrupt = remote_interrupt;
abc56d60 12971 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
4b8a223f 12972 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 12973 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 12974 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 12975 remote_ops.to_log_command = serial_log_command;
38691318 12976 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 12977 remote_ops.to_stratum = process_stratum;
c35b1492
PA
12978 remote_ops.to_has_all_memory = default_child_has_all_memory;
12979 remote_ops.to_has_memory = default_child_has_memory;
12980 remote_ops.to_has_stack = default_child_has_stack;
12981 remote_ops.to_has_registers = default_child_has_registers;
12982 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 12983 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 12984 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 12985 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 12986 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
12987 remote_ops.to_flash_erase = remote_flash_erase;
12988 remote_ops.to_flash_done = remote_flash_done;
29709017 12989 remote_ops.to_read_description = remote_read_description;
08388c79 12990 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
12991 remote_ops.to_can_async_p = remote_can_async_p;
12992 remote_ops.to_is_async_p = remote_is_async_p;
12993 remote_ops.to_async = remote_async;
65706a29 12994 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 12995 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
12996 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12997 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 12998 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 12999 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13000 remote_ops.to_supports_disable_randomization
13001 = remote_supports_disable_randomization;
4bd7dc42 13002 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13003 remote_ops.to_fileio_open = remote_hostio_open;
13004 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13005 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13006 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13007 remote_ops.to_fileio_close = remote_hostio_close;
13008 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13009 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13010 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13011 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13012 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13013 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13014 remote_ops.to_trace_init = remote_trace_init;
13015 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13016 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13017 remote_ops.to_download_trace_state_variable
13018 = remote_download_trace_state_variable;
d248b706
KY
13019 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13020 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13021 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13022 remote_ops.to_trace_start = remote_trace_start;
13023 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13024 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13025 remote_ops.to_trace_stop = remote_trace_stop;
13026 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13027 remote_ops.to_get_trace_state_variable_value
13028 = remote_get_trace_state_variable_value;
00bf0b85
SS
13029 remote_ops.to_save_trace_data = remote_save_trace_data;
13030 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13031 remote_ops.to_upload_trace_state_variables
13032 = remote_upload_trace_state_variables;
00bf0b85 13033 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13034 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13035 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13036 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13037 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13038 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13039 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13040 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13041 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13042 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13043 remote_ops.to_static_tracepoint_marker_at
13044 = remote_static_tracepoint_marker_at;
13045 remote_ops.to_static_tracepoint_markers_by_strid
13046 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13047 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13048 remote_ops.to_use_agent = remote_use_agent;
13049 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13050 remote_ops.to_supports_btrace = remote_supports_btrace;
13051 remote_ops.to_enable_btrace = remote_enable_btrace;
13052 remote_ops.to_disable_btrace = remote_disable_btrace;
13053 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13054 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13055 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13056 remote_ops.to_augmented_libraries_svr4_read =
13057 remote_augmented_libraries_svr4_read;
c906108c
SS
13058}
13059
13060/* Set up the extended remote vector by making a copy of the standard
13061 remote vector and adding to it. */
13062
13063static void
fba45db2 13064init_extended_remote_ops (void)
c906108c
SS
13065{
13066 extended_remote_ops = remote_ops;
13067
0f71a2f6 13068 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13069 extended_remote_ops.to_longname =
c906108c 13070 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13071 extended_remote_ops.to_doc =
c906108c 13072 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13073Specify the serial device it is connected to (e.g. /dev/ttya).";
13074 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
13075 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13076 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
13077 extended_remote_ops.to_detach = extended_remote_detach;
13078 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13079 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 13080 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
13081 extended_remote_ops.to_supports_disable_randomization
13082 = extended_remote_supports_disable_randomization;
de0d863e 13083 extended_remote_ops.to_follow_fork = remote_follow_fork;
94585166 13084 extended_remote_ops.to_follow_exec = remote_follow_exec;
cbb8991c
DB
13085 extended_remote_ops.to_insert_fork_catchpoint
13086 = remote_insert_fork_catchpoint;
13087 extended_remote_ops.to_remove_fork_catchpoint
13088 = remote_remove_fork_catchpoint;
13089 extended_remote_ops.to_insert_vfork_catchpoint
13090 = remote_insert_vfork_catchpoint;
13091 extended_remote_ops.to_remove_vfork_catchpoint
13092 = remote_remove_vfork_catchpoint;
d46addbb
DB
13093 extended_remote_ops.to_insert_exec_catchpoint
13094 = remote_insert_exec_catchpoint;
13095 extended_remote_ops.to_remove_exec_catchpoint
13096 = remote_remove_exec_catchpoint;
0f71a2f6
JM
13097}
13098
6426a772 13099static int
6a109b6b 13100remote_can_async_p (struct target_ops *ops)
6426a772 13101{
5d93a237
TT
13102 struct remote_state *rs = get_remote_state ();
13103
c6ebd6cf 13104 if (!target_async_permitted)
75c99385
PA
13105 /* We only enable async when the user specifically asks for it. */
13106 return 0;
13107
23860348 13108 /* We're async whenever the serial device is. */
5d93a237 13109 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13110}
13111
13112static int
6a109b6b 13113remote_is_async_p (struct target_ops *ops)
6426a772 13114{
5d93a237
TT
13115 struct remote_state *rs = get_remote_state ();
13116
c6ebd6cf 13117 if (!target_async_permitted)
75c99385
PA
13118 /* We only enable async when the user specifically asks for it. */
13119 return 0;
13120
23860348 13121 /* We're async whenever the serial device is. */
5d93a237 13122 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13123}
13124
2acceee2
JM
13125/* Pass the SERIAL event on and up to the client. One day this code
13126 will be able to delay notifying the client of an event until the
23860348 13127 point where an entire packet has been received. */
2acceee2 13128
2acceee2
JM
13129static serial_event_ftype remote_async_serial_handler;
13130
6426a772 13131static void
819cc324 13132remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13133{
19ba03f4 13134 struct remote_state *rs = (struct remote_state *) context;
88b496c3 13135
2acceee2
JM
13136 /* Don't propogate error information up to the client. Instead let
13137 the client find out about the error by querying the target. */
6a3753b3 13138 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13139}
13140
74531fed
PA
13141static void
13142remote_async_inferior_event_handler (gdb_client_data data)
13143{
13144 inferior_event_handler (INF_REG_EVENT, NULL);
13145}
13146
2acceee2 13147static void
6a3753b3 13148remote_async (struct target_ops *ops, int enable)
2acceee2 13149{
5d93a237
TT
13150 struct remote_state *rs = get_remote_state ();
13151
6a3753b3 13152 if (enable)
2acceee2 13153 {
88b496c3 13154 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13155
13156 /* If there are pending events in the stop reply queue tell the
13157 event loop to process them. */
13158 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13159 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13160 /* For simplicity, below we clear the pending events token
13161 without remembering whether it is marked, so here we always
13162 mark it. If there's actually no pending notification to
13163 process, this ends up being a no-op (other than a spurious
13164 event-loop wakeup). */
13165 if (target_is_non_stop_p ())
13166 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13167 }
13168 else
b7d2e916
PA
13169 {
13170 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13171 /* If the core is disabling async, it doesn't want to be
13172 disturbed with target events. Clear all async event sources
13173 too. */
b7d2e916 13174 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13175 if (target_is_non_stop_p ())
13176 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13177 }
6426a772
JM
13178}
13179
65706a29
PA
13180/* Implementation of the to_thread_events method. */
13181
13182static void
13183remote_thread_events (struct target_ops *ops, int enable)
13184{
13185 struct remote_state *rs = get_remote_state ();
13186 size_t size = get_remote_packet_size ();
13187 char *p = rs->buf;
13188
13189 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13190 return;
13191
13192 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13193 putpkt (rs->buf);
13194 getpkt (&rs->buf, &rs->buf_size, 0);
13195
13196 switch (packet_ok (rs->buf,
13197 &remote_protocol_packets[PACKET_QThreadEvents]))
13198 {
13199 case PACKET_OK:
13200 if (strcmp (rs->buf, "OK") != 0)
13201 error (_("Remote refused setting thread events: %s"), rs->buf);
13202 break;
13203 case PACKET_ERROR:
13204 warning (_("Remote failure reply: %s"), rs->buf);
13205 break;
13206 case PACKET_UNKNOWN:
13207 break;
13208 }
13209}
13210
5a2468f5 13211static void
c2d11a7d 13212set_remote_cmd (char *args, int from_tty)
5a2468f5 13213{
635c7e8a 13214 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13215}
13216
d471ea57
AC
13217static void
13218show_remote_cmd (char *args, int from_tty)
13219{
37a105a1 13220 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13221 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13222 struct cleanup *showlist_chain;
13223 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13224 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13225
13226 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13227 for (; list != NULL; list = list->next)
13228 if (strcmp (list->name, "Z-packet") == 0)
13229 continue;
427c3a89
DJ
13230 else if (list->type == not_set_cmd)
13231 /* Alias commands are exactly like the original, except they
13232 don't have the normal type. */
13233 continue;
13234 else
37a105a1
DJ
13235 {
13236 struct cleanup *option_chain
13237 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13238
37a105a1
DJ
13239 ui_out_field_string (uiout, "name", list->name);
13240 ui_out_text (uiout, ": ");
427c3a89 13241 if (list->type == show_cmd)
5b9afe8a 13242 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
13243 else
13244 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13245 /* Close the tuple. */
13246 do_cleanups (option_chain);
13247 }
427c3a89
DJ
13248
13249 /* Close the tuple. */
13250 do_cleanups (showlist_chain);
d471ea57 13251}
5a2468f5 13252
0f71a2f6 13253
23860348 13254/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13255static void
13256remote_new_objfile (struct objfile *objfile)
13257{
5d93a237
TT
13258 struct remote_state *rs = get_remote_state ();
13259
13260 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13261 remote_check_symbols ();
dc8acb97
MS
13262}
13263
00bf0b85
SS
13264/* Pull all the tracepoints defined on the target and create local
13265 data structures representing them. We don't want to create real
13266 tracepoints yet, we don't want to mess up the user's existing
13267 collection. */
13268
13269static int
ab6617cc 13270remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13271{
00bf0b85
SS
13272 struct remote_state *rs = get_remote_state ();
13273 char *p;
d5551862 13274
00bf0b85
SS
13275 /* Ask for a first packet of tracepoint definition. */
13276 putpkt ("qTfP");
13277 getpkt (&rs->buf, &rs->buf_size, 0);
13278 p = rs->buf;
13279 while (*p && *p != 'l')
d5551862 13280 {
00bf0b85
SS
13281 parse_tracepoint_definition (p, utpp);
13282 /* Ask for another packet of tracepoint definition. */
13283 putpkt ("qTsP");
13284 getpkt (&rs->buf, &rs->buf_size, 0);
13285 p = rs->buf;
d5551862 13286 }
00bf0b85 13287 return 0;
d5551862
SS
13288}
13289
00bf0b85 13290static int
181e3713
TT
13291remote_upload_trace_state_variables (struct target_ops *self,
13292 struct uploaded_tsv **utsvp)
d5551862 13293{
00bf0b85 13294 struct remote_state *rs = get_remote_state ();
d5551862 13295 char *p;
d5551862 13296
00bf0b85
SS
13297 /* Ask for a first packet of variable definition. */
13298 putpkt ("qTfV");
d5551862
SS
13299 getpkt (&rs->buf, &rs->buf_size, 0);
13300 p = rs->buf;
00bf0b85 13301 while (*p && *p != 'l')
d5551862 13302 {
00bf0b85
SS
13303 parse_tsv_definition (p, utsvp);
13304 /* Ask for another packet of variable definition. */
13305 putpkt ("qTsV");
d5551862
SS
13306 getpkt (&rs->buf, &rs->buf_size, 0);
13307 p = rs->buf;
13308 }
00bf0b85 13309 return 0;
d5551862
SS
13310}
13311
c1e36e3e
PA
13312/* The "set/show range-stepping" show hook. */
13313
13314static void
13315show_range_stepping (struct ui_file *file, int from_tty,
13316 struct cmd_list_element *c,
13317 const char *value)
13318{
13319 fprintf_filtered (file,
13320 _("Debugger's willingness to use range stepping "
13321 "is %s.\n"), value);
13322}
13323
13324/* The "set/show range-stepping" set hook. */
13325
13326static void
13327set_range_stepping (char *ignore_args, int from_tty,
13328 struct cmd_list_element *c)
13329{
5d93a237
TT
13330 struct remote_state *rs = get_remote_state ();
13331
c1e36e3e
PA
13332 /* Whene enabling, check whether range stepping is actually
13333 supported by the target, and warn if not. */
13334 if (use_range_stepping)
13335 {
5d93a237 13336 if (rs->remote_desc != NULL)
c1e36e3e 13337 {
4082afcc 13338 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13339 remote_vcont_probe (rs);
13340
4082afcc 13341 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13342 && rs->supports_vCont.r)
13343 return;
13344 }
13345
13346 warning (_("Range stepping is not supported by the current target"));
13347 }
13348}
13349
c906108c 13350void
fba45db2 13351_initialize_remote (void)
c906108c 13352{
ea9c271d 13353 struct remote_state *rs;
9a7071a8 13354 struct cmd_list_element *cmd;
6f937416 13355 const char *cmd_name;
ea9c271d 13356
0f71a2f6 13357 /* architecture specific data */
2bc416ba 13358 remote_gdbarch_data_handle =
23860348 13359 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13360 remote_g_packet_data_handle =
13361 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13362
94585166
DB
13363 remote_pspace_data
13364 = register_program_space_data_with_cleanup (NULL,
13365 remote_pspace_data_cleanup);
13366
ea9c271d
DJ
13367 /* Initialize the per-target state. At the moment there is only one
13368 of these, not one per target. Only one target is active at a
cf792862
TT
13369 time. */
13370 remote_state = new_remote_state ();
ea9c271d 13371
c906108c
SS
13372 init_remote_ops ();
13373 add_target (&remote_ops);
13374
13375 init_extended_remote_ops ();
13376 add_target (&extended_remote_ops);
cce74817 13377
dc8acb97 13378 /* Hook into new objfile notification. */
06d3b283 13379 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13380 /* We're no longer interested in notification events of an inferior
13381 when it exits. */
13382 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13383
b803fb0f 13384 /* Set up signal handlers. */
934b9bac 13385 async_sigint_remote_token =
b803fb0f 13386 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 13387 async_sigint_remote_twice_token =
6d549500 13388 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 13389
c906108c
SS
13390#if 0
13391 init_remote_threadtests ();
13392#endif
13393
722247f1 13394 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13395 /* set/show remote ... */
d471ea57 13396
1bedd215 13397 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13398Remote protocol specific variables\n\
13399Configure various remote-protocol specific variables such as\n\
1bedd215 13400the packets being used"),
cff3e48b 13401 &remote_set_cmdlist, "set remote ",
23860348 13402 0 /* allow-unknown */, &setlist);
1bedd215 13403 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13404Remote protocol specific variables\n\
13405Configure various remote-protocol specific variables such as\n\
1bedd215 13406the packets being used"),
cff3e48b 13407 &remote_show_cmdlist, "show remote ",
23860348 13408 0 /* allow-unknown */, &showlist);
5a2468f5 13409
1a966eab
AC
13410 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13411Compare section data on target to the exec file.\n\
95cf3b38
DT
13412Argument is a single section name (default: all loaded sections).\n\
13413To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13414 &cmdlist);
13415
1a966eab
AC
13416 add_cmd ("packet", class_maintenance, packet_command, _("\
13417Send an arbitrary packet to a remote target.\n\
c906108c
SS
13418 maintenance packet TEXT\n\
13419If GDB is talking to an inferior via the GDB serial protocol, then\n\
13420this command sends the string TEXT to the inferior, and displays the\n\
13421response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13422terminating `#' character and checksum."),
c906108c
SS
13423 &maintenancelist);
13424
7915a72c
AC
13425 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13426Set whether to send break if interrupted."), _("\
13427Show whether to send break if interrupted."), _("\
13428If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13429 set_remotebreak, show_remotebreak,
e707bbc2 13430 &setlist, &showlist);
9a7071a8
JB
13431 cmd_name = "remotebreak";
13432 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13433 deprecate_cmd (cmd, "set remote interrupt-sequence");
13434 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13435 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13436 deprecate_cmd (cmd, "show remote interrupt-sequence");
13437
13438 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13439 interrupt_sequence_modes, &interrupt_sequence_mode,
13440 _("\
9a7071a8
JB
13441Set interrupt sequence to remote target."), _("\
13442Show interrupt sequence to remote target."), _("\
13443Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13444 NULL, show_interrupt_sequence,
13445 &remote_set_cmdlist,
13446 &remote_show_cmdlist);
13447
13448 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13449 &interrupt_on_connect, _("\
13450Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13451Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13452If set, interrupt sequence is sent to remote target."),
13453 NULL, NULL,
13454 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13455
23860348 13456 /* Install commands for configuring memory read/write packets. */
11cf8741 13457
1a966eab
AC
13458 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13459Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13460 &setlist);
1a966eab
AC
13461 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13462Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13463 &showlist);
13464 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13465 set_memory_write_packet_size, _("\
13466Set the maximum number of bytes per memory-write packet.\n\
13467Specify the number of bytes in a packet or 0 (zero) for the\n\
13468default packet size. The actual limit is further reduced\n\
13469dependent on the target. Specify ``fixed'' to disable the\n\
13470further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13471 &remote_set_cmdlist);
13472 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13473 set_memory_read_packet_size, _("\
13474Set the maximum number of bytes per memory-read packet.\n\
13475Specify the number of bytes in a packet or 0 (zero) for the\n\
13476default packet size. The actual limit is further reduced\n\
13477dependent on the target. Specify ``fixed'' to disable the\n\
13478further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13479 &remote_set_cmdlist);
13480 add_cmd ("memory-write-packet-size", no_class,
13481 show_memory_write_packet_size,
1a966eab 13482 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13483 &remote_show_cmdlist);
13484 add_cmd ("memory-read-packet-size", no_class,
13485 show_memory_read_packet_size,
1a966eab 13486 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13487 &remote_show_cmdlist);
c906108c 13488
b3f42336 13489 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13490 &remote_hw_watchpoint_limit, _("\
13491Set the maximum number of target hardware watchpoints."), _("\
13492Show the maximum number of target hardware watchpoints."), _("\
13493Specify a negative limit for unlimited."),
3e43a32a
MS
13494 NULL, NULL, /* FIXME: i18n: The maximum
13495 number of target hardware
13496 watchpoints is %s. */
b3f42336 13497 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13498 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13499 &remote_hw_watchpoint_length_limit, _("\
13500Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13501Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13502Specify a negative limit for unlimited."),
13503 NULL, NULL, /* FIXME: i18n: The maximum
13504 length (in bytes) of a target
13505 hardware watchpoint is %s. */
13506 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13507 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13508 &remote_hw_breakpoint_limit, _("\
13509Set the maximum number of target hardware breakpoints."), _("\
13510Show the maximum number of target hardware breakpoints."), _("\
13511Specify a negative limit for unlimited."),
3e43a32a
MS
13512 NULL, NULL, /* FIXME: i18n: The maximum
13513 number of target hardware
13514 breakpoints is %s. */
b3f42336 13515 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13516
1b493192
PA
13517 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13518 &remote_address_size, _("\
4d28ad1e
AC
13519Set the maximum size of the address (in bits) in a memory packet."), _("\
13520Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13521 NULL,
13522 NULL, /* FIXME: i18n: */
13523 &setlist, &showlist);
c906108c 13524
ca4f7f8b
PA
13525 init_all_packet_configs ();
13526
444abaca 13527 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13528 "X", "binary-download", 1);
0f71a2f6 13529
444abaca 13530 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13531 "vCont", "verbose-resume", 0);
506fb367 13532
89be2091
DJ
13533 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13534 "QPassSignals", "pass-signals", 0);
13535
9b224c5e
PA
13536 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13537 "QProgramSignals", "program-signals", 0);
13538
444abaca 13539 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13540 "qSymbol", "symbol-lookup", 0);
dc8acb97 13541
444abaca 13542 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13543 "P", "set-register", 1);
d471ea57 13544
444abaca 13545 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13546 "p", "fetch-register", 1);
b96ec7ac 13547
444abaca 13548 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13549 "Z0", "software-breakpoint", 0);
d471ea57 13550
444abaca 13551 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13552 "Z1", "hardware-breakpoint", 0);
d471ea57 13553
444abaca 13554 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13555 "Z2", "write-watchpoint", 0);
d471ea57 13556
444abaca 13557 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13558 "Z3", "read-watchpoint", 0);
d471ea57 13559
444abaca 13560 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13561 "Z4", "access-watchpoint", 0);
d471ea57 13562
0876f84a
DJ
13563 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13564 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13565
c78fa86a
GB
13566 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13567 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13568
23181151
DJ
13569 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13570 "qXfer:features:read", "target-features", 0);
13571
cfa9d6d9
DJ
13572 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13573 "qXfer:libraries:read", "library-info", 0);
13574
2268b414
JK
13575 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13576 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13577
fd79ecee
DJ
13578 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13579 "qXfer:memory-map:read", "memory-map", 0);
13580
0e7f50da
UW
13581 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13582 "qXfer:spu:read", "read-spu-object", 0);
13583
13584 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13585 "qXfer:spu:write", "write-spu-object", 0);
13586
07e059b5
VP
13587 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13588 "qXfer:osdata:read", "osdata", 0);
13589
dc146f7c
VP
13590 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13591 "qXfer:threads:read", "threads", 0);
13592
4aa995e1
PA
13593 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13594 "qXfer:siginfo:read", "read-siginfo-object", 0);
13595
13596 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13597 "qXfer:siginfo:write", "write-siginfo-object", 0);
13598
b3b9301e
PA
13599 add_packet_config_cmd
13600 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13601 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13602
169081d0
TG
13603 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13604 "qXfer:uib:read", "unwind-info-block", 0);
13605
444abaca 13606 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13607 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13608 0);
13609
711e434b
PM
13610 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13611 "qGetTIBAddr", "get-thread-information-block-address",
13612 0);
13613
40ab02ce
MS
13614 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13615 "bc", "reverse-continue", 0);
13616
13617 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13618 "bs", "reverse-step", 0);
13619
be2a5f71
DJ
13620 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13621 "qSupported", "supported-packets", 0);
13622
08388c79
DE
13623 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13624 "qSearch:memory", "search-memory", 0);
13625
bd3eecc3
PA
13626 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13627 "qTStatus", "trace-status", 0);
13628
15a201c8
GB
13629 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13630 "vFile:setfs", "hostio-setfs", 0);
13631
a6b151f1
DJ
13632 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13633 "vFile:open", "hostio-open", 0);
13634
13635 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13636 "vFile:pread", "hostio-pread", 0);
13637
13638 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13639 "vFile:pwrite", "hostio-pwrite", 0);
13640
13641 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13642 "vFile:close", "hostio-close", 0);
13643
13644 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13645 "vFile:unlink", "hostio-unlink", 0);
13646
b9e7b9c3
UW
13647 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13648 "vFile:readlink", "hostio-readlink", 0);
13649
0a93529c
GB
13650 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13651 "vFile:fstat", "hostio-fstat", 0);
13652
2d717e4f
DJ
13653 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13654 "vAttach", "attach", 0);
13655
13656 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13657 "vRun", "run", 0);
13658
a6f3e723
SL
13659 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13660 "QStartNoAckMode", "noack", 0);
13661
82f73884
PA
13662 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13663 "vKill", "kill", 0);
13664
0b16c5cf
PA
13665 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13666 "qAttached", "query-attached", 0);
13667
782b2b07 13668 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13669 "ConditionalTracepoints",
13670 "conditional-tracepoints", 0);
3788aec7
LM
13671
13672 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13673 "ConditionalBreakpoints",
13674 "conditional-breakpoints", 0);
13675
d3ce09f5
SS
13676 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13677 "BreakpointCommands",
13678 "breakpoint-commands", 0);
13679
7a697b8d
SS
13680 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13681 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13682
409873ef
SS
13683 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13684 "TracepointSource", "TracepointSource", 0);
13685
d914c394
SS
13686 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13687 "QAllow", "allow", 0);
13688
0fb4aa4b
PA
13689 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13690 "StaticTracepoints", "static-tracepoints", 0);
13691
1e4d1764
YQ
13692 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13693 "InstallInTrace", "install-in-trace", 0);
13694
0fb4aa4b
PA
13695 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13696 "qXfer:statictrace:read", "read-sdata-object", 0);
13697
78d85199
YQ
13698 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13699 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13700
03583c20
UW
13701 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13702 "QDisableRandomization", "disable-randomization", 0);
13703
d1feda86
YQ
13704 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13705 "QAgent", "agent", 0);
13706
f6f899bf
HAQ
13707 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13708 "QTBuffer:size", "trace-buffer-size", 0);
13709
9accd112
MM
13710 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13711 "Qbtrace:off", "disable-btrace", 0);
13712
13713 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13714 "Qbtrace:bts", "enable-btrace-bts", 0);
13715
13716 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13717 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13718
13719 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13720 "qXfer:btrace", "read-btrace", 0);
13721
f4abbc16
MM
13722 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13723 "qXfer:btrace-conf", "read-btrace-conf", 0);
13724
d33501a5
MM
13725 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13726 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13727
73b8c1fd
PA
13728 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13729 "multiprocess-feature", "multiprocess-feature", 0);
13730
f7e6eed5
PA
13731 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13732 "swbreak-feature", "swbreak-feature", 0);
13733
13734 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13735 "hwbreak-feature", "hwbreak-feature", 0);
13736
89245bc0
DB
13737 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13738 "fork-event-feature", "fork-event-feature", 0);
13739
13740 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13741 "vfork-event-feature", "vfork-event-feature", 0);
13742
b20a6524
MM
13743 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13744 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13745
750ce8d1
YQ
13746 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13747 "vContSupported", "verbose-resume-supported", 0);
13748
94585166
DB
13749 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13750 "exec-event-feature", "exec-event-feature", 0);
13751
de979965
PA
13752 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13753 "vCtrlC", "ctrl-c", 0);
13754
65706a29
PA
13755 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13756 "QThreadEvents", "thread-events", 0);
13757
0b736949
DB
13758 /* Assert that we've registered "set remote foo-packet" commands
13759 for all packet configs. */
ca4f7f8b
PA
13760 {
13761 int i;
13762
13763 for (i = 0; i < PACKET_MAX; i++)
13764 {
13765 /* Ideally all configs would have a command associated. Some
13766 still don't though. */
13767 int excepted;
13768
13769 switch (i)
13770 {
13771 case PACKET_QNonStop:
ca4f7f8b
PA
13772 case PACKET_EnableDisableTracepoints_feature:
13773 case PACKET_tracenz_feature:
13774 case PACKET_DisconnectedTracing_feature:
13775 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13776 case PACKET_qCRC:
13777 /* Additions to this list need to be well justified:
13778 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13779 excepted = 1;
13780 break;
13781 default:
13782 excepted = 0;
13783 break;
13784 }
13785
13786 /* This catches both forgetting to add a config command, and
13787 forgetting to remove a packet from the exception list. */
13788 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13789 }
13790 }
13791
37a105a1
DJ
13792 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13793 Z sub-packet has its own set and show commands, but users may
13794 have sets to this variable in their .gdbinit files (or in their
13795 documentation). */
e9e68a56 13796 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13797 &remote_Z_packet_detect, _("\
13798Set use of remote protocol `Z' packets"), _("\
13799Show use of remote protocol `Z' packets "), _("\
3b64bf98 13800When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13801packets."),
e9e68a56 13802 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13803 show_remote_protocol_Z_packet_cmd,
13804 /* FIXME: i18n: Use of remote protocol
13805 `Z' packets is %s. */
e9e68a56 13806 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13807
a6b151f1
DJ
13808 add_prefix_cmd ("remote", class_files, remote_command, _("\
13809Manipulate files on the remote system\n\
13810Transfer files to and from the remote target system."),
13811 &remote_cmdlist, "remote ",
13812 0 /* allow-unknown */, &cmdlist);
13813
13814 add_cmd ("put", class_files, remote_put_command,
13815 _("Copy a local file to the remote system."),
13816 &remote_cmdlist);
13817
13818 add_cmd ("get", class_files, remote_get_command,
13819 _("Copy a remote file to the local system."),
13820 &remote_cmdlist);
13821
13822 add_cmd ("delete", class_files, remote_delete_command,
13823 _("Delete a remote file."),
13824 &remote_cmdlist);
13825
2d717e4f 13826 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13827 &remote_exec_file_var, _("\
2d717e4f 13828Set the remote pathname for \"run\""), _("\
94585166
DB
13829Show the remote pathname for \"run\""), NULL,
13830 set_remote_exec_file,
13831 show_remote_exec_file,
13832 &remote_set_cmdlist,
13833 &remote_show_cmdlist);
2d717e4f 13834
c1e36e3e
PA
13835 add_setshow_boolean_cmd ("range-stepping", class_run,
13836 &use_range_stepping, _("\
13837Enable or disable range stepping."), _("\
13838Show whether target-assisted range stepping is enabled."), _("\
13839If on, and the target supports it, when stepping a source line, GDB\n\
13840tells the target to step the corresponding range of addresses itself instead\n\
13841of issuing multiple single-steps. This speeds up source level\n\
13842stepping. If off, GDB always issues single-steps, even if range\n\
13843stepping is supported by the target. The default is on."),
13844 set_range_stepping,
13845 show_range_stepping,
13846 &setlist,
13847 &showlist);
13848
449092f6
CV
13849 /* Eventually initialize fileio. See fileio.c */
13850 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13851
ba348170 13852 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13853 special ptids with it set to != 0. */
ba348170
PA
13854 magic_null_ptid = ptid_build (42000, -1, 1);
13855 not_sent_ptid = ptid_build (42000, -2, 1);
13856 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13857
13858 target_buf_size = 2048;
224c3ddb 13859 target_buf = (char *) xmalloc (target_buf_size);
c906108c 13860}
10760264 13861
This page took 4.319267 seconds and 4 git commands to generate.