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