[ARC] Fixed-linker-related-testsuite-for-ARC
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
618f726f 3 Copyright (C) 1988-2016 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
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. */
6d820c5c 100static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 101static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 102 int forever, int *is_notif);
6426a772 103
a14ed312 104static void remote_files_info (struct target_ops *ignore);
c906108c 105
f32dbf8c
MM
106static void remote_prepare_to_store (struct target_ops *self,
107 struct regcache *regcache);
c906108c 108
014f9477
TT
109static void remote_open_1 (const char *, int, struct target_ops *,
110 int extended_p);
c906108c 111
de90e03d 112static void remote_close (struct target_ops *self);
c906108c 113
cbb8991c
DB
114struct remote_state;
115
116static int remote_vkill (int pid, struct remote_state *rs);
117
8020350c
DB
118static void remote_kill_k (void);
119
136d6dae 120static void remote_mourn (struct target_ops *ops);
c906108c 121
a14ed312 122static void extended_remote_restart (void);
c906108c 123
6d820c5c 124static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 125
a14ed312 126static int readchar (int timeout);
c906108c 127
c33e31fd
PA
128static void remote_serial_write (const char *str, int len);
129
7d85a9c0 130static void remote_kill (struct target_ops *ops);
c906108c 131
6a109b6b 132static int remote_can_async_p (struct target_ops *);
75c99385 133
6a109b6b 134static int remote_is_async_p (struct target_ops *);
75c99385 135
6a3753b3 136static void remote_async (struct target_ops *ops, int enable);
75c99385 137
65706a29
PA
138static void remote_thread_events (struct target_ops *ops, int enable);
139
a14ed312 140static void interrupt_query (void);
c906108c 141
79d7f229
PA
142static void set_general_thread (struct ptid ptid);
143static void set_continue_thread (struct ptid ptid);
c906108c 144
a14ed312 145static void get_offsets (void);
c906108c 146
6d820c5c
DJ
147static void skip_frame (void);
148
149static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 150
a14ed312 151static int hexnumlen (ULONGEST num);
c906108c 152
a14ed312 153static void init_remote_ops (void);
c906108c 154
a14ed312 155static void init_extended_remote_ops (void);
c906108c 156
1eab8a48 157static void remote_stop (struct target_ops *self, ptid_t);
c906108c 158
a14ed312 159static int stubhex (int ch);
c906108c 160
a14ed312 161static int hexnumstr (char *, ULONGEST);
c906108c 162
a14ed312 163static int hexnumnstr (char *, ULONGEST, int);
2df3850c 164
a14ed312 165static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 166
baa336ce 167static void print_packet (const char *);
c906108c 168
a14ed312 169static void compare_sections_command (char *, int);
c906108c 170
a14ed312 171static void packet_command (char *, int);
c906108c 172
a14ed312 173static int stub_unpack_int (char *buff, int fieldlength);
c906108c 174
39f77062 175static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 176
baa336ce 177static int putpkt_binary (const char *buf, int cnt);
c906108c 178
a14ed312 179static void check_binary_download (CORE_ADDR addr);
c906108c 180
5a2468f5 181struct packet_config;
5a2468f5 182
a14ed312 183static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 184
bb572ddd
DJ
185static void show_remote_protocol_packet_cmd (struct ui_file *file,
186 int from_tty,
187 struct cmd_list_element *c,
188 const char *value);
189
82f73884
PA
190static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
191static ptid_t read_ptid (char *buf, char **obuf);
192
c378d69d 193static void remote_set_permissions (struct target_ops *self);
d914c394 194
8bd200f1
TT
195static int remote_get_trace_status (struct target_ops *self,
196 struct trace_status *ts);
d5551862 197
ab6617cc
TT
198static int remote_upload_tracepoints (struct target_ops *self,
199 struct uploaded_tp **utpp);
00bf0b85 200
181e3713
TT
201static int remote_upload_trace_state_variables (struct target_ops *self,
202 struct uploaded_tsv **utsvp);
00bf0b85 203
c8d104ad
PA
204static void remote_query_supported (void);
205
36d25514 206static void remote_check_symbols (void);
c8d104ad 207
a14ed312 208void _initialize_remote (void);
c906108c 209
74531fed 210struct stop_reply;
74531fed 211static void stop_reply_xfree (struct stop_reply *);
722247f1 212static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 213static void push_stop_reply (struct stop_reply *);
bcc75809 214static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
215static int peek_stop_reply (ptid_t ptid);
216
cbb8991c
DB
217struct threads_listing_context;
218static void remove_new_fork_children (struct threads_listing_context *);
219
74531fed 220static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 221
e3594fd1 222static void remote_terminal_ours (struct target_ops *self);
d3fd5342 223
d962ef82
DJ
224static int remote_read_description_p (struct target_ops *target);
225
176a6961 226static void remote_console_output (char *msg);
dde08ee1 227
efcc2da7 228static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 229
78eff0ec 230static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 231
f4abbc16
MM
232static void remote_btrace_reset (void);
233
221e1a37
PA
234static int stop_reply_queue_length (void);
235
80152258
PA
236static void readahead_cache_invalidate (void);
237
048094ac
PA
238static void remote_unpush_and_throw (void);
239
a6b151f1
DJ
240/* For "remote". */
241
242static struct cmd_list_element *remote_cmdlist;
243
bb572ddd
DJ
244/* For "set remote" and "show remote". */
245
246static struct cmd_list_element *remote_set_cmdlist;
247static struct cmd_list_element *remote_show_cmdlist;
248
d458bd84
PA
249/* Stub vCont actions support.
250
251 Each field is a boolean flag indicating whether the stub reports
252 support for the corresponding action. */
253
254struct vCont_action_support
255{
256 /* vCont;t */
257 int t;
c1e36e3e
PA
258
259 /* vCont;r */
260 int r;
750ce8d1
YQ
261
262 /* vCont;s */
263 int s;
264
265 /* vCont;S */
266 int S;
d458bd84
PA
267};
268
c1e36e3e
PA
269/* Controls whether GDB is willing to use range stepping. */
270
271static int use_range_stepping = 1;
272
0d031856
TT
273#define OPAQUETHREADBYTES 8
274
275/* a 64 bit opaque identifier */
276typedef unsigned char threadref[OPAQUETHREADBYTES];
277
278/* About this many threadisds fit in a packet. */
279
280#define MAXTHREADLISTRESULTS 32
281
80152258
PA
282/* Data for the vFile:pread readahead cache. */
283
284struct readahead_cache
285{
286 /* The file descriptor for the file that is being cached. -1 if the
287 cache is invalid. */
288 int fd;
289
290 /* The offset into the file that the cache buffer corresponds
291 to. */
292 ULONGEST offset;
293
294 /* The buffer holding the cache contents. */
295 gdb_byte *buf;
296 /* The buffer's size. We try to read as much as fits into a packet
297 at a time. */
298 size_t bufsize;
299
300 /* Cache hit and miss counters. */
301 ULONGEST hit_count;
302 ULONGEST miss_count;
303};
304
ea9c271d
DJ
305/* Description of the remote protocol state for the currently
306 connected target. This is per-target state, and independent of the
307 selected architecture. */
308
309struct remote_state
310{
311 /* A buffer to use for incoming packets, and its current size. The
312 buffer is grown dynamically for larger incoming packets.
313 Outgoing packets may also be constructed in this buffer.
314 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
315 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
316 packets. */
317 char *buf;
318 long buf_size;
be2a5f71 319
1e51243a
PA
320 /* True if we're going through initial connection setup (finding out
321 about the remote side's threads, relocating symbols, etc.). */
322 int starting_up;
323
be2a5f71
DJ
324 /* If we negotiated packet size explicitly (and thus can bypass
325 heuristics for the largest packet size that will not overflow
326 a buffer in the stub), this will be set to that packet size.
327 Otherwise zero, meaning to use the guessed size. */
328 long explicit_packet_size;
2d717e4f
DJ
329
330 /* remote_wait is normally called when the target is running and
331 waits for a stop reply packet. But sometimes we need to call it
332 when the target is already stopped. We can send a "?" packet
333 and have remote_wait read the response. Or, if we already have
334 the response, we can stash it in BUF and tell remote_wait to
335 skip calling getpkt. This flag is set when BUF contains a
336 stop reply packet and the target is not waiting. */
337 int cached_wait_status;
a6f3e723
SL
338
339 /* True, if in no ack mode. That is, neither GDB nor the stub will
340 expect acks from each other. The connection is assumed to be
341 reliable. */
342 int noack_mode;
82f73884
PA
343
344 /* True if we're connected in extended remote mode. */
345 int extended;
346
e24a49d8
PA
347 /* True if we resumed the target and we're waiting for the target to
348 stop. In the mean time, we can't start another command/query.
349 The remote server wouldn't be ready to process it, so we'd
350 timeout waiting for a reply that would never come and eventually
351 we'd close the connection. This can happen in asynchronous mode
352 because we allow GDB commands while the target is running. */
353 int waiting_for_stop_reply;
74531fed 354
d458bd84
PA
355 /* The status of the stub support for the various vCont actions. */
356 struct vCont_action_support supports_vCont;
782b2b07 357
3a29589a
DJ
358 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
359 responded to that. */
360 int ctrlc_pending_p;
5d93a237 361
048094ac
PA
362 /* True if we saw a Ctrl-C while reading or writing from/to the
363 remote descriptor. At that point it is not safe to send a remote
364 interrupt packet, so we instead remember we saw the Ctrl-C and
365 process it once we're done with sending/receiving the current
366 packet, which should be shortly. If however that takes too long,
367 and the user presses Ctrl-C again, we offer to disconnect. */
368 int got_ctrlc_during_io;
369
5d93a237
TT
370 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
371 remote_open knows that we don't have a file open when the program
372 starts. */
373 struct serial *remote_desc;
47f8a51d
TT
374
375 /* These are the threads which we last sent to the remote system. The
376 TID member will be -1 for all or -2 for not sent yet. */
377 ptid_t general_thread;
378 ptid_t continue_thread;
262e1174
TT
379
380 /* This is the traceframe which we last selected on the remote system.
381 It will be -1 if no traceframe is selected. */
382 int remote_traceframe_number;
747dc59d
TT
383
384 char *last_pass_packet;
5e4a05c4
TT
385
386 /* The last QProgramSignals packet sent to the target. We bypass
387 sending a new program signals list down to the target if the new
388 packet is exactly the same as the last we sent. IOW, we only let
389 the target know about program signals list changes. */
390 char *last_program_signals_packet;
b73be471
TT
391
392 enum gdb_signal last_sent_signal;
280ceea3
TT
393
394 int last_sent_step;
8e88304f 395
3a00c802
PA
396 /* The execution direction of the last resume we got. */
397 enum exec_direction_kind last_resume_exec_dir;
398
8e88304f
TT
399 char *finished_object;
400 char *finished_annex;
401 ULONGEST finished_offset;
b80fafe3
TT
402
403 /* Should we try the 'ThreadInfo' query packet?
404
405 This variable (NOT available to the user: auto-detect only!)
406 determines whether GDB will use the new, simpler "ThreadInfo"
407 query or the older, more complex syntax for thread queries.
408 This is an auto-detect variable (set to true at each connect,
409 and set to false when the target fails to recognize it). */
410 int use_threadinfo_query;
411 int use_threadextra_query;
88b496c3 412
0d031856
TT
413 threadref echo_nextthread;
414 threadref nextthread;
415 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
416
417 /* The state of remote notification. */
418 struct remote_notif_state *notif_state;
f4abbc16
MM
419
420 /* The branch trace configuration. */
421 struct btrace_config btrace_config;
15a201c8
GB
422
423 /* The argument to the last "vFile:setfs:" packet we sent, used
424 to avoid sending repeated unnecessary "vFile:setfs:" packets.
425 Initialized to -1 to indicate that no "vFile:setfs:" packet
426 has yet been sent. */
427 int fs_pid;
80152258
PA
428
429 /* A readahead cache for vFile:pread. Often, reading a binary
430 involves a sequence of small reads. E.g., when parsing an ELF
431 file. A readahead cache helps mostly the case of remote
432 debugging on a connection with higher latency, due to the
433 request/reply nature of the RSP. We only cache data for a single
434 file descriptor at a time. */
435 struct readahead_cache readahead_cache;
ea9c271d
DJ
436};
437
dc146f7c
VP
438/* Private data that we'll store in (struct thread_info)->private. */
439struct private_thread_info
440{
441 char *extra;
79efa585 442 char *name;
dc146f7c 443 int core;
799a2abe
PA
444
445 /* Whether the target stopped for a breakpoint/watchpoint. */
446 enum target_stop_reason stop_reason;
447
448 /* This is set to the data address of the access causing the target
449 to stop for a watchpoint. */
450 CORE_ADDR watch_data_address;
dc146f7c
VP
451};
452
453static void
454free_private_thread_info (struct private_thread_info *info)
455{
456 xfree (info->extra);
79efa585 457 xfree (info->name);
dc146f7c
VP
458 xfree (info);
459}
460
ea9c271d
DJ
461/* This data could be associated with a target, but we do not always
462 have access to the current target when we need it, so for now it is
463 static. This will be fine for as long as only one target is in use
464 at a time. */
cf792862 465static struct remote_state *remote_state;
ea9c271d
DJ
466
467static struct remote_state *
0b83947e 468get_remote_state_raw (void)
ea9c271d 469{
cf792862
TT
470 return remote_state;
471}
472
473/* Allocate a new struct remote_state with xmalloc, initialize it, and
474 return it. */
475
476static struct remote_state *
477new_remote_state (void)
478{
479 struct remote_state *result = XCNEW (struct remote_state);
480
481 /* The default buffer size is unimportant; it will be expanded
482 whenever a larger buffer is needed. */
483 result->buf_size = 400;
224c3ddb 484 result->buf = (char *) xmalloc (result->buf_size);
262e1174 485 result->remote_traceframe_number = -1;
b73be471 486 result->last_sent_signal = GDB_SIGNAL_0;
3a00c802 487 result->last_resume_exec_dir = EXEC_FORWARD;
15a201c8 488 result->fs_pid = -1;
cf792862
TT
489
490 return result;
ea9c271d
DJ
491}
492
493/* Description of the remote protocol for a given architecture. */
d01949b6 494
ad10f812
AC
495struct packet_reg
496{
497 long offset; /* Offset into G packet. */
498 long regnum; /* GDB's internal register number. */
499 LONGEST pnum; /* Remote protocol register number. */
b323314b 500 int in_g_packet; /* Always part of G packet. */
f5656ead 501 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 502 at present. */
f5656ead 503 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 504 at present. */
ad10f812
AC
505};
506
ea9c271d 507struct remote_arch_state
d01949b6 508{
ad10f812
AC
509 /* Description of the remote protocol registers. */
510 long sizeof_g_packet;
b323314b
AC
511
512 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 513 (making an array gdbarch_num_regs in size). */
b323314b 514 struct packet_reg *regs;
ad10f812 515
d01949b6
AC
516 /* This is the size (in chars) of the first response to the ``g''
517 packet. It is used as a heuristic when determining the maximum
518 size of memory-read and memory-write packets. A target will
519 typically only reserve a buffer large enough to hold the ``g''
520 packet. The size does not include packet overhead (headers and
23860348 521 trailers). */
d01949b6
AC
522 long actual_register_packet_size;
523
524 /* This is the maximum size (in chars) of a non read/write packet.
23860348 525 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
526 long remote_packet_size;
527};
528
35b1e5cc
SS
529/* Utility: generate error from an incoming stub packet. */
530static void
531trace_error (char *buf)
532{
533 if (*buf++ != 'E')
534 return; /* not an error msg */
535 switch (*buf)
536 {
537 case '1': /* malformed packet error */
538 if (*++buf == '0') /* general case: */
539 error (_("remote.c: error in outgoing packet."));
540 else
541 error (_("remote.c: error in outgoing packet at field #%ld."),
542 strtol (buf, NULL, 16));
35b1e5cc
SS
543 default:
544 error (_("Target returns error code '%s'."), buf);
545 }
546}
547
548/* Utility: wait for reply from stub, while accepting "O" packets. */
549static char *
550remote_get_noisy_reply (char **buf_p,
551 long *sizeof_buf)
552{
553 do /* Loop on reply from remote stub. */
554 {
555 char *buf;
a744cf53 556
0df8b418 557 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
558 getpkt (buf_p, sizeof_buf, 0);
559 buf = *buf_p;
ad91cd99 560 if (buf[0] == 'E')
35b1e5cc 561 trace_error (buf);
61012eef 562 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
563 {
564 ULONGEST ul;
565 CORE_ADDR from, to, org_to;
566 char *p, *pp;
567 int adjusted_size = 0;
7556d4a4 568 int relocated = 0;
dde08ee1
PA
569
570 p = buf + strlen ("qRelocInsn:");
571 pp = unpack_varlen_hex (p, &ul);
572 if (*pp != ';')
cb91c06a 573 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
574 from = ul;
575
576 p = pp + 1;
a9cbf802 577 unpack_varlen_hex (p, &ul);
dde08ee1
PA
578 to = ul;
579
580 org_to = to;
581
492d29ea 582 TRY
dde08ee1 583 {
f5656ead 584 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 585 relocated = 1;
dde08ee1 586 }
492d29ea 587 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
588 {
589 if (ex.error == MEMORY_ERROR)
590 {
591 /* Propagate memory errors silently back to the
592 target. The stub may have limited the range of
593 addresses we can write to, for example. */
594 }
595 else
596 {
597 /* Something unexpectedly bad happened. Be verbose
598 so we can tell what, and propagate the error back
599 to the stub, so it doesn't get stuck waiting for
600 a response. */
601 exception_fprintf (gdb_stderr, ex,
602 _("warning: relocating instruction: "));
603 }
604 putpkt ("E01");
605 }
492d29ea 606 END_CATCH
7556d4a4
PA
607
608 if (relocated)
dde08ee1
PA
609 {
610 adjusted_size = to - org_to;
611
bba74b36 612 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
613 putpkt (buf);
614 }
dde08ee1 615 }
ad91cd99 616 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
617 remote_console_output (buf + 1); /* 'O' message from stub */
618 else
0df8b418 619 return buf; /* Here's the actual reply. */
35b1e5cc
SS
620 }
621 while (1);
622}
3c3bea1c 623
d01949b6
AC
624/* Handle for retreving the remote protocol data from gdbarch. */
625static struct gdbarch_data *remote_gdbarch_data_handle;
626
ea9c271d
DJ
627static struct remote_arch_state *
628get_remote_arch_state (void)
d01949b6 629{
17d8546e 630 gdb_assert (target_gdbarch () != NULL);
19ba03f4
SM
631 return ((struct remote_arch_state *)
632 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
d01949b6
AC
633}
634
0b83947e
DJ
635/* Fetch the global remote target state. */
636
637static struct remote_state *
638get_remote_state (void)
639{
640 /* Make sure that the remote architecture state has been
641 initialized, because doing so might reallocate rs->buf. Any
642 function which calls getpkt also needs to be mindful of changes
643 to rs->buf, but this call limits the number of places which run
644 into trouble. */
645 get_remote_arch_state ();
646
647 return get_remote_state_raw ();
648}
649
94585166
DB
650/* Cleanup routine for the remote module's pspace data. */
651
652static void
653remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
654{
19ba03f4 655 char *remote_exec_file = (char *) arg;
94585166
DB
656
657 xfree (remote_exec_file);
658}
659
660/* Fetch the remote exec-file from the current program space. */
661
662static const char *
663get_remote_exec_file (void)
664{
665 char *remote_exec_file;
666
19ba03f4
SM
667 remote_exec_file
668 = (char *) program_space_data (current_program_space,
669 remote_pspace_data);
94585166
DB
670 if (remote_exec_file == NULL)
671 return "";
672
673 return remote_exec_file;
674}
675
676/* Set the remote exec file for PSPACE. */
677
678static void
679set_pspace_remote_exec_file (struct program_space *pspace,
680 char *remote_exec_file)
681{
19ba03f4 682 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
683
684 xfree (old_file);
685 set_program_space_data (pspace, remote_pspace_data,
686 xstrdup (remote_exec_file));
687}
688
689/* The "set/show remote exec-file" set command hook. */
690
691static void
692set_remote_exec_file (char *ignored, int from_tty,
693 struct cmd_list_element *c)
694{
695 gdb_assert (remote_exec_file_var != NULL);
696 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
697}
698
699/* The "set/show remote exec-file" show command hook. */
700
701static void
702show_remote_exec_file (struct ui_file *file, int from_tty,
703 struct cmd_list_element *cmd, const char *value)
704{
705 fprintf_filtered (file, "%s\n", remote_exec_file_var);
706}
707
74ca34ce
DJ
708static int
709compare_pnums (const void *lhs_, const void *rhs_)
710{
19ba03f4
SM
711 const struct packet_reg * const *lhs
712 = (const struct packet_reg * const *) lhs_;
713 const struct packet_reg * const *rhs
714 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
715
716 if ((*lhs)->pnum < (*rhs)->pnum)
717 return -1;
718 else if ((*lhs)->pnum == (*rhs)->pnum)
719 return 0;
720 else
721 return 1;
722}
723
c21236dc
PA
724static int
725map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 726{
74ca34ce 727 int regnum, num_remote_regs, offset;
74ca34ce 728 struct packet_reg **remote_regs;
ea9c271d 729
4a22f64d 730 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 731 {
c21236dc 732 struct packet_reg *r = &regs[regnum];
baef701f 733
4a22f64d 734 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
735 /* Do not try to fetch zero-sized (placeholder) registers. */
736 r->pnum = -1;
737 else
738 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
739
b323314b 740 r->regnum = regnum;
74ca34ce
DJ
741 }
742
743 /* Define the g/G packet format as the contents of each register
744 with a remote protocol number, in order of ascending protocol
745 number. */
746
224c3ddb 747 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 748 for (num_remote_regs = 0, regnum = 0;
4a22f64d 749 regnum < gdbarch_num_regs (gdbarch);
f57d151a 750 regnum++)
c21236dc
PA
751 if (regs[regnum].pnum != -1)
752 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 753
74ca34ce
DJ
754 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
755 compare_pnums);
756
757 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
758 {
759 remote_regs[regnum]->in_g_packet = 1;
760 remote_regs[regnum]->offset = offset;
4a22f64d 761 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
762 }
763
c21236dc
PA
764 return offset;
765}
766
767/* Given the architecture described by GDBARCH, return the remote
768 protocol register's number and the register's offset in the g/G
769 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
770 If the target does not have a mapping for REGNUM, return false,
771 otherwise, return true. */
772
773int
774remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
775 int *pnum, int *poffset)
776{
c21236dc
PA
777 struct packet_reg *regs;
778 struct cleanup *old_chain;
779
780 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
781
224c3ddb 782 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
c21236dc
PA
783 old_chain = make_cleanup (xfree, regs);
784
54887903 785 map_regcache_remote_table (gdbarch, regs);
c21236dc
PA
786
787 *pnum = regs[regnum].pnum;
788 *poffset = regs[regnum].offset;
789
790 do_cleanups (old_chain);
791
792 return *pnum != -1;
793}
794
795static void *
796init_remote_state (struct gdbarch *gdbarch)
797{
798 struct remote_state *rs = get_remote_state_raw ();
799 struct remote_arch_state *rsa;
800
801 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
802
803 /* Use the architecture to build a regnum<->pnum table, which will be
804 1:1 unless a feature set specifies otherwise. */
805 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
806 gdbarch_num_regs (gdbarch),
807 struct packet_reg);
808
74ca34ce
DJ
809 /* Record the maximum possible size of the g packet - it may turn out
810 to be smaller. */
c21236dc 811 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 812
0df8b418 813 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
814 remote stubs have a hardwired buffer size of 400 bytes
815 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
816 as the maximum packet-size to ensure that the packet and an extra
817 NUL character can always fit in the buffer. This stops GDB
818 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
819 already a full buffer (As of 1999-12-04 that was most stubs). */
820 rsa->remote_packet_size = 400 - 1;
d01949b6 821
ea9c271d
DJ
822 /* This one is filled in when a ``g'' packet is received. */
823 rsa->actual_register_packet_size = 0;
824
825 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
826 default, adjust the size accordingly. Remember that each byte is
827 encoded as two characters. 32 is the overhead for the packet
828 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 829 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 830 little. */
ea9c271d
DJ
831 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
832 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 833
ea9c271d
DJ
834 /* Make sure that the packet buffer is plenty big enough for
835 this architecture. */
836 if (rs->buf_size < rsa->remote_packet_size)
837 {
838 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 839 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 840 }
6d820c5c 841
ea9c271d
DJ
842 return rsa;
843}
844
845/* Return the current allowed size of a remote packet. This is
846 inferred from the current architecture, and should be used to
847 limit the length of outgoing packets. */
848static long
849get_remote_packet_size (void)
850{
be2a5f71 851 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
852 struct remote_arch_state *rsa = get_remote_arch_state ();
853
be2a5f71
DJ
854 if (rs->explicit_packet_size)
855 return rs->explicit_packet_size;
856
ea9c271d 857 return rsa->remote_packet_size;
d01949b6
AC
858}
859
ad10f812 860static struct packet_reg *
ea9c271d 861packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 862{
f5656ead 863 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
864 return NULL;
865 else
ad10f812 866 {
ea9c271d 867 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 868
b323314b
AC
869 gdb_assert (r->regnum == regnum);
870 return r;
ad10f812 871 }
ad10f812
AC
872}
873
874static struct packet_reg *
ea9c271d 875packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 876{
b323314b 877 int i;
a744cf53 878
f5656ead 879 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 880 {
ea9c271d 881 struct packet_reg *r = &rsa->regs[i];
a744cf53 882
b323314b
AC
883 if (r->pnum == pnum)
884 return r;
ad10f812
AC
885 }
886 return NULL;
d01949b6
AC
887}
888
c906108c
SS
889static struct target_ops remote_ops;
890
891static struct target_ops extended_remote_ops;
892
6426a772
JM
893/* FIXME: cagney/1999-09-23: Even though getpkt was called with
894 ``forever'' still use the normal timeout mechanism. This is
895 currently used by the ASYNC code to guarentee that target reads
896 during the initial connect always time-out. Once getpkt has been
897 modified to return a timeout indication and, in turn
898 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 899 this can go away. */
6426a772
JM
900static int wait_forever_enabled_p = 1;
901
9a7071a8
JB
902/* Allow the user to specify what sequence to send to the remote
903 when he requests a program interruption: Although ^C is usually
904 what remote systems expect (this is the default, here), it is
905 sometimes preferable to send a break. On other systems such
906 as the Linux kernel, a break followed by g, which is Magic SysRq g
907 is required in order to interrupt the execution. */
908const char interrupt_sequence_control_c[] = "Ctrl-C";
909const char interrupt_sequence_break[] = "BREAK";
910const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 911static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
912 {
913 interrupt_sequence_control_c,
914 interrupt_sequence_break,
915 interrupt_sequence_break_g,
916 NULL
917 };
918static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
919
920static void
921show_interrupt_sequence (struct ui_file *file, int from_tty,
922 struct cmd_list_element *c,
923 const char *value)
924{
925 if (interrupt_sequence_mode == interrupt_sequence_control_c)
926 fprintf_filtered (file,
927 _("Send the ASCII ETX character (Ctrl-c) "
928 "to the remote target to interrupt the "
929 "execution of the program.\n"));
930 else if (interrupt_sequence_mode == interrupt_sequence_break)
931 fprintf_filtered (file,
932 _("send a break signal to the remote target "
933 "to interrupt the execution of the program.\n"));
934 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
935 fprintf_filtered (file,
936 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
937 "the remote target to interrupt the execution "
938 "of Linux kernel.\n"));
939 else
940 internal_error (__FILE__, __LINE__,
941 _("Invalid value for interrupt_sequence_mode: %s."),
942 interrupt_sequence_mode);
943}
6426a772 944
9a7071a8
JB
945/* This boolean variable specifies whether interrupt_sequence is sent
946 to the remote target when gdb connects to it.
947 This is mostly needed when you debug the Linux kernel: The Linux kernel
948 expects BREAK g which is Magic SysRq g for connecting gdb. */
949static int interrupt_on_connect = 0;
c906108c 950
9a7071a8
JB
951/* This variable is used to implement the "set/show remotebreak" commands.
952 Since these commands are now deprecated in favor of "set/show remote
953 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
954static int remote_break;
955
9a7071a8
JB
956static void
957set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
958{
959 if (remote_break)
960 interrupt_sequence_mode = interrupt_sequence_break;
961 else
962 interrupt_sequence_mode = interrupt_sequence_control_c;
963}
964
965static void
966show_remotebreak (struct ui_file *file, int from_tty,
967 struct cmd_list_element *c,
968 const char *value)
969{
970}
971
c906108c
SS
972/* This variable sets the number of bits in an address that are to be
973 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 974 leading zeros, the entire address would be sent. This variable
c906108c
SS
975 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
976 initial implementation of remote.c restricted the address sent in
977 memory packets to ``host::sizeof long'' bytes - (typically 32
978 bits). Consequently, for 64 bit targets, the upper 32 bits of an
979 address was never sent. Since fixing this bug may cause a break in
980 some remote targets this variable is principly provided to
23860348 981 facilitate backward compatibility. */
c906108c 982
883b9c6c 983static unsigned int remote_address_size;
c906108c 984
75c99385
PA
985/* Temporary to track who currently owns the terminal. See
986 remote_terminal_* for more details. */
6426a772
JM
987
988static int remote_async_terminal_ours_p;
989
11cf8741 990\f
11cf8741 991/* User configurable variables for the number of characters in a
ea9c271d
DJ
992 memory read/write packet. MIN (rsa->remote_packet_size,
993 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 994 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
995 (speed up transfers). The variables ``preferred_*'' (the user
996 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 997 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
998
999struct memory_packet_config
1000{
1001 char *name;
1002 long size;
1003 int fixed_p;
1004};
1005
a5c0808e
PA
1006/* The default max memory-write-packet-size. The 16k is historical.
1007 (It came from older GDB's using alloca for buffers and the
1008 knowledge (folklore?) that some hosts don't cope very well with
1009 large alloca calls.) */
1010#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1011
1012/* The minimum remote packet size for memory transfers. Ensures we
1013 can write at least one byte. */
1014#define MIN_MEMORY_PACKET_SIZE 20
1015
11cf8741
JM
1016/* Compute the current size of a read/write packet. Since this makes
1017 use of ``actual_register_packet_size'' the computation is dynamic. */
1018
1019static long
1020get_memory_packet_size (struct memory_packet_config *config)
1021{
d01949b6 1022 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
1023 struct remote_arch_state *rsa = get_remote_arch_state ();
1024
11cf8741
JM
1025 long what_they_get;
1026 if (config->fixed_p)
1027 {
1028 if (config->size <= 0)
a5c0808e 1029 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1030 else
1031 what_they_get = config->size;
1032 }
1033 else
1034 {
ea9c271d 1035 what_they_get = get_remote_packet_size ();
23860348 1036 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1037 if (config->size > 0
1038 && what_they_get > config->size)
1039 what_they_get = config->size;
be2a5f71
DJ
1040
1041 /* Limit it to the size of the targets ``g'' response unless we have
1042 permission from the stub to use a larger packet size. */
1043 if (rs->explicit_packet_size == 0
1044 && rsa->actual_register_packet_size > 0
1045 && what_they_get > rsa->actual_register_packet_size)
1046 what_they_get = rsa->actual_register_packet_size;
11cf8741 1047 }
a5c0808e
PA
1048 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1049 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1050
1051 /* Make sure there is room in the global buffer for this packet
1052 (including its trailing NUL byte). */
1053 if (rs->buf_size < what_they_get + 1)
1054 {
1055 rs->buf_size = 2 * what_they_get;
224c3ddb 1056 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1057 }
1058
11cf8741
JM
1059 return what_they_get;
1060}
1061
0df8b418 1062/* Update the size of a read/write packet. If they user wants
23860348 1063 something really big then do a sanity check. */
11cf8741
JM
1064
1065static void
1066set_memory_packet_size (char *args, struct memory_packet_config *config)
1067{
1068 int fixed_p = config->fixed_p;
1069 long size = config->size;
a744cf53 1070
11cf8741 1071 if (args == NULL)
8a3fe4f8 1072 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1073 else if (strcmp (args, "hard") == 0
1074 || strcmp (args, "fixed") == 0)
1075 fixed_p = 1;
1076 else if (strcmp (args, "soft") == 0
1077 || strcmp (args, "limit") == 0)
1078 fixed_p = 0;
1079 else
1080 {
1081 char *end;
a744cf53 1082
11cf8741
JM
1083 size = strtoul (args, &end, 0);
1084 if (args == end)
8a3fe4f8 1085 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1086
1087 /* Instead of explicitly capping the size of a packet to or
1088 disallowing it, the user is allowed to set the size to
1089 something arbitrarily large. */
11cf8741 1090 }
a5c0808e
PA
1091
1092 /* So that the query shows the correct value. */
1093 if (size <= 0)
1094 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1095
23860348 1096 /* Extra checks? */
11cf8741
JM
1097 if (fixed_p && !config->fixed_p)
1098 {
e2e0b3e5
AC
1099 if (! query (_("The target may not be able to correctly handle a %s\n"
1100 "of %ld bytes. Change the packet size? "),
11cf8741 1101 config->name, size))
8a3fe4f8 1102 error (_("Packet size not changed."));
11cf8741 1103 }
23860348 1104 /* Update the config. */
11cf8741
JM
1105 config->fixed_p = fixed_p;
1106 config->size = size;
1107}
1108
1109static void
1110show_memory_packet_size (struct memory_packet_config *config)
1111{
a3f17187 1112 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1113 if (config->fixed_p)
a3f17187 1114 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1115 get_memory_packet_size (config));
1116 else
a3f17187 1117 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1118 get_memory_packet_size (config));
1119}
1120
1121static struct memory_packet_config memory_write_packet_config =
1122{
1123 "memory-write-packet-size",
1124};
1125
1126static void
1127set_memory_write_packet_size (char *args, int from_tty)
1128{
1129 set_memory_packet_size (args, &memory_write_packet_config);
1130}
1131
1132static void
1133show_memory_write_packet_size (char *args, int from_tty)
1134{
1135 show_memory_packet_size (&memory_write_packet_config);
1136}
1137
1138static long
1139get_memory_write_packet_size (void)
1140{
1141 return get_memory_packet_size (&memory_write_packet_config);
1142}
1143
1144static struct memory_packet_config memory_read_packet_config =
1145{
1146 "memory-read-packet-size",
1147};
1148
1149static void
1150set_memory_read_packet_size (char *args, int from_tty)
1151{
1152 set_memory_packet_size (args, &memory_read_packet_config);
1153}
1154
1155static void
1156show_memory_read_packet_size (char *args, int from_tty)
1157{
1158 show_memory_packet_size (&memory_read_packet_config);
1159}
1160
1161static long
1162get_memory_read_packet_size (void)
1163{
1164 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1165
11cf8741
JM
1166 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1167 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1168 increased beyond this. */
1169 if (size > get_remote_packet_size ())
1170 size = get_remote_packet_size ();
11cf8741
JM
1171 return size;
1172}
1173
11cf8741 1174\f
5a2468f5 1175/* Generic configuration support for packets the stub optionally
0df8b418 1176 supports. Allows the user to specify the use of the packet as well
23860348 1177 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1178
1179enum packet_support
1180 {
1181 PACKET_SUPPORT_UNKNOWN = 0,
1182 PACKET_ENABLE,
1183 PACKET_DISABLE
1184 };
1185
5a2468f5
JM
1186struct packet_config
1187 {
bb572ddd
DJ
1188 const char *name;
1189 const char *title;
4082afcc
PA
1190
1191 /* If auto, GDB auto-detects support for this packet or feature,
1192 either through qSupported, or by trying the packet and looking
1193 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1194 packet. If false, the packet is disabled. Configs that don't
1195 have an associated command always have this set to auto. */
7f19b9a2 1196 enum auto_boolean detect;
4082afcc
PA
1197
1198 /* Does the target support this packet? */
5a2468f5
JM
1199 enum packet_support support;
1200 };
1201
d471ea57 1202/* Analyze a packet's return value and update the packet config
23860348 1203 accordingly. */
d471ea57
AC
1204
1205enum packet_result
1206{
1207 PACKET_ERROR,
1208 PACKET_OK,
1209 PACKET_UNKNOWN
1210};
1211
4082afcc
PA
1212static enum packet_support packet_config_support (struct packet_config *config);
1213static enum packet_support packet_support (int packet);
5a2468f5
JM
1214
1215static void
fba45db2 1216show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1217{
1218 char *support = "internal-error";
a744cf53 1219
4082afcc 1220 switch (packet_config_support (config))
5a2468f5
JM
1221 {
1222 case PACKET_ENABLE:
1223 support = "enabled";
1224 break;
1225 case PACKET_DISABLE:
1226 support = "disabled";
1227 break;
1228 case PACKET_SUPPORT_UNKNOWN:
1229 support = "unknown";
1230 break;
1231 }
1232 switch (config->detect)
1233 {
7f19b9a2 1234 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1235 printf_filtered (_("Support for the `%s' packet "
1236 "is auto-detected, currently %s.\n"),
37a105a1 1237 config->name, support);
5a2468f5 1238 break;
7f19b9a2
AC
1239 case AUTO_BOOLEAN_TRUE:
1240 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1241 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1242 config->name, support);
8e248173 1243 break;
5a2468f5
JM
1244 }
1245}
1246
1247static void
bb572ddd
DJ
1248add_packet_config_cmd (struct packet_config *config, const char *name,
1249 const char *title, int legacy)
d471ea57 1250{
5a2468f5
JM
1251 char *set_doc;
1252 char *show_doc;
d471ea57 1253 char *cmd_name;
3ed07be4 1254
5a2468f5
JM
1255 config->name = name;
1256 config->title = title;
b435e160
AC
1257 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1258 name, title);
3e43a32a
MS
1259 show_doc = xstrprintf ("Show current use of remote "
1260 "protocol `%s' (%s) packet",
b435e160 1261 name, title);
d471ea57 1262 /* set/show TITLE-packet {auto,on,off} */
b435e160 1263 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1264 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1265 &config->detect, set_doc,
1266 show_doc, NULL, /* help_doc */
4082afcc 1267 NULL,
bb572ddd
DJ
1268 show_remote_protocol_packet_cmd,
1269 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1270 /* The command code copies the documentation strings. */
1271 xfree (set_doc);
1272 xfree (show_doc);
23860348 1273 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1274 if (legacy)
1275 {
1276 char *legacy_name;
a744cf53 1277
b435e160 1278 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1279 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1280 &remote_set_cmdlist);
d471ea57 1281 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1282 &remote_show_cmdlist);
d471ea57 1283 }
5a2468f5
JM
1284}
1285
d471ea57 1286static enum packet_result
a76d924d 1287packet_check_result (const char *buf)
5a2468f5 1288{
d471ea57 1289 if (buf[0] != '\0')
5a2468f5 1290 {
d471ea57 1291 /* The stub recognized the packet request. Check that the
23860348 1292 operation succeeded. */
a76d924d
DJ
1293 if (buf[0] == 'E'
1294 && isxdigit (buf[1]) && isxdigit (buf[2])
1295 && buf[3] == '\0')
1296 /* "Enn" - definitly an error. */
1297 return PACKET_ERROR;
1298
1299 /* Always treat "E." as an error. This will be used for
1300 more verbose error messages, such as E.memtypes. */
1301 if (buf[0] == 'E' && buf[1] == '.')
1302 return PACKET_ERROR;
1303
1304 /* The packet may or may not be OK. Just assume it is. */
1305 return PACKET_OK;
1306 }
1307 else
1308 /* The stub does not support the packet. */
1309 return PACKET_UNKNOWN;
1310}
1311
1312static enum packet_result
1313packet_ok (const char *buf, struct packet_config *config)
1314{
1315 enum packet_result result;
1316
4082afcc
PA
1317 if (config->detect != AUTO_BOOLEAN_TRUE
1318 && config->support == PACKET_DISABLE)
1319 internal_error (__FILE__, __LINE__,
1320 _("packet_ok: attempt to use a disabled packet"));
1321
a76d924d
DJ
1322 result = packet_check_result (buf);
1323 switch (result)
1324 {
1325 case PACKET_OK:
1326 case PACKET_ERROR:
1327 /* The stub recognized the packet request. */
4082afcc 1328 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1329 {
d471ea57
AC
1330 if (remote_debug)
1331 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1332 "Packet %s (%s) is supported\n",
1333 config->name, config->title);
d471ea57 1334 config->support = PACKET_ENABLE;
d471ea57 1335 }
a76d924d
DJ
1336 break;
1337 case PACKET_UNKNOWN:
23860348 1338 /* The stub does not support the packet. */
4082afcc
PA
1339 if (config->detect == AUTO_BOOLEAN_AUTO
1340 && config->support == PACKET_ENABLE)
d471ea57 1341 {
4082afcc
PA
1342 /* If the stub previously indicated that the packet was
1343 supported then there is a protocol error. */
1344 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1345 config->name, config->title);
1346 }
1347 else if (config->detect == AUTO_BOOLEAN_TRUE)
1348 {
1349 /* The user set it wrong. */
1350 error (_("Enabled packet %s (%s) not recognized by stub"),
1351 config->name, config->title);
d471ea57 1352 }
4082afcc
PA
1353
1354 if (remote_debug)
1355 fprintf_unfiltered (gdb_stdlog,
1356 "Packet %s (%s) is NOT supported\n",
1357 config->name, config->title);
1358 config->support = PACKET_DISABLE;
a76d924d 1359 break;
5a2468f5 1360 }
a76d924d
DJ
1361
1362 return result;
5a2468f5
JM
1363}
1364
444abaca
DJ
1365enum {
1366 PACKET_vCont = 0,
1367 PACKET_X,
1368 PACKET_qSymbol,
1369 PACKET_P,
1370 PACKET_p,
1371 PACKET_Z0,
1372 PACKET_Z1,
1373 PACKET_Z2,
1374 PACKET_Z3,
1375 PACKET_Z4,
15a201c8 1376 PACKET_vFile_setfs,
a6b151f1
DJ
1377 PACKET_vFile_open,
1378 PACKET_vFile_pread,
1379 PACKET_vFile_pwrite,
1380 PACKET_vFile_close,
1381 PACKET_vFile_unlink,
b9e7b9c3 1382 PACKET_vFile_readlink,
0a93529c 1383 PACKET_vFile_fstat,
0876f84a 1384 PACKET_qXfer_auxv,
23181151 1385 PACKET_qXfer_features,
c78fa86a 1386 PACKET_qXfer_exec_file,
cfa9d6d9 1387 PACKET_qXfer_libraries,
2268b414 1388 PACKET_qXfer_libraries_svr4,
fd79ecee 1389 PACKET_qXfer_memory_map,
0e7f50da
UW
1390 PACKET_qXfer_spu_read,
1391 PACKET_qXfer_spu_write,
07e059b5 1392 PACKET_qXfer_osdata,
dc146f7c 1393 PACKET_qXfer_threads,
0fb4aa4b 1394 PACKET_qXfer_statictrace_read,
b3b9301e 1395 PACKET_qXfer_traceframe_info,
169081d0 1396 PACKET_qXfer_uib,
711e434b 1397 PACKET_qGetTIBAddr,
444abaca 1398 PACKET_qGetTLSAddr,
be2a5f71 1399 PACKET_qSupported,
bd3eecc3 1400 PACKET_qTStatus,
89be2091 1401 PACKET_QPassSignals,
82075af2 1402 PACKET_QCatchSyscalls,
9b224c5e 1403 PACKET_QProgramSignals,
936d2992 1404 PACKET_qCRC,
08388c79 1405 PACKET_qSearch_memory,
2d717e4f
DJ
1406 PACKET_vAttach,
1407 PACKET_vRun,
a6f3e723 1408 PACKET_QStartNoAckMode,
82f73884 1409 PACKET_vKill,
4aa995e1
PA
1410 PACKET_qXfer_siginfo_read,
1411 PACKET_qXfer_siginfo_write,
0b16c5cf 1412 PACKET_qAttached,
4082afcc
PA
1413
1414 /* Support for conditional tracepoints. */
782b2b07 1415 PACKET_ConditionalTracepoints,
4082afcc
PA
1416
1417 /* Support for target-side breakpoint conditions. */
3788aec7 1418 PACKET_ConditionalBreakpoints,
4082afcc
PA
1419
1420 /* Support for target-side breakpoint commands. */
d3ce09f5 1421 PACKET_BreakpointCommands,
4082afcc
PA
1422
1423 /* Support for fast tracepoints. */
7a697b8d 1424 PACKET_FastTracepoints,
4082afcc
PA
1425
1426 /* Support for static tracepoints. */
0fb4aa4b 1427 PACKET_StaticTracepoints,
4082afcc
PA
1428
1429 /* Support for installing tracepoints while a trace experiment is
1430 running. */
1e4d1764 1431 PACKET_InstallInTrace,
4082afcc 1432
40ab02ce
MS
1433 PACKET_bc,
1434 PACKET_bs,
409873ef 1435 PACKET_TracepointSource,
d914c394 1436 PACKET_QAllow,
78d85199 1437 PACKET_qXfer_fdpic,
03583c20 1438 PACKET_QDisableRandomization,
d1feda86 1439 PACKET_QAgent,
f6f899bf 1440 PACKET_QTBuffer_size,
9accd112
MM
1441 PACKET_Qbtrace_off,
1442 PACKET_Qbtrace_bts,
b20a6524 1443 PACKET_Qbtrace_pt,
9accd112 1444 PACKET_qXfer_btrace,
4082afcc
PA
1445
1446 /* Support for the QNonStop packet. */
1447 PACKET_QNonStop,
1448
65706a29
PA
1449 /* Support for the QThreadEvents packet. */
1450 PACKET_QThreadEvents,
1451
4082afcc
PA
1452 /* Support for multi-process extensions. */
1453 PACKET_multiprocess_feature,
1454
1455 /* Support for enabling and disabling tracepoints while a trace
1456 experiment is running. */
1457 PACKET_EnableDisableTracepoints_feature,
1458
1459 /* Support for collecting strings using the tracenz bytecode. */
1460 PACKET_tracenz_feature,
1461
1462 /* Support for continuing to run a trace experiment while GDB is
1463 disconnected. */
1464 PACKET_DisconnectedTracing_feature,
1465
1466 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1467 PACKET_augmented_libraries_svr4_read_feature,
1468
f4abbc16
MM
1469 /* Support for the qXfer:btrace-conf:read packet. */
1470 PACKET_qXfer_btrace_conf,
1471
d33501a5
MM
1472 /* Support for the Qbtrace-conf:bts:size packet. */
1473 PACKET_Qbtrace_conf_bts_size,
1474
f7e6eed5
PA
1475 /* Support for swbreak+ feature. */
1476 PACKET_swbreak_feature,
1477
1478 /* Support for hwbreak+ feature. */
1479 PACKET_hwbreak_feature,
1480
89245bc0
DB
1481 /* Support for fork events. */
1482 PACKET_fork_event_feature,
1483
1484 /* Support for vfork events. */
1485 PACKET_vfork_event_feature,
1486
b20a6524
MM
1487 /* Support for the Qbtrace-conf:pt:size packet. */
1488 PACKET_Qbtrace_conf_pt_size,
1489
94585166
DB
1490 /* Support for exec events. */
1491 PACKET_exec_event_feature,
1492
750ce8d1
YQ
1493 /* Support for query supported vCont actions. */
1494 PACKET_vContSupported,
1495
de979965
PA
1496 /* Support remote CTRL-C. */
1497 PACKET_vCtrlC,
1498
f2faf941
PA
1499 /* Support TARGET_WAITKIND_NO_RESUMED. */
1500 PACKET_no_resumed,
1501
444abaca
DJ
1502 PACKET_MAX
1503};
506fb367 1504
444abaca 1505static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1506
f7e6eed5
PA
1507/* Returns the packet's corresponding "set remote foo-packet" command
1508 state. See struct packet_config for more details. */
1509
1510static enum auto_boolean
1511packet_set_cmd_state (int packet)
1512{
1513 return remote_protocol_packets[packet].detect;
1514}
1515
4082afcc
PA
1516/* Returns whether a given packet or feature is supported. This takes
1517 into account the state of the corresponding "set remote foo-packet"
1518 command, which may be used to bypass auto-detection. */
dc8acb97 1519
4082afcc
PA
1520static enum packet_support
1521packet_config_support (struct packet_config *config)
1522{
1523 switch (config->detect)
444abaca 1524 {
4082afcc
PA
1525 case AUTO_BOOLEAN_TRUE:
1526 return PACKET_ENABLE;
1527 case AUTO_BOOLEAN_FALSE:
1528 return PACKET_DISABLE;
1529 case AUTO_BOOLEAN_AUTO:
1530 return config->support;
1531 default:
1532 gdb_assert_not_reached (_("bad switch"));
444abaca 1533 }
4082afcc
PA
1534}
1535
1536/* Same as packet_config_support, but takes the packet's enum value as
1537 argument. */
1538
1539static enum packet_support
1540packet_support (int packet)
1541{
1542 struct packet_config *config = &remote_protocol_packets[packet];
1543
1544 return packet_config_support (config);
dc8acb97
MS
1545}
1546
5a2468f5 1547static void
444abaca
DJ
1548show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1549 struct cmd_list_element *c,
1550 const char *value)
5a2468f5 1551{
444abaca 1552 struct packet_config *packet;
5a2468f5 1553
444abaca
DJ
1554 for (packet = remote_protocol_packets;
1555 packet < &remote_protocol_packets[PACKET_MAX];
1556 packet++)
1557 {
1558 if (&packet->detect == c->var)
1559 {
1560 show_packet_config_cmd (packet);
1561 return;
1562 }
1563 }
9b20d036 1564 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1565 c->name);
5a2468f5
JM
1566}
1567
d471ea57
AC
1568/* Should we try one of the 'Z' requests? */
1569
1570enum Z_packet_type
1571{
1572 Z_PACKET_SOFTWARE_BP,
1573 Z_PACKET_HARDWARE_BP,
1574 Z_PACKET_WRITE_WP,
1575 Z_PACKET_READ_WP,
1576 Z_PACKET_ACCESS_WP,
1577 NR_Z_PACKET_TYPES
1578};
96baa820 1579
d471ea57 1580/* For compatibility with older distributions. Provide a ``set remote
23860348 1581 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1582
7f19b9a2 1583static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1584
1585static void
fba45db2
KB
1586set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1587 struct cmd_list_element *c)
96baa820 1588{
d471ea57 1589 int i;
a744cf53 1590
d471ea57 1591 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1592 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1593}
1594
1595static void
08546159
AC
1596show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1597 struct cmd_list_element *c,
1598 const char *value)
96baa820 1599{
d471ea57 1600 int i;
a744cf53 1601
d471ea57
AC
1602 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1603 {
444abaca 1604 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1605 }
96baa820
JM
1606}
1607
4082afcc
PA
1608/* Returns true if the multi-process extensions are in effect. */
1609
1610static int
1611remote_multi_process_p (struct remote_state *rs)
1612{
1613 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1614}
1615
de0d863e
DB
1616/* Returns true if fork events are supported. */
1617
1618static int
1619remote_fork_event_p (struct remote_state *rs)
1620{
1621 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1622}
1623
c269dbdb
DB
1624/* Returns true if vfork events are supported. */
1625
1626static int
1627remote_vfork_event_p (struct remote_state *rs)
1628{
1629 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1630}
1631
d46addbb
DB
1632/* Returns true if exec events are supported. */
1633
1634static int
1635remote_exec_event_p (struct remote_state *rs)
1636{
1637 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1638}
1639
cbb8991c
DB
1640/* Insert fork catchpoint target routine. If fork events are enabled
1641 then return success, nothing more to do. */
1642
1643static int
1644remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1645{
1646 struct remote_state *rs = get_remote_state ();
1647
1648 return !remote_fork_event_p (rs);
1649}
1650
1651/* Remove fork catchpoint target routine. Nothing to do, just
1652 return success. */
1653
1654static int
1655remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1656{
1657 return 0;
1658}
1659
1660/* Insert vfork catchpoint target routine. If vfork events are enabled
1661 then return success, nothing more to do. */
1662
1663static int
1664remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1665{
1666 struct remote_state *rs = get_remote_state ();
1667
1668 return !remote_vfork_event_p (rs);
1669}
1670
1671/* Remove vfork catchpoint target routine. Nothing to do, just
1672 return success. */
1673
1674static int
1675remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1676{
1677 return 0;
1678}
1679
d46addbb
DB
1680/* Insert exec catchpoint target routine. If exec events are
1681 enabled, just return success. */
1682
1683static int
1684remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1685{
1686 struct remote_state *rs = get_remote_state ();
1687
1688 return !remote_exec_event_p (rs);
1689}
1690
1691/* Remove exec catchpoint target routine. Nothing to do, just
1692 return success. */
1693
1694static int
1695remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1696{
1697 return 0;
1698}
1699
74531fed
PA
1700\f
1701/* Asynchronous signal handle registered as event loop source for
1702 when we have pending events ready to be passed to the core. */
1703
1704static struct async_event_handler *remote_async_inferior_event_token;
1705
c906108c
SS
1706\f
1707
79d7f229
PA
1708static ptid_t magic_null_ptid;
1709static ptid_t not_sent_ptid;
1710static ptid_t any_thread_ptid;
1711
0b16c5cf
PA
1712/* Find out if the stub attached to PID (and hence GDB should offer to
1713 detach instead of killing it when bailing out). */
1714
1715static int
1716remote_query_attached (int pid)
1717{
1718 struct remote_state *rs = get_remote_state ();
bba74b36 1719 size_t size = get_remote_packet_size ();
0b16c5cf 1720
4082afcc 1721 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1722 return 0;
1723
1724 if (remote_multi_process_p (rs))
bba74b36 1725 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1726 else
bba74b36 1727 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1728
1729 putpkt (rs->buf);
1730 getpkt (&rs->buf, &rs->buf_size, 0);
1731
1732 switch (packet_ok (rs->buf,
1554e9be 1733 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1734 {
1735 case PACKET_OK:
1736 if (strcmp (rs->buf, "1") == 0)
1737 return 1;
1738 break;
1739 case PACKET_ERROR:
1740 warning (_("Remote failure reply: %s"), rs->buf);
1741 break;
1742 case PACKET_UNKNOWN:
1743 break;
1744 }
1745
1746 return 0;
1747}
1748
49c62f2e
PA
1749/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1750 has been invented by GDB, instead of reported by the target. Since
1751 we can be connected to a remote system before before knowing about
1752 any inferior, mark the target with execution when we find the first
1753 inferior. If ATTACHED is 1, then we had just attached to this
1754 inferior. If it is 0, then we just created this inferior. If it
1755 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1756 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1757 attempt to open this inferior's executable as the main executable
1758 if no main executable is open already. */
1941c569
PA
1759
1760static struct inferior *
1b6e6f5c
GB
1761remote_add_inferior (int fake_pid_p, int pid, int attached,
1762 int try_open_exec)
1941c569 1763{
1941c569
PA
1764 struct inferior *inf;
1765
0b16c5cf
PA
1766 /* Check whether this process we're learning about is to be
1767 considered attached, or if is to be considered to have been
1768 spawned by the stub. */
1769 if (attached == -1)
1770 attached = remote_query_attached (pid);
1771
f5656ead 1772 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1773 {
1774 /* If the target shares code across all inferiors, then every
1775 attach adds a new inferior. */
1776 inf = add_inferior (pid);
1777
1778 /* ... and every inferior is bound to the same program space.
1779 However, each inferior may still have its own address
1780 space. */
1781 inf->aspace = maybe_new_address_space ();
1782 inf->pspace = current_program_space;
1783 }
1784 else
1785 {
1786 /* In the traditional debugging scenario, there's a 1-1 match
1787 between program/address spaces. We simply bind the inferior
1788 to the program space's address space. */
1789 inf = current_inferior ();
1790 inferior_appeared (inf, pid);
1791 }
1941c569 1792
0b16c5cf 1793 inf->attach_flag = attached;
49c62f2e 1794 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1795
1b6e6f5c
GB
1796 /* If no main executable is currently open then attempt to
1797 open the file that was executed to create this inferior. */
835205d0 1798 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1799 exec_file_locate_attach (pid, 1);
1800
1941c569
PA
1801 return inf;
1802}
1803
1804/* Add thread PTID to GDB's thread list. Tag it as executing/running
1805 according to RUNNING. */
1806
c906108c 1807static void
0d5b594f 1808remote_add_thread (ptid_t ptid, int running, int executing)
c906108c 1809{
b7ea362b
PA
1810 struct remote_state *rs = get_remote_state ();
1811
1812 /* GDB historically didn't pull threads in the initial connection
1813 setup. If the remote target doesn't even have a concept of
1814 threads (e.g., a bare-metal target), even if internally we
1815 consider that a single-threaded target, mentioning a new thread
1816 might be confusing to the user. Be silent then, preserving the
1817 age old behavior. */
1818 if (rs->starting_up)
1819 add_thread_silent (ptid);
1820 else
1821 add_thread (ptid);
1941c569 1822
0d5b594f 1823 set_executing (ptid, executing);
1941c569
PA
1824 set_running (ptid, running);
1825}
1826
1827/* Come here when we learn about a thread id from the remote target.
1828 It may be the first time we hear about such thread, so take the
1829 opportunity to add it to GDB's thread list. In case this is the
1830 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
1831 GDB's inferior list as well. EXECUTING indicates whether the
1832 thread is (internally) executing or stopped. */
1941c569
PA
1833
1834static void
0d5b594f 1835remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 1836{
0d5b594f
PA
1837 /* In non-stop mode, we assume new found threads are (externally)
1838 running until proven otherwise with a stop reply. In all-stop,
1839 we can only get here if all threads are stopped. */
1840 int running = target_is_non_stop_p () ? 1 : 0;
1841
c906108c
SS
1842 /* If this is a new thread, add it to GDB's thread list.
1843 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1844
1845 if (in_thread_list (currthread) && is_exited (currthread))
1846 {
1847 /* We're seeing an event on a thread id we knew had exited.
1848 This has to be a new thread reusing the old id. Add it. */
0d5b594f 1849 remote_add_thread (currthread, running, executing);
82f73884
PA
1850 return;
1851 }
1852
79d7f229 1853 if (!in_thread_list (currthread))
c0a2216e 1854 {
1941c569 1855 struct inferior *inf = NULL;
bad34192 1856 int pid = ptid_get_pid (currthread);
1941c569 1857
bad34192
PA
1858 if (ptid_is_pid (inferior_ptid)
1859 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1860 {
1861 /* inferior_ptid has no thread member yet. This can happen
1862 with the vAttach -> remote_wait,"TAAthread:" path if the
1863 stub doesn't support qC. This is the first stop reported
1864 after an attach, so this is the main thread. Update the
1865 ptid in the thread list. */
bad34192
PA
1866 if (in_thread_list (pid_to_ptid (pid)))
1867 thread_change_ptid (inferior_ptid, currthread);
1868 else
1869 {
0d5b594f 1870 remote_add_thread (currthread, running, executing);
bad34192
PA
1871 inferior_ptid = currthread;
1872 }
dc146f7c 1873 return;
c0a2216e 1874 }
82f73884
PA
1875
1876 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1877 {
1878 /* inferior_ptid is not set yet. This can happen with the
1879 vRun -> remote_wait,"TAAthread:" path if the stub
1880 doesn't support qC. This is the first stop reported
1881 after an attach, so this is the main thread. Update the
1882 ptid in the thread list. */
dc146f7c 1883 thread_change_ptid (inferior_ptid, currthread);
82f73884 1884 return;
c0a2216e 1885 }
82f73884 1886
29c87f7f
PA
1887 /* When connecting to a target remote, or to a target
1888 extended-remote which already was debugging an inferior, we
1889 may not know about it yet. Add it before adding its child
1890 thread, so notifications are emitted in a sensible order. */
1891 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1892 {
1893 struct remote_state *rs = get_remote_state ();
1894 int fake_pid_p = !remote_multi_process_p (rs);
1895
1896 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1897 ptid_get_pid (currthread), -1, 1);
49c62f2e 1898 }
29c87f7f 1899
82f73884 1900 /* This is really a new thread. Add it. */
0d5b594f 1901 remote_add_thread (currthread, running, executing);
1941c569
PA
1902
1903 /* If we found a new inferior, let the common code do whatever
1904 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1905 breakpoints), unless we're just setting up an all-stop
1906 connection. */
1941c569 1907 if (inf != NULL)
b7ea362b
PA
1908 {
1909 struct remote_state *rs = get_remote_state ();
1910
6efcd9a8 1911 if (!rs->starting_up)
0d5b594f 1912 notice_new_inferior (currthread, executing, 0);
b7ea362b 1913 }
c0a2216e 1914 }
c906108c
SS
1915}
1916
dc146f7c
VP
1917/* Return the private thread data, creating it if necessary. */
1918
70221824 1919static struct private_thread_info *
dc146f7c
VP
1920demand_private_info (ptid_t ptid)
1921{
1922 struct thread_info *info = find_thread_ptid (ptid);
1923
1924 gdb_assert (info);
1925
fe978cb0 1926 if (!info->priv)
dc146f7c 1927 {
8d749320 1928 info->priv = XNEW (struct private_thread_info);
dc146f7c 1929 info->private_dtor = free_private_thread_info;
fe978cb0 1930 info->priv->core = -1;
8020350c
DB
1931 info->priv->extra = NULL;
1932 info->priv->name = NULL;
dc146f7c
VP
1933 }
1934
fe978cb0 1935 return info->priv;
dc146f7c
VP
1936}
1937
74531fed
PA
1938/* Call this function as a result of
1939 1) A halt indication (T packet) containing a thread id
1940 2) A direct query of currthread
0df8b418 1941 3) Successful execution of set thread */
74531fed
PA
1942
1943static void
47f8a51d 1944record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1945{
47f8a51d 1946 rs->general_thread = currthread;
74531fed
PA
1947}
1948
89be2091
DJ
1949/* If 'QPassSignals' is supported, tell the remote stub what signals
1950 it can simply pass through to the inferior without reporting. */
1951
1952static void
94bedb42
TT
1953remote_pass_signals (struct target_ops *self,
1954 int numsigs, unsigned char *pass_signals)
89be2091 1955{
4082afcc 1956 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1957 {
1958 char *pass_packet, *p;
89be2091 1959 int count = 0, i;
747dc59d 1960 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1961
1962 gdb_assert (numsigs < 256);
1963 for (i = 0; i < numsigs; i++)
1964 {
2455069d 1965 if (pass_signals[i])
89be2091
DJ
1966 count++;
1967 }
224c3ddb 1968 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
1969 strcpy (pass_packet, "QPassSignals:");
1970 p = pass_packet + strlen (pass_packet);
1971 for (i = 0; i < numsigs; i++)
1972 {
2455069d 1973 if (pass_signals[i])
89be2091
DJ
1974 {
1975 if (i >= 16)
1976 *p++ = tohex (i >> 4);
1977 *p++ = tohex (i & 15);
1978 if (count)
1979 *p++ = ';';
1980 else
1981 break;
1982 count--;
1983 }
1984 }
1985 *p = 0;
747dc59d 1986 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1987 {
89be2091
DJ
1988 putpkt (pass_packet);
1989 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1990 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1991 if (rs->last_pass_packet)
1992 xfree (rs->last_pass_packet);
1993 rs->last_pass_packet = pass_packet;
89be2091
DJ
1994 }
1995 else
1996 xfree (pass_packet);
1997 }
1998}
1999
82075af2
JS
2000/* If 'QCatchSyscalls' is supported, tell the remote stub
2001 to report syscalls to GDB. */
2002
2003static int
2004remote_set_syscall_catchpoint (struct target_ops *self,
2005 int pid, int needed, int any_count,
2006 int table_size, int *table)
2007{
2008 char *catch_packet;
2009 enum packet_result result;
2010 int n_sysno = 0;
2011
2012 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2013 {
2014 /* Not supported. */
2015 return 1;
2016 }
2017
2018 if (needed && !any_count)
2019 {
2020 int i;
2021
2022 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2023 for (i = 0; i < table_size; i++)
2024 {
2025 if (table[i] != 0)
2026 n_sysno++;
2027 }
2028 }
2029
2030 if (remote_debug)
2031 {
2032 fprintf_unfiltered (gdb_stdlog,
2033 "remote_set_syscall_catchpoint "
2034 "pid %d needed %d any_count %d n_sysno %d\n",
2035 pid, needed, any_count, n_sysno);
2036 }
2037
2038 if (needed)
2039 {
2040 /* Prepare a packet with the sysno list, assuming max 8+1
2041 characters for a sysno. If the resulting packet size is too
2042 big, fallback on the non-selective packet. */
2043 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2044
c0518081 2045 catch_packet = (char *) xmalloc (maxpktsz);
82075af2
JS
2046 strcpy (catch_packet, "QCatchSyscalls:1");
2047 if (!any_count)
2048 {
2049 int i;
2050 char *p;
2051
2052 p = catch_packet;
2053 p += strlen (p);
2054
2055 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2056 for (i = 0; i < table_size; i++)
2057 {
2058 if (table[i] != 0)
2059 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2060 }
2061 }
2062 if (strlen (catch_packet) > get_remote_packet_size ())
2063 {
2064 /* catch_packet too big. Fallback to less efficient
2065 non selective mode, with GDB doing the filtering. */
2066 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2067 }
2068 }
2069 else
2070 catch_packet = xstrdup ("QCatchSyscalls:0");
2071
2072 {
2073 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2074 struct remote_state *rs = get_remote_state ();
2075
2076 putpkt (catch_packet);
2077 getpkt (&rs->buf, &rs->buf_size, 0);
2078 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2079 do_cleanups (old_chain);
2080 if (result == PACKET_OK)
2081 return 0;
2082 else
2083 return -1;
2084 }
2085}
2086
9b224c5e
PA
2087/* If 'QProgramSignals' is supported, tell the remote stub what
2088 signals it should pass through to the inferior when detaching. */
2089
2090static void
daf5e9b6
TT
2091remote_program_signals (struct target_ops *self,
2092 int numsigs, unsigned char *signals)
9b224c5e 2093{
4082afcc 2094 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2095 {
2096 char *packet, *p;
2097 int count = 0, i;
5e4a05c4 2098 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2099
2100 gdb_assert (numsigs < 256);
2101 for (i = 0; i < numsigs; i++)
2102 {
2103 if (signals[i])
2104 count++;
2105 }
224c3ddb 2106 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2107 strcpy (packet, "QProgramSignals:");
2108 p = packet + strlen (packet);
2109 for (i = 0; i < numsigs; i++)
2110 {
2111 if (signal_pass_state (i))
2112 {
2113 if (i >= 16)
2114 *p++ = tohex (i >> 4);
2115 *p++ = tohex (i & 15);
2116 if (count)
2117 *p++ = ';';
2118 else
2119 break;
2120 count--;
2121 }
2122 }
2123 *p = 0;
5e4a05c4
TT
2124 if (!rs->last_program_signals_packet
2125 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2126 {
9b224c5e
PA
2127 putpkt (packet);
2128 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2129 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2130 xfree (rs->last_program_signals_packet);
2131 rs->last_program_signals_packet = packet;
9b224c5e
PA
2132 }
2133 else
2134 xfree (packet);
2135 }
2136}
2137
79d7f229
PA
2138/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2139 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2140 thread. If GEN is set, set the general thread, if not, then set
2141 the step/continue thread. */
c906108c 2142static void
79d7f229 2143set_thread (struct ptid ptid, int gen)
c906108c 2144{
d01949b6 2145 struct remote_state *rs = get_remote_state ();
47f8a51d 2146 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2147 char *buf = rs->buf;
79d7f229 2148 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2149
79d7f229 2150 if (ptid_equal (state, ptid))
c906108c
SS
2151 return;
2152
79d7f229
PA
2153 *buf++ = 'H';
2154 *buf++ = gen ? 'g' : 'c';
2155 if (ptid_equal (ptid, magic_null_ptid))
2156 xsnprintf (buf, endbuf - buf, "0");
2157 else if (ptid_equal (ptid, any_thread_ptid))
2158 xsnprintf (buf, endbuf - buf, "0");
2159 else if (ptid_equal (ptid, minus_one_ptid))
2160 xsnprintf (buf, endbuf - buf, "-1");
2161 else
82f73884 2162 write_ptid (buf, endbuf, ptid);
79d7f229 2163 putpkt (rs->buf);
6d820c5c 2164 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2165 if (gen)
47f8a51d 2166 rs->general_thread = ptid;
c906108c 2167 else
47f8a51d 2168 rs->continue_thread = ptid;
c906108c 2169}
79d7f229
PA
2170
2171static void
2172set_general_thread (struct ptid ptid)
2173{
2174 set_thread (ptid, 1);
2175}
2176
2177static void
2178set_continue_thread (struct ptid ptid)
2179{
2180 set_thread (ptid, 0);
2181}
2182
3c9c4b83
PA
2183/* Change the remote current process. Which thread within the process
2184 ends up selected isn't important, as long as it is the same process
2185 as what INFERIOR_PTID points to.
2186
2187 This comes from that fact that there is no explicit notion of
2188 "selected process" in the protocol. The selected process for
2189 general operations is the process the selected general thread
2190 belongs to. */
2191
2192static void
2193set_general_process (void)
2194{
2195 struct remote_state *rs = get_remote_state ();
2196
2197 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2198 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2199 return;
2200
2201 /* We only need to change the remote current thread if it's pointing
2202 at some other process. */
47f8a51d 2203 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2204 set_general_thread (inferior_ptid);
2205}
2206
c906108c 2207\f
7d1a114c
PA
2208/* Return nonzero if this is the main thread that we made up ourselves
2209 to model non-threaded targets as single-threaded. */
c906108c
SS
2210
2211static int
7d1a114c 2212remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2213{
c0a2216e
PA
2214 if (ptid_equal (ptid, magic_null_ptid))
2215 /* The main thread is always alive. */
2216 return 1;
2217
ba348170 2218 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2219 /* The main thread is always alive. This can happen after a
2220 vAttach, if the remote side doesn't support
2221 multi-threading. */
2222 return 1;
2223
7d1a114c
PA
2224 return 0;
2225}
2226
2227/* Return nonzero if the thread PTID is still alive on the remote
2228 system. */
2229
2230static int
2231remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2232{
2233 struct remote_state *rs = get_remote_state ();
2234 char *p, *endp;
2235
2236 /* Check if this is a thread that we made up ourselves to model
2237 non-threaded targets as single-threaded. */
2238 if (remote_thread_always_alive (ops, ptid))
2239 return 1;
2240
82f73884
PA
2241 p = rs->buf;
2242 endp = rs->buf + get_remote_packet_size ();
2243
2244 *p++ = 'T';
2245 write_ptid (p, endp, ptid);
2246
2e9f7625 2247 putpkt (rs->buf);
6d820c5c 2248 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2249 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2250}
2251
79efa585
SM
2252/* Return a pointer to a thread name if we know it and NULL otherwise.
2253 The thread_info object owns the memory for the name. */
2254
2255static const char *
2256remote_thread_name (struct target_ops *ops, struct thread_info *info)
2257{
2258 if (info->priv != NULL)
2259 return info->priv->name;
2260
2261 return NULL;
2262}
2263
c906108c
SS
2264/* About these extended threadlist and threadinfo packets. They are
2265 variable length packets but, the fields within them are often fixed
2266 length. They are redundent enough to send over UDP as is the
2267 remote protocol in general. There is a matching unit test module
2268 in libstub. */
2269
23860348 2270/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2271 libstub protocol encoding, and remote.c. It is not particularly
23860348 2272 changable. */
cce74817
JM
2273
2274/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2275 Plan to fix this. */
cce74817 2276
23860348 2277typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2278
9d1f7ab2 2279/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2280 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2281
2282struct gdb_ext_thread_info
c5aa993b 2283 {
23860348 2284 threadref threadid; /* External form of thread reference. */
2bc416ba 2285 int active; /* Has state interesting to GDB?
23860348 2286 regs, stack. */
2bc416ba 2287 char display[256]; /* Brief state display, name,
cedea757 2288 blocked/suspended. */
23860348 2289 char shortname[32]; /* To be used to name threads. */
2bc416ba 2290 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2291 whatever. */
c5aa993b 2292 };
cce74817
JM
2293
2294/* The volume of remote transfers can be limited by submitting
2295 a mask containing bits specifying the desired information.
2296 Use a union of these values as the 'selection' parameter to
0df8b418 2297 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2298
2299#define TAG_THREADID 1
2300#define TAG_EXISTS 2
2301#define TAG_DISPLAY 4
2302#define TAG_THREADNAME 8
c5aa993b 2303#define TAG_MOREDISPLAY 16
cce74817 2304
23860348 2305#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2306
a14ed312 2307static char *unpack_nibble (char *buf, int *val);
cce74817 2308
a14ed312 2309static char *unpack_byte (char *buf, int *value);
cce74817 2310
a14ed312 2311static char *pack_int (char *buf, int value);
cce74817 2312
a14ed312 2313static char *unpack_int (char *buf, int *value);
cce74817 2314
a14ed312 2315static char *unpack_string (char *src, char *dest, int length);
cce74817 2316
23860348 2317static char *pack_threadid (char *pkt, threadref *id);
cce74817 2318
23860348 2319static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2320
23860348 2321void int_to_threadref (threadref *id, int value);
cce74817 2322
23860348 2323static int threadref_to_int (threadref *ref);
cce74817 2324
23860348 2325static void copy_threadref (threadref *dest, threadref *src);
cce74817 2326
23860348 2327static int threadmatch (threadref *dest, threadref *src);
cce74817 2328
2bc416ba 2329static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2330 threadref *id);
cce74817 2331
a14ed312 2332static int remote_unpack_thread_info_response (char *pkt,
23860348 2333 threadref *expectedref,
a14ed312
KB
2334 struct gdb_ext_thread_info
2335 *info);
cce74817
JM
2336
2337
2bc416ba 2338static int remote_get_threadinfo (threadref *threadid,
23860348 2339 int fieldset, /*TAG mask */
a14ed312 2340 struct gdb_ext_thread_info *info);
cce74817 2341
a14ed312
KB
2342static char *pack_threadlist_request (char *pkt, int startflag,
2343 int threadcount,
23860348 2344 threadref *nextthread);
cce74817 2345
a14ed312
KB
2346static int parse_threadlist_response (char *pkt,
2347 int result_limit,
23860348 2348 threadref *original_echo,
2bc416ba 2349 threadref *resultlist,
23860348 2350 int *doneflag);
cce74817 2351
a14ed312 2352static int remote_get_threadlist (int startflag,
23860348 2353 threadref *nextthread,
a14ed312
KB
2354 int result_limit,
2355 int *done,
2bc416ba 2356 int *result_count,
23860348 2357 threadref *threadlist);
cce74817 2358
23860348 2359typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2360
a14ed312
KB
2361static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2362 void *context, int looplimit);
cce74817 2363
23860348 2364static int remote_newthread_step (threadref *ref, void *context);
cce74817 2365
82f73884
PA
2366
2367/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2368 buffer we're allowed to write to. Returns
2369 BUF+CHARACTERS_WRITTEN. */
2370
2371static char *
2372write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2373{
2374 int pid, tid;
2375 struct remote_state *rs = get_remote_state ();
2376
2377 if (remote_multi_process_p (rs))
2378 {
2379 pid = ptid_get_pid (ptid);
2380 if (pid < 0)
2381 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2382 else
2383 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2384 }
ba348170 2385 tid = ptid_get_lwp (ptid);
82f73884
PA
2386 if (tid < 0)
2387 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2388 else
2389 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2390
2391 return buf;
2392}
2393
2394/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2395 passed the last parsed char. Returns null_ptid on error. */
2396
2397static ptid_t
2398read_ptid (char *buf, char **obuf)
2399{
2400 char *p = buf;
2401 char *pp;
2402 ULONGEST pid = 0, tid = 0;
82f73884
PA
2403
2404 if (*p == 'p')
2405 {
2406 /* Multi-process ptid. */
2407 pp = unpack_varlen_hex (p + 1, &pid);
2408 if (*pp != '.')
b37520b6 2409 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2410
2411 p = pp;
2412 pp = unpack_varlen_hex (p + 1, &tid);
2413 if (obuf)
2414 *obuf = pp;
ba348170 2415 return ptid_build (pid, tid, 0);
82f73884
PA
2416 }
2417
2418 /* No multi-process. Just a tid. */
2419 pp = unpack_varlen_hex (p, &tid);
2420
c9f35b34
KB
2421 /* Return null_ptid when no thread id is found. */
2422 if (p == pp)
2423 {
2424 if (obuf)
2425 *obuf = pp;
2426 return null_ptid;
2427 }
2428
82f73884 2429 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2430 what's in inferior_ptid, unless it's null at this point. If so,
2431 then since there's no way to know the pid of the reported
2432 threads, use the magic number. */
2433 if (ptid_equal (inferior_ptid, null_ptid))
2434 pid = ptid_get_pid (magic_null_ptid);
2435 else
2436 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2437
2438 if (obuf)
2439 *obuf = pp;
ba348170 2440 return ptid_build (pid, tid, 0);
82f73884
PA
2441}
2442
c906108c 2443static int
fba45db2 2444stubhex (int ch)
c906108c
SS
2445{
2446 if (ch >= 'a' && ch <= 'f')
2447 return ch - 'a' + 10;
2448 if (ch >= '0' && ch <= '9')
2449 return ch - '0';
2450 if (ch >= 'A' && ch <= 'F')
2451 return ch - 'A' + 10;
2452 return -1;
2453}
2454
2455static int
fba45db2 2456stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2457{
2458 int nibble;
2459 int retval = 0;
2460
2461 while (fieldlength)
2462 {
2463 nibble = stubhex (*buff++);
2464 retval |= nibble;
2465 fieldlength--;
2466 if (fieldlength)
2467 retval = retval << 4;
2468 }
2469 return retval;
2470}
2471
c906108c 2472static char *
fba45db2 2473unpack_nibble (char *buf, int *val)
c906108c 2474{
b7589f7d 2475 *val = fromhex (*buf++);
c906108c
SS
2476 return buf;
2477}
2478
c906108c 2479static char *
fba45db2 2480unpack_byte (char *buf, int *value)
c906108c
SS
2481{
2482 *value = stub_unpack_int (buf, 2);
2483 return buf + 2;
2484}
2485
2486static char *
fba45db2 2487pack_int (char *buf, int value)
c906108c
SS
2488{
2489 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2490 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2491 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2492 buf = pack_hex_byte (buf, (value & 0xff));
2493 return buf;
2494}
2495
2496static char *
fba45db2 2497unpack_int (char *buf, int *value)
c906108c
SS
2498{
2499 *value = stub_unpack_int (buf, 8);
2500 return buf + 8;
2501}
2502
23860348 2503#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2504static char *pack_string (char *pkt, char *string);
c906108c
SS
2505
2506static char *
fba45db2 2507pack_string (char *pkt, char *string)
c906108c
SS
2508{
2509 char ch;
2510 int len;
2511
2512 len = strlen (string);
2513 if (len > 200)
23860348 2514 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2515 pkt = pack_hex_byte (pkt, len);
2516 while (len-- > 0)
2517 {
2518 ch = *string++;
2519 if ((ch == '\0') || (ch == '#'))
23860348 2520 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2521 *pkt++ = ch;
2522 }
2523 return pkt;
2524}
2525#endif /* 0 (unused) */
2526
2527static char *
fba45db2 2528unpack_string (char *src, char *dest, int length)
c906108c
SS
2529{
2530 while (length--)
2531 *dest++ = *src++;
2532 *dest = '\0';
2533 return src;
2534}
2535
2536static char *
fba45db2 2537pack_threadid (char *pkt, threadref *id)
c906108c
SS
2538{
2539 char *limit;
2540 unsigned char *altid;
2541
2542 altid = (unsigned char *) id;
2543 limit = pkt + BUF_THREAD_ID_SIZE;
2544 while (pkt < limit)
2545 pkt = pack_hex_byte (pkt, *altid++);
2546 return pkt;
2547}
2548
2549
2550static char *
fba45db2 2551unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2552{
2553 char *altref;
2554 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2555 int x, y;
2556
2557 altref = (char *) id;
2558
2559 while (inbuf < limit)
2560 {
2561 x = stubhex (*inbuf++);
2562 y = stubhex (*inbuf++);
2563 *altref++ = (x << 4) | y;
2564 }
2565 return inbuf;
2566}
2567
2568/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2569 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2570 to use 64bit thread references internally. This is an adapter
2571 function. */
2572
2573void
fba45db2 2574int_to_threadref (threadref *id, int value)
c906108c
SS
2575{
2576 unsigned char *scan;
2577
2578 scan = (unsigned char *) id;
2579 {
2580 int i = 4;
2581 while (i--)
2582 *scan++ = 0;
2583 }
2584 *scan++ = (value >> 24) & 0xff;
2585 *scan++ = (value >> 16) & 0xff;
2586 *scan++ = (value >> 8) & 0xff;
2587 *scan++ = (value & 0xff);
2588}
2589
2590static int
fba45db2 2591threadref_to_int (threadref *ref)
c906108c
SS
2592{
2593 int i, value = 0;
2594 unsigned char *scan;
2595
cfd77fa1 2596 scan = *ref;
c906108c
SS
2597 scan += 4;
2598 i = 4;
2599 while (i-- > 0)
2600 value = (value << 8) | ((*scan++) & 0xff);
2601 return value;
2602}
2603
2604static void
fba45db2 2605copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2606{
2607 int i;
2608 unsigned char *csrc, *cdest;
2609
2610 csrc = (unsigned char *) src;
2611 cdest = (unsigned char *) dest;
2612 i = 8;
2613 while (i--)
2614 *cdest++ = *csrc++;
2615}
2616
2617static int
fba45db2 2618threadmatch (threadref *dest, threadref *src)
c906108c 2619{
23860348 2620 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2621#if 0
2622 unsigned char *srcp, *destp;
2623 int i, result;
2624 srcp = (char *) src;
2625 destp = (char *) dest;
2626
2627 result = 1;
2628 while (i-- > 0)
2629 result &= (*srcp++ == *destp++) ? 1 : 0;
2630 return result;
2631#endif
2632 return 1;
2633}
2634
2635/*
c5aa993b
JM
2636 threadid:1, # always request threadid
2637 context_exists:2,
2638 display:4,
2639 unique_name:8,
2640 more_display:16
2641 */
c906108c
SS
2642
2643/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2644
2645static char *
fba45db2 2646pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2647{
23860348
MS
2648 *pkt++ = 'q'; /* Info Query */
2649 *pkt++ = 'P'; /* process or thread info */
2650 pkt = pack_int (pkt, mode); /* mode */
c906108c 2651 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2652 *pkt = '\0'; /* terminate */
c906108c
SS
2653 return pkt;
2654}
2655
23860348 2656/* These values tag the fields in a thread info response packet. */
c906108c 2657/* Tagging the fields allows us to request specific fields and to
23860348 2658 add more fields as time goes by. */
c906108c 2659
23860348 2660#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2661#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2662 fetch registers and its stack? */
c5aa993b 2663#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2664#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2665#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2666 the process. */
c906108c
SS
2667
2668static int
fba45db2
KB
2669remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2670 struct gdb_ext_thread_info *info)
c906108c 2671{
d01949b6 2672 struct remote_state *rs = get_remote_state ();
c906108c 2673 int mask, length;
cfd77fa1 2674 int tag;
c906108c 2675 threadref ref;
6d820c5c 2676 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2677 int retval = 1;
2678
23860348 2679 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2680 info->active = 0;
2681 info->display[0] = '\0';
2682 info->shortname[0] = '\0';
2683 info->more_display[0] = '\0';
2684
23860348
MS
2685 /* Assume the characters indicating the packet type have been
2686 stripped. */
c906108c
SS
2687 pkt = unpack_int (pkt, &mask); /* arg mask */
2688 pkt = unpack_threadid (pkt, &ref);
2689
2690 if (mask == 0)
8a3fe4f8 2691 warning (_("Incomplete response to threadinfo request."));
c906108c 2692 if (!threadmatch (&ref, expectedref))
23860348 2693 { /* This is an answer to a different request. */
8a3fe4f8 2694 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2695 return 0;
2696 }
2697 copy_threadref (&info->threadid, &ref);
2698
23860348 2699 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2700
23860348
MS
2701 /* Packets are terminated with nulls. */
2702 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2703 {
2704 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2705 pkt = unpack_byte (pkt, &length); /* length */
2706 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2707 {
8a3fe4f8 2708 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2709 retval = 0;
2710 break;
2711 }
2712 if (tag == TAG_THREADID)
2713 {
2714 if (length != 16)
2715 {
8a3fe4f8 2716 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2717 retval = 0;
2718 break;
2719 }
2720 pkt = unpack_threadid (pkt, &ref);
2721 mask = mask & ~TAG_THREADID;
2722 continue;
2723 }
2724 if (tag == TAG_EXISTS)
2725 {
2726 info->active = stub_unpack_int (pkt, length);
2727 pkt += length;
2728 mask = mask & ~(TAG_EXISTS);
2729 if (length > 8)
2730 {
8a3fe4f8 2731 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2732 retval = 0;
2733 break;
2734 }
2735 continue;
2736 }
2737 if (tag == TAG_THREADNAME)
2738 {
2739 pkt = unpack_string (pkt, &info->shortname[0], length);
2740 mask = mask & ~TAG_THREADNAME;
2741 continue;
2742 }
2743 if (tag == TAG_DISPLAY)
2744 {
2745 pkt = unpack_string (pkt, &info->display[0], length);
2746 mask = mask & ~TAG_DISPLAY;
2747 continue;
2748 }
2749 if (tag == TAG_MOREDISPLAY)
2750 {
2751 pkt = unpack_string (pkt, &info->more_display[0], length);
2752 mask = mask & ~TAG_MOREDISPLAY;
2753 continue;
2754 }
8a3fe4f8 2755 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2756 break; /* Not a tag we know about. */
c906108c
SS
2757 }
2758 return retval;
2759}
2760
2761static int
fba45db2
KB
2762remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2763 struct gdb_ext_thread_info *info)
c906108c 2764{
d01949b6 2765 struct remote_state *rs = get_remote_state ();
c906108c 2766 int result;
c906108c 2767
2e9f7625
DJ
2768 pack_threadinfo_request (rs->buf, fieldset, threadid);
2769 putpkt (rs->buf);
6d820c5c 2770 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2771
2772 if (rs->buf[0] == '\0')
2773 return 0;
2774
2e9f7625 2775 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2776 threadid, info);
c906108c
SS
2777 return result;
2778}
2779
c906108c
SS
2780/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2781
2782static char *
fba45db2
KB
2783pack_threadlist_request (char *pkt, int startflag, int threadcount,
2784 threadref *nextthread)
c906108c
SS
2785{
2786 *pkt++ = 'q'; /* info query packet */
2787 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2788 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2789 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2790 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2791 *pkt = '\0';
2792 return pkt;
2793}
2794
2795/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2796
2797static int
fba45db2
KB
2798parse_threadlist_response (char *pkt, int result_limit,
2799 threadref *original_echo, threadref *resultlist,
2800 int *doneflag)
c906108c 2801{
d01949b6 2802 struct remote_state *rs = get_remote_state ();
c906108c
SS
2803 char *limit;
2804 int count, resultcount, done;
2805
2806 resultcount = 0;
2807 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2808 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2809 /* done parse past here */
c906108c
SS
2810 pkt = unpack_byte (pkt, &count); /* count field */
2811 pkt = unpack_nibble (pkt, &done);
2812 /* The first threadid is the argument threadid. */
2813 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2814 while ((count-- > 0) && (pkt < limit))
2815 {
2816 pkt = unpack_threadid (pkt, resultlist++);
2817 if (resultcount++ >= result_limit)
2818 break;
2819 }
2820 if (doneflag)
2821 *doneflag = done;
2822 return resultcount;
2823}
2824
6dc54d91
PA
2825/* Fetch the next batch of threads from the remote. Returns -1 if the
2826 qL packet is not supported, 0 on error and 1 on success. */
2827
c906108c 2828static int
fba45db2
KB
2829remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2830 int *done, int *result_count, threadref *threadlist)
c906108c 2831{
d01949b6 2832 struct remote_state *rs = get_remote_state ();
c906108c
SS
2833 int result = 1;
2834
23860348 2835 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2836 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2837 >= get_remote_packet_size ())
ea9c271d 2838 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2839
6d820c5c
DJ
2840 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2841 putpkt (rs->buf);
2842 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2843 if (*rs->buf == '\0')
6dc54d91
PA
2844 {
2845 /* Packet not supported. */
2846 return -1;
2847 }
2848
2849 *result_count =
2850 parse_threadlist_response (rs->buf + 2, result_limit,
2851 &rs->echo_nextthread, threadlist, done);
c906108c 2852
0d031856 2853 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2854 {
23860348
MS
2855 /* FIXME: This is a good reason to drop the packet. */
2856 /* Possably, there is a duplicate response. */
c906108c
SS
2857 /* Possabilities :
2858 retransmit immediatly - race conditions
2859 retransmit after timeout - yes
2860 exit
2861 wait for packet, then exit
2862 */
8a3fe4f8 2863 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2864 return 0; /* I choose simply exiting. */
c906108c
SS
2865 }
2866 if (*result_count <= 0)
2867 {
2868 if (*done != 1)
2869 {
8a3fe4f8 2870 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2871 result = 0;
2872 }
2873 return result; /* break; */
2874 }
2875 if (*result_count > result_limit)
2876 {
2877 *result_count = 0;
8a3fe4f8 2878 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2879 return 0;
2880 }
2881 return result;
2882}
2883
6dc54d91
PA
2884/* Fetch the list of remote threads, with the qL packet, and call
2885 STEPFUNCTION for each thread found. Stops iterating and returns 1
2886 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2887 STEPFUNCTION returns false. If the packet is not supported,
2888 returns -1. */
c906108c 2889
c906108c 2890static int
fba45db2
KB
2891remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2892 int looplimit)
c906108c 2893{
0d031856 2894 struct remote_state *rs = get_remote_state ();
c906108c
SS
2895 int done, i, result_count;
2896 int startflag = 1;
2897 int result = 1;
2898 int loopcount = 0;
c906108c
SS
2899
2900 done = 0;
2901 while (!done)
2902 {
2903 if (loopcount++ > looplimit)
2904 {
2905 result = 0;
8a3fe4f8 2906 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2907 break;
2908 }
6dc54d91
PA
2909 result = remote_get_threadlist (startflag, &rs->nextthread,
2910 MAXTHREADLISTRESULTS,
2911 &done, &result_count,
2912 rs->resultthreadlist);
2913 if (result <= 0)
2914 break;
23860348 2915 /* Clear for later iterations. */
c906108c
SS
2916 startflag = 0;
2917 /* Setup to resume next batch of thread references, set nextthread. */
2918 if (result_count >= 1)
0d031856
TT
2919 copy_threadref (&rs->nextthread,
2920 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2921 i = 0;
2922 while (result_count--)
6dc54d91
PA
2923 {
2924 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2925 {
2926 result = 0;
2927 break;
2928 }
2929 }
c906108c
SS
2930 }
2931 return result;
2932}
2933
6dc54d91
PA
2934/* A thread found on the remote target. */
2935
2936typedef struct thread_item
2937{
2938 /* The thread's PTID. */
2939 ptid_t ptid;
2940
2941 /* The thread's extra info. May be NULL. */
2942 char *extra;
2943
79efa585
SM
2944 /* The thread's name. May be NULL. */
2945 char *name;
2946
6dc54d91
PA
2947 /* The core the thread was running on. -1 if not known. */
2948 int core;
2949} thread_item_t;
2950DEF_VEC_O(thread_item_t);
2951
2952/* Context passed around to the various methods listing remote
2953 threads. As new threads are found, they're added to the ITEMS
2954 vector. */
2955
2956struct threads_listing_context
2957{
2958 /* The threads found on the remote target. */
2959 VEC (thread_item_t) *items;
2960};
2961
80134cf5
PA
2962/* Discard the contents of the constructed thread listing context. */
2963
2964static void
2965clear_threads_listing_context (void *p)
2966{
19ba03f4
SM
2967 struct threads_listing_context *context
2968 = (struct threads_listing_context *) p;
80134cf5
PA
2969 int i;
2970 struct thread_item *item;
2971
2972 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
2973 {
2974 xfree (item->extra);
2975 xfree (item->name);
2976 }
80134cf5
PA
2977
2978 VEC_free (thread_item_t, context->items);
2979}
2980
cbb8991c
DB
2981/* Remove the thread specified as the related_pid field of WS
2982 from the CONTEXT list. */
2983
2984static void
2985threads_listing_context_remove (struct target_waitstatus *ws,
2986 struct threads_listing_context *context)
2987{
2988 struct thread_item *item;
2989 int i;
2990 ptid_t child_ptid = ws->value.related_pid;
2991
2992 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2993 {
2994 if (ptid_equal (item->ptid, child_ptid))
2995 {
2996 VEC_ordered_remove (thread_item_t, context->items, i);
2997 break;
2998 }
2999 }
3000}
3001
c906108c 3002static int
6dc54d91 3003remote_newthread_step (threadref *ref, void *data)
c906108c 3004{
19ba03f4
SM
3005 struct threads_listing_context *context
3006 = (struct threads_listing_context *) data;
6dc54d91 3007 struct thread_item item;
79d7f229 3008 int pid = ptid_get_pid (inferior_ptid);
39f77062 3009
6dc54d91
PA
3010 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3011 item.core = -1;
2e3b657e 3012 item.name = NULL;
6dc54d91
PA
3013 item.extra = NULL;
3014
3015 VEC_safe_push (thread_item_t, context->items, &item);
3016
c906108c
SS
3017 return 1; /* continue iterator */
3018}
3019
3020#define CRAZY_MAX_THREADS 1000
3021
39f77062
KB
3022static ptid_t
3023remote_current_thread (ptid_t oldpid)
c906108c 3024{
d01949b6 3025 struct remote_state *rs = get_remote_state ();
c906108c
SS
3026
3027 putpkt ("qC");
6d820c5c 3028 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3029 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
3030 {
3031 char *obuf;
3032 ptid_t result;
3033
3034 result = read_ptid (&rs->buf[2], &obuf);
3035 if (*obuf != '\0' && remote_debug)
3036 fprintf_unfiltered (gdb_stdlog,
3037 "warning: garbage in qC reply\n");
3038
3039 return result;
3040 }
c906108c
SS
3041 else
3042 return oldpid;
3043}
3044
6dc54d91 3045/* List remote threads using the deprecated qL packet. */
cce74817 3046
6dc54d91
PA
3047static int
3048remote_get_threads_with_ql (struct target_ops *ops,
3049 struct threads_listing_context *context)
c906108c 3050{
6dc54d91
PA
3051 if (remote_threadlist_iterator (remote_newthread_step, context,
3052 CRAZY_MAX_THREADS) >= 0)
3053 return 1;
3054
3055 return 0;
c906108c
SS
3056}
3057
dc146f7c
VP
3058#if defined(HAVE_LIBEXPAT)
3059
dc146f7c
VP
3060static void
3061start_thread (struct gdb_xml_parser *parser,
3062 const struct gdb_xml_element *element,
3063 void *user_data, VEC(gdb_xml_value_s) *attributes)
3064{
19ba03f4
SM
3065 struct threads_listing_context *data
3066 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3067
3068 struct thread_item item;
3069 char *id;
3d2c1d41 3070 struct gdb_xml_value *attr;
dc146f7c 3071
19ba03f4 3072 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
3073 item.ptid = read_ptid (id, NULL);
3074
3d2c1d41
PA
3075 attr = xml_find_attribute (attributes, "core");
3076 if (attr != NULL)
3077 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
3078 else
3079 item.core = -1;
3080
79efa585 3081 attr = xml_find_attribute (attributes, "name");
e1961661 3082 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 3083
dc146f7c
VP
3084 item.extra = 0;
3085
3086 VEC_safe_push (thread_item_t, data->items, &item);
3087}
3088
3089static void
3090end_thread (struct gdb_xml_parser *parser,
3091 const struct gdb_xml_element *element,
3092 void *user_data, const char *body_text)
3093{
19ba03f4
SM
3094 struct threads_listing_context *data
3095 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3096
3097 if (body_text && *body_text)
2ae2a0b7 3098 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3099}
3100
3101const struct gdb_xml_attribute thread_attributes[] = {
3102 { "id", GDB_XML_AF_NONE, NULL, NULL },
3103 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3104 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3105 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3106};
3107
3108const struct gdb_xml_element thread_children[] = {
3109 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3110};
3111
3112const struct gdb_xml_element threads_children[] = {
3113 { "thread", thread_attributes, thread_children,
3114 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3115 start_thread, end_thread },
3116 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3117};
3118
3119const struct gdb_xml_element threads_elements[] = {
3120 { "threads", NULL, threads_children,
3121 GDB_XML_EF_NONE, NULL, NULL },
3122 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3123};
3124
3125#endif
3126
6dc54d91 3127/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3128
6dc54d91
PA
3129static int
3130remote_get_threads_with_qxfer (struct target_ops *ops,
3131 struct threads_listing_context *context)
0f71a2f6 3132{
dc146f7c 3133#if defined(HAVE_LIBEXPAT)
4082afcc 3134 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3135 {
6dc54d91 3136 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3137 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3138
6dc54d91 3139 if (xml != NULL && *xml != '\0')
dc146f7c 3140 {
6dc54d91
PA
3141 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3142 threads_elements, xml, context);
dc146f7c
VP
3143 }
3144
3145 do_cleanups (back_to);
6dc54d91 3146 return 1;
dc146f7c
VP
3147 }
3148#endif
3149
6dc54d91
PA
3150 return 0;
3151}
3152
3153/* List remote threads using qfThreadInfo/qsThreadInfo. */
3154
3155static int
3156remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3157 struct threads_listing_context *context)
3158{
3159 struct remote_state *rs = get_remote_state ();
3160
b80fafe3 3161 if (rs->use_threadinfo_query)
9d1f7ab2 3162 {
6dc54d91
PA
3163 char *bufp;
3164
9d1f7ab2 3165 putpkt ("qfThreadInfo");
6d820c5c 3166 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3167 bufp = rs->buf;
9d1f7ab2 3168 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3169 {
9d1f7ab2
MS
3170 while (*bufp++ == 'm') /* reply contains one or more TID */
3171 {
3172 do
3173 {
6dc54d91
PA
3174 struct thread_item item;
3175
3176 item.ptid = read_ptid (bufp, &bufp);
3177 item.core = -1;
2e3b657e 3178 item.name = NULL;
6dc54d91
PA
3179 item.extra = NULL;
3180
3181 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3182 }
3183 while (*bufp++ == ','); /* comma-separated list */
3184 putpkt ("qsThreadInfo");
6d820c5c 3185 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3186 bufp = rs->buf;
9d1f7ab2 3187 }
6dc54d91
PA
3188 return 1;
3189 }
3190 else
3191 {
3192 /* Packet not recognized. */
3193 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3194 }
3195 }
3196
6dc54d91
PA
3197 return 0;
3198}
3199
e8032dde 3200/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3201 targets. */
3202
3203static void
e8032dde 3204remote_update_thread_list (struct target_ops *ops)
6dc54d91 3205{
6dc54d91
PA
3206 struct threads_listing_context context;
3207 struct cleanup *old_chain;
ab970af1 3208 int got_list = 0;
e8032dde 3209
6dc54d91
PA
3210 context.items = NULL;
3211 old_chain = make_cleanup (clear_threads_listing_context, &context);
3212
3213 /* We have a few different mechanisms to fetch the thread list. Try
3214 them all, starting with the most preferred one first, falling
3215 back to older methods. */
3216 if (remote_get_threads_with_qxfer (ops, &context)
3217 || remote_get_threads_with_qthreadinfo (ops, &context)
3218 || remote_get_threads_with_ql (ops, &context))
3219 {
3220 int i;
3221 struct thread_item *item;
ab970af1
PA
3222 struct thread_info *tp, *tmp;
3223
3224 got_list = 1;
3225
7d1a114c
PA
3226 if (VEC_empty (thread_item_t, context.items)
3227 && remote_thread_always_alive (ops, inferior_ptid))
3228 {
3229 /* Some targets don't really support threads, but still
3230 reply an (empty) thread list in response to the thread
3231 listing packets, instead of replying "packet not
3232 supported". Exit early so we don't delete the main
3233 thread. */
3234 do_cleanups (old_chain);
3235 return;
3236 }
3237
ab970af1
PA
3238 /* CONTEXT now holds the current thread list on the remote
3239 target end. Delete GDB-side threads no longer found on the
3240 target. */
8a06aea7 3241 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3242 {
ab970af1
PA
3243 for (i = 0;
3244 VEC_iterate (thread_item_t, context.items, i, item);
3245 ++i)
3246 {
3247 if (ptid_equal (item->ptid, tp->ptid))
3248 break;
3249 }
3250
3251 if (i == VEC_length (thread_item_t, context.items))
3252 {
3253 /* Not found. */
3254 delete_thread (tp->ptid);
3255 }
cbb8991c
DB
3256 }
3257
3258 /* Remove any unreported fork child threads from CONTEXT so
3259 that we don't interfere with follow fork, which is where
3260 creation of such threads is handled. */
3261 remove_new_fork_children (&context);
74531fed 3262
ab970af1 3263 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3264 for (i = 0;
3265 VEC_iterate (thread_item_t, context.items, i, item);
3266 ++i)
3267 {
3268 if (!ptid_equal (item->ptid, null_ptid))
3269 {
3270 struct private_thread_info *info;
3271 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3272 executing until proven otherwise with a stop reply.
3273 In all-stop, we can only get here if all threads are
6dc54d91 3274 stopped. */
0d5b594f 3275 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3276
0d5b594f 3277 remote_notice_new_inferior (item->ptid, executing);
6dc54d91
PA
3278
3279 info = demand_private_info (item->ptid);
3280 info->core = item->core;
3281 info->extra = item->extra;
3282 item->extra = NULL;
79efa585
SM
3283 info->name = item->name;
3284 item->name = NULL;
6dc54d91
PA
3285 }
3286 }
3287 }
3288
ab970af1
PA
3289 if (!got_list)
3290 {
3291 /* If no thread listing method is supported, then query whether
3292 each known thread is alive, one by one, with the T packet.
3293 If the target doesn't support threads at all, then this is a
3294 no-op. See remote_thread_alive. */
3295 prune_threads ();
3296 }
3297
6dc54d91 3298 do_cleanups (old_chain);
9d1f7ab2
MS
3299}
3300
802188a7 3301/*
9d1f7ab2
MS
3302 * Collect a descriptive string about the given thread.
3303 * The target may say anything it wants to about the thread
3304 * (typically info about its blocked / runnable state, name, etc.).
3305 * This string will appear in the info threads display.
802188a7 3306 *
9d1f7ab2
MS
3307 * Optional: targets are not required to implement this function.
3308 */
3309
3310static char *
c15906d8 3311remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3312{
d01949b6 3313 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3314 int result;
3315 int set;
3316 threadref id;
3317 struct gdb_ext_thread_info threadinfo;
23860348 3318 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3319 int n = 0; /* position in display_buf */
3320
5d93a237 3321 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3322 internal_error (__FILE__, __LINE__,
e2e0b3e5 3323 _("remote_threads_extra_info"));
9d1f7ab2 3324
60e569b9 3325 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3326 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3327 /* This is the main thread which was added by GDB. The remote
3328 server doesn't know about it. */
3329 return NULL;
3330
4082afcc 3331 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3332 {
3333 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3334
fe978cb0
PA
3335 if (info && info->priv)
3336 return info->priv->extra;
dc146f7c
VP
3337 else
3338 return NULL;
3339 }
3340
b80fafe3 3341 if (rs->use_threadextra_query)
9d1f7ab2 3342 {
82f73884
PA
3343 char *b = rs->buf;
3344 char *endb = rs->buf + get_remote_packet_size ();
3345
3346 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3347 b += strlen (b);
3348 write_ptid (b, endb, tp->ptid);
3349
2e9f7625 3350 putpkt (rs->buf);
6d820c5c 3351 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3352 if (rs->buf[0] != 0)
9d1f7ab2 3353 {
2e9f7625
DJ
3354 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3355 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3356 display_buf [result] = '\0';
9d1f7ab2
MS
3357 return display_buf;
3358 }
0f71a2f6 3359 }
9d1f7ab2
MS
3360
3361 /* If the above query fails, fall back to the old method. */
b80fafe3 3362 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3363 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3364 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3365 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3366 if (remote_get_threadinfo (&id, set, &threadinfo))
3367 if (threadinfo.active)
0f71a2f6 3368 {
9d1f7ab2 3369 if (*threadinfo.shortname)
2bc416ba 3370 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3371 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3372 if (*threadinfo.display)
2bc416ba 3373 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3374 " State: %s,", threadinfo.display);
9d1f7ab2 3375 if (*threadinfo.more_display)
2bc416ba 3376 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3377 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3378
3379 if (n > 0)
c5aa993b 3380 {
23860348 3381 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3382 if (',' == display_buf[n-1])
3383 display_buf[n-1] = ' ';
3384 return display_buf;
c5aa993b 3385 }
0f71a2f6 3386 }
9d1f7ab2 3387 return NULL;
0f71a2f6 3388}
c906108c 3389\f
c5aa993b 3390
0fb4aa4b 3391static int
61fc905d 3392remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3393 struct static_tracepoint_marker *marker)
3394{
3395 struct remote_state *rs = get_remote_state ();
3396 char *p = rs->buf;
3397
bba74b36 3398 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3399 p += strlen (p);
3400 p += hexnumstr (p, addr);
3401 putpkt (rs->buf);
3402 getpkt (&rs->buf, &rs->buf_size, 0);
3403 p = rs->buf;
3404
3405 if (*p == 'E')
3406 error (_("Remote failure reply: %s"), p);
3407
3408 if (*p++ == 'm')
3409 {
3410 parse_static_tracepoint_marker_definition (p, &p, marker);
3411 return 1;
3412 }
3413
3414 return 0;
3415}
3416
0fb4aa4b 3417static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3418remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3419 const char *strid)
0fb4aa4b
PA
3420{
3421 struct remote_state *rs = get_remote_state ();
3422 VEC(static_tracepoint_marker_p) *markers = NULL;
3423 struct static_tracepoint_marker *marker = NULL;
3424 struct cleanup *old_chain;
3425 char *p;
3426
3427 /* Ask for a first packet of static tracepoint marker
3428 definition. */
3429 putpkt ("qTfSTM");
3430 getpkt (&rs->buf, &rs->buf_size, 0);
3431 p = rs->buf;
3432 if (*p == 'E')
3433 error (_("Remote failure reply: %s"), p);
3434
3435 old_chain = make_cleanup (free_current_marker, &marker);
3436
3437 while (*p++ == 'm')
3438 {
3439 if (marker == NULL)
3440 marker = XCNEW (struct static_tracepoint_marker);
3441
3442 do
3443 {
3444 parse_static_tracepoint_marker_definition (p, &p, marker);
3445
3446 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3447 {
3448 VEC_safe_push (static_tracepoint_marker_p,
3449 markers, marker);
3450 marker = NULL;
3451 }
3452 else
3453 {
3454 release_static_tracepoint_marker (marker);
3455 memset (marker, 0, sizeof (*marker));
3456 }
3457 }
3458 while (*p++ == ','); /* comma-separated list */
3459 /* Ask for another packet of static tracepoint definition. */
3460 putpkt ("qTsSTM");
3461 getpkt (&rs->buf, &rs->buf_size, 0);
3462 p = rs->buf;
3463 }
3464
3465 do_cleanups (old_chain);
3466 return markers;
3467}
3468
3469\f
10760264
JB
3470/* Implement the to_get_ada_task_ptid function for the remote targets. */
3471
3472static ptid_t
1e6b91a4 3473remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3474{
ba348170 3475 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3476}
3477\f
3478
24b06219 3479/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3480
3481static void
fba45db2 3482extended_remote_restart (void)
c906108c 3483{
d01949b6 3484 struct remote_state *rs = get_remote_state ();
c906108c
SS
3485
3486 /* Send the restart command; for reasons I don't understand the
3487 remote side really expects a number after the "R". */
ea9c271d 3488 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3489 putpkt (rs->buf);
c906108c 3490
ad9a8f3f 3491 remote_fileio_reset ();
c906108c
SS
3492}
3493\f
3494/* Clean up connection to a remote debugger. */
3495
c906108c 3496static void
de90e03d 3497remote_close (struct target_ops *self)
c906108c 3498{
5d93a237
TT
3499 struct remote_state *rs = get_remote_state ();
3500
3501 if (rs->remote_desc == NULL)
d3fd5342
PA
3502 return; /* already closed */
3503
048094ac 3504 /* Make sure we leave stdin registered in the event loop. */
e3594fd1 3505 remote_terminal_ours (self);
ce5ce7ed 3506
5d93a237
TT
3507 serial_close (rs->remote_desc);
3508 rs->remote_desc = NULL;
ce5ce7ed
PA
3509
3510 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3511 of all the inferiors and their threads we were controlling.
3512 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3513 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3514 inferior_ptid = null_ptid;
f67fd822 3515 discard_all_inferiors ();
ce5ce7ed 3516
f48ff2a7
YQ
3517 /* We are closing the remote target, so we should discard
3518 everything of this target. */
bcc75809 3519 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3520
3521 if (remote_async_inferior_event_token)
3522 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3523
5965e028 3524 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3525
3526 trace_reset_local_state ();
c906108c
SS
3527}
3528
23860348 3529/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3530
3531static void
fba45db2 3532get_offsets (void)
c906108c 3533{
d01949b6 3534 struct remote_state *rs = get_remote_state ();
2e9f7625 3535 char *buf;
085dd6e6 3536 char *ptr;
31d99776
DJ
3537 int lose, num_segments = 0, do_sections, do_segments;
3538 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3539 struct section_offsets *offs;
31d99776
DJ
3540 struct symfile_segment_data *data;
3541
3542 if (symfile_objfile == NULL)
3543 return;
c906108c
SS
3544
3545 putpkt ("qOffsets");
6d820c5c 3546 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3547 buf = rs->buf;
c906108c
SS
3548
3549 if (buf[0] == '\000')
3550 return; /* Return silently. Stub doesn't support
23860348 3551 this command. */
c906108c
SS
3552 if (buf[0] == 'E')
3553 {
8a3fe4f8 3554 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3555 return;
3556 }
3557
3558 /* Pick up each field in turn. This used to be done with scanf, but
3559 scanf will make trouble if CORE_ADDR size doesn't match
3560 conversion directives correctly. The following code will work
3561 with any size of CORE_ADDR. */
3562 text_addr = data_addr = bss_addr = 0;
3563 ptr = buf;
3564 lose = 0;
3565
61012eef 3566 if (startswith (ptr, "Text="))
c906108c
SS
3567 {
3568 ptr += 5;
3569 /* Don't use strtol, could lose on big values. */
3570 while (*ptr && *ptr != ';')
3571 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3572
61012eef 3573 if (startswith (ptr, ";Data="))
31d99776
DJ
3574 {
3575 ptr += 6;
3576 while (*ptr && *ptr != ';')
3577 data_addr = (data_addr << 4) + fromhex (*ptr++);
3578 }
3579 else
3580 lose = 1;
3581
61012eef 3582 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3583 {
3584 ptr += 5;
3585 while (*ptr && *ptr != ';')
3586 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3587
31d99776
DJ
3588 if (bss_addr != data_addr)
3589 warning (_("Target reported unsupported offsets: %s"), buf);
3590 }
3591 else
3592 lose = 1;
3593 }
61012eef 3594 else if (startswith (ptr, "TextSeg="))
c906108c 3595 {
31d99776
DJ
3596 ptr += 8;
3597 /* Don't use strtol, could lose on big values. */
c906108c 3598 while (*ptr && *ptr != ';')
31d99776
DJ
3599 text_addr = (text_addr << 4) + fromhex (*ptr++);
3600 num_segments = 1;
3601
61012eef 3602 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3603 {
3604 ptr += 9;
3605 while (*ptr && *ptr != ';')
3606 data_addr = (data_addr << 4) + fromhex (*ptr++);
3607 num_segments++;
3608 }
c906108c
SS
3609 }
3610 else
3611 lose = 1;
3612
3613 if (lose)
8a3fe4f8 3614 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3615 else if (*ptr != '\0')
3616 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3617
802188a7 3618 offs = ((struct section_offsets *)
a39a16c4 3619 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3620 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3621 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3622
31d99776
DJ
3623 data = get_symfile_segment_data (symfile_objfile->obfd);
3624 do_segments = (data != NULL);
3625 do_sections = num_segments == 0;
c906108c 3626
28c32713 3627 if (num_segments > 0)
31d99776 3628 {
31d99776
DJ
3629 segments[0] = text_addr;
3630 segments[1] = data_addr;
3631 }
28c32713
JB
3632 /* If we have two segments, we can still try to relocate everything
3633 by assuming that the .text and .data offsets apply to the whole
3634 text and data segments. Convert the offsets given in the packet
3635 to base addresses for symfile_map_offsets_to_segments. */
3636 else if (data && data->num_segments == 2)
3637 {
3638 segments[0] = data->segment_bases[0] + text_addr;
3639 segments[1] = data->segment_bases[1] + data_addr;
3640 num_segments = 2;
3641 }
8d385431
DJ
3642 /* If the object file has only one segment, assume that it is text
3643 rather than data; main programs with no writable data are rare,
3644 but programs with no code are useless. Of course the code might
3645 have ended up in the data segment... to detect that we would need
3646 the permissions here. */
3647 else if (data && data->num_segments == 1)
3648 {
3649 segments[0] = data->segment_bases[0] + text_addr;
3650 num_segments = 1;
3651 }
28c32713
JB
3652 /* There's no way to relocate by segment. */
3653 else
3654 do_segments = 0;
31d99776
DJ
3655
3656 if (do_segments)
3657 {
3658 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3659 offs, num_segments, segments);
3660
3661 if (ret == 0 && !do_sections)
3e43a32a
MS
3662 error (_("Can not handle qOffsets TextSeg "
3663 "response with this symbol file"));
31d99776
DJ
3664
3665 if (ret > 0)
3666 do_sections = 0;
3667 }
c906108c 3668
9ef895d6
DJ
3669 if (data)
3670 free_symfile_segment_data (data);
31d99776
DJ
3671
3672 if (do_sections)
3673 {
3674 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3675
3e43a32a
MS
3676 /* This is a temporary kludge to force data and bss to use the
3677 same offsets because that's what nlmconv does now. The real
3678 solution requires changes to the stub and remote.c that I
3679 don't have time to do right now. */
31d99776
DJ
3680
3681 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3682 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3683 }
c906108c
SS
3684
3685 objfile_relocate (symfile_objfile, offs);
3686}
3687
9a7071a8
JB
3688/* Send interrupt_sequence to remote target. */
3689static void
eeae04df 3690send_interrupt_sequence (void)
9a7071a8 3691{
5d93a237
TT
3692 struct remote_state *rs = get_remote_state ();
3693
9a7071a8 3694 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3695 remote_serial_write ("\x03", 1);
9a7071a8 3696 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3697 serial_send_break (rs->remote_desc);
9a7071a8
JB
3698 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3699 {
5d93a237 3700 serial_send_break (rs->remote_desc);
c33e31fd 3701 remote_serial_write ("g", 1);
9a7071a8
JB
3702 }
3703 else
3704 internal_error (__FILE__, __LINE__,
3705 _("Invalid value for interrupt_sequence_mode: %s."),
3706 interrupt_sequence_mode);
3707}
3708
3405876a
PA
3709
3710/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3711 and extract the PTID. Returns NULL_PTID if not found. */
3712
3713static ptid_t
3714stop_reply_extract_thread (char *stop_reply)
3715{
3716 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3717 {
3718 char *p;
3719
3720 /* Txx r:val ; r:val (...) */
3721 p = &stop_reply[3];
3722
3723 /* Look for "register" named "thread". */
3724 while (*p != '\0')
3725 {
3726 char *p1;
3727
3728 p1 = strchr (p, ':');
3729 if (p1 == NULL)
3730 return null_ptid;
3731
3732 if (strncmp (p, "thread", p1 - p) == 0)
3733 return read_ptid (++p1, &p);
3734
3735 p1 = strchr (p, ';');
3736 if (p1 == NULL)
3737 return null_ptid;
3738 p1++;
3739
3740 p = p1;
3741 }
3742 }
3743
3744 return null_ptid;
3745}
3746
b7ea362b
PA
3747/* Determine the remote side's current thread. If we have a stop
3748 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3749 "thread" register we can extract the current thread from. If not,
3750 ask the remote which is the current thread with qC. The former
3751 method avoids a roundtrip. */
3752
3753static ptid_t
3754get_current_thread (char *wait_status)
3755{
6a49a997 3756 ptid_t ptid = null_ptid;
b7ea362b
PA
3757
3758 /* Note we don't use remote_parse_stop_reply as that makes use of
3759 the target architecture, which we haven't yet fully determined at
3760 this point. */
3761 if (wait_status != NULL)
3762 ptid = stop_reply_extract_thread (wait_status);
3763 if (ptid_equal (ptid, null_ptid))
3764 ptid = remote_current_thread (inferior_ptid);
3765
3766 return ptid;
3767}
3768
49c62f2e
PA
3769/* Query the remote target for which is the current thread/process,
3770 add it to our tables, and update INFERIOR_PTID. The caller is
3771 responsible for setting the state such that the remote end is ready
3405876a
PA
3772 to return the current thread.
3773
3774 This function is called after handling the '?' or 'vRun' packets,
3775 whose response is a stop reply from which we can also try
3776 extracting the thread. If the target doesn't support the explicit
3777 qC query, we infer the current thread from that stop reply, passed
3778 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3779
3780static void
3405876a 3781add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3782{
3783 struct remote_state *rs = get_remote_state ();
3784 int fake_pid_p = 0;
6a49a997 3785 ptid_t ptid;
49c62f2e
PA
3786
3787 inferior_ptid = null_ptid;
3788
b7ea362b
PA
3789 /* Now, if we have thread information, update inferior_ptid. */
3790 ptid = get_current_thread (wait_status);
3405876a 3791
49c62f2e
PA
3792 if (!ptid_equal (ptid, null_ptid))
3793 {
3794 if (!remote_multi_process_p (rs))
3795 fake_pid_p = 1;
3796
3797 inferior_ptid = ptid;
3798 }
3799 else
3800 {
3801 /* Without this, some commands which require an active target
3802 (such as kill) won't work. This variable serves (at least)
3803 double duty as both the pid of the target process (if it has
3804 such), and as a flag indicating that a target is active. */
3805 inferior_ptid = magic_null_ptid;
3806 fake_pid_p = 1;
3807 }
3808
1b6e6f5c 3809 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3810
3811 /* Add the main thread. */
3812 add_thread_silent (inferior_ptid);
3813}
3814
6efcd9a8
PA
3815/* Print info about a thread that was found already stopped on
3816 connection. */
3817
3818static void
3819print_one_stopped_thread (struct thread_info *thread)
3820{
3821 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3822
3823 switch_to_thread (thread->ptid);
3824 stop_pc = get_frame_pc (get_current_frame ());
3825 set_current_sal_from_frame (get_current_frame ());
3826
3827 thread->suspend.waitstatus_pending_p = 0;
3828
3829 if (ws->kind == TARGET_WAITKIND_STOPPED)
3830 {
3831 enum gdb_signal sig = ws->value.sig;
3832
3833 if (signal_print_state (sig))
3834 observer_notify_signal_received (sig);
3835 }
3836 observer_notify_normal_stop (NULL, 1);
3837}
3838
221e1a37
PA
3839/* Process all initial stop replies the remote side sent in response
3840 to the ? packet. These indicate threads that were already stopped
3841 on initial connection. We mark these threads as stopped and print
3842 their current frame before giving the user the prompt. */
3843
3844static void
6efcd9a8 3845process_initial_stop_replies (int from_tty)
221e1a37
PA
3846{
3847 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3848 struct inferior *inf;
3849 struct thread_info *thread;
3850 struct thread_info *selected = NULL;
3851 struct thread_info *lowest_stopped = NULL;
3852 struct thread_info *first = NULL;
221e1a37
PA
3853
3854 /* Consume the initial pending events. */
3855 while (pending_stop_replies-- > 0)
3856 {
3857 ptid_t waiton_ptid = minus_one_ptid;
3858 ptid_t event_ptid;
3859 struct target_waitstatus ws;
3860 int ignore_event = 0;
6efcd9a8 3861 struct thread_info *thread;
221e1a37
PA
3862
3863 memset (&ws, 0, sizeof (ws));
3864 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3865 if (remote_debug)
3866 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3867
3868 switch (ws.kind)
3869 {
3870 case TARGET_WAITKIND_IGNORE:
3871 case TARGET_WAITKIND_NO_RESUMED:
3872 case TARGET_WAITKIND_SIGNALLED:
3873 case TARGET_WAITKIND_EXITED:
3874 /* We shouldn't see these, but if we do, just ignore. */
3875 if (remote_debug)
3876 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3877 ignore_event = 1;
3878 break;
3879
3880 case TARGET_WAITKIND_EXECD:
3881 xfree (ws.value.execd_pathname);
3882 break;
3883 default:
3884 break;
3885 }
3886
3887 if (ignore_event)
3888 continue;
3889
6efcd9a8 3890 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3891
3892 if (ws.kind == TARGET_WAITKIND_STOPPED)
3893 {
3894 enum gdb_signal sig = ws.value.sig;
3895
3896 /* Stubs traditionally report SIGTRAP as initial signal,
3897 instead of signal 0. Suppress it. */
3898 if (sig == GDB_SIGNAL_TRAP)
3899 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3900 thread->suspend.stop_signal = sig;
3901 ws.value.sig = sig;
3902 }
221e1a37 3903
6efcd9a8
PA
3904 thread->suspend.waitstatus = ws;
3905
3906 if (ws.kind != TARGET_WAITKIND_STOPPED
3907 || ws.value.sig != GDB_SIGNAL_0)
3908 thread->suspend.waitstatus_pending_p = 1;
3909
3910 set_executing (event_ptid, 0);
3911 set_running (event_ptid, 0);
3912 }
3913
3914 /* "Notice" the new inferiors before anything related to
3915 registers/memory. */
3916 ALL_INFERIORS (inf)
3917 {
3918 if (inf->pid == 0)
3919 continue;
3920
3921 inf->needs_setup = 1;
3922
3923 if (non_stop)
3924 {
3925 thread = any_live_thread_of_process (inf->pid);
3926 notice_new_inferior (thread->ptid,
3927 thread->state == THREAD_RUNNING,
3928 from_tty);
3929 }
3930 }
3931
3932 /* If all-stop on top of non-stop, pause all threads. Note this
3933 records the threads' stop pc, so must be done after "noticing"
3934 the inferiors. */
3935 if (!non_stop)
3936 {
3937 stop_all_threads ();
3938
3939 /* If all threads of an inferior were already stopped, we
3940 haven't setup the inferior yet. */
3941 ALL_INFERIORS (inf)
3942 {
3943 if (inf->pid == 0)
3944 continue;
221e1a37 3945
6efcd9a8
PA
3946 if (inf->needs_setup)
3947 {
3948 thread = any_live_thread_of_process (inf->pid);
3949 switch_to_thread_no_regs (thread);
3950 setup_inferior (0);
3951 }
3952 }
221e1a37 3953 }
6efcd9a8
PA
3954
3955 /* Now go over all threads that are stopped, and print their current
3956 frame. If all-stop, then if there's a signalled thread, pick
3957 that as current. */
3958 ALL_NON_EXITED_THREADS (thread)
3959 {
6efcd9a8
PA
3960 if (first == NULL)
3961 first = thread;
3962
3963 if (!non_stop)
3964 set_running (thread->ptid, 0);
3965 else if (thread->state != THREAD_STOPPED)
3966 continue;
3967
6efcd9a8
PA
3968 if (selected == NULL
3969 && thread->suspend.waitstatus_pending_p)
3970 selected = thread;
3971
5d5658a1
PA
3972 if (lowest_stopped == NULL
3973 || thread->inf->num < lowest_stopped->inf->num
3974 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
3975 lowest_stopped = thread;
3976
3977 if (non_stop)
3978 print_one_stopped_thread (thread);
3979 }
3980
3981 /* In all-stop, we only print the status of one thread, and leave
3982 others with their status pending. */
3983 if (!non_stop)
3984 {
3985 thread = selected;
3986 if (thread == NULL)
3987 thread = lowest_stopped;
3988 if (thread == NULL)
3989 thread = first;
3990
3991 print_one_stopped_thread (thread);
3992 }
3993
3994 /* For "info program". */
3995 thread = inferior_thread ();
3996 if (thread->state == THREAD_STOPPED)
3997 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
3998}
3999
048094ac
PA
4000/* Start the remote connection and sync state. */
4001
9cbc821d 4002static void
04bd08de 4003remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 4004{
c8d104ad
PA
4005 struct remote_state *rs = get_remote_state ();
4006 struct packet_config *noack_config;
2d717e4f 4007 char *wait_status = NULL;
8621d6a9 4008
048094ac
PA
4009 /* Signal other parts that we're going through the initial setup,
4010 and so things may not be stable yet. E.g., we don't try to
4011 install tracepoints until we've relocated symbols. Also, a
4012 Ctrl-C before we're connected and synced up can't interrupt the
4013 target. Instead, it offers to drop the (potentially wedged)
4014 connection. */
4015 rs->starting_up = 1;
4016
522002f9 4017 QUIT;
c906108c 4018
9a7071a8
JB
4019 if (interrupt_on_connect)
4020 send_interrupt_sequence ();
4021
57e12211 4022 /* Ack any packet which the remote side has already sent. */
048094ac 4023 remote_serial_write ("+", 1);
1e51243a 4024
c8d104ad
PA
4025 /* The first packet we send to the target is the optional "supported
4026 packets" request. If the target can answer this, it will tell us
4027 which later probes to skip. */
4028 remote_query_supported ();
4029
d914c394 4030 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4031 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 4032 remote_set_permissions (target);
d914c394 4033
57809e5e
JK
4034 /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4035 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
4036 as a reply to known packet. For packet "vFile:setfs:" it is an
4037 invalid reply and GDB would return error in
4038 remote_hostio_set_filesystem, making remote files access impossible.
4039 Disable "vFile:setfs:" in such case. Do not disable other 'v' packets as
4040 other "vFile" packets get correctly detected even on gdbserver < 7.7. */
4041 {
4042 const char v_mustreplyempty[] = "vMustReplyEmpty";
4043
4044 putpkt (v_mustreplyempty);
4045 getpkt (&rs->buf, &rs->buf_size, 0);
4046 if (strcmp (rs->buf, "OK") == 0)
4047 remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4048 else if (strcmp (rs->buf, "") != 0)
4049 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4050 rs->buf);
4051 }
4052
c8d104ad
PA
4053 /* Next, we possibly activate noack mode.
4054
4055 If the QStartNoAckMode packet configuration is set to AUTO,
4056 enable noack mode if the stub reported a wish for it with
4057 qSupported.
4058
4059 If set to TRUE, then enable noack mode even if the stub didn't
4060 report it in qSupported. If the stub doesn't reply OK, the
4061 session ends with an error.
4062
4063 If FALSE, then don't activate noack mode, regardless of what the
4064 stub claimed should be the default with qSupported. */
4065
4066 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4067 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4068 {
4069 putpkt ("QStartNoAckMode");
4070 getpkt (&rs->buf, &rs->buf_size, 0);
4071 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4072 rs->noack_mode = 1;
4073 }
4074
04bd08de 4075 if (extended_p)
5fe04517
PA
4076 {
4077 /* Tell the remote that we are using the extended protocol. */
4078 putpkt ("!");
4079 getpkt (&rs->buf, &rs->buf_size, 0);
4080 }
4081
9b224c5e
PA
4082 /* Let the target know which signals it is allowed to pass down to
4083 the program. */
4084 update_signals_program_target ();
4085
d962ef82
DJ
4086 /* Next, if the target can specify a description, read it. We do
4087 this before anything involving memory or registers. */
4088 target_find_description ();
4089
6c95b8df
PA
4090 /* Next, now that we know something about the target, update the
4091 address spaces in the program spaces. */
4092 update_address_spaces ();
4093
50c71eaf
PA
4094 /* On OSs where the list of libraries is global to all
4095 processes, we fetch them early. */
f5656ead 4096 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 4097 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 4098
6efcd9a8 4099 if (target_is_non_stop_p ())
74531fed 4100 {
4082afcc 4101 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4102 error (_("Non-stop mode requested, but remote "
4103 "does not support non-stop"));
74531fed
PA
4104
4105 putpkt ("QNonStop:1");
4106 getpkt (&rs->buf, &rs->buf_size, 0);
4107
4108 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4109 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4110
4111 /* Find about threads and processes the stub is already
4112 controlling. We default to adding them in the running state.
4113 The '?' query below will then tell us about which threads are
4114 stopped. */
e8032dde 4115 remote_update_thread_list (target);
74531fed 4116 }
4082afcc 4117 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4118 {
4119 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4120 Request it explicitly. */
74531fed
PA
4121 putpkt ("QNonStop:0");
4122 getpkt (&rs->buf, &rs->buf_size, 0);
4123
4124 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4125 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4126 }
4127
a0743c90
YQ
4128 /* Upload TSVs regardless of whether the target is running or not. The
4129 remote stub, such as GDBserver, may have some predefined or builtin
4130 TSVs, even if the target is not running. */
8bd200f1 4131 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4132 {
4133 struct uploaded_tsv *uploaded_tsvs = NULL;
4134
181e3713 4135 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4136 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4137 }
4138
2d717e4f
DJ
4139 /* Check whether the target is running now. */
4140 putpkt ("?");
4141 getpkt (&rs->buf, &rs->buf_size, 0);
4142
6efcd9a8 4143 if (!target_is_non_stop_p ())
2d717e4f 4144 {
74531fed 4145 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4146 {
04bd08de 4147 if (!extended_p)
74531fed 4148 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4149
4150 /* We're connected, but not running. Drop out before we
4151 call start_remote. */
e278ad5b 4152 rs->starting_up = 0;
c35b1492 4153 return;
2d717e4f
DJ
4154 }
4155 else
74531fed 4156 {
74531fed 4157 /* Save the reply for later. */
224c3ddb 4158 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4159 strcpy (wait_status, rs->buf);
4160 }
4161
b7ea362b 4162 /* Fetch thread list. */
e8032dde 4163 target_update_thread_list ();
b7ea362b 4164
74531fed
PA
4165 /* Let the stub know that we want it to return the thread. */
4166 set_continue_thread (minus_one_ptid);
4167
b7ea362b
PA
4168 if (thread_count () == 0)
4169 {
4170 /* Target has no concept of threads at all. GDB treats
4171 non-threaded target as single-threaded; add a main
4172 thread. */
4173 add_current_inferior_and_thread (wait_status);
4174 }
4175 else
4176 {
4177 /* We have thread information; select the thread the target
4178 says should be current. If we're reconnecting to a
4179 multi-threaded program, this will ideally be the thread
4180 that last reported an event before GDB disconnected. */
4181 inferior_ptid = get_current_thread (wait_status);
4182 if (ptid_equal (inferior_ptid, null_ptid))
4183 {
4184 /* Odd... The target was able to list threads, but not
4185 tell us which thread was current (no "thread"
4186 register in T stop reply?). Just pick the first
4187 thread in the thread list then. */
c9f35b34
KB
4188
4189 if (remote_debug)
4190 fprintf_unfiltered (gdb_stdlog,
4191 "warning: couldn't determine remote "
4192 "current thread; picking first in list.\n");
4193
b7ea362b
PA
4194 inferior_ptid = thread_list->ptid;
4195 }
4196 }
74531fed 4197
6e586cc5
YQ
4198 /* init_wait_for_inferior should be called before get_offsets in order
4199 to manage `inserted' flag in bp loc in a correct state.
4200 breakpoint_init_inferior, called from init_wait_for_inferior, set
4201 `inserted' flag to 0, while before breakpoint_re_set, called from
4202 start_remote, set `inserted' flag to 1. In the initialization of
4203 inferior, breakpoint_init_inferior should be called first, and then
4204 breakpoint_re_set can be called. If this order is broken, state of
4205 `inserted' flag is wrong, and cause some problems on breakpoint
4206 manipulation. */
4207 init_wait_for_inferior ();
4208
74531fed
PA
4209 get_offsets (); /* Get text, data & bss offsets. */
4210
d962ef82
DJ
4211 /* If we could not find a description using qXfer, and we know
4212 how to do it some other way, try again. This is not
4213 supported for non-stop; it could be, but it is tricky if
4214 there are no stopped threads when we connect. */
04bd08de 4215 if (remote_read_description_p (target)
f5656ead 4216 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4217 {
4218 target_clear_description ();
4219 target_find_description ();
4220 }
4221
74531fed
PA
4222 /* Use the previously fetched status. */
4223 gdb_assert (wait_status != NULL);
4224 strcpy (rs->buf, wait_status);
4225 rs->cached_wait_status = 1;
4226
04bd08de 4227 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4228 }
4229 else
4230 {
68c97600
PA
4231 /* Clear WFI global state. Do this before finding about new
4232 threads and inferiors, and setting the current inferior.
4233 Otherwise we would clear the proceed status of the current
4234 inferior when we want its stop_soon state to be preserved
4235 (see notice_new_inferior). */
4236 init_wait_for_inferior ();
4237
74531fed
PA
4238 /* In non-stop, we will either get an "OK", meaning that there
4239 are no stopped threads at this time; or, a regular stop
4240 reply. In the latter case, there may be more than one thread
4241 stopped --- we pull them all out using the vStopped
4242 mechanism. */
4243 if (strcmp (rs->buf, "OK") != 0)
4244 {
722247f1 4245 struct notif_client *notif = &notif_client_stop;
2d717e4f 4246
722247f1
YQ
4247 /* remote_notif_get_pending_replies acks this one, and gets
4248 the rest out. */
f48ff2a7 4249 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4250 = remote_notif_parse (notif, rs->buf);
4251 remote_notif_get_pending_events (notif);
74531fed 4252 }
2d717e4f 4253
74531fed
PA
4254 if (thread_count () == 0)
4255 {
04bd08de 4256 if (!extended_p)
74531fed 4257 error (_("The target is not running (try extended-remote?)"));
82f73884 4258
c35b1492
PA
4259 /* We're connected, but not running. Drop out before we
4260 call start_remote. */
e278ad5b 4261 rs->starting_up = 0;
c35b1492
PA
4262 return;
4263 }
74531fed 4264
74531fed
PA
4265 /* In non-stop mode, any cached wait status will be stored in
4266 the stop reply queue. */
4267 gdb_assert (wait_status == NULL);
f0223081 4268
2455069d 4269 /* Report all signals during attach/startup. */
94bedb42 4270 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4271
4272 /* If there are already stopped threads, mark them stopped and
4273 report their stops before giving the prompt to the user. */
6efcd9a8 4274 process_initial_stop_replies (from_tty);
221e1a37
PA
4275
4276 if (target_can_async_p ())
4277 target_async (1);
74531fed 4278 }
c8d104ad 4279
c8d104ad
PA
4280 /* If we connected to a live target, do some additional setup. */
4281 if (target_has_execution)
4282 {
f4ccffad 4283 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4284 remote_check_symbols ();
c8d104ad 4285 }
50c71eaf 4286
d5551862
SS
4287 /* Possibly the target has been engaged in a trace run started
4288 previously; find out where things are at. */
8bd200f1 4289 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4290 {
00bf0b85 4291 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4292
00bf0b85
SS
4293 if (current_trace_status ()->running)
4294 printf_filtered (_("Trace is already running on the target.\n"));
4295
ab6617cc 4296 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4297
4298 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4299 }
4300
1e51243a
PA
4301 /* The thread and inferior lists are now synchronized with the
4302 target, our symbols have been relocated, and we're merged the
4303 target's tracepoints with ours. We're done with basic start
4304 up. */
4305 rs->starting_up = 0;
4306
a25a5a45
PA
4307 /* Maybe breakpoints are global and need to be inserted now. */
4308 if (breakpoints_should_be_inserted_now ())
50c71eaf 4309 insert_breakpoints ();
c906108c
SS
4310}
4311
4312/* Open a connection to a remote debugger.
4313 NAME is the filename used for communication. */
4314
4315static void
014f9477 4316remote_open (const char *name, int from_tty)
c906108c 4317{
75c99385 4318 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4319}
4320
c906108c
SS
4321/* Open a connection to a remote debugger using the extended
4322 remote gdb protocol. NAME is the filename used for communication. */
4323
4324static void
014f9477 4325extended_remote_open (const char *name, int from_tty)
c906108c 4326{
75c99385 4327 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4328}
4329
ca4f7f8b
PA
4330/* Reset all packets back to "unknown support". Called when opening a
4331 new connection to a remote target. */
c906108c 4332
d471ea57 4333static void
ca4f7f8b 4334reset_all_packet_configs_support (void)
d471ea57
AC
4335{
4336 int i;
a744cf53 4337
444abaca 4338 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4339 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4340}
4341
ca4f7f8b
PA
4342/* Initialize all packet configs. */
4343
4344static void
4345init_all_packet_configs (void)
4346{
4347 int i;
4348
4349 for (i = 0; i < PACKET_MAX; i++)
4350 {
4351 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4352 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4353 }
4354}
4355
23860348 4356/* Symbol look-up. */
dc8acb97
MS
4357
4358static void
36d25514 4359remote_check_symbols (void)
dc8acb97 4360{
d01949b6 4361 struct remote_state *rs = get_remote_state ();
dc8acb97 4362 char *msg, *reply, *tmp;
dc8acb97 4363 int end;
28170b88 4364 long reply_size;
a5c0808e 4365 struct cleanup *old_chain;
dc8acb97 4366
63154eca
PA
4367 /* The remote side has no concept of inferiors that aren't running
4368 yet, it only knows about running processes. If we're connected
4369 but our current inferior is not running, we should not invite the
4370 remote target to request symbol lookups related to its
4371 (unrelated) current process. */
4372 if (!target_has_execution)
4373 return;
4374
4082afcc 4375 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4376 return;
4377
63154eca
PA
4378 /* Make sure the remote is pointing at the right process. Note
4379 there's no way to select "no process". */
3c9c4b83
PA
4380 set_general_process ();
4381
6d820c5c
DJ
4382 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4383 because we need both at the same time. */
224c3ddb 4384 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4385 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4386 reply = (char *) xmalloc (get_remote_packet_size ());
4387 make_cleanup (free_current_contents, &reply);
4388 reply_size = get_remote_packet_size ();
6d820c5c 4389
23860348 4390 /* Invite target to request symbol lookups. */
dc8acb97
MS
4391
4392 putpkt ("qSymbol::");
28170b88
MK
4393 getpkt (&reply, &reply_size, 0);
4394 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4395
61012eef 4396 while (startswith (reply, "qSymbol:"))
dc8acb97 4397 {
77e371c0
TT
4398 struct bound_minimal_symbol sym;
4399
dc8acb97 4400 tmp = &reply[8];
cfd77fa1 4401 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4402 msg[end] = '\0';
4403 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4404 if (sym.minsym == NULL)
ea9c271d 4405 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4406 else
2bbe3cc1 4407 {
f5656ead 4408 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4409 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4410
4411 /* If this is a function address, return the start of code
4412 instead of any data function descriptor. */
f5656ead 4413 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4414 sym_addr,
4415 &current_target);
4416
4417 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4418 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4419 }
4420
dc8acb97 4421 putpkt (msg);
28170b88 4422 getpkt (&reply, &reply_size, 0);
dc8acb97 4423 }
a5c0808e
PA
4424
4425 do_cleanups (old_chain);
dc8acb97
MS
4426}
4427
9db8d71f 4428static struct serial *
baa336ce 4429remote_serial_open (const char *name)
9db8d71f
DJ
4430{
4431 static int udp_warning = 0;
4432
4433 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4434 of in ser-tcp.c, because it is the remote protocol assuming that the
4435 serial connection is reliable and not the serial connection promising
4436 to be. */
61012eef 4437 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4438 {
3e43a32a
MS
4439 warning (_("The remote protocol may be unreliable over UDP.\n"
4440 "Some events may be lost, rendering further debugging "
4441 "impossible."));
9db8d71f
DJ
4442 udp_warning = 1;
4443 }
4444
4445 return serial_open (name);
4446}
4447
d914c394
SS
4448/* Inform the target of our permission settings. The permission flags
4449 work without this, but if the target knows the settings, it can do
4450 a couple things. First, it can add its own check, to catch cases
4451 that somehow manage to get by the permissions checks in target
4452 methods. Second, if the target is wired to disallow particular
4453 settings (for instance, a system in the field that is not set up to
4454 be able to stop at a breakpoint), it can object to any unavailable
4455 permissions. */
4456
4457void
c378d69d 4458remote_set_permissions (struct target_ops *self)
d914c394
SS
4459{
4460 struct remote_state *rs = get_remote_state ();
4461
bba74b36
YQ
4462 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4463 "WriteReg:%x;WriteMem:%x;"
4464 "InsertBreak:%x;InsertTrace:%x;"
4465 "InsertFastTrace:%x;Stop:%x",
4466 may_write_registers, may_write_memory,
4467 may_insert_breakpoints, may_insert_tracepoints,
4468 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4469 putpkt (rs->buf);
4470 getpkt (&rs->buf, &rs->buf_size, 0);
4471
4472 /* If the target didn't like the packet, warn the user. Do not try
4473 to undo the user's settings, that would just be maddening. */
4474 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4475 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4476}
4477
be2a5f71
DJ
4478/* This type describes each known response to the qSupported
4479 packet. */
4480struct protocol_feature
4481{
4482 /* The name of this protocol feature. */
4483 const char *name;
4484
4485 /* The default for this protocol feature. */
4486 enum packet_support default_support;
4487
4488 /* The function to call when this feature is reported, or after
4489 qSupported processing if the feature is not supported.
4490 The first argument points to this structure. The second
4491 argument indicates whether the packet requested support be
4492 enabled, disabled, or probed (or the default, if this function
4493 is being called at the end of processing and this feature was
4494 not reported). The third argument may be NULL; if not NULL, it
4495 is a NUL-terminated string taken from the packet following
4496 this feature's name and an equals sign. */
4497 void (*func) (const struct protocol_feature *, enum packet_support,
4498 const char *);
4499
4500 /* The corresponding packet for this feature. Only used if
4501 FUNC is remote_supported_packet. */
4502 int packet;
4503};
4504
be2a5f71
DJ
4505static void
4506remote_supported_packet (const struct protocol_feature *feature,
4507 enum packet_support support,
4508 const char *argument)
4509{
4510 if (argument)
4511 {
4512 warning (_("Remote qSupported response supplied an unexpected value for"
4513 " \"%s\"."), feature->name);
4514 return;
4515 }
4516
4082afcc 4517 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4518}
be2a5f71
DJ
4519
4520static void
4521remote_packet_size (const struct protocol_feature *feature,
4522 enum packet_support support, const char *value)
4523{
4524 struct remote_state *rs = get_remote_state ();
4525
4526 int packet_size;
4527 char *value_end;
4528
4529 if (support != PACKET_ENABLE)
4530 return;
4531
4532 if (value == NULL || *value == '\0')
4533 {
4534 warning (_("Remote target reported \"%s\" without a size."),
4535 feature->name);
4536 return;
4537 }
4538
4539 errno = 0;
4540 packet_size = strtol (value, &value_end, 16);
4541 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4542 {
4543 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4544 feature->name, value);
4545 return;
4546 }
4547
be2a5f71
DJ
4548 /* Record the new maximum packet size. */
4549 rs->explicit_packet_size = packet_size;
4550}
4551
dc473cfb 4552static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4553 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4554 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4555 PACKET_qXfer_auxv },
c78fa86a
GB
4556 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4557 PACKET_qXfer_exec_file },
23181151
DJ
4558 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4559 PACKET_qXfer_features },
cfa9d6d9
DJ
4560 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4561 PACKET_qXfer_libraries },
2268b414
JK
4562 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4563 PACKET_qXfer_libraries_svr4 },
ced63ec0 4564 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4565 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4566 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4567 PACKET_qXfer_memory_map },
4de6483e
UW
4568 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4569 PACKET_qXfer_spu_read },
4570 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4571 PACKET_qXfer_spu_write },
07e059b5
VP
4572 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4573 PACKET_qXfer_osdata },
dc146f7c
VP
4574 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4575 PACKET_qXfer_threads },
b3b9301e
PA
4576 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4577 PACKET_qXfer_traceframe_info },
89be2091
DJ
4578 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4579 PACKET_QPassSignals },
82075af2
JS
4580 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4581 PACKET_QCatchSyscalls },
9b224c5e
PA
4582 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4583 PACKET_QProgramSignals },
a6f3e723
SL
4584 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4585 PACKET_QStartNoAckMode },
4082afcc
PA
4586 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4587 PACKET_multiprocess_feature },
4588 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4589 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4590 PACKET_qXfer_siginfo_read },
4591 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4592 PACKET_qXfer_siginfo_write },
4082afcc 4593 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4594 PACKET_ConditionalTracepoints },
4082afcc 4595 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4596 PACKET_ConditionalBreakpoints },
4082afcc 4597 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4598 PACKET_BreakpointCommands },
4082afcc 4599 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4600 PACKET_FastTracepoints },
4082afcc 4601 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4602 PACKET_StaticTracepoints },
4082afcc 4603 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4604 PACKET_InstallInTrace},
4082afcc
PA
4605 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4606 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4607 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4608 PACKET_bc },
4609 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4610 PACKET_bs },
409873ef
SS
4611 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4612 PACKET_TracepointSource },
d914c394
SS
4613 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4614 PACKET_QAllow },
4082afcc
PA
4615 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4616 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4617 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4618 PACKET_qXfer_fdpic },
169081d0
TG
4619 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4620 PACKET_qXfer_uib },
03583c20
UW
4621 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4622 PACKET_QDisableRandomization },
d1feda86 4623 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4624 { "QTBuffer:size", PACKET_DISABLE,
4625 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4626 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4627 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4628 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4629 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4630 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4631 PACKET_qXfer_btrace },
4632 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4633 PACKET_qXfer_btrace_conf },
4634 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4635 PACKET_Qbtrace_conf_bts_size },
4636 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4637 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4638 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4639 PACKET_fork_event_feature },
4640 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4641 PACKET_vfork_event_feature },
94585166
DB
4642 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4643 PACKET_exec_event_feature },
b20a6524 4644 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4645 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4646 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4647 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4648 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4649};
4650
c8d5aac9
L
4651static char *remote_support_xml;
4652
4653/* Register string appended to "xmlRegisters=" in qSupported query. */
4654
4655void
6e39997a 4656register_remote_support_xml (const char *xml)
c8d5aac9
L
4657{
4658#if defined(HAVE_LIBEXPAT)
4659 if (remote_support_xml == NULL)
c4f7c687 4660 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4661 else
4662 {
4663 char *copy = xstrdup (remote_support_xml + 13);
4664 char *p = strtok (copy, ",");
4665
4666 do
4667 {
4668 if (strcmp (p, xml) == 0)
4669 {
4670 /* already there */
4671 xfree (copy);
4672 return;
4673 }
4674 }
4675 while ((p = strtok (NULL, ",")) != NULL);
4676 xfree (copy);
4677
94b0dee1
PA
4678 remote_support_xml = reconcat (remote_support_xml,
4679 remote_support_xml, ",", xml,
4680 (char *) NULL);
c8d5aac9
L
4681 }
4682#endif
4683}
4684
4685static char *
4686remote_query_supported_append (char *msg, const char *append)
4687{
4688 if (msg)
94b0dee1 4689 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4690 else
4691 return xstrdup (append);
4692}
4693
be2a5f71
DJ
4694static void
4695remote_query_supported (void)
4696{
4697 struct remote_state *rs = get_remote_state ();
4698 char *next;
4699 int i;
4700 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4701
4702 /* The packet support flags are handled differently for this packet
4703 than for most others. We treat an error, a disabled packet, and
4704 an empty response identically: any features which must be reported
4705 to be used will be automatically disabled. An empty buffer
4706 accomplishes this, since that is also the representation for a list
4707 containing no features. */
4708
4709 rs->buf[0] = 0;
4082afcc 4710 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4711 {
c8d5aac9 4712 char *q = NULL;
94b0dee1 4713 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4714
73b8c1fd
PA
4715 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4716 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4717
f7e6eed5
PA
4718 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4719 q = remote_query_supported_append (q, "swbreak+");
4720 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4721 q = remote_query_supported_append (q, "hwbreak+");
4722
dde08ee1
PA
4723 q = remote_query_supported_append (q, "qRelocInsn+");
4724
8020350c
DB
4725 if (packet_set_cmd_state (PACKET_fork_event_feature)
4726 != AUTO_BOOLEAN_FALSE)
4727 q = remote_query_supported_append (q, "fork-events+");
4728 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4729 != AUTO_BOOLEAN_FALSE)
4730 q = remote_query_supported_append (q, "vfork-events+");
4731 if (packet_set_cmd_state (PACKET_exec_event_feature)
4732 != AUTO_BOOLEAN_FALSE)
4733 q = remote_query_supported_append (q, "exec-events+");
89245bc0 4734
750ce8d1
YQ
4735 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4736 q = remote_query_supported_append (q, "vContSupported+");
4737
65706a29
PA
4738 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4739 q = remote_query_supported_append (q, "QThreadEvents+");
4740
f2faf941
PA
4741 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4742 q = remote_query_supported_append (q, "no-resumed+");
4743
b35d5edb
PA
4744 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4745 the qSupported:xmlRegisters=i386 handling. */
4746 if (remote_support_xml != NULL)
4747 q = remote_query_supported_append (q, remote_support_xml);
4748
dde08ee1
PA
4749 q = reconcat (q, "qSupported:", q, (char *) NULL);
4750 putpkt (q);
82f73884 4751
94b0dee1
PA
4752 do_cleanups (old_chain);
4753
be2a5f71
DJ
4754 getpkt (&rs->buf, &rs->buf_size, 0);
4755
4756 /* If an error occured, warn, but do not return - just reset the
4757 buffer to empty and go on to disable features. */
4758 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4759 == PACKET_ERROR)
4760 {
4761 warning (_("Remote failure reply: %s"), rs->buf);
4762 rs->buf[0] = 0;
4763 }
4764 }
4765
4766 memset (seen, 0, sizeof (seen));
4767
4768 next = rs->buf;
4769 while (*next)
4770 {
4771 enum packet_support is_supported;
4772 char *p, *end, *name_end, *value;
4773
4774 /* First separate out this item from the rest of the packet. If
4775 there's another item after this, we overwrite the separator
4776 (terminated strings are much easier to work with). */
4777 p = next;
4778 end = strchr (p, ';');
4779 if (end == NULL)
4780 {
4781 end = p + strlen (p);
4782 next = end;
4783 }
4784 else
4785 {
89be2091
DJ
4786 *end = '\0';
4787 next = end + 1;
4788
be2a5f71
DJ
4789 if (end == p)
4790 {
4791 warning (_("empty item in \"qSupported\" response"));
4792 continue;
4793 }
be2a5f71
DJ
4794 }
4795
4796 name_end = strchr (p, '=');
4797 if (name_end)
4798 {
4799 /* This is a name=value entry. */
4800 is_supported = PACKET_ENABLE;
4801 value = name_end + 1;
4802 *name_end = '\0';
4803 }
4804 else
4805 {
4806 value = NULL;
4807 switch (end[-1])
4808 {
4809 case '+':
4810 is_supported = PACKET_ENABLE;
4811 break;
4812
4813 case '-':
4814 is_supported = PACKET_DISABLE;
4815 break;
4816
4817 case '?':
4818 is_supported = PACKET_SUPPORT_UNKNOWN;
4819 break;
4820
4821 default:
3e43a32a
MS
4822 warning (_("unrecognized item \"%s\" "
4823 "in \"qSupported\" response"), p);
be2a5f71
DJ
4824 continue;
4825 }
4826 end[-1] = '\0';
4827 }
4828
4829 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4830 if (strcmp (remote_protocol_features[i].name, p) == 0)
4831 {
4832 const struct protocol_feature *feature;
4833
4834 seen[i] = 1;
4835 feature = &remote_protocol_features[i];
4836 feature->func (feature, is_supported, value);
4837 break;
4838 }
4839 }
4840
4841 /* If we increased the packet size, make sure to increase the global
4842 buffer size also. We delay this until after parsing the entire
4843 qSupported packet, because this is the same buffer we were
4844 parsing. */
4845 if (rs->buf_size < rs->explicit_packet_size)
4846 {
4847 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4848 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4849 }
4850
4851 /* Handle the defaults for unmentioned features. */
4852 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4853 if (!seen[i])
4854 {
4855 const struct protocol_feature *feature;
4856
4857 feature = &remote_protocol_features[i];
4858 feature->func (feature, feature->default_support, NULL);
4859 }
4860}
4861
048094ac
PA
4862/* Serial QUIT handler for the remote serial descriptor.
4863
4864 Defers handling a Ctrl-C until we're done with the current
4865 command/response packet sequence, unless:
4866
4867 - We're setting up the connection. Don't send a remote interrupt
4868 request, as we're not fully synced yet. Quit immediately
4869 instead.
4870
4871 - The target has been resumed in the foreground
4872 (target_terminal_is_ours is false) with a synchronous resume
4873 packet, and we're blocked waiting for the stop reply, thus a
4874 Ctrl-C should be immediately sent to the target.
4875
4876 - We get a second Ctrl-C while still within the same serial read or
4877 write. In that case the serial is seemingly wedged --- offer to
4878 quit/disconnect.
4879
4880 - We see a second Ctrl-C without target response, after having
4881 previously interrupted the target. In that case the target/stub
4882 is probably wedged --- offer to quit/disconnect.
4883*/
4884
4885static void
4886remote_serial_quit_handler (void)
4887{
4888 struct remote_state *rs = get_remote_state ();
4889
4890 if (check_quit_flag ())
4891 {
4892 /* If we're starting up, we're not fully synced yet. Quit
4893 immediately. */
4894 if (rs->starting_up)
4895 quit ();
4896 else if (rs->got_ctrlc_during_io)
4897 {
4898 if (query (_("The target is not responding to GDB commands.\n"
4899 "Stop debugging it? ")))
4900 remote_unpush_and_throw ();
4901 }
4902 /* If ^C has already been sent once, offer to disconnect. */
4903 else if (!target_terminal_is_ours () && rs->ctrlc_pending_p)
4904 interrupt_query ();
4905 /* All-stop protocol, and blocked waiting for stop reply. Send
4906 an interrupt request. */
4907 else if (!target_terminal_is_ours () && rs->waiting_for_stop_reply)
4908 target_interrupt (inferior_ptid);
4909 else
4910 rs->got_ctrlc_during_io = 1;
4911 }
4912}
4913
78a095c3
JK
4914/* Remove any of the remote.c targets from target stack. Upper targets depend
4915 on it so remove them first. */
4916
4917static void
4918remote_unpush_target (void)
4919{
915ef8b1 4920 pop_all_targets_at_and_above (process_stratum);
78a095c3 4921}
be2a5f71 4922
048094ac
PA
4923static void
4924remote_unpush_and_throw (void)
4925{
4926 remote_unpush_target ();
4927 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
4928}
4929
c906108c 4930static void
014f9477 4931remote_open_1 (const char *name, int from_tty,
3e43a32a 4932 struct target_ops *target, int extended_p)
c906108c 4933{
d01949b6 4934 struct remote_state *rs = get_remote_state ();
a6f3e723 4935
c906108c 4936 if (name == 0)
8a3fe4f8 4937 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4938 "serial device is attached to the remote system\n"
8a3fe4f8 4939 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4940
23860348 4941 /* See FIXME above. */
c6ebd6cf 4942 if (!target_async_permitted)
92d1e331 4943 wait_forever_enabled_p = 1;
6426a772 4944
2d717e4f 4945 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4946 Ask this question first, before target_preopen has a chance to kill
4947 anything. */
5d93a237 4948 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4949 {
78a095c3
JK
4950 if (from_tty
4951 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4952 error (_("Still connected."));
4953 }
4954
78a095c3 4955 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4956 target_preopen (from_tty);
4957
89be2091 4958 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4959 xfree (rs->last_pass_packet);
4960 rs->last_pass_packet = NULL;
89be2091 4961
9b224c5e
PA
4962 /* Make sure we send the program signals list the next time we
4963 resume. */
5e4a05c4
TT
4964 xfree (rs->last_program_signals_packet);
4965 rs->last_program_signals_packet = NULL;
9b224c5e 4966
ad9a8f3f 4967 remote_fileio_reset ();
1dd41f16
NS
4968 reopen_exec_file ();
4969 reread_symbols ();
4970
5d93a237
TT
4971 rs->remote_desc = remote_serial_open (name);
4972 if (!rs->remote_desc)
c906108c
SS
4973 perror_with_name (name);
4974
4975 if (baud_rate != -1)
4976 {
5d93a237 4977 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4978 {
9b74d5d3
KB
4979 /* The requested speed could not be set. Error out to
4980 top level after closing remote_desc. Take care to
4981 set remote_desc to NULL to avoid closing remote_desc
4982 more than once. */
5d93a237
TT
4983 serial_close (rs->remote_desc);
4984 rs->remote_desc = NULL;
c906108c
SS
4985 perror_with_name (name);
4986 }
4987 }
4988
236af5e3 4989 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4990 serial_raw (rs->remote_desc);
c906108c
SS
4991
4992 /* If there is something sitting in the buffer we might take it as a
4993 response to a command, which would be bad. */
5d93a237 4994 serial_flush_input (rs->remote_desc);
c906108c
SS
4995
4996 if (from_tty)
4997 {
4998 puts_filtered ("Remote debugging using ");
4999 puts_filtered (name);
5000 puts_filtered ("\n");
5001 }
23860348 5002 push_target (target); /* Switch to using remote target now. */
c906108c 5003
74531fed
PA
5004 /* Register extra event sources in the event loop. */
5005 remote_async_inferior_event_token
5006 = create_async_event_handler (remote_async_inferior_event_handler,
5007 NULL);
5965e028 5008 rs->notif_state = remote_notif_state_allocate ();
74531fed 5009
be2a5f71
DJ
5010 /* Reset the target state; these things will be queried either by
5011 remote_query_supported or as they are needed. */
ca4f7f8b 5012 reset_all_packet_configs_support ();
74531fed 5013 rs->cached_wait_status = 0;
be2a5f71 5014 rs->explicit_packet_size = 0;
a6f3e723 5015 rs->noack_mode = 0;
82f73884 5016 rs->extended = extended_p;
e24a49d8 5017 rs->waiting_for_stop_reply = 0;
3a29589a 5018 rs->ctrlc_pending_p = 0;
048094ac 5019 rs->got_ctrlc_during_io = 0;
802188a7 5020
47f8a51d
TT
5021 rs->general_thread = not_sent_ptid;
5022 rs->continue_thread = not_sent_ptid;
262e1174 5023 rs->remote_traceframe_number = -1;
c906108c 5024
3a00c802
PA
5025 rs->last_resume_exec_dir = EXEC_FORWARD;
5026
9d1f7ab2 5027 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5028 rs->use_threadinfo_query = 1;
5029 rs->use_threadextra_query = 1;
9d1f7ab2 5030
80152258
PA
5031 readahead_cache_invalidate ();
5032
048094ac
PA
5033 /* Start out by owning the terminal. */
5034 remote_async_terminal_ours_p = 1;
5035
c6ebd6cf 5036 if (target_async_permitted)
92d1e331 5037 {
92d1e331
DJ
5038 /* FIXME: cagney/1999-09-23: During the initial connection it is
5039 assumed that the target is already ready and able to respond to
0df8b418 5040 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5041 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5042 around this. Eventually a mechanism that allows
92d1e331 5043 wait_for_inferior() to expect/get timeouts will be
23860348 5044 implemented. */
92d1e331
DJ
5045 wait_forever_enabled_p = 0;
5046 }
5047
23860348 5048 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5049 no_shared_libraries (NULL, 0);
f78f6cf1 5050
74531fed
PA
5051 /* Start afresh. */
5052 init_thread_list ();
5053
36918e70 5054 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5055 target (we'd otherwise be in an inconsistent state) and then
5056 propogate the error on up the exception chain. This ensures that
5057 the caller doesn't stumble along blindly assuming that the
5058 function succeeded. The CLI doesn't have this problem but other
5059 UI's, such as MI do.
36918e70
AC
5060
5061 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5062 this function should return an error indication letting the
ce2826aa 5063 caller restore the previous state. Unfortunately the command
36918e70
AC
5064 ``target remote'' is directly wired to this function making that
5065 impossible. On a positive note, the CLI side of this problem has
5066 been fixed - the function set_cmd_context() makes it possible for
5067 all the ``target ....'' commands to share a common callback
5068 function. See cli-dump.c. */
109c3e39 5069 {
2d717e4f 5070
492d29ea 5071 TRY
04bd08de
TT
5072 {
5073 remote_start_remote (from_tty, target, extended_p);
5074 }
492d29ea 5075 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5076 {
c8d104ad
PA
5077 /* Pop the partially set up target - unless something else did
5078 already before throwing the exception. */
5d93a237 5079 if (rs->remote_desc != NULL)
78a095c3 5080 remote_unpush_target ();
c6ebd6cf 5081 if (target_async_permitted)
109c3e39
AC
5082 wait_forever_enabled_p = 1;
5083 throw_exception (ex);
5084 }
492d29ea 5085 END_CATCH
109c3e39 5086 }
c906108c 5087
f4abbc16
MM
5088 remote_btrace_reset ();
5089
c6ebd6cf 5090 if (target_async_permitted)
92d1e331 5091 wait_forever_enabled_p = 1;
43ff13b4
JM
5092}
5093
de0d863e
DB
5094/* Detach the specified process. */
5095
5096static void
5097remote_detach_pid (int pid)
5098{
5099 struct remote_state *rs = get_remote_state ();
5100
5101 if (remote_multi_process_p (rs))
5102 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5103 else
5104 strcpy (rs->buf, "D");
5105
5106 putpkt (rs->buf);
5107 getpkt (&rs->buf, &rs->buf_size, 0);
5108
5109 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5110 ;
5111 else if (rs->buf[0] == '\0')
5112 error (_("Remote doesn't know how to detach"));
5113 else
5114 error (_("Can't detach process."));
5115}
5116
5117/* This detaches a program to which we previously attached, using
5118 inferior_ptid to identify the process. After this is done, GDB
5119 can be used to debug some other program. We better not have left
5120 any breakpoints in the target program or it'll die when it hits
5121 one. */
c906108c
SS
5122
5123static void
de0d863e 5124remote_detach_1 (const char *args, int from_tty)
c906108c 5125{
82f73884 5126 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5127 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5128 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5129 int is_fork_parent;
c906108c
SS
5130
5131 if (args)
8a3fe4f8 5132 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 5133
2d717e4f
DJ
5134 if (!target_has_execution)
5135 error (_("No process to detach from."));
5136
7cee1e54
PA
5137 if (from_tty)
5138 {
5139 char *exec_file = get_exec_file (0);
5140 if (exec_file == NULL)
5141 exec_file = "";
5142 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
5143 target_pid_to_str (pid_to_ptid (pid)));
5144 gdb_flush (gdb_stdout);
5145 }
5146
c906108c 5147 /* Tell the remote target to detach. */
de0d863e 5148 remote_detach_pid (pid);
82f73884 5149
8020350c
DB
5150 /* Exit only if this is the only active inferior. */
5151 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5152 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5153
de0d863e
DB
5154 /* Check to see if we are detaching a fork parent. Note that if we
5155 are detaching a fork child, tp == NULL. */
5156 is_fork_parent = (tp != NULL
5157 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5158
5159 /* If doing detach-on-fork, we don't mourn, because that will delete
5160 breakpoints that should be available for the followed inferior. */
5161 if (!is_fork_parent)
5162 target_mourn_inferior ();
5163 else
5164 {
5165 inferior_ptid = null_ptid;
5166 detach_inferior (pid);
5167 }
2d717e4f
DJ
5168}
5169
5170static void
52554a0e 5171remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5172{
de0d863e 5173 remote_detach_1 (args, from_tty);
2d717e4f
DJ
5174}
5175
5176static void
52554a0e 5177extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5178{
de0d863e
DB
5179 remote_detach_1 (args, from_tty);
5180}
5181
5182/* Target follow-fork function for remote targets. On entry, and
5183 at return, the current inferior is the fork parent.
5184
5185 Note that although this is currently only used for extended-remote,
5186 it is named remote_follow_fork in anticipation of using it for the
5187 remote target as well. */
5188
5189static int
5190remote_follow_fork (struct target_ops *ops, int follow_child,
5191 int detach_fork)
5192{
5193 struct remote_state *rs = get_remote_state ();
c269dbdb 5194 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5195
c269dbdb
DB
5196 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5197 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5198 {
5199 /* When following the parent and detaching the child, we detach
5200 the child here. For the case of following the child and
5201 detaching the parent, the detach is done in the target-
5202 independent follow fork code in infrun.c. We can't use
5203 target_detach when detaching an unfollowed child because
5204 the client side doesn't know anything about the child. */
5205 if (detach_fork && !follow_child)
5206 {
5207 /* Detach the fork child. */
5208 ptid_t child_ptid;
5209 pid_t child_pid;
5210
5211 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5212 child_pid = ptid_get_pid (child_ptid);
5213
5214 remote_detach_pid (child_pid);
5215 detach_inferior (child_pid);
5216 }
5217 }
5218 return 0;
c906108c
SS
5219}
5220
94585166
DB
5221/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5222 in the program space of the new inferior. On entry and at return the
5223 current inferior is the exec'ing inferior. INF is the new exec'd
5224 inferior, which may be the same as the exec'ing inferior unless
5225 follow-exec-mode is "new". */
5226
5227static void
5228remote_follow_exec (struct target_ops *ops,
5229 struct inferior *inf, char *execd_pathname)
5230{
5231 /* We know that this is a target file name, so if it has the "target:"
5232 prefix we strip it off before saving it in the program space. */
5233 if (is_target_filename (execd_pathname))
5234 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5235
5236 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5237}
5238
6ad8ae5c
DJ
5239/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5240
43ff13b4 5241static void
fee354ee 5242remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5243{
43ff13b4 5244 if (args)
2d717e4f 5245 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5246
8020350c
DB
5247 /* Make sure we unpush even the extended remote targets. Calling
5248 target_mourn_inferior won't unpush, and remote_mourn won't
5249 unpush if there is more than one inferior left. */
5250 unpush_target (target);
5251 generic_mourn_inferior ();
2d717e4f 5252
43ff13b4
JM
5253 if (from_tty)
5254 puts_filtered ("Ending remote debugging.\n");
5255}
5256
2d717e4f
DJ
5257/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5258 be chatty about it. */
5259
5260static void
20f796c9
GB
5261extended_remote_attach (struct target_ops *target, const char *args,
5262 int from_tty)
2d717e4f
DJ
5263{
5264 struct remote_state *rs = get_remote_state ();
be86555c 5265 int pid;
96ef3384 5266 char *wait_status = NULL;
2d717e4f 5267
74164c56 5268 pid = parse_pid_to_attach (args);
2d717e4f 5269
74164c56
JK
5270 /* Remote PID can be freely equal to getpid, do not check it here the same
5271 way as in other targets. */
2d717e4f 5272
4082afcc 5273 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5274 error (_("This target does not support attaching to a process"));
5275
7cee1e54
PA
5276 if (from_tty)
5277 {
5278 char *exec_file = get_exec_file (0);
5279
5280 if (exec_file)
5281 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5282 target_pid_to_str (pid_to_ptid (pid)));
5283 else
5284 printf_unfiltered (_("Attaching to %s\n"),
5285 target_pid_to_str (pid_to_ptid (pid)));
5286
5287 gdb_flush (gdb_stdout);
5288 }
5289
bba74b36 5290 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5291 putpkt (rs->buf);
5292 getpkt (&rs->buf, &rs->buf_size, 0);
5293
4082afcc
PA
5294 switch (packet_ok (rs->buf,
5295 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5296 {
4082afcc 5297 case PACKET_OK:
6efcd9a8 5298 if (!target_is_non_stop_p ())
74531fed
PA
5299 {
5300 /* Save the reply for later. */
224c3ddb 5301 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5302 strcpy (wait_status, rs->buf);
5303 }
5304 else if (strcmp (rs->buf, "OK") != 0)
5305 error (_("Attaching to %s failed with: %s"),
5306 target_pid_to_str (pid_to_ptid (pid)),
5307 rs->buf);
4082afcc
PA
5308 break;
5309 case PACKET_UNKNOWN:
5310 error (_("This target does not support attaching to a process"));
5311 default:
5312 error (_("Attaching to %s failed"),
5313 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5314 }
2d717e4f 5315
1b6e6f5c 5316 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5317
2d717e4f 5318 inferior_ptid = pid_to_ptid (pid);
79d7f229 5319
6efcd9a8 5320 if (target_is_non_stop_p ())
bad34192
PA
5321 {
5322 struct thread_info *thread;
79d7f229 5323
bad34192 5324 /* Get list of threads. */
e8032dde 5325 remote_update_thread_list (target);
82f73884 5326
bad34192
PA
5327 thread = first_thread_of_process (pid);
5328 if (thread)
5329 inferior_ptid = thread->ptid;
5330 else
5331 inferior_ptid = pid_to_ptid (pid);
5332
5333 /* Invalidate our notion of the remote current thread. */
47f8a51d 5334 record_currthread (rs, minus_one_ptid);
bad34192 5335 }
74531fed 5336 else
bad34192
PA
5337 {
5338 /* Now, if we have thread information, update inferior_ptid. */
5339 inferior_ptid = remote_current_thread (inferior_ptid);
5340
5341 /* Add the main thread to the thread list. */
5342 add_thread_silent (inferior_ptid);
5343 }
c0a2216e 5344
96ef3384
UW
5345 /* Next, if the target can specify a description, read it. We do
5346 this before anything involving memory or registers. */
5347 target_find_description ();
5348
6efcd9a8 5349 if (!target_is_non_stop_p ())
74531fed
PA
5350 {
5351 /* Use the previously fetched status. */
5352 gdb_assert (wait_status != NULL);
5353
5354 if (target_can_async_p ())
5355 {
722247f1
YQ
5356 struct notif_event *reply
5357 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5358
722247f1 5359 push_stop_reply ((struct stop_reply *) reply);
74531fed 5360
6a3753b3 5361 target_async (1);
74531fed
PA
5362 }
5363 else
5364 {
5365 gdb_assert (wait_status != NULL);
5366 strcpy (rs->buf, wait_status);
5367 rs->cached_wait_status = 1;
5368 }
5369 }
5370 else
5371 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5372}
5373
b9c1d481
AS
5374/* Implementation of the to_post_attach method. */
5375
5376static void
5377extended_remote_post_attach (struct target_ops *ops, int pid)
5378{
6efcd9a8
PA
5379 /* Get text, data & bss offsets. */
5380 get_offsets ();
5381
b9c1d481
AS
5382 /* In certain cases GDB might not have had the chance to start
5383 symbol lookup up until now. This could happen if the debugged
5384 binary is not using shared libraries, the vsyscall page is not
5385 present (on Linux) and the binary itself hadn't changed since the
5386 debugging process was started. */
5387 if (symfile_objfile != NULL)
5388 remote_check_symbols();
5389}
5390
c906108c 5391\f
506fb367
DJ
5392/* Check for the availability of vCont. This function should also check
5393 the response. */
c906108c
SS
5394
5395static void
6d820c5c 5396remote_vcont_probe (struct remote_state *rs)
c906108c 5397{
2e9f7625 5398 char *buf;
6d820c5c 5399
2e9f7625
DJ
5400 strcpy (rs->buf, "vCont?");
5401 putpkt (rs->buf);
6d820c5c 5402 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5403 buf = rs->buf;
c906108c 5404
506fb367 5405 /* Make sure that the features we assume are supported. */
61012eef 5406 if (startswith (buf, "vCont"))
506fb367
DJ
5407 {
5408 char *p = &buf[5];
750ce8d1 5409 int support_c, support_C;
506fb367 5410
750ce8d1
YQ
5411 rs->supports_vCont.s = 0;
5412 rs->supports_vCont.S = 0;
506fb367
DJ
5413 support_c = 0;
5414 support_C = 0;
d458bd84 5415 rs->supports_vCont.t = 0;
c1e36e3e 5416 rs->supports_vCont.r = 0;
506fb367
DJ
5417 while (p && *p == ';')
5418 {
5419 p++;
5420 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5421 rs->supports_vCont.s = 1;
506fb367 5422 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5423 rs->supports_vCont.S = 1;
506fb367
DJ
5424 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5425 support_c = 1;
5426 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5427 support_C = 1;
74531fed 5428 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5429 rs->supports_vCont.t = 1;
c1e36e3e
PA
5430 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5431 rs->supports_vCont.r = 1;
506fb367
DJ
5432
5433 p = strchr (p, ';');
5434 }
c906108c 5435
750ce8d1
YQ
5436 /* If c, and C are not all supported, we can't use vCont. Clearing
5437 BUF will make packet_ok disable the packet. */
5438 if (!support_c || !support_C)
506fb367
DJ
5439 buf[0] = 0;
5440 }
c906108c 5441
444abaca 5442 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5443}
c906108c 5444
0d8f58ca
PA
5445/* Helper function for building "vCont" resumptions. Write a
5446 resumption to P. ENDP points to one-passed-the-end of the buffer
5447 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5448 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5449 resumed thread should be single-stepped and/or signalled. If PTID
5450 equals minus_one_ptid, then all threads are resumed; if PTID
5451 represents a process, then all threads of the process are resumed;
5452 the thread to be stepped and/or signalled is given in the global
5453 INFERIOR_PTID. */
5454
5455static char *
5456append_resumption (char *p, char *endp,
2ea28649 5457 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5458{
5459 struct remote_state *rs = get_remote_state ();
5460
a493e3e2 5461 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5462 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5463 else if (step
5464 /* GDB is willing to range step. */
5465 && use_range_stepping
5466 /* Target supports range stepping. */
5467 && rs->supports_vCont.r
5468 /* We don't currently support range stepping multiple
5469 threads with a wildcard (though the protocol allows it,
5470 so stubs shouldn't make an active effort to forbid
5471 it). */
5472 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5473 {
5474 struct thread_info *tp;
5475
5476 if (ptid_equal (ptid, minus_one_ptid))
5477 {
5478 /* If we don't know about the target thread's tid, then
5479 we're resuming magic_null_ptid (see caller). */
5480 tp = find_thread_ptid (magic_null_ptid);
5481 }
5482 else
5483 tp = find_thread_ptid (ptid);
5484 gdb_assert (tp != NULL);
5485
5486 if (tp->control.may_range_step)
5487 {
5488 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5489
5490 p += xsnprintf (p, endp - p, ";r%s,%s",
5491 phex_nz (tp->control.step_range_start,
5492 addr_size),
5493 phex_nz (tp->control.step_range_end,
5494 addr_size));
5495 }
5496 else
5497 p += xsnprintf (p, endp - p, ";s");
5498 }
0d8f58ca
PA
5499 else if (step)
5500 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5501 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5502 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5503 else
5504 p += xsnprintf (p, endp - p, ";c");
5505
5506 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5507 {
5508 ptid_t nptid;
5509
5510 /* All (-1) threads of process. */
ba348170 5511 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5512
5513 p += xsnprintf (p, endp - p, ":");
5514 p = write_ptid (p, endp, nptid);
5515 }
5516 else if (!ptid_equal (ptid, minus_one_ptid))
5517 {
5518 p += xsnprintf (p, endp - p, ":");
5519 p = write_ptid (p, endp, ptid);
5520 }
5521
5522 return p;
5523}
5524
799a2abe
PA
5525/* Clear the thread's private info on resume. */
5526
5527static void
5528resume_clear_thread_private_info (struct thread_info *thread)
5529{
5530 if (thread->priv != NULL)
5531 {
5532 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5533 thread->priv->watch_data_address = 0;
5534 }
5535}
5536
e5ef252a
PA
5537/* Append a vCont continue-with-signal action for threads that have a
5538 non-zero stop signal. */
5539
5540static char *
5541append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5542{
5543 struct thread_info *thread;
5544
034f788c 5545 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5546 if (ptid_match (thread->ptid, ptid)
5547 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5548 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5549 {
5550 p = append_resumption (p, endp, thread->ptid,
5551 0, thread->suspend.stop_signal);
5552 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5553 resume_clear_thread_private_info (thread);
e5ef252a
PA
5554 }
5555
5556 return p;
5557}
5558
506fb367
DJ
5559/* Resume the remote inferior by using a "vCont" packet. The thread
5560 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5561 resumed thread should be single-stepped and/or signalled. If PTID
5562 equals minus_one_ptid, then all threads are resumed; the thread to
5563 be stepped and/or signalled is given in the global INFERIOR_PTID.
5564 This function returns non-zero iff it resumes the inferior.
44eaed12 5565
506fb367
DJ
5566 This function issues a strict subset of all possible vCont commands at the
5567 moment. */
44eaed12 5568
506fb367 5569static int
2ea28649 5570remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5571{
5572 struct remote_state *rs = get_remote_state ();
82f73884
PA
5573 char *p;
5574 char *endp;
44eaed12 5575
4082afcc 5576 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5577 remote_vcont_probe (rs);
44eaed12 5578
4082afcc 5579 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5580 return 0;
44eaed12 5581
82f73884
PA
5582 p = rs->buf;
5583 endp = rs->buf + get_remote_packet_size ();
5584
506fb367
DJ
5585 /* If we could generate a wider range of packets, we'd have to worry
5586 about overflowing BUF. Should there be a generic
5587 "multi-part-packet" packet? */
5588
0d8f58ca
PA
5589 p += xsnprintf (p, endp - p, "vCont");
5590
79d7f229 5591 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5592 {
79d7f229
PA
5593 /* MAGIC_NULL_PTID means that we don't have any active threads,
5594 so we don't have any TID numbers the inferior will
5595 understand. Make sure to only send forms that do not specify
5596 a TID. */
a9cbf802 5597 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5598 }
0d8f58ca 5599 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5600 {
0d8f58ca
PA
5601 /* Resume all threads (of all processes, or of a single
5602 process), with preference for INFERIOR_PTID. This assumes
5603 inferior_ptid belongs to the set of all threads we are about
5604 to resume. */
a493e3e2 5605 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5606 {
0d8f58ca
PA
5607 /* Step inferior_ptid, with or without signal. */
5608 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5609 }
0d8f58ca 5610
e5ef252a
PA
5611 /* Also pass down any pending signaled resumption for other
5612 threads not the current. */
5613 p = append_pending_thread_resumptions (p, endp, ptid);
5614
0d8f58ca 5615 /* And continue others without a signal. */
a493e3e2 5616 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5617 }
5618 else
506fb367
DJ
5619 {
5620 /* Scheduler locking; resume only PTID. */
a9cbf802 5621 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5622 }
c906108c 5623
82f73884
PA
5624 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5625 putpkt (rs->buf);
506fb367 5626
6efcd9a8 5627 if (target_is_non_stop_p ())
74531fed
PA
5628 {
5629 /* In non-stop, the stub replies to vCont with "OK". The stop
5630 reply will be reported asynchronously by means of a `%Stop'
5631 notification. */
5632 getpkt (&rs->buf, &rs->buf_size, 0);
5633 if (strcmp (rs->buf, "OK") != 0)
5634 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5635 }
5636
506fb367 5637 return 1;
c906108c 5638}
43ff13b4 5639
506fb367
DJ
5640/* Tell the remote machine to resume. */
5641
43ff13b4 5642static void
28439f5e 5643remote_resume (struct target_ops *ops,
2ea28649 5644 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5645{
d01949b6 5646 struct remote_state *rs = get_remote_state ();
2e9f7625 5647 char *buf;
799a2abe 5648 struct thread_info *thread;
43ff13b4 5649
722247f1
YQ
5650 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5651 (explained in remote-notif.c:handle_notification) so
5652 remote_notif_process is not called. We need find a place where
5653 it is safe to start a 'vNotif' sequence. It is good to do it
5654 before resuming inferior, because inferior was stopped and no RSP
5655 traffic at that moment. */
6efcd9a8 5656 if (!target_is_non_stop_p ())
5965e028 5657 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5658
b73be471 5659 rs->last_sent_signal = siggnal;
280ceea3 5660 rs->last_sent_step = step;
43ff13b4 5661
3a00c802
PA
5662 rs->last_resume_exec_dir = execution_direction;
5663
506fb367 5664 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5665 /* No reverse support (yet) for vCont. */
5666 if (execution_direction != EXEC_REVERSE)
5667 if (remote_vcont_resume (ptid, step, siggnal))
5668 goto done;
506fb367 5669
79d7f229
PA
5670 /* All other supported resume packets do use Hc, so set the continue
5671 thread. */
5672 if (ptid_equal (ptid, minus_one_ptid))
5673 set_continue_thread (any_thread_ptid);
506fb367 5674 else
79d7f229 5675 set_continue_thread (ptid);
506fb367 5676
799a2abe
PA
5677 ALL_NON_EXITED_THREADS (thread)
5678 resume_clear_thread_private_info (thread);
5679
2e9f7625 5680 buf = rs->buf;
b2175913
MS
5681 if (execution_direction == EXEC_REVERSE)
5682 {
5683 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5684 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5685 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5686 siggnal);
40ab02ce 5687
4082afcc 5688 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5689 error (_("Remote reverse-step not supported."));
4082afcc 5690 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5691 error (_("Remote reverse-continue not supported."));
40ab02ce 5692
b2175913
MS
5693 strcpy (buf, step ? "bs" : "bc");
5694 }
a493e3e2 5695 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5696 {
5697 buf[0] = step ? 'S' : 'C';
c5aa993b 5698 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5699 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5700 buf[3] = '\0';
5701 }
5702 else
c5aa993b 5703 strcpy (buf, step ? "s" : "c");
506fb367 5704
44eaed12 5705 putpkt (buf);
43ff13b4 5706
75c99385 5707 done:
2acceee2 5708 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5709 with the event loop. NOTE: this is the one place where all the
5710 execution commands end up. We could alternatively do this in each
23860348 5711 of the execution commands in infcmd.c. */
2acceee2
JM
5712 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5713 into infcmd.c in order to allow inferior function calls to work
23860348 5714 NOT asynchronously. */
362646f5 5715 if (target_can_async_p ())
6a3753b3 5716 target_async (1);
e24a49d8
PA
5717
5718 /* We've just told the target to resume. The remote server will
5719 wait for the inferior to stop, and then send a stop reply. In
5720 the mean time, we can't start another command/query ourselves
74531fed
PA
5721 because the stub wouldn't be ready to process it. This applies
5722 only to the base all-stop protocol, however. In non-stop (which
5723 only supports vCont), the stub replies with an "OK", and is
5724 immediate able to process further serial input. */
6efcd9a8 5725 if (!target_is_non_stop_p ())
74531fed 5726 rs->waiting_for_stop_reply = 1;
43ff13b4 5727}
c906108c 5728\f
43ff13b4 5729
74531fed
PA
5730/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5731 thread, all threads of a remote process, or all threads of all
5732 processes. */
5733
5734static void
5735remote_stop_ns (ptid_t ptid)
5736{
5737 struct remote_state *rs = get_remote_state ();
5738 char *p = rs->buf;
5739 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5740
4082afcc 5741 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5742 remote_vcont_probe (rs);
5743
d458bd84 5744 if (!rs->supports_vCont.t)
74531fed
PA
5745 error (_("Remote server does not support stopping threads"));
5746
f91d3df5
PA
5747 if (ptid_equal (ptid, minus_one_ptid)
5748 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5749 p += xsnprintf (p, endp - p, "vCont;t");
5750 else
5751 {
5752 ptid_t nptid;
5753
74531fed
PA
5754 p += xsnprintf (p, endp - p, "vCont;t:");
5755
5756 if (ptid_is_pid (ptid))
5757 /* All (-1) threads of process. */
ba348170 5758 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5759 else
5760 {
5761 /* Small optimization: if we already have a stop reply for
5762 this thread, no use in telling the stub we want this
5763 stopped. */
5764 if (peek_stop_reply (ptid))
5765 return;
5766
5767 nptid = ptid;
5768 }
5769
a9cbf802 5770 write_ptid (p, endp, nptid);
74531fed
PA
5771 }
5772
5773 /* In non-stop, we get an immediate OK reply. The stop reply will
5774 come in asynchronously by notification. */
5775 putpkt (rs->buf);
5776 getpkt (&rs->buf, &rs->buf_size, 0);
5777 if (strcmp (rs->buf, "OK") != 0)
5778 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5779}
5780
bfedc46a
PA
5781/* All-stop version of target_interrupt. Sends a break or a ^C to
5782 interrupt the remote target. It is undefined which thread of which
5783 process reports the interrupt. */
74531fed
PA
5784
5785static void
de979965 5786remote_interrupt_as (void)
74531fed
PA
5787{
5788 struct remote_state *rs = get_remote_state ();
5789
3a29589a
DJ
5790 rs->ctrlc_pending_p = 1;
5791
74531fed
PA
5792 /* If the inferior is stopped already, but the core didn't know
5793 about it yet, just ignore the request. The cached wait status
5794 will be collected in remote_wait. */
5795 if (rs->cached_wait_status)
5796 return;
5797
9a7071a8
JB
5798 /* Send interrupt_sequence to remote target. */
5799 send_interrupt_sequence ();
74531fed
PA
5800}
5801
de979965
PA
5802/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5803 the remote target. It is undefined which thread of which process
e42de8c7
PA
5804 reports the interrupt. Throws an error if the packet is not
5805 supported by the server. */
de979965 5806
e42de8c7 5807static void
de979965
PA
5808remote_interrupt_ns (void)
5809{
5810 struct remote_state *rs = get_remote_state ();
5811 char *p = rs->buf;
5812 char *endp = rs->buf + get_remote_packet_size ();
5813
5814 xsnprintf (p, endp - p, "vCtrlC");
5815
5816 /* In non-stop, we get an immediate OK reply. The stop reply will
5817 come in asynchronously by notification. */
5818 putpkt (rs->buf);
5819 getpkt (&rs->buf, &rs->buf_size, 0);
5820
5821 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5822 {
5823 case PACKET_OK:
5824 break;
5825 case PACKET_UNKNOWN:
e42de8c7 5826 error (_("No support for interrupting the remote target."));
de979965
PA
5827 case PACKET_ERROR:
5828 error (_("Interrupting target failed: %s"), rs->buf);
5829 }
de979965
PA
5830}
5831
bfedc46a 5832/* Implement the to_stop function for the remote targets. */
74531fed 5833
c906108c 5834static void
1eab8a48 5835remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5836{
7a292a7a 5837 if (remote_debug)
0f71a2f6 5838 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5839
6efcd9a8 5840 if (target_is_non_stop_p ())
74531fed 5841 remote_stop_ns (ptid);
c906108c 5842 else
bfedc46a
PA
5843 {
5844 /* We don't currently have a way to transparently pause the
5845 remote target in all-stop mode. Interrupt it instead. */
de979965 5846 remote_interrupt_as ();
bfedc46a
PA
5847 }
5848}
5849
5850/* Implement the to_interrupt function for the remote targets. */
5851
5852static void
5853remote_interrupt (struct target_ops *self, ptid_t ptid)
5854{
e42de8c7
PA
5855 struct remote_state *rs = get_remote_state ();
5856
bfedc46a
PA
5857 if (remote_debug)
5858 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5859
e42de8c7
PA
5860 if (target_is_non_stop_p ())
5861 remote_interrupt_ns ();
bfedc46a 5862 else
e42de8c7 5863 remote_interrupt_as ();
c906108c
SS
5864}
5865
93692b58
PA
5866/* Implement the to_pass_ctrlc function for the remote targets. */
5867
5868static void
5869remote_pass_ctrlc (struct target_ops *self)
5870{
5871 struct remote_state *rs = get_remote_state ();
5872
5873 if (remote_debug)
5874 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
5875
5876 /* If we're starting up, we're not fully synced yet. Quit
5877 immediately. */
5878 if (rs->starting_up)
5879 quit ();
5880 /* If ^C has already been sent once, offer to disconnect. */
5881 else if (rs->ctrlc_pending_p)
5882 interrupt_query ();
5883 else
5884 target_interrupt (inferior_ptid);
5885}
5886
c906108c
SS
5887/* Ask the user what to do when an interrupt is received. */
5888
5889static void
fba45db2 5890interrupt_query (void)
c906108c 5891{
abc56d60 5892 struct remote_state *rs = get_remote_state ();
c906108c 5893
abc56d60 5894 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5895 {
abc56d60
PA
5896 if (query (_("The target is not responding to interrupt requests.\n"
5897 "Stop debugging it? ")))
74531fed 5898 {
78a095c3 5899 remote_unpush_target ();
abc56d60 5900 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5901 }
5902 }
abc56d60
PA
5903 else
5904 {
5905 if (query (_("Interrupted while waiting for the program.\n"
5906 "Give up waiting? ")))
5907 quit ();
5908 }
c906108c
SS
5909}
5910
6426a772
JM
5911/* Enable/disable target terminal ownership. Most targets can use
5912 terminal groups to control terminal ownership. Remote targets are
5913 different in that explicit transfer of ownership to/from GDB/target
23860348 5914 is required. */
6426a772
JM
5915
5916static void
d2f640d4 5917remote_terminal_inferior (struct target_ops *self)
6426a772 5918{
d9d2d8b6
PA
5919 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5920 idempotent. The event-loop GDB talking to an asynchronous target
5921 with a synchronous command calls this function from both
5922 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5923 transfer the terminal to the target when it shouldn't this guard
5924 can go away. */
6426a772
JM
5925 if (!remote_async_terminal_ours_p)
5926 return;
5927 delete_file_handler (input_fd);
5928 remote_async_terminal_ours_p = 0;
6426a772
JM
5929 /* NOTE: At this point we could also register our selves as the
5930 recipient of all input. Any characters typed could then be
23860348 5931 passed on down to the target. */
6426a772
JM
5932}
5933
5934static void
e3594fd1 5935remote_terminal_ours (struct target_ops *self)
6426a772 5936{
75c99385 5937 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5938 if (remote_async_terminal_ours_p)
5939 return;
6426a772
JM
5940 add_file_handler (input_fd, stdin_event_handler, 0);
5941 remote_async_terminal_ours_p = 1;
5942}
5943
176a6961 5944static void
917317f4 5945remote_console_output (char *msg)
c906108c
SS
5946{
5947 char *p;
5948
c5aa993b 5949 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5950 {
5951 char tb[2];
5952 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5953
c906108c
SS
5954 tb[0] = c;
5955 tb[1] = 0;
43ff13b4 5956 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5957 }
00db5b94
PA
5958 gdb_flush (gdb_stdtarg);
5959}
74531fed
PA
5960
5961typedef struct cached_reg
5962{
5963 int num;
5964 gdb_byte data[MAX_REGISTER_SIZE];
5965} cached_reg_t;
5966
5967DEF_VEC_O(cached_reg_t);
5968
722247f1 5969typedef struct stop_reply
74531fed 5970{
722247f1 5971 struct notif_event base;
74531fed 5972
722247f1 5973 /* The identifier of the thread about this event */
74531fed
PA
5974 ptid_t ptid;
5975
340e3c99 5976 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5977 connection, represented by a remote_state object, is closed,
5978 all the associated stop_reply events should be released. */
5979 struct remote_state *rs;
5980
74531fed
PA
5981 struct target_waitstatus ws;
5982
15148d6a
PA
5983 /* Expedited registers. This makes remote debugging a bit more
5984 efficient for those targets that provide critical registers as
5985 part of their normal status mechanism (as another roundtrip to
5986 fetch them is avoided). */
74531fed
PA
5987 VEC(cached_reg_t) *regcache;
5988
f7e6eed5
PA
5989 enum target_stop_reason stop_reason;
5990
74531fed
PA
5991 CORE_ADDR watch_data_address;
5992
dc146f7c 5993 int core;
722247f1 5994} *stop_reply_p;
a744cf53 5995
722247f1
YQ
5996DECLARE_QUEUE_P (stop_reply_p);
5997DEFINE_QUEUE_P (stop_reply_p);
5998/* The list of already fetched and acknowledged stop events. This
5999 queue is used for notification Stop, and other notifications
6000 don't need queue for their events, because the notification events
6001 of Stop can't be consumed immediately, so that events should be
6002 queued first, and be consumed by remote_wait_{ns,as} one per
6003 time. Other notifications can consume their events immediately,
6004 so queue is not needed for them. */
6005static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
6006
6007static void
6008stop_reply_xfree (struct stop_reply *r)
6009{
f48ff2a7 6010 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6011}
6012
221e1a37
PA
6013/* Return the length of the stop reply queue. */
6014
6015static int
6016stop_reply_queue_length (void)
6017{
6018 return QUEUE_length (stop_reply_p, stop_reply_queue);
6019}
6020
722247f1
YQ
6021static void
6022remote_notif_stop_parse (struct notif_client *self, char *buf,
6023 struct notif_event *event)
6024{
6025 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6026}
6027
6028static void
6029remote_notif_stop_ack (struct notif_client *self, char *buf,
6030 struct notif_event *event)
6031{
6032 struct stop_reply *stop_reply = (struct stop_reply *) event;
6033
6034 /* acknowledge */
6035 putpkt ((char *) self->ack_command);
6036
6037 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6038 /* We got an unknown stop reply. */
6039 error (_("Unknown stop reply"));
6040
6041 push_stop_reply (stop_reply);
6042}
6043
6044static int
6045remote_notif_stop_can_get_pending_events (struct notif_client *self)
6046{
6047 /* We can't get pending events in remote_notif_process for
6048 notification stop, and we have to do this in remote_wait_ns
6049 instead. If we fetch all queued events from stub, remote stub
6050 may exit and we have no chance to process them back in
6051 remote_wait_ns. */
6052 mark_async_event_handler (remote_async_inferior_event_token);
6053 return 0;
6054}
6055
6056static void
6057stop_reply_dtr (struct notif_event *event)
6058{
6059 struct stop_reply *r = (struct stop_reply *) event;
6060
6061 VEC_free (cached_reg_t, r->regcache);
6062}
6063
6064static struct notif_event *
6065remote_notif_stop_alloc_reply (void)
6066{
8d749320
SM
6067 /* We cast to a pointer to the "base class". */
6068 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6069
6070 r->dtr = stop_reply_dtr;
6071
6072 return r;
6073}
6074
6075/* A client of notification Stop. */
6076
6077struct notif_client notif_client_stop =
6078{
6079 "Stop",
6080 "vStopped",
6081 remote_notif_stop_parse,
6082 remote_notif_stop_ack,
6083 remote_notif_stop_can_get_pending_events,
6084 remote_notif_stop_alloc_reply,
f48ff2a7 6085 REMOTE_NOTIF_STOP,
722247f1
YQ
6086};
6087
6088/* A parameter to pass data in and out. */
6089
6090struct queue_iter_param
6091{
6092 void *input;
6093 struct stop_reply *output;
6094};
6095
cbb8991c
DB
6096/* Determine if THREAD is a pending fork parent thread. ARG contains
6097 the pid of the process that owns the threads we want to check, or
6098 -1 if we want to check all threads. */
6099
6100static int
6101is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6102 ptid_t thread_ptid)
6103{
6104 if (ws->kind == TARGET_WAITKIND_FORKED
6105 || ws->kind == TARGET_WAITKIND_VFORKED)
6106 {
6107 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6108 return 1;
6109 }
6110
6111 return 0;
6112}
6113
6114/* Check whether EVENT is a fork event, and if it is, remove the
6115 fork child from the context list passed in DATA. */
6116
6117static int
6118remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6119 QUEUE_ITER (stop_reply_p) *iter,
6120 stop_reply_p event,
6121 void *data)
6122{
19ba03f4
SM
6123 struct queue_iter_param *param = (struct queue_iter_param *) data;
6124 struct threads_listing_context *context
6125 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6126
6127 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6128 || event->ws.kind == TARGET_WAITKIND_VFORKED
6129 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6130 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6131
6132 return 1;
6133}
6134
6135/* If CONTEXT contains any fork child threads that have not been
6136 reported yet, remove them from the CONTEXT list. If such a
6137 thread exists it is because we are stopped at a fork catchpoint
6138 and have not yet called follow_fork, which will set up the
6139 host-side data structures for the new process. */
6140
6141static void
6142remove_new_fork_children (struct threads_listing_context *context)
6143{
6144 struct thread_info * thread;
6145 int pid = -1;
6146 struct notif_client *notif = &notif_client_stop;
6147 struct queue_iter_param param;
6148
6149 /* For any threads stopped at a fork event, remove the corresponding
6150 fork child threads from the CONTEXT list. */
6151 ALL_NON_EXITED_THREADS (thread)
6152 {
4041ed77
DB
6153 struct target_waitstatus *ws;
6154
6155 if (thread->suspend.waitstatus_pending_p)
6156 ws = &thread->suspend.waitstatus;
6157 else
6158 ws = &thread->pending_follow;
cbb8991c
DB
6159
6160 if (is_pending_fork_parent (ws, pid, thread->ptid))
6161 {
6162 threads_listing_context_remove (ws, context);
6163 }
6164 }
6165
6166 /* Check for any pending fork events (not reported or processed yet)
6167 in process PID and remove those fork child threads from the
6168 CONTEXT list as well. */
6169 remote_notif_get_pending_events (notif);
6170 param.input = context;
6171 param.output = NULL;
6172 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6173 remove_child_of_pending_fork, &param);
6174}
6175
f48ff2a7
YQ
6176/* Remove stop replies in the queue if its pid is equal to the given
6177 inferior's pid. */
722247f1
YQ
6178
6179static int
f48ff2a7
YQ
6180remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6181 QUEUE_ITER (stop_reply_p) *iter,
6182 stop_reply_p event,
6183 void *data)
722247f1 6184{
19ba03f4
SM
6185 struct queue_iter_param *param = (struct queue_iter_param *) data;
6186 struct inferior *inf = (struct inferior *) param->input;
722247f1 6187
f48ff2a7 6188 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6189 {
6190 stop_reply_xfree (event);
6191 QUEUE_remove_elem (stop_reply_p, q, iter);
6192 }
6193
6194 return 1;
6195}
6196
f48ff2a7 6197/* Discard all pending stop replies of inferior INF. */
c906108c 6198
74531fed 6199static void
5f4cf0bb 6200discard_pending_stop_replies (struct inferior *inf)
c906108c 6201{
722247f1 6202 struct queue_iter_param param;
f48ff2a7
YQ
6203 struct stop_reply *reply;
6204 struct remote_state *rs = get_remote_state ();
6205 struct remote_notif_state *rns = rs->notif_state;
6206
6207 /* This function can be notified when an inferior exists. When the
6208 target is not remote, the notification state is NULL. */
6209 if (rs->remote_desc == NULL)
6210 return;
6211
6212 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6213
74531fed 6214 /* Discard the in-flight notification. */
f48ff2a7 6215 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6216 {
722247f1 6217 stop_reply_xfree (reply);
f48ff2a7 6218 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6219 }
c906108c 6220
722247f1
YQ
6221 param.input = inf;
6222 param.output = NULL;
74531fed
PA
6223 /* Discard the stop replies we have already pulled with
6224 vStopped. */
722247f1 6225 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6226 remove_stop_reply_for_inferior, &param);
6227}
6228
bcc75809
YQ
6229/* If its remote state is equal to the given remote state,
6230 remove EVENT from the stop reply queue. */
6231
6232static int
6233remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6234 QUEUE_ITER (stop_reply_p) *iter,
6235 stop_reply_p event,
6236 void *data)
6237{
19ba03f4
SM
6238 struct queue_iter_param *param = (struct queue_iter_param *) data;
6239 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6240
6241 if (event->rs == rs)
6242 {
6243 stop_reply_xfree (event);
6244 QUEUE_remove_elem (stop_reply_p, q, iter);
6245 }
6246
6247 return 1;
6248}
6249
6250/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6251
6252static void
bcc75809 6253discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6254{
6255 struct queue_iter_param param;
6256
bcc75809 6257 param.input = rs;
f48ff2a7
YQ
6258 param.output = NULL;
6259 /* Discard the stop replies we have already pulled with
6260 vStopped. */
6261 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6262 remove_stop_reply_of_remote_state, &param);
722247f1 6263}
74531fed 6264
722247f1
YQ
6265/* A parameter to pass data in and out. */
6266
6267static int
6268remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6269 QUEUE_ITER (stop_reply_p) *iter,
6270 stop_reply_p event,
6271 void *data)
6272{
19ba03f4
SM
6273 struct queue_iter_param *param = (struct queue_iter_param *) data;
6274 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6275
6276 if (ptid_match (event->ptid, *ptid))
6277 {
6278 param->output = event;
6279 QUEUE_remove_elem (stop_reply_p, q, iter);
6280 return 0;
c8e38a49 6281 }
722247f1
YQ
6282
6283 return 1;
74531fed 6284}
43ff13b4 6285
722247f1
YQ
6286/* Remove the first reply in 'stop_reply_queue' which matches
6287 PTID. */
2e9f7625 6288
722247f1
YQ
6289static struct stop_reply *
6290remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6291{
722247f1
YQ
6292 struct queue_iter_param param;
6293
6294 param.input = &ptid;
6295 param.output = NULL;
6296
6297 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6298 remote_notif_remove_once_on_match, &param);
6299 if (notif_debug)
6300 fprintf_unfiltered (gdb_stdlog,
6301 "notif: discard queued event: 'Stop' in %s\n",
6302 target_pid_to_str (ptid));
a744cf53 6303
722247f1 6304 return param.output;
74531fed 6305}
75c99385 6306
74531fed
PA
6307/* Look for a queued stop reply belonging to PTID. If one is found,
6308 remove it from the queue, and return it. Returns NULL if none is
6309 found. If there are still queued events left to process, tell the
6310 event loop to get back to target_wait soon. */
e24a49d8 6311
74531fed
PA
6312static struct stop_reply *
6313queued_stop_reply (ptid_t ptid)
6314{
722247f1 6315 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6316
722247f1 6317 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6318 /* There's still at least an event left. */
6319 mark_async_event_handler (remote_async_inferior_event_token);
6320
722247f1 6321 return r;
74531fed
PA
6322}
6323
6324/* Push a fully parsed stop reply in the stop reply queue. Since we
6325 know that we now have at least one queued event left to pass to the
6326 core side, tell the event loop to get back to target_wait soon. */
6327
6328static void
6329push_stop_reply (struct stop_reply *new_event)
6330{
722247f1 6331 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6332
722247f1
YQ
6333 if (notif_debug)
6334 fprintf_unfiltered (gdb_stdlog,
6335 "notif: push 'Stop' %s to queue %d\n",
6336 target_pid_to_str (new_event->ptid),
6337 QUEUE_length (stop_reply_p,
6338 stop_reply_queue));
74531fed
PA
6339
6340 mark_async_event_handler (remote_async_inferior_event_token);
6341}
6342
722247f1
YQ
6343static int
6344stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6345 QUEUE_ITER (stop_reply_p) *iter,
6346 struct stop_reply *event,
6347 void *data)
6348{
19ba03f4 6349 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6350
6351 return !(ptid_equal (*ptid, event->ptid)
6352 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6353}
6354
74531fed
PA
6355/* Returns true if we have a stop reply for PTID. */
6356
6357static int
6358peek_stop_reply (ptid_t ptid)
6359{
722247f1
YQ
6360 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6361 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6362}
6363
26d56a93
SL
6364/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6365 starting with P and ending with PEND matches PREFIX. */
6366
6367static int
6368strprefix (const char *p, const char *pend, const char *prefix)
6369{
6370 for ( ; p < pend; p++, prefix++)
6371 if (*p != *prefix)
6372 return 0;
6373 return *prefix == '\0';
6374}
6375
74531fed
PA
6376/* Parse the stop reply in BUF. Either the function succeeds, and the
6377 result is stored in EVENT, or throws an error. */
6378
6379static void
6380remote_parse_stop_reply (char *buf, struct stop_reply *event)
6381{
6382 struct remote_arch_state *rsa = get_remote_arch_state ();
6383 ULONGEST addr;
6384 char *p;
94585166 6385 int skipregs = 0;
74531fed
PA
6386
6387 event->ptid = null_ptid;
bcc75809 6388 event->rs = get_remote_state ();
74531fed
PA
6389 event->ws.kind = TARGET_WAITKIND_IGNORE;
6390 event->ws.value.integer = 0;
f7e6eed5 6391 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6392 event->regcache = NULL;
dc146f7c 6393 event->core = -1;
74531fed
PA
6394
6395 switch (buf[0])
6396 {
6397 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6398 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6399 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6400 ss = signal number
6401 n... = register number
6402 r... = register contents
6403 */
6404
6405 p = &buf[3]; /* after Txx */
6406 while (*p)
6407 {
6408 char *p1;
cea39f65 6409 int fieldsize;
43ff13b4 6410
1f10ba14
PA
6411 p1 = strchr (p, ':');
6412 if (p1 == NULL)
6413 error (_("Malformed packet(a) (missing colon): %s\n\
6414Packet: '%s'\n"),
6415 p, buf);
6416 if (p == p1)
6417 error (_("Malformed packet(a) (missing register number): %s\n\
6418Packet: '%s'\n"),
6419 p, buf);
3c3bea1c 6420
1f10ba14
PA
6421 /* Some "registers" are actually extended stop information.
6422 Note if you're adding a new entry here: GDB 7.9 and
6423 earlier assume that all register "numbers" that start
6424 with an hex digit are real register numbers. Make sure
6425 the server only sends such a packet if it knows the
6426 client understands it. */
c8e38a49 6427
26d56a93 6428 if (strprefix (p, p1, "thread"))
1f10ba14 6429 event->ptid = read_ptid (++p1, &p);
82075af2
JS
6430 else if (strprefix (p, p1, "syscall_entry"))
6431 {
6432 ULONGEST sysno;
6433
6434 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6435 p = unpack_varlen_hex (++p1, &sysno);
6436 event->ws.value.syscall_number = (int) sysno;
6437 }
6438 else if (strprefix (p, p1, "syscall_return"))
6439 {
6440 ULONGEST sysno;
6441
6442 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6443 p = unpack_varlen_hex (++p1, &sysno);
6444 event->ws.value.syscall_number = (int) sysno;
6445 }
26d56a93
SL
6446 else if (strprefix (p, p1, "watch")
6447 || strprefix (p, p1, "rwatch")
6448 || strprefix (p, p1, "awatch"))
cea39f65 6449 {
f7e6eed5 6450 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6451 p = unpack_varlen_hex (++p1, &addr);
6452 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6453 }
26d56a93 6454 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6455 {
6456 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6457
6458 /* Make sure the stub doesn't forget to indicate support
6459 with qSupported. */
6460 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6461 error (_("Unexpected swbreak stop reason"));
6462
6463 /* The value part is documented as "must be empty",
6464 though we ignore it, in case we ever decide to make
6465 use of it in a backward compatible way. */
8424cc97 6466 p = strchrnul (p1 + 1, ';');
f7e6eed5 6467 }
26d56a93 6468 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6469 {
6470 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6471
6472 /* Make sure the stub doesn't forget to indicate support
6473 with qSupported. */
6474 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6475 error (_("Unexpected hwbreak stop reason"));
6476
6477 /* See above. */
8424cc97 6478 p = strchrnul (p1 + 1, ';');
f7e6eed5 6479 }
26d56a93 6480 else if (strprefix (p, p1, "library"))
cea39f65 6481 {
1f10ba14 6482 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 6483 p = strchrnul (p1 + 1, ';');
1f10ba14 6484 }
26d56a93 6485 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6486 {
6487 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6488 /* p1 will indicate "begin" or "end", but it makes
6489 no difference for now, so ignore it. */
8424cc97 6490 p = strchrnul (p1 + 1, ';');
1f10ba14 6491 }
26d56a93 6492 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6493 {
6494 ULONGEST c;
a744cf53 6495
1f10ba14
PA
6496 p = unpack_varlen_hex (++p1, &c);
6497 event->core = c;
cea39f65 6498 }
26d56a93 6499 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6500 {
6501 event->ws.value.related_pid = read_ptid (++p1, &p);
6502 event->ws.kind = TARGET_WAITKIND_FORKED;
6503 }
26d56a93 6504 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6505 {
6506 event->ws.value.related_pid = read_ptid (++p1, &p);
6507 event->ws.kind = TARGET_WAITKIND_VFORKED;
6508 }
26d56a93 6509 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6510 {
6511 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 6512 p = strchrnul (p1 + 1, ';');
c269dbdb 6513 }
6ab24463 6514 else if (strprefix (p, p1, "exec"))
94585166
DB
6515 {
6516 ULONGEST ignored;
6517 char pathname[PATH_MAX];
6518 int pathlen;
6519
6520 /* Determine the length of the execd pathname. */
6521 p = unpack_varlen_hex (++p1, &ignored);
6522 pathlen = (p - p1) / 2;
6523
6524 /* Save the pathname for event reporting and for
6525 the next run command. */
6526 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6527 pathname[pathlen] = '\0';
6528
6529 /* This is freed during event handling. */
6530 event->ws.value.execd_pathname = xstrdup (pathname);
6531 event->ws.kind = TARGET_WAITKIND_EXECD;
6532
6533 /* Skip the registers included in this packet, since
6534 they may be for an architecture different from the
6535 one used by the original program. */
6536 skipregs = 1;
6537 }
65706a29
PA
6538 else if (strprefix (p, p1, "create"))
6539 {
6540 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 6541 p = strchrnul (p1 + 1, ';');
65706a29 6542 }
cea39f65
MS
6543 else
6544 {
1f10ba14
PA
6545 ULONGEST pnum;
6546 char *p_temp;
6547
94585166
DB
6548 if (skipregs)
6549 {
8424cc97 6550 p = strchrnul (p1 + 1, ';');
94585166
DB
6551 p++;
6552 continue;
6553 }
6554
1f10ba14
PA
6555 /* Maybe a real ``P'' register number. */
6556 p_temp = unpack_varlen_hex (p, &pnum);
6557 /* If the first invalid character is the colon, we got a
6558 register number. Otherwise, it's an unknown stop
6559 reason. */
6560 if (p_temp == p1)
6561 {
6562 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6563 cached_reg_t cached_reg;
43ff13b4 6564
1f10ba14
PA
6565 if (reg == NULL)
6566 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6567Packet: '%s'\n"),
1f10ba14 6568 hex_string (pnum), p, buf);
c8e38a49 6569
1f10ba14 6570 cached_reg.num = reg->regnum;
4100683b 6571
1f10ba14
PA
6572 p = p1 + 1;
6573 fieldsize = hex2bin (p, cached_reg.data,
6574 register_size (target_gdbarch (),
6575 reg->regnum));
6576 p += 2 * fieldsize;
6577 if (fieldsize < register_size (target_gdbarch (),
6578 reg->regnum))
6579 warning (_("Remote reply is too short: %s"), buf);
74531fed 6580
1f10ba14
PA
6581 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6582 }
6583 else
6584 {
6585 /* Not a number. Silently skip unknown optional
6586 info. */
8424cc97 6587 p = strchrnul (p1 + 1, ';');
1f10ba14 6588 }
cea39f65 6589 }
c8e38a49 6590
cea39f65
MS
6591 if (*p != ';')
6592 error (_("Remote register badly formatted: %s\nhere: %s"),
6593 buf, p);
6594 ++p;
6595 }
5b5596ff
PA
6596
6597 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6598 break;
6599
c8e38a49
PA
6600 /* fall through */
6601 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6602 {
6603 int sig;
6604
6605 event->ws.kind = TARGET_WAITKIND_STOPPED;
6606 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6607 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6608 event->ws.value.sig = (enum gdb_signal) sig;
6609 else
6610 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6611 }
c8e38a49 6612 break;
65706a29
PA
6613 case 'w': /* Thread exited. */
6614 {
6615 char *p;
6616 ULONGEST value;
6617
6618 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6619 p = unpack_varlen_hex (&buf[1], &value);
6620 event->ws.value.integer = value;
6621 if (*p != ';')
6622 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 6623 event->ptid = read_ptid (++p, NULL);
65706a29
PA
6624 break;
6625 }
c8e38a49
PA
6626 case 'W': /* Target exited. */
6627 case 'X':
6628 {
6629 char *p;
6630 int pid;
6631 ULONGEST value;
82f73884 6632
c8e38a49
PA
6633 /* GDB used to accept only 2 hex chars here. Stubs should
6634 only send more if they detect GDB supports multi-process
6635 support. */
6636 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6637
c8e38a49
PA
6638 if (buf[0] == 'W')
6639 {
6640 /* The remote process exited. */
74531fed
PA
6641 event->ws.kind = TARGET_WAITKIND_EXITED;
6642 event->ws.value.integer = value;
c8e38a49
PA
6643 }
6644 else
6645 {
6646 /* The remote process exited with a signal. */
74531fed 6647 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6648 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6649 event->ws.value.sig = (enum gdb_signal) value;
6650 else
6651 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6652 }
82f73884 6653
c8e38a49
PA
6654 /* If no process is specified, assume inferior_ptid. */
6655 pid = ptid_get_pid (inferior_ptid);
6656 if (*p == '\0')
6657 ;
6658 else if (*p == ';')
6659 {
6660 p++;
6661
0b24eb2d 6662 if (*p == '\0')
82f73884 6663 ;
61012eef 6664 else if (startswith (p, "process:"))
82f73884 6665 {
c8e38a49 6666 ULONGEST upid;
a744cf53 6667
c8e38a49
PA
6668 p += sizeof ("process:") - 1;
6669 unpack_varlen_hex (p, &upid);
6670 pid = upid;
82f73884
PA
6671 }
6672 else
6673 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6674 }
c8e38a49
PA
6675 else
6676 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6677 event->ptid = pid_to_ptid (pid);
6678 }
6679 break;
f2faf941
PA
6680 case 'N':
6681 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6682 event->ptid = minus_one_ptid;
6683 break;
74531fed
PA
6684 }
6685
6efcd9a8 6686 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
6687 error (_("No process or thread specified in stop reply: %s"), buf);
6688}
6689
722247f1
YQ
6690/* When the stub wants to tell GDB about a new notification reply, it
6691 sends a notification (%Stop, for example). Those can come it at
6692 any time, hence, we have to make sure that any pending
6693 putpkt/getpkt sequence we're making is finished, before querying
6694 the stub for more events with the corresponding ack command
6695 (vStopped, for example). E.g., if we started a vStopped sequence
6696 immediately upon receiving the notification, something like this
6697 could happen:
74531fed
PA
6698
6699 1.1) --> Hg 1
6700 1.2) <-- OK
6701 1.3) --> g
6702 1.4) <-- %Stop
6703 1.5) --> vStopped
6704 1.6) <-- (registers reply to step #1.3)
6705
6706 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6707 query.
6708
796cb314 6709 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6710 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6711 doing whatever we were doing:
6712
6713 2.1) --> Hg 1
6714 2.2) <-- OK
6715 2.3) --> g
6716 2.4) <-- %Stop
6717 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6718 2.5) <-- (registers reply to step #2.3)
6719
6720 Eventualy after step #2.5, we return to the event loop, which
6721 notices there's an event on the
6722 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6723 associated callback --- the function below. At this point, we're
6724 always safe to start a vStopped sequence. :
6725
6726 2.6) --> vStopped
6727 2.7) <-- T05 thread:2
6728 2.8) --> vStopped
6729 2.9) --> OK
6730*/
6731
722247f1
YQ
6732void
6733remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6734{
6735 struct remote_state *rs = get_remote_state ();
74531fed 6736
f48ff2a7 6737 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6738 {
722247f1
YQ
6739 if (notif_debug)
6740 fprintf_unfiltered (gdb_stdlog,
6741 "notif: process: '%s' ack pending event\n",
6742 nc->name);
74531fed 6743
722247f1 6744 /* acknowledge */
f48ff2a7
YQ
6745 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6746 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6747
6748 while (1)
6749 {
6750 getpkt (&rs->buf, &rs->buf_size, 0);
6751 if (strcmp (rs->buf, "OK") == 0)
6752 break;
6753 else
722247f1 6754 remote_notif_ack (nc, rs->buf);
74531fed
PA
6755 }
6756 }
722247f1
YQ
6757 else
6758 {
6759 if (notif_debug)
6760 fprintf_unfiltered (gdb_stdlog,
6761 "notif: process: '%s' no pending reply\n",
6762 nc->name);
6763 }
74531fed
PA
6764}
6765
74531fed
PA
6766/* Called when it is decided that STOP_REPLY holds the info of the
6767 event that is to be returned to the core. This function always
6768 destroys STOP_REPLY. */
6769
6770static ptid_t
6771process_stop_reply (struct stop_reply *stop_reply,
6772 struct target_waitstatus *status)
6773{
6774 ptid_t ptid;
6775
6776 *status = stop_reply->ws;
6777 ptid = stop_reply->ptid;
6778
6779 /* If no thread/process was reported by the stub, assume the current
6780 inferior. */
6781 if (ptid_equal (ptid, null_ptid))
6782 ptid = inferior_ptid;
6783
5f3563ea 6784 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
6785 && status->kind != TARGET_WAITKIND_SIGNALLED
6786 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 6787 {
799a2abe 6788 struct private_thread_info *remote_thr;
ee154bee 6789
5f3563ea
PA
6790 /* Expedited registers. */
6791 if (stop_reply->regcache)
6792 {
217f1f79 6793 struct regcache *regcache
f5656ead 6794 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6795 cached_reg_t *reg;
6796 int ix;
6797
6798 for (ix = 0;
6799 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6800 ix++)
217f1f79 6801 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6802 VEC_free (cached_reg_t, stop_reply->regcache);
6803 }
74531fed 6804
1941c569 6805 remote_notice_new_inferior (ptid, 0);
799a2abe
PA
6806 remote_thr = demand_private_info (ptid);
6807 remote_thr->core = stop_reply->core;
6808 remote_thr->stop_reason = stop_reply->stop_reason;
6809 remote_thr->watch_data_address = stop_reply->watch_data_address;
74531fed
PA
6810 }
6811
74531fed
PA
6812 stop_reply_xfree (stop_reply);
6813 return ptid;
6814}
6815
6816/* The non-stop mode version of target_wait. */
6817
6818static ptid_t
47608cb1 6819remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6820{
6821 struct remote_state *rs = get_remote_state ();
74531fed
PA
6822 struct stop_reply *stop_reply;
6823 int ret;
fee9eda9 6824 int is_notif = 0;
74531fed
PA
6825
6826 /* If in non-stop mode, get out of getpkt even if a
6827 notification is received. */
6828
6829 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6830 0 /* forever */, &is_notif);
74531fed
PA
6831 while (1)
6832 {
fee9eda9 6833 if (ret != -1 && !is_notif)
74531fed
PA
6834 switch (rs->buf[0])
6835 {
6836 case 'E': /* Error of some sort. */
6837 /* We're out of sync with the target now. Did it continue
6838 or not? We can't tell which thread it was in non-stop,
6839 so just ignore this. */
6840 warning (_("Remote failure reply: %s"), rs->buf);
6841 break;
6842 case 'O': /* Console output. */
6843 remote_console_output (rs->buf + 1);
6844 break;
6845 default:
6846 warning (_("Invalid remote reply: %s"), rs->buf);
6847 break;
6848 }
6849
6850 /* Acknowledge a pending stop reply that may have arrived in the
6851 mean time. */
f48ff2a7 6852 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6853 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6854
6855 /* If indeed we noticed a stop reply, we're done. */
6856 stop_reply = queued_stop_reply (ptid);
6857 if (stop_reply != NULL)
6858 return process_stop_reply (stop_reply, status);
6859
47608cb1 6860 /* Still no event. If we're just polling for an event, then
74531fed 6861 return to the event loop. */
47608cb1 6862 if (options & TARGET_WNOHANG)
74531fed
PA
6863 {
6864 status->kind = TARGET_WAITKIND_IGNORE;
6865 return minus_one_ptid;
6866 }
6867
47608cb1 6868 /* Otherwise do a blocking wait. */
74531fed 6869 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6870 1 /* forever */, &is_notif);
74531fed
PA
6871 }
6872}
6873
6874/* Wait until the remote machine stops, then return, storing status in
6875 STATUS just as `wait' would. */
6876
6877static ptid_t
47608cb1 6878remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6879{
6880 struct remote_state *rs = get_remote_state ();
74531fed 6881 ptid_t event_ptid = null_ptid;
cea39f65 6882 char *buf;
74531fed
PA
6883 struct stop_reply *stop_reply;
6884
47608cb1
PA
6885 again:
6886
74531fed
PA
6887 status->kind = TARGET_WAITKIND_IGNORE;
6888 status->value.integer = 0;
6889
6890 stop_reply = queued_stop_reply (ptid);
6891 if (stop_reply != NULL)
6892 return process_stop_reply (stop_reply, status);
6893
6894 if (rs->cached_wait_status)
6895 /* Use the cached wait status, but only once. */
6896 rs->cached_wait_status = 0;
6897 else
6898 {
6899 int ret;
722247f1 6900 int is_notif;
567420d1
PA
6901 int forever = ((options & TARGET_WNOHANG) == 0
6902 && wait_forever_enabled_p);
6903
6904 if (!rs->waiting_for_stop_reply)
6905 {
6906 status->kind = TARGET_WAITKIND_NO_RESUMED;
6907 return minus_one_ptid;
6908 }
74531fed 6909
74531fed
PA
6910 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6911 _never_ wait for ever -> test on target_is_async_p().
6912 However, before we do that we need to ensure that the caller
6913 knows how to take the target into/out of async mode. */
722247f1 6914 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6915 forever, &is_notif);
722247f1
YQ
6916
6917 /* GDB gets a notification. Return to core as this event is
6918 not interesting. */
6919 if (ret != -1 && is_notif)
6920 return minus_one_ptid;
567420d1
PA
6921
6922 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6923 return minus_one_ptid;
74531fed
PA
6924 }
6925
6926 buf = rs->buf;
6927
3a29589a
DJ
6928 /* Assume that the target has acknowledged Ctrl-C unless we receive
6929 an 'F' or 'O' packet. */
6930 if (buf[0] != 'F' && buf[0] != 'O')
6931 rs->ctrlc_pending_p = 0;
6932
74531fed
PA
6933 switch (buf[0])
6934 {
6935 case 'E': /* Error of some sort. */
6936 /* We're out of sync with the target now. Did it continue or
6937 not? Not is more likely, so report a stop. */
29090fb6
LM
6938 rs->waiting_for_stop_reply = 0;
6939
74531fed
PA
6940 warning (_("Remote failure reply: %s"), buf);
6941 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6942 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6943 break;
6944 case 'F': /* File-I/O request. */
e42e5352
YQ
6945 /* GDB may access the inferior memory while handling the File-I/O
6946 request, but we don't want GDB accessing memory while waiting
6947 for a stop reply. See the comments in putpkt_binary. Set
6948 waiting_for_stop_reply to 0 temporarily. */
6949 rs->waiting_for_stop_reply = 0;
3a29589a
DJ
6950 remote_fileio_request (buf, rs->ctrlc_pending_p);
6951 rs->ctrlc_pending_p = 0;
e42e5352
YQ
6952 /* GDB handled the File-I/O request, and the target is running
6953 again. Keep waiting for events. */
6954 rs->waiting_for_stop_reply = 1;
74531fed 6955 break;
f2faf941 6956 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 6957 {
29090fb6
LM
6958 struct stop_reply *stop_reply;
6959
6960 /* There is a stop reply to handle. */
6961 rs->waiting_for_stop_reply = 0;
6962
6963 stop_reply
722247f1
YQ
6964 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6965 rs->buf);
74531fed 6966
74531fed 6967 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6968 break;
6969 }
6970 case 'O': /* Console output. */
6971 remote_console_output (buf + 1);
c8e38a49
PA
6972 break;
6973 case '\0':
b73be471 6974 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6975 {
6976 /* Zero length reply means that we tried 'S' or 'C' and the
6977 remote system doesn't support it. */
6978 target_terminal_ours_for_output ();
6979 printf_filtered
6980 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6981 gdb_signal_to_name (rs->last_sent_signal));
6982 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6983 target_terminal_inferior ();
6984
280ceea3 6985 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49 6986 putpkt ((char *) buf);
c8e38a49 6987 break;
43ff13b4 6988 }
c8e38a49
PA
6989 /* else fallthrough */
6990 default:
6991 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 6992 break;
43ff13b4 6993 }
c8e38a49 6994
f2faf941
PA
6995 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
6996 return minus_one_ptid;
6997 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6998 {
6999 /* Nothing interesting happened. If we're doing a non-blocking
7000 poll, we're done. Otherwise, go back to waiting. */
7001 if (options & TARGET_WNOHANG)
7002 return minus_one_ptid;
7003 else
7004 goto again;
7005 }
74531fed
PA
7006 else if (status->kind != TARGET_WAITKIND_EXITED
7007 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7008 {
7009 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7010 record_currthread (rs, event_ptid);
82f73884
PA
7011 else
7012 event_ptid = inferior_ptid;
43ff13b4 7013 }
74531fed
PA
7014 else
7015 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7016 record_currthread (rs, minus_one_ptid);
79d7f229 7017
82f73884 7018 return event_ptid;
43ff13b4
JM
7019}
7020
74531fed
PA
7021/* Wait until the remote machine stops, then return, storing status in
7022 STATUS just as `wait' would. */
7023
c8e38a49 7024static ptid_t
117de6a9 7025remote_wait (struct target_ops *ops,
47608cb1 7026 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7027{
7028 ptid_t event_ptid;
7029
6efcd9a8 7030 if (target_is_non_stop_p ())
47608cb1 7031 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7032 else
47608cb1 7033 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7034
d9d41e78 7035 if (target_is_async_p ())
c8e38a49 7036 {
74531fed
PA
7037 /* If there are are events left in the queue tell the event loop
7038 to return here. */
722247f1 7039 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7040 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7041 }
c8e38a49
PA
7042
7043 return event_ptid;
7044}
7045
74ca34ce 7046/* Fetch a single register using a 'p' packet. */
c906108c 7047
b96ec7ac 7048static int
56be3814 7049fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
7050{
7051 struct remote_state *rs = get_remote_state ();
2e9f7625 7052 char *buf, *p;
b96ec7ac
AC
7053 char regp[MAX_REGISTER_SIZE];
7054 int i;
7055
4082afcc 7056 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7057 return 0;
7058
7059 if (reg->pnum == -1)
7060 return 0;
7061
2e9f7625 7062 p = rs->buf;
fcad0fa4 7063 *p++ = 'p';
74ca34ce 7064 p += hexnumstr (p, reg->pnum);
fcad0fa4 7065 *p++ = '\0';
1f4437a4
MS
7066 putpkt (rs->buf);
7067 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7068
2e9f7625
DJ
7069 buf = rs->buf;
7070
74ca34ce
DJ
7071 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7072 {
7073 case PACKET_OK:
7074 break;
7075 case PACKET_UNKNOWN:
7076 return 0;
7077 case PACKET_ERROR:
27a9c0bf
MS
7078 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7079 gdbarch_register_name (get_regcache_arch (regcache),
7080 reg->regnum),
7081 buf);
74ca34ce 7082 }
3f9a994c
JB
7083
7084 /* If this register is unfetchable, tell the regcache. */
7085 if (buf[0] == 'x')
8480adf2 7086 {
56be3814 7087 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7088 return 1;
b96ec7ac 7089 }
b96ec7ac 7090
3f9a994c
JB
7091 /* Otherwise, parse and supply the value. */
7092 p = buf;
7093 i = 0;
7094 while (p[0] != 0)
7095 {
7096 if (p[1] == 0)
74ca34ce 7097 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7098
7099 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7100 p += 2;
7101 }
56be3814 7102 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7103 return 1;
b96ec7ac
AC
7104}
7105
74ca34ce
DJ
7106/* Fetch the registers included in the target's 'g' packet. */
7107
29709017
DJ
7108static int
7109send_g_packet (void)
c906108c 7110{
d01949b6 7111 struct remote_state *rs = get_remote_state ();
cea39f65 7112 int buf_len;
c906108c 7113
bba74b36 7114 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7115 remote_send (&rs->buf, &rs->buf_size);
c906108c 7116
29709017
DJ
7117 /* We can get out of synch in various cases. If the first character
7118 in the buffer is not a hex character, assume that has happened
7119 and try to fetch another packet to read. */
7120 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7121 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7122 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7123 && rs->buf[0] != 'x') /* New: unavailable register value. */
7124 {
7125 if (remote_debug)
7126 fprintf_unfiltered (gdb_stdlog,
7127 "Bad register packet; fetching a new packet\n");
7128 getpkt (&rs->buf, &rs->buf_size, 0);
7129 }
7130
74ca34ce
DJ
7131 buf_len = strlen (rs->buf);
7132
7133 /* Sanity check the received packet. */
7134 if (buf_len % 2 != 0)
7135 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7136
7137 return buf_len / 2;
7138}
7139
7140static void
56be3814 7141process_g_packet (struct regcache *regcache)
29709017 7142{
4a22f64d 7143 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7144 struct remote_state *rs = get_remote_state ();
7145 struct remote_arch_state *rsa = get_remote_arch_state ();
7146 int i, buf_len;
7147 char *p;
7148 char *regs;
7149
7150 buf_len = strlen (rs->buf);
7151
7152 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7153 if (buf_len > 2 * rsa->sizeof_g_packet)
7154 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7155
7156 /* Save the size of the packet sent to us by the target. It is used
7157 as a heuristic when determining the max size of packets that the
7158 target can safely receive. */
7159 if (rsa->actual_register_packet_size == 0)
7160 rsa->actual_register_packet_size = buf_len;
7161
7162 /* If this is smaller than we guessed the 'g' packet would be,
7163 update our records. A 'g' reply that doesn't include a register's
7164 value implies either that the register is not available, or that
7165 the 'p' packet must be used. */
7166 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7167 {
74ca34ce
DJ
7168 rsa->sizeof_g_packet = buf_len / 2;
7169
4a22f64d 7170 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7171 {
74ca34ce
DJ
7172 if (rsa->regs[i].pnum == -1)
7173 continue;
7174
7175 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7176 rsa->regs[i].in_g_packet = 0;
b96ec7ac 7177 else
74ca34ce 7178 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7179 }
74ca34ce 7180 }
b323314b 7181
224c3ddb 7182 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7183
7184 /* Unimplemented registers read as all bits zero. */
ea9c271d 7185 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7186
c906108c
SS
7187 /* Reply describes registers byte by byte, each byte encoded as two
7188 hex characters. Suck them all up, then supply them to the
7189 register cacheing/storage mechanism. */
7190
74ca34ce 7191 p = rs->buf;
ea9c271d 7192 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7193 {
74ca34ce
DJ
7194 if (p[0] == 0 || p[1] == 0)
7195 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7196 internal_error (__FILE__, __LINE__,
9b20d036 7197 _("unexpected end of 'g' packet reply"));
74ca34ce 7198
c906108c 7199 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7200 regs[i] = 0; /* 'x' */
c906108c
SS
7201 else
7202 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7203 p += 2;
7204 }
7205
a744cf53
MS
7206 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7207 {
7208 struct packet_reg *r = &rsa->regs[i];
7209
7210 if (r->in_g_packet)
7211 {
7212 if (r->offset * 2 >= strlen (rs->buf))
7213 /* This shouldn't happen - we adjusted in_g_packet above. */
7214 internal_error (__FILE__, __LINE__,
9b20d036 7215 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7216 else if (rs->buf[r->offset * 2] == 'x')
7217 {
7218 gdb_assert (r->offset * 2 < strlen (rs->buf));
7219 /* The register isn't available, mark it as such (at
7220 the same time setting the value to zero). */
7221 regcache_raw_supply (regcache, r->regnum, NULL);
7222 }
7223 else
7224 regcache_raw_supply (regcache, r->regnum,
7225 regs + r->offset);
7226 }
7227 }
c906108c
SS
7228}
7229
29709017 7230static void
56be3814 7231fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7232{
7233 send_g_packet ();
56be3814 7234 process_g_packet (regcache);
29709017
DJ
7235}
7236
e6e4e701
PA
7237/* Make the remote selected traceframe match GDB's selected
7238 traceframe. */
7239
7240static void
7241set_remote_traceframe (void)
7242{
7243 int newnum;
262e1174 7244 struct remote_state *rs = get_remote_state ();
e6e4e701 7245
262e1174 7246 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7247 return;
7248
7249 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7250 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7251
7252 newnum = target_trace_find (tfind_number,
7253 get_traceframe_number (), 0, 0, NULL);
7254
7255 /* Should not happen. If it does, all bets are off. */
7256 if (newnum != get_traceframe_number ())
7257 warning (_("could not set remote traceframe"));
7258}
7259
74ca34ce 7260static void
28439f5e
PA
7261remote_fetch_registers (struct target_ops *ops,
7262 struct regcache *regcache, int regnum)
74ca34ce 7263{
74ca34ce
DJ
7264 struct remote_arch_state *rsa = get_remote_arch_state ();
7265 int i;
7266
e6e4e701 7267 set_remote_traceframe ();
79d7f229 7268 set_general_thread (inferior_ptid);
74ca34ce
DJ
7269
7270 if (regnum >= 0)
7271 {
7272 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7273
74ca34ce
DJ
7274 gdb_assert (reg != NULL);
7275
7276 /* If this register might be in the 'g' packet, try that first -
7277 we are likely to read more than one register. If this is the
7278 first 'g' packet, we might be overly optimistic about its
7279 contents, so fall back to 'p'. */
7280 if (reg->in_g_packet)
7281 {
56be3814 7282 fetch_registers_using_g (regcache);
74ca34ce
DJ
7283 if (reg->in_g_packet)
7284 return;
7285 }
7286
56be3814 7287 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7288 return;
7289
7290 /* This register is not available. */
56be3814 7291 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7292
7293 return;
7294 }
7295
56be3814 7296 fetch_registers_using_g (regcache);
74ca34ce 7297
4a22f64d 7298 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7299 if (!rsa->regs[i].in_g_packet)
56be3814 7300 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7301 {
7302 /* This register is not available. */
56be3814 7303 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7304 }
7305}
7306
c906108c
SS
7307/* Prepare to store registers. Since we may send them all (using a
7308 'G' request), we have to read out the ones we don't want to change
7309 first. */
7310
c5aa993b 7311static void
f32dbf8c 7312remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7313{
ea9c271d 7314 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7315 int i;
cfd77fa1 7316 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7317
c906108c 7318 /* Make sure the entire registers array is valid. */
4082afcc 7319 switch (packet_support (PACKET_P))
5a2468f5
JM
7320 {
7321 case PACKET_DISABLE:
7322 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7323 /* Make sure all the necessary registers are cached. */
4a22f64d 7324 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7325 if (rsa->regs[i].in_g_packet)
316f2060 7326 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7327 break;
7328 case PACKET_ENABLE:
7329 break;
7330 }
7331}
7332
ad10f812 7333/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7334 packet was not recognized. */
5a2468f5
JM
7335
7336static int
1f4437a4
MS
7337store_register_using_P (const struct regcache *regcache,
7338 struct packet_reg *reg)
5a2468f5 7339{
4a22f64d 7340 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7341 struct remote_state *rs = get_remote_state ();
5a2468f5 7342 /* Try storing a single register. */
6d820c5c 7343 char *buf = rs->buf;
cfd77fa1 7344 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7345 char *p;
5a2468f5 7346
4082afcc 7347 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7348 return 0;
7349
7350 if (reg->pnum == -1)
7351 return 0;
7352
ea9c271d 7353 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7354 p = buf + strlen (buf);
56be3814 7355 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7356 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7357 putpkt (rs->buf);
7358 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7359
74ca34ce
DJ
7360 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7361 {
7362 case PACKET_OK:
7363 return 1;
7364 case PACKET_ERROR:
27a9c0bf
MS
7365 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7366 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7367 case PACKET_UNKNOWN:
7368 return 0;
7369 default:
7370 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7371 }
c906108c
SS
7372}
7373
23860348
MS
7374/* Store register REGNUM, or all registers if REGNUM == -1, from the
7375 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7376
7377static void
56be3814 7378store_registers_using_G (const struct regcache *regcache)
c906108c 7379{
d01949b6 7380 struct remote_state *rs = get_remote_state ();
ea9c271d 7381 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7382 gdb_byte *regs;
c906108c
SS
7383 char *p;
7384
193cb69f
AC
7385 /* Extract all the registers in the regcache copying them into a
7386 local buffer. */
7387 {
b323314b 7388 int i;
a744cf53 7389
224c3ddb 7390 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7391 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7392 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7393 {
ea9c271d 7394 struct packet_reg *r = &rsa->regs[i];
a744cf53 7395
b323314b 7396 if (r->in_g_packet)
56be3814 7397 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7398 }
7399 }
c906108c
SS
7400
7401 /* Command describes registers byte by byte,
7402 each byte encoded as two hex characters. */
6d820c5c 7403 p = rs->buf;
193cb69f 7404 *p++ = 'G';
74ca34ce
DJ
7405 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7406 updated. */
7407 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7408 putpkt (rs->buf);
7409 getpkt (&rs->buf, &rs->buf_size, 0);
7410 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7411 error (_("Could not write registers; remote failure reply '%s'"),
7412 rs->buf);
c906108c 7413}
74ca34ce
DJ
7414
7415/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7416 of the register cache buffer. FIXME: ignores errors. */
7417
7418static void
28439f5e
PA
7419remote_store_registers (struct target_ops *ops,
7420 struct regcache *regcache, int regnum)
74ca34ce 7421{
74ca34ce
DJ
7422 struct remote_arch_state *rsa = get_remote_arch_state ();
7423 int i;
7424
e6e4e701 7425 set_remote_traceframe ();
79d7f229 7426 set_general_thread (inferior_ptid);
74ca34ce
DJ
7427
7428 if (regnum >= 0)
7429 {
7430 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7431
74ca34ce
DJ
7432 gdb_assert (reg != NULL);
7433
7434 /* Always prefer to store registers using the 'P' packet if
7435 possible; we often change only a small number of registers.
7436 Sometimes we change a larger number; we'd need help from a
7437 higher layer to know to use 'G'. */
56be3814 7438 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7439 return;
7440
7441 /* For now, don't complain if we have no way to write the
7442 register. GDB loses track of unavailable registers too
7443 easily. Some day, this may be an error. We don't have
0df8b418 7444 any way to read the register, either... */
74ca34ce
DJ
7445 if (!reg->in_g_packet)
7446 return;
7447
56be3814 7448 store_registers_using_G (regcache);
74ca34ce
DJ
7449 return;
7450 }
7451
56be3814 7452 store_registers_using_G (regcache);
74ca34ce 7453
4a22f64d 7454 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7455 if (!rsa->regs[i].in_g_packet)
56be3814 7456 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7457 /* See above for why we do not issue an error here. */
7458 continue;
7459}
c906108c
SS
7460\f
7461
7462/* Return the number of hex digits in num. */
7463
7464static int
fba45db2 7465hexnumlen (ULONGEST num)
c906108c
SS
7466{
7467 int i;
7468
7469 for (i = 0; num != 0; i++)
7470 num >>= 4;
7471
7472 return max (i, 1);
7473}
7474
2df3850c 7475/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7476
7477static int
fba45db2 7478hexnumstr (char *buf, ULONGEST num)
c906108c 7479{
c906108c 7480 int len = hexnumlen (num);
a744cf53 7481
2df3850c
JM
7482 return hexnumnstr (buf, num, len);
7483}
7484
c906108c 7485
2df3850c 7486/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7487
2df3850c 7488static int
fba45db2 7489hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7490{
7491 int i;
7492
7493 buf[width] = '\0';
7494
7495 for (i = width - 1; i >= 0; i--)
c906108c 7496 {
c5aa993b 7497 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7498 num >>= 4;
7499 }
7500
2df3850c 7501 return width;
c906108c
SS
7502}
7503
23860348 7504/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7505
7506static CORE_ADDR
fba45db2 7507remote_address_masked (CORE_ADDR addr)
c906108c 7508{
883b9c6c 7509 unsigned int address_size = remote_address_size;
a744cf53 7510
911c95a5
UW
7511 /* If "remoteaddresssize" was not set, default to target address size. */
7512 if (!address_size)
f5656ead 7513 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7514
7515 if (address_size > 0
7516 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7517 {
7518 /* Only create a mask when that mask can safely be constructed
23860348 7519 in a ULONGEST variable. */
c906108c 7520 ULONGEST mask = 1;
a744cf53 7521
911c95a5 7522 mask = (mask << address_size) - 1;
c906108c
SS
7523 addr &= mask;
7524 }
7525 return addr;
7526}
7527
7528/* Determine whether the remote target supports binary downloading.
7529 This is accomplished by sending a no-op memory write of zero length
7530 to the target at the specified address. It does not suffice to send
23860348
MS
7531 the whole packet, since many stubs strip the eighth bit and
7532 subsequently compute a wrong checksum, which causes real havoc with
7533 remote_write_bytes.
7a292a7a 7534
96baa820 7535 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7536 clean. In cases like this, the user should clear "remote
23860348 7537 X-packet". */
96baa820 7538
c906108c 7539static void
fba45db2 7540check_binary_download (CORE_ADDR addr)
c906108c 7541{
d01949b6 7542 struct remote_state *rs = get_remote_state ();
24b06219 7543
4082afcc 7544 switch (packet_support (PACKET_X))
c906108c 7545 {
96baa820
JM
7546 case PACKET_DISABLE:
7547 break;
7548 case PACKET_ENABLE:
7549 break;
7550 case PACKET_SUPPORT_UNKNOWN:
7551 {
96baa820 7552 char *p;
802188a7 7553
2e9f7625 7554 p = rs->buf;
96baa820
JM
7555 *p++ = 'X';
7556 p += hexnumstr (p, (ULONGEST) addr);
7557 *p++ = ',';
7558 p += hexnumstr (p, (ULONGEST) 0);
7559 *p++ = ':';
7560 *p = '\0';
802188a7 7561
2e9f7625 7562 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7563 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7564
2e9f7625 7565 if (rs->buf[0] == '\0')
96baa820
JM
7566 {
7567 if (remote_debug)
7568 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7569 "binary downloading NOT "
7570 "supported by target\n");
444abaca 7571 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7572 }
7573 else
7574 {
7575 if (remote_debug)
7576 fprintf_unfiltered (gdb_stdlog,
64b9b334 7577 "binary downloading supported by target\n");
444abaca 7578 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7579 }
7580 break;
7581 }
c906108c
SS
7582 }
7583}
7584
124e13d9
SM
7585/* Helper function to resize the payload in order to try to get a good
7586 alignment. We try to write an amount of data such that the next write will
7587 start on an address aligned on REMOTE_ALIGN_WRITES. */
7588
7589static int
7590align_for_efficient_write (int todo, CORE_ADDR memaddr)
7591{
7592 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7593}
7594
c906108c
SS
7595/* Write memory data directly to the remote machine.
7596 This does not inform the data cache; the data cache uses this.
a76d924d 7597 HEADER is the starting part of the packet.
c906108c
SS
7598 MEMADDR is the address in the remote memory space.
7599 MYADDR is the address of the buffer in our space.
124e13d9
SM
7600 LEN_UNITS is the number of addressable units to write.
7601 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7602 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7603 should send data as binary ('X'), or hex-encoded ('M').
7604
7605 The function creates packet of the form
7606 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7607
124e13d9 7608 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7609
7610 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7611 are omitted.
7612
9b409511 7613 Return the transferred status, error or OK (an
124e13d9
SM
7614 'enum target_xfer_status' value). Save the number of addressable units
7615 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7616
7617 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7618 exchange between gdb and the stub could look like (?? in place of the
7619 checksum):
7620
7621 -> $m1000,4#??
7622 <- aaaabbbbccccdddd
7623
7624 -> $M1000,3:eeeeffffeeee#??
7625 <- OK
7626
7627 -> $m1000,4#??
7628 <- eeeeffffeeeedddd */
c906108c 7629
9b409511 7630static enum target_xfer_status
a76d924d 7631remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7632 const gdb_byte *myaddr, ULONGEST len_units,
7633 int unit_size, ULONGEST *xfered_len_units,
7634 char packet_format, int use_length)
c906108c 7635{
6d820c5c 7636 struct remote_state *rs = get_remote_state ();
cfd77fa1 7637 char *p;
a76d924d
DJ
7638 char *plen = NULL;
7639 int plenlen = 0;
124e13d9
SM
7640 int todo_units;
7641 int units_written;
7642 int payload_capacity_bytes;
7643 int payload_length_bytes;
a76d924d
DJ
7644
7645 if (packet_format != 'X' && packet_format != 'M')
7646 internal_error (__FILE__, __LINE__,
9b20d036 7647 _("remote_write_bytes_aux: bad packet format"));
c906108c 7648
124e13d9 7649 if (len_units == 0)
9b409511 7650 return TARGET_XFER_EOF;
b2182ed2 7651
124e13d9 7652 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7653
6d820c5c
DJ
7654 /* The packet buffer will be large enough for the payload;
7655 get_memory_packet_size ensures this. */
a76d924d 7656 rs->buf[0] = '\0';
c906108c 7657
a257b5bb 7658 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7659 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7660
124e13d9 7661 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7662 if (!use_length)
0df8b418 7663 /* The comma won't be used. */
124e13d9
SM
7664 payload_capacity_bytes += 1;
7665 payload_capacity_bytes -= strlen (header);
7666 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7667
a76d924d 7668 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7669
a76d924d
DJ
7670 strcat (rs->buf, header);
7671 p = rs->buf + strlen (header);
7672
7673 /* Compute a best guess of the number of bytes actually transfered. */
7674 if (packet_format == 'X')
c906108c 7675 {
23860348 7676 /* Best guess at number of bytes that will fit. */
124e13d9 7677 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7678 if (use_length)
124e13d9
SM
7679 payload_capacity_bytes -= hexnumlen (todo_units);
7680 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7681 }
7682 else
7683 {
124e13d9
SM
7684 /* Number of bytes that will fit. */
7685 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7686 if (use_length)
124e13d9
SM
7687 payload_capacity_bytes -= hexnumlen (todo_units);
7688 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7689 }
a76d924d 7690
124e13d9 7691 if (todo_units <= 0)
3de11b2e 7692 internal_error (__FILE__, __LINE__,
405f8e94 7693 _("minimum packet size too small to write data"));
802188a7 7694
6765f3e5
DJ
7695 /* If we already need another packet, then try to align the end
7696 of this packet to a useful boundary. */
124e13d9
SM
7697 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7698 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7699
a257b5bb 7700 /* Append "<memaddr>". */
917317f4
JM
7701 memaddr = remote_address_masked (memaddr);
7702 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7703
a76d924d
DJ
7704 if (use_length)
7705 {
7706 /* Append ",". */
7707 *p++ = ',';
802188a7 7708
124e13d9
SM
7709 /* Append the length and retain its location and size. It may need to be
7710 adjusted once the packet body has been created. */
a76d924d 7711 plen = p;
124e13d9 7712 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7713 p += plenlen;
7714 }
a257b5bb
AC
7715
7716 /* Append ":". */
917317f4
JM
7717 *p++ = ':';
7718 *p = '\0';
802188a7 7719
a257b5bb 7720 /* Append the packet body. */
a76d924d 7721 if (packet_format == 'X')
917317f4 7722 {
917317f4
JM
7723 /* Binary mode. Send target system values byte by byte, in
7724 increasing byte addresses. Only escape certain critical
7725 characters. */
124e13d9
SM
7726 payload_length_bytes =
7727 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7728 &units_written, payload_capacity_bytes);
6765f3e5 7729
124e13d9 7730 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7731 a second try to keep the end of the packet aligned. Don't do
7732 this if the packet is tiny. */
124e13d9 7733 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7734 {
124e13d9
SM
7735 int new_todo_units;
7736
7737 new_todo_units = align_for_efficient_write (units_written, memaddr);
7738
7739 if (new_todo_units != units_written)
7740 payload_length_bytes =
7741 remote_escape_output (myaddr, new_todo_units, unit_size,
7742 (gdb_byte *) p, &units_written,
7743 payload_capacity_bytes);
6765f3e5
DJ
7744 }
7745
124e13d9
SM
7746 p += payload_length_bytes;
7747 if (use_length && units_written < todo_units)
c906108c 7748 {
802188a7 7749 /* Escape chars have filled up the buffer prematurely,
124e13d9 7750 and we have actually sent fewer units than planned.
917317f4
JM
7751 Fix-up the length field of the packet. Use the same
7752 number of characters as before. */
124e13d9
SM
7753 plen += hexnumnstr (plen, (ULONGEST) units_written,
7754 plenlen);
917317f4 7755 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7756 }
a76d924d
DJ
7757 }
7758 else
7759 {
917317f4
JM
7760 /* Normal mode: Send target system values byte by byte, in
7761 increasing byte addresses. Each byte is encoded as a two hex
7762 value. */
124e13d9
SM
7763 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7764 units_written = todo_units;
c906108c 7765 }
802188a7 7766
2e9f7625 7767 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7768 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7769
2e9f7625 7770 if (rs->buf[0] == 'E')
00d84524 7771 return TARGET_XFER_E_IO;
802188a7 7772
124e13d9
SM
7773 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7774 send fewer units than we'd planned. */
7775 *xfered_len_units = (ULONGEST) units_written;
9b409511 7776 return TARGET_XFER_OK;
c906108c
SS
7777}
7778
a76d924d
DJ
7779/* Write memory data directly to the remote machine.
7780 This does not inform the data cache; the data cache uses this.
7781 MEMADDR is the address in the remote memory space.
7782 MYADDR is the address of the buffer in our space.
7783 LEN is the number of bytes.
7784
9b409511
YQ
7785 Return the transferred status, error or OK (an
7786 'enum target_xfer_status' value). Save the number of bytes
7787 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7788
9b409511
YQ
7789static enum target_xfer_status
7790remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7791 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7792{
7793 char *packet_format = 0;
7794
7795 /* Check whether the target supports binary download. */
7796 check_binary_download (memaddr);
7797
4082afcc 7798 switch (packet_support (PACKET_X))
a76d924d
DJ
7799 {
7800 case PACKET_ENABLE:
7801 packet_format = "X";
7802 break;
7803 case PACKET_DISABLE:
7804 packet_format = "M";
7805 break;
7806 case PACKET_SUPPORT_UNKNOWN:
7807 internal_error (__FILE__, __LINE__,
7808 _("remote_write_bytes: bad internal state"));
7809 default:
7810 internal_error (__FILE__, __LINE__, _("bad switch"));
7811 }
7812
7813 return remote_write_bytes_aux (packet_format,
124e13d9 7814 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7815 packet_format[0], 1);
a76d924d
DJ
7816}
7817
9217e74e
YQ
7818/* Read memory data directly from the remote machine.
7819 This does not use the data cache; the data cache uses this.
7820 MEMADDR is the address in the remote memory space.
7821 MYADDR is the address of the buffer in our space.
124e13d9
SM
7822 LEN_UNITS is the number of addressable memory units to read..
7823 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7824
7825 Return the transferred status, error or OK (an
7826 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7827 transferred in *XFERED_LEN_UNITS.
7828
7829 See the comment of remote_write_bytes_aux for an example of
7830 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7831
7832static enum target_xfer_status
124e13d9
SM
7833remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7834 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7835{
7836 struct remote_state *rs = get_remote_state ();
124e13d9 7837 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7838 char *p;
124e13d9
SM
7839 int todo_units;
7840 int decoded_bytes;
9217e74e 7841
124e13d9 7842 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7843 /* The packet buffer will be large enough for the payload;
7844 get_memory_packet_size ensures this. */
7845
124e13d9
SM
7846 /* Number of units that will fit. */
7847 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7848
7849 /* Construct "m"<memaddr>","<len>". */
7850 memaddr = remote_address_masked (memaddr);
7851 p = rs->buf;
7852 *p++ = 'm';
7853 p += hexnumstr (p, (ULONGEST) memaddr);
7854 *p++ = ',';
124e13d9 7855 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7856 *p = '\0';
7857 putpkt (rs->buf);
7858 getpkt (&rs->buf, &rs->buf_size, 0);
7859 if (rs->buf[0] == 'E'
7860 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7861 && rs->buf[3] == '\0')
7862 return TARGET_XFER_E_IO;
7863 /* Reply describes memory byte by byte, each byte encoded as two hex
7864 characters. */
7865 p = rs->buf;
124e13d9 7866 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7867 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7868 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7869 return TARGET_XFER_OK;
7870}
7871
b55fbac4
YQ
7872/* Using the set of read-only target sections of remote, read live
7873 read-only memory.
8acf9577
YQ
7874
7875 For interface/parameters/return description see target.h,
7876 to_xfer_partial. */
7877
7878static enum target_xfer_status
b55fbac4
YQ
7879remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7880 ULONGEST memaddr, ULONGEST len,
124e13d9 7881 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7882{
7883 struct target_section *secp;
7884 struct target_section_table *table;
7885
7886 secp = target_section_by_addr (ops, memaddr);
7887 if (secp != NULL
7888 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7889 secp->the_bfd_section)
7890 & SEC_READONLY))
7891 {
7892 struct target_section *p;
7893 ULONGEST memend = memaddr + len;
7894
7895 table = target_get_section_table (ops);
7896
7897 for (p = table->sections; p < table->sections_end; p++)
7898 {
7899 if (memaddr >= p->addr)
7900 {
7901 if (memend <= p->endaddr)
7902 {
7903 /* Entire transfer is within this section. */
124e13d9 7904 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7905 xfered_len);
8acf9577
YQ
7906 }
7907 else if (memaddr >= p->endaddr)
7908 {
7909 /* This section ends before the transfer starts. */
7910 continue;
7911 }
7912 else
7913 {
7914 /* This section overlaps the transfer. Just do half. */
7915 len = p->endaddr - memaddr;
124e13d9 7916 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7917 xfered_len);
8acf9577
YQ
7918 }
7919 }
7920 }
7921 }
7922
7923 return TARGET_XFER_EOF;
7924}
7925
9217e74e
YQ
7926/* Similar to remote_read_bytes_1, but it reads from the remote stub
7927 first if the requested memory is unavailable in traceframe.
7928 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7929
9b409511 7930static enum target_xfer_status
8acf9577 7931remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7932 gdb_byte *myaddr, ULONGEST len, int unit_size,
7933 ULONGEST *xfered_len)
c906108c 7934{
6b6aa828 7935 if (len == 0)
96c4f946 7936 return TARGET_XFER_EOF;
b2182ed2 7937
8acf9577
YQ
7938 if (get_traceframe_number () != -1)
7939 {
7940 VEC(mem_range_s) *available;
7941
7942 /* If we fail to get the set of available memory, then the
7943 target does not support querying traceframe info, and so we
7944 attempt reading from the traceframe anyway (assuming the
7945 target implements the old QTro packet then). */
7946 if (traceframe_available_memory (&available, memaddr, len))
7947 {
7948 struct cleanup *old_chain;
7949
7950 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7951
7952 if (VEC_empty (mem_range_s, available)
7953 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7954 {
7955 enum target_xfer_status res;
7956
7957 /* Don't read into the traceframe's available
7958 memory. */
7959 if (!VEC_empty (mem_range_s, available))
7960 {
7961 LONGEST oldlen = len;
7962
7963 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7964 gdb_assert (len <= oldlen);
7965 }
7966
7967 do_cleanups (old_chain);
7968
7969 /* This goes through the topmost target again. */
b55fbac4 7970 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7971 len, unit_size, xfered_len);
8acf9577
YQ
7972 if (res == TARGET_XFER_OK)
7973 return TARGET_XFER_OK;
7974 else
7975 {
7976 /* No use trying further, we know some memory starting
7977 at MEMADDR isn't available. */
7978 *xfered_len = len;
7979 return TARGET_XFER_UNAVAILABLE;
7980 }
7981 }
7982
7983 /* Don't try to read more than how much is available, in
7984 case the target implements the deprecated QTro packet to
7985 cater for older GDBs (the target's knowledge of read-only
7986 sections may be outdated by now). */
7987 len = VEC_index (mem_range_s, available, 0)->length;
7988
7989 do_cleanups (old_chain);
7990 }
7991 }
7992
124e13d9 7993 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7994}
74531fed 7995
c906108c 7996\f
c906108c 7997
a76d924d
DJ
7998/* Sends a packet with content determined by the printf format string
7999 FORMAT and the remaining arguments, then gets the reply. Returns
8000 whether the packet was a success, a failure, or unknown. */
8001
77b64a49
PA
8002static enum packet_result remote_send_printf (const char *format, ...)
8003 ATTRIBUTE_PRINTF (1, 2);
8004
2c0b251b 8005static enum packet_result
a76d924d
DJ
8006remote_send_printf (const char *format, ...)
8007{
8008 struct remote_state *rs = get_remote_state ();
8009 int max_size = get_remote_packet_size ();
a76d924d 8010 va_list ap;
a744cf53 8011
a76d924d
DJ
8012 va_start (ap, format);
8013
8014 rs->buf[0] = '\0';
8015 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8016 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8017
8018 if (putpkt (rs->buf) < 0)
8019 error (_("Communication problem with target."));
8020
8021 rs->buf[0] = '\0';
8022 getpkt (&rs->buf, &rs->buf_size, 0);
8023
8024 return packet_check_result (rs->buf);
8025}
8026
8027static void
8028restore_remote_timeout (void *p)
8029{
8030 int value = *(int *)p;
a744cf53 8031
a76d924d
DJ
8032 remote_timeout = value;
8033}
8034
8035/* Flash writing can take quite some time. We'll set
8036 effectively infinite timeout for flash operations.
8037 In future, we'll need to decide on a better approach. */
8038static const int remote_flash_timeout = 1000;
8039
8040static void
8041remote_flash_erase (struct target_ops *ops,
8042 ULONGEST address, LONGEST length)
8043{
f5656ead 8044 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
8045 int saved_remote_timeout = remote_timeout;
8046 enum packet_result ret;
a76d924d
DJ
8047 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8048 &saved_remote_timeout);
a744cf53 8049
a76d924d
DJ
8050 remote_timeout = remote_flash_timeout;
8051
8052 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8053 phex (address, addr_size),
a76d924d
DJ
8054 phex (length, 4));
8055 switch (ret)
8056 {
8057 case PACKET_UNKNOWN:
8058 error (_("Remote target does not support flash erase"));
8059 case PACKET_ERROR:
8060 error (_("Error erasing flash with vFlashErase packet"));
8061 default:
8062 break;
8063 }
8064
8065 do_cleanups (back_to);
8066}
8067
9b409511
YQ
8068static enum target_xfer_status
8069remote_flash_write (struct target_ops *ops, ULONGEST address,
8070 ULONGEST length, ULONGEST *xfered_len,
8071 const gdb_byte *data)
a76d924d
DJ
8072{
8073 int saved_remote_timeout = remote_timeout;
9b409511 8074 enum target_xfer_status ret;
a76d924d 8075 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 8076 &saved_remote_timeout);
a76d924d
DJ
8077
8078 remote_timeout = remote_flash_timeout;
124e13d9 8079 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 8080 xfered_len,'X', 0);
a76d924d
DJ
8081 do_cleanups (back_to);
8082
8083 return ret;
8084}
8085
8086static void
8087remote_flash_done (struct target_ops *ops)
8088{
8089 int saved_remote_timeout = remote_timeout;
8090 int ret;
8091 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8092 &saved_remote_timeout);
8093
8094 remote_timeout = remote_flash_timeout;
8095 ret = remote_send_printf ("vFlashDone");
8096 do_cleanups (back_to);
8097
8098 switch (ret)
8099 {
8100 case PACKET_UNKNOWN:
8101 error (_("Remote target does not support vFlashDone"));
8102 case PACKET_ERROR:
8103 error (_("Error finishing flash operation"));
8104 default:
8105 break;
8106 }
8107}
8108
c906108c 8109static void
fba45db2 8110remote_files_info (struct target_ops *ignore)
c906108c
SS
8111{
8112 puts_filtered ("Debugging a target over a serial line.\n");
8113}
8114\f
8115/* Stuff for dealing with the packets which are part of this protocol.
8116 See comment at top of file for details. */
8117
1927e618
PA
8118/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8119 error to higher layers. Called when a serial error is detected.
8120 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8121 the system error message for errno at function entry and final dot
8122 for output compatibility with throw_perror_with_name. */
1927e618
PA
8123
8124static void
8125unpush_and_perror (const char *string)
8126{
d6cb50a2 8127 int saved_errno = errno;
1927e618
PA
8128
8129 remote_unpush_target ();
d6cb50a2
JK
8130 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8131 safe_strerror (saved_errno));
1927e618
PA
8132}
8133
048094ac
PA
8134/* Read a single character from the remote end. The current quit
8135 handler is overridden to avoid quitting in the middle of packet
8136 sequence, as that would break communication with the remote server.
8137 See remote_serial_quit_handler for more detail. */
c906108c
SS
8138
8139static int
fba45db2 8140readchar (int timeout)
c906108c
SS
8141{
8142 int ch;
5d93a237 8143 struct remote_state *rs = get_remote_state ();
048094ac
PA
8144 struct cleanup *old_chain;
8145
8146 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8147
8148 rs->got_ctrlc_during_io = 0;
c906108c 8149
5d93a237 8150 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 8151
048094ac
PA
8152 if (rs->got_ctrlc_during_io)
8153 set_quit_flag ();
8154
8155 do_cleanups (old_chain);
8156
2acceee2 8157 if (ch >= 0)
0876f84a 8158 return ch;
2acceee2
JM
8159
8160 switch ((enum serial_rc) ch)
c906108c
SS
8161 {
8162 case SERIAL_EOF:
78a095c3 8163 remote_unpush_target ();
598d3636 8164 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8165 /* no return */
c906108c 8166 case SERIAL_ERROR:
1927e618
PA
8167 unpush_and_perror (_("Remote communication error. "
8168 "Target disconnected."));
2acceee2 8169 /* no return */
c906108c 8170 case SERIAL_TIMEOUT:
2acceee2 8171 break;
c906108c 8172 }
2acceee2 8173 return ch;
c906108c
SS
8174}
8175
c33e31fd 8176/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
8177 writing fails. The current quit handler is overridden to avoid
8178 quitting in the middle of packet sequence, as that would break
8179 communication with the remote server. See
8180 remote_serial_quit_handler for more detail. */
c33e31fd
PA
8181
8182static void
8183remote_serial_write (const char *str, int len)
8184{
5d93a237 8185 struct remote_state *rs = get_remote_state ();
048094ac
PA
8186 struct cleanup *old_chain;
8187
8188 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8189
8190 rs->got_ctrlc_during_io = 0;
5d93a237
TT
8191
8192 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8193 {
1927e618
PA
8194 unpush_and_perror (_("Remote communication error. "
8195 "Target disconnected."));
c33e31fd 8196 }
048094ac
PA
8197
8198 if (rs->got_ctrlc_during_io)
8199 set_quit_flag ();
8200
8201 do_cleanups (old_chain);
c33e31fd
PA
8202}
8203
6d820c5c
DJ
8204/* Send the command in *BUF to the remote machine, and read the reply
8205 into *BUF. Report an error if we get an error reply. Resize
8206 *BUF using xrealloc if necessary to hold the result, and update
8207 *SIZEOF_BUF. */
c906108c
SS
8208
8209static void
6d820c5c
DJ
8210remote_send (char **buf,
8211 long *sizeof_buf)
c906108c 8212{
6d820c5c 8213 putpkt (*buf);
c2d11a7d 8214 getpkt (buf, sizeof_buf, 0);
c906108c 8215
6d820c5c
DJ
8216 if ((*buf)[0] == 'E')
8217 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8218}
8219
6e5abd65
PA
8220/* Return a pointer to an xmalloc'ed string representing an escaped
8221 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8222 etc. The caller is responsible for releasing the returned
8223 memory. */
8224
8225static char *
8226escape_buffer (const char *buf, int n)
8227{
8228 struct cleanup *old_chain;
8229 struct ui_file *stb;
8230 char *str;
6e5abd65
PA
8231
8232 stb = mem_fileopen ();
8233 old_chain = make_cleanup_ui_file_delete (stb);
8234
6ef284bd 8235 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 8236 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
8237 do_cleanups (old_chain);
8238 return str;
8239}
8240
c906108c
SS
8241/* Display a null-terminated packet on stdout, for debugging, using C
8242 string notation. */
8243
8244static void
baa336ce 8245print_packet (const char *buf)
c906108c
SS
8246{
8247 puts_filtered ("\"");
43e526b9 8248 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8249 puts_filtered ("\"");
8250}
8251
8252int
baa336ce 8253putpkt (const char *buf)
c906108c
SS
8254{
8255 return putpkt_binary (buf, strlen (buf));
8256}
8257
8258/* Send a packet to the remote machine, with error checking. The data
23860348 8259 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8260 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8261 and for a possible /0 if we are debugging (remote_debug) and want
8262 to print the sent packet as a string. */
c906108c
SS
8263
8264static int
baa336ce 8265putpkt_binary (const char *buf, int cnt)
c906108c 8266{
2d717e4f 8267 struct remote_state *rs = get_remote_state ();
c906108c
SS
8268 int i;
8269 unsigned char csum = 0;
224c3ddb 8270 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8271 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8272
c906108c
SS
8273 int ch;
8274 int tcount = 0;
8275 char *p;
8276
e24a49d8
PA
8277 /* Catch cases like trying to read memory or listing threads while
8278 we're waiting for a stop reply. The remote server wouldn't be
8279 ready to handle this request, so we'd hang and timeout. We don't
8280 have to worry about this in synchronous mode, because in that
8281 case it's not possible to issue a command while the target is
74531fed
PA
8282 running. This is not a problem in non-stop mode, because in that
8283 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8284 if (!target_is_non_stop_p ()
8285 && target_is_async_p ()
8286 && rs->waiting_for_stop_reply)
9597b22a
DE
8287 {
8288 error (_("Cannot execute this command while the target is running.\n"
8289 "Use the \"interrupt\" command to stop the target\n"
8290 "and then try again."));
8291 }
e24a49d8 8292
2d717e4f
DJ
8293 /* We're sending out a new packet. Make sure we don't look at a
8294 stale cached response. */
8295 rs->cached_wait_status = 0;
8296
c906108c
SS
8297 /* Copy the packet into buffer BUF2, encapsulating it
8298 and giving it a checksum. */
8299
c906108c
SS
8300 p = buf2;
8301 *p++ = '$';
8302
8303 for (i = 0; i < cnt; i++)
8304 {
8305 csum += buf[i];
8306 *p++ = buf[i];
8307 }
8308 *p++ = '#';
8309 *p++ = tohex ((csum >> 4) & 0xf);
8310 *p++ = tohex (csum & 0xf);
8311
8312 /* Send it over and over until we get a positive ack. */
8313
8314 while (1)
8315 {
8316 int started_error_output = 0;
8317
8318 if (remote_debug)
8319 {
6e5abd65
PA
8320 struct cleanup *old_chain;
8321 char *str;
8322
c906108c 8323 *p = '\0';
6e5abd65
PA
8324 str = escape_buffer (buf2, p - buf2);
8325 old_chain = make_cleanup (xfree, str);
8326 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8327 gdb_flush (gdb_stdlog);
6e5abd65 8328 do_cleanups (old_chain);
c906108c 8329 }
c33e31fd 8330 remote_serial_write (buf2, p - buf2);
c906108c 8331
a6f3e723
SL
8332 /* If this is a no acks version of the remote protocol, send the
8333 packet and move on. */
8334 if (rs->noack_mode)
8335 break;
8336
74531fed
PA
8337 /* Read until either a timeout occurs (-2) or '+' is read.
8338 Handle any notification that arrives in the mean time. */
c906108c
SS
8339 while (1)
8340 {
8341 ch = readchar (remote_timeout);
8342
c5aa993b 8343 if (remote_debug)
c906108c
SS
8344 {
8345 switch (ch)
8346 {
8347 case '+':
1216fa2c 8348 case '-':
c906108c
SS
8349 case SERIAL_TIMEOUT:
8350 case '$':
74531fed 8351 case '%':
c906108c
SS
8352 if (started_error_output)
8353 {
8354 putchar_unfiltered ('\n');
8355 started_error_output = 0;
8356 }
8357 }
8358 }
8359
8360 switch (ch)
8361 {
8362 case '+':
8363 if (remote_debug)
0f71a2f6 8364 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8365 do_cleanups (old_chain);
c906108c 8366 return 1;
1216fa2c
AC
8367 case '-':
8368 if (remote_debug)
8369 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8370 /* FALLTHROUGH */
c906108c 8371 case SERIAL_TIMEOUT:
c5aa993b 8372 tcount++;
c906108c 8373 if (tcount > 3)
a5c0808e
PA
8374 {
8375 do_cleanups (old_chain);
8376 return 0;
8377 }
23860348 8378 break; /* Retransmit buffer. */
c906108c
SS
8379 case '$':
8380 {
40e3f985 8381 if (remote_debug)
2bc416ba 8382 fprintf_unfiltered (gdb_stdlog,
23860348 8383 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8384 /* It's probably an old response sent because an ACK
8385 was lost. Gobble up the packet and ack it so it
8386 doesn't get retransmitted when we resend this
8387 packet. */
6d820c5c 8388 skip_frame ();
c33e31fd 8389 remote_serial_write ("+", 1);
23860348 8390 continue; /* Now, go look for +. */
c906108c 8391 }
74531fed
PA
8392
8393 case '%':
8394 {
8395 int val;
8396
8397 /* If we got a notification, handle it, and go back to looking
8398 for an ack. */
8399 /* We've found the start of a notification. Now
8400 collect the data. */
8401 val = read_frame (&rs->buf, &rs->buf_size);
8402 if (val >= 0)
8403 {
8404 if (remote_debug)
8405 {
6e5abd65
PA
8406 struct cleanup *old_chain;
8407 char *str;
8408
8409 str = escape_buffer (rs->buf, val);
8410 old_chain = make_cleanup (xfree, str);
8411 fprintf_unfiltered (gdb_stdlog,
8412 " Notification received: %s\n",
8413 str);
8414 do_cleanups (old_chain);
74531fed 8415 }
5965e028 8416 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8417 /* We're in sync now, rewait for the ack. */
8418 tcount = 0;
8419 }
8420 else
8421 {
8422 if (remote_debug)
8423 {
8424 if (!started_error_output)
8425 {
8426 started_error_output = 1;
8427 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8428 }
8429 fputc_unfiltered (ch & 0177, gdb_stdlog);
8430 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8431 }
8432 }
8433 continue;
8434 }
8435 /* fall-through */
c906108c
SS
8436 default:
8437 if (remote_debug)
8438 {
8439 if (!started_error_output)
8440 {
8441 started_error_output = 1;
0f71a2f6 8442 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8443 }
0f71a2f6 8444 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8445 }
8446 continue;
8447 }
23860348 8448 break; /* Here to retransmit. */
c906108c
SS
8449 }
8450
8451#if 0
8452 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8453 able to get out next time we call QUIT, without anything as
8454 violent as interrupt_query. If we want to provide a way out of
8455 here without getting to the next QUIT, it should be based on
8456 hitting ^C twice as in remote_wait. */
c906108c
SS
8457 if (quit_flag)
8458 {
8459 quit_flag = 0;
8460 interrupt_query ();
8461 }
8462#endif
8463 }
a5c0808e
PA
8464
8465 do_cleanups (old_chain);
a6f3e723 8466 return 0;
c906108c
SS
8467}
8468
6d820c5c
DJ
8469/* Come here after finding the start of a frame when we expected an
8470 ack. Do our best to discard the rest of this packet. */
8471
8472static void
8473skip_frame (void)
8474{
8475 int c;
8476
8477 while (1)
8478 {
8479 c = readchar (remote_timeout);
8480 switch (c)
8481 {
8482 case SERIAL_TIMEOUT:
8483 /* Nothing we can do. */
8484 return;
8485 case '#':
8486 /* Discard the two bytes of checksum and stop. */
8487 c = readchar (remote_timeout);
8488 if (c >= 0)
8489 c = readchar (remote_timeout);
8490
8491 return;
8492 case '*': /* Run length encoding. */
8493 /* Discard the repeat count. */
8494 c = readchar (remote_timeout);
8495 if (c < 0)
8496 return;
8497 break;
8498 default:
8499 /* A regular character. */
8500 break;
8501 }
8502 }
8503}
8504
c906108c 8505/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8506 into *BUF, verifying the checksum, length, and handling run-length
8507 compression. NUL terminate the buffer. If there is not enough room,
8508 expand *BUF using xrealloc.
c906108c 8509
c2d11a7d
JM
8510 Returns -1 on error, number of characters in buffer (ignoring the
8511 trailing NULL) on success. (could be extended to return one of the
23860348 8512 SERIAL status indications). */
c2d11a7d
JM
8513
8514static long
6d820c5c
DJ
8515read_frame (char **buf_p,
8516 long *sizeof_buf)
c906108c
SS
8517{
8518 unsigned char csum;
c2d11a7d 8519 long bc;
c906108c 8520 int c;
6d820c5c 8521 char *buf = *buf_p;
a6f3e723 8522 struct remote_state *rs = get_remote_state ();
c906108c
SS
8523
8524 csum = 0;
c2d11a7d 8525 bc = 0;
c906108c
SS
8526
8527 while (1)
8528 {
8529 c = readchar (remote_timeout);
c906108c
SS
8530 switch (c)
8531 {
8532 case SERIAL_TIMEOUT:
8533 if (remote_debug)
0f71a2f6 8534 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8535 return -1;
c906108c
SS
8536 case '$':
8537 if (remote_debug)
0f71a2f6
JM
8538 fputs_filtered ("Saw new packet start in middle of old one\n",
8539 gdb_stdlog);
23860348 8540 return -1; /* Start a new packet, count retries. */
c906108c
SS
8541 case '#':
8542 {
8543 unsigned char pktcsum;
e1b09194
AC
8544 int check_0 = 0;
8545 int check_1 = 0;
c906108c 8546
c2d11a7d 8547 buf[bc] = '\0';
c906108c 8548
e1b09194
AC
8549 check_0 = readchar (remote_timeout);
8550 if (check_0 >= 0)
8551 check_1 = readchar (remote_timeout);
802188a7 8552
e1b09194
AC
8553 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8554 {
8555 if (remote_debug)
2bc416ba 8556 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8557 gdb_stdlog);
e1b09194
AC
8558 return -1;
8559 }
8560 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8561 {
8562 if (remote_debug)
2bc416ba 8563 fputs_filtered ("Communication error in checksum\n",
23860348 8564 gdb_stdlog);
40e3f985
FN
8565 return -1;
8566 }
c906108c 8567
a6f3e723
SL
8568 /* Don't recompute the checksum; with no ack packets we
8569 don't have any way to indicate a packet retransmission
8570 is necessary. */
8571 if (rs->noack_mode)
8572 return bc;
8573
e1b09194 8574 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8575 if (csum == pktcsum)
c2d11a7d 8576 return bc;
c906108c 8577
c5aa993b 8578 if (remote_debug)
c906108c 8579 {
6e5abd65
PA
8580 struct cleanup *old_chain;
8581 char *str;
8582
8583 str = escape_buffer (buf, bc);
8584 old_chain = make_cleanup (xfree, str);
8585 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8586 "Bad checksum, sentsum=0x%x, "
8587 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8588 pktcsum, csum, str);
8589 do_cleanups (old_chain);
c906108c 8590 }
c2d11a7d 8591 /* Number of characters in buffer ignoring trailing
23860348 8592 NULL. */
c2d11a7d 8593 return -1;
c906108c 8594 }
23860348 8595 case '*': /* Run length encoding. */
c2c6d25f
JM
8596 {
8597 int repeat;
c906108c 8598
a744cf53 8599 csum += c;
b4501125
AC
8600 c = readchar (remote_timeout);
8601 csum += c;
23860348 8602 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8603
23860348 8604 /* The character before ``*'' is repeated. */
c2d11a7d 8605
6d820c5c 8606 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8607 {
6d820c5c
DJ
8608 if (bc + repeat - 1 >= *sizeof_buf - 1)
8609 {
8610 /* Make some more room in the buffer. */
8611 *sizeof_buf += repeat;
224c3ddb 8612 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
8613 buf = *buf_p;
8614 }
8615
c2d11a7d
JM
8616 memset (&buf[bc], buf[bc - 1], repeat);
8617 bc += repeat;
c2c6d25f
JM
8618 continue;
8619 }
8620
c2d11a7d 8621 buf[bc] = '\0';
6d820c5c 8622 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8623 return -1;
c2c6d25f 8624 }
c906108c 8625 default:
6d820c5c 8626 if (bc >= *sizeof_buf - 1)
c906108c 8627 {
6d820c5c
DJ
8628 /* Make some more room in the buffer. */
8629 *sizeof_buf *= 2;
224c3ddb 8630 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 8631 buf = *buf_p;
c906108c
SS
8632 }
8633
6d820c5c
DJ
8634 buf[bc++] = c;
8635 csum += c;
8636 continue;
c906108c
SS
8637 }
8638 }
8639}
8640
8641/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8642 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8643 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8644 rather than timing out; this is used (in synchronous mode) to wait
8645 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8646/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8647 don't have to change all the calls to getpkt to deal with the
8648 return value, because at the moment I don't know what the right
23860348 8649 thing to do it for those. */
c906108c 8650void
6d820c5c
DJ
8651getpkt (char **buf,
8652 long *sizeof_buf,
c2d11a7d 8653 int forever)
d9fcf2fb 8654{
54887903 8655 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
8656}
8657
8658
8659/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8660 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8661 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8662 rather than timing out; this is used (in synchronous mode) to wait
8663 for a target that is is executing user code to stop. If FOREVER ==
8664 0, this function is allowed to time out gracefully and return an
74531fed
PA
8665 indication of this to the caller. Otherwise return the number of
8666 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8667 enough reason to return to the caller. *IS_NOTIF is an output
8668 boolean that indicates whether *BUF holds a notification or not
8669 (a regular packet). */
74531fed 8670
3172dc30 8671static int
74531fed 8672getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8673 int expecting_notif, int *is_notif)
c906108c 8674{
2d717e4f 8675 struct remote_state *rs = get_remote_state ();
c906108c
SS
8676 int c;
8677 int tries;
8678 int timeout;
df4b58fe 8679 int val = -1;
c906108c 8680
2d717e4f
DJ
8681 /* We're reading a new response. Make sure we don't look at a
8682 previously cached response. */
8683 rs->cached_wait_status = 0;
8684
6d820c5c 8685 strcpy (*buf, "timeout");
c906108c
SS
8686
8687 if (forever)
74531fed
PA
8688 timeout = watchdog > 0 ? watchdog : -1;
8689 else if (expecting_notif)
8690 timeout = 0; /* There should already be a char in the buffer. If
8691 not, bail out. */
c906108c
SS
8692 else
8693 timeout = remote_timeout;
8694
8695#define MAX_TRIES 3
8696
74531fed
PA
8697 /* Process any number of notifications, and then return when
8698 we get a packet. */
8699 for (;;)
c906108c 8700 {
d9c43928 8701 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8702 times. */
8703 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8704 {
74531fed
PA
8705 /* This can loop forever if the remote side sends us
8706 characters continuously, but if it pauses, we'll get
8707 SERIAL_TIMEOUT from readchar because of timeout. Then
8708 we'll count that as a retry.
8709
8710 Note that even when forever is set, we will only wait
8711 forever prior to the start of a packet. After that, we
8712 expect characters to arrive at a brisk pace. They should
8713 show up within remote_timeout intervals. */
8714 do
8715 c = readchar (timeout);
8716 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8717
8718 if (c == SERIAL_TIMEOUT)
8719 {
74531fed
PA
8720 if (expecting_notif)
8721 return -1; /* Don't complain, it's normal to not get
8722 anything in this case. */
8723
23860348 8724 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8725 {
78a095c3 8726 remote_unpush_target ();
598d3636
JK
8727 throw_error (TARGET_CLOSE_ERROR,
8728 _("Watchdog timeout has expired. "
8729 "Target detached."));
c906108c 8730 }
c906108c 8731 if (remote_debug)
0f71a2f6 8732 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8733 }
74531fed
PA
8734 else
8735 {
8736 /* We've found the start of a packet or notification.
8737 Now collect the data. */
8738 val = read_frame (buf, sizeof_buf);
8739 if (val >= 0)
8740 break;
8741 }
8742
c33e31fd 8743 remote_serial_write ("-", 1);
c906108c 8744 }
c906108c 8745
74531fed
PA
8746 if (tries > MAX_TRIES)
8747 {
8748 /* We have tried hard enough, and just can't receive the
8749 packet/notification. Give up. */
8750 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8751
74531fed
PA
8752 /* Skip the ack char if we're in no-ack mode. */
8753 if (!rs->noack_mode)
c33e31fd 8754 remote_serial_write ("+", 1);
74531fed
PA
8755 return -1;
8756 }
c906108c 8757
74531fed
PA
8758 /* If we got an ordinary packet, return that to our caller. */
8759 if (c == '$')
c906108c
SS
8760 {
8761 if (remote_debug)
43e526b9 8762 {
6e5abd65
PA
8763 struct cleanup *old_chain;
8764 char *str;
8765
8766 str = escape_buffer (*buf, val);
8767 old_chain = make_cleanup (xfree, str);
8768 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8769 do_cleanups (old_chain);
43e526b9 8770 }
a6f3e723
SL
8771
8772 /* Skip the ack char if we're in no-ack mode. */
8773 if (!rs->noack_mode)
c33e31fd 8774 remote_serial_write ("+", 1);
fee9eda9
YQ
8775 if (is_notif != NULL)
8776 *is_notif = 0;
0876f84a 8777 return val;
c906108c
SS
8778 }
8779
74531fed
PA
8780 /* If we got a notification, handle it, and go back to looking
8781 for a packet. */
8782 else
8783 {
8784 gdb_assert (c == '%');
8785
8786 if (remote_debug)
8787 {
6e5abd65
PA
8788 struct cleanup *old_chain;
8789 char *str;
8790
8791 str = escape_buffer (*buf, val);
8792 old_chain = make_cleanup (xfree, str);
8793 fprintf_unfiltered (gdb_stdlog,
8794 " Notification received: %s\n",
8795 str);
8796 do_cleanups (old_chain);
74531fed 8797 }
fee9eda9
YQ
8798 if (is_notif != NULL)
8799 *is_notif = 1;
c906108c 8800
5965e028 8801 handle_notification (rs->notif_state, *buf);
c906108c 8802
74531fed 8803 /* Notifications require no acknowledgement. */
a6f3e723 8804
74531fed 8805 if (expecting_notif)
fee9eda9 8806 return val;
74531fed
PA
8807 }
8808 }
8809}
8810
8811static int
8812getpkt_sane (char **buf, long *sizeof_buf, int forever)
8813{
fee9eda9 8814 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8815}
8816
8817static int
fee9eda9
YQ
8818getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8819 int *is_notif)
74531fed 8820{
fee9eda9
YQ
8821 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8822 is_notif);
c906108c 8823}
74531fed 8824
cbb8991c
DB
8825/* Check whether EVENT is a fork event for the process specified
8826 by the pid passed in DATA, and if it is, kill the fork child. */
8827
8828static int
8829kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8830 QUEUE_ITER (stop_reply_p) *iter,
8831 stop_reply_p event,
8832 void *data)
8833{
19ba03f4 8834 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
8835 int parent_pid = *(int *) param->input;
8836
8837 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8838 {
8839 struct remote_state *rs = get_remote_state ();
8840 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8841 int res;
8842
8843 res = remote_vkill (child_pid, rs);
8844 if (res != 0)
8845 error (_("Can't kill fork child process %d"), child_pid);
8846 }
8847
8848 return 1;
8849}
8850
8851/* Kill any new fork children of process PID that haven't been
8852 processed by follow_fork. */
8853
8854static void
8855kill_new_fork_children (int pid, struct remote_state *rs)
8856{
8857 struct thread_info *thread;
8858 struct notif_client *notif = &notif_client_stop;
8859 struct queue_iter_param param;
8860
8861 /* Kill the fork child threads of any threads in process PID
8862 that are stopped at a fork event. */
8863 ALL_NON_EXITED_THREADS (thread)
8864 {
8865 struct target_waitstatus *ws = &thread->pending_follow;
8866
8867 if (is_pending_fork_parent (ws, pid, thread->ptid))
8868 {
8869 struct remote_state *rs = get_remote_state ();
8870 int child_pid = ptid_get_pid (ws->value.related_pid);
8871 int res;
8872
8873 res = remote_vkill (child_pid, rs);
8874 if (res != 0)
8875 error (_("Can't kill fork child process %d"), child_pid);
8876 }
8877 }
8878
8879 /* Check for any pending fork events (not reported or processed yet)
8880 in process PID and kill those fork child threads as well. */
8881 remote_notif_get_pending_events (notif);
8882 param.input = &pid;
8883 param.output = NULL;
8884 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8885 kill_child_of_pending_fork, &param);
8886}
8887
c906108c 8888\f
8020350c
DB
8889/* Target hook to kill the current inferior. */
8890
c906108c 8891static void
7d85a9c0 8892remote_kill (struct target_ops *ops)
43ff13b4 8893{
8020350c
DB
8894 int res = -1;
8895 int pid = ptid_get_pid (inferior_ptid);
8896 struct remote_state *rs = get_remote_state ();
0fdf84ca 8897
8020350c 8898 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 8899 {
8020350c
DB
8900 /* If we're stopped while forking and we haven't followed yet,
8901 kill the child task. We need to do this before killing the
8902 parent task because if this is a vfork then the parent will
8903 be sleeping. */
8904 kill_new_fork_children (pid, rs);
8905
8906 res = remote_vkill (pid, rs);
8907 if (res == 0)
0fdf84ca 8908 {
8020350c 8909 target_mourn_inferior ();
0fdf84ca
PA
8910 return;
8911 }
8020350c 8912 }
0fdf84ca 8913
8020350c
DB
8914 /* If we are in 'target remote' mode and we are killing the only
8915 inferior, then we will tell gdbserver to exit and unpush the
8916 target. */
8917 if (res == -1 && !remote_multi_process_p (rs)
8918 && number_of_live_inferiors () == 1)
8919 {
8920 remote_kill_k ();
8921
8922 /* We've killed the remote end, we get to mourn it. If we are
8923 not in extended mode, mourning the inferior also unpushes
8924 remote_ops from the target stack, which closes the remote
8925 connection. */
8926 target_mourn_inferior ();
8927
8928 return;
0fdf84ca 8929 }
43ff13b4 8930
8020350c 8931 error (_("Can't kill process"));
43ff13b4
JM
8932}
8933
8020350c
DB
8934/* Send a kill request to the target using the 'vKill' packet. */
8935
82f73884
PA
8936static int
8937remote_vkill (int pid, struct remote_state *rs)
8938{
4082afcc 8939 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8940 return -1;
8941
8942 /* Tell the remote target to detach. */
bba74b36 8943 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8944 putpkt (rs->buf);
8945 getpkt (&rs->buf, &rs->buf_size, 0);
8946
4082afcc
PA
8947 switch (packet_ok (rs->buf,
8948 &remote_protocol_packets[PACKET_vKill]))
8949 {
8950 case PACKET_OK:
8951 return 0;
8952 case PACKET_ERROR:
8953 return 1;
8954 case PACKET_UNKNOWN:
8955 return -1;
8956 default:
8957 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8958 }
82f73884
PA
8959}
8960
8020350c
DB
8961/* Send a kill request to the target using the 'k' packet. */
8962
82f73884 8963static void
8020350c 8964remote_kill_k (void)
82f73884 8965{
8020350c
DB
8966 /* Catch errors so the user can quit from gdb even when we
8967 aren't on speaking terms with the remote system. */
8968 TRY
82f73884 8969 {
82f73884 8970 putpkt ("k");
82f73884 8971 }
8020350c
DB
8972 CATCH (ex, RETURN_MASK_ERROR)
8973 {
8974 if (ex.error == TARGET_CLOSE_ERROR)
8975 {
8976 /* If we got an (EOF) error that caused the target
8977 to go away, then we're done, that's what we wanted.
8978 "k" is susceptible to cause a premature EOF, given
8979 that the remote server isn't actually required to
8980 reply to "k", and it can happen that it doesn't
8981 even get to reply ACK to the "k". */
8982 return;
8983 }
82f73884 8984
8020350c
DB
8985 /* Otherwise, something went wrong. We didn't actually kill
8986 the target. Just propagate the exception, and let the
8987 user or higher layers decide what to do. */
8988 throw_exception (ex);
8989 }
8990 END_CATCH
82f73884
PA
8991}
8992
c906108c 8993static void
20f796c9 8994remote_mourn (struct target_ops *target)
c906108c 8995{
8020350c 8996 struct remote_state *rs = get_remote_state ();
ce5ce7ed 8997
8020350c
DB
8998 /* In 'target remote' mode with one inferior, we close the connection. */
8999 if (!rs->extended && number_of_live_inferiors () <= 1)
9000 {
9001 unpush_target (target);
c906108c 9002
8020350c
DB
9003 /* remote_close takes care of doing most of the clean up. */
9004 generic_mourn_inferior ();
9005 return;
9006 }
c906108c 9007
e24a49d8
PA
9008 /* In case we got here due to an error, but we're going to stay
9009 connected. */
9010 rs->waiting_for_stop_reply = 0;
9011
dc1981d7
PA
9012 /* If the current general thread belonged to the process we just
9013 detached from or has exited, the remote side current general
9014 thread becomes undefined. Considering a case like this:
9015
9016 - We just got here due to a detach.
9017 - The process that we're detaching from happens to immediately
9018 report a global breakpoint being hit in non-stop mode, in the
9019 same thread we had selected before.
9020 - GDB attaches to this process again.
9021 - This event happens to be the next event we handle.
9022
9023 GDB would consider that the current general thread didn't need to
9024 be set on the stub side (with Hg), since for all it knew,
9025 GENERAL_THREAD hadn't changed.
9026
9027 Notice that although in all-stop mode, the remote server always
9028 sets the current thread to the thread reporting the stop event,
9029 that doesn't happen in non-stop mode; in non-stop, the stub *must
9030 not* change the current thread when reporting a breakpoint hit,
9031 due to the decoupling of event reporting and event handling.
9032
9033 To keep things simple, we always invalidate our notion of the
9034 current thread. */
47f8a51d 9035 record_currthread (rs, minus_one_ptid);
dc1981d7 9036
8020350c 9037 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9038 generic_mourn_inferior ();
9039
d729566a 9040 if (!have_inferiors ())
2d717e4f 9041 {
82f73884
PA
9042 if (!remote_multi_process_p (rs))
9043 {
9044 /* Check whether the target is running now - some remote stubs
9045 automatically restart after kill. */
9046 putpkt ("?");
9047 getpkt (&rs->buf, &rs->buf_size, 0);
9048
9049 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9050 {
3e43a32a
MS
9051 /* Assume that the target has been restarted. Set
9052 inferior_ptid so that bits of core GDB realizes
9053 there's something here, e.g., so that the user can
9054 say "kill" again. */
82f73884
PA
9055 inferior_ptid = magic_null_ptid;
9056 }
82f73884 9057 }
2d717e4f
DJ
9058 }
9059}
c906108c 9060
03583c20 9061static int
2bfc0540 9062extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 9063{
4082afcc 9064 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9065}
9066
9067static void
9068extended_remote_disable_randomization (int val)
9069{
9070 struct remote_state *rs = get_remote_state ();
9071 char *reply;
9072
bba74b36
YQ
9073 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9074 val);
03583c20
UW
9075 putpkt (rs->buf);
9076 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9077 if (*reply == '\0')
9078 error (_("Target does not support QDisableRandomization."));
9079 if (strcmp (reply, "OK") != 0)
9080 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9081}
9082
2d717e4f
DJ
9083static int
9084extended_remote_run (char *args)
9085{
9086 struct remote_state *rs = get_remote_state ();
2d717e4f 9087 int len;
94585166 9088 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9089
2d717e4f
DJ
9090 /* If the user has disabled vRun support, or we have detected that
9091 support is not available, do not try it. */
4082afcc 9092 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9093 return -1;
424163ea 9094
2d717e4f
DJ
9095 strcpy (rs->buf, "vRun;");
9096 len = strlen (rs->buf);
c906108c 9097
2d717e4f
DJ
9098 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9099 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9100 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9101 strlen (remote_exec_file));
2d717e4f 9102
d1a41061 9103 gdb_assert (args != NULL);
2d717e4f
DJ
9104 if (*args)
9105 {
9106 struct cleanup *back_to;
9107 int i;
9108 char **argv;
9109
d1a41061 9110 argv = gdb_buildargv (args);
6e366df1 9111 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
9112 for (i = 0; argv[i] != NULL; i++)
9113 {
9114 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9115 error (_("Argument list too long for run packet"));
9116 rs->buf[len++] = ';';
9f1b45b0
TT
9117 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9118 strlen (argv[i]));
2d717e4f
DJ
9119 }
9120 do_cleanups (back_to);
9121 }
9122
9123 rs->buf[len++] = '\0';
9124
9125 putpkt (rs->buf);
9126 getpkt (&rs->buf, &rs->buf_size, 0);
9127
4082afcc 9128 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9129 {
4082afcc 9130 case PACKET_OK:
3405876a 9131 /* We have a wait response. All is well. */
2d717e4f 9132 return 0;
4082afcc
PA
9133 case PACKET_UNKNOWN:
9134 return -1;
9135 case PACKET_ERROR:
2d717e4f
DJ
9136 if (remote_exec_file[0] == '\0')
9137 error (_("Running the default executable on the remote target failed; "
9138 "try \"set remote exec-file\"?"));
9139 else
9140 error (_("Running \"%s\" on the remote target failed"),
9141 remote_exec_file);
4082afcc
PA
9142 default:
9143 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9144 }
c906108c
SS
9145}
9146
2d717e4f
DJ
9147/* In the extended protocol we want to be able to do things like
9148 "run" and have them basically work as expected. So we need
9149 a special create_inferior function. We support changing the
9150 executable file and the command line arguments, but not the
9151 environment. */
9152
43ff13b4 9153static void
77a19445
TT
9154extended_remote_create_inferior (struct target_ops *ops,
9155 char *exec_file, char *args,
9156 char **env, int from_tty)
43ff13b4 9157{
3405876a
PA
9158 int run_worked;
9159 char *stop_reply;
9160 struct remote_state *rs = get_remote_state ();
94585166 9161 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9162
43ff13b4 9163 /* If running asynchronously, register the target file descriptor
23860348 9164 with the event loop. */
75c99385 9165 if (target_can_async_p ())
6a3753b3 9166 target_async (1);
43ff13b4 9167
03583c20 9168 /* Disable address space randomization if requested (and supported). */
2bfc0540 9169 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9170 extended_remote_disable_randomization (disable_randomization);
9171
43ff13b4 9172 /* Now restart the remote server. */
3405876a
PA
9173 run_worked = extended_remote_run (args) != -1;
9174 if (!run_worked)
2d717e4f
DJ
9175 {
9176 /* vRun was not supported. Fail if we need it to do what the
9177 user requested. */
9178 if (remote_exec_file[0])
9179 error (_("Remote target does not support \"set remote exec-file\""));
9180 if (args[0])
9181 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9182
2d717e4f
DJ
9183 /* Fall back to "R". */
9184 extended_remote_restart ();
9185 }
424163ea 9186
6c95b8df
PA
9187 if (!have_inferiors ())
9188 {
9189 /* Clean up from the last time we ran, before we mark the target
9190 running again. This will mark breakpoints uninserted, and
9191 get_offsets may insert breakpoints. */
9192 init_thread_list ();
9193 init_wait_for_inferior ();
9194 }
45280a52 9195
3405876a
PA
9196 /* vRun's success return is a stop reply. */
9197 stop_reply = run_worked ? rs->buf : NULL;
9198 add_current_inferior_and_thread (stop_reply);
c0a2216e 9199
2d717e4f
DJ
9200 /* Get updated offsets, if the stub uses qOffsets. */
9201 get_offsets ();
2d717e4f 9202}
c906108c 9203\f
c5aa993b 9204
b775012e
LM
9205/* Given a location's target info BP_TGT and the packet buffer BUF, output
9206 the list of conditions (in agent expression bytecode format), if any, the
9207 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9208 started from BUF and ended at BUF_END. */
b775012e
LM
9209
9210static int
9211remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9212 struct bp_target_info *bp_tgt, char *buf,
9213 char *buf_end)
b775012e
LM
9214{
9215 struct agent_expr *aexpr = NULL;
9216 int i, ix;
b775012e
LM
9217
9218 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9219 return 0;
9220
9221 buf += strlen (buf);
bba74b36 9222 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9223 buf++;
9224
9225 /* Send conditions to the target and free the vector. */
9226 for (ix = 0;
9227 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9228 ix++)
9229 {
bba74b36 9230 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
9231 buf += strlen (buf);
9232 for (i = 0; i < aexpr->len; ++i)
9233 buf = pack_hex_byte (buf, aexpr->buf[i]);
9234 *buf = '\0';
9235 }
b775012e
LM
9236 return 0;
9237}
9238
d3ce09f5
SS
9239static void
9240remote_add_target_side_commands (struct gdbarch *gdbarch,
9241 struct bp_target_info *bp_tgt, char *buf)
9242{
9243 struct agent_expr *aexpr = NULL;
9244 int i, ix;
9245
9246 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9247 return;
9248
9249 buf += strlen (buf);
9250
9251 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9252 buf += strlen (buf);
9253
9254 /* Concatenate all the agent expressions that are commands into the
9255 cmds parameter. */
9256 for (ix = 0;
9257 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9258 ix++)
9259 {
9260 sprintf (buf, "X%x,", aexpr->len);
9261 buf += strlen (buf);
9262 for (i = 0; i < aexpr->len; ++i)
9263 buf = pack_hex_byte (buf, aexpr->buf[i]);
9264 *buf = '\0';
9265 }
d3ce09f5
SS
9266}
9267
8181d85f
DJ
9268/* Insert a breakpoint. On targets that have software breakpoint
9269 support, we ask the remote target to do the work; on targets
9270 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9271
9272static int
3db08215
MM
9273remote_insert_breakpoint (struct target_ops *ops,
9274 struct gdbarch *gdbarch,
a6d9a66e 9275 struct bp_target_info *bp_tgt)
c906108c 9276{
d471ea57
AC
9277 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9278 If it succeeds, then set the support to PACKET_ENABLE. If it
9279 fails, and the user has explicitly requested the Z support then
23860348 9280 report an error, otherwise, mark it disabled and go on. */
802188a7 9281
4082afcc 9282 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9283 {
0d5ed153 9284 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9285 struct remote_state *rs;
bba74b36 9286 char *p, *endbuf;
7c0f6dcc 9287 int bpsize;
4fff2411 9288
28439a30
PA
9289 /* Make sure the remote is pointing at the right process, if
9290 necessary. */
9291 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9292 set_general_process ();
9293
a1dcb23a 9294 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
9295
9296 rs = get_remote_state ();
9297 p = rs->buf;
bba74b36 9298 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9299
96baa820
JM
9300 *(p++) = 'Z';
9301 *(p++) = '0';
9302 *(p++) = ',';
7c0f6dcc 9303 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9304 p += hexnumstr (p, addr);
bba74b36 9305 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 9306
efcc2da7 9307 if (remote_supports_cond_breakpoints (ops))
bba74b36 9308 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9309
78eff0ec 9310 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9311 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9312
6d820c5c
DJ
9313 putpkt (rs->buf);
9314 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9315
6d820c5c 9316 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9317 {
d471ea57
AC
9318 case PACKET_ERROR:
9319 return -1;
9320 case PACKET_OK:
7c0f6dcc
JL
9321 bp_tgt->placed_address = addr;
9322 bp_tgt->placed_size = bpsize;
d471ea57
AC
9323 return 0;
9324 case PACKET_UNKNOWN:
9325 break;
96baa820
JM
9326 }
9327 }
c906108c 9328
0000e5cc
PA
9329 /* If this breakpoint has target-side commands but this stub doesn't
9330 support Z0 packets, throw error. */
9331 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9332 throw_error (NOT_SUPPORTED_ERROR, _("\
9333Target doesn't support breakpoints that have target side commands."));
9334
3db08215 9335 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9336}
9337
9338static int
3db08215
MM
9339remote_remove_breakpoint (struct target_ops *ops,
9340 struct gdbarch *gdbarch,
a6d9a66e 9341 struct bp_target_info *bp_tgt)
c906108c 9342{
8181d85f 9343 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9344 struct remote_state *rs = get_remote_state ();
96baa820 9345
4082afcc 9346 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9347 {
6d820c5c 9348 char *p = rs->buf;
bba74b36 9349 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9350
28439a30
PA
9351 /* Make sure the remote is pointing at the right process, if
9352 necessary. */
9353 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9354 set_general_process ();
9355
96baa820
JM
9356 *(p++) = 'z';
9357 *(p++) = '0';
9358 *(p++) = ',';
9359
8181d85f
DJ
9360 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9361 p += hexnumstr (p, addr);
bba74b36 9362 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9363
6d820c5c
DJ
9364 putpkt (rs->buf);
9365 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9366
6d820c5c 9367 return (rs->buf[0] == 'E');
96baa820
JM
9368 }
9369
3db08215 9370 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9371}
9372
f486487f 9373static enum Z_packet_type
d471ea57
AC
9374watchpoint_to_Z_packet (int type)
9375{
9376 switch (type)
9377 {
9378 case hw_write:
bb858e6a 9379 return Z_PACKET_WRITE_WP;
d471ea57
AC
9380 break;
9381 case hw_read:
bb858e6a 9382 return Z_PACKET_READ_WP;
d471ea57
AC
9383 break;
9384 case hw_access:
bb858e6a 9385 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9386 break;
9387 default:
8e65ff28 9388 internal_error (__FILE__, __LINE__,
e2e0b3e5 9389 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9390 }
9391}
9392
3c3bea1c 9393static int
f486487f
SM
9394remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9395 enum target_hw_bp_type type, struct expression *cond)
96baa820 9396{
d01949b6 9397 struct remote_state *rs = get_remote_state ();
bba74b36 9398 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9399 char *p;
d471ea57 9400 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9401
4082afcc 9402 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9403 return 1;
802188a7 9404
28439a30
PA
9405 /* Make sure the remote is pointing at the right process, if
9406 necessary. */
9407 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9408 set_general_process ();
9409
bba74b36 9410 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9411 p = strchr (rs->buf, '\0');
96baa820
JM
9412 addr = remote_address_masked (addr);
9413 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9414 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9415
6d820c5c
DJ
9416 putpkt (rs->buf);
9417 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9418
6d820c5c 9419 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9420 {
9421 case PACKET_ERROR:
d471ea57 9422 return -1;
85d721b8
PA
9423 case PACKET_UNKNOWN:
9424 return 1;
d471ea57
AC
9425 case PACKET_OK:
9426 return 0;
9427 }
8e65ff28 9428 internal_error (__FILE__, __LINE__,
e2e0b3e5 9429 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9430}
9431
283002cf
MR
9432static int
9433remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9434 CORE_ADDR start, int length)
9435{
9436 CORE_ADDR diff = remote_address_masked (addr - start);
9437
9438 return diff < length;
9439}
9440
d471ea57 9441
3c3bea1c 9442static int
f486487f
SM
9443remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9444 enum target_hw_bp_type type, struct expression *cond)
96baa820 9445{
d01949b6 9446 struct remote_state *rs = get_remote_state ();
bba74b36 9447 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9448 char *p;
d471ea57
AC
9449 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9450
4082afcc 9451 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9452 return -1;
802188a7 9453
28439a30
PA
9454 /* Make sure the remote is pointing at the right process, if
9455 necessary. */
9456 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9457 set_general_process ();
9458
bba74b36 9459 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9460 p = strchr (rs->buf, '\0');
96baa820
JM
9461 addr = remote_address_masked (addr);
9462 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9463 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9464 putpkt (rs->buf);
9465 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9466
6d820c5c 9467 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9468 {
9469 case PACKET_ERROR:
9470 case PACKET_UNKNOWN:
9471 return -1;
9472 case PACKET_OK:
9473 return 0;
9474 }
8e65ff28 9475 internal_error (__FILE__, __LINE__,
e2e0b3e5 9476 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9477}
9478
3c3bea1c 9479
501eef12 9480int remote_hw_watchpoint_limit = -1;
480a3f21 9481int remote_hw_watchpoint_length_limit = -1;
501eef12 9482int remote_hw_breakpoint_limit = -1;
d471ea57 9483
480a3f21 9484static int
31568a15
TT
9485remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9486 CORE_ADDR addr, int len)
480a3f21
PW
9487{
9488 if (remote_hw_watchpoint_length_limit == 0)
9489 return 0;
9490 else if (remote_hw_watchpoint_length_limit < 0)
9491 return 1;
9492 else if (len <= remote_hw_watchpoint_length_limit)
9493 return 1;
9494 else
9495 return 0;
9496}
9497
b9362cc7 9498static int
5461485a 9499remote_check_watch_resources (struct target_ops *self,
f486487f 9500 enum bptype type, int cnt, int ot)
96baa820 9501{
3c3bea1c
GS
9502 if (type == bp_hardware_breakpoint)
9503 {
9504 if (remote_hw_breakpoint_limit == 0)
9505 return 0;
501eef12
AC
9506 else if (remote_hw_breakpoint_limit < 0)
9507 return 1;
3c3bea1c
GS
9508 else if (cnt <= remote_hw_breakpoint_limit)
9509 return 1;
9510 }
9511 else
9512 {
9513 if (remote_hw_watchpoint_limit == 0)
9514 return 0;
501eef12
AC
9515 else if (remote_hw_watchpoint_limit < 0)
9516 return 1;
3c3bea1c
GS
9517 else if (ot)
9518 return -1;
9519 else if (cnt <= remote_hw_watchpoint_limit)
9520 return 1;
9521 }
9522 return -1;
9523}
9524
f7e6eed5
PA
9525/* The to_stopped_by_sw_breakpoint method of target remote. */
9526
9527static int
9528remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9529{
799a2abe 9530 struct thread_info *thread = inferior_thread ();
f7e6eed5 9531
799a2abe
PA
9532 return (thread->priv != NULL
9533 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9534}
9535
9536/* The to_supports_stopped_by_sw_breakpoint method of target
9537 remote. */
9538
9539static int
9540remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9541{
f7e6eed5
PA
9542 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9543}
9544
9545/* The to_stopped_by_hw_breakpoint method of target remote. */
9546
9547static int
9548remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9549{
799a2abe 9550 struct thread_info *thread = inferior_thread ();
f7e6eed5 9551
799a2abe
PA
9552 return (thread->priv != NULL
9553 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9554}
9555
9556/* The to_supports_stopped_by_hw_breakpoint method of target
9557 remote. */
9558
9559static int
9560remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9561{
f7e6eed5
PA
9562 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9563}
9564
b9362cc7 9565static int
6a109b6b 9566remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9567{
799a2abe 9568 struct thread_info *thread = inferior_thread ();
ee154bee 9569
799a2abe
PA
9570 return (thread->priv != NULL
9571 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9572}
9573
4aa7a7f5
JJ
9574static int
9575remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9576{
799a2abe 9577 struct thread_info *thread = inferior_thread ();
a744cf53 9578
799a2abe
PA
9579 if (thread->priv != NULL
9580 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9581 {
799a2abe
PA
9582 *addr_p = thread->priv->watch_data_address;
9583 return 1;
4aa7a7f5
JJ
9584 }
9585
799a2abe 9586 return 0;
3c3bea1c
GS
9587}
9588
9589
9590static int
23a26771 9591remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9592 struct bp_target_info *bp_tgt)
3c3bea1c 9593{
0d5ed153 9594 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9595 struct remote_state *rs;
bba74b36 9596 char *p, *endbuf;
dd61ec5c 9597 char *message;
0d5ed153 9598 int bpsize;
802188a7 9599
c8189ed1 9600 /* The length field should be set to the size of a breakpoint
8181d85f 9601 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9602
0d5ed153 9603 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9604
4082afcc 9605 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9606 return -1;
2bc416ba 9607
28439a30
PA
9608 /* Make sure the remote is pointing at the right process, if
9609 necessary. */
9610 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9611 set_general_process ();
9612
4fff2411
JZ
9613 rs = get_remote_state ();
9614 p = rs->buf;
bba74b36 9615 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9616
96baa820
JM
9617 *(p++) = 'Z';
9618 *(p++) = '1';
9619 *(p++) = ',';
802188a7 9620
0d5ed153 9621 addr = remote_address_masked (addr);
96baa820 9622 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9623 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9624
efcc2da7 9625 if (remote_supports_cond_breakpoints (self))
bba74b36 9626 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9627
78eff0ec 9628 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9629 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9630
6d820c5c
DJ
9631 putpkt (rs->buf);
9632 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9633
6d820c5c 9634 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9635 {
9636 case PACKET_ERROR:
dd61ec5c
MW
9637 if (rs->buf[1] == '.')
9638 {
9639 message = strchr (rs->buf + 2, '.');
9640 if (message)
0316657e 9641 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9642 }
9643 return -1;
d471ea57
AC
9644 case PACKET_UNKNOWN:
9645 return -1;
9646 case PACKET_OK:
0d5ed153
MR
9647 bp_tgt->placed_address = addr;
9648 bp_tgt->placed_size = bpsize;
d471ea57
AC
9649 return 0;
9650 }
8e65ff28 9651 internal_error (__FILE__, __LINE__,
e2e0b3e5 9652 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9653}
9654
d471ea57 9655
802188a7 9656static int
a64dc96c 9657remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9658 struct bp_target_info *bp_tgt)
96baa820 9659{
8181d85f 9660 CORE_ADDR addr;
d01949b6 9661 struct remote_state *rs = get_remote_state ();
6d820c5c 9662 char *p = rs->buf;
bba74b36 9663 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9664
4082afcc 9665 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9666 return -1;
802188a7 9667
28439a30
PA
9668 /* Make sure the remote is pointing at the right process, if
9669 necessary. */
9670 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9671 set_general_process ();
9672
96baa820
JM
9673 *(p++) = 'z';
9674 *(p++) = '1';
9675 *(p++) = ',';
802188a7 9676
8181d85f 9677 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9678 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9679 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9680
6d820c5c
DJ
9681 putpkt (rs->buf);
9682 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9683
6d820c5c 9684 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9685 {
9686 case PACKET_ERROR:
9687 case PACKET_UNKNOWN:
9688 return -1;
9689 case PACKET_OK:
9690 return 0;
9691 }
8e65ff28 9692 internal_error (__FILE__, __LINE__,
e2e0b3e5 9693 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9694}
96baa820 9695
4a5e7a5b
PA
9696/* Verify memory using the "qCRC:" request. */
9697
9698static int
9699remote_verify_memory (struct target_ops *ops,
9700 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9701{
9702 struct remote_state *rs = get_remote_state ();
9703 unsigned long host_crc, target_crc;
9704 char *tmp;
9705
936d2992
PA
9706 /* It doesn't make sense to use qCRC if the remote target is
9707 connected but not running. */
9708 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9709 {
9710 enum packet_result result;
28439a30 9711
936d2992
PA
9712 /* Make sure the remote is pointing at the right process. */
9713 set_general_process ();
4a5e7a5b 9714
936d2992
PA
9715 /* FIXME: assumes lma can fit into long. */
9716 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9717 (long) lma, (long) size);
9718 putpkt (rs->buf);
4a5e7a5b 9719
936d2992
PA
9720 /* Be clever; compute the host_crc before waiting for target
9721 reply. */
9722 host_crc = xcrc32 (data, size, 0xffffffff);
9723
9724 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9725
936d2992
PA
9726 result = packet_ok (rs->buf,
9727 &remote_protocol_packets[PACKET_qCRC]);
9728 if (result == PACKET_ERROR)
9729 return -1;
9730 else if (result == PACKET_OK)
9731 {
9732 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9733 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9734
936d2992
PA
9735 return (host_crc == target_crc);
9736 }
9737 }
4a5e7a5b 9738
936d2992 9739 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9740}
9741
c906108c
SS
9742/* compare-sections command
9743
9744 With no arguments, compares each loadable section in the exec bfd
9745 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9746 Useful for verifying the image on the target against the exec file. */
e514a9d6 9747
c906108c 9748static void
fba45db2 9749compare_sections_command (char *args, int from_tty)
c906108c
SS
9750{
9751 asection *s;
c906108c 9752 struct cleanup *old_chain;
948f8e3d 9753 gdb_byte *sectdata;
ce359b09 9754 const char *sectname;
c906108c
SS
9755 bfd_size_type size;
9756 bfd_vma lma;
9757 int matched = 0;
9758 int mismatched = 0;
4a5e7a5b 9759 int res;
95cf3b38 9760 int read_only = 0;
c906108c
SS
9761
9762 if (!exec_bfd)
8a3fe4f8 9763 error (_("command cannot be used without an exec file"));
c906108c 9764
28439a30
PA
9765 /* Make sure the remote is pointing at the right process. */
9766 set_general_process ();
9767
95cf3b38
DT
9768 if (args != NULL && strcmp (args, "-r") == 0)
9769 {
9770 read_only = 1;
9771 args = NULL;
9772 }
9773
c5aa993b 9774 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9775 {
9776 if (!(s->flags & SEC_LOAD))
0df8b418 9777 continue; /* Skip non-loadable section. */
c906108c 9778
95cf3b38
DT
9779 if (read_only && (s->flags & SEC_READONLY) == 0)
9780 continue; /* Skip writeable sections */
9781
2c500098 9782 size = bfd_get_section_size (s);
c906108c 9783 if (size == 0)
0df8b418 9784 continue; /* Skip zero-length section. */
c906108c 9785
ce359b09 9786 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9787 if (args && strcmp (args, sectname) != 0)
0df8b418 9788 continue; /* Not the section selected by user. */
c906108c 9789
0df8b418 9790 matched = 1; /* Do this section. */
c906108c 9791 lma = s->lma;
c906108c 9792
224c3ddb 9793 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9794 old_chain = make_cleanup (xfree, sectdata);
c906108c 9795 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9796
4a5e7a5b
PA
9797 res = target_verify_memory (sectdata, lma, size);
9798
9799 if (res == -1)
5af949e3 9800 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9801 paddress (target_gdbarch (), lma),
9802 paddress (target_gdbarch (), lma + size));
c906108c 9803
5af949e3 9804 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9805 paddress (target_gdbarch (), lma),
9806 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9807 if (res)
c906108c
SS
9808 printf_filtered ("matched.\n");
9809 else
c5aa993b
JM
9810 {
9811 printf_filtered ("MIS-MATCHED!\n");
9812 mismatched++;
9813 }
c906108c
SS
9814
9815 do_cleanups (old_chain);
9816 }
9817 if (mismatched > 0)
936d2992 9818 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9819the loaded file\n"));
c906108c 9820 if (args && !matched)
a3f17187 9821 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9822}
9823
0e7f50da
UW
9824/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9825 into remote target. The number of bytes written to the remote
9826 target is returned, or -1 for error. */
9827
9b409511 9828static enum target_xfer_status
0e7f50da
UW
9829remote_write_qxfer (struct target_ops *ops, const char *object_name,
9830 const char *annex, const gdb_byte *writebuf,
9b409511 9831 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9832 struct packet_config *packet)
9833{
9834 int i, buf_len;
9835 ULONGEST n;
0e7f50da
UW
9836 struct remote_state *rs = get_remote_state ();
9837 int max_size = get_memory_write_packet_size ();
9838
9839 if (packet->support == PACKET_DISABLE)
2ed4b548 9840 return TARGET_XFER_E_IO;
0e7f50da
UW
9841
9842 /* Insert header. */
9843 i = snprintf (rs->buf, max_size,
9844 "qXfer:%s:write:%s:%s:",
9845 object_name, annex ? annex : "",
9846 phex_nz (offset, sizeof offset));
9847 max_size -= (i + 1);
9848
9849 /* Escape as much data as fits into rs->buf. */
9850 buf_len = remote_escape_output
124e13d9 9851 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9852
9853 if (putpkt_binary (rs->buf, i + buf_len) < 0
9854 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9855 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9856 return TARGET_XFER_E_IO;
0e7f50da
UW
9857
9858 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9859
9860 *xfered_len = n;
9861 return TARGET_XFER_OK;
0e7f50da
UW
9862}
9863
0876f84a
DJ
9864/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9865 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9866 number of bytes read is returned, or 0 for EOF, or -1 for error.
9867 The number of bytes read may be less than LEN without indicating an
9868 EOF. PACKET is checked and updated to indicate whether the remote
9869 target supports this object. */
9870
9b409511 9871static enum target_xfer_status
0876f84a
DJ
9872remote_read_qxfer (struct target_ops *ops, const char *object_name,
9873 const char *annex,
9874 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9875 ULONGEST *xfered_len,
0876f84a
DJ
9876 struct packet_config *packet)
9877{
0876f84a 9878 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9879 LONGEST i, n, packet_len;
9880
9881 if (packet->support == PACKET_DISABLE)
2ed4b548 9882 return TARGET_XFER_E_IO;
0876f84a
DJ
9883
9884 /* Check whether we've cached an end-of-object packet that matches
9885 this request. */
8e88304f 9886 if (rs->finished_object)
0876f84a 9887 {
8e88304f
TT
9888 if (strcmp (object_name, rs->finished_object) == 0
9889 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9890 && offset == rs->finished_offset)
9b409511
YQ
9891 return TARGET_XFER_EOF;
9892
0876f84a
DJ
9893
9894 /* Otherwise, we're now reading something different. Discard
9895 the cache. */
8e88304f
TT
9896 xfree (rs->finished_object);
9897 xfree (rs->finished_annex);
9898 rs->finished_object = NULL;
9899 rs->finished_annex = NULL;
0876f84a
DJ
9900 }
9901
9902 /* Request only enough to fit in a single packet. The actual data
9903 may not, since we don't know how much of it will need to be escaped;
9904 the target is free to respond with slightly less data. We subtract
9905 five to account for the response type and the protocol frame. */
9906 n = min (get_remote_packet_size () - 5, len);
9907 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9908 object_name, annex ? annex : "",
9909 phex_nz (offset, sizeof offset),
9910 phex_nz (n, sizeof n));
9911 i = putpkt (rs->buf);
9912 if (i < 0)
2ed4b548 9913 return TARGET_XFER_E_IO;
0876f84a
DJ
9914
9915 rs->buf[0] = '\0';
9916 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9917 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9918 return TARGET_XFER_E_IO;
0876f84a
DJ
9919
9920 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9921 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9922
9923 /* 'm' means there is (or at least might be) more data after this
9924 batch. That does not make sense unless there's at least one byte
9925 of data in this reply. */
9926 if (rs->buf[0] == 'm' && packet_len == 1)
9927 error (_("Remote qXfer reply contained no data."));
9928
9929 /* Got some data. */
bc20a4af
PA
9930 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9931 packet_len - 1, readbuf, n);
0876f84a
DJ
9932
9933 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9934 or possibly empty. If we have the final block of a non-empty
9935 object, record this fact to bypass a subsequent partial read. */
9936 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9937 {
8e88304f
TT
9938 rs->finished_object = xstrdup (object_name);
9939 rs->finished_annex = xstrdup (annex ? annex : "");
9940 rs->finished_offset = offset + i;
0876f84a
DJ
9941 }
9942
9b409511
YQ
9943 if (i == 0)
9944 return TARGET_XFER_EOF;
9945 else
9946 {
9947 *xfered_len = i;
9948 return TARGET_XFER_OK;
9949 }
0876f84a
DJ
9950}
9951
9b409511 9952static enum target_xfer_status
4b8a223f 9953remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9954 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9955 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9956 ULONGEST *xfered_len)
c906108c 9957{
82f73884 9958 struct remote_state *rs;
c906108c 9959 int i;
6d820c5c 9960 char *p2;
1e3ff5ad 9961 char query_type;
124e13d9 9962 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9963
e6e4e701 9964 set_remote_traceframe ();
82f73884
PA
9965 set_general_thread (inferior_ptid);
9966
9967 rs = get_remote_state ();
9968
b2182ed2 9969 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9970 if (object == TARGET_OBJECT_MEMORY)
9971 {
2d717e4f
DJ
9972 /* If the remote target is connected but not running, we should
9973 pass this request down to a lower stratum (e.g. the executable
9974 file). */
9975 if (!target_has_execution)
9b409511 9976 return TARGET_XFER_EOF;
2d717e4f 9977
21e3b9b9 9978 if (writebuf != NULL)
124e13d9
SM
9979 return remote_write_bytes (offset, writebuf, len, unit_size,
9980 xfered_len);
21e3b9b9 9981 else
124e13d9
SM
9982 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9983 xfered_len);
21e3b9b9
DJ
9984 }
9985
0df8b418 9986 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9987 if (object == TARGET_OBJECT_SPU)
9988 {
9989 if (readbuf)
9990 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9991 xfered_len, &remote_protocol_packets
9992 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9993 else
9994 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9995 xfered_len, &remote_protocol_packets
9996 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9997 }
9998
4aa995e1
PA
9999 /* Handle extra signal info using qxfer packets. */
10000 if (object == TARGET_OBJECT_SIGNAL_INFO)
10001 {
10002 if (readbuf)
10003 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 10004 xfered_len, &remote_protocol_packets
4aa995e1
PA
10005 [PACKET_qXfer_siginfo_read]);
10006 else
3e43a32a 10007 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 10008 writebuf, offset, len, xfered_len,
4aa995e1
PA
10009 &remote_protocol_packets
10010 [PACKET_qXfer_siginfo_write]);
10011 }
10012
0fb4aa4b
PA
10013 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10014 {
10015 if (readbuf)
3e43a32a 10016 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 10017 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10018 &remote_protocol_packets
10019 [PACKET_qXfer_statictrace_read]);
10020 else
2ed4b548 10021 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10022 }
10023
a76d924d
DJ
10024 /* Only handle flash writes. */
10025 if (writebuf != NULL)
10026 {
a76d924d
DJ
10027 switch (object)
10028 {
10029 case TARGET_OBJECT_FLASH:
9b409511
YQ
10030 return remote_flash_write (ops, offset, len, xfered_len,
10031 writebuf);
a76d924d
DJ
10032
10033 default:
2ed4b548 10034 return TARGET_XFER_E_IO;
a76d924d
DJ
10035 }
10036 }
4b8a223f 10037
1e3ff5ad
AC
10038 /* Map pre-existing objects onto letters. DO NOT do this for new
10039 objects!!! Instead specify new query packets. */
10040 switch (object)
c906108c 10041 {
1e3ff5ad
AC
10042 case TARGET_OBJECT_AVR:
10043 query_type = 'R';
10044 break;
802188a7
RM
10045
10046 case TARGET_OBJECT_AUXV:
0876f84a
DJ
10047 gdb_assert (annex == NULL);
10048 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 10049 xfered_len,
0876f84a 10050 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10051
23181151
DJ
10052 case TARGET_OBJECT_AVAILABLE_FEATURES:
10053 return remote_read_qxfer
9b409511 10054 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10055 &remote_protocol_packets[PACKET_qXfer_features]);
10056
cfa9d6d9
DJ
10057 case TARGET_OBJECT_LIBRARIES:
10058 return remote_read_qxfer
9b409511 10059 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10060 &remote_protocol_packets[PACKET_qXfer_libraries]);
10061
2268b414
JK
10062 case TARGET_OBJECT_LIBRARIES_SVR4:
10063 return remote_read_qxfer
9b409511 10064 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10065 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10066
fd79ecee
DJ
10067 case TARGET_OBJECT_MEMORY_MAP:
10068 gdb_assert (annex == NULL);
10069 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 10070 xfered_len,
fd79ecee
DJ
10071 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10072
07e059b5
VP
10073 case TARGET_OBJECT_OSDATA:
10074 /* Should only get here if we're connected. */
5d93a237 10075 gdb_assert (rs->remote_desc);
07e059b5 10076 return remote_read_qxfer
9b409511 10077 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10078 &remote_protocol_packets[PACKET_qXfer_osdata]);
10079
dc146f7c
VP
10080 case TARGET_OBJECT_THREADS:
10081 gdb_assert (annex == NULL);
10082 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10083 xfered_len,
dc146f7c
VP
10084 &remote_protocol_packets[PACKET_qXfer_threads]);
10085
b3b9301e
PA
10086 case TARGET_OBJECT_TRACEFRAME_INFO:
10087 gdb_assert (annex == NULL);
10088 return remote_read_qxfer
9b409511 10089 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10090 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10091
10092 case TARGET_OBJECT_FDPIC:
10093 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10094 xfered_len,
78d85199 10095 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10096
10097 case TARGET_OBJECT_OPENVMS_UIB:
10098 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10099 xfered_len,
169081d0
TG
10100 &remote_protocol_packets[PACKET_qXfer_uib]);
10101
9accd112
MM
10102 case TARGET_OBJECT_BTRACE:
10103 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10104 xfered_len,
9accd112
MM
10105 &remote_protocol_packets[PACKET_qXfer_btrace]);
10106
f4abbc16
MM
10107 case TARGET_OBJECT_BTRACE_CONF:
10108 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10109 len, xfered_len,
10110 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10111
c78fa86a
GB
10112 case TARGET_OBJECT_EXEC_FILE:
10113 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10114 len, xfered_len,
10115 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10116
1e3ff5ad 10117 default:
2ed4b548 10118 return TARGET_XFER_E_IO;
c906108c
SS
10119 }
10120
0df8b418 10121 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10122 large enough let the caller deal with it. */
ea9c271d 10123 if (len < get_remote_packet_size ())
2ed4b548 10124 return TARGET_XFER_E_IO;
ea9c271d 10125 len = get_remote_packet_size ();
1e3ff5ad 10126
23860348 10127 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10128 if (!rs->remote_desc)
8a3fe4f8 10129 error (_("remote query is only available after target open"));
c906108c 10130
1e3ff5ad 10131 gdb_assert (annex != NULL);
4b8a223f 10132 gdb_assert (readbuf != NULL);
c906108c 10133
6d820c5c 10134 p2 = rs->buf;
c906108c
SS
10135 *p2++ = 'q';
10136 *p2++ = query_type;
10137
23860348
MS
10138 /* We used one buffer char for the remote protocol q command and
10139 another for the query type. As the remote protocol encapsulation
10140 uses 4 chars plus one extra in case we are debugging
10141 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10142 string. */
c906108c 10143 i = 0;
ea9c271d 10144 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10145 {
1e3ff5ad
AC
10146 /* Bad caller may have sent forbidden characters. */
10147 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10148 *p2++ = annex[i];
c906108c
SS
10149 i++;
10150 }
1e3ff5ad
AC
10151 *p2 = '\0';
10152 gdb_assert (annex[i] == '\0');
c906108c 10153
6d820c5c 10154 i = putpkt (rs->buf);
c5aa993b 10155 if (i < 0)
2ed4b548 10156 return TARGET_XFER_E_IO;
c906108c 10157
6d820c5c
DJ
10158 getpkt (&rs->buf, &rs->buf_size, 0);
10159 strcpy ((char *) readbuf, rs->buf);
c906108c 10160
9b409511
YQ
10161 *xfered_len = strlen ((char *) readbuf);
10162 return TARGET_XFER_OK;
c906108c
SS
10163}
10164
08388c79
DE
10165static int
10166remote_search_memory (struct target_ops* ops,
10167 CORE_ADDR start_addr, ULONGEST search_space_len,
10168 const gdb_byte *pattern, ULONGEST pattern_len,
10169 CORE_ADDR *found_addrp)
10170{
f5656ead 10171 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10172 struct remote_state *rs = get_remote_state ();
10173 int max_size = get_memory_write_packet_size ();
10174 struct packet_config *packet =
10175 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10176 /* Number of packet bytes used to encode the pattern;
10177 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10178 int escaped_pattern_len;
0df8b418 10179 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10180 int used_pattern_len;
10181 int i;
10182 int found;
10183 ULONGEST found_addr;
10184
10185 /* Don't go to the target if we don't have to.
10186 This is done before checking packet->support to avoid the possibility that
10187 a success for this edge case means the facility works in general. */
10188 if (pattern_len > search_space_len)
10189 return 0;
10190 if (pattern_len == 0)
10191 {
10192 *found_addrp = start_addr;
10193 return 1;
10194 }
10195
10196 /* If we already know the packet isn't supported, fall back to the simple
10197 way of searching memory. */
10198
4082afcc 10199 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10200 {
10201 /* Target doesn't provided special support, fall back and use the
10202 standard support (copy memory and do the search here). */
10203 return simple_search_memory (ops, start_addr, search_space_len,
10204 pattern, pattern_len, found_addrp);
10205 }
10206
28439a30
PA
10207 /* Make sure the remote is pointing at the right process. */
10208 set_general_process ();
10209
08388c79
DE
10210 /* Insert header. */
10211 i = snprintf (rs->buf, max_size,
10212 "qSearch:memory:%s;%s;",
5af949e3 10213 phex_nz (start_addr, addr_size),
08388c79
DE
10214 phex_nz (search_space_len, sizeof (search_space_len)));
10215 max_size -= (i + 1);
10216
10217 /* Escape as much data as fits into rs->buf. */
10218 escaped_pattern_len =
124e13d9 10219 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10220 &used_pattern_len, max_size);
10221
10222 /* Bail if the pattern is too large. */
10223 if (used_pattern_len != pattern_len)
9b20d036 10224 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10225
10226 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10227 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10228 || packet_ok (rs->buf, packet) != PACKET_OK)
10229 {
10230 /* The request may not have worked because the command is not
10231 supported. If so, fall back to the simple way. */
10232 if (packet->support == PACKET_DISABLE)
10233 {
10234 return simple_search_memory (ops, start_addr, search_space_len,
10235 pattern, pattern_len, found_addrp);
10236 }
10237 return -1;
10238 }
10239
10240 if (rs->buf[0] == '0')
10241 found = 0;
10242 else if (rs->buf[0] == '1')
10243 {
10244 found = 1;
10245 if (rs->buf[1] != ',')
10e0fa18 10246 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10247 unpack_varlen_hex (rs->buf + 2, &found_addr);
10248 *found_addrp = found_addr;
10249 }
10250 else
10e0fa18 10251 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10252
10253 return found;
10254}
10255
96baa820 10256static void
a30bf1f1 10257remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10258 struct ui_file *outbuf)
96baa820 10259{
d01949b6 10260 struct remote_state *rs = get_remote_state ();
2e9f7625 10261 char *p = rs->buf;
96baa820 10262
5d93a237 10263 if (!rs->remote_desc)
8a3fe4f8 10264 error (_("remote rcmd is only available after target open"));
96baa820 10265
23860348 10266 /* Send a NULL command across as an empty command. */
7be570e7
JM
10267 if (command == NULL)
10268 command = "";
10269
23860348 10270 /* The query prefix. */
2e9f7625
DJ
10271 strcpy (rs->buf, "qRcmd,");
10272 p = strchr (rs->buf, '\0');
96baa820 10273
3e43a32a
MS
10274 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10275 > get_remote_packet_size ())
8a3fe4f8 10276 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10277
23860348 10278 /* Encode the actual command. */
a30bf1f1 10279 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10280
6d820c5c 10281 if (putpkt (rs->buf) < 0)
8a3fe4f8 10282 error (_("Communication problem with target."));
96baa820
JM
10283
10284 /* get/display the response */
10285 while (1)
10286 {
2e9f7625
DJ
10287 char *buf;
10288
00bf0b85 10289 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10290 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10291 rs->buf[0] = '\0';
5b37825d
PW
10292 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10293 {
10294 /* Timeout. Continue to (try to) read responses.
10295 This is better than stopping with an error, assuming the stub
10296 is still executing the (long) monitor command.
10297 If needed, the user can interrupt gdb using C-c, obtaining
10298 an effect similar to stop on timeout. */
10299 continue;
10300 }
2e9f7625 10301 buf = rs->buf;
96baa820 10302 if (buf[0] == '\0')
8a3fe4f8 10303 error (_("Target does not support this command."));
96baa820
JM
10304 if (buf[0] == 'O' && buf[1] != 'K')
10305 {
23860348 10306 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10307 continue;
10308 }
10309 if (strcmp (buf, "OK") == 0)
10310 break;
7be570e7
JM
10311 if (strlen (buf) == 3 && buf[0] == 'E'
10312 && isdigit (buf[1]) && isdigit (buf[2]))
10313 {
8a3fe4f8 10314 error (_("Protocol error with Rcmd"));
7be570e7 10315 }
96baa820
JM
10316 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10317 {
10318 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10319
96baa820
JM
10320 fputc_unfiltered (c, outbuf);
10321 }
10322 break;
10323 }
10324}
10325
fd79ecee
DJ
10326static VEC(mem_region_s) *
10327remote_memory_map (struct target_ops *ops)
10328{
10329 VEC(mem_region_s) *result = NULL;
10330 char *text = target_read_stralloc (&current_target,
10331 TARGET_OBJECT_MEMORY_MAP, NULL);
10332
10333 if (text)
10334 {
10335 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10336
fd79ecee
DJ
10337 result = parse_memory_map (text);
10338 do_cleanups (back_to);
10339 }
10340
10341 return result;
10342}
10343
c906108c 10344static void
fba45db2 10345packet_command (char *args, int from_tty)
c906108c 10346{
d01949b6 10347 struct remote_state *rs = get_remote_state ();
c906108c 10348
5d93a237 10349 if (!rs->remote_desc)
8a3fe4f8 10350 error (_("command can only be used with remote target"));
c906108c 10351
c5aa993b 10352 if (!args)
8a3fe4f8 10353 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10354
10355 puts_filtered ("sending: ");
10356 print_packet (args);
10357 puts_filtered ("\n");
10358 putpkt (args);
10359
6d820c5c 10360 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10361 puts_filtered ("received: ");
6d820c5c 10362 print_packet (rs->buf);
c906108c
SS
10363 puts_filtered ("\n");
10364}
10365
10366#if 0
23860348 10367/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10368
a14ed312 10369static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10370
a14ed312 10371static void threadset_test_cmd (char *cmd, int tty);
c906108c 10372
a14ed312 10373static void threadalive_test (char *cmd, int tty);
c906108c 10374
a14ed312 10375static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10376
23860348 10377int get_and_display_threadinfo (threadref *ref);
c906108c 10378
a14ed312 10379static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10380
23860348 10381static int thread_display_step (threadref *ref, void *context);
c906108c 10382
a14ed312 10383static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10384
a14ed312 10385static void init_remote_threadtests (void);
c906108c 10386
23860348 10387#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10388
10389static void
fba45db2 10390threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10391{
10392 int sample_thread = SAMPLE_THREAD;
10393
a3f17187 10394 printf_filtered (_("Remote threadset test\n"));
79d7f229 10395 set_general_thread (sample_thread);
c906108c
SS
10396}
10397
10398
10399static void
fba45db2 10400threadalive_test (char *cmd, int tty)
c906108c
SS
10401{
10402 int sample_thread = SAMPLE_THREAD;
79d7f229 10403 int pid = ptid_get_pid (inferior_ptid);
ba348170 10404 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10405
79d7f229 10406 if (remote_thread_alive (ptid))
c906108c
SS
10407 printf_filtered ("PASS: Thread alive test\n");
10408 else
10409 printf_filtered ("FAIL: Thread alive test\n");
10410}
10411
23860348 10412void output_threadid (char *title, threadref *ref);
c906108c
SS
10413
10414void
fba45db2 10415output_threadid (char *title, threadref *ref)
c906108c
SS
10416{
10417 char hexid[20];
10418
23860348 10419 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10420 hexid[16] = 0;
10421 printf_filtered ("%s %s\n", title, (&hexid[0]));
10422}
10423
10424static void
fba45db2 10425threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10426{
10427 int startflag = 1;
10428 threadref nextthread;
10429 int done, result_count;
10430 threadref threadlist[3];
10431
10432 printf_filtered ("Remote Threadlist test\n");
10433 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10434 &result_count, &threadlist[0]))
10435 printf_filtered ("FAIL: threadlist test\n");
10436 else
10437 {
10438 threadref *scan = threadlist;
10439 threadref *limit = scan + result_count;
10440
10441 while (scan < limit)
10442 output_threadid (" thread ", scan++);
10443 }
10444}
10445
10446void
fba45db2 10447display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10448{
10449 output_threadid ("Threadid: ", &info->threadid);
10450 printf_filtered ("Name: %s\n ", info->shortname);
10451 printf_filtered ("State: %s\n", info->display);
10452 printf_filtered ("other: %s\n\n", info->more_display);
10453}
10454
10455int
fba45db2 10456get_and_display_threadinfo (threadref *ref)
c906108c
SS
10457{
10458 int result;
10459 int set;
10460 struct gdb_ext_thread_info threadinfo;
10461
10462 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10463 | TAG_MOREDISPLAY | TAG_DISPLAY;
10464 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10465 display_thread_info (&threadinfo);
10466 return result;
10467}
10468
10469static void
fba45db2 10470threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10471{
10472 int athread = SAMPLE_THREAD;
10473 threadref thread;
10474 int set;
10475
10476 int_to_threadref (&thread, athread);
10477 printf_filtered ("Remote Threadinfo test\n");
10478 if (!get_and_display_threadinfo (&thread))
10479 printf_filtered ("FAIL cannot get thread info\n");
10480}
10481
10482static int
fba45db2 10483thread_display_step (threadref *ref, void *context)
c906108c
SS
10484{
10485 /* output_threadid(" threadstep ",ref); *//* simple test */
10486 return get_and_display_threadinfo (ref);
10487}
10488
10489static void
fba45db2 10490threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10491{
10492 printf_filtered ("Remote Threadlist update test\n");
10493 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10494}
10495
10496static void
10497init_remote_threadtests (void)
10498{
3e43a32a
MS
10499 add_com ("tlist", class_obscure, threadlist_test_cmd,
10500 _("Fetch and print the remote list of "
10501 "thread identifiers, one pkt only"));
c906108c 10502 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10503 _("Fetch and display info about one thread"));
c906108c 10504 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10505 _("Test setting to a different thread"));
c906108c 10506 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10507 _("Iterate through updating all remote thread info"));
c906108c 10508 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10509 _(" Remote thread alive test "));
c906108c
SS
10510}
10511
10512#endif /* 0 */
10513
f3fb8c85
MS
10514/* Convert a thread ID to a string. Returns the string in a static
10515 buffer. */
10516
10517static char *
117de6a9 10518remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10519{
79d7f229 10520 static char buf[64];
82f73884 10521 struct remote_state *rs = get_remote_state ();
f3fb8c85 10522
7cee1e54
PA
10523 if (ptid_equal (ptid, null_ptid))
10524 return normal_pid_to_str (ptid);
10525 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10526 {
10527 /* Printing an inferior target id. */
10528
10529 /* When multi-process extensions are off, there's no way in the
10530 remote protocol to know the remote process id, if there's any
10531 at all. There's one exception --- when we're connected with
10532 target extended-remote, and we manually attached to a process
10533 with "attach PID". We don't record anywhere a flag that
10534 allows us to distinguish that case from the case of
10535 connecting with extended-remote and the stub already being
10536 attached to a process, and reporting yes to qAttached, hence
10537 no smart special casing here. */
10538 if (!remote_multi_process_p (rs))
10539 {
10540 xsnprintf (buf, sizeof buf, "Remote target");
10541 return buf;
10542 }
10543
10544 return normal_pid_to_str (ptid);
82f73884 10545 }
ecd0ada5 10546 else
79d7f229 10547 {
ecd0ada5
PA
10548 if (ptid_equal (magic_null_ptid, ptid))
10549 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 10550 else if (remote_multi_process_p (rs))
de0d863e
DB
10551 if (ptid_get_lwp (ptid) == 0)
10552 return normal_pid_to_str (ptid);
10553 else
10554 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10555 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10556 else
10557 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10558 ptid_get_lwp (ptid));
79d7f229
PA
10559 return buf;
10560 }
f3fb8c85
MS
10561}
10562
38691318
KB
10563/* Get the address of the thread local variable in OBJFILE which is
10564 stored at OFFSET within the thread local storage for thread PTID. */
10565
10566static CORE_ADDR
117de6a9
PA
10567remote_get_thread_local_address (struct target_ops *ops,
10568 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10569{
4082afcc 10570 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10571 {
10572 struct remote_state *rs = get_remote_state ();
6d820c5c 10573 char *p = rs->buf;
82f73884 10574 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10575 enum packet_result result;
38691318
KB
10576
10577 strcpy (p, "qGetTLSAddr:");
10578 p += strlen (p);
82f73884 10579 p = write_ptid (p, endp, ptid);
38691318
KB
10580 *p++ = ',';
10581 p += hexnumstr (p, offset);
10582 *p++ = ',';
10583 p += hexnumstr (p, lm);
10584 *p++ = '\0';
10585
6d820c5c
DJ
10586 putpkt (rs->buf);
10587 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10588 result = packet_ok (rs->buf,
10589 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10590 if (result == PACKET_OK)
38691318
KB
10591 {
10592 ULONGEST result;
10593
6d820c5c 10594 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10595 return result;
10596 }
571dd617 10597 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10598 throw_error (TLS_GENERIC_ERROR,
10599 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10600 else
109c3e39
AC
10601 throw_error (TLS_GENERIC_ERROR,
10602 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10603 }
10604 else
109c3e39
AC
10605 throw_error (TLS_GENERIC_ERROR,
10606 _("TLS not supported or disabled on this target"));
38691318
KB
10607 /* Not reached. */
10608 return 0;
10609}
10610
711e434b
PM
10611/* Provide thread local base, i.e. Thread Information Block address.
10612 Returns 1 if ptid is found and thread_local_base is non zero. */
10613
70221824 10614static int
bd7ae0f5 10615remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10616{
4082afcc 10617 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10618 {
10619 struct remote_state *rs = get_remote_state ();
10620 char *p = rs->buf;
10621 char *endp = rs->buf + get_remote_packet_size ();
10622 enum packet_result result;
10623
10624 strcpy (p, "qGetTIBAddr:");
10625 p += strlen (p);
10626 p = write_ptid (p, endp, ptid);
10627 *p++ = '\0';
10628
10629 putpkt (rs->buf);
10630 getpkt (&rs->buf, &rs->buf_size, 0);
10631 result = packet_ok (rs->buf,
10632 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10633 if (result == PACKET_OK)
10634 {
10635 ULONGEST result;
10636
10637 unpack_varlen_hex (rs->buf, &result);
10638 if (addr)
10639 *addr = (CORE_ADDR) result;
10640 return 1;
10641 }
10642 else if (result == PACKET_UNKNOWN)
10643 error (_("Remote target doesn't support qGetTIBAddr packet"));
10644 else
10645 error (_("Remote target failed to process qGetTIBAddr request"));
10646 }
10647 else
10648 error (_("qGetTIBAddr not supported or disabled on this target"));
10649 /* Not reached. */
10650 return 0;
10651}
10652
29709017
DJ
10653/* Support for inferring a target description based on the current
10654 architecture and the size of a 'g' packet. While the 'g' packet
10655 can have any size (since optional registers can be left off the
10656 end), some sizes are easily recognizable given knowledge of the
10657 approximate architecture. */
10658
10659struct remote_g_packet_guess
10660{
10661 int bytes;
10662 const struct target_desc *tdesc;
10663};
10664typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10665DEF_VEC_O(remote_g_packet_guess_s);
10666
10667struct remote_g_packet_data
10668{
10669 VEC(remote_g_packet_guess_s) *guesses;
10670};
10671
10672static struct gdbarch_data *remote_g_packet_data_handle;
10673
10674static void *
10675remote_g_packet_data_init (struct obstack *obstack)
10676{
10677 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10678}
10679
10680void
10681register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10682 const struct target_desc *tdesc)
10683{
10684 struct remote_g_packet_data *data
19ba03f4
SM
10685 = ((struct remote_g_packet_data *)
10686 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10687 struct remote_g_packet_guess new_guess, *guess;
10688 int ix;
10689
10690 gdb_assert (tdesc != NULL);
10691
10692 for (ix = 0;
10693 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10694 ix++)
10695 if (guess->bytes == bytes)
10696 internal_error (__FILE__, __LINE__,
9b20d036 10697 _("Duplicate g packet description added for size %d"),
29709017
DJ
10698 bytes);
10699
10700 new_guess.bytes = bytes;
10701 new_guess.tdesc = tdesc;
10702 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10703}
10704
d962ef82
DJ
10705/* Return 1 if remote_read_description would do anything on this target
10706 and architecture, 0 otherwise. */
10707
10708static int
10709remote_read_description_p (struct target_ops *target)
10710{
10711 struct remote_g_packet_data *data
19ba03f4
SM
10712 = ((struct remote_g_packet_data *)
10713 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10714
10715 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10716 return 1;
10717
10718 return 0;
10719}
10720
29709017
DJ
10721static const struct target_desc *
10722remote_read_description (struct target_ops *target)
10723{
10724 struct remote_g_packet_data *data
19ba03f4
SM
10725 = ((struct remote_g_packet_data *)
10726 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10727
d962ef82
DJ
10728 /* Do not try this during initial connection, when we do not know
10729 whether there is a running but stopped thread. */
10730 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10731 return target->beneath->to_read_description (target->beneath);
d962ef82 10732
29709017
DJ
10733 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10734 {
10735 struct remote_g_packet_guess *guess;
10736 int ix;
10737 int bytes = send_g_packet ();
10738
10739 for (ix = 0;
10740 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10741 ix++)
10742 if (guess->bytes == bytes)
10743 return guess->tdesc;
10744
10745 /* We discard the g packet. A minor optimization would be to
10746 hold on to it, and fill the register cache once we have selected
10747 an architecture, but it's too tricky to do safely. */
10748 }
10749
2117c711 10750 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10751}
10752
a6b151f1
DJ
10753/* Remote file transfer support. This is host-initiated I/O, not
10754 target-initiated; for target-initiated, see remote-fileio.c. */
10755
10756/* If *LEFT is at least the length of STRING, copy STRING to
10757 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10758 decrease *LEFT. Otherwise raise an error. */
10759
10760static void
10761remote_buffer_add_string (char **buffer, int *left, char *string)
10762{
10763 int len = strlen (string);
10764
10765 if (len > *left)
10766 error (_("Packet too long for target."));
10767
10768 memcpy (*buffer, string, len);
10769 *buffer += len;
10770 *left -= len;
10771
10772 /* NUL-terminate the buffer as a convenience, if there is
10773 room. */
10774 if (*left)
10775 **buffer = '\0';
10776}
10777
10778/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10779 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10780 decrease *LEFT. Otherwise raise an error. */
10781
10782static void
10783remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10784 int len)
10785{
10786 if (2 * len > *left)
10787 error (_("Packet too long for target."));
10788
10789 bin2hex (bytes, *buffer, len);
10790 *buffer += 2 * len;
10791 *left -= 2 * len;
10792
10793 /* NUL-terminate the buffer as a convenience, if there is
10794 room. */
10795 if (*left)
10796 **buffer = '\0';
10797}
10798
10799/* If *LEFT is large enough, convert VALUE to hex and add it to
10800 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10801 decrease *LEFT. Otherwise raise an error. */
10802
10803static void
10804remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10805{
10806 int len = hexnumlen (value);
10807
10808 if (len > *left)
10809 error (_("Packet too long for target."));
10810
10811 hexnumstr (*buffer, value);
10812 *buffer += len;
10813 *left -= len;
10814
10815 /* NUL-terminate the buffer as a convenience, if there is
10816 room. */
10817 if (*left)
10818 **buffer = '\0';
10819}
10820
10821/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10822 value, *REMOTE_ERRNO to the remote error number or zero if none
10823 was included, and *ATTACHMENT to point to the start of the annex
10824 if any. The length of the packet isn't needed here; there may
10825 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10826
10827 Return 0 if the packet could be parsed, -1 if it could not. If
10828 -1 is returned, the other variables may not be initialized. */
10829
10830static int
10831remote_hostio_parse_result (char *buffer, int *retcode,
10832 int *remote_errno, char **attachment)
10833{
10834 char *p, *p2;
10835
10836 *remote_errno = 0;
10837 *attachment = NULL;
10838
10839 if (buffer[0] != 'F')
10840 return -1;
10841
10842 errno = 0;
10843 *retcode = strtol (&buffer[1], &p, 16);
10844 if (errno != 0 || p == &buffer[1])
10845 return -1;
10846
10847 /* Check for ",errno". */
10848 if (*p == ',')
10849 {
10850 errno = 0;
10851 *remote_errno = strtol (p + 1, &p2, 16);
10852 if (errno != 0 || p + 1 == p2)
10853 return -1;
10854 p = p2;
10855 }
10856
10857 /* Check for ";attachment". If there is no attachment, the
10858 packet should end here. */
10859 if (*p == ';')
10860 {
10861 *attachment = p + 1;
10862 return 0;
10863 }
10864 else if (*p == '\0')
10865 return 0;
10866 else
10867 return -1;
10868}
10869
10870/* Send a prepared I/O packet to the target and read its response.
10871 The prepared packet is in the global RS->BUF before this function
10872 is called, and the answer is there when we return.
10873
10874 COMMAND_BYTES is the length of the request to send, which may include
10875 binary data. WHICH_PACKET is the packet configuration to check
10876 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10877 is set to the error number and -1 is returned. Otherwise the value
10878 returned by the function is returned.
10879
10880 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10881 attachment is expected; an error will be reported if there's a
10882 mismatch. If one is found, *ATTACHMENT will be set to point into
10883 the packet buffer and *ATTACHMENT_LEN will be set to the
10884 attachment's length. */
10885
10886static int
10887remote_hostio_send_command (int command_bytes, int which_packet,
10888 int *remote_errno, char **attachment,
10889 int *attachment_len)
10890{
10891 struct remote_state *rs = get_remote_state ();
10892 int ret, bytes_read;
10893 char *attachment_tmp;
10894
5d93a237 10895 if (!rs->remote_desc
4082afcc 10896 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10897 {
10898 *remote_errno = FILEIO_ENOSYS;
10899 return -1;
10900 }
10901
10902 putpkt_binary (rs->buf, command_bytes);
10903 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10904
10905 /* If it timed out, something is wrong. Don't try to parse the
10906 buffer. */
10907 if (bytes_read < 0)
10908 {
10909 *remote_errno = FILEIO_EINVAL;
10910 return -1;
10911 }
10912
10913 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10914 {
10915 case PACKET_ERROR:
10916 *remote_errno = FILEIO_EINVAL;
10917 return -1;
10918 case PACKET_UNKNOWN:
10919 *remote_errno = FILEIO_ENOSYS;
10920 return -1;
10921 case PACKET_OK:
10922 break;
10923 }
10924
10925 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10926 &attachment_tmp))
10927 {
10928 *remote_errno = FILEIO_EINVAL;
10929 return -1;
10930 }
10931
10932 /* Make sure we saw an attachment if and only if we expected one. */
10933 if ((attachment_tmp == NULL && attachment != NULL)
10934 || (attachment_tmp != NULL && attachment == NULL))
10935 {
10936 *remote_errno = FILEIO_EINVAL;
10937 return -1;
10938 }
10939
10940 /* If an attachment was found, it must point into the packet buffer;
10941 work out how many bytes there were. */
10942 if (attachment_tmp != NULL)
10943 {
10944 *attachment = attachment_tmp;
10945 *attachment_len = bytes_read - (*attachment - rs->buf);
10946 }
10947
10948 return ret;
10949}
10950
80152258
PA
10951/* Invalidate the readahead cache. */
10952
10953static void
10954readahead_cache_invalidate (void)
10955{
10956 struct remote_state *rs = get_remote_state ();
10957
10958 rs->readahead_cache.fd = -1;
10959}
10960
10961/* Invalidate the readahead cache if it is holding data for FD. */
10962
10963static void
10964readahead_cache_invalidate_fd (int fd)
10965{
10966 struct remote_state *rs = get_remote_state ();
10967
10968 if (rs->readahead_cache.fd == fd)
10969 rs->readahead_cache.fd = -1;
10970}
10971
15a201c8
GB
10972/* Set the filesystem remote_hostio functions that take FILENAME
10973 arguments will use. Return 0 on success, or -1 if an error
10974 occurs (and set *REMOTE_ERRNO). */
10975
10976static int
10977remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10978{
10979 struct remote_state *rs = get_remote_state ();
10980 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10981 char *p = rs->buf;
10982 int left = get_remote_packet_size () - 1;
10983 char arg[9];
10984 int ret;
10985
10986 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10987 return 0;
10988
10989 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10990 return 0;
10991
10992 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10993
10994 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10995 remote_buffer_add_string (&p, &left, arg);
10996
10997 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10998 remote_errno, NULL, NULL);
10999
11000 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11001 return 0;
11002
11003 if (ret == 0)
11004 rs->fs_pid = required_pid;
11005
11006 return ret;
11007}
11008
12e2a5fd 11009/* Implementation of to_fileio_open. */
a6b151f1
DJ
11010
11011static int
cd897586 11012remote_hostio_open (struct target_ops *self,
07c138c8 11013 struct inferior *inf, const char *filename,
4313b8c0
GB
11014 int flags, int mode, int warn_if_slow,
11015 int *remote_errno)
a6b151f1
DJ
11016{
11017 struct remote_state *rs = get_remote_state ();
11018 char *p = rs->buf;
11019 int left = get_remote_packet_size () - 1;
11020
4313b8c0
GB
11021 if (warn_if_slow)
11022 {
11023 static int warning_issued = 0;
11024
11025 printf_unfiltered (_("Reading %s from remote target...\n"),
11026 filename);
11027
11028 if (!warning_issued)
11029 {
11030 warning (_("File transfers from remote targets can be slow."
11031 " Use \"set sysroot\" to access files locally"
11032 " instead."));
11033 warning_issued = 1;
11034 }
11035 }
11036
15a201c8
GB
11037 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11038 return -1;
11039
a6b151f1
DJ
11040 remote_buffer_add_string (&p, &left, "vFile:open:");
11041
11042 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11043 strlen (filename));
11044 remote_buffer_add_string (&p, &left, ",");
11045
11046 remote_buffer_add_int (&p, &left, flags);
11047 remote_buffer_add_string (&p, &left, ",");
11048
11049 remote_buffer_add_int (&p, &left, mode);
11050
11051 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11052 remote_errno, NULL, NULL);
11053}
11054
12e2a5fd 11055/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11056
11057static int
0d866f62
TT
11058remote_hostio_pwrite (struct target_ops *self,
11059 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11060 ULONGEST offset, int *remote_errno)
11061{
11062 struct remote_state *rs = get_remote_state ();
11063 char *p = rs->buf;
11064 int left = get_remote_packet_size ();
11065 int out_len;
11066
80152258
PA
11067 readahead_cache_invalidate_fd (fd);
11068
a6b151f1
DJ
11069 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11070
11071 remote_buffer_add_int (&p, &left, fd);
11072 remote_buffer_add_string (&p, &left, ",");
11073
11074 remote_buffer_add_int (&p, &left, offset);
11075 remote_buffer_add_string (&p, &left, ",");
11076
124e13d9 11077 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11078 get_remote_packet_size () - (p - rs->buf));
11079
11080 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11081 remote_errno, NULL, NULL);
11082}
11083
80152258
PA
11084/* Helper for the implementation of to_fileio_pread. Read the file
11085 from the remote side with vFile:pread. */
a6b151f1
DJ
11086
11087static int
80152258
PA
11088remote_hostio_pread_vFile (struct target_ops *self,
11089 int fd, gdb_byte *read_buf, int len,
11090 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11091{
11092 struct remote_state *rs = get_remote_state ();
11093 char *p = rs->buf;
11094 char *attachment;
11095 int left = get_remote_packet_size ();
11096 int ret, attachment_len;
11097 int read_len;
11098
11099 remote_buffer_add_string (&p, &left, "vFile:pread:");
11100
11101 remote_buffer_add_int (&p, &left, fd);
11102 remote_buffer_add_string (&p, &left, ",");
11103
11104 remote_buffer_add_int (&p, &left, len);
11105 remote_buffer_add_string (&p, &left, ",");
11106
11107 remote_buffer_add_int (&p, &left, offset);
11108
11109 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11110 remote_errno, &attachment,
11111 &attachment_len);
11112
11113 if (ret < 0)
11114 return ret;
11115
bc20a4af 11116 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11117 read_buf, len);
11118 if (read_len != ret)
11119 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11120
11121 return ret;
11122}
11123
80152258
PA
11124/* Serve pread from the readahead cache. Returns number of bytes
11125 read, or 0 if the request can't be served from the cache. */
11126
11127static int
11128remote_hostio_pread_from_cache (struct remote_state *rs,
11129 int fd, gdb_byte *read_buf, size_t len,
11130 ULONGEST offset)
11131{
11132 struct readahead_cache *cache = &rs->readahead_cache;
11133
11134 if (cache->fd == fd
11135 && cache->offset <= offset
11136 && offset < cache->offset + cache->bufsize)
11137 {
11138 ULONGEST max = cache->offset + cache->bufsize;
11139
11140 if (offset + len > max)
11141 len = max - offset;
11142
11143 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11144 return len;
11145 }
11146
11147 return 0;
11148}
11149
11150/* Implementation of to_fileio_pread. */
11151
11152static int
11153remote_hostio_pread (struct target_ops *self,
11154 int fd, gdb_byte *read_buf, int len,
11155 ULONGEST offset, int *remote_errno)
11156{
11157 int ret;
11158 struct remote_state *rs = get_remote_state ();
11159 struct readahead_cache *cache = &rs->readahead_cache;
11160
11161 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11162 if (ret > 0)
11163 {
11164 cache->hit_count++;
11165
11166 if (remote_debug)
11167 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11168 pulongest (cache->hit_count));
11169 return ret;
11170 }
11171
11172 cache->miss_count++;
11173 if (remote_debug)
11174 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11175 pulongest (cache->miss_count));
11176
11177 cache->fd = fd;
11178 cache->offset = offset;
11179 cache->bufsize = get_remote_packet_size ();
224c3ddb 11180 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11181
11182 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11183 cache->offset, remote_errno);
11184 if (ret <= 0)
11185 {
11186 readahead_cache_invalidate_fd (fd);
11187 return ret;
11188 }
11189
11190 cache->bufsize = ret;
11191 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11192}
11193
12e2a5fd 11194/* Implementation of to_fileio_close. */
a6b151f1
DJ
11195
11196static int
df39ea25 11197remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11198{
11199 struct remote_state *rs = get_remote_state ();
11200 char *p = rs->buf;
11201 int left = get_remote_packet_size () - 1;
11202
80152258
PA
11203 readahead_cache_invalidate_fd (fd);
11204
a6b151f1
DJ
11205 remote_buffer_add_string (&p, &left, "vFile:close:");
11206
11207 remote_buffer_add_int (&p, &left, fd);
11208
11209 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11210 remote_errno, NULL, NULL);
11211}
11212
12e2a5fd 11213/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11214
11215static int
dbbca37d 11216remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11217 struct inferior *inf, const char *filename,
11218 int *remote_errno)
a6b151f1
DJ
11219{
11220 struct remote_state *rs = get_remote_state ();
11221 char *p = rs->buf;
11222 int left = get_remote_packet_size () - 1;
11223
15a201c8
GB
11224 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11225 return -1;
11226
a6b151f1
DJ
11227 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11228
11229 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11230 strlen (filename));
11231
11232 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11233 remote_errno, NULL, NULL);
11234}
11235
12e2a5fd 11236/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11237
11238static char *
fab5aa7c 11239remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11240 struct inferior *inf, const char *filename,
11241 int *remote_errno)
b9e7b9c3
UW
11242{
11243 struct remote_state *rs = get_remote_state ();
11244 char *p = rs->buf;
11245 char *attachment;
11246 int left = get_remote_packet_size ();
11247 int len, attachment_len;
11248 int read_len;
11249 char *ret;
11250
15a201c8
GB
11251 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11252 return NULL;
11253
b9e7b9c3
UW
11254 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11255
11256 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11257 strlen (filename));
11258
11259 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11260 remote_errno, &attachment,
11261 &attachment_len);
11262
11263 if (len < 0)
11264 return NULL;
11265
224c3ddb 11266 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11267
bc20a4af
PA
11268 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11269 (gdb_byte *) ret, len);
b9e7b9c3
UW
11270 if (read_len != len)
11271 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11272
11273 ret[len] = '\0';
11274 return ret;
11275}
11276
12e2a5fd 11277/* Implementation of to_fileio_fstat. */
0a93529c
GB
11278
11279static int
11280remote_hostio_fstat (struct target_ops *self,
11281 int fd, struct stat *st,
11282 int *remote_errno)
11283{
11284 struct remote_state *rs = get_remote_state ();
11285 char *p = rs->buf;
11286 int left = get_remote_packet_size ();
11287 int attachment_len, ret;
11288 char *attachment;
11289 struct fio_stat fst;
11290 int read_len;
11291
464b0089
GB
11292 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11293
11294 remote_buffer_add_int (&p, &left, fd);
11295
11296 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11297 remote_errno, &attachment,
11298 &attachment_len);
11299 if (ret < 0)
0a93529c 11300 {
464b0089
GB
11301 if (*remote_errno != FILEIO_ENOSYS)
11302 return ret;
11303
0a93529c
GB
11304 /* Strictly we should return -1, ENOSYS here, but when
11305 "set sysroot remote:" was implemented in August 2008
11306 BFD's need for a stat function was sidestepped with
11307 this hack. This was not remedied until March 2015
11308 so we retain the previous behavior to avoid breaking
11309 compatibility.
11310
11311 Note that the memset is a March 2015 addition; older
11312 GDBs set st_size *and nothing else* so the structure
11313 would have garbage in all other fields. This might
11314 break something but retaining the previous behavior
11315 here would be just too wrong. */
11316
11317 memset (st, 0, sizeof (struct stat));
11318 st->st_size = INT_MAX;
11319 return 0;
11320 }
11321
0a93529c
GB
11322 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11323 (gdb_byte *) &fst, sizeof (fst));
11324
11325 if (read_len != ret)
11326 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11327
11328 if (read_len != sizeof (fst))
11329 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11330 read_len, (int) sizeof (fst));
11331
11332 remote_fileio_to_host_stat (&fst, st);
11333
11334 return 0;
11335}
11336
12e2a5fd 11337/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11338
11339static int
11340remote_filesystem_is_local (struct target_ops *self)
11341{
11342 /* Valgrind GDB presents itself as a remote target but works
11343 on the local filesystem: it does not implement remote get
11344 and users are not expected to set a sysroot. To handle
11345 this case we treat the remote filesystem as local if the
11346 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11347 does not support vFile:open. */
a3be80c3 11348 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11349 {
11350 enum packet_support ps = packet_support (PACKET_vFile_open);
11351
11352 if (ps == PACKET_SUPPORT_UNKNOWN)
11353 {
11354 int fd, remote_errno;
11355
11356 /* Try opening a file to probe support. The supplied
11357 filename is irrelevant, we only care about whether
11358 the stub recognizes the packet or not. */
07c138c8 11359 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11360 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11361 &remote_errno);
11362
11363 if (fd >= 0)
11364 remote_hostio_close (self, fd, &remote_errno);
11365
11366 ps = packet_support (PACKET_vFile_open);
11367 }
11368
11369 if (ps == PACKET_DISABLE)
11370 {
11371 static int warning_issued = 0;
11372
11373 if (!warning_issued)
11374 {
11375 warning (_("remote target does not support file"
11376 " transfer, attempting to access files"
11377 " from local filesystem."));
11378 warning_issued = 1;
11379 }
11380
11381 return 1;
11382 }
11383 }
11384
11385 return 0;
11386}
11387
a6b151f1
DJ
11388static int
11389remote_fileio_errno_to_host (int errnum)
11390{
11391 switch (errnum)
11392 {
11393 case FILEIO_EPERM:
11394 return EPERM;
11395 case FILEIO_ENOENT:
11396 return ENOENT;
11397 case FILEIO_EINTR:
11398 return EINTR;
11399 case FILEIO_EIO:
11400 return EIO;
11401 case FILEIO_EBADF:
11402 return EBADF;
11403 case FILEIO_EACCES:
11404 return EACCES;
11405 case FILEIO_EFAULT:
11406 return EFAULT;
11407 case FILEIO_EBUSY:
11408 return EBUSY;
11409 case FILEIO_EEXIST:
11410 return EEXIST;
11411 case FILEIO_ENODEV:
11412 return ENODEV;
11413 case FILEIO_ENOTDIR:
11414 return ENOTDIR;
11415 case FILEIO_EISDIR:
11416 return EISDIR;
11417 case FILEIO_EINVAL:
11418 return EINVAL;
11419 case FILEIO_ENFILE:
11420 return ENFILE;
11421 case FILEIO_EMFILE:
11422 return EMFILE;
11423 case FILEIO_EFBIG:
11424 return EFBIG;
11425 case FILEIO_ENOSPC:
11426 return ENOSPC;
11427 case FILEIO_ESPIPE:
11428 return ESPIPE;
11429 case FILEIO_EROFS:
11430 return EROFS;
11431 case FILEIO_ENOSYS:
11432 return ENOSYS;
11433 case FILEIO_ENAMETOOLONG:
11434 return ENAMETOOLONG;
11435 }
11436 return -1;
11437}
11438
11439static char *
11440remote_hostio_error (int errnum)
11441{
11442 int host_error = remote_fileio_errno_to_host (errnum);
11443
11444 if (host_error == -1)
11445 error (_("Unknown remote I/O error %d"), errnum);
11446 else
11447 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11448}
11449
a6b151f1
DJ
11450static void
11451remote_hostio_close_cleanup (void *opaque)
11452{
11453 int fd = *(int *) opaque;
11454 int remote_errno;
11455
df39ea25 11456 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11457}
11458
11459void
11460remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11461{
11462 struct cleanup *back_to, *close_cleanup;
11463 int retcode, fd, remote_errno, bytes, io_size;
11464 FILE *file;
11465 gdb_byte *buffer;
11466 int bytes_in_buffer;
11467 int saw_eof;
11468 ULONGEST offset;
5d93a237 11469 struct remote_state *rs = get_remote_state ();
a6b151f1 11470
5d93a237 11471 if (!rs->remote_desc)
a6b151f1
DJ
11472 error (_("command can only be used with remote target"));
11473
614c279d 11474 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11475 if (file == NULL)
11476 perror_with_name (local_file);
7c8a8b04 11477 back_to = make_cleanup_fclose (file);
a6b151f1 11478
07c138c8 11479 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11480 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11481 | FILEIO_O_TRUNC),
4313b8c0 11482 0700, 0, &remote_errno);
a6b151f1
DJ
11483 if (fd == -1)
11484 remote_hostio_error (remote_errno);
11485
11486 /* Send up to this many bytes at once. They won't all fit in the
11487 remote packet limit, so we'll transfer slightly fewer. */
11488 io_size = get_remote_packet_size ();
224c3ddb 11489 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11490 make_cleanup (xfree, buffer);
11491
11492 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11493
11494 bytes_in_buffer = 0;
11495 saw_eof = 0;
11496 offset = 0;
11497 while (bytes_in_buffer || !saw_eof)
11498 {
11499 if (!saw_eof)
11500 {
3e43a32a
MS
11501 bytes = fread (buffer + bytes_in_buffer, 1,
11502 io_size - bytes_in_buffer,
a6b151f1
DJ
11503 file);
11504 if (bytes == 0)
11505 {
11506 if (ferror (file))
11507 error (_("Error reading %s."), local_file);
11508 else
11509 {
11510 /* EOF. Unless there is something still in the
11511 buffer from the last iteration, we are done. */
11512 saw_eof = 1;
11513 if (bytes_in_buffer == 0)
11514 break;
11515 }
11516 }
11517 }
11518 else
11519 bytes = 0;
11520
11521 bytes += bytes_in_buffer;
11522 bytes_in_buffer = 0;
11523
0d866f62
TT
11524 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11525 fd, buffer, bytes,
3e43a32a 11526 offset, &remote_errno);
a6b151f1
DJ
11527
11528 if (retcode < 0)
11529 remote_hostio_error (remote_errno);
11530 else if (retcode == 0)
11531 error (_("Remote write of %d bytes returned 0!"), bytes);
11532 else if (retcode < bytes)
11533 {
11534 /* Short write. Save the rest of the read data for the next
11535 write. */
11536 bytes_in_buffer = bytes - retcode;
11537 memmove (buffer, buffer + retcode, bytes_in_buffer);
11538 }
11539
11540 offset += retcode;
11541 }
11542
11543 discard_cleanups (close_cleanup);
df39ea25 11544 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11545 remote_hostio_error (remote_errno);
11546
11547 if (from_tty)
11548 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11549 do_cleanups (back_to);
11550}
11551
11552void
11553remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11554{
11555 struct cleanup *back_to, *close_cleanup;
cea39f65 11556 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11557 FILE *file;
11558 gdb_byte *buffer;
11559 ULONGEST offset;
5d93a237 11560 struct remote_state *rs = get_remote_state ();
a6b151f1 11561
5d93a237 11562 if (!rs->remote_desc)
a6b151f1
DJ
11563 error (_("command can only be used with remote target"));
11564
07c138c8 11565 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11566 remote_file, FILEIO_O_RDONLY, 0, 0,
11567 &remote_errno);
a6b151f1
DJ
11568 if (fd == -1)
11569 remote_hostio_error (remote_errno);
11570
614c279d 11571 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11572 if (file == NULL)
11573 perror_with_name (local_file);
7c8a8b04 11574 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11575
11576 /* Send up to this many bytes at once. They won't all fit in the
11577 remote packet limit, so we'll transfer slightly fewer. */
11578 io_size = get_remote_packet_size ();
224c3ddb 11579 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11580 make_cleanup (xfree, buffer);
11581
11582 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11583
11584 offset = 0;
11585 while (1)
11586 {
a3be983c
TT
11587 bytes = remote_hostio_pread (find_target_at (process_stratum),
11588 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11589 if (bytes == 0)
11590 /* Success, but no bytes, means end-of-file. */
11591 break;
11592 if (bytes == -1)
11593 remote_hostio_error (remote_errno);
11594
11595 offset += bytes;
11596
11597 bytes = fwrite (buffer, 1, bytes, file);
11598 if (bytes == 0)
11599 perror_with_name (local_file);
11600 }
11601
11602 discard_cleanups (close_cleanup);
df39ea25 11603 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11604 remote_hostio_error (remote_errno);
11605
11606 if (from_tty)
11607 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11608 do_cleanups (back_to);
11609}
11610
11611void
11612remote_file_delete (const char *remote_file, int from_tty)
11613{
11614 int retcode, remote_errno;
5d93a237 11615 struct remote_state *rs = get_remote_state ();
a6b151f1 11616
5d93a237 11617 if (!rs->remote_desc)
a6b151f1
DJ
11618 error (_("command can only be used with remote target"));
11619
dbbca37d 11620 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11621 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11622 if (retcode == -1)
11623 remote_hostio_error (remote_errno);
11624
11625 if (from_tty)
11626 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11627}
11628
11629static void
11630remote_put_command (char *args, int from_tty)
11631{
11632 struct cleanup *back_to;
11633 char **argv;
11634
d1a41061
PP
11635 if (args == NULL)
11636 error_no_arg (_("file to put"));
11637
11638 argv = gdb_buildargv (args);
a6b151f1
DJ
11639 back_to = make_cleanup_freeargv (argv);
11640 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11641 error (_("Invalid parameters to remote put"));
11642
11643 remote_file_put (argv[0], argv[1], from_tty);
11644
11645 do_cleanups (back_to);
11646}
11647
11648static void
11649remote_get_command (char *args, int from_tty)
11650{
11651 struct cleanup *back_to;
11652 char **argv;
11653
d1a41061
PP
11654 if (args == NULL)
11655 error_no_arg (_("file to get"));
11656
11657 argv = gdb_buildargv (args);
a6b151f1
DJ
11658 back_to = make_cleanup_freeargv (argv);
11659 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11660 error (_("Invalid parameters to remote get"));
11661
11662 remote_file_get (argv[0], argv[1], from_tty);
11663
11664 do_cleanups (back_to);
11665}
11666
11667static void
11668remote_delete_command (char *args, int from_tty)
11669{
11670 struct cleanup *back_to;
11671 char **argv;
11672
d1a41061
PP
11673 if (args == NULL)
11674 error_no_arg (_("file to delete"));
11675
11676 argv = gdb_buildargv (args);
a6b151f1
DJ
11677 back_to = make_cleanup_freeargv (argv);
11678 if (argv[0] == NULL || argv[1] != NULL)
11679 error (_("Invalid parameters to remote delete"));
11680
11681 remote_file_delete (argv[0], from_tty);
11682
11683 do_cleanups (back_to);
11684}
11685
11686static void
11687remote_command (char *args, int from_tty)
11688{
635c7e8a 11689 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11690}
11691
b2175913 11692static int
19db3e69 11693remote_can_execute_reverse (struct target_ops *self)
b2175913 11694{
4082afcc
PA
11695 if (packet_support (PACKET_bs) == PACKET_ENABLE
11696 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11697 return 1;
11698 else
11699 return 0;
b2175913
MS
11700}
11701
74531fed 11702static int
2a9a2795 11703remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11704{
11705 return 1;
11706}
11707
03583c20 11708static int
2bfc0540 11709remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11710{
11711 /* Only supported in extended mode. */
11712 return 0;
11713}
11714
8a305172 11715static int
86ce2668 11716remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11717{
11718 struct remote_state *rs = get_remote_state ();
a744cf53 11719
8020350c 11720 return remote_multi_process_p (rs);
8a305172
PA
11721}
11722
70221824 11723static int
782b2b07
SS
11724remote_supports_cond_tracepoints (void)
11725{
4082afcc 11726 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11727}
11728
3788aec7 11729static int
efcc2da7 11730remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11731{
4082afcc 11732 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11733}
11734
70221824 11735static int
7a697b8d
SS
11736remote_supports_fast_tracepoints (void)
11737{
4082afcc 11738 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11739}
11740
0fb4aa4b
PA
11741static int
11742remote_supports_static_tracepoints (void)
11743{
4082afcc 11744 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11745}
11746
1e4d1764
YQ
11747static int
11748remote_supports_install_in_trace (void)
11749{
4082afcc 11750 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11751}
11752
d248b706 11753static int
7d178d6a 11754remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11755{
4082afcc
PA
11756 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11757 == PACKET_ENABLE);
d248b706
KY
11758}
11759
3065dfb6 11760static int
6de37a3a 11761remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11762{
4082afcc 11763 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11764}
11765
d3ce09f5 11766static int
78eff0ec 11767remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11768{
4082afcc 11769 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11770}
11771
35b1e5cc 11772static void
ecae04e1 11773remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11774{
11775 putpkt ("QTinit");
11776 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11777 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11778 error (_("Target does not support this command."));
11779}
11780
11781static void free_actions_list (char **actions_list);
11782static void free_actions_list_cleanup_wrapper (void *);
11783static void
11784free_actions_list_cleanup_wrapper (void *al)
11785{
19ba03f4 11786 free_actions_list ((char **) al);
35b1e5cc
SS
11787}
11788
11789static void
11790free_actions_list (char **actions_list)
11791{
11792 int ndx;
11793
11794 if (actions_list == 0)
11795 return;
11796
11797 for (ndx = 0; actions_list[ndx]; ndx++)
11798 xfree (actions_list[ndx]);
11799
11800 xfree (actions_list);
11801}
11802
409873ef
SS
11803/* Recursive routine to walk through command list including loops, and
11804 download packets for each command. */
11805
11806static void
11807remote_download_command_source (int num, ULONGEST addr,
11808 struct command_line *cmds)
11809{
11810 struct remote_state *rs = get_remote_state ();
11811 struct command_line *cmd;
11812
11813 for (cmd = cmds; cmd; cmd = cmd->next)
11814 {
0df8b418 11815 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11816 strcpy (rs->buf, "QTDPsrc:");
11817 encode_source_string (num, addr, "cmd", cmd->line,
11818 rs->buf + strlen (rs->buf),
11819 rs->buf_size - strlen (rs->buf));
11820 putpkt (rs->buf);
11821 remote_get_noisy_reply (&target_buf, &target_buf_size);
11822 if (strcmp (target_buf, "OK"))
11823 warning (_("Target does not support source download."));
11824
11825 if (cmd->control_type == while_control
11826 || cmd->control_type == while_stepping_control)
11827 {
11828 remote_download_command_source (num, addr, *cmd->body_list);
11829
0df8b418 11830 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11831 strcpy (rs->buf, "QTDPsrc:");
11832 encode_source_string (num, addr, "cmd", "end",
11833 rs->buf + strlen (rs->buf),
11834 rs->buf_size - strlen (rs->buf));
11835 putpkt (rs->buf);
11836 remote_get_noisy_reply (&target_buf, &target_buf_size);
11837 if (strcmp (target_buf, "OK"))
11838 warning (_("Target does not support source download."));
11839 }
11840 }
11841}
11842
35b1e5cc 11843static void
548f7808 11844remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11845{
bba74b36 11846#define BUF_SIZE 2048
e8ba3115 11847
35b1e5cc 11848 CORE_ADDR tpaddr;
409873ef 11849 char addrbuf[40];
bba74b36 11850 char buf[BUF_SIZE];
35b1e5cc
SS
11851 char **tdp_actions;
11852 char **stepping_actions;
11853 int ndx;
11854 struct cleanup *old_chain = NULL;
11855 struct agent_expr *aexpr;
11856 struct cleanup *aexpr_chain = NULL;
11857 char *pkt;
e8ba3115 11858 struct breakpoint *b = loc->owner;
d9b3f62e 11859 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11860
dc673c81 11861 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11862 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11863 tdp_actions);
11864 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11865 stepping_actions);
11866
11867 tpaddr = loc->address;
11868 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11869 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11870 addrbuf, /* address */
11871 (b->enable_state == bp_enabled ? 'E' : 'D'),
11872 t->step_count, t->pass_count);
e8ba3115
YQ
11873 /* Fast tracepoints are mostly handled by the target, but we can
11874 tell the target how big of an instruction block should be moved
11875 around. */
11876 if (b->type == bp_fast_tracepoint)
11877 {
11878 /* Only test for support at download time; we may not know
11879 target capabilities at definition time. */
11880 if (remote_supports_fast_tracepoints ())
35b1e5cc 11881 {
6b940e6a
PL
11882 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11883 NULL))
bba74b36 11884 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11885 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11886 else
e8ba3115
YQ
11887 /* If it passed validation at definition but fails now,
11888 something is very wrong. */
11889 internal_error (__FILE__, __LINE__,
11890 _("Fast tracepoint not "
11891 "valid during download"));
35b1e5cc 11892 }
e8ba3115
YQ
11893 else
11894 /* Fast tracepoints are functionally identical to regular
11895 tracepoints, so don't take lack of support as a reason to
11896 give up on the trace run. */
11897 warning (_("Target does not support fast tracepoints, "
11898 "downloading %d as regular tracepoint"), b->number);
11899 }
11900 else if (b->type == bp_static_tracepoint)
11901 {
11902 /* Only test for support at download time; we may not know
11903 target capabilities at definition time. */
11904 if (remote_supports_static_tracepoints ())
0fb4aa4b 11905 {
e8ba3115 11906 struct static_tracepoint_marker marker;
0fb4aa4b 11907
e8ba3115
YQ
11908 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11909 strcat (buf, ":S");
0fb4aa4b 11910 else
e8ba3115 11911 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11912 }
e8ba3115
YQ
11913 else
11914 /* Fast tracepoints are functionally identical to regular
11915 tracepoints, so don't take lack of support as a reason
11916 to give up on the trace run. */
11917 error (_("Target does not support static tracepoints"));
11918 }
11919 /* If the tracepoint has a conditional, make it into an agent
11920 expression and append to the definition. */
11921 if (loc->cond)
11922 {
11923 /* Only test support at download time, we may not know target
11924 capabilities at definition time. */
11925 if (remote_supports_cond_tracepoints ())
35b1e5cc 11926 {
e8ba3115
YQ
11927 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11928 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11929 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11930 aexpr->len);
e8ba3115
YQ
11931 pkt = buf + strlen (buf);
11932 for (ndx = 0; ndx < aexpr->len; ++ndx)
11933 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11934 *pkt = '\0';
11935 do_cleanups (aexpr_chain);
35b1e5cc 11936 }
e8ba3115
YQ
11937 else
11938 warning (_("Target does not support conditional tracepoints, "
11939 "ignoring tp %d cond"), b->number);
11940 }
35b1e5cc 11941
d9b3f62e 11942 if (b->commands || *default_collect)
e8ba3115
YQ
11943 strcat (buf, "-");
11944 putpkt (buf);
11945 remote_get_noisy_reply (&target_buf, &target_buf_size);
11946 if (strcmp (target_buf, "OK"))
11947 error (_("Target does not support tracepoints."));
35b1e5cc 11948
e8ba3115
YQ
11949 /* do_single_steps (t); */
11950 if (tdp_actions)
11951 {
11952 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11953 {
e8ba3115 11954 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11955 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11956 b->number, addrbuf, /* address */
11957 tdp_actions[ndx],
11958 ((tdp_actions[ndx + 1] || stepping_actions)
11959 ? '-' : 0));
e8ba3115
YQ
11960 putpkt (buf);
11961 remote_get_noisy_reply (&target_buf,
11962 &target_buf_size);
11963 if (strcmp (target_buf, "OK"))
11964 error (_("Error on target while setting tracepoints."));
35b1e5cc 11965 }
e8ba3115
YQ
11966 }
11967 if (stepping_actions)
11968 {
11969 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11970 {
e8ba3115 11971 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11972 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11973 b->number, addrbuf, /* address */
11974 ((ndx == 0) ? "S" : ""),
11975 stepping_actions[ndx],
11976 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11977 putpkt (buf);
11978 remote_get_noisy_reply (&target_buf,
11979 &target_buf_size);
11980 if (strcmp (target_buf, "OK"))
11981 error (_("Error on target while setting tracepoints."));
35b1e5cc 11982 }
e8ba3115 11983 }
409873ef 11984
4082afcc 11985 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11986 {
f00aae0f 11987 if (b->location != NULL)
409873ef 11988 {
e8ba3115 11989 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11990 encode_source_string (b->number, loc->address, "at",
11991 event_location_to_string (b->location),
11992 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11993 putpkt (buf);
11994 remote_get_noisy_reply (&target_buf, &target_buf_size);
11995 if (strcmp (target_buf, "OK"))
11996 warning (_("Target does not support source download."));
409873ef 11997 }
e8ba3115
YQ
11998 if (b->cond_string)
11999 {
12000 strcpy (buf, "QTDPsrc:");
12001 encode_source_string (b->number, loc->address,
12002 "cond", b->cond_string, buf + strlen (buf),
12003 2048 - strlen (buf));
12004 putpkt (buf);
12005 remote_get_noisy_reply (&target_buf, &target_buf_size);
12006 if (strcmp (target_buf, "OK"))
12007 warning (_("Target does not support source download."));
12008 }
12009 remote_download_command_source (b->number, loc->address,
12010 breakpoint_commands (b));
35b1e5cc 12011 }
e8ba3115
YQ
12012
12013 do_cleanups (old_chain);
35b1e5cc
SS
12014}
12015
1e4d1764 12016static int
a52a8357 12017remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 12018{
1e51243a
PA
12019 struct remote_state *rs = get_remote_state ();
12020 struct trace_status *ts;
12021 int status;
12022
12023 /* Don't try to install tracepoints until we've relocated our
12024 symbols, and fetched and merged the target's tracepoint list with
12025 ours. */
12026 if (rs->starting_up)
12027 return 0;
12028
12029 ts = current_trace_status ();
8bd200f1 12030 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
12031
12032 if (status == -1 || !ts->running_known || !ts->running)
12033 return 0;
12034
12035 /* If we are in a tracing experiment, but remote stub doesn't support
12036 installing tracepoint in trace, we have to return. */
12037 if (!remote_supports_install_in_trace ())
12038 return 0;
12039
12040 return 1;
12041}
12042
12043
35b1e5cc 12044static void
559d2b81
TT
12045remote_download_trace_state_variable (struct target_ops *self,
12046 struct trace_state_variable *tsv)
35b1e5cc
SS
12047{
12048 struct remote_state *rs = get_remote_state ();
00bf0b85 12049 char *p;
35b1e5cc 12050
bba74b36
YQ
12051 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12052 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12053 tsv->builtin);
00bf0b85
SS
12054 p = rs->buf + strlen (rs->buf);
12055 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12056 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 12057 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 12058 *p++ = '\0';
35b1e5cc
SS
12059 putpkt (rs->buf);
12060 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12061 if (*target_buf == '\0')
12062 error (_("Target does not support this command."));
12063 if (strcmp (target_buf, "OK") != 0)
12064 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12065}
12066
d248b706 12067static void
46670d57
TT
12068remote_enable_tracepoint (struct target_ops *self,
12069 struct bp_location *location)
d248b706
KY
12070{
12071 struct remote_state *rs = get_remote_state ();
12072 char addr_buf[40];
12073
12074 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12075 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12076 location->owner->number, addr_buf);
d248b706
KY
12077 putpkt (rs->buf);
12078 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12079 if (*rs->buf == '\0')
12080 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12081 if (strcmp (rs->buf, "OK") != 0)
12082 error (_("Error on target while enabling tracepoint."));
12083}
12084
12085static void
780b049c
TT
12086remote_disable_tracepoint (struct target_ops *self,
12087 struct bp_location *location)
d248b706
KY
12088{
12089 struct remote_state *rs = get_remote_state ();
12090 char addr_buf[40];
12091
12092 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12093 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12094 location->owner->number, addr_buf);
d248b706
KY
12095 putpkt (rs->buf);
12096 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12097 if (*rs->buf == '\0')
12098 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12099 if (strcmp (rs->buf, "OK") != 0)
12100 error (_("Error on target while disabling tracepoint."));
12101}
12102
35b1e5cc 12103static void
583f9a86 12104remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12105{
12106 asection *s;
81b9b86e 12107 bfd *abfd = NULL;
35b1e5cc 12108 bfd_size_type size;
608bcef2 12109 bfd_vma vma;
35b1e5cc 12110 int anysecs = 0;
c2fa21f1 12111 int offset = 0;
35b1e5cc
SS
12112
12113 if (!exec_bfd)
12114 return; /* No information to give. */
12115
12116 strcpy (target_buf, "QTro");
9779ab84 12117 offset = strlen (target_buf);
35b1e5cc
SS
12118 for (s = exec_bfd->sections; s; s = s->next)
12119 {
12120 char tmp1[40], tmp2[40];
c2fa21f1 12121 int sec_length;
35b1e5cc
SS
12122
12123 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12124 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12125 (s->flags & SEC_READONLY) == 0)
12126 continue;
12127
12128 anysecs = 1;
81b9b86e 12129 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12130 size = bfd_get_section_size (s);
608bcef2
HZ
12131 sprintf_vma (tmp1, vma);
12132 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12133 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12134 if (offset + sec_length + 1 > target_buf_size)
12135 {
4082afcc 12136 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12137 warning (_("\
c2fa21f1
HZ
12138Too many sections for read-only sections definition packet."));
12139 break;
12140 }
bba74b36
YQ
12141 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12142 tmp1, tmp2);
c2fa21f1 12143 offset += sec_length;
35b1e5cc
SS
12144 }
12145 if (anysecs)
12146 {
12147 putpkt (target_buf);
12148 getpkt (&target_buf, &target_buf_size, 0);
12149 }
12150}
12151
12152static void
e2d1aae3 12153remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12154{
12155 putpkt ("QTStart");
12156 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12157 if (*target_buf == '\0')
12158 error (_("Target does not support this command."));
12159 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12160 error (_("Bogus reply from target: %s"), target_buf);
12161}
12162
12163static int
8bd200f1 12164remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12165{
953b98d1 12166 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12167 char *p = NULL;
0df8b418 12168 /* FIXME we need to get register block size some other way. */
00bf0b85 12169 extern int trace_regblock_size;
bd3eecc3
PA
12170 enum packet_result result;
12171
4082afcc 12172 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12173 return -1;
a744cf53 12174
00bf0b85
SS
12175 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12176
049dc89b
JK
12177 putpkt ("qTStatus");
12178
492d29ea 12179 TRY
67f41397
JK
12180 {
12181 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12182 }
492d29ea 12183 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12184 {
598d3636
JK
12185 if (ex.error != TARGET_CLOSE_ERROR)
12186 {
12187 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12188 return -1;
12189 }
12190 throw_exception (ex);
67f41397 12191 }
492d29ea 12192 END_CATCH
00bf0b85 12193
bd3eecc3
PA
12194 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12195
00bf0b85 12196 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12197 if (result == PACKET_UNKNOWN)
00bf0b85 12198 return -1;
35b1e5cc 12199
00bf0b85 12200 /* We're working with a live target. */
f5911ea1 12201 ts->filename = NULL;
00bf0b85 12202
00bf0b85 12203 if (*p++ != 'T')
35b1e5cc
SS
12204 error (_("Bogus trace status reply from target: %s"), target_buf);
12205
84cebc4a
YQ
12206 /* Function 'parse_trace_status' sets default value of each field of
12207 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12208 parse_trace_status (p, ts);
12209
12210 return ts->running;
35b1e5cc
SS
12211}
12212
70221824 12213static void
db90e85c 12214remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12215 struct uploaded_tp *utp)
12216{
12217 struct remote_state *rs = get_remote_state ();
f196051f
SS
12218 char *reply;
12219 struct bp_location *loc;
12220 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12221 size_t size = get_remote_packet_size ();
f196051f
SS
12222
12223 if (tp)
12224 {
12225 tp->base.hit_count = 0;
12226 tp->traceframe_usage = 0;
12227 for (loc = tp->base.loc; loc; loc = loc->next)
12228 {
12229 /* If the tracepoint was never downloaded, don't go asking for
12230 any status. */
12231 if (tp->number_on_target == 0)
12232 continue;
bba74b36
YQ
12233 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12234 phex_nz (loc->address, 0));
f196051f
SS
12235 putpkt (rs->buf);
12236 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12237 if (reply && *reply)
12238 {
12239 if (*reply == 'V')
12240 parse_tracepoint_status (reply + 1, bp, utp);
12241 }
12242 }
12243 }
12244 else if (utp)
12245 {
12246 utp->hit_count = 0;
12247 utp->traceframe_usage = 0;
bba74b36
YQ
12248 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12249 phex_nz (utp->addr, 0));
f196051f
SS
12250 putpkt (rs->buf);
12251 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12252 if (reply && *reply)
12253 {
12254 if (*reply == 'V')
12255 parse_tracepoint_status (reply + 1, bp, utp);
12256 }
12257 }
12258}
12259
35b1e5cc 12260static void
74499f1b 12261remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12262{
12263 putpkt ("QTStop");
12264 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12265 if (*target_buf == '\0')
12266 error (_("Target does not support this command."));
12267 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12268 error (_("Bogus reply from target: %s"), target_buf);
12269}
12270
12271static int
bd4c6793
TT
12272remote_trace_find (struct target_ops *self,
12273 enum trace_find_type type, int num,
cc5925ad 12274 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12275 int *tpp)
12276{
12277 struct remote_state *rs = get_remote_state ();
bba74b36 12278 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12279 char *p, *reply;
12280 int target_frameno = -1, target_tracept = -1;
12281
e6e4e701
PA
12282 /* Lookups other than by absolute frame number depend on the current
12283 trace selected, so make sure it is correct on the remote end
12284 first. */
12285 if (type != tfind_number)
12286 set_remote_traceframe ();
12287
35b1e5cc
SS
12288 p = rs->buf;
12289 strcpy (p, "QTFrame:");
12290 p = strchr (p, '\0');
12291 switch (type)
12292 {
12293 case tfind_number:
bba74b36 12294 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12295 break;
12296 case tfind_pc:
bba74b36 12297 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12298 break;
12299 case tfind_tp:
bba74b36 12300 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12301 break;
12302 case tfind_range:
bba74b36
YQ
12303 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12304 phex_nz (addr2, 0));
35b1e5cc
SS
12305 break;
12306 case tfind_outside:
bba74b36
YQ
12307 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12308 phex_nz (addr2, 0));
35b1e5cc
SS
12309 break;
12310 default:
9b20d036 12311 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12312 }
12313
12314 putpkt (rs->buf);
2f65bcb7 12315 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12316 if (*reply == '\0')
12317 error (_("Target does not support this command."));
35b1e5cc
SS
12318
12319 while (reply && *reply)
12320 switch (*reply)
12321 {
12322 case 'F':
f197e0f1
VP
12323 p = ++reply;
12324 target_frameno = (int) strtol (p, &reply, 16);
12325 if (reply == p)
12326 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12327 /* Don't update our remote traceframe number cache on failure
12328 to select a remote traceframe. */
f197e0f1
VP
12329 if (target_frameno == -1)
12330 return -1;
35b1e5cc
SS
12331 break;
12332 case 'T':
f197e0f1
VP
12333 p = ++reply;
12334 target_tracept = (int) strtol (p, &reply, 16);
12335 if (reply == p)
12336 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12337 break;
12338 case 'O': /* "OK"? */
12339 if (reply[1] == 'K' && reply[2] == '\0')
12340 reply += 2;
12341 else
12342 error (_("Bogus reply from target: %s"), reply);
12343 break;
12344 default:
12345 error (_("Bogus reply from target: %s"), reply);
12346 }
12347 if (tpp)
12348 *tpp = target_tracept;
e6e4e701 12349
262e1174 12350 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12351 return target_frameno;
12352}
12353
12354static int
4011015b
TT
12355remote_get_trace_state_variable_value (struct target_ops *self,
12356 int tsvnum, LONGEST *val)
35b1e5cc
SS
12357{
12358 struct remote_state *rs = get_remote_state ();
12359 char *reply;
12360 ULONGEST uval;
12361
e6e4e701
PA
12362 set_remote_traceframe ();
12363
bba74b36 12364 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12365 putpkt (rs->buf);
12366 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12367 if (reply && *reply)
12368 {
12369 if (*reply == 'V')
12370 {
12371 unpack_varlen_hex (reply + 1, &uval);
12372 *val = (LONGEST) uval;
12373 return 1;
12374 }
12375 }
12376 return 0;
12377}
12378
00bf0b85 12379static int
dc3decaf 12380remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12381{
12382 struct remote_state *rs = get_remote_state ();
12383 char *p, *reply;
12384
12385 p = rs->buf;
12386 strcpy (p, "QTSave:");
12387 p += strlen (p);
12388 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12389 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12390 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12391 *p++ = '\0';
12392 putpkt (rs->buf);
ad91cd99 12393 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12394 if (*reply == '\0')
ad91cd99
PA
12395 error (_("Target does not support this command."));
12396 if (strcmp (reply, "OK") != 0)
12397 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12398 return 0;
12399}
12400
12401/* This is basically a memory transfer, but needs to be its own packet
12402 because we don't know how the target actually organizes its trace
12403 memory, plus we want to be able to ask for as much as possible, but
12404 not be unhappy if we don't get as much as we ask for. */
12405
12406static LONGEST
88ee6f45
TT
12407remote_get_raw_trace_data (struct target_ops *self,
12408 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12409{
12410 struct remote_state *rs = get_remote_state ();
12411 char *reply;
12412 char *p;
12413 int rslt;
12414
12415 p = rs->buf;
12416 strcpy (p, "qTBuffer:");
12417 p += strlen (p);
12418 p += hexnumstr (p, offset);
12419 *p++ = ',';
12420 p += hexnumstr (p, len);
12421 *p++ = '\0';
12422
12423 putpkt (rs->buf);
12424 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12425 if (reply && *reply)
12426 {
12427 /* 'l' by itself means we're at the end of the buffer and
12428 there is nothing more to get. */
12429 if (*reply == 'l')
12430 return 0;
12431
12432 /* Convert the reply into binary. Limit the number of bytes to
12433 convert according to our passed-in buffer size, rather than
12434 what was returned in the packet; if the target is
12435 unexpectedly generous and gives us a bigger reply than we
12436 asked for, we don't want to crash. */
12437 rslt = hex2bin (target_buf, buf, len);
12438 return rslt;
12439 }
12440
12441 /* Something went wrong, flag as an error. */
12442 return -1;
12443}
12444
35b1e5cc 12445static void
37b25738 12446remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12447{
12448 struct remote_state *rs = get_remote_state ();
12449
4082afcc 12450 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12451 {
ad91cd99
PA
12452 char *reply;
12453
bba74b36 12454 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12455 putpkt (rs->buf);
ad91cd99
PA
12456 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12457 if (*reply == '\0')
33da3f1c 12458 error (_("Target does not support this command."));
ad91cd99
PA
12459 if (strcmp (reply, "OK") != 0)
12460 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12461 }
12462 else if (val)
12463 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12464}
12465
dc146f7c
VP
12466static int
12467remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12468{
12469 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12470
fe978cb0
PA
12471 if (info && info->priv)
12472 return info->priv->core;
dc146f7c
VP
12473 return -1;
12474}
12475
4daf5ac0 12476static void
736d5b1f 12477remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12478{
12479 struct remote_state *rs = get_remote_state ();
ad91cd99 12480 char *reply;
4daf5ac0 12481
bba74b36 12482 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12483 putpkt (rs->buf);
ad91cd99
PA
12484 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12485 if (*reply == '\0')
4daf5ac0 12486 error (_("Target does not support this command."));
ad91cd99
PA
12487 if (strcmp (reply, "OK") != 0)
12488 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12489}
12490
b3b9301e 12491static struct traceframe_info *
a893e81f 12492remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12493{
12494 char *text;
12495
12496 text = target_read_stralloc (&current_target,
12497 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12498 if (text != NULL)
12499 {
12500 struct traceframe_info *info;
12501 struct cleanup *back_to = make_cleanup (xfree, text);
12502
12503 info = parse_traceframe_info (text);
12504 do_cleanups (back_to);
12505 return info;
12506 }
12507
12508 return NULL;
12509}
12510
405f8e94
SS
12511/* Handle the qTMinFTPILen packet. Returns the minimum length of
12512 instruction on which a fast tracepoint may be placed. Returns -1
12513 if the packet is not supported, and 0 if the minimum instruction
12514 length is unknown. */
12515
12516static int
0e67620a 12517remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12518{
12519 struct remote_state *rs = get_remote_state ();
12520 char *reply;
12521
e886a173
PA
12522 /* If we're not debugging a process yet, the IPA can't be
12523 loaded. */
12524 if (!target_has_execution)
12525 return 0;
12526
12527 /* Make sure the remote is pointing at the right process. */
12528 set_general_process ();
12529
bba74b36 12530 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12531 putpkt (rs->buf);
12532 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12533 if (*reply == '\0')
12534 return -1;
12535 else
12536 {
12537 ULONGEST min_insn_len;
12538
12539 unpack_varlen_hex (reply, &min_insn_len);
12540
12541 return (int) min_insn_len;
12542 }
12543}
12544
f6f899bf 12545static void
4da384be 12546remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12547{
4082afcc 12548 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12549 {
12550 struct remote_state *rs = get_remote_state ();
12551 char *buf = rs->buf;
12552 char *endbuf = rs->buf + get_remote_packet_size ();
12553 enum packet_result result;
12554
12555 gdb_assert (val >= 0 || val == -1);
12556 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12557 /* Send -1 as literal "-1" to avoid host size dependency. */
12558 if (val < 0)
12559 {
12560 *buf++ = '-';
12561 buf += hexnumstr (buf, (ULONGEST) -val);
12562 }
12563 else
12564 buf += hexnumstr (buf, (ULONGEST) val);
12565
12566 putpkt (rs->buf);
12567 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12568 result = packet_ok (rs->buf,
12569 &remote_protocol_packets[PACKET_QTBuffer_size]);
12570
12571 if (result != PACKET_OK)
12572 warning (_("Bogus reply from target: %s"), rs->buf);
12573 }
12574}
12575
f196051f 12576static int
d9e68a2c
TT
12577remote_set_trace_notes (struct target_ops *self,
12578 const char *user, const char *notes,
ca623f82 12579 const char *stop_notes)
f196051f
SS
12580{
12581 struct remote_state *rs = get_remote_state ();
12582 char *reply;
12583 char *buf = rs->buf;
12584 char *endbuf = rs->buf + get_remote_packet_size ();
12585 int nbytes;
12586
12587 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12588 if (user)
12589 {
12590 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12591 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12592 buf += 2 * nbytes;
12593 *buf++ = ';';
12594 }
12595 if (notes)
12596 {
12597 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12598 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12599 buf += 2 * nbytes;
12600 *buf++ = ';';
12601 }
12602 if (stop_notes)
12603 {
12604 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12605 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12606 buf += 2 * nbytes;
12607 *buf++ = ';';
12608 }
12609 /* Ensure the buffer is terminated. */
12610 *buf = '\0';
12611
12612 putpkt (rs->buf);
12613 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12614 if (*reply == '\0')
12615 return 0;
12616
12617 if (strcmp (reply, "OK") != 0)
12618 error (_("Bogus reply from target: %s"), reply);
12619
12620 return 1;
12621}
12622
d1feda86 12623static int
2c152180 12624remote_use_agent (struct target_ops *self, int use)
d1feda86 12625{
4082afcc 12626 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12627 {
12628 struct remote_state *rs = get_remote_state ();
12629
12630 /* If the stub supports QAgent. */
bba74b36 12631 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12632 putpkt (rs->buf);
12633 getpkt (&rs->buf, &rs->buf_size, 0);
12634
12635 if (strcmp (rs->buf, "OK") == 0)
12636 {
12637 use_agent = use;
12638 return 1;
12639 }
12640 }
12641
12642 return 0;
12643}
12644
12645static int
fe38f897 12646remote_can_use_agent (struct target_ops *self)
d1feda86 12647{
4082afcc 12648 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12649}
12650
9accd112
MM
12651struct btrace_target_info
12652{
12653 /* The ptid of the traced thread. */
12654 ptid_t ptid;
f4abbc16
MM
12655
12656 /* The obtained branch trace configuration. */
12657 struct btrace_config conf;
9accd112
MM
12658};
12659
f4abbc16
MM
12660/* Reset our idea of our target's btrace configuration. */
12661
12662static void
12663remote_btrace_reset (void)
12664{
12665 struct remote_state *rs = get_remote_state ();
12666
12667 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12668}
12669
9accd112
MM
12670/* Check whether the target supports branch tracing. */
12671
12672static int
043c3577 12673remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12674{
4082afcc 12675 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12676 return 0;
4082afcc 12677 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12678 return 0;
12679
043c3577
MM
12680 switch (format)
12681 {
12682 case BTRACE_FORMAT_NONE:
12683 return 0;
12684
12685 case BTRACE_FORMAT_BTS:
12686 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12687
12688 case BTRACE_FORMAT_PT:
12689 /* The trace is decoded on the host. Even if our target supports it,
12690 we still need to have libipt to decode the trace. */
12691#if defined (HAVE_LIBIPT)
12692 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12693#else /* !defined (HAVE_LIBIPT) */
12694 return 0;
12695#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12696 }
12697
12698 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12699}
12700
f4abbc16
MM
12701/* Synchronize the configuration with the target. */
12702
12703static void
12704btrace_sync_conf (const struct btrace_config *conf)
12705{
d33501a5
MM
12706 struct packet_config *packet;
12707 struct remote_state *rs;
12708 char *buf, *pos, *endbuf;
12709
12710 rs = get_remote_state ();
12711 buf = rs->buf;
12712 endbuf = buf + get_remote_packet_size ();
12713
12714 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12715 if (packet_config_support (packet) == PACKET_ENABLE
12716 && conf->bts.size != rs->btrace_config.bts.size)
12717 {
12718 pos = buf;
12719 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12720 conf->bts.size);
12721
12722 putpkt (buf);
12723 getpkt (&buf, &rs->buf_size, 0);
12724
12725 if (packet_ok (buf, packet) == PACKET_ERROR)
12726 {
12727 if (buf[0] == 'E' && buf[1] == '.')
12728 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12729 else
12730 error (_("Failed to configure the BTS buffer size."));
12731 }
12732
12733 rs->btrace_config.bts.size = conf->bts.size;
12734 }
b20a6524
MM
12735
12736 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12737 if (packet_config_support (packet) == PACKET_ENABLE
12738 && conf->pt.size != rs->btrace_config.pt.size)
12739 {
12740 pos = buf;
12741 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12742 conf->pt.size);
12743
12744 putpkt (buf);
12745 getpkt (&buf, &rs->buf_size, 0);
12746
12747 if (packet_ok (buf, packet) == PACKET_ERROR)
12748 {
12749 if (buf[0] == 'E' && buf[1] == '.')
12750 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12751 else
12752 error (_("Failed to configure the trace buffer size."));
12753 }
12754
12755 rs->btrace_config.pt.size = conf->pt.size;
12756 }
f4abbc16
MM
12757}
12758
12759/* Read the current thread's btrace configuration from the target and
12760 store it into CONF. */
12761
12762static void
12763btrace_read_config (struct btrace_config *conf)
12764{
12765 char *xml;
12766
12767 xml = target_read_stralloc (&current_target,
b20a6524 12768 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12769 if (xml != NULL)
12770 {
12771 struct cleanup *cleanup;
12772
12773 cleanup = make_cleanup (xfree, xml);
12774 parse_xml_btrace_conf (conf, xml);
12775 do_cleanups (cleanup);
12776 }
12777}
12778
9accd112
MM
12779/* Enable branch tracing. */
12780
12781static struct btrace_target_info *
f4abbc16
MM
12782remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12783 const struct btrace_config *conf)
9accd112
MM
12784{
12785 struct btrace_target_info *tinfo = NULL;
b20a6524 12786 struct packet_config *packet = NULL;
9accd112
MM
12787 struct remote_state *rs = get_remote_state ();
12788 char *buf = rs->buf;
12789 char *endbuf = rs->buf + get_remote_packet_size ();
12790
b20a6524
MM
12791 switch (conf->format)
12792 {
12793 case BTRACE_FORMAT_BTS:
12794 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12795 break;
12796
12797 case BTRACE_FORMAT_PT:
12798 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12799 break;
12800 }
12801
12802 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12803 error (_("Target does not support branch tracing."));
12804
f4abbc16
MM
12805 btrace_sync_conf (conf);
12806
9accd112
MM
12807 set_general_thread (ptid);
12808
12809 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12810 putpkt (rs->buf);
12811 getpkt (&rs->buf, &rs->buf_size, 0);
12812
12813 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12814 {
12815 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12816 error (_("Could not enable branch tracing for %s: %s"),
12817 target_pid_to_str (ptid), rs->buf + 2);
12818 else
12819 error (_("Could not enable branch tracing for %s."),
12820 target_pid_to_str (ptid));
12821 }
12822
8d749320 12823 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12824 tinfo->ptid = ptid;
12825
f4abbc16
MM
12826 /* If we fail to read the configuration, we lose some information, but the
12827 tracing itself is not impacted. */
492d29ea
PA
12828 TRY
12829 {
12830 btrace_read_config (&tinfo->conf);
12831 }
12832 CATCH (err, RETURN_MASK_ERROR)
12833 {
12834 if (err.message != NULL)
12835 warning ("%s", err.message);
12836 }
12837 END_CATCH
f4abbc16 12838
9accd112
MM
12839 return tinfo;
12840}
12841
12842/* Disable branch tracing. */
12843
12844static void
25e95349
TT
12845remote_disable_btrace (struct target_ops *self,
12846 struct btrace_target_info *tinfo)
9accd112
MM
12847{
12848 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12849 struct remote_state *rs = get_remote_state ();
12850 char *buf = rs->buf;
12851 char *endbuf = rs->buf + get_remote_packet_size ();
12852
4082afcc 12853 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12854 error (_("Target does not support branch tracing."));
12855
12856 set_general_thread (tinfo->ptid);
12857
12858 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12859 putpkt (rs->buf);
12860 getpkt (&rs->buf, &rs->buf_size, 0);
12861
12862 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12863 {
12864 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12865 error (_("Could not disable branch tracing for %s: %s"),
12866 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12867 else
12868 error (_("Could not disable branch tracing for %s."),
12869 target_pid_to_str (tinfo->ptid));
12870 }
12871
12872 xfree (tinfo);
12873}
12874
12875/* Teardown branch tracing. */
12876
12877static void
1777056d
TT
12878remote_teardown_btrace (struct target_ops *self,
12879 struct btrace_target_info *tinfo)
9accd112
MM
12880{
12881 /* We must not talk to the target during teardown. */
12882 xfree (tinfo);
12883}
12884
12885/* Read the branch trace. */
12886
969c39fb 12887static enum btrace_error
39c49f83 12888remote_read_btrace (struct target_ops *self,
734b0e4b 12889 struct btrace_data *btrace,
969c39fb 12890 struct btrace_target_info *tinfo,
9accd112
MM
12891 enum btrace_read_type type)
12892{
12893 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
969c39fb 12894 struct cleanup *cleanup;
9accd112
MM
12895 const char *annex;
12896 char *xml;
12897
4082afcc 12898 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12899 error (_("Target does not support branch tracing."));
12900
12901#if !defined(HAVE_LIBEXPAT)
12902 error (_("Cannot process branch tracing result. XML parsing not supported."));
12903#endif
12904
12905 switch (type)
12906 {
864089d2 12907 case BTRACE_READ_ALL:
9accd112
MM
12908 annex = "all";
12909 break;
864089d2 12910 case BTRACE_READ_NEW:
9accd112
MM
12911 annex = "new";
12912 break;
969c39fb
MM
12913 case BTRACE_READ_DELTA:
12914 annex = "delta";
12915 break;
9accd112
MM
12916 default:
12917 internal_error (__FILE__, __LINE__,
12918 _("Bad branch tracing read type: %u."),
12919 (unsigned int) type);
12920 }
12921
12922 xml = target_read_stralloc (&current_target,
b20a6524 12923 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12924 if (xml == NULL)
12925 return BTRACE_ERR_UNKNOWN;
9accd112 12926
969c39fb 12927 cleanup = make_cleanup (xfree, xml);
734b0e4b 12928 parse_xml_btrace (btrace, xml);
969c39fb 12929 do_cleanups (cleanup);
9accd112 12930
969c39fb 12931 return BTRACE_ERR_NONE;
9accd112
MM
12932}
12933
f4abbc16
MM
12934static const struct btrace_config *
12935remote_btrace_conf (struct target_ops *self,
12936 const struct btrace_target_info *tinfo)
12937{
12938 return &tinfo->conf;
12939}
12940
ced63ec0 12941static int
5436ff03 12942remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12943{
4082afcc
PA
12944 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12945 == PACKET_ENABLE);
ced63ec0
GB
12946}
12947
9dd130a0
TT
12948/* Implementation of to_load. */
12949
12950static void
9cbe5fff 12951remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12952{
12953 generic_load (name, from_tty);
12954}
12955
c78fa86a
GB
12956/* Accepts an integer PID; returns a string representing a file that
12957 can be opened on the remote side to get the symbols for the child
12958 process. Returns NULL if the operation is not supported. */
12959
12960static char *
12961remote_pid_to_exec_file (struct target_ops *self, int pid)
12962{
12963 static char *filename = NULL;
835205d0
GB
12964 struct inferior *inf;
12965 char *annex = NULL;
c78fa86a
GB
12966
12967 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12968 return NULL;
12969
12970 if (filename != NULL)
12971 xfree (filename);
12972
835205d0
GB
12973 inf = find_inferior_pid (pid);
12974 if (inf == NULL)
12975 internal_error (__FILE__, __LINE__,
12976 _("not currently attached to process %d"), pid);
12977
12978 if (!inf->fake_pid_p)
12979 {
12980 const int annex_size = 9;
12981
224c3ddb 12982 annex = (char *) alloca (annex_size);
835205d0
GB
12983 xsnprintf (annex, annex_size, "%x", pid);
12984 }
12985
c78fa86a
GB
12986 filename = target_read_stralloc (&current_target,
12987 TARGET_OBJECT_EXEC_FILE, annex);
12988
12989 return filename;
12990}
12991
750ce8d1
YQ
12992/* Implement the to_can_do_single_step target_ops method. */
12993
12994static int
12995remote_can_do_single_step (struct target_ops *ops)
12996{
12997 /* We can only tell whether target supports single step or not by
12998 supported s and S vCont actions if the stub supports vContSupported
12999 feature. If the stub doesn't support vContSupported feature,
13000 we have conservatively to think target doesn't supports single
13001 step. */
13002 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13003 {
13004 struct remote_state *rs = get_remote_state ();
13005
13006 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13007 remote_vcont_probe (rs);
13008
13009 return rs->supports_vCont.s && rs->supports_vCont.S;
13010 }
13011 else
13012 return 0;
13013}
13014
3a00c802
PA
13015/* Implementation of the to_execution_direction method for the remote
13016 target. */
13017
13018static enum exec_direction_kind
13019remote_execution_direction (struct target_ops *self)
13020{
13021 struct remote_state *rs = get_remote_state ();
13022
13023 return rs->last_resume_exec_dir;
13024}
13025
c906108c 13026static void
fba45db2 13027init_remote_ops (void)
c906108c 13028{
c5aa993b 13029 remote_ops.to_shortname = "remote";
c906108c 13030 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 13031 remote_ops.to_doc =
c906108c 13032 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
13033Specify the serial device it is connected to\n\
13034(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
13035 remote_ops.to_open = remote_open;
13036 remote_ops.to_close = remote_close;
c906108c 13037 remote_ops.to_detach = remote_detach;
6ad8ae5c 13038 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 13039 remote_ops.to_resume = remote_resume;
c906108c
SS
13040 remote_ops.to_wait = remote_wait;
13041 remote_ops.to_fetch_registers = remote_fetch_registers;
13042 remote_ops.to_store_registers = remote_store_registers;
13043 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 13044 remote_ops.to_files_info = remote_files_info;
c906108c
SS
13045 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13046 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
13047 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13048 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13049 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13050 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
13051 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13052 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
13053 remote_ops.to_watchpoint_addr_within_range =
13054 remote_watchpoint_addr_within_range;
3c3bea1c
GS
13055 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13056 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13057 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
13058 remote_ops.to_region_ok_for_hw_watchpoint
13059 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
13060 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13061 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 13062 remote_ops.to_kill = remote_kill;
9dd130a0 13063 remote_ops.to_load = remote_load;
c906108c 13064 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 13065 remote_ops.to_pass_signals = remote_pass_signals;
82075af2 13066 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
9b224c5e 13067 remote_ops.to_program_signals = remote_program_signals;
c906108c 13068 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 13069 remote_ops.to_thread_name = remote_thread_name;
e8032dde 13070 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 13071 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 13072 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 13073 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 13074 remote_ops.to_stop = remote_stop;
bfedc46a 13075 remote_ops.to_interrupt = remote_interrupt;
93692b58 13076 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
4b8a223f 13077 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 13078 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 13079 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 13080 remote_ops.to_log_command = serial_log_command;
38691318 13081 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 13082 remote_ops.to_stratum = process_stratum;
c35b1492
PA
13083 remote_ops.to_has_all_memory = default_child_has_all_memory;
13084 remote_ops.to_has_memory = default_child_has_memory;
13085 remote_ops.to_has_stack = default_child_has_stack;
13086 remote_ops.to_has_registers = default_child_has_registers;
13087 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 13088 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13089 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13090 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13091 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13092 remote_ops.to_flash_erase = remote_flash_erase;
13093 remote_ops.to_flash_done = remote_flash_done;
29709017 13094 remote_ops.to_read_description = remote_read_description;
08388c79 13095 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13096 remote_ops.to_can_async_p = remote_can_async_p;
13097 remote_ops.to_is_async_p = remote_is_async_p;
13098 remote_ops.to_async = remote_async;
65706a29 13099 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13100 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13101 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13102 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13103 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13104 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13105 remote_ops.to_supports_disable_randomization
13106 = remote_supports_disable_randomization;
4bd7dc42 13107 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13108 remote_ops.to_fileio_open = remote_hostio_open;
13109 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13110 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13111 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13112 remote_ops.to_fileio_close = remote_hostio_close;
13113 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13114 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13115 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13116 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13117 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13118 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13119 remote_ops.to_trace_init = remote_trace_init;
13120 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13121 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13122 remote_ops.to_download_trace_state_variable
13123 = remote_download_trace_state_variable;
d248b706
KY
13124 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13125 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13126 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13127 remote_ops.to_trace_start = remote_trace_start;
13128 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13129 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13130 remote_ops.to_trace_stop = remote_trace_stop;
13131 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13132 remote_ops.to_get_trace_state_variable_value
13133 = remote_get_trace_state_variable_value;
00bf0b85
SS
13134 remote_ops.to_save_trace_data = remote_save_trace_data;
13135 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13136 remote_ops.to_upload_trace_state_variables
13137 = remote_upload_trace_state_variables;
00bf0b85 13138 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13139 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13140 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13141 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13142 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13143 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13144 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13145 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13146 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13147 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13148 remote_ops.to_static_tracepoint_marker_at
13149 = remote_static_tracepoint_marker_at;
13150 remote_ops.to_static_tracepoint_markers_by_strid
13151 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13152 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13153 remote_ops.to_use_agent = remote_use_agent;
13154 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13155 remote_ops.to_supports_btrace = remote_supports_btrace;
13156 remote_ops.to_enable_btrace = remote_enable_btrace;
13157 remote_ops.to_disable_btrace = remote_disable_btrace;
13158 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13159 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13160 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13161 remote_ops.to_augmented_libraries_svr4_read =
13162 remote_augmented_libraries_svr4_read;
8020350c
DB
13163 remote_ops.to_follow_fork = remote_follow_fork;
13164 remote_ops.to_follow_exec = remote_follow_exec;
13165 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13166 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13167 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13168 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13169 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13170 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
3a00c802 13171 remote_ops.to_execution_direction = remote_execution_direction;
c906108c
SS
13172}
13173
13174/* Set up the extended remote vector by making a copy of the standard
13175 remote vector and adding to it. */
13176
13177static void
fba45db2 13178init_extended_remote_ops (void)
c906108c
SS
13179{
13180 extended_remote_ops = remote_ops;
13181
0f71a2f6 13182 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13183 extended_remote_ops.to_longname =
c906108c 13184 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13185 extended_remote_ops.to_doc =
c906108c 13186 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13187Specify the serial device it is connected to (e.g. /dev/ttya).";
13188 extended_remote_ops.to_open = extended_remote_open;
c906108c 13189 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
2d717e4f
DJ
13190 extended_remote_ops.to_detach = extended_remote_detach;
13191 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13192 extended_remote_ops.to_post_attach = extended_remote_post_attach;
03583c20
UW
13193 extended_remote_ops.to_supports_disable_randomization
13194 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
13195}
13196
6426a772 13197static int
6a109b6b 13198remote_can_async_p (struct target_ops *ops)
6426a772 13199{
5d93a237
TT
13200 struct remote_state *rs = get_remote_state ();
13201
c6ebd6cf 13202 if (!target_async_permitted)
75c99385
PA
13203 /* We only enable async when the user specifically asks for it. */
13204 return 0;
13205
23860348 13206 /* We're async whenever the serial device is. */
5d93a237 13207 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13208}
13209
13210static int
6a109b6b 13211remote_is_async_p (struct target_ops *ops)
6426a772 13212{
5d93a237
TT
13213 struct remote_state *rs = get_remote_state ();
13214
c6ebd6cf 13215 if (!target_async_permitted)
75c99385
PA
13216 /* We only enable async when the user specifically asks for it. */
13217 return 0;
13218
23860348 13219 /* We're async whenever the serial device is. */
5d93a237 13220 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13221}
13222
2acceee2
JM
13223/* Pass the SERIAL event on and up to the client. One day this code
13224 will be able to delay notifying the client of an event until the
23860348 13225 point where an entire packet has been received. */
2acceee2 13226
2acceee2
JM
13227static serial_event_ftype remote_async_serial_handler;
13228
6426a772 13229static void
819cc324 13230remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13231{
2acceee2
JM
13232 /* Don't propogate error information up to the client. Instead let
13233 the client find out about the error by querying the target. */
6a3753b3 13234 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13235}
13236
74531fed
PA
13237static void
13238remote_async_inferior_event_handler (gdb_client_data data)
13239{
13240 inferior_event_handler (INF_REG_EVENT, NULL);
13241}
13242
2acceee2 13243static void
6a3753b3 13244remote_async (struct target_ops *ops, int enable)
2acceee2 13245{
5d93a237
TT
13246 struct remote_state *rs = get_remote_state ();
13247
6a3753b3 13248 if (enable)
2acceee2 13249 {
88b496c3 13250 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13251
13252 /* If there are pending events in the stop reply queue tell the
13253 event loop to process them. */
13254 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13255 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13256 /* For simplicity, below we clear the pending events token
13257 without remembering whether it is marked, so here we always
13258 mark it. If there's actually no pending notification to
13259 process, this ends up being a no-op (other than a spurious
13260 event-loop wakeup). */
13261 if (target_is_non_stop_p ())
13262 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13263 }
13264 else
b7d2e916
PA
13265 {
13266 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13267 /* If the core is disabling async, it doesn't want to be
13268 disturbed with target events. Clear all async event sources
13269 too. */
b7d2e916 13270 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13271 if (target_is_non_stop_p ())
13272 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13273 }
6426a772
JM
13274}
13275
65706a29
PA
13276/* Implementation of the to_thread_events method. */
13277
13278static void
13279remote_thread_events (struct target_ops *ops, int enable)
13280{
13281 struct remote_state *rs = get_remote_state ();
13282 size_t size = get_remote_packet_size ();
65706a29
PA
13283
13284 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13285 return;
13286
13287 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13288 putpkt (rs->buf);
13289 getpkt (&rs->buf, &rs->buf_size, 0);
13290
13291 switch (packet_ok (rs->buf,
13292 &remote_protocol_packets[PACKET_QThreadEvents]))
13293 {
13294 case PACKET_OK:
13295 if (strcmp (rs->buf, "OK") != 0)
13296 error (_("Remote refused setting thread events: %s"), rs->buf);
13297 break;
13298 case PACKET_ERROR:
13299 warning (_("Remote failure reply: %s"), rs->buf);
13300 break;
13301 case PACKET_UNKNOWN:
13302 break;
13303 }
13304}
13305
5a2468f5 13306static void
c2d11a7d 13307set_remote_cmd (char *args, int from_tty)
5a2468f5 13308{
635c7e8a 13309 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13310}
13311
d471ea57
AC
13312static void
13313show_remote_cmd (char *args, int from_tty)
13314{
37a105a1 13315 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13316 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13317 struct cleanup *showlist_chain;
13318 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13319 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13320
13321 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13322 for (; list != NULL; list = list->next)
13323 if (strcmp (list->name, "Z-packet") == 0)
13324 continue;
427c3a89
DJ
13325 else if (list->type == not_set_cmd)
13326 /* Alias commands are exactly like the original, except they
13327 don't have the normal type. */
13328 continue;
13329 else
37a105a1
DJ
13330 {
13331 struct cleanup *option_chain
13332 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13333
37a105a1
DJ
13334 ui_out_field_string (uiout, "name", list->name);
13335 ui_out_text (uiout, ": ");
427c3a89 13336 if (list->type == show_cmd)
5b9afe8a 13337 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
13338 else
13339 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13340 /* Close the tuple. */
13341 do_cleanups (option_chain);
13342 }
427c3a89
DJ
13343
13344 /* Close the tuple. */
13345 do_cleanups (showlist_chain);
d471ea57 13346}
5a2468f5 13347
0f71a2f6 13348
23860348 13349/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13350static void
13351remote_new_objfile (struct objfile *objfile)
13352{
5d93a237
TT
13353 struct remote_state *rs = get_remote_state ();
13354
13355 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13356 remote_check_symbols ();
dc8acb97
MS
13357}
13358
00bf0b85
SS
13359/* Pull all the tracepoints defined on the target and create local
13360 data structures representing them. We don't want to create real
13361 tracepoints yet, we don't want to mess up the user's existing
13362 collection. */
13363
13364static int
ab6617cc 13365remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13366{
00bf0b85
SS
13367 struct remote_state *rs = get_remote_state ();
13368 char *p;
d5551862 13369
00bf0b85
SS
13370 /* Ask for a first packet of tracepoint definition. */
13371 putpkt ("qTfP");
13372 getpkt (&rs->buf, &rs->buf_size, 0);
13373 p = rs->buf;
13374 while (*p && *p != 'l')
d5551862 13375 {
00bf0b85
SS
13376 parse_tracepoint_definition (p, utpp);
13377 /* Ask for another packet of tracepoint definition. */
13378 putpkt ("qTsP");
13379 getpkt (&rs->buf, &rs->buf_size, 0);
13380 p = rs->buf;
d5551862 13381 }
00bf0b85 13382 return 0;
d5551862
SS
13383}
13384
00bf0b85 13385static int
181e3713
TT
13386remote_upload_trace_state_variables (struct target_ops *self,
13387 struct uploaded_tsv **utsvp)
d5551862 13388{
00bf0b85 13389 struct remote_state *rs = get_remote_state ();
d5551862 13390 char *p;
d5551862 13391
00bf0b85
SS
13392 /* Ask for a first packet of variable definition. */
13393 putpkt ("qTfV");
d5551862
SS
13394 getpkt (&rs->buf, &rs->buf_size, 0);
13395 p = rs->buf;
00bf0b85 13396 while (*p && *p != 'l')
d5551862 13397 {
00bf0b85
SS
13398 parse_tsv_definition (p, utsvp);
13399 /* Ask for another packet of variable definition. */
13400 putpkt ("qTsV");
d5551862
SS
13401 getpkt (&rs->buf, &rs->buf_size, 0);
13402 p = rs->buf;
13403 }
00bf0b85 13404 return 0;
d5551862
SS
13405}
13406
c1e36e3e
PA
13407/* The "set/show range-stepping" show hook. */
13408
13409static void
13410show_range_stepping (struct ui_file *file, int from_tty,
13411 struct cmd_list_element *c,
13412 const char *value)
13413{
13414 fprintf_filtered (file,
13415 _("Debugger's willingness to use range stepping "
13416 "is %s.\n"), value);
13417}
13418
13419/* The "set/show range-stepping" set hook. */
13420
13421static void
13422set_range_stepping (char *ignore_args, int from_tty,
13423 struct cmd_list_element *c)
13424{
5d93a237
TT
13425 struct remote_state *rs = get_remote_state ();
13426
c1e36e3e
PA
13427 /* Whene enabling, check whether range stepping is actually
13428 supported by the target, and warn if not. */
13429 if (use_range_stepping)
13430 {
5d93a237 13431 if (rs->remote_desc != NULL)
c1e36e3e 13432 {
4082afcc 13433 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13434 remote_vcont_probe (rs);
13435
4082afcc 13436 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13437 && rs->supports_vCont.r)
13438 return;
13439 }
13440
13441 warning (_("Range stepping is not supported by the current target"));
13442 }
13443}
13444
c906108c 13445void
fba45db2 13446_initialize_remote (void)
c906108c 13447{
9a7071a8 13448 struct cmd_list_element *cmd;
6f937416 13449 const char *cmd_name;
ea9c271d 13450
0f71a2f6 13451 /* architecture specific data */
2bc416ba 13452 remote_gdbarch_data_handle =
23860348 13453 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13454 remote_g_packet_data_handle =
13455 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13456
94585166
DB
13457 remote_pspace_data
13458 = register_program_space_data_with_cleanup (NULL,
13459 remote_pspace_data_cleanup);
13460
ea9c271d
DJ
13461 /* Initialize the per-target state. At the moment there is only one
13462 of these, not one per target. Only one target is active at a
cf792862
TT
13463 time. */
13464 remote_state = new_remote_state ();
ea9c271d 13465
c906108c
SS
13466 init_remote_ops ();
13467 add_target (&remote_ops);
13468
13469 init_extended_remote_ops ();
13470 add_target (&extended_remote_ops);
cce74817 13471
dc8acb97 13472 /* Hook into new objfile notification. */
06d3b283 13473 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13474 /* We're no longer interested in notification events of an inferior
13475 when it exits. */
13476 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13477
c906108c
SS
13478#if 0
13479 init_remote_threadtests ();
13480#endif
13481
722247f1 13482 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13483 /* set/show remote ... */
d471ea57 13484
1bedd215 13485 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13486Remote protocol specific variables\n\
13487Configure various remote-protocol specific variables such as\n\
1bedd215 13488the packets being used"),
cff3e48b 13489 &remote_set_cmdlist, "set remote ",
23860348 13490 0 /* allow-unknown */, &setlist);
1bedd215 13491 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13492Remote protocol specific variables\n\
13493Configure various remote-protocol specific variables such as\n\
1bedd215 13494the packets being used"),
cff3e48b 13495 &remote_show_cmdlist, "show remote ",
23860348 13496 0 /* allow-unknown */, &showlist);
5a2468f5 13497
1a966eab
AC
13498 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13499Compare section data on target to the exec file.\n\
95cf3b38
DT
13500Argument is a single section name (default: all loaded sections).\n\
13501To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13502 &cmdlist);
13503
1a966eab
AC
13504 add_cmd ("packet", class_maintenance, packet_command, _("\
13505Send an arbitrary packet to a remote target.\n\
c906108c
SS
13506 maintenance packet TEXT\n\
13507If GDB is talking to an inferior via the GDB serial protocol, then\n\
13508this command sends the string TEXT to the inferior, and displays the\n\
13509response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13510terminating `#' character and checksum."),
c906108c
SS
13511 &maintenancelist);
13512
7915a72c
AC
13513 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13514Set whether to send break if interrupted."), _("\
13515Show whether to send break if interrupted."), _("\
13516If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13517 set_remotebreak, show_remotebreak,
e707bbc2 13518 &setlist, &showlist);
9a7071a8
JB
13519 cmd_name = "remotebreak";
13520 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13521 deprecate_cmd (cmd, "set remote interrupt-sequence");
13522 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13523 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13524 deprecate_cmd (cmd, "show remote interrupt-sequence");
13525
13526 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13527 interrupt_sequence_modes, &interrupt_sequence_mode,
13528 _("\
9a7071a8
JB
13529Set interrupt sequence to remote target."), _("\
13530Show interrupt sequence to remote target."), _("\
13531Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13532 NULL, show_interrupt_sequence,
13533 &remote_set_cmdlist,
13534 &remote_show_cmdlist);
13535
13536 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13537 &interrupt_on_connect, _("\
13538Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13539Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13540If set, interrupt sequence is sent to remote target."),
13541 NULL, NULL,
13542 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13543
23860348 13544 /* Install commands for configuring memory read/write packets. */
11cf8741 13545
1a966eab
AC
13546 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13547Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13548 &setlist);
1a966eab
AC
13549 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13550Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13551 &showlist);
13552 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13553 set_memory_write_packet_size, _("\
13554Set the maximum number of bytes per memory-write packet.\n\
13555Specify the number of bytes in a packet or 0 (zero) for the\n\
13556default packet size. The actual limit is further reduced\n\
13557dependent on the target. Specify ``fixed'' to disable the\n\
13558further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13559 &remote_set_cmdlist);
13560 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13561 set_memory_read_packet_size, _("\
13562Set the maximum number of bytes per memory-read packet.\n\
13563Specify the number of bytes in a packet or 0 (zero) for the\n\
13564default packet size. The actual limit is further reduced\n\
13565dependent on the target. Specify ``fixed'' to disable the\n\
13566further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13567 &remote_set_cmdlist);
13568 add_cmd ("memory-write-packet-size", no_class,
13569 show_memory_write_packet_size,
1a966eab 13570 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13571 &remote_show_cmdlist);
13572 add_cmd ("memory-read-packet-size", no_class,
13573 show_memory_read_packet_size,
1a966eab 13574 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13575 &remote_show_cmdlist);
c906108c 13576
b3f42336 13577 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13578 &remote_hw_watchpoint_limit, _("\
13579Set the maximum number of target hardware watchpoints."), _("\
13580Show the maximum number of target hardware watchpoints."), _("\
13581Specify a negative limit for unlimited."),
3e43a32a
MS
13582 NULL, NULL, /* FIXME: i18n: The maximum
13583 number of target hardware
13584 watchpoints is %s. */
b3f42336 13585 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13586 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13587 &remote_hw_watchpoint_length_limit, _("\
13588Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13589Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13590Specify a negative limit for unlimited."),
13591 NULL, NULL, /* FIXME: i18n: The maximum
13592 length (in bytes) of a target
13593 hardware watchpoint is %s. */
13594 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13595 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13596 &remote_hw_breakpoint_limit, _("\
13597Set the maximum number of target hardware breakpoints."), _("\
13598Show the maximum number of target hardware breakpoints."), _("\
13599Specify a negative limit for unlimited."),
3e43a32a
MS
13600 NULL, NULL, /* FIXME: i18n: The maximum
13601 number of target hardware
13602 breakpoints is %s. */
b3f42336 13603 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13604
1b493192
PA
13605 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13606 &remote_address_size, _("\
4d28ad1e
AC
13607Set the maximum size of the address (in bits) in a memory packet."), _("\
13608Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13609 NULL,
13610 NULL, /* FIXME: i18n: */
13611 &setlist, &showlist);
c906108c 13612
ca4f7f8b
PA
13613 init_all_packet_configs ();
13614
444abaca 13615 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13616 "X", "binary-download", 1);
0f71a2f6 13617
444abaca 13618 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13619 "vCont", "verbose-resume", 0);
506fb367 13620
89be2091
DJ
13621 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13622 "QPassSignals", "pass-signals", 0);
13623
82075af2
JS
13624 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13625 "QCatchSyscalls", "catch-syscalls", 0);
13626
9b224c5e
PA
13627 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13628 "QProgramSignals", "program-signals", 0);
13629
444abaca 13630 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13631 "qSymbol", "symbol-lookup", 0);
dc8acb97 13632
444abaca 13633 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13634 "P", "set-register", 1);
d471ea57 13635
444abaca 13636 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13637 "p", "fetch-register", 1);
b96ec7ac 13638
444abaca 13639 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13640 "Z0", "software-breakpoint", 0);
d471ea57 13641
444abaca 13642 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13643 "Z1", "hardware-breakpoint", 0);
d471ea57 13644
444abaca 13645 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13646 "Z2", "write-watchpoint", 0);
d471ea57 13647
444abaca 13648 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13649 "Z3", "read-watchpoint", 0);
d471ea57 13650
444abaca 13651 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13652 "Z4", "access-watchpoint", 0);
d471ea57 13653
0876f84a
DJ
13654 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13655 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13656
c78fa86a
GB
13657 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13658 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13659
23181151
DJ
13660 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13661 "qXfer:features:read", "target-features", 0);
13662
cfa9d6d9
DJ
13663 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13664 "qXfer:libraries:read", "library-info", 0);
13665
2268b414
JK
13666 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13667 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13668
fd79ecee
DJ
13669 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13670 "qXfer:memory-map:read", "memory-map", 0);
13671
0e7f50da
UW
13672 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13673 "qXfer:spu:read", "read-spu-object", 0);
13674
13675 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13676 "qXfer:spu:write", "write-spu-object", 0);
13677
07e059b5
VP
13678 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13679 "qXfer:osdata:read", "osdata", 0);
13680
dc146f7c
VP
13681 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13682 "qXfer:threads:read", "threads", 0);
13683
4aa995e1
PA
13684 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13685 "qXfer:siginfo:read", "read-siginfo-object", 0);
13686
13687 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13688 "qXfer:siginfo:write", "write-siginfo-object", 0);
13689
b3b9301e
PA
13690 add_packet_config_cmd
13691 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13692 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13693
169081d0
TG
13694 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13695 "qXfer:uib:read", "unwind-info-block", 0);
13696
444abaca 13697 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13698 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13699 0);
13700
711e434b
PM
13701 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13702 "qGetTIBAddr", "get-thread-information-block-address",
13703 0);
13704
40ab02ce
MS
13705 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13706 "bc", "reverse-continue", 0);
13707
13708 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13709 "bs", "reverse-step", 0);
13710
be2a5f71
DJ
13711 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13712 "qSupported", "supported-packets", 0);
13713
08388c79
DE
13714 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13715 "qSearch:memory", "search-memory", 0);
13716
bd3eecc3
PA
13717 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13718 "qTStatus", "trace-status", 0);
13719
15a201c8
GB
13720 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13721 "vFile:setfs", "hostio-setfs", 0);
13722
a6b151f1
DJ
13723 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13724 "vFile:open", "hostio-open", 0);
13725
13726 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13727 "vFile:pread", "hostio-pread", 0);
13728
13729 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13730 "vFile:pwrite", "hostio-pwrite", 0);
13731
13732 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13733 "vFile:close", "hostio-close", 0);
13734
13735 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13736 "vFile:unlink", "hostio-unlink", 0);
13737
b9e7b9c3
UW
13738 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13739 "vFile:readlink", "hostio-readlink", 0);
13740
0a93529c
GB
13741 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13742 "vFile:fstat", "hostio-fstat", 0);
13743
2d717e4f
DJ
13744 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13745 "vAttach", "attach", 0);
13746
13747 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13748 "vRun", "run", 0);
13749
a6f3e723
SL
13750 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13751 "QStartNoAckMode", "noack", 0);
13752
82f73884
PA
13753 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13754 "vKill", "kill", 0);
13755
0b16c5cf
PA
13756 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13757 "qAttached", "query-attached", 0);
13758
782b2b07 13759 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13760 "ConditionalTracepoints",
13761 "conditional-tracepoints", 0);
3788aec7
LM
13762
13763 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13764 "ConditionalBreakpoints",
13765 "conditional-breakpoints", 0);
13766
d3ce09f5
SS
13767 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13768 "BreakpointCommands",
13769 "breakpoint-commands", 0);
13770
7a697b8d
SS
13771 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13772 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13773
409873ef
SS
13774 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13775 "TracepointSource", "TracepointSource", 0);
13776
d914c394
SS
13777 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13778 "QAllow", "allow", 0);
13779
0fb4aa4b
PA
13780 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13781 "StaticTracepoints", "static-tracepoints", 0);
13782
1e4d1764
YQ
13783 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13784 "InstallInTrace", "install-in-trace", 0);
13785
0fb4aa4b
PA
13786 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13787 "qXfer:statictrace:read", "read-sdata-object", 0);
13788
78d85199
YQ
13789 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13790 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13791
03583c20
UW
13792 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13793 "QDisableRandomization", "disable-randomization", 0);
13794
d1feda86
YQ
13795 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13796 "QAgent", "agent", 0);
13797
f6f899bf
HAQ
13798 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13799 "QTBuffer:size", "trace-buffer-size", 0);
13800
9accd112
MM
13801 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13802 "Qbtrace:off", "disable-btrace", 0);
13803
13804 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13805 "Qbtrace:bts", "enable-btrace-bts", 0);
13806
13807 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13808 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13809
13810 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13811 "qXfer:btrace", "read-btrace", 0);
13812
f4abbc16
MM
13813 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13814 "qXfer:btrace-conf", "read-btrace-conf", 0);
13815
d33501a5
MM
13816 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13817 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13818
73b8c1fd
PA
13819 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13820 "multiprocess-feature", "multiprocess-feature", 0);
13821
f7e6eed5
PA
13822 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13823 "swbreak-feature", "swbreak-feature", 0);
13824
13825 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13826 "hwbreak-feature", "hwbreak-feature", 0);
13827
89245bc0
DB
13828 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13829 "fork-event-feature", "fork-event-feature", 0);
13830
13831 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13832 "vfork-event-feature", "vfork-event-feature", 0);
13833
b20a6524
MM
13834 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13835 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13836
750ce8d1
YQ
13837 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13838 "vContSupported", "verbose-resume-supported", 0);
13839
94585166
DB
13840 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13841 "exec-event-feature", "exec-event-feature", 0);
13842
de979965
PA
13843 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13844 "vCtrlC", "ctrl-c", 0);
13845
65706a29
PA
13846 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13847 "QThreadEvents", "thread-events", 0);
13848
f2faf941
PA
13849 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13850 "N stop reply", "no-resumed-stop-reply", 0);
13851
0b736949
DB
13852 /* Assert that we've registered "set remote foo-packet" commands
13853 for all packet configs. */
ca4f7f8b
PA
13854 {
13855 int i;
13856
13857 for (i = 0; i < PACKET_MAX; i++)
13858 {
13859 /* Ideally all configs would have a command associated. Some
13860 still don't though. */
13861 int excepted;
13862
13863 switch (i)
13864 {
13865 case PACKET_QNonStop:
ca4f7f8b
PA
13866 case PACKET_EnableDisableTracepoints_feature:
13867 case PACKET_tracenz_feature:
13868 case PACKET_DisconnectedTracing_feature:
13869 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13870 case PACKET_qCRC:
13871 /* Additions to this list need to be well justified:
13872 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13873 excepted = 1;
13874 break;
13875 default:
13876 excepted = 0;
13877 break;
13878 }
13879
13880 /* This catches both forgetting to add a config command, and
13881 forgetting to remove a packet from the exception list. */
13882 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13883 }
13884 }
13885
37a105a1
DJ
13886 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13887 Z sub-packet has its own set and show commands, but users may
13888 have sets to this variable in their .gdbinit files (or in their
13889 documentation). */
e9e68a56 13890 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13891 &remote_Z_packet_detect, _("\
13892Set use of remote protocol `Z' packets"), _("\
13893Show use of remote protocol `Z' packets "), _("\
3b64bf98 13894When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13895packets."),
e9e68a56 13896 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13897 show_remote_protocol_Z_packet_cmd,
13898 /* FIXME: i18n: Use of remote protocol
13899 `Z' packets is %s. */
e9e68a56 13900 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13901
a6b151f1
DJ
13902 add_prefix_cmd ("remote", class_files, remote_command, _("\
13903Manipulate files on the remote system\n\
13904Transfer files to and from the remote target system."),
13905 &remote_cmdlist, "remote ",
13906 0 /* allow-unknown */, &cmdlist);
13907
13908 add_cmd ("put", class_files, remote_put_command,
13909 _("Copy a local file to the remote system."),
13910 &remote_cmdlist);
13911
13912 add_cmd ("get", class_files, remote_get_command,
13913 _("Copy a remote file to the local system."),
13914 &remote_cmdlist);
13915
13916 add_cmd ("delete", class_files, remote_delete_command,
13917 _("Delete a remote file."),
13918 &remote_cmdlist);
13919
2d717e4f 13920 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13921 &remote_exec_file_var, _("\
2d717e4f 13922Set the remote pathname for \"run\""), _("\
94585166
DB
13923Show the remote pathname for \"run\""), NULL,
13924 set_remote_exec_file,
13925 show_remote_exec_file,
13926 &remote_set_cmdlist,
13927 &remote_show_cmdlist);
2d717e4f 13928
c1e36e3e
PA
13929 add_setshow_boolean_cmd ("range-stepping", class_run,
13930 &use_range_stepping, _("\
13931Enable or disable range stepping."), _("\
13932Show whether target-assisted range stepping is enabled."), _("\
13933If on, and the target supports it, when stepping a source line, GDB\n\
13934tells the target to step the corresponding range of addresses itself instead\n\
13935of issuing multiple single-steps. This speeds up source level\n\
13936stepping. If off, GDB always issues single-steps, even if range\n\
13937stepping is supported by the target. The default is on."),
13938 set_range_stepping,
13939 show_range_stepping,
13940 &setlist,
13941 &showlist);
13942
449092f6
CV
13943 /* Eventually initialize fileio. See fileio.c */
13944 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13945
ba348170 13946 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13947 special ptids with it set to != 0. */
ba348170
PA
13948 magic_null_ptid = ptid_build (42000, -1, 1);
13949 not_sent_ptid = ptid_build (42000, -2, 1);
13950 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13951
13952 target_buf_size = 2048;
224c3ddb 13953 target_buf = (char *) xmalloc (target_buf_size);
c906108c 13954}
10760264 13955
This page took 2.912136 seconds and 4 git commands to generate.