Print the "file" command suggestion in exec_file_locate_attach
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
618f726f 3 Copyright (C) 1988-2016 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
35b1e5cc 73
0df8b418 74/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
75static char *target_buf;
76static long target_buf_size;
35b1e5cc 77
94585166
DB
78/* Per-program-space data key. */
79static const struct program_space_data *remote_pspace_data;
80
81/* The variable registered as the control variable used by the
82 remote exec-file commands. While the remote exec-file setting is
83 per-program-space, the set/show machinery uses this as the
84 location of the remote exec-file value. */
85static char *remote_exec_file_var;
86
6765f3e5
DJ
87/* The size to align memory write packets, when practical. The protocol
88 does not guarantee any alignment, and gdb will generate short
89 writes and unaligned writes, but even as a best-effort attempt this
90 can improve bulk transfers. For instance, if a write is misaligned
91 relative to the target's data bus, the stub may need to make an extra
92 round trip fetching data from the target. This doesn't make a
93 huge difference, but it's easy to do, so we try to be helpful.
94
95 The alignment chosen is arbitrary; usually data bus width is
96 important here, not the possibly larger cache line size. */
97enum { REMOTE_ALIGN_WRITES = 16 };
98
23860348 99/* Prototypes for local functions. */
934b9bac 100static void async_cleanup_sigint_signal_handler (void *dummy);
6d820c5c 101static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 102static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 103 int forever, int *is_notif);
6426a772 104
934b9bac
JK
105static void async_handle_remote_sigint (int);
106static void async_handle_remote_sigint_twice (int);
43ff13b4 107
a14ed312 108static void remote_files_info (struct target_ops *ignore);
c906108c 109
f32dbf8c
MM
110static void remote_prepare_to_store (struct target_ops *self,
111 struct regcache *regcache);
c906108c 112
014f9477
TT
113static void remote_open_1 (const char *, int, struct target_ops *,
114 int extended_p);
c906108c 115
de90e03d 116static void remote_close (struct target_ops *self);
c906108c 117
cbb8991c
DB
118struct remote_state;
119
120static int remote_vkill (int pid, struct remote_state *rs);
121
8020350c
DB
122static void remote_kill_k (void);
123
136d6dae 124static void remote_mourn (struct target_ops *ops);
c906108c 125
a14ed312 126static void extended_remote_restart (void);
c906108c 127
6d820c5c 128static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 129
a14ed312 130static int readchar (int timeout);
c906108c 131
c33e31fd
PA
132static void remote_serial_write (const char *str, int len);
133
7d85a9c0 134static void remote_kill (struct target_ops *ops);
c906108c 135
6a109b6b 136static int remote_can_async_p (struct target_ops *);
75c99385 137
6a109b6b 138static int remote_is_async_p (struct target_ops *);
75c99385 139
6a3753b3 140static void remote_async (struct target_ops *ops, int enable);
75c99385 141
65706a29
PA
142static void remote_thread_events (struct target_ops *ops, int enable);
143
934b9bac 144static void sync_remote_interrupt_twice (int signo);
7a292a7a 145
a14ed312 146static void interrupt_query (void);
c906108c 147
79d7f229
PA
148static void set_general_thread (struct ptid ptid);
149static void set_continue_thread (struct ptid ptid);
c906108c 150
a14ed312 151static void get_offsets (void);
c906108c 152
6d820c5c
DJ
153static void skip_frame (void);
154
155static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 156
a14ed312 157static int hexnumlen (ULONGEST num);
c906108c 158
a14ed312 159static void init_remote_ops (void);
c906108c 160
a14ed312 161static void init_extended_remote_ops (void);
c906108c 162
1eab8a48 163static void remote_stop (struct target_ops *self, ptid_t);
c906108c 164
a14ed312 165static int stubhex (int ch);
c906108c 166
a14ed312 167static int hexnumstr (char *, ULONGEST);
c906108c 168
a14ed312 169static int hexnumnstr (char *, ULONGEST, int);
2df3850c 170
a14ed312 171static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 172
baa336ce 173static void print_packet (const char *);
c906108c 174
a14ed312 175static void compare_sections_command (char *, int);
c906108c 176
a14ed312 177static void packet_command (char *, int);
c906108c 178
a14ed312 179static int stub_unpack_int (char *buff, int fieldlength);
c906108c 180
39f77062 181static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 182
baa336ce 183static int putpkt_binary (const char *buf, int cnt);
c906108c 184
a14ed312 185static void check_binary_download (CORE_ADDR addr);
c906108c 186
5a2468f5 187struct packet_config;
5a2468f5 188
a14ed312 189static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 190
bb572ddd
DJ
191static void show_remote_protocol_packet_cmd (struct ui_file *file,
192 int from_tty,
193 struct cmd_list_element *c,
194 const char *value);
195
82f73884
PA
196static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
197static ptid_t read_ptid (char *buf, char **obuf);
198
c378d69d 199static void remote_set_permissions (struct target_ops *self);
d914c394 200
8bd200f1
TT
201static int remote_get_trace_status (struct target_ops *self,
202 struct trace_status *ts);
d5551862 203
ab6617cc
TT
204static int remote_upload_tracepoints (struct target_ops *self,
205 struct uploaded_tp **utpp);
00bf0b85 206
181e3713
TT
207static int remote_upload_trace_state_variables (struct target_ops *self,
208 struct uploaded_tsv **utsvp);
00bf0b85 209
c8d104ad
PA
210static void remote_query_supported (void);
211
36d25514 212static void remote_check_symbols (void);
c8d104ad 213
a14ed312 214void _initialize_remote (void);
c906108c 215
74531fed 216struct stop_reply;
74531fed 217static void stop_reply_xfree (struct stop_reply *);
722247f1 218static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 219static void push_stop_reply (struct stop_reply *);
bcc75809 220static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
221static int peek_stop_reply (ptid_t ptid);
222
cbb8991c
DB
223struct threads_listing_context;
224static void remove_new_fork_children (struct threads_listing_context *);
225
74531fed 226static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 227
e3594fd1 228static void remote_terminal_ours (struct target_ops *self);
d3fd5342 229
d962ef82
DJ
230static int remote_read_description_p (struct target_ops *target);
231
176a6961 232static void remote_console_output (char *msg);
dde08ee1 233
efcc2da7 234static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 235
78eff0ec 236static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 237
f4abbc16
MM
238static void remote_btrace_reset (void);
239
221e1a37
PA
240static int stop_reply_queue_length (void);
241
80152258
PA
242static void readahead_cache_invalidate (void);
243
a6b151f1
DJ
244/* For "remote". */
245
246static struct cmd_list_element *remote_cmdlist;
247
bb572ddd
DJ
248/* For "set remote" and "show remote". */
249
250static struct cmd_list_element *remote_set_cmdlist;
251static struct cmd_list_element *remote_show_cmdlist;
252
d458bd84
PA
253/* Stub vCont actions support.
254
255 Each field is a boolean flag indicating whether the stub reports
256 support for the corresponding action. */
257
258struct vCont_action_support
259{
260 /* vCont;t */
261 int t;
c1e36e3e
PA
262
263 /* vCont;r */
264 int r;
750ce8d1
YQ
265
266 /* vCont;s */
267 int s;
268
269 /* vCont;S */
270 int S;
d458bd84
PA
271};
272
c1e36e3e
PA
273/* Controls whether GDB is willing to use range stepping. */
274
275static int use_range_stepping = 1;
276
0d031856
TT
277#define OPAQUETHREADBYTES 8
278
279/* a 64 bit opaque identifier */
280typedef unsigned char threadref[OPAQUETHREADBYTES];
281
282/* About this many threadisds fit in a packet. */
283
284#define MAXTHREADLISTRESULTS 32
285
80152258
PA
286/* Data for the vFile:pread readahead cache. */
287
288struct readahead_cache
289{
290 /* The file descriptor for the file that is being cached. -1 if the
291 cache is invalid. */
292 int fd;
293
294 /* The offset into the file that the cache buffer corresponds
295 to. */
296 ULONGEST offset;
297
298 /* The buffer holding the cache contents. */
299 gdb_byte *buf;
300 /* The buffer's size. We try to read as much as fits into a packet
301 at a time. */
302 size_t bufsize;
303
304 /* Cache hit and miss counters. */
305 ULONGEST hit_count;
306 ULONGEST miss_count;
307};
308
ea9c271d
DJ
309/* Description of the remote protocol state for the currently
310 connected target. This is per-target state, and independent of the
311 selected architecture. */
312
313struct remote_state
314{
315 /* A buffer to use for incoming packets, and its current size. The
316 buffer is grown dynamically for larger incoming packets.
317 Outgoing packets may also be constructed in this buffer.
318 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
319 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
320 packets. */
321 char *buf;
322 long buf_size;
be2a5f71 323
1e51243a
PA
324 /* True if we're going through initial connection setup (finding out
325 about the remote side's threads, relocating symbols, etc.). */
326 int starting_up;
327
be2a5f71
DJ
328 /* If we negotiated packet size explicitly (and thus can bypass
329 heuristics for the largest packet size that will not overflow
330 a buffer in the stub), this will be set to that packet size.
331 Otherwise zero, meaning to use the guessed size. */
332 long explicit_packet_size;
2d717e4f
DJ
333
334 /* remote_wait is normally called when the target is running and
335 waits for a stop reply packet. But sometimes we need to call it
336 when the target is already stopped. We can send a "?" packet
337 and have remote_wait read the response. Or, if we already have
338 the response, we can stash it in BUF and tell remote_wait to
339 skip calling getpkt. This flag is set when BUF contains a
340 stop reply packet and the target is not waiting. */
341 int cached_wait_status;
a6f3e723
SL
342
343 /* True, if in no ack mode. That is, neither GDB nor the stub will
344 expect acks from each other. The connection is assumed to be
345 reliable. */
346 int noack_mode;
82f73884
PA
347
348 /* True if we're connected in extended remote mode. */
349 int extended;
350
e24a49d8
PA
351 /* True if we resumed the target and we're waiting for the target to
352 stop. In the mean time, we can't start another command/query.
353 The remote server wouldn't be ready to process it, so we'd
354 timeout waiting for a reply that would never come and eventually
355 we'd close the connection. This can happen in asynchronous mode
356 because we allow GDB commands while the target is running. */
357 int waiting_for_stop_reply;
74531fed 358
d458bd84
PA
359 /* The status of the stub support for the various vCont actions. */
360 struct vCont_action_support supports_vCont;
782b2b07 361
3a29589a
DJ
362 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
363 responded to that. */
364 int ctrlc_pending_p;
5d93a237
TT
365
366 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
367 remote_open knows that we don't have a file open when the program
368 starts. */
369 struct serial *remote_desc;
47f8a51d
TT
370
371 /* These are the threads which we last sent to the remote system. The
372 TID member will be -1 for all or -2 for not sent yet. */
373 ptid_t general_thread;
374 ptid_t continue_thread;
262e1174
TT
375
376 /* This is the traceframe which we last selected on the remote system.
377 It will be -1 if no traceframe is selected. */
378 int remote_traceframe_number;
747dc59d
TT
379
380 char *last_pass_packet;
5e4a05c4
TT
381
382 /* The last QProgramSignals packet sent to the target. We bypass
383 sending a new program signals list down to the target if the new
384 packet is exactly the same as the last we sent. IOW, we only let
385 the target know about program signals list changes. */
386 char *last_program_signals_packet;
b73be471
TT
387
388 enum gdb_signal last_sent_signal;
280ceea3
TT
389
390 int last_sent_step;
8e88304f
TT
391
392 char *finished_object;
393 char *finished_annex;
394 ULONGEST finished_offset;
b80fafe3
TT
395
396 /* Should we try the 'ThreadInfo' query packet?
397
398 This variable (NOT available to the user: auto-detect only!)
399 determines whether GDB will use the new, simpler "ThreadInfo"
400 query or the older, more complex syntax for thread queries.
401 This is an auto-detect variable (set to true at each connect,
402 and set to false when the target fails to recognize it). */
403 int use_threadinfo_query;
404 int use_threadextra_query;
88b496c3 405
0d031856
TT
406 threadref echo_nextthread;
407 threadref nextthread;
408 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
409
410 /* The state of remote notification. */
411 struct remote_notif_state *notif_state;
f4abbc16
MM
412
413 /* The branch trace configuration. */
414 struct btrace_config btrace_config;
15a201c8
GB
415
416 /* The argument to the last "vFile:setfs:" packet we sent, used
417 to avoid sending repeated unnecessary "vFile:setfs:" packets.
418 Initialized to -1 to indicate that no "vFile:setfs:" packet
419 has yet been sent. */
420 int fs_pid;
80152258
PA
421
422 /* A readahead cache for vFile:pread. Often, reading a binary
423 involves a sequence of small reads. E.g., when parsing an ELF
424 file. A readahead cache helps mostly the case of remote
425 debugging on a connection with higher latency, due to the
426 request/reply nature of the RSP. We only cache data for a single
427 file descriptor at a time. */
428 struct readahead_cache readahead_cache;
ea9c271d
DJ
429};
430
dc146f7c
VP
431/* Private data that we'll store in (struct thread_info)->private. */
432struct private_thread_info
433{
434 char *extra;
79efa585 435 char *name;
dc146f7c 436 int core;
799a2abe
PA
437
438 /* Whether the target stopped for a breakpoint/watchpoint. */
439 enum target_stop_reason stop_reason;
440
441 /* This is set to the data address of the access causing the target
442 to stop for a watchpoint. */
443 CORE_ADDR watch_data_address;
dc146f7c
VP
444};
445
446static void
447free_private_thread_info (struct private_thread_info *info)
448{
449 xfree (info->extra);
79efa585 450 xfree (info->name);
dc146f7c
VP
451 xfree (info);
452}
453
ea9c271d
DJ
454/* This data could be associated with a target, but we do not always
455 have access to the current target when we need it, so for now it is
456 static. This will be fine for as long as only one target is in use
457 at a time. */
cf792862 458static struct remote_state *remote_state;
ea9c271d
DJ
459
460static struct remote_state *
0b83947e 461get_remote_state_raw (void)
ea9c271d 462{
cf792862
TT
463 return remote_state;
464}
465
466/* Allocate a new struct remote_state with xmalloc, initialize it, and
467 return it. */
468
469static struct remote_state *
470new_remote_state (void)
471{
472 struct remote_state *result = XCNEW (struct remote_state);
473
474 /* The default buffer size is unimportant; it will be expanded
475 whenever a larger buffer is needed. */
476 result->buf_size = 400;
224c3ddb 477 result->buf = (char *) xmalloc (result->buf_size);
262e1174 478 result->remote_traceframe_number = -1;
b73be471 479 result->last_sent_signal = GDB_SIGNAL_0;
15a201c8 480 result->fs_pid = -1;
cf792862
TT
481
482 return result;
ea9c271d
DJ
483}
484
485/* Description of the remote protocol for a given architecture. */
d01949b6 486
ad10f812
AC
487struct packet_reg
488{
489 long offset; /* Offset into G packet. */
490 long regnum; /* GDB's internal register number. */
491 LONGEST pnum; /* Remote protocol register number. */
b323314b 492 int in_g_packet; /* Always part of G packet. */
f5656ead 493 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 494 at present. */
f5656ead 495 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 496 at present. */
ad10f812
AC
497};
498
ea9c271d 499struct remote_arch_state
d01949b6 500{
ad10f812
AC
501 /* Description of the remote protocol registers. */
502 long sizeof_g_packet;
b323314b
AC
503
504 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 505 (making an array gdbarch_num_regs in size). */
b323314b 506 struct packet_reg *regs;
ad10f812 507
d01949b6
AC
508 /* This is the size (in chars) of the first response to the ``g''
509 packet. It is used as a heuristic when determining the maximum
510 size of memory-read and memory-write packets. A target will
511 typically only reserve a buffer large enough to hold the ``g''
512 packet. The size does not include packet overhead (headers and
23860348 513 trailers). */
d01949b6
AC
514 long actual_register_packet_size;
515
516 /* This is the maximum size (in chars) of a non read/write packet.
23860348 517 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
518 long remote_packet_size;
519};
520
35b1e5cc
SS
521/* Utility: generate error from an incoming stub packet. */
522static void
523trace_error (char *buf)
524{
525 if (*buf++ != 'E')
526 return; /* not an error msg */
527 switch (*buf)
528 {
529 case '1': /* malformed packet error */
530 if (*++buf == '0') /* general case: */
531 error (_("remote.c: error in outgoing packet."));
532 else
533 error (_("remote.c: error in outgoing packet at field #%ld."),
534 strtol (buf, NULL, 16));
35b1e5cc
SS
535 default:
536 error (_("Target returns error code '%s'."), buf);
537 }
538}
539
540/* Utility: wait for reply from stub, while accepting "O" packets. */
541static char *
542remote_get_noisy_reply (char **buf_p,
543 long *sizeof_buf)
544{
545 do /* Loop on reply from remote stub. */
546 {
547 char *buf;
a744cf53 548
0df8b418 549 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
550 getpkt (buf_p, sizeof_buf, 0);
551 buf = *buf_p;
ad91cd99 552 if (buf[0] == 'E')
35b1e5cc 553 trace_error (buf);
61012eef 554 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
555 {
556 ULONGEST ul;
557 CORE_ADDR from, to, org_to;
558 char *p, *pp;
559 int adjusted_size = 0;
7556d4a4 560 int relocated = 0;
dde08ee1
PA
561
562 p = buf + strlen ("qRelocInsn:");
563 pp = unpack_varlen_hex (p, &ul);
564 if (*pp != ';')
cb91c06a 565 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
566 from = ul;
567
568 p = pp + 1;
a9cbf802 569 unpack_varlen_hex (p, &ul);
dde08ee1
PA
570 to = ul;
571
572 org_to = to;
573
492d29ea 574 TRY
dde08ee1 575 {
f5656ead 576 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 577 relocated = 1;
dde08ee1 578 }
492d29ea 579 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
580 {
581 if (ex.error == MEMORY_ERROR)
582 {
583 /* Propagate memory errors silently back to the
584 target. The stub may have limited the range of
585 addresses we can write to, for example. */
586 }
587 else
588 {
589 /* Something unexpectedly bad happened. Be verbose
590 so we can tell what, and propagate the error back
591 to the stub, so it doesn't get stuck waiting for
592 a response. */
593 exception_fprintf (gdb_stderr, ex,
594 _("warning: relocating instruction: "));
595 }
596 putpkt ("E01");
597 }
492d29ea 598 END_CATCH
7556d4a4
PA
599
600 if (relocated)
dde08ee1
PA
601 {
602 adjusted_size = to - org_to;
603
bba74b36 604 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
605 putpkt (buf);
606 }
dde08ee1 607 }
ad91cd99 608 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
609 remote_console_output (buf + 1); /* 'O' message from stub */
610 else
0df8b418 611 return buf; /* Here's the actual reply. */
35b1e5cc
SS
612 }
613 while (1);
614}
3c3bea1c 615
d01949b6
AC
616/* Handle for retreving the remote protocol data from gdbarch. */
617static struct gdbarch_data *remote_gdbarch_data_handle;
618
ea9c271d
DJ
619static struct remote_arch_state *
620get_remote_arch_state (void)
d01949b6 621{
17d8546e 622 gdb_assert (target_gdbarch () != NULL);
19ba03f4
SM
623 return ((struct remote_arch_state *)
624 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
d01949b6
AC
625}
626
0b83947e
DJ
627/* Fetch the global remote target state. */
628
629static struct remote_state *
630get_remote_state (void)
631{
632 /* Make sure that the remote architecture state has been
633 initialized, because doing so might reallocate rs->buf. Any
634 function which calls getpkt also needs to be mindful of changes
635 to rs->buf, but this call limits the number of places which run
636 into trouble. */
637 get_remote_arch_state ();
638
639 return get_remote_state_raw ();
640}
641
94585166
DB
642/* Cleanup routine for the remote module's pspace data. */
643
644static void
645remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
646{
19ba03f4 647 char *remote_exec_file = (char *) arg;
94585166
DB
648
649 xfree (remote_exec_file);
650}
651
652/* Fetch the remote exec-file from the current program space. */
653
654static const char *
655get_remote_exec_file (void)
656{
657 char *remote_exec_file;
658
19ba03f4
SM
659 remote_exec_file
660 = (char *) program_space_data (current_program_space,
661 remote_pspace_data);
94585166
DB
662 if (remote_exec_file == NULL)
663 return "";
664
665 return remote_exec_file;
666}
667
668/* Set the remote exec file for PSPACE. */
669
670static void
671set_pspace_remote_exec_file (struct program_space *pspace,
672 char *remote_exec_file)
673{
19ba03f4 674 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
675
676 xfree (old_file);
677 set_program_space_data (pspace, remote_pspace_data,
678 xstrdup (remote_exec_file));
679}
680
681/* The "set/show remote exec-file" set command hook. */
682
683static void
684set_remote_exec_file (char *ignored, int from_tty,
685 struct cmd_list_element *c)
686{
687 gdb_assert (remote_exec_file_var != NULL);
688 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
689}
690
691/* The "set/show remote exec-file" show command hook. */
692
693static void
694show_remote_exec_file (struct ui_file *file, int from_tty,
695 struct cmd_list_element *cmd, const char *value)
696{
697 fprintf_filtered (file, "%s\n", remote_exec_file_var);
698}
699
74ca34ce
DJ
700static int
701compare_pnums (const void *lhs_, const void *rhs_)
702{
19ba03f4
SM
703 const struct packet_reg * const *lhs
704 = (const struct packet_reg * const *) lhs_;
705 const struct packet_reg * const *rhs
706 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
707
708 if ((*lhs)->pnum < (*rhs)->pnum)
709 return -1;
710 else if ((*lhs)->pnum == (*rhs)->pnum)
711 return 0;
712 else
713 return 1;
714}
715
c21236dc
PA
716static int
717map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 718{
74ca34ce 719 int regnum, num_remote_regs, offset;
74ca34ce 720 struct packet_reg **remote_regs;
ea9c271d 721
4a22f64d 722 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 723 {
c21236dc 724 struct packet_reg *r = &regs[regnum];
baef701f 725
4a22f64d 726 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
727 /* Do not try to fetch zero-sized (placeholder) registers. */
728 r->pnum = -1;
729 else
730 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
731
b323314b 732 r->regnum = regnum;
74ca34ce
DJ
733 }
734
735 /* Define the g/G packet format as the contents of each register
736 with a remote protocol number, in order of ascending protocol
737 number. */
738
224c3ddb 739 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 740 for (num_remote_regs = 0, regnum = 0;
4a22f64d 741 regnum < gdbarch_num_regs (gdbarch);
f57d151a 742 regnum++)
c21236dc
PA
743 if (regs[regnum].pnum != -1)
744 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 745
74ca34ce
DJ
746 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
747 compare_pnums);
748
749 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
750 {
751 remote_regs[regnum]->in_g_packet = 1;
752 remote_regs[regnum]->offset = offset;
4a22f64d 753 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
754 }
755
c21236dc
PA
756 return offset;
757}
758
759/* Given the architecture described by GDBARCH, return the remote
760 protocol register's number and the register's offset in the g/G
761 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
762 If the target does not have a mapping for REGNUM, return false,
763 otherwise, return true. */
764
765int
766remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
767 int *pnum, int *poffset)
768{
c21236dc
PA
769 struct packet_reg *regs;
770 struct cleanup *old_chain;
771
772 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
773
224c3ddb 774 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
c21236dc
PA
775 old_chain = make_cleanup (xfree, regs);
776
54887903 777 map_regcache_remote_table (gdbarch, regs);
c21236dc
PA
778
779 *pnum = regs[regnum].pnum;
780 *poffset = regs[regnum].offset;
781
782 do_cleanups (old_chain);
783
784 return *pnum != -1;
785}
786
787static void *
788init_remote_state (struct gdbarch *gdbarch)
789{
790 struct remote_state *rs = get_remote_state_raw ();
791 struct remote_arch_state *rsa;
792
793 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
794
795 /* Use the architecture to build a regnum<->pnum table, which will be
796 1:1 unless a feature set specifies otherwise. */
797 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
798 gdbarch_num_regs (gdbarch),
799 struct packet_reg);
800
74ca34ce
DJ
801 /* Record the maximum possible size of the g packet - it may turn out
802 to be smaller. */
c21236dc 803 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 804
0df8b418 805 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
806 remote stubs have a hardwired buffer size of 400 bytes
807 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
808 as the maximum packet-size to ensure that the packet and an extra
809 NUL character can always fit in the buffer. This stops GDB
810 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
811 already a full buffer (As of 1999-12-04 that was most stubs). */
812 rsa->remote_packet_size = 400 - 1;
d01949b6 813
ea9c271d
DJ
814 /* This one is filled in when a ``g'' packet is received. */
815 rsa->actual_register_packet_size = 0;
816
817 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
818 default, adjust the size accordingly. Remember that each byte is
819 encoded as two characters. 32 is the overhead for the packet
820 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 821 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 822 little. */
ea9c271d
DJ
823 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
824 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 825
ea9c271d
DJ
826 /* Make sure that the packet buffer is plenty big enough for
827 this architecture. */
828 if (rs->buf_size < rsa->remote_packet_size)
829 {
830 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 831 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 832 }
6d820c5c 833
ea9c271d
DJ
834 return rsa;
835}
836
837/* Return the current allowed size of a remote packet. This is
838 inferred from the current architecture, and should be used to
839 limit the length of outgoing packets. */
840static long
841get_remote_packet_size (void)
842{
be2a5f71 843 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
844 struct remote_arch_state *rsa = get_remote_arch_state ();
845
be2a5f71
DJ
846 if (rs->explicit_packet_size)
847 return rs->explicit_packet_size;
848
ea9c271d 849 return rsa->remote_packet_size;
d01949b6
AC
850}
851
ad10f812 852static struct packet_reg *
ea9c271d 853packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 854{
f5656ead 855 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
856 return NULL;
857 else
ad10f812 858 {
ea9c271d 859 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 860
b323314b
AC
861 gdb_assert (r->regnum == regnum);
862 return r;
ad10f812 863 }
ad10f812
AC
864}
865
866static struct packet_reg *
ea9c271d 867packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 868{
b323314b 869 int i;
a744cf53 870
f5656ead 871 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 872 {
ea9c271d 873 struct packet_reg *r = &rsa->regs[i];
a744cf53 874
b323314b
AC
875 if (r->pnum == pnum)
876 return r;
ad10f812
AC
877 }
878 return NULL;
d01949b6
AC
879}
880
c906108c
SS
881static struct target_ops remote_ops;
882
883static struct target_ops extended_remote_ops;
884
6426a772
JM
885/* FIXME: cagney/1999-09-23: Even though getpkt was called with
886 ``forever'' still use the normal timeout mechanism. This is
887 currently used by the ASYNC code to guarentee that target reads
888 during the initial connect always time-out. Once getpkt has been
889 modified to return a timeout indication and, in turn
890 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 891 this can go away. */
6426a772
JM
892static int wait_forever_enabled_p = 1;
893
9a7071a8
JB
894/* Allow the user to specify what sequence to send to the remote
895 when he requests a program interruption: Although ^C is usually
896 what remote systems expect (this is the default, here), it is
897 sometimes preferable to send a break. On other systems such
898 as the Linux kernel, a break followed by g, which is Magic SysRq g
899 is required in order to interrupt the execution. */
900const char interrupt_sequence_control_c[] = "Ctrl-C";
901const char interrupt_sequence_break[] = "BREAK";
902const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 903static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
904 {
905 interrupt_sequence_control_c,
906 interrupt_sequence_break,
907 interrupt_sequence_break_g,
908 NULL
909 };
910static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
911
912static void
913show_interrupt_sequence (struct ui_file *file, int from_tty,
914 struct cmd_list_element *c,
915 const char *value)
916{
917 if (interrupt_sequence_mode == interrupt_sequence_control_c)
918 fprintf_filtered (file,
919 _("Send the ASCII ETX character (Ctrl-c) "
920 "to the remote target to interrupt the "
921 "execution of the program.\n"));
922 else if (interrupt_sequence_mode == interrupt_sequence_break)
923 fprintf_filtered (file,
924 _("send a break signal to the remote target "
925 "to interrupt the execution of the program.\n"));
926 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
927 fprintf_filtered (file,
928 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
929 "the remote target to interrupt the execution "
930 "of Linux kernel.\n"));
931 else
932 internal_error (__FILE__, __LINE__,
933 _("Invalid value for interrupt_sequence_mode: %s."),
934 interrupt_sequence_mode);
935}
6426a772 936
9a7071a8
JB
937/* This boolean variable specifies whether interrupt_sequence is sent
938 to the remote target when gdb connects to it.
939 This is mostly needed when you debug the Linux kernel: The Linux kernel
940 expects BREAK g which is Magic SysRq g for connecting gdb. */
941static int interrupt_on_connect = 0;
c906108c 942
9a7071a8
JB
943/* This variable is used to implement the "set/show remotebreak" commands.
944 Since these commands are now deprecated in favor of "set/show remote
945 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
946static int remote_break;
947
9a7071a8
JB
948static void
949set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
950{
951 if (remote_break)
952 interrupt_sequence_mode = interrupt_sequence_break;
953 else
954 interrupt_sequence_mode = interrupt_sequence_control_c;
955}
956
957static void
958show_remotebreak (struct ui_file *file, int from_tty,
959 struct cmd_list_element *c,
960 const char *value)
961{
962}
963
c906108c
SS
964/* This variable sets the number of bits in an address that are to be
965 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 966 leading zeros, the entire address would be sent. This variable
c906108c
SS
967 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
968 initial implementation of remote.c restricted the address sent in
969 memory packets to ``host::sizeof long'' bytes - (typically 32
970 bits). Consequently, for 64 bit targets, the upper 32 bits of an
971 address was never sent. Since fixing this bug may cause a break in
972 some remote targets this variable is principly provided to
23860348 973 facilitate backward compatibility. */
c906108c 974
883b9c6c 975static unsigned int remote_address_size;
c906108c 976
75c99385
PA
977/* Temporary to track who currently owns the terminal. See
978 remote_terminal_* for more details. */
6426a772
JM
979
980static int remote_async_terminal_ours_p;
981
11cf8741 982\f
11cf8741 983/* User configurable variables for the number of characters in a
ea9c271d
DJ
984 memory read/write packet. MIN (rsa->remote_packet_size,
985 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 986 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
987 (speed up transfers). The variables ``preferred_*'' (the user
988 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 989 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
990
991struct memory_packet_config
992{
993 char *name;
994 long size;
995 int fixed_p;
996};
997
a5c0808e
PA
998/* The default max memory-write-packet-size. The 16k is historical.
999 (It came from older GDB's using alloca for buffers and the
1000 knowledge (folklore?) that some hosts don't cope very well with
1001 large alloca calls.) */
1002#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1003
1004/* The minimum remote packet size for memory transfers. Ensures we
1005 can write at least one byte. */
1006#define MIN_MEMORY_PACKET_SIZE 20
1007
11cf8741
JM
1008/* Compute the current size of a read/write packet. Since this makes
1009 use of ``actual_register_packet_size'' the computation is dynamic. */
1010
1011static long
1012get_memory_packet_size (struct memory_packet_config *config)
1013{
d01949b6 1014 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
1015 struct remote_arch_state *rsa = get_remote_arch_state ();
1016
11cf8741
JM
1017 long what_they_get;
1018 if (config->fixed_p)
1019 {
1020 if (config->size <= 0)
a5c0808e 1021 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1022 else
1023 what_they_get = config->size;
1024 }
1025 else
1026 {
ea9c271d 1027 what_they_get = get_remote_packet_size ();
23860348 1028 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1029 if (config->size > 0
1030 && what_they_get > config->size)
1031 what_they_get = config->size;
be2a5f71
DJ
1032
1033 /* Limit it to the size of the targets ``g'' response unless we have
1034 permission from the stub to use a larger packet size. */
1035 if (rs->explicit_packet_size == 0
1036 && rsa->actual_register_packet_size > 0
1037 && what_they_get > rsa->actual_register_packet_size)
1038 what_they_get = rsa->actual_register_packet_size;
11cf8741 1039 }
a5c0808e
PA
1040 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1041 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1042
1043 /* Make sure there is room in the global buffer for this packet
1044 (including its trailing NUL byte). */
1045 if (rs->buf_size < what_they_get + 1)
1046 {
1047 rs->buf_size = 2 * what_they_get;
224c3ddb 1048 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1049 }
1050
11cf8741
JM
1051 return what_they_get;
1052}
1053
0df8b418 1054/* Update the size of a read/write packet. If they user wants
23860348 1055 something really big then do a sanity check. */
11cf8741
JM
1056
1057static void
1058set_memory_packet_size (char *args, struct memory_packet_config *config)
1059{
1060 int fixed_p = config->fixed_p;
1061 long size = config->size;
a744cf53 1062
11cf8741 1063 if (args == NULL)
8a3fe4f8 1064 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1065 else if (strcmp (args, "hard") == 0
1066 || strcmp (args, "fixed") == 0)
1067 fixed_p = 1;
1068 else if (strcmp (args, "soft") == 0
1069 || strcmp (args, "limit") == 0)
1070 fixed_p = 0;
1071 else
1072 {
1073 char *end;
a744cf53 1074
11cf8741
JM
1075 size = strtoul (args, &end, 0);
1076 if (args == end)
8a3fe4f8 1077 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1078
1079 /* Instead of explicitly capping the size of a packet to or
1080 disallowing it, the user is allowed to set the size to
1081 something arbitrarily large. */
11cf8741 1082 }
a5c0808e
PA
1083
1084 /* So that the query shows the correct value. */
1085 if (size <= 0)
1086 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1087
23860348 1088 /* Extra checks? */
11cf8741
JM
1089 if (fixed_p && !config->fixed_p)
1090 {
e2e0b3e5
AC
1091 if (! query (_("The target may not be able to correctly handle a %s\n"
1092 "of %ld bytes. Change the packet size? "),
11cf8741 1093 config->name, size))
8a3fe4f8 1094 error (_("Packet size not changed."));
11cf8741 1095 }
23860348 1096 /* Update the config. */
11cf8741
JM
1097 config->fixed_p = fixed_p;
1098 config->size = size;
1099}
1100
1101static void
1102show_memory_packet_size (struct memory_packet_config *config)
1103{
a3f17187 1104 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1105 if (config->fixed_p)
a3f17187 1106 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1107 get_memory_packet_size (config));
1108 else
a3f17187 1109 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1110 get_memory_packet_size (config));
1111}
1112
1113static struct memory_packet_config memory_write_packet_config =
1114{
1115 "memory-write-packet-size",
1116};
1117
1118static void
1119set_memory_write_packet_size (char *args, int from_tty)
1120{
1121 set_memory_packet_size (args, &memory_write_packet_config);
1122}
1123
1124static void
1125show_memory_write_packet_size (char *args, int from_tty)
1126{
1127 show_memory_packet_size (&memory_write_packet_config);
1128}
1129
1130static long
1131get_memory_write_packet_size (void)
1132{
1133 return get_memory_packet_size (&memory_write_packet_config);
1134}
1135
1136static struct memory_packet_config memory_read_packet_config =
1137{
1138 "memory-read-packet-size",
1139};
1140
1141static void
1142set_memory_read_packet_size (char *args, int from_tty)
1143{
1144 set_memory_packet_size (args, &memory_read_packet_config);
1145}
1146
1147static void
1148show_memory_read_packet_size (char *args, int from_tty)
1149{
1150 show_memory_packet_size (&memory_read_packet_config);
1151}
1152
1153static long
1154get_memory_read_packet_size (void)
1155{
1156 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1157
11cf8741
JM
1158 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1159 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1160 increased beyond this. */
1161 if (size > get_remote_packet_size ())
1162 size = get_remote_packet_size ();
11cf8741
JM
1163 return size;
1164}
1165
11cf8741 1166\f
5a2468f5 1167/* Generic configuration support for packets the stub optionally
0df8b418 1168 supports. Allows the user to specify the use of the packet as well
23860348 1169 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1170
1171enum packet_support
1172 {
1173 PACKET_SUPPORT_UNKNOWN = 0,
1174 PACKET_ENABLE,
1175 PACKET_DISABLE
1176 };
1177
5a2468f5
JM
1178struct packet_config
1179 {
bb572ddd
DJ
1180 const char *name;
1181 const char *title;
4082afcc
PA
1182
1183 /* If auto, GDB auto-detects support for this packet or feature,
1184 either through qSupported, or by trying the packet and looking
1185 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1186 packet. If false, the packet is disabled. Configs that don't
1187 have an associated command always have this set to auto. */
7f19b9a2 1188 enum auto_boolean detect;
4082afcc
PA
1189
1190 /* Does the target support this packet? */
5a2468f5
JM
1191 enum packet_support support;
1192 };
1193
d471ea57 1194/* Analyze a packet's return value and update the packet config
23860348 1195 accordingly. */
d471ea57
AC
1196
1197enum packet_result
1198{
1199 PACKET_ERROR,
1200 PACKET_OK,
1201 PACKET_UNKNOWN
1202};
1203
4082afcc
PA
1204static enum packet_support packet_config_support (struct packet_config *config);
1205static enum packet_support packet_support (int packet);
5a2468f5
JM
1206
1207static void
fba45db2 1208show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1209{
1210 char *support = "internal-error";
a744cf53 1211
4082afcc 1212 switch (packet_config_support (config))
5a2468f5
JM
1213 {
1214 case PACKET_ENABLE:
1215 support = "enabled";
1216 break;
1217 case PACKET_DISABLE:
1218 support = "disabled";
1219 break;
1220 case PACKET_SUPPORT_UNKNOWN:
1221 support = "unknown";
1222 break;
1223 }
1224 switch (config->detect)
1225 {
7f19b9a2 1226 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1227 printf_filtered (_("Support for the `%s' packet "
1228 "is auto-detected, currently %s.\n"),
37a105a1 1229 config->name, support);
5a2468f5 1230 break;
7f19b9a2
AC
1231 case AUTO_BOOLEAN_TRUE:
1232 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1233 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1234 config->name, support);
8e248173 1235 break;
5a2468f5
JM
1236 }
1237}
1238
1239static void
bb572ddd
DJ
1240add_packet_config_cmd (struct packet_config *config, const char *name,
1241 const char *title, int legacy)
d471ea57 1242{
5a2468f5
JM
1243 char *set_doc;
1244 char *show_doc;
d471ea57 1245 char *cmd_name;
3ed07be4 1246
5a2468f5
JM
1247 config->name = name;
1248 config->title = title;
b435e160
AC
1249 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1250 name, title);
3e43a32a
MS
1251 show_doc = xstrprintf ("Show current use of remote "
1252 "protocol `%s' (%s) packet",
b435e160 1253 name, title);
d471ea57 1254 /* set/show TITLE-packet {auto,on,off} */
b435e160 1255 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1256 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1257 &config->detect, set_doc,
1258 show_doc, NULL, /* help_doc */
4082afcc 1259 NULL,
bb572ddd
DJ
1260 show_remote_protocol_packet_cmd,
1261 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1262 /* The command code copies the documentation strings. */
1263 xfree (set_doc);
1264 xfree (show_doc);
23860348 1265 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1266 if (legacy)
1267 {
1268 char *legacy_name;
a744cf53 1269
b435e160 1270 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1271 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1272 &remote_set_cmdlist);
d471ea57 1273 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1274 &remote_show_cmdlist);
d471ea57 1275 }
5a2468f5
JM
1276}
1277
d471ea57 1278static enum packet_result
a76d924d 1279packet_check_result (const char *buf)
5a2468f5 1280{
d471ea57 1281 if (buf[0] != '\0')
5a2468f5 1282 {
d471ea57 1283 /* The stub recognized the packet request. Check that the
23860348 1284 operation succeeded. */
a76d924d
DJ
1285 if (buf[0] == 'E'
1286 && isxdigit (buf[1]) && isxdigit (buf[2])
1287 && buf[3] == '\0')
1288 /* "Enn" - definitly an error. */
1289 return PACKET_ERROR;
1290
1291 /* Always treat "E." as an error. This will be used for
1292 more verbose error messages, such as E.memtypes. */
1293 if (buf[0] == 'E' && buf[1] == '.')
1294 return PACKET_ERROR;
1295
1296 /* The packet may or may not be OK. Just assume it is. */
1297 return PACKET_OK;
1298 }
1299 else
1300 /* The stub does not support the packet. */
1301 return PACKET_UNKNOWN;
1302}
1303
1304static enum packet_result
1305packet_ok (const char *buf, struct packet_config *config)
1306{
1307 enum packet_result result;
1308
4082afcc
PA
1309 if (config->detect != AUTO_BOOLEAN_TRUE
1310 && config->support == PACKET_DISABLE)
1311 internal_error (__FILE__, __LINE__,
1312 _("packet_ok: attempt to use a disabled packet"));
1313
a76d924d
DJ
1314 result = packet_check_result (buf);
1315 switch (result)
1316 {
1317 case PACKET_OK:
1318 case PACKET_ERROR:
1319 /* The stub recognized the packet request. */
4082afcc 1320 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1321 {
d471ea57
AC
1322 if (remote_debug)
1323 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1324 "Packet %s (%s) is supported\n",
1325 config->name, config->title);
d471ea57 1326 config->support = PACKET_ENABLE;
d471ea57 1327 }
a76d924d
DJ
1328 break;
1329 case PACKET_UNKNOWN:
23860348 1330 /* The stub does not support the packet. */
4082afcc
PA
1331 if (config->detect == AUTO_BOOLEAN_AUTO
1332 && config->support == PACKET_ENABLE)
d471ea57 1333 {
4082afcc
PA
1334 /* If the stub previously indicated that the packet was
1335 supported then there is a protocol error. */
1336 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1337 config->name, config->title);
1338 }
1339 else if (config->detect == AUTO_BOOLEAN_TRUE)
1340 {
1341 /* The user set it wrong. */
1342 error (_("Enabled packet %s (%s) not recognized by stub"),
1343 config->name, config->title);
d471ea57 1344 }
4082afcc
PA
1345
1346 if (remote_debug)
1347 fprintf_unfiltered (gdb_stdlog,
1348 "Packet %s (%s) is NOT supported\n",
1349 config->name, config->title);
1350 config->support = PACKET_DISABLE;
a76d924d 1351 break;
5a2468f5 1352 }
a76d924d
DJ
1353
1354 return result;
5a2468f5
JM
1355}
1356
444abaca
DJ
1357enum {
1358 PACKET_vCont = 0,
1359 PACKET_X,
1360 PACKET_qSymbol,
1361 PACKET_P,
1362 PACKET_p,
1363 PACKET_Z0,
1364 PACKET_Z1,
1365 PACKET_Z2,
1366 PACKET_Z3,
1367 PACKET_Z4,
15a201c8 1368 PACKET_vFile_setfs,
a6b151f1
DJ
1369 PACKET_vFile_open,
1370 PACKET_vFile_pread,
1371 PACKET_vFile_pwrite,
1372 PACKET_vFile_close,
1373 PACKET_vFile_unlink,
b9e7b9c3 1374 PACKET_vFile_readlink,
0a93529c 1375 PACKET_vFile_fstat,
0876f84a 1376 PACKET_qXfer_auxv,
23181151 1377 PACKET_qXfer_features,
c78fa86a 1378 PACKET_qXfer_exec_file,
cfa9d6d9 1379 PACKET_qXfer_libraries,
2268b414 1380 PACKET_qXfer_libraries_svr4,
fd79ecee 1381 PACKET_qXfer_memory_map,
0e7f50da
UW
1382 PACKET_qXfer_spu_read,
1383 PACKET_qXfer_spu_write,
07e059b5 1384 PACKET_qXfer_osdata,
dc146f7c 1385 PACKET_qXfer_threads,
0fb4aa4b 1386 PACKET_qXfer_statictrace_read,
b3b9301e 1387 PACKET_qXfer_traceframe_info,
169081d0 1388 PACKET_qXfer_uib,
711e434b 1389 PACKET_qGetTIBAddr,
444abaca 1390 PACKET_qGetTLSAddr,
be2a5f71 1391 PACKET_qSupported,
bd3eecc3 1392 PACKET_qTStatus,
89be2091 1393 PACKET_QPassSignals,
82075af2 1394 PACKET_QCatchSyscalls,
9b224c5e 1395 PACKET_QProgramSignals,
936d2992 1396 PACKET_qCRC,
08388c79 1397 PACKET_qSearch_memory,
2d717e4f
DJ
1398 PACKET_vAttach,
1399 PACKET_vRun,
a6f3e723 1400 PACKET_QStartNoAckMode,
82f73884 1401 PACKET_vKill,
4aa995e1
PA
1402 PACKET_qXfer_siginfo_read,
1403 PACKET_qXfer_siginfo_write,
0b16c5cf 1404 PACKET_qAttached,
4082afcc
PA
1405
1406 /* Support for conditional tracepoints. */
782b2b07 1407 PACKET_ConditionalTracepoints,
4082afcc
PA
1408
1409 /* Support for target-side breakpoint conditions. */
3788aec7 1410 PACKET_ConditionalBreakpoints,
4082afcc
PA
1411
1412 /* Support for target-side breakpoint commands. */
d3ce09f5 1413 PACKET_BreakpointCommands,
4082afcc
PA
1414
1415 /* Support for fast tracepoints. */
7a697b8d 1416 PACKET_FastTracepoints,
4082afcc
PA
1417
1418 /* Support for static tracepoints. */
0fb4aa4b 1419 PACKET_StaticTracepoints,
4082afcc
PA
1420
1421 /* Support for installing tracepoints while a trace experiment is
1422 running. */
1e4d1764 1423 PACKET_InstallInTrace,
4082afcc 1424
40ab02ce
MS
1425 PACKET_bc,
1426 PACKET_bs,
409873ef 1427 PACKET_TracepointSource,
d914c394 1428 PACKET_QAllow,
78d85199 1429 PACKET_qXfer_fdpic,
03583c20 1430 PACKET_QDisableRandomization,
d1feda86 1431 PACKET_QAgent,
f6f899bf 1432 PACKET_QTBuffer_size,
9accd112
MM
1433 PACKET_Qbtrace_off,
1434 PACKET_Qbtrace_bts,
b20a6524 1435 PACKET_Qbtrace_pt,
9accd112 1436 PACKET_qXfer_btrace,
4082afcc
PA
1437
1438 /* Support for the QNonStop packet. */
1439 PACKET_QNonStop,
1440
65706a29
PA
1441 /* Support for the QThreadEvents packet. */
1442 PACKET_QThreadEvents,
1443
4082afcc
PA
1444 /* Support for multi-process extensions. */
1445 PACKET_multiprocess_feature,
1446
1447 /* Support for enabling and disabling tracepoints while a trace
1448 experiment is running. */
1449 PACKET_EnableDisableTracepoints_feature,
1450
1451 /* Support for collecting strings using the tracenz bytecode. */
1452 PACKET_tracenz_feature,
1453
1454 /* Support for continuing to run a trace experiment while GDB is
1455 disconnected. */
1456 PACKET_DisconnectedTracing_feature,
1457
1458 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1459 PACKET_augmented_libraries_svr4_read_feature,
1460
f4abbc16
MM
1461 /* Support for the qXfer:btrace-conf:read packet. */
1462 PACKET_qXfer_btrace_conf,
1463
d33501a5
MM
1464 /* Support for the Qbtrace-conf:bts:size packet. */
1465 PACKET_Qbtrace_conf_bts_size,
1466
f7e6eed5
PA
1467 /* Support for swbreak+ feature. */
1468 PACKET_swbreak_feature,
1469
1470 /* Support for hwbreak+ feature. */
1471 PACKET_hwbreak_feature,
1472
89245bc0
DB
1473 /* Support for fork events. */
1474 PACKET_fork_event_feature,
1475
1476 /* Support for vfork events. */
1477 PACKET_vfork_event_feature,
1478
b20a6524
MM
1479 /* Support for the Qbtrace-conf:pt:size packet. */
1480 PACKET_Qbtrace_conf_pt_size,
1481
94585166
DB
1482 /* Support for exec events. */
1483 PACKET_exec_event_feature,
1484
750ce8d1
YQ
1485 /* Support for query supported vCont actions. */
1486 PACKET_vContSupported,
1487
de979965
PA
1488 /* Support remote CTRL-C. */
1489 PACKET_vCtrlC,
1490
f2faf941
PA
1491 /* Support TARGET_WAITKIND_NO_RESUMED. */
1492 PACKET_no_resumed,
1493
444abaca
DJ
1494 PACKET_MAX
1495};
506fb367 1496
444abaca 1497static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1498
fef3cb9f
JK
1499/* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
1500 unknown 'v' packet with string "OK". "OK" gets interpreted by GDB
1501 as a reply to known packet. For packet "vFile:setfs:" it is an
1502 invalid reply and GDB would return error in
1503 remote_hostio_set_filesystem, making remote files access impossible.
1504 If this variable is non-zero it means the remote gdbserver is buggy
1505 and any not yet detected packets are assumed as unsupported. */
1506static int unknown_v_replies_ok;
1507
f7e6eed5
PA
1508/* Returns the packet's corresponding "set remote foo-packet" command
1509 state. See struct packet_config for more details. */
1510
1511static enum auto_boolean
1512packet_set_cmd_state (int packet)
1513{
1514 return remote_protocol_packets[packet].detect;
1515}
1516
4082afcc
PA
1517/* Returns whether a given packet or feature is supported. This takes
1518 into account the state of the corresponding "set remote foo-packet"
1519 command, which may be used to bypass auto-detection. */
dc8acb97 1520
4082afcc
PA
1521static enum packet_support
1522packet_config_support (struct packet_config *config)
1523{
1524 switch (config->detect)
444abaca 1525 {
4082afcc
PA
1526 case AUTO_BOOLEAN_TRUE:
1527 return PACKET_ENABLE;
1528 case AUTO_BOOLEAN_FALSE:
1529 return PACKET_DISABLE;
1530 case AUTO_BOOLEAN_AUTO:
fef3cb9f
JK
1531 if (unknown_v_replies_ok && config->name != NULL
1532 && config->name[0] == 'v')
1533 return PACKET_DISABLE;
4082afcc
PA
1534 return config->support;
1535 default:
1536 gdb_assert_not_reached (_("bad switch"));
444abaca 1537 }
4082afcc
PA
1538}
1539
1540/* Same as packet_config_support, but takes the packet's enum value as
1541 argument. */
1542
1543static enum packet_support
1544packet_support (int packet)
1545{
1546 struct packet_config *config = &remote_protocol_packets[packet];
1547
1548 return packet_config_support (config);
dc8acb97
MS
1549}
1550
5a2468f5 1551static void
444abaca
DJ
1552show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1553 struct cmd_list_element *c,
1554 const char *value)
5a2468f5 1555{
444abaca 1556 struct packet_config *packet;
5a2468f5 1557
444abaca
DJ
1558 for (packet = remote_protocol_packets;
1559 packet < &remote_protocol_packets[PACKET_MAX];
1560 packet++)
1561 {
1562 if (&packet->detect == c->var)
1563 {
1564 show_packet_config_cmd (packet);
1565 return;
1566 }
1567 }
9b20d036 1568 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1569 c->name);
5a2468f5
JM
1570}
1571
d471ea57
AC
1572/* Should we try one of the 'Z' requests? */
1573
1574enum Z_packet_type
1575{
1576 Z_PACKET_SOFTWARE_BP,
1577 Z_PACKET_HARDWARE_BP,
1578 Z_PACKET_WRITE_WP,
1579 Z_PACKET_READ_WP,
1580 Z_PACKET_ACCESS_WP,
1581 NR_Z_PACKET_TYPES
1582};
96baa820 1583
d471ea57 1584/* For compatibility with older distributions. Provide a ``set remote
23860348 1585 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1586
7f19b9a2 1587static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1588
1589static void
fba45db2
KB
1590set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1591 struct cmd_list_element *c)
96baa820 1592{
d471ea57 1593 int i;
a744cf53 1594
d471ea57 1595 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1596 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1597}
1598
1599static void
08546159
AC
1600show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1601 struct cmd_list_element *c,
1602 const char *value)
96baa820 1603{
d471ea57 1604 int i;
a744cf53 1605
d471ea57
AC
1606 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1607 {
444abaca 1608 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1609 }
96baa820
JM
1610}
1611
4082afcc
PA
1612/* Returns true if the multi-process extensions are in effect. */
1613
1614static int
1615remote_multi_process_p (struct remote_state *rs)
1616{
1617 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1618}
1619
de0d863e
DB
1620/* Returns true if fork events are supported. */
1621
1622static int
1623remote_fork_event_p (struct remote_state *rs)
1624{
1625 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1626}
1627
c269dbdb
DB
1628/* Returns true if vfork events are supported. */
1629
1630static int
1631remote_vfork_event_p (struct remote_state *rs)
1632{
1633 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1634}
1635
d46addbb
DB
1636/* Returns true if exec events are supported. */
1637
1638static int
1639remote_exec_event_p (struct remote_state *rs)
1640{
1641 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1642}
1643
cbb8991c
DB
1644/* Insert fork catchpoint target routine. If fork events are enabled
1645 then return success, nothing more to do. */
1646
1647static int
1648remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1649{
1650 struct remote_state *rs = get_remote_state ();
1651
1652 return !remote_fork_event_p (rs);
1653}
1654
1655/* Remove fork catchpoint target routine. Nothing to do, just
1656 return success. */
1657
1658static int
1659remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1660{
1661 return 0;
1662}
1663
1664/* Insert vfork catchpoint target routine. If vfork events are enabled
1665 then return success, nothing more to do. */
1666
1667static int
1668remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1669{
1670 struct remote_state *rs = get_remote_state ();
1671
1672 return !remote_vfork_event_p (rs);
1673}
1674
1675/* Remove vfork catchpoint target routine. Nothing to do, just
1676 return success. */
1677
1678static int
1679remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1680{
1681 return 0;
1682}
1683
d46addbb
DB
1684/* Insert exec catchpoint target routine. If exec events are
1685 enabled, just return success. */
1686
1687static int
1688remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1689{
1690 struct remote_state *rs = get_remote_state ();
1691
1692 return !remote_exec_event_p (rs);
1693}
1694
1695/* Remove exec catchpoint target routine. Nothing to do, just
1696 return success. */
1697
1698static int
1699remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1700{
1701 return 0;
1702}
1703
23860348 1704/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1705static struct async_signal_handler *async_sigint_remote_twice_token;
1706static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1707
74531fed
PA
1708\f
1709/* Asynchronous signal handle registered as event loop source for
1710 when we have pending events ready to be passed to the core. */
1711
1712static struct async_event_handler *remote_async_inferior_event_token;
1713
c906108c
SS
1714\f
1715
79d7f229
PA
1716static ptid_t magic_null_ptid;
1717static ptid_t not_sent_ptid;
1718static ptid_t any_thread_ptid;
1719
0b16c5cf
PA
1720/* Find out if the stub attached to PID (and hence GDB should offer to
1721 detach instead of killing it when bailing out). */
1722
1723static int
1724remote_query_attached (int pid)
1725{
1726 struct remote_state *rs = get_remote_state ();
bba74b36 1727 size_t size = get_remote_packet_size ();
0b16c5cf 1728
4082afcc 1729 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1730 return 0;
1731
1732 if (remote_multi_process_p (rs))
bba74b36 1733 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1734 else
bba74b36 1735 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1736
1737 putpkt (rs->buf);
1738 getpkt (&rs->buf, &rs->buf_size, 0);
1739
1740 switch (packet_ok (rs->buf,
1554e9be 1741 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1742 {
1743 case PACKET_OK:
1744 if (strcmp (rs->buf, "1") == 0)
1745 return 1;
1746 break;
1747 case PACKET_ERROR:
1748 warning (_("Remote failure reply: %s"), rs->buf);
1749 break;
1750 case PACKET_UNKNOWN:
1751 break;
1752 }
1753
1754 return 0;
1755}
1756
49c62f2e
PA
1757/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1758 has been invented by GDB, instead of reported by the target. Since
1759 we can be connected to a remote system before before knowing about
1760 any inferior, mark the target with execution when we find the first
1761 inferior. If ATTACHED is 1, then we had just attached to this
1762 inferior. If it is 0, then we just created this inferior. If it
1763 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1764 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1765 attempt to open this inferior's executable as the main executable
1766 if no main executable is open already. */
1941c569
PA
1767
1768static struct inferior *
1b6e6f5c
GB
1769remote_add_inferior (int fake_pid_p, int pid, int attached,
1770 int try_open_exec)
1941c569 1771{
1941c569
PA
1772 struct inferior *inf;
1773
0b16c5cf
PA
1774 /* Check whether this process we're learning about is to be
1775 considered attached, or if is to be considered to have been
1776 spawned by the stub. */
1777 if (attached == -1)
1778 attached = remote_query_attached (pid);
1779
f5656ead 1780 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1781 {
1782 /* If the target shares code across all inferiors, then every
1783 attach adds a new inferior. */
1784 inf = add_inferior (pid);
1785
1786 /* ... and every inferior is bound to the same program space.
1787 However, each inferior may still have its own address
1788 space. */
1789 inf->aspace = maybe_new_address_space ();
1790 inf->pspace = current_program_space;
1791 }
1792 else
1793 {
1794 /* In the traditional debugging scenario, there's a 1-1 match
1795 between program/address spaces. We simply bind the inferior
1796 to the program space's address space. */
1797 inf = current_inferior ();
1798 inferior_appeared (inf, pid);
1799 }
1941c569 1800
0b16c5cf 1801 inf->attach_flag = attached;
49c62f2e 1802 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1803
1b6e6f5c
GB
1804 /* If no main executable is currently open then attempt to
1805 open the file that was executed to create this inferior. */
835205d0 1806 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1807 exec_file_locate_attach (pid, 1);
1808
1941c569
PA
1809 return inf;
1810}
1811
1812/* Add thread PTID to GDB's thread list. Tag it as executing/running
1813 according to RUNNING. */
1814
c906108c 1815static void
0d5b594f 1816remote_add_thread (ptid_t ptid, int running, int executing)
c906108c 1817{
b7ea362b
PA
1818 struct remote_state *rs = get_remote_state ();
1819
1820 /* GDB historically didn't pull threads in the initial connection
1821 setup. If the remote target doesn't even have a concept of
1822 threads (e.g., a bare-metal target), even if internally we
1823 consider that a single-threaded target, mentioning a new thread
1824 might be confusing to the user. Be silent then, preserving the
1825 age old behavior. */
1826 if (rs->starting_up)
1827 add_thread_silent (ptid);
1828 else
1829 add_thread (ptid);
1941c569 1830
0d5b594f 1831 set_executing (ptid, executing);
1941c569
PA
1832 set_running (ptid, running);
1833}
1834
1835/* Come here when we learn about a thread id from the remote target.
1836 It may be the first time we hear about such thread, so take the
1837 opportunity to add it to GDB's thread list. In case this is the
1838 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
1839 GDB's inferior list as well. EXECUTING indicates whether the
1840 thread is (internally) executing or stopped. */
1941c569
PA
1841
1842static void
0d5b594f 1843remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 1844{
0d5b594f
PA
1845 /* In non-stop mode, we assume new found threads are (externally)
1846 running until proven otherwise with a stop reply. In all-stop,
1847 we can only get here if all threads are stopped. */
1848 int running = target_is_non_stop_p () ? 1 : 0;
1849
c906108c
SS
1850 /* If this is a new thread, add it to GDB's thread list.
1851 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1852
1853 if (in_thread_list (currthread) && is_exited (currthread))
1854 {
1855 /* We're seeing an event on a thread id we knew had exited.
1856 This has to be a new thread reusing the old id. Add it. */
0d5b594f 1857 remote_add_thread (currthread, running, executing);
82f73884
PA
1858 return;
1859 }
1860
79d7f229 1861 if (!in_thread_list (currthread))
c0a2216e 1862 {
1941c569 1863 struct inferior *inf = NULL;
bad34192 1864 int pid = ptid_get_pid (currthread);
1941c569 1865
bad34192
PA
1866 if (ptid_is_pid (inferior_ptid)
1867 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1868 {
1869 /* inferior_ptid has no thread member yet. This can happen
1870 with the vAttach -> remote_wait,"TAAthread:" path if the
1871 stub doesn't support qC. This is the first stop reported
1872 after an attach, so this is the main thread. Update the
1873 ptid in the thread list. */
bad34192
PA
1874 if (in_thread_list (pid_to_ptid (pid)))
1875 thread_change_ptid (inferior_ptid, currthread);
1876 else
1877 {
0d5b594f 1878 remote_add_thread (currthread, running, executing);
bad34192
PA
1879 inferior_ptid = currthread;
1880 }
dc146f7c 1881 return;
c0a2216e 1882 }
82f73884
PA
1883
1884 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1885 {
1886 /* inferior_ptid is not set yet. This can happen with the
1887 vRun -> remote_wait,"TAAthread:" path if the stub
1888 doesn't support qC. This is the first stop reported
1889 after an attach, so this is the main thread. Update the
1890 ptid in the thread list. */
dc146f7c 1891 thread_change_ptid (inferior_ptid, currthread);
82f73884 1892 return;
c0a2216e 1893 }
82f73884 1894
29c87f7f
PA
1895 /* When connecting to a target remote, or to a target
1896 extended-remote which already was debugging an inferior, we
1897 may not know about it yet. Add it before adding its child
1898 thread, so notifications are emitted in a sensible order. */
1899 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1900 {
1901 struct remote_state *rs = get_remote_state ();
1902 int fake_pid_p = !remote_multi_process_p (rs);
1903
1904 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1905 ptid_get_pid (currthread), -1, 1);
49c62f2e 1906 }
29c87f7f 1907
82f73884 1908 /* This is really a new thread. Add it. */
0d5b594f 1909 remote_add_thread (currthread, running, executing);
1941c569
PA
1910
1911 /* If we found a new inferior, let the common code do whatever
1912 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1913 breakpoints), unless we're just setting up an all-stop
1914 connection. */
1941c569 1915 if (inf != NULL)
b7ea362b
PA
1916 {
1917 struct remote_state *rs = get_remote_state ();
1918
6efcd9a8 1919 if (!rs->starting_up)
0d5b594f 1920 notice_new_inferior (currthread, executing, 0);
b7ea362b 1921 }
c0a2216e 1922 }
c906108c
SS
1923}
1924
dc146f7c
VP
1925/* Return the private thread data, creating it if necessary. */
1926
70221824 1927static struct private_thread_info *
dc146f7c
VP
1928demand_private_info (ptid_t ptid)
1929{
1930 struct thread_info *info = find_thread_ptid (ptid);
1931
1932 gdb_assert (info);
1933
fe978cb0 1934 if (!info->priv)
dc146f7c 1935 {
8d749320 1936 info->priv = XNEW (struct private_thread_info);
dc146f7c 1937 info->private_dtor = free_private_thread_info;
fe978cb0 1938 info->priv->core = -1;
8020350c
DB
1939 info->priv->extra = NULL;
1940 info->priv->name = NULL;
dc146f7c
VP
1941 }
1942
fe978cb0 1943 return info->priv;
dc146f7c
VP
1944}
1945
74531fed
PA
1946/* Call this function as a result of
1947 1) A halt indication (T packet) containing a thread id
1948 2) A direct query of currthread
0df8b418 1949 3) Successful execution of set thread */
74531fed
PA
1950
1951static void
47f8a51d 1952record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1953{
47f8a51d 1954 rs->general_thread = currthread;
74531fed
PA
1955}
1956
89be2091
DJ
1957/* If 'QPassSignals' is supported, tell the remote stub what signals
1958 it can simply pass through to the inferior without reporting. */
1959
1960static void
94bedb42
TT
1961remote_pass_signals (struct target_ops *self,
1962 int numsigs, unsigned char *pass_signals)
89be2091 1963{
4082afcc 1964 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1965 {
1966 char *pass_packet, *p;
89be2091 1967 int count = 0, i;
747dc59d 1968 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1969
1970 gdb_assert (numsigs < 256);
1971 for (i = 0; i < numsigs; i++)
1972 {
2455069d 1973 if (pass_signals[i])
89be2091
DJ
1974 count++;
1975 }
224c3ddb 1976 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
1977 strcpy (pass_packet, "QPassSignals:");
1978 p = pass_packet + strlen (pass_packet);
1979 for (i = 0; i < numsigs; i++)
1980 {
2455069d 1981 if (pass_signals[i])
89be2091
DJ
1982 {
1983 if (i >= 16)
1984 *p++ = tohex (i >> 4);
1985 *p++ = tohex (i & 15);
1986 if (count)
1987 *p++ = ';';
1988 else
1989 break;
1990 count--;
1991 }
1992 }
1993 *p = 0;
747dc59d 1994 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1995 {
89be2091
DJ
1996 putpkt (pass_packet);
1997 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1998 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1999 if (rs->last_pass_packet)
2000 xfree (rs->last_pass_packet);
2001 rs->last_pass_packet = pass_packet;
89be2091
DJ
2002 }
2003 else
2004 xfree (pass_packet);
2005 }
2006}
2007
82075af2
JS
2008/* If 'QCatchSyscalls' is supported, tell the remote stub
2009 to report syscalls to GDB. */
2010
2011static int
2012remote_set_syscall_catchpoint (struct target_ops *self,
2013 int pid, int needed, int any_count,
2014 int table_size, int *table)
2015{
2016 char *catch_packet;
2017 enum packet_result result;
2018 int n_sysno = 0;
2019
2020 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2021 {
2022 /* Not supported. */
2023 return 1;
2024 }
2025
2026 if (needed && !any_count)
2027 {
2028 int i;
2029
2030 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2031 for (i = 0; i < table_size; i++)
2032 {
2033 if (table[i] != 0)
2034 n_sysno++;
2035 }
2036 }
2037
2038 if (remote_debug)
2039 {
2040 fprintf_unfiltered (gdb_stdlog,
2041 "remote_set_syscall_catchpoint "
2042 "pid %d needed %d any_count %d n_sysno %d\n",
2043 pid, needed, any_count, n_sysno);
2044 }
2045
2046 if (needed)
2047 {
2048 /* Prepare a packet with the sysno list, assuming max 8+1
2049 characters for a sysno. If the resulting packet size is too
2050 big, fallback on the non-selective packet. */
2051 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2052
c0518081 2053 catch_packet = (char *) xmalloc (maxpktsz);
82075af2
JS
2054 strcpy (catch_packet, "QCatchSyscalls:1");
2055 if (!any_count)
2056 {
2057 int i;
2058 char *p;
2059
2060 p = catch_packet;
2061 p += strlen (p);
2062
2063 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2064 for (i = 0; i < table_size; i++)
2065 {
2066 if (table[i] != 0)
2067 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2068 }
2069 }
2070 if (strlen (catch_packet) > get_remote_packet_size ())
2071 {
2072 /* catch_packet too big. Fallback to less efficient
2073 non selective mode, with GDB doing the filtering. */
2074 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2075 }
2076 }
2077 else
2078 catch_packet = xstrdup ("QCatchSyscalls:0");
2079
2080 {
2081 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2082 struct remote_state *rs = get_remote_state ();
2083
2084 putpkt (catch_packet);
2085 getpkt (&rs->buf, &rs->buf_size, 0);
2086 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2087 do_cleanups (old_chain);
2088 if (result == PACKET_OK)
2089 return 0;
2090 else
2091 return -1;
2092 }
2093}
2094
9b224c5e
PA
2095/* If 'QProgramSignals' is supported, tell the remote stub what
2096 signals it should pass through to the inferior when detaching. */
2097
2098static void
daf5e9b6
TT
2099remote_program_signals (struct target_ops *self,
2100 int numsigs, unsigned char *signals)
9b224c5e 2101{
4082afcc 2102 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2103 {
2104 char *packet, *p;
2105 int count = 0, i;
5e4a05c4 2106 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2107
2108 gdb_assert (numsigs < 256);
2109 for (i = 0; i < numsigs; i++)
2110 {
2111 if (signals[i])
2112 count++;
2113 }
224c3ddb 2114 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2115 strcpy (packet, "QProgramSignals:");
2116 p = packet + strlen (packet);
2117 for (i = 0; i < numsigs; i++)
2118 {
2119 if (signal_pass_state (i))
2120 {
2121 if (i >= 16)
2122 *p++ = tohex (i >> 4);
2123 *p++ = tohex (i & 15);
2124 if (count)
2125 *p++ = ';';
2126 else
2127 break;
2128 count--;
2129 }
2130 }
2131 *p = 0;
5e4a05c4
TT
2132 if (!rs->last_program_signals_packet
2133 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2134 {
9b224c5e
PA
2135 putpkt (packet);
2136 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2137 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2138 xfree (rs->last_program_signals_packet);
2139 rs->last_program_signals_packet = packet;
9b224c5e
PA
2140 }
2141 else
2142 xfree (packet);
2143 }
2144}
2145
79d7f229
PA
2146/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2147 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2148 thread. If GEN is set, set the general thread, if not, then set
2149 the step/continue thread. */
c906108c 2150static void
79d7f229 2151set_thread (struct ptid ptid, int gen)
c906108c 2152{
d01949b6 2153 struct remote_state *rs = get_remote_state ();
47f8a51d 2154 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2155 char *buf = rs->buf;
79d7f229 2156 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2157
79d7f229 2158 if (ptid_equal (state, ptid))
c906108c
SS
2159 return;
2160
79d7f229
PA
2161 *buf++ = 'H';
2162 *buf++ = gen ? 'g' : 'c';
2163 if (ptid_equal (ptid, magic_null_ptid))
2164 xsnprintf (buf, endbuf - buf, "0");
2165 else if (ptid_equal (ptid, any_thread_ptid))
2166 xsnprintf (buf, endbuf - buf, "0");
2167 else if (ptid_equal (ptid, minus_one_ptid))
2168 xsnprintf (buf, endbuf - buf, "-1");
2169 else
82f73884 2170 write_ptid (buf, endbuf, ptid);
79d7f229 2171 putpkt (rs->buf);
6d820c5c 2172 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2173 if (gen)
47f8a51d 2174 rs->general_thread = ptid;
c906108c 2175 else
47f8a51d 2176 rs->continue_thread = ptid;
c906108c 2177}
79d7f229
PA
2178
2179static void
2180set_general_thread (struct ptid ptid)
2181{
2182 set_thread (ptid, 1);
2183}
2184
2185static void
2186set_continue_thread (struct ptid ptid)
2187{
2188 set_thread (ptid, 0);
2189}
2190
3c9c4b83
PA
2191/* Change the remote current process. Which thread within the process
2192 ends up selected isn't important, as long as it is the same process
2193 as what INFERIOR_PTID points to.
2194
2195 This comes from that fact that there is no explicit notion of
2196 "selected process" in the protocol. The selected process for
2197 general operations is the process the selected general thread
2198 belongs to. */
2199
2200static void
2201set_general_process (void)
2202{
2203 struct remote_state *rs = get_remote_state ();
2204
2205 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2206 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2207 return;
2208
2209 /* We only need to change the remote current thread if it's pointing
2210 at some other process. */
47f8a51d 2211 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2212 set_general_thread (inferior_ptid);
2213}
2214
c906108c 2215\f
7d1a114c
PA
2216/* Return nonzero if this is the main thread that we made up ourselves
2217 to model non-threaded targets as single-threaded. */
c906108c
SS
2218
2219static int
7d1a114c 2220remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2221{
c0a2216e
PA
2222 if (ptid_equal (ptid, magic_null_ptid))
2223 /* The main thread is always alive. */
2224 return 1;
2225
ba348170 2226 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2227 /* The main thread is always alive. This can happen after a
2228 vAttach, if the remote side doesn't support
2229 multi-threading. */
2230 return 1;
2231
7d1a114c
PA
2232 return 0;
2233}
2234
2235/* Return nonzero if the thread PTID is still alive on the remote
2236 system. */
2237
2238static int
2239remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2240{
2241 struct remote_state *rs = get_remote_state ();
2242 char *p, *endp;
2243
2244 /* Check if this is a thread that we made up ourselves to model
2245 non-threaded targets as single-threaded. */
2246 if (remote_thread_always_alive (ops, ptid))
2247 return 1;
2248
82f73884
PA
2249 p = rs->buf;
2250 endp = rs->buf + get_remote_packet_size ();
2251
2252 *p++ = 'T';
2253 write_ptid (p, endp, ptid);
2254
2e9f7625 2255 putpkt (rs->buf);
6d820c5c 2256 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2257 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2258}
2259
79efa585
SM
2260/* Return a pointer to a thread name if we know it and NULL otherwise.
2261 The thread_info object owns the memory for the name. */
2262
2263static const char *
2264remote_thread_name (struct target_ops *ops, struct thread_info *info)
2265{
2266 if (info->priv != NULL)
2267 return info->priv->name;
2268
2269 return NULL;
2270}
2271
c906108c
SS
2272/* About these extended threadlist and threadinfo packets. They are
2273 variable length packets but, the fields within them are often fixed
2274 length. They are redundent enough to send over UDP as is the
2275 remote protocol in general. There is a matching unit test module
2276 in libstub. */
2277
23860348 2278/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2279 libstub protocol encoding, and remote.c. It is not particularly
23860348 2280 changable. */
cce74817
JM
2281
2282/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2283 Plan to fix this. */
cce74817 2284
23860348 2285typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2286
9d1f7ab2 2287/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2288 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2289
2290struct gdb_ext_thread_info
c5aa993b 2291 {
23860348 2292 threadref threadid; /* External form of thread reference. */
2bc416ba 2293 int active; /* Has state interesting to GDB?
23860348 2294 regs, stack. */
2bc416ba 2295 char display[256]; /* Brief state display, name,
cedea757 2296 blocked/suspended. */
23860348 2297 char shortname[32]; /* To be used to name threads. */
2bc416ba 2298 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2299 whatever. */
c5aa993b 2300 };
cce74817
JM
2301
2302/* The volume of remote transfers can be limited by submitting
2303 a mask containing bits specifying the desired information.
2304 Use a union of these values as the 'selection' parameter to
0df8b418 2305 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2306
2307#define TAG_THREADID 1
2308#define TAG_EXISTS 2
2309#define TAG_DISPLAY 4
2310#define TAG_THREADNAME 8
c5aa993b 2311#define TAG_MOREDISPLAY 16
cce74817 2312
23860348 2313#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2314
a14ed312 2315static char *unpack_nibble (char *buf, int *val);
cce74817 2316
a14ed312 2317static char *unpack_byte (char *buf, int *value);
cce74817 2318
a14ed312 2319static char *pack_int (char *buf, int value);
cce74817 2320
a14ed312 2321static char *unpack_int (char *buf, int *value);
cce74817 2322
a14ed312 2323static char *unpack_string (char *src, char *dest, int length);
cce74817 2324
23860348 2325static char *pack_threadid (char *pkt, threadref *id);
cce74817 2326
23860348 2327static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2328
23860348 2329void int_to_threadref (threadref *id, int value);
cce74817 2330
23860348 2331static int threadref_to_int (threadref *ref);
cce74817 2332
23860348 2333static void copy_threadref (threadref *dest, threadref *src);
cce74817 2334
23860348 2335static int threadmatch (threadref *dest, threadref *src);
cce74817 2336
2bc416ba 2337static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2338 threadref *id);
cce74817 2339
a14ed312 2340static int remote_unpack_thread_info_response (char *pkt,
23860348 2341 threadref *expectedref,
a14ed312
KB
2342 struct gdb_ext_thread_info
2343 *info);
cce74817
JM
2344
2345
2bc416ba 2346static int remote_get_threadinfo (threadref *threadid,
23860348 2347 int fieldset, /*TAG mask */
a14ed312 2348 struct gdb_ext_thread_info *info);
cce74817 2349
a14ed312
KB
2350static char *pack_threadlist_request (char *pkt, int startflag,
2351 int threadcount,
23860348 2352 threadref *nextthread);
cce74817 2353
a14ed312
KB
2354static int parse_threadlist_response (char *pkt,
2355 int result_limit,
23860348 2356 threadref *original_echo,
2bc416ba 2357 threadref *resultlist,
23860348 2358 int *doneflag);
cce74817 2359
a14ed312 2360static int remote_get_threadlist (int startflag,
23860348 2361 threadref *nextthread,
a14ed312
KB
2362 int result_limit,
2363 int *done,
2bc416ba 2364 int *result_count,
23860348 2365 threadref *threadlist);
cce74817 2366
23860348 2367typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2368
a14ed312
KB
2369static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2370 void *context, int looplimit);
cce74817 2371
23860348 2372static int remote_newthread_step (threadref *ref, void *context);
cce74817 2373
82f73884
PA
2374
2375/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2376 buffer we're allowed to write to. Returns
2377 BUF+CHARACTERS_WRITTEN. */
2378
2379static char *
2380write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2381{
2382 int pid, tid;
2383 struct remote_state *rs = get_remote_state ();
2384
2385 if (remote_multi_process_p (rs))
2386 {
2387 pid = ptid_get_pid (ptid);
2388 if (pid < 0)
2389 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2390 else
2391 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2392 }
ba348170 2393 tid = ptid_get_lwp (ptid);
82f73884
PA
2394 if (tid < 0)
2395 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2396 else
2397 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2398
2399 return buf;
2400}
2401
2402/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2403 passed the last parsed char. Returns null_ptid on error. */
2404
2405static ptid_t
2406read_ptid (char *buf, char **obuf)
2407{
2408 char *p = buf;
2409 char *pp;
2410 ULONGEST pid = 0, tid = 0;
82f73884
PA
2411
2412 if (*p == 'p')
2413 {
2414 /* Multi-process ptid. */
2415 pp = unpack_varlen_hex (p + 1, &pid);
2416 if (*pp != '.')
b37520b6 2417 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2418
2419 p = pp;
2420 pp = unpack_varlen_hex (p + 1, &tid);
2421 if (obuf)
2422 *obuf = pp;
ba348170 2423 return ptid_build (pid, tid, 0);
82f73884
PA
2424 }
2425
2426 /* No multi-process. Just a tid. */
2427 pp = unpack_varlen_hex (p, &tid);
2428
c9f35b34
KB
2429 /* Return null_ptid when no thread id is found. */
2430 if (p == pp)
2431 {
2432 if (obuf)
2433 *obuf = pp;
2434 return null_ptid;
2435 }
2436
82f73884 2437 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2438 what's in inferior_ptid, unless it's null at this point. If so,
2439 then since there's no way to know the pid of the reported
2440 threads, use the magic number. */
2441 if (ptid_equal (inferior_ptid, null_ptid))
2442 pid = ptid_get_pid (magic_null_ptid);
2443 else
2444 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2445
2446 if (obuf)
2447 *obuf = pp;
ba348170 2448 return ptid_build (pid, tid, 0);
82f73884
PA
2449}
2450
c906108c 2451static int
fba45db2 2452stubhex (int ch)
c906108c
SS
2453{
2454 if (ch >= 'a' && ch <= 'f')
2455 return ch - 'a' + 10;
2456 if (ch >= '0' && ch <= '9')
2457 return ch - '0';
2458 if (ch >= 'A' && ch <= 'F')
2459 return ch - 'A' + 10;
2460 return -1;
2461}
2462
2463static int
fba45db2 2464stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2465{
2466 int nibble;
2467 int retval = 0;
2468
2469 while (fieldlength)
2470 {
2471 nibble = stubhex (*buff++);
2472 retval |= nibble;
2473 fieldlength--;
2474 if (fieldlength)
2475 retval = retval << 4;
2476 }
2477 return retval;
2478}
2479
c906108c 2480static char *
fba45db2 2481unpack_nibble (char *buf, int *val)
c906108c 2482{
b7589f7d 2483 *val = fromhex (*buf++);
c906108c
SS
2484 return buf;
2485}
2486
c906108c 2487static char *
fba45db2 2488unpack_byte (char *buf, int *value)
c906108c
SS
2489{
2490 *value = stub_unpack_int (buf, 2);
2491 return buf + 2;
2492}
2493
2494static char *
fba45db2 2495pack_int (char *buf, int value)
c906108c
SS
2496{
2497 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2498 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2499 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2500 buf = pack_hex_byte (buf, (value & 0xff));
2501 return buf;
2502}
2503
2504static char *
fba45db2 2505unpack_int (char *buf, int *value)
c906108c
SS
2506{
2507 *value = stub_unpack_int (buf, 8);
2508 return buf + 8;
2509}
2510
23860348 2511#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2512static char *pack_string (char *pkt, char *string);
c906108c
SS
2513
2514static char *
fba45db2 2515pack_string (char *pkt, char *string)
c906108c
SS
2516{
2517 char ch;
2518 int len;
2519
2520 len = strlen (string);
2521 if (len > 200)
23860348 2522 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2523 pkt = pack_hex_byte (pkt, len);
2524 while (len-- > 0)
2525 {
2526 ch = *string++;
2527 if ((ch == '\0') || (ch == '#'))
23860348 2528 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2529 *pkt++ = ch;
2530 }
2531 return pkt;
2532}
2533#endif /* 0 (unused) */
2534
2535static char *
fba45db2 2536unpack_string (char *src, char *dest, int length)
c906108c
SS
2537{
2538 while (length--)
2539 *dest++ = *src++;
2540 *dest = '\0';
2541 return src;
2542}
2543
2544static char *
fba45db2 2545pack_threadid (char *pkt, threadref *id)
c906108c
SS
2546{
2547 char *limit;
2548 unsigned char *altid;
2549
2550 altid = (unsigned char *) id;
2551 limit = pkt + BUF_THREAD_ID_SIZE;
2552 while (pkt < limit)
2553 pkt = pack_hex_byte (pkt, *altid++);
2554 return pkt;
2555}
2556
2557
2558static char *
fba45db2 2559unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2560{
2561 char *altref;
2562 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2563 int x, y;
2564
2565 altref = (char *) id;
2566
2567 while (inbuf < limit)
2568 {
2569 x = stubhex (*inbuf++);
2570 y = stubhex (*inbuf++);
2571 *altref++ = (x << 4) | y;
2572 }
2573 return inbuf;
2574}
2575
2576/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2577 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2578 to use 64bit thread references internally. This is an adapter
2579 function. */
2580
2581void
fba45db2 2582int_to_threadref (threadref *id, int value)
c906108c
SS
2583{
2584 unsigned char *scan;
2585
2586 scan = (unsigned char *) id;
2587 {
2588 int i = 4;
2589 while (i--)
2590 *scan++ = 0;
2591 }
2592 *scan++ = (value >> 24) & 0xff;
2593 *scan++ = (value >> 16) & 0xff;
2594 *scan++ = (value >> 8) & 0xff;
2595 *scan++ = (value & 0xff);
2596}
2597
2598static int
fba45db2 2599threadref_to_int (threadref *ref)
c906108c
SS
2600{
2601 int i, value = 0;
2602 unsigned char *scan;
2603
cfd77fa1 2604 scan = *ref;
c906108c
SS
2605 scan += 4;
2606 i = 4;
2607 while (i-- > 0)
2608 value = (value << 8) | ((*scan++) & 0xff);
2609 return value;
2610}
2611
2612static void
fba45db2 2613copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2614{
2615 int i;
2616 unsigned char *csrc, *cdest;
2617
2618 csrc = (unsigned char *) src;
2619 cdest = (unsigned char *) dest;
2620 i = 8;
2621 while (i--)
2622 *cdest++ = *csrc++;
2623}
2624
2625static int
fba45db2 2626threadmatch (threadref *dest, threadref *src)
c906108c 2627{
23860348 2628 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2629#if 0
2630 unsigned char *srcp, *destp;
2631 int i, result;
2632 srcp = (char *) src;
2633 destp = (char *) dest;
2634
2635 result = 1;
2636 while (i-- > 0)
2637 result &= (*srcp++ == *destp++) ? 1 : 0;
2638 return result;
2639#endif
2640 return 1;
2641}
2642
2643/*
c5aa993b
JM
2644 threadid:1, # always request threadid
2645 context_exists:2,
2646 display:4,
2647 unique_name:8,
2648 more_display:16
2649 */
c906108c
SS
2650
2651/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2652
2653static char *
fba45db2 2654pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2655{
23860348
MS
2656 *pkt++ = 'q'; /* Info Query */
2657 *pkt++ = 'P'; /* process or thread info */
2658 pkt = pack_int (pkt, mode); /* mode */
c906108c 2659 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2660 *pkt = '\0'; /* terminate */
c906108c
SS
2661 return pkt;
2662}
2663
23860348 2664/* These values tag the fields in a thread info response packet. */
c906108c 2665/* Tagging the fields allows us to request specific fields and to
23860348 2666 add more fields as time goes by. */
c906108c 2667
23860348 2668#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2669#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2670 fetch registers and its stack? */
c5aa993b 2671#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2672#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2673#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2674 the process. */
c906108c
SS
2675
2676static int
fba45db2
KB
2677remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2678 struct gdb_ext_thread_info *info)
c906108c 2679{
d01949b6 2680 struct remote_state *rs = get_remote_state ();
c906108c 2681 int mask, length;
cfd77fa1 2682 int tag;
c906108c 2683 threadref ref;
6d820c5c 2684 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2685 int retval = 1;
2686
23860348 2687 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2688 info->active = 0;
2689 info->display[0] = '\0';
2690 info->shortname[0] = '\0';
2691 info->more_display[0] = '\0';
2692
23860348
MS
2693 /* Assume the characters indicating the packet type have been
2694 stripped. */
c906108c
SS
2695 pkt = unpack_int (pkt, &mask); /* arg mask */
2696 pkt = unpack_threadid (pkt, &ref);
2697
2698 if (mask == 0)
8a3fe4f8 2699 warning (_("Incomplete response to threadinfo request."));
c906108c 2700 if (!threadmatch (&ref, expectedref))
23860348 2701 { /* This is an answer to a different request. */
8a3fe4f8 2702 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2703 return 0;
2704 }
2705 copy_threadref (&info->threadid, &ref);
2706
23860348 2707 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2708
23860348
MS
2709 /* Packets are terminated with nulls. */
2710 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2711 {
2712 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2713 pkt = unpack_byte (pkt, &length); /* length */
2714 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2715 {
8a3fe4f8 2716 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2717 retval = 0;
2718 break;
2719 }
2720 if (tag == TAG_THREADID)
2721 {
2722 if (length != 16)
2723 {
8a3fe4f8 2724 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2725 retval = 0;
2726 break;
2727 }
2728 pkt = unpack_threadid (pkt, &ref);
2729 mask = mask & ~TAG_THREADID;
2730 continue;
2731 }
2732 if (tag == TAG_EXISTS)
2733 {
2734 info->active = stub_unpack_int (pkt, length);
2735 pkt += length;
2736 mask = mask & ~(TAG_EXISTS);
2737 if (length > 8)
2738 {
8a3fe4f8 2739 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2740 retval = 0;
2741 break;
2742 }
2743 continue;
2744 }
2745 if (tag == TAG_THREADNAME)
2746 {
2747 pkt = unpack_string (pkt, &info->shortname[0], length);
2748 mask = mask & ~TAG_THREADNAME;
2749 continue;
2750 }
2751 if (tag == TAG_DISPLAY)
2752 {
2753 pkt = unpack_string (pkt, &info->display[0], length);
2754 mask = mask & ~TAG_DISPLAY;
2755 continue;
2756 }
2757 if (tag == TAG_MOREDISPLAY)
2758 {
2759 pkt = unpack_string (pkt, &info->more_display[0], length);
2760 mask = mask & ~TAG_MOREDISPLAY;
2761 continue;
2762 }
8a3fe4f8 2763 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2764 break; /* Not a tag we know about. */
c906108c
SS
2765 }
2766 return retval;
2767}
2768
2769static int
fba45db2
KB
2770remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2771 struct gdb_ext_thread_info *info)
c906108c 2772{
d01949b6 2773 struct remote_state *rs = get_remote_state ();
c906108c 2774 int result;
c906108c 2775
2e9f7625
DJ
2776 pack_threadinfo_request (rs->buf, fieldset, threadid);
2777 putpkt (rs->buf);
6d820c5c 2778 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2779
2780 if (rs->buf[0] == '\0')
2781 return 0;
2782
2e9f7625 2783 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2784 threadid, info);
c906108c
SS
2785 return result;
2786}
2787
c906108c
SS
2788/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2789
2790static char *
fba45db2
KB
2791pack_threadlist_request (char *pkt, int startflag, int threadcount,
2792 threadref *nextthread)
c906108c
SS
2793{
2794 *pkt++ = 'q'; /* info query packet */
2795 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2796 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2797 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2798 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2799 *pkt = '\0';
2800 return pkt;
2801}
2802
2803/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2804
2805static int
fba45db2
KB
2806parse_threadlist_response (char *pkt, int result_limit,
2807 threadref *original_echo, threadref *resultlist,
2808 int *doneflag)
c906108c 2809{
d01949b6 2810 struct remote_state *rs = get_remote_state ();
c906108c
SS
2811 char *limit;
2812 int count, resultcount, done;
2813
2814 resultcount = 0;
2815 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2816 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2817 /* done parse past here */
c906108c
SS
2818 pkt = unpack_byte (pkt, &count); /* count field */
2819 pkt = unpack_nibble (pkt, &done);
2820 /* The first threadid is the argument threadid. */
2821 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2822 while ((count-- > 0) && (pkt < limit))
2823 {
2824 pkt = unpack_threadid (pkt, resultlist++);
2825 if (resultcount++ >= result_limit)
2826 break;
2827 }
2828 if (doneflag)
2829 *doneflag = done;
2830 return resultcount;
2831}
2832
6dc54d91
PA
2833/* Fetch the next batch of threads from the remote. Returns -1 if the
2834 qL packet is not supported, 0 on error and 1 on success. */
2835
c906108c 2836static int
fba45db2
KB
2837remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2838 int *done, int *result_count, threadref *threadlist)
c906108c 2839{
d01949b6 2840 struct remote_state *rs = get_remote_state ();
c906108c
SS
2841 int result = 1;
2842
23860348 2843 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2844 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2845 >= get_remote_packet_size ())
ea9c271d 2846 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2847
6d820c5c
DJ
2848 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2849 putpkt (rs->buf);
2850 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2851 if (*rs->buf == '\0')
6dc54d91
PA
2852 {
2853 /* Packet not supported. */
2854 return -1;
2855 }
2856
2857 *result_count =
2858 parse_threadlist_response (rs->buf + 2, result_limit,
2859 &rs->echo_nextthread, threadlist, done);
c906108c 2860
0d031856 2861 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2862 {
23860348
MS
2863 /* FIXME: This is a good reason to drop the packet. */
2864 /* Possably, there is a duplicate response. */
c906108c
SS
2865 /* Possabilities :
2866 retransmit immediatly - race conditions
2867 retransmit after timeout - yes
2868 exit
2869 wait for packet, then exit
2870 */
8a3fe4f8 2871 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2872 return 0; /* I choose simply exiting. */
c906108c
SS
2873 }
2874 if (*result_count <= 0)
2875 {
2876 if (*done != 1)
2877 {
8a3fe4f8 2878 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2879 result = 0;
2880 }
2881 return result; /* break; */
2882 }
2883 if (*result_count > result_limit)
2884 {
2885 *result_count = 0;
8a3fe4f8 2886 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2887 return 0;
2888 }
2889 return result;
2890}
2891
6dc54d91
PA
2892/* Fetch the list of remote threads, with the qL packet, and call
2893 STEPFUNCTION for each thread found. Stops iterating and returns 1
2894 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2895 STEPFUNCTION returns false. If the packet is not supported,
2896 returns -1. */
c906108c 2897
c906108c 2898static int
fba45db2
KB
2899remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2900 int looplimit)
c906108c 2901{
0d031856 2902 struct remote_state *rs = get_remote_state ();
c906108c
SS
2903 int done, i, result_count;
2904 int startflag = 1;
2905 int result = 1;
2906 int loopcount = 0;
c906108c
SS
2907
2908 done = 0;
2909 while (!done)
2910 {
2911 if (loopcount++ > looplimit)
2912 {
2913 result = 0;
8a3fe4f8 2914 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2915 break;
2916 }
6dc54d91
PA
2917 result = remote_get_threadlist (startflag, &rs->nextthread,
2918 MAXTHREADLISTRESULTS,
2919 &done, &result_count,
2920 rs->resultthreadlist);
2921 if (result <= 0)
2922 break;
23860348 2923 /* Clear for later iterations. */
c906108c
SS
2924 startflag = 0;
2925 /* Setup to resume next batch of thread references, set nextthread. */
2926 if (result_count >= 1)
0d031856
TT
2927 copy_threadref (&rs->nextthread,
2928 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2929 i = 0;
2930 while (result_count--)
6dc54d91
PA
2931 {
2932 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2933 {
2934 result = 0;
2935 break;
2936 }
2937 }
c906108c
SS
2938 }
2939 return result;
2940}
2941
6dc54d91
PA
2942/* A thread found on the remote target. */
2943
2944typedef struct thread_item
2945{
2946 /* The thread's PTID. */
2947 ptid_t ptid;
2948
2949 /* The thread's extra info. May be NULL. */
2950 char *extra;
2951
79efa585
SM
2952 /* The thread's name. May be NULL. */
2953 char *name;
2954
6dc54d91
PA
2955 /* The core the thread was running on. -1 if not known. */
2956 int core;
2957} thread_item_t;
2958DEF_VEC_O(thread_item_t);
2959
2960/* Context passed around to the various methods listing remote
2961 threads. As new threads are found, they're added to the ITEMS
2962 vector. */
2963
2964struct threads_listing_context
2965{
2966 /* The threads found on the remote target. */
2967 VEC (thread_item_t) *items;
2968};
2969
80134cf5
PA
2970/* Discard the contents of the constructed thread listing context. */
2971
2972static void
2973clear_threads_listing_context (void *p)
2974{
19ba03f4
SM
2975 struct threads_listing_context *context
2976 = (struct threads_listing_context *) p;
80134cf5
PA
2977 int i;
2978 struct thread_item *item;
2979
2980 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
2981 {
2982 xfree (item->extra);
2983 xfree (item->name);
2984 }
80134cf5
PA
2985
2986 VEC_free (thread_item_t, context->items);
2987}
2988
cbb8991c
DB
2989/* Remove the thread specified as the related_pid field of WS
2990 from the CONTEXT list. */
2991
2992static void
2993threads_listing_context_remove (struct target_waitstatus *ws,
2994 struct threads_listing_context *context)
2995{
2996 struct thread_item *item;
2997 int i;
2998 ptid_t child_ptid = ws->value.related_pid;
2999
3000 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
3001 {
3002 if (ptid_equal (item->ptid, child_ptid))
3003 {
3004 VEC_ordered_remove (thread_item_t, context->items, i);
3005 break;
3006 }
3007 }
3008}
3009
c906108c 3010static int
6dc54d91 3011remote_newthread_step (threadref *ref, void *data)
c906108c 3012{
19ba03f4
SM
3013 struct threads_listing_context *context
3014 = (struct threads_listing_context *) data;
6dc54d91 3015 struct thread_item item;
79d7f229 3016 int pid = ptid_get_pid (inferior_ptid);
39f77062 3017
6dc54d91
PA
3018 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3019 item.core = -1;
2e3b657e 3020 item.name = NULL;
6dc54d91
PA
3021 item.extra = NULL;
3022
3023 VEC_safe_push (thread_item_t, context->items, &item);
3024
c906108c
SS
3025 return 1; /* continue iterator */
3026}
3027
3028#define CRAZY_MAX_THREADS 1000
3029
39f77062
KB
3030static ptid_t
3031remote_current_thread (ptid_t oldpid)
c906108c 3032{
d01949b6 3033 struct remote_state *rs = get_remote_state ();
c906108c
SS
3034
3035 putpkt ("qC");
6d820c5c 3036 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3037 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
3038 {
3039 char *obuf;
3040 ptid_t result;
3041
3042 result = read_ptid (&rs->buf[2], &obuf);
3043 if (*obuf != '\0' && remote_debug)
3044 fprintf_unfiltered (gdb_stdlog,
3045 "warning: garbage in qC reply\n");
3046
3047 return result;
3048 }
c906108c
SS
3049 else
3050 return oldpid;
3051}
3052
6dc54d91 3053/* List remote threads using the deprecated qL packet. */
cce74817 3054
6dc54d91
PA
3055static int
3056remote_get_threads_with_ql (struct target_ops *ops,
3057 struct threads_listing_context *context)
c906108c 3058{
6dc54d91
PA
3059 if (remote_threadlist_iterator (remote_newthread_step, context,
3060 CRAZY_MAX_THREADS) >= 0)
3061 return 1;
3062
3063 return 0;
c906108c
SS
3064}
3065
dc146f7c
VP
3066#if defined(HAVE_LIBEXPAT)
3067
dc146f7c
VP
3068static void
3069start_thread (struct gdb_xml_parser *parser,
3070 const struct gdb_xml_element *element,
3071 void *user_data, VEC(gdb_xml_value_s) *attributes)
3072{
19ba03f4
SM
3073 struct threads_listing_context *data
3074 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3075
3076 struct thread_item item;
3077 char *id;
3d2c1d41 3078 struct gdb_xml_value *attr;
dc146f7c 3079
19ba03f4 3080 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
3081 item.ptid = read_ptid (id, NULL);
3082
3d2c1d41
PA
3083 attr = xml_find_attribute (attributes, "core");
3084 if (attr != NULL)
3085 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
3086 else
3087 item.core = -1;
3088
79efa585 3089 attr = xml_find_attribute (attributes, "name");
e1961661 3090 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 3091
dc146f7c
VP
3092 item.extra = 0;
3093
3094 VEC_safe_push (thread_item_t, data->items, &item);
3095}
3096
3097static void
3098end_thread (struct gdb_xml_parser *parser,
3099 const struct gdb_xml_element *element,
3100 void *user_data, const char *body_text)
3101{
19ba03f4
SM
3102 struct threads_listing_context *data
3103 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3104
3105 if (body_text && *body_text)
2ae2a0b7 3106 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3107}
3108
3109const struct gdb_xml_attribute thread_attributes[] = {
3110 { "id", GDB_XML_AF_NONE, NULL, NULL },
3111 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3112 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3113 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3114};
3115
3116const struct gdb_xml_element thread_children[] = {
3117 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3118};
3119
3120const struct gdb_xml_element threads_children[] = {
3121 { "thread", thread_attributes, thread_children,
3122 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3123 start_thread, end_thread },
3124 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3125};
3126
3127const struct gdb_xml_element threads_elements[] = {
3128 { "threads", NULL, threads_children,
3129 GDB_XML_EF_NONE, NULL, NULL },
3130 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3131};
3132
3133#endif
3134
6dc54d91 3135/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3136
6dc54d91
PA
3137static int
3138remote_get_threads_with_qxfer (struct target_ops *ops,
3139 struct threads_listing_context *context)
0f71a2f6 3140{
dc146f7c 3141#if defined(HAVE_LIBEXPAT)
4082afcc 3142 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3143 {
6dc54d91 3144 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3145 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3146
6dc54d91 3147 if (xml != NULL && *xml != '\0')
dc146f7c 3148 {
6dc54d91
PA
3149 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3150 threads_elements, xml, context);
dc146f7c
VP
3151 }
3152
3153 do_cleanups (back_to);
6dc54d91 3154 return 1;
dc146f7c
VP
3155 }
3156#endif
3157
6dc54d91
PA
3158 return 0;
3159}
3160
3161/* List remote threads using qfThreadInfo/qsThreadInfo. */
3162
3163static int
3164remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3165 struct threads_listing_context *context)
3166{
3167 struct remote_state *rs = get_remote_state ();
3168
b80fafe3 3169 if (rs->use_threadinfo_query)
9d1f7ab2 3170 {
6dc54d91
PA
3171 char *bufp;
3172
9d1f7ab2 3173 putpkt ("qfThreadInfo");
6d820c5c 3174 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3175 bufp = rs->buf;
9d1f7ab2 3176 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3177 {
9d1f7ab2
MS
3178 while (*bufp++ == 'm') /* reply contains one or more TID */
3179 {
3180 do
3181 {
6dc54d91
PA
3182 struct thread_item item;
3183
3184 item.ptid = read_ptid (bufp, &bufp);
3185 item.core = -1;
2e3b657e 3186 item.name = NULL;
6dc54d91
PA
3187 item.extra = NULL;
3188
3189 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3190 }
3191 while (*bufp++ == ','); /* comma-separated list */
3192 putpkt ("qsThreadInfo");
6d820c5c 3193 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3194 bufp = rs->buf;
9d1f7ab2 3195 }
6dc54d91
PA
3196 return 1;
3197 }
3198 else
3199 {
3200 /* Packet not recognized. */
3201 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3202 }
3203 }
3204
6dc54d91
PA
3205 return 0;
3206}
3207
e8032dde 3208/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3209 targets. */
3210
3211static void
e8032dde 3212remote_update_thread_list (struct target_ops *ops)
6dc54d91 3213{
6dc54d91
PA
3214 struct threads_listing_context context;
3215 struct cleanup *old_chain;
ab970af1 3216 int got_list = 0;
e8032dde 3217
6dc54d91
PA
3218 context.items = NULL;
3219 old_chain = make_cleanup (clear_threads_listing_context, &context);
3220
3221 /* We have a few different mechanisms to fetch the thread list. Try
3222 them all, starting with the most preferred one first, falling
3223 back to older methods. */
3224 if (remote_get_threads_with_qxfer (ops, &context)
3225 || remote_get_threads_with_qthreadinfo (ops, &context)
3226 || remote_get_threads_with_ql (ops, &context))
3227 {
3228 int i;
3229 struct thread_item *item;
ab970af1
PA
3230 struct thread_info *tp, *tmp;
3231
3232 got_list = 1;
3233
7d1a114c
PA
3234 if (VEC_empty (thread_item_t, context.items)
3235 && remote_thread_always_alive (ops, inferior_ptid))
3236 {
3237 /* Some targets don't really support threads, but still
3238 reply an (empty) thread list in response to the thread
3239 listing packets, instead of replying "packet not
3240 supported". Exit early so we don't delete the main
3241 thread. */
3242 do_cleanups (old_chain);
3243 return;
3244 }
3245
ab970af1
PA
3246 /* CONTEXT now holds the current thread list on the remote
3247 target end. Delete GDB-side threads no longer found on the
3248 target. */
8a06aea7 3249 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3250 {
ab970af1
PA
3251 for (i = 0;
3252 VEC_iterate (thread_item_t, context.items, i, item);
3253 ++i)
3254 {
3255 if (ptid_equal (item->ptid, tp->ptid))
3256 break;
3257 }
3258
3259 if (i == VEC_length (thread_item_t, context.items))
3260 {
3261 /* Not found. */
3262 delete_thread (tp->ptid);
3263 }
cbb8991c
DB
3264 }
3265
3266 /* Remove any unreported fork child threads from CONTEXT so
3267 that we don't interfere with follow fork, which is where
3268 creation of such threads is handled. */
3269 remove_new_fork_children (&context);
74531fed 3270
ab970af1 3271 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3272 for (i = 0;
3273 VEC_iterate (thread_item_t, context.items, i, item);
3274 ++i)
3275 {
3276 if (!ptid_equal (item->ptid, null_ptid))
3277 {
3278 struct private_thread_info *info;
3279 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3280 executing until proven otherwise with a stop reply.
3281 In all-stop, we can only get here if all threads are
6dc54d91 3282 stopped. */
0d5b594f 3283 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3284
0d5b594f 3285 remote_notice_new_inferior (item->ptid, executing);
6dc54d91
PA
3286
3287 info = demand_private_info (item->ptid);
3288 info->core = item->core;
3289 info->extra = item->extra;
3290 item->extra = NULL;
79efa585
SM
3291 info->name = item->name;
3292 item->name = NULL;
6dc54d91
PA
3293 }
3294 }
3295 }
3296
ab970af1
PA
3297 if (!got_list)
3298 {
3299 /* If no thread listing method is supported, then query whether
3300 each known thread is alive, one by one, with the T packet.
3301 If the target doesn't support threads at all, then this is a
3302 no-op. See remote_thread_alive. */
3303 prune_threads ();
3304 }
3305
6dc54d91 3306 do_cleanups (old_chain);
9d1f7ab2
MS
3307}
3308
802188a7 3309/*
9d1f7ab2
MS
3310 * Collect a descriptive string about the given thread.
3311 * The target may say anything it wants to about the thread
3312 * (typically info about its blocked / runnable state, name, etc.).
3313 * This string will appear in the info threads display.
802188a7 3314 *
9d1f7ab2
MS
3315 * Optional: targets are not required to implement this function.
3316 */
3317
3318static char *
c15906d8 3319remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3320{
d01949b6 3321 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3322 int result;
3323 int set;
3324 threadref id;
3325 struct gdb_ext_thread_info threadinfo;
23860348 3326 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3327 int n = 0; /* position in display_buf */
3328
5d93a237 3329 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3330 internal_error (__FILE__, __LINE__,
e2e0b3e5 3331 _("remote_threads_extra_info"));
9d1f7ab2 3332
60e569b9 3333 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3334 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3335 /* This is the main thread which was added by GDB. The remote
3336 server doesn't know about it. */
3337 return NULL;
3338
4082afcc 3339 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3340 {
3341 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3342
fe978cb0
PA
3343 if (info && info->priv)
3344 return info->priv->extra;
dc146f7c
VP
3345 else
3346 return NULL;
3347 }
3348
b80fafe3 3349 if (rs->use_threadextra_query)
9d1f7ab2 3350 {
82f73884
PA
3351 char *b = rs->buf;
3352 char *endb = rs->buf + get_remote_packet_size ();
3353
3354 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3355 b += strlen (b);
3356 write_ptid (b, endb, tp->ptid);
3357
2e9f7625 3358 putpkt (rs->buf);
6d820c5c 3359 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3360 if (rs->buf[0] != 0)
9d1f7ab2 3361 {
2e9f7625
DJ
3362 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3363 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3364 display_buf [result] = '\0';
9d1f7ab2
MS
3365 return display_buf;
3366 }
0f71a2f6 3367 }
9d1f7ab2
MS
3368
3369 /* If the above query fails, fall back to the old method. */
b80fafe3 3370 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3371 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3372 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3373 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3374 if (remote_get_threadinfo (&id, set, &threadinfo))
3375 if (threadinfo.active)
0f71a2f6 3376 {
9d1f7ab2 3377 if (*threadinfo.shortname)
2bc416ba 3378 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3379 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3380 if (*threadinfo.display)
2bc416ba 3381 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3382 " State: %s,", threadinfo.display);
9d1f7ab2 3383 if (*threadinfo.more_display)
2bc416ba 3384 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3385 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3386
3387 if (n > 0)
c5aa993b 3388 {
23860348 3389 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3390 if (',' == display_buf[n-1])
3391 display_buf[n-1] = ' ';
3392 return display_buf;
c5aa993b 3393 }
0f71a2f6 3394 }
9d1f7ab2 3395 return NULL;
0f71a2f6 3396}
c906108c 3397\f
c5aa993b 3398
0fb4aa4b 3399static int
61fc905d 3400remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3401 struct static_tracepoint_marker *marker)
3402{
3403 struct remote_state *rs = get_remote_state ();
3404 char *p = rs->buf;
3405
bba74b36 3406 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3407 p += strlen (p);
3408 p += hexnumstr (p, addr);
3409 putpkt (rs->buf);
3410 getpkt (&rs->buf, &rs->buf_size, 0);
3411 p = rs->buf;
3412
3413 if (*p == 'E')
3414 error (_("Remote failure reply: %s"), p);
3415
3416 if (*p++ == 'm')
3417 {
3418 parse_static_tracepoint_marker_definition (p, &p, marker);
3419 return 1;
3420 }
3421
3422 return 0;
3423}
3424
0fb4aa4b 3425static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3426remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3427 const char *strid)
0fb4aa4b
PA
3428{
3429 struct remote_state *rs = get_remote_state ();
3430 VEC(static_tracepoint_marker_p) *markers = NULL;
3431 struct static_tracepoint_marker *marker = NULL;
3432 struct cleanup *old_chain;
3433 char *p;
3434
3435 /* Ask for a first packet of static tracepoint marker
3436 definition. */
3437 putpkt ("qTfSTM");
3438 getpkt (&rs->buf, &rs->buf_size, 0);
3439 p = rs->buf;
3440 if (*p == 'E')
3441 error (_("Remote failure reply: %s"), p);
3442
3443 old_chain = make_cleanup (free_current_marker, &marker);
3444
3445 while (*p++ == 'm')
3446 {
3447 if (marker == NULL)
3448 marker = XCNEW (struct static_tracepoint_marker);
3449
3450 do
3451 {
3452 parse_static_tracepoint_marker_definition (p, &p, marker);
3453
3454 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3455 {
3456 VEC_safe_push (static_tracepoint_marker_p,
3457 markers, marker);
3458 marker = NULL;
3459 }
3460 else
3461 {
3462 release_static_tracepoint_marker (marker);
3463 memset (marker, 0, sizeof (*marker));
3464 }
3465 }
3466 while (*p++ == ','); /* comma-separated list */
3467 /* Ask for another packet of static tracepoint definition. */
3468 putpkt ("qTsSTM");
3469 getpkt (&rs->buf, &rs->buf_size, 0);
3470 p = rs->buf;
3471 }
3472
3473 do_cleanups (old_chain);
3474 return markers;
3475}
3476
3477\f
10760264
JB
3478/* Implement the to_get_ada_task_ptid function for the remote targets. */
3479
3480static ptid_t
1e6b91a4 3481remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3482{
ba348170 3483 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3484}
3485\f
3486
24b06219 3487/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3488
3489static void
fba45db2 3490extended_remote_restart (void)
c906108c 3491{
d01949b6 3492 struct remote_state *rs = get_remote_state ();
c906108c
SS
3493
3494 /* Send the restart command; for reasons I don't understand the
3495 remote side really expects a number after the "R". */
ea9c271d 3496 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3497 putpkt (rs->buf);
c906108c 3498
ad9a8f3f 3499 remote_fileio_reset ();
c906108c
SS
3500}
3501\f
3502/* Clean up connection to a remote debugger. */
3503
c906108c 3504static void
de90e03d 3505remote_close (struct target_ops *self)
c906108c 3506{
5d93a237
TT
3507 struct remote_state *rs = get_remote_state ();
3508
3509 if (rs->remote_desc == NULL)
d3fd5342
PA
3510 return; /* already closed */
3511
3512 /* Make sure we leave stdin registered in the event loop, and we
3513 don't leave the async SIGINT signal handler installed. */
e3594fd1 3514 remote_terminal_ours (self);
ce5ce7ed 3515
5d93a237
TT
3516 serial_close (rs->remote_desc);
3517 rs->remote_desc = NULL;
ce5ce7ed
PA
3518
3519 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3520 of all the inferiors and their threads we were controlling.
3521 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3522 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3523 inferior_ptid = null_ptid;
f67fd822 3524 discard_all_inferiors ();
ce5ce7ed 3525
f48ff2a7
YQ
3526 /* We are closing the remote target, so we should discard
3527 everything of this target. */
bcc75809 3528 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3529
3530 if (remote_async_inferior_event_token)
3531 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3532
5965e028 3533 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3534
3535 trace_reset_local_state ();
c906108c
SS
3536}
3537
23860348 3538/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3539
3540static void
fba45db2 3541get_offsets (void)
c906108c 3542{
d01949b6 3543 struct remote_state *rs = get_remote_state ();
2e9f7625 3544 char *buf;
085dd6e6 3545 char *ptr;
31d99776
DJ
3546 int lose, num_segments = 0, do_sections, do_segments;
3547 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3548 struct section_offsets *offs;
31d99776
DJ
3549 struct symfile_segment_data *data;
3550
3551 if (symfile_objfile == NULL)
3552 return;
c906108c
SS
3553
3554 putpkt ("qOffsets");
6d820c5c 3555 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3556 buf = rs->buf;
c906108c
SS
3557
3558 if (buf[0] == '\000')
3559 return; /* Return silently. Stub doesn't support
23860348 3560 this command. */
c906108c
SS
3561 if (buf[0] == 'E')
3562 {
8a3fe4f8 3563 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3564 return;
3565 }
3566
3567 /* Pick up each field in turn. This used to be done with scanf, but
3568 scanf will make trouble if CORE_ADDR size doesn't match
3569 conversion directives correctly. The following code will work
3570 with any size of CORE_ADDR. */
3571 text_addr = data_addr = bss_addr = 0;
3572 ptr = buf;
3573 lose = 0;
3574
61012eef 3575 if (startswith (ptr, "Text="))
c906108c
SS
3576 {
3577 ptr += 5;
3578 /* Don't use strtol, could lose on big values. */
3579 while (*ptr && *ptr != ';')
3580 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3581
61012eef 3582 if (startswith (ptr, ";Data="))
31d99776
DJ
3583 {
3584 ptr += 6;
3585 while (*ptr && *ptr != ';')
3586 data_addr = (data_addr << 4) + fromhex (*ptr++);
3587 }
3588 else
3589 lose = 1;
3590
61012eef 3591 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3592 {
3593 ptr += 5;
3594 while (*ptr && *ptr != ';')
3595 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3596
31d99776
DJ
3597 if (bss_addr != data_addr)
3598 warning (_("Target reported unsupported offsets: %s"), buf);
3599 }
3600 else
3601 lose = 1;
3602 }
61012eef 3603 else if (startswith (ptr, "TextSeg="))
c906108c 3604 {
31d99776
DJ
3605 ptr += 8;
3606 /* Don't use strtol, could lose on big values. */
c906108c 3607 while (*ptr && *ptr != ';')
31d99776
DJ
3608 text_addr = (text_addr << 4) + fromhex (*ptr++);
3609 num_segments = 1;
3610
61012eef 3611 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3612 {
3613 ptr += 9;
3614 while (*ptr && *ptr != ';')
3615 data_addr = (data_addr << 4) + fromhex (*ptr++);
3616 num_segments++;
3617 }
c906108c
SS
3618 }
3619 else
3620 lose = 1;
3621
3622 if (lose)
8a3fe4f8 3623 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3624 else if (*ptr != '\0')
3625 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3626
802188a7 3627 offs = ((struct section_offsets *)
a39a16c4 3628 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3629 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3630 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3631
31d99776
DJ
3632 data = get_symfile_segment_data (symfile_objfile->obfd);
3633 do_segments = (data != NULL);
3634 do_sections = num_segments == 0;
c906108c 3635
28c32713 3636 if (num_segments > 0)
31d99776 3637 {
31d99776
DJ
3638 segments[0] = text_addr;
3639 segments[1] = data_addr;
3640 }
28c32713
JB
3641 /* If we have two segments, we can still try to relocate everything
3642 by assuming that the .text and .data offsets apply to the whole
3643 text and data segments. Convert the offsets given in the packet
3644 to base addresses for symfile_map_offsets_to_segments. */
3645 else if (data && data->num_segments == 2)
3646 {
3647 segments[0] = data->segment_bases[0] + text_addr;
3648 segments[1] = data->segment_bases[1] + data_addr;
3649 num_segments = 2;
3650 }
8d385431
DJ
3651 /* If the object file has only one segment, assume that it is text
3652 rather than data; main programs with no writable data are rare,
3653 but programs with no code are useless. Of course the code might
3654 have ended up in the data segment... to detect that we would need
3655 the permissions here. */
3656 else if (data && data->num_segments == 1)
3657 {
3658 segments[0] = data->segment_bases[0] + text_addr;
3659 num_segments = 1;
3660 }
28c32713
JB
3661 /* There's no way to relocate by segment. */
3662 else
3663 do_segments = 0;
31d99776
DJ
3664
3665 if (do_segments)
3666 {
3667 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3668 offs, num_segments, segments);
3669
3670 if (ret == 0 && !do_sections)
3e43a32a
MS
3671 error (_("Can not handle qOffsets TextSeg "
3672 "response with this symbol file"));
31d99776
DJ
3673
3674 if (ret > 0)
3675 do_sections = 0;
3676 }
c906108c 3677
9ef895d6
DJ
3678 if (data)
3679 free_symfile_segment_data (data);
31d99776
DJ
3680
3681 if (do_sections)
3682 {
3683 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3684
3e43a32a
MS
3685 /* This is a temporary kludge to force data and bss to use the
3686 same offsets because that's what nlmconv does now. The real
3687 solution requires changes to the stub and remote.c that I
3688 don't have time to do right now. */
31d99776
DJ
3689
3690 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3691 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3692 }
c906108c
SS
3693
3694 objfile_relocate (symfile_objfile, offs);
3695}
3696
9a7071a8
JB
3697/* Send interrupt_sequence to remote target. */
3698static void
eeae04df 3699send_interrupt_sequence (void)
9a7071a8 3700{
5d93a237
TT
3701 struct remote_state *rs = get_remote_state ();
3702
9a7071a8 3703 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3704 remote_serial_write ("\x03", 1);
9a7071a8 3705 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3706 serial_send_break (rs->remote_desc);
9a7071a8
JB
3707 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3708 {
5d93a237 3709 serial_send_break (rs->remote_desc);
c33e31fd 3710 remote_serial_write ("g", 1);
9a7071a8
JB
3711 }
3712 else
3713 internal_error (__FILE__, __LINE__,
3714 _("Invalid value for interrupt_sequence_mode: %s."),
3715 interrupt_sequence_mode);
3716}
3717
3405876a
PA
3718
3719/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3720 and extract the PTID. Returns NULL_PTID if not found. */
3721
3722static ptid_t
3723stop_reply_extract_thread (char *stop_reply)
3724{
3725 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3726 {
3727 char *p;
3728
3729 /* Txx r:val ; r:val (...) */
3730 p = &stop_reply[3];
3731
3732 /* Look for "register" named "thread". */
3733 while (*p != '\0')
3734 {
3735 char *p1;
3736
3737 p1 = strchr (p, ':');
3738 if (p1 == NULL)
3739 return null_ptid;
3740
3741 if (strncmp (p, "thread", p1 - p) == 0)
3742 return read_ptid (++p1, &p);
3743
3744 p1 = strchr (p, ';');
3745 if (p1 == NULL)
3746 return null_ptid;
3747 p1++;
3748
3749 p = p1;
3750 }
3751 }
3752
3753 return null_ptid;
3754}
3755
b7ea362b
PA
3756/* Determine the remote side's current thread. If we have a stop
3757 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3758 "thread" register we can extract the current thread from. If not,
3759 ask the remote which is the current thread with qC. The former
3760 method avoids a roundtrip. */
3761
3762static ptid_t
3763get_current_thread (char *wait_status)
3764{
6a49a997 3765 ptid_t ptid = null_ptid;
b7ea362b
PA
3766
3767 /* Note we don't use remote_parse_stop_reply as that makes use of
3768 the target architecture, which we haven't yet fully determined at
3769 this point. */
3770 if (wait_status != NULL)
3771 ptid = stop_reply_extract_thread (wait_status);
3772 if (ptid_equal (ptid, null_ptid))
3773 ptid = remote_current_thread (inferior_ptid);
3774
3775 return ptid;
3776}
3777
49c62f2e
PA
3778/* Query the remote target for which is the current thread/process,
3779 add it to our tables, and update INFERIOR_PTID. The caller is
3780 responsible for setting the state such that the remote end is ready
3405876a
PA
3781 to return the current thread.
3782
3783 This function is called after handling the '?' or 'vRun' packets,
3784 whose response is a stop reply from which we can also try
3785 extracting the thread. If the target doesn't support the explicit
3786 qC query, we infer the current thread from that stop reply, passed
3787 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3788
3789static void
3405876a 3790add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3791{
3792 struct remote_state *rs = get_remote_state ();
3793 int fake_pid_p = 0;
6a49a997 3794 ptid_t ptid;
49c62f2e
PA
3795
3796 inferior_ptid = null_ptid;
3797
b7ea362b
PA
3798 /* Now, if we have thread information, update inferior_ptid. */
3799 ptid = get_current_thread (wait_status);
3405876a 3800
49c62f2e
PA
3801 if (!ptid_equal (ptid, null_ptid))
3802 {
3803 if (!remote_multi_process_p (rs))
3804 fake_pid_p = 1;
3805
3806 inferior_ptid = ptid;
3807 }
3808 else
3809 {
3810 /* Without this, some commands which require an active target
3811 (such as kill) won't work. This variable serves (at least)
3812 double duty as both the pid of the target process (if it has
3813 such), and as a flag indicating that a target is active. */
3814 inferior_ptid = magic_null_ptid;
3815 fake_pid_p = 1;
3816 }
3817
1b6e6f5c 3818 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3819
3820 /* Add the main thread. */
3821 add_thread_silent (inferior_ptid);
3822}
3823
6efcd9a8
PA
3824/* Print info about a thread that was found already stopped on
3825 connection. */
3826
3827static void
3828print_one_stopped_thread (struct thread_info *thread)
3829{
3830 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3831
3832 switch_to_thread (thread->ptid);
3833 stop_pc = get_frame_pc (get_current_frame ());
3834 set_current_sal_from_frame (get_current_frame ());
3835
3836 thread->suspend.waitstatus_pending_p = 0;
3837
3838 if (ws->kind == TARGET_WAITKIND_STOPPED)
3839 {
3840 enum gdb_signal sig = ws->value.sig;
3841
3842 if (signal_print_state (sig))
3843 observer_notify_signal_received (sig);
3844 }
3845 observer_notify_normal_stop (NULL, 1);
3846}
3847
221e1a37
PA
3848/* Process all initial stop replies the remote side sent in response
3849 to the ? packet. These indicate threads that were already stopped
3850 on initial connection. We mark these threads as stopped and print
3851 their current frame before giving the user the prompt. */
3852
3853static void
6efcd9a8 3854process_initial_stop_replies (int from_tty)
221e1a37
PA
3855{
3856 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3857 struct inferior *inf;
3858 struct thread_info *thread;
3859 struct thread_info *selected = NULL;
3860 struct thread_info *lowest_stopped = NULL;
3861 struct thread_info *first = NULL;
221e1a37
PA
3862
3863 /* Consume the initial pending events. */
3864 while (pending_stop_replies-- > 0)
3865 {
3866 ptid_t waiton_ptid = minus_one_ptid;
3867 ptid_t event_ptid;
3868 struct target_waitstatus ws;
3869 int ignore_event = 0;
6efcd9a8 3870 struct thread_info *thread;
221e1a37
PA
3871
3872 memset (&ws, 0, sizeof (ws));
3873 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3874 if (remote_debug)
3875 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3876
3877 switch (ws.kind)
3878 {
3879 case TARGET_WAITKIND_IGNORE:
3880 case TARGET_WAITKIND_NO_RESUMED:
3881 case TARGET_WAITKIND_SIGNALLED:
3882 case TARGET_WAITKIND_EXITED:
3883 /* We shouldn't see these, but if we do, just ignore. */
3884 if (remote_debug)
3885 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3886 ignore_event = 1;
3887 break;
3888
3889 case TARGET_WAITKIND_EXECD:
3890 xfree (ws.value.execd_pathname);
3891 break;
3892 default:
3893 break;
3894 }
3895
3896 if (ignore_event)
3897 continue;
3898
6efcd9a8 3899 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3900
3901 if (ws.kind == TARGET_WAITKIND_STOPPED)
3902 {
3903 enum gdb_signal sig = ws.value.sig;
3904
3905 /* Stubs traditionally report SIGTRAP as initial signal,
3906 instead of signal 0. Suppress it. */
3907 if (sig == GDB_SIGNAL_TRAP)
3908 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3909 thread->suspend.stop_signal = sig;
3910 ws.value.sig = sig;
3911 }
221e1a37 3912
6efcd9a8
PA
3913 thread->suspend.waitstatus = ws;
3914
3915 if (ws.kind != TARGET_WAITKIND_STOPPED
3916 || ws.value.sig != GDB_SIGNAL_0)
3917 thread->suspend.waitstatus_pending_p = 1;
3918
3919 set_executing (event_ptid, 0);
3920 set_running (event_ptid, 0);
3921 }
3922
3923 /* "Notice" the new inferiors before anything related to
3924 registers/memory. */
3925 ALL_INFERIORS (inf)
3926 {
3927 if (inf->pid == 0)
3928 continue;
3929
3930 inf->needs_setup = 1;
3931
3932 if (non_stop)
3933 {
3934 thread = any_live_thread_of_process (inf->pid);
3935 notice_new_inferior (thread->ptid,
3936 thread->state == THREAD_RUNNING,
3937 from_tty);
3938 }
3939 }
3940
3941 /* If all-stop on top of non-stop, pause all threads. Note this
3942 records the threads' stop pc, so must be done after "noticing"
3943 the inferiors. */
3944 if (!non_stop)
3945 {
3946 stop_all_threads ();
3947
3948 /* If all threads of an inferior were already stopped, we
3949 haven't setup the inferior yet. */
3950 ALL_INFERIORS (inf)
3951 {
3952 if (inf->pid == 0)
3953 continue;
221e1a37 3954
6efcd9a8
PA
3955 if (inf->needs_setup)
3956 {
3957 thread = any_live_thread_of_process (inf->pid);
3958 switch_to_thread_no_regs (thread);
3959 setup_inferior (0);
3960 }
3961 }
221e1a37 3962 }
6efcd9a8
PA
3963
3964 /* Now go over all threads that are stopped, and print their current
3965 frame. If all-stop, then if there's a signalled thread, pick
3966 that as current. */
3967 ALL_NON_EXITED_THREADS (thread)
3968 {
6efcd9a8
PA
3969 if (first == NULL)
3970 first = thread;
3971
3972 if (!non_stop)
3973 set_running (thread->ptid, 0);
3974 else if (thread->state != THREAD_STOPPED)
3975 continue;
3976
6efcd9a8
PA
3977 if (selected == NULL
3978 && thread->suspend.waitstatus_pending_p)
3979 selected = thread;
3980
5d5658a1
PA
3981 if (lowest_stopped == NULL
3982 || thread->inf->num < lowest_stopped->inf->num
3983 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
3984 lowest_stopped = thread;
3985
3986 if (non_stop)
3987 print_one_stopped_thread (thread);
3988 }
3989
3990 /* In all-stop, we only print the status of one thread, and leave
3991 others with their status pending. */
3992 if (!non_stop)
3993 {
3994 thread = selected;
3995 if (thread == NULL)
3996 thread = lowest_stopped;
3997 if (thread == NULL)
3998 thread = first;
3999
4000 print_one_stopped_thread (thread);
4001 }
4002
4003 /* For "info program". */
4004 thread = inferior_thread ();
4005 if (thread->state == THREAD_STOPPED)
4006 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
4007}
4008
9cbc821d 4009static void
04bd08de 4010remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 4011{
c8d104ad
PA
4012 struct remote_state *rs = get_remote_state ();
4013 struct packet_config *noack_config;
2d717e4f 4014 char *wait_status = NULL;
8621d6a9 4015
23860348 4016 immediate_quit++; /* Allow user to interrupt it. */
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. */
5d93a237 4023 serial_write (rs->remote_desc, "+", 1);
57e12211 4024
1e51243a
PA
4025 /* Signal other parts that we're going through the initial setup,
4026 and so things may not be stable yet. */
4027 rs->starting_up = 1;
4028
c8d104ad
PA
4029 /* The first packet we send to the target is the optional "supported
4030 packets" request. If the target can answer this, it will tell us
4031 which later probes to skip. */
4032 remote_query_supported ();
4033
d914c394 4034 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4035 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 4036 remote_set_permissions (target);
d914c394 4037
fef3cb9f
JK
4038 /* See unknown_v_replies_ok description. */
4039 {
4040 const char v_mustreplyempty[] = "vMustReplyEmpty";
4041
4042 putpkt (v_mustreplyempty);
4043 getpkt (&rs->buf, &rs->buf_size, 0);
4044 if (strcmp (rs->buf, "OK") == 0)
4045 unknown_v_replies_ok = 1;
4046 else if (strcmp (rs->buf, "") == 0)
4047 unknown_v_replies_ok = 0;
4048 else
4049 error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4050 rs->buf);
4051 }
4052
c8d104ad
PA
4053 /* Next, we possibly activate noack mode.
4054
4055 If the QStartNoAckMode packet configuration is set to AUTO,
4056 enable noack mode if the stub reported a wish for it with
4057 qSupported.
4058
4059 If set to TRUE, then enable noack mode even if the stub didn't
4060 report it in qSupported. If the stub doesn't reply OK, the
4061 session ends with an error.
4062
4063 If FALSE, then don't activate noack mode, regardless of what the
4064 stub claimed should be the default with qSupported. */
4065
4066 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4067 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4068 {
4069 putpkt ("QStartNoAckMode");
4070 getpkt (&rs->buf, &rs->buf_size, 0);
4071 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4072 rs->noack_mode = 1;
4073 }
4074
04bd08de 4075 if (extended_p)
5fe04517
PA
4076 {
4077 /* Tell the remote that we are using the extended protocol. */
4078 putpkt ("!");
4079 getpkt (&rs->buf, &rs->buf_size, 0);
4080 }
4081
9b224c5e
PA
4082 /* Let the target know which signals it is allowed to pass down to
4083 the program. */
4084 update_signals_program_target ();
4085
d962ef82
DJ
4086 /* Next, if the target can specify a description, read it. We do
4087 this before anything involving memory or registers. */
4088 target_find_description ();
4089
6c95b8df
PA
4090 /* Next, now that we know something about the target, update the
4091 address spaces in the program spaces. */
4092 update_address_spaces ();
4093
50c71eaf
PA
4094 /* On OSs where the list of libraries is global to all
4095 processes, we fetch them early. */
f5656ead 4096 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 4097 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 4098
6efcd9a8 4099 if (target_is_non_stop_p ())
74531fed 4100 {
4082afcc 4101 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4102 error (_("Non-stop mode requested, but remote "
4103 "does not support non-stop"));
74531fed
PA
4104
4105 putpkt ("QNonStop:1");
4106 getpkt (&rs->buf, &rs->buf_size, 0);
4107
4108 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4109 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4110
4111 /* Find about threads and processes the stub is already
4112 controlling. We default to adding them in the running state.
4113 The '?' query below will then tell us about which threads are
4114 stopped. */
e8032dde 4115 remote_update_thread_list (target);
74531fed 4116 }
4082afcc 4117 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4118 {
4119 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4120 Request it explicitly. */
74531fed
PA
4121 putpkt ("QNonStop:0");
4122 getpkt (&rs->buf, &rs->buf_size, 0);
4123
4124 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4125 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4126 }
4127
a0743c90
YQ
4128 /* Upload TSVs regardless of whether the target is running or not. The
4129 remote stub, such as GDBserver, may have some predefined or builtin
4130 TSVs, even if the target is not running. */
8bd200f1 4131 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4132 {
4133 struct uploaded_tsv *uploaded_tsvs = NULL;
4134
181e3713 4135 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4136 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4137 }
4138
2d717e4f
DJ
4139 /* Check whether the target is running now. */
4140 putpkt ("?");
4141 getpkt (&rs->buf, &rs->buf_size, 0);
4142
6efcd9a8 4143 if (!target_is_non_stop_p ())
2d717e4f 4144 {
74531fed 4145 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4146 {
04bd08de 4147 if (!extended_p)
74531fed 4148 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4149
4150 /* We're connected, but not running. Drop out before we
4151 call start_remote. */
e278ad5b 4152 rs->starting_up = 0;
c35b1492 4153 return;
2d717e4f
DJ
4154 }
4155 else
74531fed 4156 {
74531fed 4157 /* Save the reply for later. */
224c3ddb 4158 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4159 strcpy (wait_status, rs->buf);
4160 }
4161
b7ea362b 4162 /* Fetch thread list. */
e8032dde 4163 target_update_thread_list ();
b7ea362b 4164
74531fed
PA
4165 /* Let the stub know that we want it to return the thread. */
4166 set_continue_thread (minus_one_ptid);
4167
b7ea362b
PA
4168 if (thread_count () == 0)
4169 {
4170 /* Target has no concept of threads at all. GDB treats
4171 non-threaded target as single-threaded; add a main
4172 thread. */
4173 add_current_inferior_and_thread (wait_status);
4174 }
4175 else
4176 {
4177 /* We have thread information; select the thread the target
4178 says should be current. If we're reconnecting to a
4179 multi-threaded program, this will ideally be the thread
4180 that last reported an event before GDB disconnected. */
4181 inferior_ptid = get_current_thread (wait_status);
4182 if (ptid_equal (inferior_ptid, null_ptid))
4183 {
4184 /* Odd... The target was able to list threads, but not
4185 tell us which thread was current (no "thread"
4186 register in T stop reply?). Just pick the first
4187 thread in the thread list then. */
c9f35b34
KB
4188
4189 if (remote_debug)
4190 fprintf_unfiltered (gdb_stdlog,
4191 "warning: couldn't determine remote "
4192 "current thread; picking first in list.\n");
4193
b7ea362b
PA
4194 inferior_ptid = thread_list->ptid;
4195 }
4196 }
74531fed 4197
6e586cc5
YQ
4198 /* init_wait_for_inferior should be called before get_offsets in order
4199 to manage `inserted' flag in bp loc in a correct state.
4200 breakpoint_init_inferior, called from init_wait_for_inferior, set
4201 `inserted' flag to 0, while before breakpoint_re_set, called from
4202 start_remote, set `inserted' flag to 1. In the initialization of
4203 inferior, breakpoint_init_inferior should be called first, and then
4204 breakpoint_re_set can be called. If this order is broken, state of
4205 `inserted' flag is wrong, and cause some problems on breakpoint
4206 manipulation. */
4207 init_wait_for_inferior ();
4208
74531fed
PA
4209 get_offsets (); /* Get text, data & bss offsets. */
4210
d962ef82
DJ
4211 /* If we could not find a description using qXfer, and we know
4212 how to do it some other way, try again. This is not
4213 supported for non-stop; it could be, but it is tricky if
4214 there are no stopped threads when we connect. */
04bd08de 4215 if (remote_read_description_p (target)
f5656ead 4216 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4217 {
4218 target_clear_description ();
4219 target_find_description ();
4220 }
4221
74531fed
PA
4222 /* Use the previously fetched status. */
4223 gdb_assert (wait_status != NULL);
4224 strcpy (rs->buf, wait_status);
4225 rs->cached_wait_status = 1;
4226
4227 immediate_quit--;
04bd08de 4228 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4229 }
4230 else
4231 {
68c97600
PA
4232 /* Clear WFI global state. Do this before finding about new
4233 threads and inferiors, and setting the current inferior.
4234 Otherwise we would clear the proceed status of the current
4235 inferior when we want its stop_soon state to be preserved
4236 (see notice_new_inferior). */
4237 init_wait_for_inferior ();
4238
74531fed
PA
4239 /* In non-stop, we will either get an "OK", meaning that there
4240 are no stopped threads at this time; or, a regular stop
4241 reply. In the latter case, there may be more than one thread
4242 stopped --- we pull them all out using the vStopped
4243 mechanism. */
4244 if (strcmp (rs->buf, "OK") != 0)
4245 {
722247f1 4246 struct notif_client *notif = &notif_client_stop;
2d717e4f 4247
722247f1
YQ
4248 /* remote_notif_get_pending_replies acks this one, and gets
4249 the rest out. */
f48ff2a7 4250 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4251 = remote_notif_parse (notif, rs->buf);
4252 remote_notif_get_pending_events (notif);
74531fed 4253 }
2d717e4f 4254
74531fed
PA
4255 if (thread_count () == 0)
4256 {
04bd08de 4257 if (!extended_p)
74531fed 4258 error (_("The target is not running (try extended-remote?)"));
82f73884 4259
c35b1492
PA
4260 /* We're connected, but not running. Drop out before we
4261 call start_remote. */
e278ad5b 4262 rs->starting_up = 0;
c35b1492
PA
4263 return;
4264 }
74531fed 4265
74531fed
PA
4266 /* In non-stop mode, any cached wait status will be stored in
4267 the stop reply queue. */
4268 gdb_assert (wait_status == NULL);
f0223081 4269
2455069d 4270 /* Report all signals during attach/startup. */
94bedb42 4271 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4272
4273 /* If there are already stopped threads, mark them stopped and
4274 report their stops before giving the prompt to the user. */
6efcd9a8 4275 process_initial_stop_replies (from_tty);
221e1a37
PA
4276
4277 if (target_can_async_p ())
4278 target_async (1);
74531fed 4279 }
c8d104ad 4280
c8d104ad
PA
4281 /* If we connected to a live target, do some additional setup. */
4282 if (target_has_execution)
4283 {
f4ccffad 4284 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4285 remote_check_symbols ();
c8d104ad 4286 }
50c71eaf 4287
d5551862
SS
4288 /* Possibly the target has been engaged in a trace run started
4289 previously; find out where things are at. */
8bd200f1 4290 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4291 {
00bf0b85 4292 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4293
00bf0b85
SS
4294 if (current_trace_status ()->running)
4295 printf_filtered (_("Trace is already running on the target.\n"));
4296
ab6617cc 4297 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4298
4299 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4300 }
4301
1e51243a
PA
4302 /* The thread and inferior lists are now synchronized with the
4303 target, our symbols have been relocated, and we're merged the
4304 target's tracepoints with ours. We're done with basic start
4305 up. */
4306 rs->starting_up = 0;
4307
a25a5a45
PA
4308 /* Maybe breakpoints are global and need to be inserted now. */
4309 if (breakpoints_should_be_inserted_now ())
50c71eaf 4310 insert_breakpoints ();
c906108c
SS
4311}
4312
4313/* Open a connection to a remote debugger.
4314 NAME is the filename used for communication. */
4315
4316static void
014f9477 4317remote_open (const char *name, int from_tty)
c906108c 4318{
75c99385 4319 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4320}
4321
c906108c
SS
4322/* Open a connection to a remote debugger using the extended
4323 remote gdb protocol. NAME is the filename used for communication. */
4324
4325static void
014f9477 4326extended_remote_open (const char *name, int from_tty)
c906108c 4327{
75c99385 4328 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4329}
4330
ca4f7f8b
PA
4331/* Reset all packets back to "unknown support". Called when opening a
4332 new connection to a remote target. */
c906108c 4333
d471ea57 4334static void
ca4f7f8b 4335reset_all_packet_configs_support (void)
d471ea57
AC
4336{
4337 int i;
a744cf53 4338
444abaca 4339 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4340 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4341}
4342
ca4f7f8b
PA
4343/* Initialize all packet configs. */
4344
4345static void
4346init_all_packet_configs (void)
4347{
4348 int i;
4349
4350 for (i = 0; i < PACKET_MAX; i++)
4351 {
4352 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4353 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4354 }
4355}
4356
23860348 4357/* Symbol look-up. */
dc8acb97
MS
4358
4359static void
36d25514 4360remote_check_symbols (void)
dc8acb97 4361{
d01949b6 4362 struct remote_state *rs = get_remote_state ();
dc8acb97 4363 char *msg, *reply, *tmp;
dc8acb97 4364 int end;
28170b88 4365 long reply_size;
a5c0808e 4366 struct cleanup *old_chain;
dc8acb97 4367
63154eca
PA
4368 /* The remote side has no concept of inferiors that aren't running
4369 yet, it only knows about running processes. If we're connected
4370 but our current inferior is not running, we should not invite the
4371 remote target to request symbol lookups related to its
4372 (unrelated) current process. */
4373 if (!target_has_execution)
4374 return;
4375
4082afcc 4376 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4377 return;
4378
63154eca
PA
4379 /* Make sure the remote is pointing at the right process. Note
4380 there's no way to select "no process". */
3c9c4b83
PA
4381 set_general_process ();
4382
6d820c5c
DJ
4383 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4384 because we need both at the same time. */
224c3ddb 4385 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4386 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4387 reply = (char *) xmalloc (get_remote_packet_size ());
4388 make_cleanup (free_current_contents, &reply);
4389 reply_size = get_remote_packet_size ();
6d820c5c 4390
23860348 4391 /* Invite target to request symbol lookups. */
dc8acb97
MS
4392
4393 putpkt ("qSymbol::");
28170b88
MK
4394 getpkt (&reply, &reply_size, 0);
4395 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4396
61012eef 4397 while (startswith (reply, "qSymbol:"))
dc8acb97 4398 {
77e371c0
TT
4399 struct bound_minimal_symbol sym;
4400
dc8acb97 4401 tmp = &reply[8];
cfd77fa1 4402 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4403 msg[end] = '\0';
4404 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4405 if (sym.minsym == NULL)
ea9c271d 4406 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4407 else
2bbe3cc1 4408 {
f5656ead 4409 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4410 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4411
4412 /* If this is a function address, return the start of code
4413 instead of any data function descriptor. */
f5656ead 4414 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4415 sym_addr,
4416 &current_target);
4417
4418 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4419 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4420 }
4421
dc8acb97 4422 putpkt (msg);
28170b88 4423 getpkt (&reply, &reply_size, 0);
dc8acb97 4424 }
a5c0808e
PA
4425
4426 do_cleanups (old_chain);
dc8acb97
MS
4427}
4428
9db8d71f 4429static struct serial *
baa336ce 4430remote_serial_open (const char *name)
9db8d71f
DJ
4431{
4432 static int udp_warning = 0;
4433
4434 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4435 of in ser-tcp.c, because it is the remote protocol assuming that the
4436 serial connection is reliable and not the serial connection promising
4437 to be. */
61012eef 4438 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4439 {
3e43a32a
MS
4440 warning (_("The remote protocol may be unreliable over UDP.\n"
4441 "Some events may be lost, rendering further debugging "
4442 "impossible."));
9db8d71f
DJ
4443 udp_warning = 1;
4444 }
4445
4446 return serial_open (name);
4447}
4448
d914c394
SS
4449/* Inform the target of our permission settings. The permission flags
4450 work without this, but if the target knows the settings, it can do
4451 a couple things. First, it can add its own check, to catch cases
4452 that somehow manage to get by the permissions checks in target
4453 methods. Second, if the target is wired to disallow particular
4454 settings (for instance, a system in the field that is not set up to
4455 be able to stop at a breakpoint), it can object to any unavailable
4456 permissions. */
4457
4458void
c378d69d 4459remote_set_permissions (struct target_ops *self)
d914c394
SS
4460{
4461 struct remote_state *rs = get_remote_state ();
4462
bba74b36
YQ
4463 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4464 "WriteReg:%x;WriteMem:%x;"
4465 "InsertBreak:%x;InsertTrace:%x;"
4466 "InsertFastTrace:%x;Stop:%x",
4467 may_write_registers, may_write_memory,
4468 may_insert_breakpoints, may_insert_tracepoints,
4469 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4470 putpkt (rs->buf);
4471 getpkt (&rs->buf, &rs->buf_size, 0);
4472
4473 /* If the target didn't like the packet, warn the user. Do not try
4474 to undo the user's settings, that would just be maddening. */
4475 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4476 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4477}
4478
be2a5f71
DJ
4479/* This type describes each known response to the qSupported
4480 packet. */
4481struct protocol_feature
4482{
4483 /* The name of this protocol feature. */
4484 const char *name;
4485
4486 /* The default for this protocol feature. */
4487 enum packet_support default_support;
4488
4489 /* The function to call when this feature is reported, or after
4490 qSupported processing if the feature is not supported.
4491 The first argument points to this structure. The second
4492 argument indicates whether the packet requested support be
4493 enabled, disabled, or probed (or the default, if this function
4494 is being called at the end of processing and this feature was
4495 not reported). The third argument may be NULL; if not NULL, it
4496 is a NUL-terminated string taken from the packet following
4497 this feature's name and an equals sign. */
4498 void (*func) (const struct protocol_feature *, enum packet_support,
4499 const char *);
4500
4501 /* The corresponding packet for this feature. Only used if
4502 FUNC is remote_supported_packet. */
4503 int packet;
4504};
4505
be2a5f71
DJ
4506static void
4507remote_supported_packet (const struct protocol_feature *feature,
4508 enum packet_support support,
4509 const char *argument)
4510{
4511 if (argument)
4512 {
4513 warning (_("Remote qSupported response supplied an unexpected value for"
4514 " \"%s\"."), feature->name);
4515 return;
4516 }
4517
4082afcc 4518 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4519}
be2a5f71
DJ
4520
4521static void
4522remote_packet_size (const struct protocol_feature *feature,
4523 enum packet_support support, const char *value)
4524{
4525 struct remote_state *rs = get_remote_state ();
4526
4527 int packet_size;
4528 char *value_end;
4529
4530 if (support != PACKET_ENABLE)
4531 return;
4532
4533 if (value == NULL || *value == '\0')
4534 {
4535 warning (_("Remote target reported \"%s\" without a size."),
4536 feature->name);
4537 return;
4538 }
4539
4540 errno = 0;
4541 packet_size = strtol (value, &value_end, 16);
4542 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4543 {
4544 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4545 feature->name, value);
4546 return;
4547 }
4548
be2a5f71
DJ
4549 /* Record the new maximum packet size. */
4550 rs->explicit_packet_size = packet_size;
4551}
4552
dc473cfb 4553static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4554 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4555 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4556 PACKET_qXfer_auxv },
c78fa86a
GB
4557 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4558 PACKET_qXfer_exec_file },
23181151
DJ
4559 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4560 PACKET_qXfer_features },
cfa9d6d9
DJ
4561 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4562 PACKET_qXfer_libraries },
2268b414
JK
4563 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4564 PACKET_qXfer_libraries_svr4 },
ced63ec0 4565 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4566 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4567 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4568 PACKET_qXfer_memory_map },
4de6483e
UW
4569 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4570 PACKET_qXfer_spu_read },
4571 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4572 PACKET_qXfer_spu_write },
07e059b5
VP
4573 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4574 PACKET_qXfer_osdata },
dc146f7c
VP
4575 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4576 PACKET_qXfer_threads },
b3b9301e
PA
4577 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4578 PACKET_qXfer_traceframe_info },
89be2091
DJ
4579 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4580 PACKET_QPassSignals },
82075af2
JS
4581 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4582 PACKET_QCatchSyscalls },
9b224c5e
PA
4583 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4584 PACKET_QProgramSignals },
a6f3e723
SL
4585 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4586 PACKET_QStartNoAckMode },
4082afcc
PA
4587 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4588 PACKET_multiprocess_feature },
4589 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4590 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4591 PACKET_qXfer_siginfo_read },
4592 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4593 PACKET_qXfer_siginfo_write },
4082afcc 4594 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4595 PACKET_ConditionalTracepoints },
4082afcc 4596 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4597 PACKET_ConditionalBreakpoints },
4082afcc 4598 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4599 PACKET_BreakpointCommands },
4082afcc 4600 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4601 PACKET_FastTracepoints },
4082afcc 4602 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4603 PACKET_StaticTracepoints },
4082afcc 4604 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4605 PACKET_InstallInTrace},
4082afcc
PA
4606 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4607 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4608 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4609 PACKET_bc },
4610 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4611 PACKET_bs },
409873ef
SS
4612 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4613 PACKET_TracepointSource },
d914c394
SS
4614 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4615 PACKET_QAllow },
4082afcc
PA
4616 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4617 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4618 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4619 PACKET_qXfer_fdpic },
169081d0
TG
4620 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4621 PACKET_qXfer_uib },
03583c20
UW
4622 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4623 PACKET_QDisableRandomization },
d1feda86 4624 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4625 { "QTBuffer:size", PACKET_DISABLE,
4626 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4627 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4628 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4629 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4630 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4631 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4632 PACKET_qXfer_btrace },
4633 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4634 PACKET_qXfer_btrace_conf },
4635 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4636 PACKET_Qbtrace_conf_bts_size },
4637 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4638 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4639 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4640 PACKET_fork_event_feature },
4641 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4642 PACKET_vfork_event_feature },
94585166
DB
4643 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4644 PACKET_exec_event_feature },
b20a6524 4645 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4646 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4647 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4648 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4649 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4650};
4651
c8d5aac9
L
4652static char *remote_support_xml;
4653
4654/* Register string appended to "xmlRegisters=" in qSupported query. */
4655
4656void
6e39997a 4657register_remote_support_xml (const char *xml)
c8d5aac9
L
4658{
4659#if defined(HAVE_LIBEXPAT)
4660 if (remote_support_xml == NULL)
c4f7c687 4661 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4662 else
4663 {
4664 char *copy = xstrdup (remote_support_xml + 13);
4665 char *p = strtok (copy, ",");
4666
4667 do
4668 {
4669 if (strcmp (p, xml) == 0)
4670 {
4671 /* already there */
4672 xfree (copy);
4673 return;
4674 }
4675 }
4676 while ((p = strtok (NULL, ",")) != NULL);
4677 xfree (copy);
4678
94b0dee1
PA
4679 remote_support_xml = reconcat (remote_support_xml,
4680 remote_support_xml, ",", xml,
4681 (char *) NULL);
c8d5aac9
L
4682 }
4683#endif
4684}
4685
4686static char *
4687remote_query_supported_append (char *msg, const char *append)
4688{
4689 if (msg)
94b0dee1 4690 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4691 else
4692 return xstrdup (append);
4693}
4694
be2a5f71
DJ
4695static void
4696remote_query_supported (void)
4697{
4698 struct remote_state *rs = get_remote_state ();
4699 char *next;
4700 int i;
4701 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4702
4703 /* The packet support flags are handled differently for this packet
4704 than for most others. We treat an error, a disabled packet, and
4705 an empty response identically: any features which must be reported
4706 to be used will be automatically disabled. An empty buffer
4707 accomplishes this, since that is also the representation for a list
4708 containing no features. */
4709
4710 rs->buf[0] = 0;
4082afcc 4711 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4712 {
c8d5aac9 4713 char *q = NULL;
94b0dee1 4714 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4715
73b8c1fd
PA
4716 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4717 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4718
f7e6eed5
PA
4719 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4720 q = remote_query_supported_append (q, "swbreak+");
4721 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4722 q = remote_query_supported_append (q, "hwbreak+");
4723
dde08ee1
PA
4724 q = remote_query_supported_append (q, "qRelocInsn+");
4725
8020350c
DB
4726 if (packet_set_cmd_state (PACKET_fork_event_feature)
4727 != AUTO_BOOLEAN_FALSE)
4728 q = remote_query_supported_append (q, "fork-events+");
4729 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4730 != AUTO_BOOLEAN_FALSE)
4731 q = remote_query_supported_append (q, "vfork-events+");
4732 if (packet_set_cmd_state (PACKET_exec_event_feature)
4733 != AUTO_BOOLEAN_FALSE)
4734 q = remote_query_supported_append (q, "exec-events+");
89245bc0 4735
750ce8d1
YQ
4736 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4737 q = remote_query_supported_append (q, "vContSupported+");
4738
65706a29
PA
4739 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4740 q = remote_query_supported_append (q, "QThreadEvents+");
4741
f2faf941
PA
4742 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4743 q = remote_query_supported_append (q, "no-resumed+");
4744
b35d5edb
PA
4745 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4746 the qSupported:xmlRegisters=i386 handling. */
4747 if (remote_support_xml != NULL)
4748 q = remote_query_supported_append (q, remote_support_xml);
4749
dde08ee1
PA
4750 q = reconcat (q, "qSupported:", q, (char *) NULL);
4751 putpkt (q);
82f73884 4752
94b0dee1
PA
4753 do_cleanups (old_chain);
4754
be2a5f71
DJ
4755 getpkt (&rs->buf, &rs->buf_size, 0);
4756
4757 /* If an error occured, warn, but do not return - just reset the
4758 buffer to empty and go on to disable features. */
4759 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4760 == PACKET_ERROR)
4761 {
4762 warning (_("Remote failure reply: %s"), rs->buf);
4763 rs->buf[0] = 0;
4764 }
4765 }
4766
4767 memset (seen, 0, sizeof (seen));
4768
4769 next = rs->buf;
4770 while (*next)
4771 {
4772 enum packet_support is_supported;
4773 char *p, *end, *name_end, *value;
4774
4775 /* First separate out this item from the rest of the packet. If
4776 there's another item after this, we overwrite the separator
4777 (terminated strings are much easier to work with). */
4778 p = next;
4779 end = strchr (p, ';');
4780 if (end == NULL)
4781 {
4782 end = p + strlen (p);
4783 next = end;
4784 }
4785 else
4786 {
89be2091
DJ
4787 *end = '\0';
4788 next = end + 1;
4789
be2a5f71
DJ
4790 if (end == p)
4791 {
4792 warning (_("empty item in \"qSupported\" response"));
4793 continue;
4794 }
be2a5f71
DJ
4795 }
4796
4797 name_end = strchr (p, '=');
4798 if (name_end)
4799 {
4800 /* This is a name=value entry. */
4801 is_supported = PACKET_ENABLE;
4802 value = name_end + 1;
4803 *name_end = '\0';
4804 }
4805 else
4806 {
4807 value = NULL;
4808 switch (end[-1])
4809 {
4810 case '+':
4811 is_supported = PACKET_ENABLE;
4812 break;
4813
4814 case '-':
4815 is_supported = PACKET_DISABLE;
4816 break;
4817
4818 case '?':
4819 is_supported = PACKET_SUPPORT_UNKNOWN;
4820 break;
4821
4822 default:
3e43a32a
MS
4823 warning (_("unrecognized item \"%s\" "
4824 "in \"qSupported\" response"), p);
be2a5f71
DJ
4825 continue;
4826 }
4827 end[-1] = '\0';
4828 }
4829
4830 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4831 if (strcmp (remote_protocol_features[i].name, p) == 0)
4832 {
4833 const struct protocol_feature *feature;
4834
4835 seen[i] = 1;
4836 feature = &remote_protocol_features[i];
4837 feature->func (feature, is_supported, value);
4838 break;
4839 }
4840 }
4841
4842 /* If we increased the packet size, make sure to increase the global
4843 buffer size also. We delay this until after parsing the entire
4844 qSupported packet, because this is the same buffer we were
4845 parsing. */
4846 if (rs->buf_size < rs->explicit_packet_size)
4847 {
4848 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4849 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4850 }
4851
4852 /* Handle the defaults for unmentioned features. */
4853 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4854 if (!seen[i])
4855 {
4856 const struct protocol_feature *feature;
4857
4858 feature = &remote_protocol_features[i];
4859 feature->func (feature, feature->default_support, NULL);
4860 }
4861}
4862
78a095c3
JK
4863/* Remove any of the remote.c targets from target stack. Upper targets depend
4864 on it so remove them first. */
4865
4866static void
4867remote_unpush_target (void)
4868{
915ef8b1 4869 pop_all_targets_at_and_above (process_stratum);
78a095c3 4870}
be2a5f71 4871
c906108c 4872static void
014f9477 4873remote_open_1 (const char *name, int from_tty,
3e43a32a 4874 struct target_ops *target, int extended_p)
c906108c 4875{
d01949b6 4876 struct remote_state *rs = get_remote_state ();
a6f3e723 4877
c906108c 4878 if (name == 0)
8a3fe4f8 4879 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4880 "serial device is attached to the remote system\n"
8a3fe4f8 4881 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4882
23860348 4883 /* See FIXME above. */
c6ebd6cf 4884 if (!target_async_permitted)
92d1e331 4885 wait_forever_enabled_p = 1;
6426a772 4886
2d717e4f 4887 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4888 Ask this question first, before target_preopen has a chance to kill
4889 anything. */
5d93a237 4890 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4891 {
78a095c3
JK
4892 if (from_tty
4893 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4894 error (_("Still connected."));
4895 }
4896
78a095c3 4897 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4898 target_preopen (from_tty);
4899
89be2091 4900 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4901 xfree (rs->last_pass_packet);
4902 rs->last_pass_packet = NULL;
89be2091 4903
9b224c5e
PA
4904 /* Make sure we send the program signals list the next time we
4905 resume. */
5e4a05c4
TT
4906 xfree (rs->last_program_signals_packet);
4907 rs->last_program_signals_packet = NULL;
9b224c5e 4908
ad9a8f3f 4909 remote_fileio_reset ();
1dd41f16
NS
4910 reopen_exec_file ();
4911 reread_symbols ();
4912
5d93a237
TT
4913 rs->remote_desc = remote_serial_open (name);
4914 if (!rs->remote_desc)
c906108c
SS
4915 perror_with_name (name);
4916
4917 if (baud_rate != -1)
4918 {
5d93a237 4919 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4920 {
9b74d5d3
KB
4921 /* The requested speed could not be set. Error out to
4922 top level after closing remote_desc. Take care to
4923 set remote_desc to NULL to avoid closing remote_desc
4924 more than once. */
5d93a237
TT
4925 serial_close (rs->remote_desc);
4926 rs->remote_desc = NULL;
c906108c
SS
4927 perror_with_name (name);
4928 }
4929 }
4930
236af5e3 4931 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4932 serial_raw (rs->remote_desc);
c906108c
SS
4933
4934 /* If there is something sitting in the buffer we might take it as a
4935 response to a command, which would be bad. */
5d93a237 4936 serial_flush_input (rs->remote_desc);
c906108c
SS
4937
4938 if (from_tty)
4939 {
4940 puts_filtered ("Remote debugging using ");
4941 puts_filtered (name);
4942 puts_filtered ("\n");
4943 }
23860348 4944 push_target (target); /* Switch to using remote target now. */
c906108c 4945
74531fed
PA
4946 /* Register extra event sources in the event loop. */
4947 remote_async_inferior_event_token
4948 = create_async_event_handler (remote_async_inferior_event_handler,
4949 NULL);
5965e028 4950 rs->notif_state = remote_notif_state_allocate ();
74531fed 4951
be2a5f71
DJ
4952 /* Reset the target state; these things will be queried either by
4953 remote_query_supported or as they are needed. */
ca4f7f8b 4954 reset_all_packet_configs_support ();
74531fed 4955 rs->cached_wait_status = 0;
be2a5f71 4956 rs->explicit_packet_size = 0;
a6f3e723 4957 rs->noack_mode = 0;
82f73884 4958 rs->extended = extended_p;
e24a49d8 4959 rs->waiting_for_stop_reply = 0;
3a29589a 4960 rs->ctrlc_pending_p = 0;
802188a7 4961
47f8a51d
TT
4962 rs->general_thread = not_sent_ptid;
4963 rs->continue_thread = not_sent_ptid;
262e1174 4964 rs->remote_traceframe_number = -1;
c906108c 4965
9d1f7ab2 4966 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4967 rs->use_threadinfo_query = 1;
4968 rs->use_threadextra_query = 1;
9d1f7ab2 4969
80152258
PA
4970 readahead_cache_invalidate ();
4971
c6ebd6cf 4972 if (target_async_permitted)
92d1e331 4973 {
23860348 4974 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4975 remote_async_terminal_ours_p = 1;
4976
4977 /* FIXME: cagney/1999-09-23: During the initial connection it is
4978 assumed that the target is already ready and able to respond to
0df8b418 4979 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4980 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4981 around this. Eventually a mechanism that allows
92d1e331 4982 wait_for_inferior() to expect/get timeouts will be
23860348 4983 implemented. */
92d1e331
DJ
4984 wait_forever_enabled_p = 0;
4985 }
4986
23860348 4987 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4988 no_shared_libraries (NULL, 0);
f78f6cf1 4989
74531fed
PA
4990 /* Start afresh. */
4991 init_thread_list ();
4992
36918e70 4993 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4994 target (we'd otherwise be in an inconsistent state) and then
4995 propogate the error on up the exception chain. This ensures that
4996 the caller doesn't stumble along blindly assuming that the
4997 function succeeded. The CLI doesn't have this problem but other
4998 UI's, such as MI do.
36918e70
AC
4999
5000 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5001 this function should return an error indication letting the
ce2826aa 5002 caller restore the previous state. Unfortunately the command
36918e70
AC
5003 ``target remote'' is directly wired to this function making that
5004 impossible. On a positive note, the CLI side of this problem has
5005 been fixed - the function set_cmd_context() makes it possible for
5006 all the ``target ....'' commands to share a common callback
5007 function. See cli-dump.c. */
109c3e39 5008 {
2d717e4f 5009
492d29ea 5010 TRY
04bd08de
TT
5011 {
5012 remote_start_remote (from_tty, target, extended_p);
5013 }
492d29ea 5014 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5015 {
c8d104ad
PA
5016 /* Pop the partially set up target - unless something else did
5017 already before throwing the exception. */
5d93a237 5018 if (rs->remote_desc != NULL)
78a095c3 5019 remote_unpush_target ();
c6ebd6cf 5020 if (target_async_permitted)
109c3e39
AC
5021 wait_forever_enabled_p = 1;
5022 throw_exception (ex);
5023 }
492d29ea 5024 END_CATCH
109c3e39 5025 }
c906108c 5026
f4abbc16
MM
5027 remote_btrace_reset ();
5028
c6ebd6cf 5029 if (target_async_permitted)
92d1e331 5030 wait_forever_enabled_p = 1;
43ff13b4
JM
5031}
5032
de0d863e
DB
5033/* Detach the specified process. */
5034
5035static void
5036remote_detach_pid (int pid)
5037{
5038 struct remote_state *rs = get_remote_state ();
5039
5040 if (remote_multi_process_p (rs))
5041 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5042 else
5043 strcpy (rs->buf, "D");
5044
5045 putpkt (rs->buf);
5046 getpkt (&rs->buf, &rs->buf_size, 0);
5047
5048 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5049 ;
5050 else if (rs->buf[0] == '\0')
5051 error (_("Remote doesn't know how to detach"));
5052 else
5053 error (_("Can't detach process."));
5054}
5055
5056/* This detaches a program to which we previously attached, using
5057 inferior_ptid to identify the process. After this is done, GDB
5058 can be used to debug some other program. We better not have left
5059 any breakpoints in the target program or it'll die when it hits
5060 one. */
c906108c
SS
5061
5062static void
de0d863e 5063remote_detach_1 (const char *args, int from_tty)
c906108c 5064{
82f73884 5065 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5066 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5067 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5068 int is_fork_parent;
c906108c
SS
5069
5070 if (args)
8a3fe4f8 5071 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 5072
2d717e4f
DJ
5073 if (!target_has_execution)
5074 error (_("No process to detach from."));
5075
7cee1e54
PA
5076 if (from_tty)
5077 {
5078 char *exec_file = get_exec_file (0);
5079 if (exec_file == NULL)
5080 exec_file = "";
5081 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
5082 target_pid_to_str (pid_to_ptid (pid)));
5083 gdb_flush (gdb_stdout);
5084 }
5085
c906108c 5086 /* Tell the remote target to detach. */
de0d863e 5087 remote_detach_pid (pid);
82f73884 5088
8020350c
DB
5089 /* Exit only if this is the only active inferior. */
5090 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5091 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5092
de0d863e
DB
5093 /* Check to see if we are detaching a fork parent. Note that if we
5094 are detaching a fork child, tp == NULL. */
5095 is_fork_parent = (tp != NULL
5096 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5097
5098 /* If doing detach-on-fork, we don't mourn, because that will delete
5099 breakpoints that should be available for the followed inferior. */
5100 if (!is_fork_parent)
5101 target_mourn_inferior ();
5102 else
5103 {
5104 inferior_ptid = null_ptid;
5105 detach_inferior (pid);
5106 }
2d717e4f
DJ
5107}
5108
5109static void
52554a0e 5110remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5111{
de0d863e 5112 remote_detach_1 (args, from_tty);
2d717e4f
DJ
5113}
5114
5115static void
52554a0e 5116extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5117{
de0d863e
DB
5118 remote_detach_1 (args, from_tty);
5119}
5120
5121/* Target follow-fork function for remote targets. On entry, and
5122 at return, the current inferior is the fork parent.
5123
5124 Note that although this is currently only used for extended-remote,
5125 it is named remote_follow_fork in anticipation of using it for the
5126 remote target as well. */
5127
5128static int
5129remote_follow_fork (struct target_ops *ops, int follow_child,
5130 int detach_fork)
5131{
5132 struct remote_state *rs = get_remote_state ();
c269dbdb 5133 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5134
c269dbdb
DB
5135 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5136 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5137 {
5138 /* When following the parent and detaching the child, we detach
5139 the child here. For the case of following the child and
5140 detaching the parent, the detach is done in the target-
5141 independent follow fork code in infrun.c. We can't use
5142 target_detach when detaching an unfollowed child because
5143 the client side doesn't know anything about the child. */
5144 if (detach_fork && !follow_child)
5145 {
5146 /* Detach the fork child. */
5147 ptid_t child_ptid;
5148 pid_t child_pid;
5149
5150 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5151 child_pid = ptid_get_pid (child_ptid);
5152
5153 remote_detach_pid (child_pid);
5154 detach_inferior (child_pid);
5155 }
5156 }
5157 return 0;
c906108c
SS
5158}
5159
94585166
DB
5160/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5161 in the program space of the new inferior. On entry and at return the
5162 current inferior is the exec'ing inferior. INF is the new exec'd
5163 inferior, which may be the same as the exec'ing inferior unless
5164 follow-exec-mode is "new". */
5165
5166static void
5167remote_follow_exec (struct target_ops *ops,
5168 struct inferior *inf, char *execd_pathname)
5169{
5170 /* We know that this is a target file name, so if it has the "target:"
5171 prefix we strip it off before saving it in the program space. */
5172 if (is_target_filename (execd_pathname))
5173 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5174
5175 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5176}
5177
6ad8ae5c
DJ
5178/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5179
43ff13b4 5180static void
fee354ee 5181remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5182{
43ff13b4 5183 if (args)
2d717e4f 5184 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5185
8020350c
DB
5186 /* Make sure we unpush even the extended remote targets. Calling
5187 target_mourn_inferior won't unpush, and remote_mourn won't
5188 unpush if there is more than one inferior left. */
5189 unpush_target (target);
5190 generic_mourn_inferior ();
2d717e4f 5191
43ff13b4
JM
5192 if (from_tty)
5193 puts_filtered ("Ending remote debugging.\n");
5194}
5195
2d717e4f
DJ
5196/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5197 be chatty about it. */
5198
5199static void
20f796c9
GB
5200extended_remote_attach (struct target_ops *target, const char *args,
5201 int from_tty)
2d717e4f
DJ
5202{
5203 struct remote_state *rs = get_remote_state ();
be86555c 5204 int pid;
96ef3384 5205 char *wait_status = NULL;
2d717e4f 5206
74164c56 5207 pid = parse_pid_to_attach (args);
2d717e4f 5208
74164c56
JK
5209 /* Remote PID can be freely equal to getpid, do not check it here the same
5210 way as in other targets. */
2d717e4f 5211
4082afcc 5212 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5213 error (_("This target does not support attaching to a process"));
5214
7cee1e54
PA
5215 if (from_tty)
5216 {
5217 char *exec_file = get_exec_file (0);
5218
5219 if (exec_file)
5220 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5221 target_pid_to_str (pid_to_ptid (pid)));
5222 else
5223 printf_unfiltered (_("Attaching to %s\n"),
5224 target_pid_to_str (pid_to_ptid (pid)));
5225
5226 gdb_flush (gdb_stdout);
5227 }
5228
bba74b36 5229 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5230 putpkt (rs->buf);
5231 getpkt (&rs->buf, &rs->buf_size, 0);
5232
4082afcc
PA
5233 switch (packet_ok (rs->buf,
5234 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5235 {
4082afcc 5236 case PACKET_OK:
6efcd9a8 5237 if (!target_is_non_stop_p ())
74531fed
PA
5238 {
5239 /* Save the reply for later. */
224c3ddb 5240 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5241 strcpy (wait_status, rs->buf);
5242 }
5243 else if (strcmp (rs->buf, "OK") != 0)
5244 error (_("Attaching to %s failed with: %s"),
5245 target_pid_to_str (pid_to_ptid (pid)),
5246 rs->buf);
4082afcc
PA
5247 break;
5248 case PACKET_UNKNOWN:
5249 error (_("This target does not support attaching to a process"));
5250 default:
5251 error (_("Attaching to %s failed"),
5252 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5253 }
2d717e4f 5254
1b6e6f5c 5255 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5256
2d717e4f 5257 inferior_ptid = pid_to_ptid (pid);
79d7f229 5258
6efcd9a8 5259 if (target_is_non_stop_p ())
bad34192
PA
5260 {
5261 struct thread_info *thread;
79d7f229 5262
bad34192 5263 /* Get list of threads. */
e8032dde 5264 remote_update_thread_list (target);
82f73884 5265
bad34192
PA
5266 thread = first_thread_of_process (pid);
5267 if (thread)
5268 inferior_ptid = thread->ptid;
5269 else
5270 inferior_ptid = pid_to_ptid (pid);
5271
5272 /* Invalidate our notion of the remote current thread. */
47f8a51d 5273 record_currthread (rs, minus_one_ptid);
bad34192 5274 }
74531fed 5275 else
bad34192
PA
5276 {
5277 /* Now, if we have thread information, update inferior_ptid. */
5278 inferior_ptid = remote_current_thread (inferior_ptid);
5279
5280 /* Add the main thread to the thread list. */
5281 add_thread_silent (inferior_ptid);
5282 }
c0a2216e 5283
96ef3384
UW
5284 /* Next, if the target can specify a description, read it. We do
5285 this before anything involving memory or registers. */
5286 target_find_description ();
5287
6efcd9a8 5288 if (!target_is_non_stop_p ())
74531fed
PA
5289 {
5290 /* Use the previously fetched status. */
5291 gdb_assert (wait_status != NULL);
5292
5293 if (target_can_async_p ())
5294 {
722247f1
YQ
5295 struct notif_event *reply
5296 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5297
722247f1 5298 push_stop_reply ((struct stop_reply *) reply);
74531fed 5299
6a3753b3 5300 target_async (1);
74531fed
PA
5301 }
5302 else
5303 {
5304 gdb_assert (wait_status != NULL);
5305 strcpy (rs->buf, wait_status);
5306 rs->cached_wait_status = 1;
5307 }
5308 }
5309 else
5310 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5311}
5312
b9c1d481
AS
5313/* Implementation of the to_post_attach method. */
5314
5315static void
5316extended_remote_post_attach (struct target_ops *ops, int pid)
5317{
6efcd9a8
PA
5318 /* Get text, data & bss offsets. */
5319 get_offsets ();
5320
b9c1d481
AS
5321 /* In certain cases GDB might not have had the chance to start
5322 symbol lookup up until now. This could happen if the debugged
5323 binary is not using shared libraries, the vsyscall page is not
5324 present (on Linux) and the binary itself hadn't changed since the
5325 debugging process was started. */
5326 if (symfile_objfile != NULL)
5327 remote_check_symbols();
5328}
5329
c906108c 5330\f
506fb367
DJ
5331/* Check for the availability of vCont. This function should also check
5332 the response. */
c906108c
SS
5333
5334static void
6d820c5c 5335remote_vcont_probe (struct remote_state *rs)
c906108c 5336{
2e9f7625 5337 char *buf;
6d820c5c 5338
2e9f7625
DJ
5339 strcpy (rs->buf, "vCont?");
5340 putpkt (rs->buf);
6d820c5c 5341 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5342 buf = rs->buf;
c906108c 5343
506fb367 5344 /* Make sure that the features we assume are supported. */
61012eef 5345 if (startswith (buf, "vCont"))
506fb367
DJ
5346 {
5347 char *p = &buf[5];
750ce8d1 5348 int support_c, support_C;
506fb367 5349
750ce8d1
YQ
5350 rs->supports_vCont.s = 0;
5351 rs->supports_vCont.S = 0;
506fb367
DJ
5352 support_c = 0;
5353 support_C = 0;
d458bd84 5354 rs->supports_vCont.t = 0;
c1e36e3e 5355 rs->supports_vCont.r = 0;
506fb367
DJ
5356 while (p && *p == ';')
5357 {
5358 p++;
5359 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5360 rs->supports_vCont.s = 1;
506fb367 5361 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5362 rs->supports_vCont.S = 1;
506fb367
DJ
5363 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5364 support_c = 1;
5365 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5366 support_C = 1;
74531fed 5367 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5368 rs->supports_vCont.t = 1;
c1e36e3e
PA
5369 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5370 rs->supports_vCont.r = 1;
506fb367
DJ
5371
5372 p = strchr (p, ';');
5373 }
c906108c 5374
750ce8d1
YQ
5375 /* If c, and C are not all supported, we can't use vCont. Clearing
5376 BUF will make packet_ok disable the packet. */
5377 if (!support_c || !support_C)
506fb367
DJ
5378 buf[0] = 0;
5379 }
c906108c 5380
444abaca 5381 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5382}
c906108c 5383
0d8f58ca
PA
5384/* Helper function for building "vCont" resumptions. Write a
5385 resumption to P. ENDP points to one-passed-the-end of the buffer
5386 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5387 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5388 resumed thread should be single-stepped and/or signalled. If PTID
5389 equals minus_one_ptid, then all threads are resumed; if PTID
5390 represents a process, then all threads of the process are resumed;
5391 the thread to be stepped and/or signalled is given in the global
5392 INFERIOR_PTID. */
5393
5394static char *
5395append_resumption (char *p, char *endp,
2ea28649 5396 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5397{
5398 struct remote_state *rs = get_remote_state ();
5399
a493e3e2 5400 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5401 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5402 else if (step
5403 /* GDB is willing to range step. */
5404 && use_range_stepping
5405 /* Target supports range stepping. */
5406 && rs->supports_vCont.r
5407 /* We don't currently support range stepping multiple
5408 threads with a wildcard (though the protocol allows it,
5409 so stubs shouldn't make an active effort to forbid
5410 it). */
5411 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5412 {
5413 struct thread_info *tp;
5414
5415 if (ptid_equal (ptid, minus_one_ptid))
5416 {
5417 /* If we don't know about the target thread's tid, then
5418 we're resuming magic_null_ptid (see caller). */
5419 tp = find_thread_ptid (magic_null_ptid);
5420 }
5421 else
5422 tp = find_thread_ptid (ptid);
5423 gdb_assert (tp != NULL);
5424
5425 if (tp->control.may_range_step)
5426 {
5427 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5428
5429 p += xsnprintf (p, endp - p, ";r%s,%s",
5430 phex_nz (tp->control.step_range_start,
5431 addr_size),
5432 phex_nz (tp->control.step_range_end,
5433 addr_size));
5434 }
5435 else
5436 p += xsnprintf (p, endp - p, ";s");
5437 }
0d8f58ca
PA
5438 else if (step)
5439 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5440 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5441 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5442 else
5443 p += xsnprintf (p, endp - p, ";c");
5444
5445 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5446 {
5447 ptid_t nptid;
5448
5449 /* All (-1) threads of process. */
ba348170 5450 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5451
5452 p += xsnprintf (p, endp - p, ":");
5453 p = write_ptid (p, endp, nptid);
5454 }
5455 else if (!ptid_equal (ptid, minus_one_ptid))
5456 {
5457 p += xsnprintf (p, endp - p, ":");
5458 p = write_ptid (p, endp, ptid);
5459 }
5460
5461 return p;
5462}
5463
799a2abe
PA
5464/* Clear the thread's private info on resume. */
5465
5466static void
5467resume_clear_thread_private_info (struct thread_info *thread)
5468{
5469 if (thread->priv != NULL)
5470 {
5471 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5472 thread->priv->watch_data_address = 0;
5473 }
5474}
5475
e5ef252a
PA
5476/* Append a vCont continue-with-signal action for threads that have a
5477 non-zero stop signal. */
5478
5479static char *
5480append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5481{
5482 struct thread_info *thread;
5483
034f788c 5484 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5485 if (ptid_match (thread->ptid, ptid)
5486 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5487 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5488 {
5489 p = append_resumption (p, endp, thread->ptid,
5490 0, thread->suspend.stop_signal);
5491 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5492 resume_clear_thread_private_info (thread);
e5ef252a
PA
5493 }
5494
5495 return p;
5496}
5497
506fb367
DJ
5498/* Resume the remote inferior by using a "vCont" packet. The thread
5499 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5500 resumed thread should be single-stepped and/or signalled. If PTID
5501 equals minus_one_ptid, then all threads are resumed; the thread to
5502 be stepped and/or signalled is given in the global INFERIOR_PTID.
5503 This function returns non-zero iff it resumes the inferior.
44eaed12 5504
506fb367
DJ
5505 This function issues a strict subset of all possible vCont commands at the
5506 moment. */
44eaed12 5507
506fb367 5508static int
2ea28649 5509remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5510{
5511 struct remote_state *rs = get_remote_state ();
82f73884
PA
5512 char *p;
5513 char *endp;
44eaed12 5514
4082afcc 5515 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5516 remote_vcont_probe (rs);
44eaed12 5517
4082afcc 5518 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5519 return 0;
44eaed12 5520
82f73884
PA
5521 p = rs->buf;
5522 endp = rs->buf + get_remote_packet_size ();
5523
506fb367
DJ
5524 /* If we could generate a wider range of packets, we'd have to worry
5525 about overflowing BUF. Should there be a generic
5526 "multi-part-packet" packet? */
5527
0d8f58ca
PA
5528 p += xsnprintf (p, endp - p, "vCont");
5529
79d7f229 5530 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5531 {
79d7f229
PA
5532 /* MAGIC_NULL_PTID means that we don't have any active threads,
5533 so we don't have any TID numbers the inferior will
5534 understand. Make sure to only send forms that do not specify
5535 a TID. */
a9cbf802 5536 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5537 }
0d8f58ca 5538 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5539 {
0d8f58ca
PA
5540 /* Resume all threads (of all processes, or of a single
5541 process), with preference for INFERIOR_PTID. This assumes
5542 inferior_ptid belongs to the set of all threads we are about
5543 to resume. */
a493e3e2 5544 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5545 {
0d8f58ca
PA
5546 /* Step inferior_ptid, with or without signal. */
5547 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5548 }
0d8f58ca 5549
e5ef252a
PA
5550 /* Also pass down any pending signaled resumption for other
5551 threads not the current. */
5552 p = append_pending_thread_resumptions (p, endp, ptid);
5553
0d8f58ca 5554 /* And continue others without a signal. */
a493e3e2 5555 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5556 }
5557 else
506fb367
DJ
5558 {
5559 /* Scheduler locking; resume only PTID. */
a9cbf802 5560 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5561 }
c906108c 5562
82f73884
PA
5563 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5564 putpkt (rs->buf);
506fb367 5565
6efcd9a8 5566 if (target_is_non_stop_p ())
74531fed
PA
5567 {
5568 /* In non-stop, the stub replies to vCont with "OK". The stop
5569 reply will be reported asynchronously by means of a `%Stop'
5570 notification. */
5571 getpkt (&rs->buf, &rs->buf_size, 0);
5572 if (strcmp (rs->buf, "OK") != 0)
5573 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5574 }
5575
506fb367 5576 return 1;
c906108c 5577}
43ff13b4 5578
506fb367
DJ
5579/* Tell the remote machine to resume. */
5580
43ff13b4 5581static void
28439f5e 5582remote_resume (struct target_ops *ops,
2ea28649 5583 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5584{
d01949b6 5585 struct remote_state *rs = get_remote_state ();
2e9f7625 5586 char *buf;
799a2abe 5587 struct thread_info *thread;
43ff13b4 5588
722247f1
YQ
5589 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5590 (explained in remote-notif.c:handle_notification) so
5591 remote_notif_process is not called. We need find a place where
5592 it is safe to start a 'vNotif' sequence. It is good to do it
5593 before resuming inferior, because inferior was stopped and no RSP
5594 traffic at that moment. */
6efcd9a8 5595 if (!target_is_non_stop_p ())
5965e028 5596 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5597
b73be471 5598 rs->last_sent_signal = siggnal;
280ceea3 5599 rs->last_sent_step = step;
43ff13b4 5600
506fb367 5601 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5602 /* No reverse support (yet) for vCont. */
5603 if (execution_direction != EXEC_REVERSE)
5604 if (remote_vcont_resume (ptid, step, siggnal))
5605 goto done;
506fb367 5606
79d7f229
PA
5607 /* All other supported resume packets do use Hc, so set the continue
5608 thread. */
5609 if (ptid_equal (ptid, minus_one_ptid))
5610 set_continue_thread (any_thread_ptid);
506fb367 5611 else
79d7f229 5612 set_continue_thread (ptid);
506fb367 5613
799a2abe
PA
5614 ALL_NON_EXITED_THREADS (thread)
5615 resume_clear_thread_private_info (thread);
5616
2e9f7625 5617 buf = rs->buf;
b2175913
MS
5618 if (execution_direction == EXEC_REVERSE)
5619 {
5620 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5621 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5622 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5623 siggnal);
40ab02ce 5624
4082afcc 5625 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5626 error (_("Remote reverse-step not supported."));
4082afcc 5627 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5628 error (_("Remote reverse-continue not supported."));
40ab02ce 5629
b2175913
MS
5630 strcpy (buf, step ? "bs" : "bc");
5631 }
a493e3e2 5632 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5633 {
5634 buf[0] = step ? 'S' : 'C';
c5aa993b 5635 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5636 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5637 buf[3] = '\0';
5638 }
5639 else
c5aa993b 5640 strcpy (buf, step ? "s" : "c");
506fb367 5641
44eaed12 5642 putpkt (buf);
43ff13b4 5643
75c99385 5644 done:
2acceee2 5645 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5646 with the event loop. NOTE: this is the one place where all the
5647 execution commands end up. We could alternatively do this in each
23860348 5648 of the execution commands in infcmd.c. */
2acceee2
JM
5649 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5650 into infcmd.c in order to allow inferior function calls to work
23860348 5651 NOT asynchronously. */
362646f5 5652 if (target_can_async_p ())
6a3753b3 5653 target_async (1);
e24a49d8
PA
5654
5655 /* We've just told the target to resume. The remote server will
5656 wait for the inferior to stop, and then send a stop reply. In
5657 the mean time, we can't start another command/query ourselves
74531fed
PA
5658 because the stub wouldn't be ready to process it. This applies
5659 only to the base all-stop protocol, however. In non-stop (which
5660 only supports vCont), the stub replies with an "OK", and is
5661 immediate able to process further serial input. */
6efcd9a8 5662 if (!target_is_non_stop_p ())
74531fed 5663 rs->waiting_for_stop_reply = 1;
43ff13b4 5664}
c906108c 5665\f
43ff13b4
JM
5666
5667/* Set up the signal handler for SIGINT, while the target is
23860348 5668 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5669static void
934b9bac 5670async_initialize_sigint_signal_handler (void)
43ff13b4 5671{
934b9bac 5672 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5673}
5674
23860348 5675/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5676static void
934b9bac 5677async_handle_remote_sigint (int sig)
43ff13b4 5678{
934b9bac 5679 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5680 /* Note we need to go through gdb_call_async_signal_handler in order
5681 to wake up the event loop on Windows. */
5682 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5683}
5684
5685/* Signal handler for SIGINT, installed after SIGINT has already been
5686 sent once. It will take effect the second time that the user sends
23860348 5687 a ^C. */
43ff13b4 5688static void
934b9bac 5689async_handle_remote_sigint_twice (int sig)
43ff13b4 5690{
934b9bac 5691 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5692 /* See note in async_handle_remote_sigint. */
5693 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5694}
5695
abc56d60
PA
5696/* Implementation of to_check_pending_interrupt. */
5697
5698static void
5699remote_check_pending_interrupt (struct target_ops *self)
5700{
5701 struct async_signal_handler *token = async_sigint_remote_twice_token;
5702
5703 if (async_signal_handler_is_marked (token))
5704 {
5705 clear_async_signal_handler (token);
5706 call_async_signal_handler (token);
5707 }
5708}
5709
6426a772 5710/* Perform the real interruption of the target execution, in response
23860348 5711 to a ^C. */
c5aa993b 5712static void
fba45db2 5713async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5714{
5715 if (remote_debug)
248fd3bf 5716 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5717
de979965 5718 target_interrupt (inferior_ptid);
43ff13b4
JM
5719}
5720
0df8b418 5721/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5722 up on the target alltogether. */
47e1ce27 5723static void
fba45db2 5724async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5725{
2df3850c 5726 if (remote_debug)
248fd3bf 5727 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5728
5729 interrupt_query ();
43ff13b4
JM
5730}
5731
5732/* Reinstall the usual SIGINT handlers, after the target has
23860348 5733 stopped. */
6426a772 5734static void
934b9bac 5735async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5736{
5737 signal (SIGINT, handle_sigint);
43ff13b4
JM
5738}
5739
c906108c
SS
5740/* Send ^C to target to halt it. Target will respond, and send us a
5741 packet. */
507f3c78 5742static void (*ofunc) (int);
c906108c 5743
bfedc46a
PA
5744/* The command line interface's interrupt routine. This function is installed
5745 as a signal handler for SIGINT. The first time a user requests an
5746 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5747 response from the target (it didn't stop when the user requested it),
23860348 5748 we ask the user if he'd like to detach from the target. */
bfedc46a 5749
c906108c 5750static void
934b9bac 5751sync_remote_interrupt (int signo)
c906108c 5752{
23860348 5753 /* If this doesn't work, try more severe steps. */
934b9bac 5754 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5755
934b9bac 5756 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5757}
5758
5759/* The user typed ^C twice. */
5760
5761static void
934b9bac 5762sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5763{
5764 signal (signo, ofunc);
934b9bac
JK
5765 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5766 signal (signo, sync_remote_interrupt);
c906108c 5767}
7a292a7a 5768
74531fed
PA
5769/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5770 thread, all threads of a remote process, or all threads of all
5771 processes. */
5772
5773static void
5774remote_stop_ns (ptid_t ptid)
5775{
5776 struct remote_state *rs = get_remote_state ();
5777 char *p = rs->buf;
5778 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5779
4082afcc 5780 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5781 remote_vcont_probe (rs);
5782
d458bd84 5783 if (!rs->supports_vCont.t)
74531fed
PA
5784 error (_("Remote server does not support stopping threads"));
5785
f91d3df5
PA
5786 if (ptid_equal (ptid, minus_one_ptid)
5787 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5788 p += xsnprintf (p, endp - p, "vCont;t");
5789 else
5790 {
5791 ptid_t nptid;
5792
74531fed
PA
5793 p += xsnprintf (p, endp - p, "vCont;t:");
5794
5795 if (ptid_is_pid (ptid))
5796 /* All (-1) threads of process. */
ba348170 5797 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5798 else
5799 {
5800 /* Small optimization: if we already have a stop reply for
5801 this thread, no use in telling the stub we want this
5802 stopped. */
5803 if (peek_stop_reply (ptid))
5804 return;
5805
5806 nptid = ptid;
5807 }
5808
a9cbf802 5809 write_ptid (p, endp, nptid);
74531fed
PA
5810 }
5811
5812 /* In non-stop, we get an immediate OK reply. The stop reply will
5813 come in asynchronously by notification. */
5814 putpkt (rs->buf);
5815 getpkt (&rs->buf, &rs->buf_size, 0);
5816 if (strcmp (rs->buf, "OK") != 0)
5817 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5818}
5819
bfedc46a
PA
5820/* All-stop version of target_interrupt. Sends a break or a ^C to
5821 interrupt the remote target. It is undefined which thread of which
5822 process reports the interrupt. */
74531fed
PA
5823
5824static void
de979965 5825remote_interrupt_as (void)
74531fed
PA
5826{
5827 struct remote_state *rs = get_remote_state ();
5828
3a29589a
DJ
5829 rs->ctrlc_pending_p = 1;
5830
74531fed
PA
5831 /* If the inferior is stopped already, but the core didn't know
5832 about it yet, just ignore the request. The cached wait status
5833 will be collected in remote_wait. */
5834 if (rs->cached_wait_status)
5835 return;
5836
9a7071a8
JB
5837 /* Send interrupt_sequence to remote target. */
5838 send_interrupt_sequence ();
74531fed
PA
5839}
5840
de979965
PA
5841/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5842 the remote target. It is undefined which thread of which process
5843 reports the interrupt. Returns true if the packet is supported by
5844 the server, false otherwise. */
5845
5846static int
5847remote_interrupt_ns (void)
5848{
5849 struct remote_state *rs = get_remote_state ();
5850 char *p = rs->buf;
5851 char *endp = rs->buf + get_remote_packet_size ();
5852
5853 xsnprintf (p, endp - p, "vCtrlC");
5854
5855 /* In non-stop, we get an immediate OK reply. The stop reply will
5856 come in asynchronously by notification. */
5857 putpkt (rs->buf);
5858 getpkt (&rs->buf, &rs->buf_size, 0);
5859
5860 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5861 {
5862 case PACKET_OK:
5863 break;
5864 case PACKET_UNKNOWN:
5865 return 0;
5866 case PACKET_ERROR:
5867 error (_("Interrupting target failed: %s"), rs->buf);
5868 }
5869
5870 return 1;
5871}
5872
bfedc46a 5873/* Implement the to_stop function for the remote targets. */
74531fed 5874
c906108c 5875static void
1eab8a48 5876remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5877{
7a292a7a 5878 if (remote_debug)
0f71a2f6 5879 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5880
6efcd9a8 5881 if (target_is_non_stop_p ())
74531fed 5882 remote_stop_ns (ptid);
c906108c 5883 else
bfedc46a
PA
5884 {
5885 /* We don't currently have a way to transparently pause the
5886 remote target in all-stop mode. Interrupt it instead. */
de979965 5887 remote_interrupt_as ();
bfedc46a
PA
5888 }
5889}
5890
5891/* Implement the to_interrupt function for the remote targets. */
5892
5893static void
5894remote_interrupt (struct target_ops *self, ptid_t ptid)
5895{
5896 if (remote_debug)
5897 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5898
de979965 5899 if (non_stop)
bfedc46a 5900 {
de979965 5901 /* In non-stop mode, we always stop with no signal instead. */
bfedc46a
PA
5902 remote_stop_ns (ptid);
5903 }
5904 else
de979965
PA
5905 {
5906 /* In all-stop, we emulate ^C-ing the remote target's
5907 terminal. */
5908 if (target_is_non_stop_p ())
5909 {
5910 if (!remote_interrupt_ns ())
5911 {
5912 /* No support for ^C-ing the remote target. Stop it
5913 (with no signal) instead. */
5914 remote_stop_ns (ptid);
5915 }
5916 }
5917 else
5918 remote_interrupt_as ();
5919 }
c906108c
SS
5920}
5921
5922/* Ask the user what to do when an interrupt is received. */
5923
5924static void
fba45db2 5925interrupt_query (void)
c906108c 5926{
abc56d60
PA
5927 struct remote_state *rs = get_remote_state ();
5928 struct cleanup *old_chain;
5929
5930 old_chain = make_cleanup_restore_target_terminal ();
c906108c
SS
5931 target_terminal_ours ();
5932
abc56d60 5933 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5934 {
abc56d60
PA
5935 if (query (_("The target is not responding to interrupt requests.\n"
5936 "Stop debugging it? ")))
74531fed 5937 {
78a095c3 5938 remote_unpush_target ();
abc56d60 5939 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5940 }
5941 }
abc56d60
PA
5942 else
5943 {
5944 if (query (_("Interrupted while waiting for the program.\n"
5945 "Give up waiting? ")))
5946 quit ();
5947 }
c906108c 5948
abc56d60 5949 do_cleanups (old_chain);
c906108c
SS
5950}
5951
6426a772
JM
5952/* Enable/disable target terminal ownership. Most targets can use
5953 terminal groups to control terminal ownership. Remote targets are
5954 different in that explicit transfer of ownership to/from GDB/target
23860348 5955 is required. */
6426a772
JM
5956
5957static void
d2f640d4 5958remote_terminal_inferior (struct target_ops *self)
6426a772 5959{
c6ebd6cf 5960 if (!target_async_permitted)
75c99385
PA
5961 /* Nothing to do. */
5962 return;
5963
d9d2d8b6
PA
5964 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5965 idempotent. The event-loop GDB talking to an asynchronous target
5966 with a synchronous command calls this function from both
5967 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5968 transfer the terminal to the target when it shouldn't this guard
5969 can go away. */
6426a772
JM
5970 if (!remote_async_terminal_ours_p)
5971 return;
5972 delete_file_handler (input_fd);
5973 remote_async_terminal_ours_p = 0;
934b9bac 5974 async_initialize_sigint_signal_handler ();
6426a772
JM
5975 /* NOTE: At this point we could also register our selves as the
5976 recipient of all input. Any characters typed could then be
23860348 5977 passed on down to the target. */
6426a772
JM
5978}
5979
5980static void
e3594fd1 5981remote_terminal_ours (struct target_ops *self)
6426a772 5982{
c6ebd6cf 5983 if (!target_async_permitted)
75c99385
PA
5984 /* Nothing to do. */
5985 return;
5986
5987 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5988 if (remote_async_terminal_ours_p)
5989 return;
934b9bac 5990 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5991 add_file_handler (input_fd, stdin_event_handler, 0);
5992 remote_async_terminal_ours_p = 1;
5993}
5994
176a6961 5995static void
917317f4 5996remote_console_output (char *msg)
c906108c
SS
5997{
5998 char *p;
5999
c5aa993b 6000 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
6001 {
6002 char tb[2];
6003 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 6004
c906108c
SS
6005 tb[0] = c;
6006 tb[1] = 0;
43ff13b4 6007 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 6008 }
00db5b94
PA
6009 gdb_flush (gdb_stdtarg);
6010}
74531fed
PA
6011
6012typedef struct cached_reg
6013{
6014 int num;
6015 gdb_byte data[MAX_REGISTER_SIZE];
6016} cached_reg_t;
6017
6018DEF_VEC_O(cached_reg_t);
6019
722247f1 6020typedef struct stop_reply
74531fed 6021{
722247f1 6022 struct notif_event base;
74531fed 6023
722247f1 6024 /* The identifier of the thread about this event */
74531fed
PA
6025 ptid_t ptid;
6026
340e3c99 6027 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6028 connection, represented by a remote_state object, is closed,
6029 all the associated stop_reply events should be released. */
6030 struct remote_state *rs;
6031
74531fed
PA
6032 struct target_waitstatus ws;
6033
15148d6a
PA
6034 /* Expedited registers. This makes remote debugging a bit more
6035 efficient for those targets that provide critical registers as
6036 part of their normal status mechanism (as another roundtrip to
6037 fetch them is avoided). */
74531fed
PA
6038 VEC(cached_reg_t) *regcache;
6039
f7e6eed5
PA
6040 enum target_stop_reason stop_reason;
6041
74531fed
PA
6042 CORE_ADDR watch_data_address;
6043
dc146f7c 6044 int core;
722247f1 6045} *stop_reply_p;
a744cf53 6046
722247f1
YQ
6047DECLARE_QUEUE_P (stop_reply_p);
6048DEFINE_QUEUE_P (stop_reply_p);
6049/* The list of already fetched and acknowledged stop events. This
6050 queue is used for notification Stop, and other notifications
6051 don't need queue for their events, because the notification events
6052 of Stop can't be consumed immediately, so that events should be
6053 queued first, and be consumed by remote_wait_{ns,as} one per
6054 time. Other notifications can consume their events immediately,
6055 so queue is not needed for them. */
6056static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
6057
6058static void
6059stop_reply_xfree (struct stop_reply *r)
6060{
f48ff2a7 6061 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6062}
6063
221e1a37
PA
6064/* Return the length of the stop reply queue. */
6065
6066static int
6067stop_reply_queue_length (void)
6068{
6069 return QUEUE_length (stop_reply_p, stop_reply_queue);
6070}
6071
722247f1
YQ
6072static void
6073remote_notif_stop_parse (struct notif_client *self, char *buf,
6074 struct notif_event *event)
6075{
6076 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6077}
6078
6079static void
6080remote_notif_stop_ack (struct notif_client *self, char *buf,
6081 struct notif_event *event)
6082{
6083 struct stop_reply *stop_reply = (struct stop_reply *) event;
6084
6085 /* acknowledge */
6086 putpkt ((char *) self->ack_command);
6087
6088 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6089 /* We got an unknown stop reply. */
6090 error (_("Unknown stop reply"));
6091
6092 push_stop_reply (stop_reply);
6093}
6094
6095static int
6096remote_notif_stop_can_get_pending_events (struct notif_client *self)
6097{
6098 /* We can't get pending events in remote_notif_process for
6099 notification stop, and we have to do this in remote_wait_ns
6100 instead. If we fetch all queued events from stub, remote stub
6101 may exit and we have no chance to process them back in
6102 remote_wait_ns. */
6103 mark_async_event_handler (remote_async_inferior_event_token);
6104 return 0;
6105}
6106
6107static void
6108stop_reply_dtr (struct notif_event *event)
6109{
6110 struct stop_reply *r = (struct stop_reply *) event;
6111
6112 VEC_free (cached_reg_t, r->regcache);
6113}
6114
6115static struct notif_event *
6116remote_notif_stop_alloc_reply (void)
6117{
8d749320
SM
6118 /* We cast to a pointer to the "base class". */
6119 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6120
6121 r->dtr = stop_reply_dtr;
6122
6123 return r;
6124}
6125
6126/* A client of notification Stop. */
6127
6128struct notif_client notif_client_stop =
6129{
6130 "Stop",
6131 "vStopped",
6132 remote_notif_stop_parse,
6133 remote_notif_stop_ack,
6134 remote_notif_stop_can_get_pending_events,
6135 remote_notif_stop_alloc_reply,
f48ff2a7 6136 REMOTE_NOTIF_STOP,
722247f1
YQ
6137};
6138
6139/* A parameter to pass data in and out. */
6140
6141struct queue_iter_param
6142{
6143 void *input;
6144 struct stop_reply *output;
6145};
6146
cbb8991c
DB
6147/* Determine if THREAD is a pending fork parent thread. ARG contains
6148 the pid of the process that owns the threads we want to check, or
6149 -1 if we want to check all threads. */
6150
6151static int
6152is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6153 ptid_t thread_ptid)
6154{
6155 if (ws->kind == TARGET_WAITKIND_FORKED
6156 || ws->kind == TARGET_WAITKIND_VFORKED)
6157 {
6158 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6159 return 1;
6160 }
6161
6162 return 0;
6163}
6164
6165/* Check whether EVENT is a fork event, and if it is, remove the
6166 fork child from the context list passed in DATA. */
6167
6168static int
6169remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6170 QUEUE_ITER (stop_reply_p) *iter,
6171 stop_reply_p event,
6172 void *data)
6173{
19ba03f4
SM
6174 struct queue_iter_param *param = (struct queue_iter_param *) data;
6175 struct threads_listing_context *context
6176 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6177
6178 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6179 || event->ws.kind == TARGET_WAITKIND_VFORKED
6180 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6181 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6182
6183 return 1;
6184}
6185
6186/* If CONTEXT contains any fork child threads that have not been
6187 reported yet, remove them from the CONTEXT list. If such a
6188 thread exists it is because we are stopped at a fork catchpoint
6189 and have not yet called follow_fork, which will set up the
6190 host-side data structures for the new process. */
6191
6192static void
6193remove_new_fork_children (struct threads_listing_context *context)
6194{
6195 struct thread_info * thread;
6196 int pid = -1;
6197 struct notif_client *notif = &notif_client_stop;
6198 struct queue_iter_param param;
6199
6200 /* For any threads stopped at a fork event, remove the corresponding
6201 fork child threads from the CONTEXT list. */
6202 ALL_NON_EXITED_THREADS (thread)
6203 {
4041ed77
DB
6204 struct target_waitstatus *ws;
6205
6206 if (thread->suspend.waitstatus_pending_p)
6207 ws = &thread->suspend.waitstatus;
6208 else
6209 ws = &thread->pending_follow;
cbb8991c
DB
6210
6211 if (is_pending_fork_parent (ws, pid, thread->ptid))
6212 {
6213 threads_listing_context_remove (ws, context);
6214 }
6215 }
6216
6217 /* Check for any pending fork events (not reported or processed yet)
6218 in process PID and remove those fork child threads from the
6219 CONTEXT list as well. */
6220 remote_notif_get_pending_events (notif);
6221 param.input = context;
6222 param.output = NULL;
6223 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6224 remove_child_of_pending_fork, &param);
6225}
6226
f48ff2a7
YQ
6227/* Remove stop replies in the queue if its pid is equal to the given
6228 inferior's pid. */
722247f1
YQ
6229
6230static int
f48ff2a7
YQ
6231remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6232 QUEUE_ITER (stop_reply_p) *iter,
6233 stop_reply_p event,
6234 void *data)
722247f1 6235{
19ba03f4
SM
6236 struct queue_iter_param *param = (struct queue_iter_param *) data;
6237 struct inferior *inf = (struct inferior *) param->input;
722247f1 6238
f48ff2a7 6239 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6240 {
6241 stop_reply_xfree (event);
6242 QUEUE_remove_elem (stop_reply_p, q, iter);
6243 }
6244
6245 return 1;
6246}
6247
f48ff2a7 6248/* Discard all pending stop replies of inferior INF. */
c906108c 6249
74531fed 6250static void
5f4cf0bb 6251discard_pending_stop_replies (struct inferior *inf)
c906108c 6252{
722247f1 6253 struct queue_iter_param param;
f48ff2a7
YQ
6254 struct stop_reply *reply;
6255 struct remote_state *rs = get_remote_state ();
6256 struct remote_notif_state *rns = rs->notif_state;
6257
6258 /* This function can be notified when an inferior exists. When the
6259 target is not remote, the notification state is NULL. */
6260 if (rs->remote_desc == NULL)
6261 return;
6262
6263 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6264
74531fed 6265 /* Discard the in-flight notification. */
f48ff2a7 6266 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6267 {
722247f1 6268 stop_reply_xfree (reply);
f48ff2a7 6269 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6270 }
c906108c 6271
722247f1
YQ
6272 param.input = inf;
6273 param.output = NULL;
74531fed
PA
6274 /* Discard the stop replies we have already pulled with
6275 vStopped. */
722247f1 6276 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6277 remove_stop_reply_for_inferior, &param);
6278}
6279
bcc75809
YQ
6280/* If its remote state is equal to the given remote state,
6281 remove EVENT from the stop reply queue. */
6282
6283static int
6284remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6285 QUEUE_ITER (stop_reply_p) *iter,
6286 stop_reply_p event,
6287 void *data)
6288{
19ba03f4
SM
6289 struct queue_iter_param *param = (struct queue_iter_param *) data;
6290 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6291
6292 if (event->rs == rs)
6293 {
6294 stop_reply_xfree (event);
6295 QUEUE_remove_elem (stop_reply_p, q, iter);
6296 }
6297
6298 return 1;
6299}
6300
6301/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6302
6303static void
bcc75809 6304discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6305{
6306 struct queue_iter_param param;
6307
bcc75809 6308 param.input = rs;
f48ff2a7
YQ
6309 param.output = NULL;
6310 /* Discard the stop replies we have already pulled with
6311 vStopped. */
6312 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6313 remove_stop_reply_of_remote_state, &param);
722247f1 6314}
74531fed 6315
722247f1
YQ
6316/* A parameter to pass data in and out. */
6317
6318static int
6319remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6320 QUEUE_ITER (stop_reply_p) *iter,
6321 stop_reply_p event,
6322 void *data)
6323{
19ba03f4
SM
6324 struct queue_iter_param *param = (struct queue_iter_param *) data;
6325 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6326
6327 if (ptid_match (event->ptid, *ptid))
6328 {
6329 param->output = event;
6330 QUEUE_remove_elem (stop_reply_p, q, iter);
6331 return 0;
c8e38a49 6332 }
722247f1
YQ
6333
6334 return 1;
74531fed 6335}
43ff13b4 6336
722247f1
YQ
6337/* Remove the first reply in 'stop_reply_queue' which matches
6338 PTID. */
2e9f7625 6339
722247f1
YQ
6340static struct stop_reply *
6341remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6342{
722247f1
YQ
6343 struct queue_iter_param param;
6344
6345 param.input = &ptid;
6346 param.output = NULL;
6347
6348 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6349 remote_notif_remove_once_on_match, &param);
6350 if (notif_debug)
6351 fprintf_unfiltered (gdb_stdlog,
6352 "notif: discard queued event: 'Stop' in %s\n",
6353 target_pid_to_str (ptid));
a744cf53 6354
722247f1 6355 return param.output;
74531fed 6356}
75c99385 6357
74531fed
PA
6358/* Look for a queued stop reply belonging to PTID. If one is found,
6359 remove it from the queue, and return it. Returns NULL if none is
6360 found. If there are still queued events left to process, tell the
6361 event loop to get back to target_wait soon. */
e24a49d8 6362
74531fed
PA
6363static struct stop_reply *
6364queued_stop_reply (ptid_t ptid)
6365{
722247f1 6366 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6367
722247f1 6368 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6369 /* There's still at least an event left. */
6370 mark_async_event_handler (remote_async_inferior_event_token);
6371
722247f1 6372 return r;
74531fed
PA
6373}
6374
6375/* Push a fully parsed stop reply in the stop reply queue. Since we
6376 know that we now have at least one queued event left to pass to the
6377 core side, tell the event loop to get back to target_wait soon. */
6378
6379static void
6380push_stop_reply (struct stop_reply *new_event)
6381{
722247f1 6382 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6383
722247f1
YQ
6384 if (notif_debug)
6385 fprintf_unfiltered (gdb_stdlog,
6386 "notif: push 'Stop' %s to queue %d\n",
6387 target_pid_to_str (new_event->ptid),
6388 QUEUE_length (stop_reply_p,
6389 stop_reply_queue));
74531fed
PA
6390
6391 mark_async_event_handler (remote_async_inferior_event_token);
6392}
6393
722247f1
YQ
6394static int
6395stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6396 QUEUE_ITER (stop_reply_p) *iter,
6397 struct stop_reply *event,
6398 void *data)
6399{
19ba03f4 6400 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6401
6402 return !(ptid_equal (*ptid, event->ptid)
6403 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6404}
6405
74531fed
PA
6406/* Returns true if we have a stop reply for PTID. */
6407
6408static int
6409peek_stop_reply (ptid_t ptid)
6410{
722247f1
YQ
6411 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6412 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6413}
6414
26d56a93
SL
6415/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6416 starting with P and ending with PEND matches PREFIX. */
6417
6418static int
6419strprefix (const char *p, const char *pend, const char *prefix)
6420{
6421 for ( ; p < pend; p++, prefix++)
6422 if (*p != *prefix)
6423 return 0;
6424 return *prefix == '\0';
6425}
6426
74531fed
PA
6427/* Parse the stop reply in BUF. Either the function succeeds, and the
6428 result is stored in EVENT, or throws an error. */
6429
6430static void
6431remote_parse_stop_reply (char *buf, struct stop_reply *event)
6432{
6433 struct remote_arch_state *rsa = get_remote_arch_state ();
6434 ULONGEST addr;
6435 char *p;
94585166 6436 int skipregs = 0;
74531fed
PA
6437
6438 event->ptid = null_ptid;
bcc75809 6439 event->rs = get_remote_state ();
74531fed
PA
6440 event->ws.kind = TARGET_WAITKIND_IGNORE;
6441 event->ws.value.integer = 0;
f7e6eed5 6442 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6443 event->regcache = NULL;
dc146f7c 6444 event->core = -1;
74531fed
PA
6445
6446 switch (buf[0])
6447 {
6448 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6449 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6450 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6451 ss = signal number
6452 n... = register number
6453 r... = register contents
6454 */
6455
6456 p = &buf[3]; /* after Txx */
6457 while (*p)
6458 {
6459 char *p1;
cea39f65 6460 int fieldsize;
43ff13b4 6461
1f10ba14
PA
6462 p1 = strchr (p, ':');
6463 if (p1 == NULL)
6464 error (_("Malformed packet(a) (missing colon): %s\n\
6465Packet: '%s'\n"),
6466 p, buf);
6467 if (p == p1)
6468 error (_("Malformed packet(a) (missing register number): %s\n\
6469Packet: '%s'\n"),
6470 p, buf);
3c3bea1c 6471
1f10ba14
PA
6472 /* Some "registers" are actually extended stop information.
6473 Note if you're adding a new entry here: GDB 7.9 and
6474 earlier assume that all register "numbers" that start
6475 with an hex digit are real register numbers. Make sure
6476 the server only sends such a packet if it knows the
6477 client understands it. */
c8e38a49 6478
26d56a93 6479 if (strprefix (p, p1, "thread"))
1f10ba14 6480 event->ptid = read_ptid (++p1, &p);
82075af2
JS
6481 else if (strprefix (p, p1, "syscall_entry"))
6482 {
6483 ULONGEST sysno;
6484
6485 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6486 p = unpack_varlen_hex (++p1, &sysno);
6487 event->ws.value.syscall_number = (int) sysno;
6488 }
6489 else if (strprefix (p, p1, "syscall_return"))
6490 {
6491 ULONGEST sysno;
6492
6493 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6494 p = unpack_varlen_hex (++p1, &sysno);
6495 event->ws.value.syscall_number = (int) sysno;
6496 }
26d56a93
SL
6497 else if (strprefix (p, p1, "watch")
6498 || strprefix (p, p1, "rwatch")
6499 || strprefix (p, p1, "awatch"))
cea39f65 6500 {
f7e6eed5 6501 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6502 p = unpack_varlen_hex (++p1, &addr);
6503 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6504 }
26d56a93 6505 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6506 {
6507 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6508
6509 /* Make sure the stub doesn't forget to indicate support
6510 with qSupported. */
6511 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6512 error (_("Unexpected swbreak stop reason"));
6513
6514 /* The value part is documented as "must be empty",
6515 though we ignore it, in case we ever decide to make
6516 use of it in a backward compatible way. */
8424cc97 6517 p = strchrnul (p1 + 1, ';');
f7e6eed5 6518 }
26d56a93 6519 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6520 {
6521 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6522
6523 /* Make sure the stub doesn't forget to indicate support
6524 with qSupported. */
6525 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6526 error (_("Unexpected hwbreak stop reason"));
6527
6528 /* See above. */
8424cc97 6529 p = strchrnul (p1 + 1, ';');
f7e6eed5 6530 }
26d56a93 6531 else if (strprefix (p, p1, "library"))
cea39f65 6532 {
1f10ba14 6533 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 6534 p = strchrnul (p1 + 1, ';');
1f10ba14 6535 }
26d56a93 6536 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6537 {
6538 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6539 /* p1 will indicate "begin" or "end", but it makes
6540 no difference for now, so ignore it. */
8424cc97 6541 p = strchrnul (p1 + 1, ';');
1f10ba14 6542 }
26d56a93 6543 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6544 {
6545 ULONGEST c;
a744cf53 6546
1f10ba14
PA
6547 p = unpack_varlen_hex (++p1, &c);
6548 event->core = c;
cea39f65 6549 }
26d56a93 6550 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6551 {
6552 event->ws.value.related_pid = read_ptid (++p1, &p);
6553 event->ws.kind = TARGET_WAITKIND_FORKED;
6554 }
26d56a93 6555 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6556 {
6557 event->ws.value.related_pid = read_ptid (++p1, &p);
6558 event->ws.kind = TARGET_WAITKIND_VFORKED;
6559 }
26d56a93 6560 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6561 {
6562 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 6563 p = strchrnul (p1 + 1, ';');
c269dbdb 6564 }
6ab24463 6565 else if (strprefix (p, p1, "exec"))
94585166
DB
6566 {
6567 ULONGEST ignored;
6568 char pathname[PATH_MAX];
6569 int pathlen;
6570
6571 /* Determine the length of the execd pathname. */
6572 p = unpack_varlen_hex (++p1, &ignored);
6573 pathlen = (p - p1) / 2;
6574
6575 /* Save the pathname for event reporting and for
6576 the next run command. */
6577 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6578 pathname[pathlen] = '\0';
6579
6580 /* This is freed during event handling. */
6581 event->ws.value.execd_pathname = xstrdup (pathname);
6582 event->ws.kind = TARGET_WAITKIND_EXECD;
6583
6584 /* Skip the registers included in this packet, since
6585 they may be for an architecture different from the
6586 one used by the original program. */
6587 skipregs = 1;
6588 }
65706a29
PA
6589 else if (strprefix (p, p1, "create"))
6590 {
6591 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 6592 p = strchrnul (p1 + 1, ';');
65706a29 6593 }
cea39f65
MS
6594 else
6595 {
1f10ba14
PA
6596 ULONGEST pnum;
6597 char *p_temp;
6598
94585166
DB
6599 if (skipregs)
6600 {
8424cc97 6601 p = strchrnul (p1 + 1, ';');
94585166
DB
6602 p++;
6603 continue;
6604 }
6605
1f10ba14
PA
6606 /* Maybe a real ``P'' register number. */
6607 p_temp = unpack_varlen_hex (p, &pnum);
6608 /* If the first invalid character is the colon, we got a
6609 register number. Otherwise, it's an unknown stop
6610 reason. */
6611 if (p_temp == p1)
6612 {
6613 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6614 cached_reg_t cached_reg;
43ff13b4 6615
1f10ba14
PA
6616 if (reg == NULL)
6617 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6618Packet: '%s'\n"),
1f10ba14 6619 hex_string (pnum), p, buf);
c8e38a49 6620
1f10ba14 6621 cached_reg.num = reg->regnum;
4100683b 6622
1f10ba14
PA
6623 p = p1 + 1;
6624 fieldsize = hex2bin (p, cached_reg.data,
6625 register_size (target_gdbarch (),
6626 reg->regnum));
6627 p += 2 * fieldsize;
6628 if (fieldsize < register_size (target_gdbarch (),
6629 reg->regnum))
6630 warning (_("Remote reply is too short: %s"), buf);
74531fed 6631
1f10ba14
PA
6632 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6633 }
6634 else
6635 {
6636 /* Not a number. Silently skip unknown optional
6637 info. */
8424cc97 6638 p = strchrnul (p1 + 1, ';');
1f10ba14 6639 }
cea39f65 6640 }
c8e38a49 6641
cea39f65
MS
6642 if (*p != ';')
6643 error (_("Remote register badly formatted: %s\nhere: %s"),
6644 buf, p);
6645 ++p;
6646 }
5b5596ff
PA
6647
6648 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6649 break;
6650
c8e38a49
PA
6651 /* fall through */
6652 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6653 {
6654 int sig;
6655
6656 event->ws.kind = TARGET_WAITKIND_STOPPED;
6657 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6658 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6659 event->ws.value.sig = (enum gdb_signal) sig;
6660 else
6661 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6662 }
c8e38a49 6663 break;
65706a29
PA
6664 case 'w': /* Thread exited. */
6665 {
6666 char *p;
6667 ULONGEST value;
6668
6669 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6670 p = unpack_varlen_hex (&buf[1], &value);
6671 event->ws.value.integer = value;
6672 if (*p != ';')
6673 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 6674 event->ptid = read_ptid (++p, NULL);
65706a29
PA
6675 break;
6676 }
c8e38a49
PA
6677 case 'W': /* Target exited. */
6678 case 'X':
6679 {
6680 char *p;
6681 int pid;
6682 ULONGEST value;
82f73884 6683
c8e38a49
PA
6684 /* GDB used to accept only 2 hex chars here. Stubs should
6685 only send more if they detect GDB supports multi-process
6686 support. */
6687 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6688
c8e38a49
PA
6689 if (buf[0] == 'W')
6690 {
6691 /* The remote process exited. */
74531fed
PA
6692 event->ws.kind = TARGET_WAITKIND_EXITED;
6693 event->ws.value.integer = value;
c8e38a49
PA
6694 }
6695 else
6696 {
6697 /* The remote process exited with a signal. */
74531fed 6698 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6699 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6700 event->ws.value.sig = (enum gdb_signal) value;
6701 else
6702 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6703 }
82f73884 6704
c8e38a49
PA
6705 /* If no process is specified, assume inferior_ptid. */
6706 pid = ptid_get_pid (inferior_ptid);
6707 if (*p == '\0')
6708 ;
6709 else if (*p == ';')
6710 {
6711 p++;
6712
0b24eb2d 6713 if (*p == '\0')
82f73884 6714 ;
61012eef 6715 else if (startswith (p, "process:"))
82f73884 6716 {
c8e38a49 6717 ULONGEST upid;
a744cf53 6718
c8e38a49
PA
6719 p += sizeof ("process:") - 1;
6720 unpack_varlen_hex (p, &upid);
6721 pid = upid;
82f73884
PA
6722 }
6723 else
6724 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6725 }
c8e38a49
PA
6726 else
6727 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6728 event->ptid = pid_to_ptid (pid);
6729 }
6730 break;
f2faf941
PA
6731 case 'N':
6732 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6733 event->ptid = minus_one_ptid;
6734 break;
74531fed
PA
6735 }
6736
6efcd9a8 6737 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
6738 error (_("No process or thread specified in stop reply: %s"), buf);
6739}
6740
722247f1
YQ
6741/* When the stub wants to tell GDB about a new notification reply, it
6742 sends a notification (%Stop, for example). Those can come it at
6743 any time, hence, we have to make sure that any pending
6744 putpkt/getpkt sequence we're making is finished, before querying
6745 the stub for more events with the corresponding ack command
6746 (vStopped, for example). E.g., if we started a vStopped sequence
6747 immediately upon receiving the notification, something like this
6748 could happen:
74531fed
PA
6749
6750 1.1) --> Hg 1
6751 1.2) <-- OK
6752 1.3) --> g
6753 1.4) <-- %Stop
6754 1.5) --> vStopped
6755 1.6) <-- (registers reply to step #1.3)
6756
6757 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6758 query.
6759
796cb314 6760 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6761 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6762 doing whatever we were doing:
6763
6764 2.1) --> Hg 1
6765 2.2) <-- OK
6766 2.3) --> g
6767 2.4) <-- %Stop
6768 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6769 2.5) <-- (registers reply to step #2.3)
6770
6771 Eventualy after step #2.5, we return to the event loop, which
6772 notices there's an event on the
6773 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6774 associated callback --- the function below. At this point, we're
6775 always safe to start a vStopped sequence. :
6776
6777 2.6) --> vStopped
6778 2.7) <-- T05 thread:2
6779 2.8) --> vStopped
6780 2.9) --> OK
6781*/
6782
722247f1
YQ
6783void
6784remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6785{
6786 struct remote_state *rs = get_remote_state ();
74531fed 6787
f48ff2a7 6788 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6789 {
722247f1
YQ
6790 if (notif_debug)
6791 fprintf_unfiltered (gdb_stdlog,
6792 "notif: process: '%s' ack pending event\n",
6793 nc->name);
74531fed 6794
722247f1 6795 /* acknowledge */
f48ff2a7
YQ
6796 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6797 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6798
6799 while (1)
6800 {
6801 getpkt (&rs->buf, &rs->buf_size, 0);
6802 if (strcmp (rs->buf, "OK") == 0)
6803 break;
6804 else
722247f1 6805 remote_notif_ack (nc, rs->buf);
74531fed
PA
6806 }
6807 }
722247f1
YQ
6808 else
6809 {
6810 if (notif_debug)
6811 fprintf_unfiltered (gdb_stdlog,
6812 "notif: process: '%s' no pending reply\n",
6813 nc->name);
6814 }
74531fed
PA
6815}
6816
74531fed
PA
6817/* Called when it is decided that STOP_REPLY holds the info of the
6818 event that is to be returned to the core. This function always
6819 destroys STOP_REPLY. */
6820
6821static ptid_t
6822process_stop_reply (struct stop_reply *stop_reply,
6823 struct target_waitstatus *status)
6824{
6825 ptid_t ptid;
6826
6827 *status = stop_reply->ws;
6828 ptid = stop_reply->ptid;
6829
6830 /* If no thread/process was reported by the stub, assume the current
6831 inferior. */
6832 if (ptid_equal (ptid, null_ptid))
6833 ptid = inferior_ptid;
6834
5f3563ea 6835 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
6836 && status->kind != TARGET_WAITKIND_SIGNALLED
6837 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 6838 {
799a2abe 6839 struct private_thread_info *remote_thr;
ee154bee 6840
5f3563ea
PA
6841 /* Expedited registers. */
6842 if (stop_reply->regcache)
6843 {
217f1f79 6844 struct regcache *regcache
f5656ead 6845 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6846 cached_reg_t *reg;
6847 int ix;
6848
6849 for (ix = 0;
6850 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6851 ix++)
217f1f79 6852 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6853 VEC_free (cached_reg_t, stop_reply->regcache);
6854 }
74531fed 6855
1941c569 6856 remote_notice_new_inferior (ptid, 0);
799a2abe
PA
6857 remote_thr = demand_private_info (ptid);
6858 remote_thr->core = stop_reply->core;
6859 remote_thr->stop_reason = stop_reply->stop_reason;
6860 remote_thr->watch_data_address = stop_reply->watch_data_address;
74531fed
PA
6861 }
6862
74531fed
PA
6863 stop_reply_xfree (stop_reply);
6864 return ptid;
6865}
6866
6867/* The non-stop mode version of target_wait. */
6868
6869static ptid_t
47608cb1 6870remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6871{
6872 struct remote_state *rs = get_remote_state ();
74531fed
PA
6873 struct stop_reply *stop_reply;
6874 int ret;
fee9eda9 6875 int is_notif = 0;
74531fed
PA
6876
6877 /* If in non-stop mode, get out of getpkt even if a
6878 notification is received. */
6879
6880 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6881 0 /* forever */, &is_notif);
74531fed
PA
6882 while (1)
6883 {
fee9eda9 6884 if (ret != -1 && !is_notif)
74531fed
PA
6885 switch (rs->buf[0])
6886 {
6887 case 'E': /* Error of some sort. */
6888 /* We're out of sync with the target now. Did it continue
6889 or not? We can't tell which thread it was in non-stop,
6890 so just ignore this. */
6891 warning (_("Remote failure reply: %s"), rs->buf);
6892 break;
6893 case 'O': /* Console output. */
6894 remote_console_output (rs->buf + 1);
6895 break;
6896 default:
6897 warning (_("Invalid remote reply: %s"), rs->buf);
6898 break;
6899 }
6900
6901 /* Acknowledge a pending stop reply that may have arrived in the
6902 mean time. */
f48ff2a7 6903 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6904 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6905
6906 /* If indeed we noticed a stop reply, we're done. */
6907 stop_reply = queued_stop_reply (ptid);
6908 if (stop_reply != NULL)
6909 return process_stop_reply (stop_reply, status);
6910
47608cb1 6911 /* Still no event. If we're just polling for an event, then
74531fed 6912 return to the event loop. */
47608cb1 6913 if (options & TARGET_WNOHANG)
74531fed
PA
6914 {
6915 status->kind = TARGET_WAITKIND_IGNORE;
6916 return minus_one_ptid;
6917 }
6918
47608cb1 6919 /* Otherwise do a blocking wait. */
74531fed 6920 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6921 1 /* forever */, &is_notif);
74531fed
PA
6922 }
6923}
6924
6925/* Wait until the remote machine stops, then return, storing status in
6926 STATUS just as `wait' would. */
6927
6928static ptid_t
47608cb1 6929remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6930{
6931 struct remote_state *rs = get_remote_state ();
74531fed 6932 ptid_t event_ptid = null_ptid;
cea39f65 6933 char *buf;
74531fed
PA
6934 struct stop_reply *stop_reply;
6935
47608cb1
PA
6936 again:
6937
74531fed
PA
6938 status->kind = TARGET_WAITKIND_IGNORE;
6939 status->value.integer = 0;
6940
6941 stop_reply = queued_stop_reply (ptid);
6942 if (stop_reply != NULL)
6943 return process_stop_reply (stop_reply, status);
6944
6945 if (rs->cached_wait_status)
6946 /* Use the cached wait status, but only once. */
6947 rs->cached_wait_status = 0;
6948 else
6949 {
6950 int ret;
722247f1 6951 int is_notif;
567420d1
PA
6952 int forever = ((options & TARGET_WNOHANG) == 0
6953 && wait_forever_enabled_p);
6954
6955 if (!rs->waiting_for_stop_reply)
6956 {
6957 status->kind = TARGET_WAITKIND_NO_RESUMED;
6958 return minus_one_ptid;
6959 }
74531fed
PA
6960
6961 if (!target_is_async_p ())
6962 {
934b9bac 6963 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6964 /* If the user hit C-c before this packet, or between packets,
6965 pretend that it was hit right here. */
522002f9 6966 if (check_quit_flag ())
74531fed 6967 {
522002f9 6968 clear_quit_flag ();
934b9bac 6969 sync_remote_interrupt (SIGINT);
74531fed
PA
6970 }
6971 }
6972
6973 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6974 _never_ wait for ever -> test on target_is_async_p().
6975 However, before we do that we need to ensure that the caller
6976 knows how to take the target into/out of async mode. */
722247f1 6977 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6978 forever, &is_notif);
722247f1 6979
5e1b953b
SDJ
6980 if (!target_is_async_p ())
6981 signal (SIGINT, ofunc);
6982
722247f1
YQ
6983 /* GDB gets a notification. Return to core as this event is
6984 not interesting. */
6985 if (ret != -1 && is_notif)
6986 return minus_one_ptid;
567420d1
PA
6987
6988 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6989 return minus_one_ptid;
74531fed
PA
6990 }
6991
6992 buf = rs->buf;
6993
3a29589a
DJ
6994 /* Assume that the target has acknowledged Ctrl-C unless we receive
6995 an 'F' or 'O' packet. */
6996 if (buf[0] != 'F' && buf[0] != 'O')
6997 rs->ctrlc_pending_p = 0;
6998
74531fed
PA
6999 switch (buf[0])
7000 {
7001 case 'E': /* Error of some sort. */
7002 /* We're out of sync with the target now. Did it continue or
7003 not? Not is more likely, so report a stop. */
29090fb6
LM
7004 rs->waiting_for_stop_reply = 0;
7005
74531fed
PA
7006 warning (_("Remote failure reply: %s"), buf);
7007 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 7008 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
7009 break;
7010 case 'F': /* File-I/O request. */
e42e5352
YQ
7011 /* GDB may access the inferior memory while handling the File-I/O
7012 request, but we don't want GDB accessing memory while waiting
7013 for a stop reply. See the comments in putpkt_binary. Set
7014 waiting_for_stop_reply to 0 temporarily. */
7015 rs->waiting_for_stop_reply = 0;
3a29589a
DJ
7016 remote_fileio_request (buf, rs->ctrlc_pending_p);
7017 rs->ctrlc_pending_p = 0;
e42e5352
YQ
7018 /* GDB handled the File-I/O request, and the target is running
7019 again. Keep waiting for events. */
7020 rs->waiting_for_stop_reply = 1;
74531fed 7021 break;
f2faf941 7022 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7023 {
29090fb6
LM
7024 struct stop_reply *stop_reply;
7025
7026 /* There is a stop reply to handle. */
7027 rs->waiting_for_stop_reply = 0;
7028
7029 stop_reply
722247f1
YQ
7030 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7031 rs->buf);
74531fed 7032
74531fed 7033 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7034 break;
7035 }
7036 case 'O': /* Console output. */
7037 remote_console_output (buf + 1);
c8e38a49
PA
7038 break;
7039 case '\0':
b73be471 7040 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7041 {
7042 /* Zero length reply means that we tried 'S' or 'C' and the
7043 remote system doesn't support it. */
7044 target_terminal_ours_for_output ();
7045 printf_filtered
7046 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7047 gdb_signal_to_name (rs->last_sent_signal));
7048 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
7049 target_terminal_inferior ();
7050
280ceea3 7051 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49 7052 putpkt ((char *) buf);
c8e38a49 7053 break;
43ff13b4 7054 }
c8e38a49
PA
7055 /* else fallthrough */
7056 default:
7057 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7058 break;
43ff13b4 7059 }
c8e38a49 7060
f2faf941
PA
7061 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7062 return minus_one_ptid;
7063 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7064 {
7065 /* Nothing interesting happened. If we're doing a non-blocking
7066 poll, we're done. Otherwise, go back to waiting. */
7067 if (options & TARGET_WNOHANG)
7068 return minus_one_ptid;
7069 else
7070 goto again;
7071 }
74531fed
PA
7072 else if (status->kind != TARGET_WAITKIND_EXITED
7073 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7074 {
7075 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7076 record_currthread (rs, event_ptid);
82f73884
PA
7077 else
7078 event_ptid = inferior_ptid;
43ff13b4 7079 }
74531fed
PA
7080 else
7081 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7082 record_currthread (rs, minus_one_ptid);
79d7f229 7083
82f73884 7084 return event_ptid;
43ff13b4
JM
7085}
7086
74531fed
PA
7087/* Wait until the remote machine stops, then return, storing status in
7088 STATUS just as `wait' would. */
7089
c8e38a49 7090static ptid_t
117de6a9 7091remote_wait (struct target_ops *ops,
47608cb1 7092 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7093{
7094 ptid_t event_ptid;
7095
6efcd9a8 7096 if (target_is_non_stop_p ())
47608cb1 7097 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7098 else
47608cb1 7099 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7100
d9d41e78 7101 if (target_is_async_p ())
c8e38a49 7102 {
74531fed
PA
7103 /* If there are are events left in the queue tell the event loop
7104 to return here. */
722247f1 7105 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7106 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7107 }
c8e38a49
PA
7108
7109 return event_ptid;
7110}
7111
74ca34ce 7112/* Fetch a single register using a 'p' packet. */
c906108c 7113
b96ec7ac 7114static int
56be3814 7115fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
7116{
7117 struct remote_state *rs = get_remote_state ();
2e9f7625 7118 char *buf, *p;
b96ec7ac
AC
7119 char regp[MAX_REGISTER_SIZE];
7120 int i;
7121
4082afcc 7122 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7123 return 0;
7124
7125 if (reg->pnum == -1)
7126 return 0;
7127
2e9f7625 7128 p = rs->buf;
fcad0fa4 7129 *p++ = 'p';
74ca34ce 7130 p += hexnumstr (p, reg->pnum);
fcad0fa4 7131 *p++ = '\0';
1f4437a4
MS
7132 putpkt (rs->buf);
7133 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7134
2e9f7625
DJ
7135 buf = rs->buf;
7136
74ca34ce
DJ
7137 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7138 {
7139 case PACKET_OK:
7140 break;
7141 case PACKET_UNKNOWN:
7142 return 0;
7143 case PACKET_ERROR:
27a9c0bf
MS
7144 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7145 gdbarch_register_name (get_regcache_arch (regcache),
7146 reg->regnum),
7147 buf);
74ca34ce 7148 }
3f9a994c
JB
7149
7150 /* If this register is unfetchable, tell the regcache. */
7151 if (buf[0] == 'x')
8480adf2 7152 {
56be3814 7153 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7154 return 1;
b96ec7ac 7155 }
b96ec7ac 7156
3f9a994c
JB
7157 /* Otherwise, parse and supply the value. */
7158 p = buf;
7159 i = 0;
7160 while (p[0] != 0)
7161 {
7162 if (p[1] == 0)
74ca34ce 7163 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7164
7165 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7166 p += 2;
7167 }
56be3814 7168 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7169 return 1;
b96ec7ac
AC
7170}
7171
74ca34ce
DJ
7172/* Fetch the registers included in the target's 'g' packet. */
7173
29709017
DJ
7174static int
7175send_g_packet (void)
c906108c 7176{
d01949b6 7177 struct remote_state *rs = get_remote_state ();
cea39f65 7178 int buf_len;
c906108c 7179
bba74b36 7180 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7181 remote_send (&rs->buf, &rs->buf_size);
c906108c 7182
29709017
DJ
7183 /* We can get out of synch in various cases. If the first character
7184 in the buffer is not a hex character, assume that has happened
7185 and try to fetch another packet to read. */
7186 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7187 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7188 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7189 && rs->buf[0] != 'x') /* New: unavailable register value. */
7190 {
7191 if (remote_debug)
7192 fprintf_unfiltered (gdb_stdlog,
7193 "Bad register packet; fetching a new packet\n");
7194 getpkt (&rs->buf, &rs->buf_size, 0);
7195 }
7196
74ca34ce
DJ
7197 buf_len = strlen (rs->buf);
7198
7199 /* Sanity check the received packet. */
7200 if (buf_len % 2 != 0)
7201 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7202
7203 return buf_len / 2;
7204}
7205
7206static void
56be3814 7207process_g_packet (struct regcache *regcache)
29709017 7208{
4a22f64d 7209 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7210 struct remote_state *rs = get_remote_state ();
7211 struct remote_arch_state *rsa = get_remote_arch_state ();
7212 int i, buf_len;
7213 char *p;
7214 char *regs;
7215
7216 buf_len = strlen (rs->buf);
7217
7218 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7219 if (buf_len > 2 * rsa->sizeof_g_packet)
7220 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7221
7222 /* Save the size of the packet sent to us by the target. It is used
7223 as a heuristic when determining the max size of packets that the
7224 target can safely receive. */
7225 if (rsa->actual_register_packet_size == 0)
7226 rsa->actual_register_packet_size = buf_len;
7227
7228 /* If this is smaller than we guessed the 'g' packet would be,
7229 update our records. A 'g' reply that doesn't include a register's
7230 value implies either that the register is not available, or that
7231 the 'p' packet must be used. */
7232 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7233 {
74ca34ce
DJ
7234 rsa->sizeof_g_packet = buf_len / 2;
7235
4a22f64d 7236 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7237 {
74ca34ce
DJ
7238 if (rsa->regs[i].pnum == -1)
7239 continue;
7240
7241 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7242 rsa->regs[i].in_g_packet = 0;
b96ec7ac 7243 else
74ca34ce 7244 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7245 }
74ca34ce 7246 }
b323314b 7247
224c3ddb 7248 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7249
7250 /* Unimplemented registers read as all bits zero. */
ea9c271d 7251 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7252
c906108c
SS
7253 /* Reply describes registers byte by byte, each byte encoded as two
7254 hex characters. Suck them all up, then supply them to the
7255 register cacheing/storage mechanism. */
7256
74ca34ce 7257 p = rs->buf;
ea9c271d 7258 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7259 {
74ca34ce
DJ
7260 if (p[0] == 0 || p[1] == 0)
7261 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7262 internal_error (__FILE__, __LINE__,
9b20d036 7263 _("unexpected end of 'g' packet reply"));
74ca34ce 7264
c906108c 7265 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7266 regs[i] = 0; /* 'x' */
c906108c
SS
7267 else
7268 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7269 p += 2;
7270 }
7271
a744cf53
MS
7272 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7273 {
7274 struct packet_reg *r = &rsa->regs[i];
7275
7276 if (r->in_g_packet)
7277 {
7278 if (r->offset * 2 >= strlen (rs->buf))
7279 /* This shouldn't happen - we adjusted in_g_packet above. */
7280 internal_error (__FILE__, __LINE__,
9b20d036 7281 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7282 else if (rs->buf[r->offset * 2] == 'x')
7283 {
7284 gdb_assert (r->offset * 2 < strlen (rs->buf));
7285 /* The register isn't available, mark it as such (at
7286 the same time setting the value to zero). */
7287 regcache_raw_supply (regcache, r->regnum, NULL);
7288 }
7289 else
7290 regcache_raw_supply (regcache, r->regnum,
7291 regs + r->offset);
7292 }
7293 }
c906108c
SS
7294}
7295
29709017 7296static void
56be3814 7297fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7298{
7299 send_g_packet ();
56be3814 7300 process_g_packet (regcache);
29709017
DJ
7301}
7302
e6e4e701
PA
7303/* Make the remote selected traceframe match GDB's selected
7304 traceframe. */
7305
7306static void
7307set_remote_traceframe (void)
7308{
7309 int newnum;
262e1174 7310 struct remote_state *rs = get_remote_state ();
e6e4e701 7311
262e1174 7312 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7313 return;
7314
7315 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7316 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7317
7318 newnum = target_trace_find (tfind_number,
7319 get_traceframe_number (), 0, 0, NULL);
7320
7321 /* Should not happen. If it does, all bets are off. */
7322 if (newnum != get_traceframe_number ())
7323 warning (_("could not set remote traceframe"));
7324}
7325
74ca34ce 7326static void
28439f5e
PA
7327remote_fetch_registers (struct target_ops *ops,
7328 struct regcache *regcache, int regnum)
74ca34ce 7329{
74ca34ce
DJ
7330 struct remote_arch_state *rsa = get_remote_arch_state ();
7331 int i;
7332
e6e4e701 7333 set_remote_traceframe ();
79d7f229 7334 set_general_thread (inferior_ptid);
74ca34ce
DJ
7335
7336 if (regnum >= 0)
7337 {
7338 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7339
74ca34ce
DJ
7340 gdb_assert (reg != NULL);
7341
7342 /* If this register might be in the 'g' packet, try that first -
7343 we are likely to read more than one register. If this is the
7344 first 'g' packet, we might be overly optimistic about its
7345 contents, so fall back to 'p'. */
7346 if (reg->in_g_packet)
7347 {
56be3814 7348 fetch_registers_using_g (regcache);
74ca34ce
DJ
7349 if (reg->in_g_packet)
7350 return;
7351 }
7352
56be3814 7353 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7354 return;
7355
7356 /* This register is not available. */
56be3814 7357 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7358
7359 return;
7360 }
7361
56be3814 7362 fetch_registers_using_g (regcache);
74ca34ce 7363
4a22f64d 7364 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7365 if (!rsa->regs[i].in_g_packet)
56be3814 7366 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7367 {
7368 /* This register is not available. */
56be3814 7369 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7370 }
7371}
7372
c906108c
SS
7373/* Prepare to store registers. Since we may send them all (using a
7374 'G' request), we have to read out the ones we don't want to change
7375 first. */
7376
c5aa993b 7377static void
f32dbf8c 7378remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7379{
ea9c271d 7380 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7381 int i;
cfd77fa1 7382 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7383
c906108c 7384 /* Make sure the entire registers array is valid. */
4082afcc 7385 switch (packet_support (PACKET_P))
5a2468f5
JM
7386 {
7387 case PACKET_DISABLE:
7388 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7389 /* Make sure all the necessary registers are cached. */
4a22f64d 7390 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7391 if (rsa->regs[i].in_g_packet)
316f2060 7392 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7393 break;
7394 case PACKET_ENABLE:
7395 break;
7396 }
7397}
7398
ad10f812 7399/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7400 packet was not recognized. */
5a2468f5
JM
7401
7402static int
1f4437a4
MS
7403store_register_using_P (const struct regcache *regcache,
7404 struct packet_reg *reg)
5a2468f5 7405{
4a22f64d 7406 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7407 struct remote_state *rs = get_remote_state ();
5a2468f5 7408 /* Try storing a single register. */
6d820c5c 7409 char *buf = rs->buf;
cfd77fa1 7410 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7411 char *p;
5a2468f5 7412
4082afcc 7413 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7414 return 0;
7415
7416 if (reg->pnum == -1)
7417 return 0;
7418
ea9c271d 7419 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7420 p = buf + strlen (buf);
56be3814 7421 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7422 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7423 putpkt (rs->buf);
7424 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7425
74ca34ce
DJ
7426 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7427 {
7428 case PACKET_OK:
7429 return 1;
7430 case PACKET_ERROR:
27a9c0bf
MS
7431 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7432 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7433 case PACKET_UNKNOWN:
7434 return 0;
7435 default:
7436 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7437 }
c906108c
SS
7438}
7439
23860348
MS
7440/* Store register REGNUM, or all registers if REGNUM == -1, from the
7441 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7442
7443static void
56be3814 7444store_registers_using_G (const struct regcache *regcache)
c906108c 7445{
d01949b6 7446 struct remote_state *rs = get_remote_state ();
ea9c271d 7447 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7448 gdb_byte *regs;
c906108c
SS
7449 char *p;
7450
193cb69f
AC
7451 /* Extract all the registers in the regcache copying them into a
7452 local buffer. */
7453 {
b323314b 7454 int i;
a744cf53 7455
224c3ddb 7456 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7457 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7458 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7459 {
ea9c271d 7460 struct packet_reg *r = &rsa->regs[i];
a744cf53 7461
b323314b 7462 if (r->in_g_packet)
56be3814 7463 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7464 }
7465 }
c906108c
SS
7466
7467 /* Command describes registers byte by byte,
7468 each byte encoded as two hex characters. */
6d820c5c 7469 p = rs->buf;
193cb69f 7470 *p++ = 'G';
74ca34ce
DJ
7471 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7472 updated. */
7473 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7474 putpkt (rs->buf);
7475 getpkt (&rs->buf, &rs->buf_size, 0);
7476 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7477 error (_("Could not write registers; remote failure reply '%s'"),
7478 rs->buf);
c906108c 7479}
74ca34ce
DJ
7480
7481/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7482 of the register cache buffer. FIXME: ignores errors. */
7483
7484static void
28439f5e
PA
7485remote_store_registers (struct target_ops *ops,
7486 struct regcache *regcache, int regnum)
74ca34ce 7487{
74ca34ce
DJ
7488 struct remote_arch_state *rsa = get_remote_arch_state ();
7489 int i;
7490
e6e4e701 7491 set_remote_traceframe ();
79d7f229 7492 set_general_thread (inferior_ptid);
74ca34ce
DJ
7493
7494 if (regnum >= 0)
7495 {
7496 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7497
74ca34ce
DJ
7498 gdb_assert (reg != NULL);
7499
7500 /* Always prefer to store registers using the 'P' packet if
7501 possible; we often change only a small number of registers.
7502 Sometimes we change a larger number; we'd need help from a
7503 higher layer to know to use 'G'. */
56be3814 7504 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7505 return;
7506
7507 /* For now, don't complain if we have no way to write the
7508 register. GDB loses track of unavailable registers too
7509 easily. Some day, this may be an error. We don't have
0df8b418 7510 any way to read the register, either... */
74ca34ce
DJ
7511 if (!reg->in_g_packet)
7512 return;
7513
56be3814 7514 store_registers_using_G (regcache);
74ca34ce
DJ
7515 return;
7516 }
7517
56be3814 7518 store_registers_using_G (regcache);
74ca34ce 7519
4a22f64d 7520 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7521 if (!rsa->regs[i].in_g_packet)
56be3814 7522 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7523 /* See above for why we do not issue an error here. */
7524 continue;
7525}
c906108c
SS
7526\f
7527
7528/* Return the number of hex digits in num. */
7529
7530static int
fba45db2 7531hexnumlen (ULONGEST num)
c906108c
SS
7532{
7533 int i;
7534
7535 for (i = 0; num != 0; i++)
7536 num >>= 4;
7537
7538 return max (i, 1);
7539}
7540
2df3850c 7541/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7542
7543static int
fba45db2 7544hexnumstr (char *buf, ULONGEST num)
c906108c 7545{
c906108c 7546 int len = hexnumlen (num);
a744cf53 7547
2df3850c
JM
7548 return hexnumnstr (buf, num, len);
7549}
7550
c906108c 7551
2df3850c 7552/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7553
2df3850c 7554static int
fba45db2 7555hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7556{
7557 int i;
7558
7559 buf[width] = '\0';
7560
7561 for (i = width - 1; i >= 0; i--)
c906108c 7562 {
c5aa993b 7563 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7564 num >>= 4;
7565 }
7566
2df3850c 7567 return width;
c906108c
SS
7568}
7569
23860348 7570/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7571
7572static CORE_ADDR
fba45db2 7573remote_address_masked (CORE_ADDR addr)
c906108c 7574{
883b9c6c 7575 unsigned int address_size = remote_address_size;
a744cf53 7576
911c95a5
UW
7577 /* If "remoteaddresssize" was not set, default to target address size. */
7578 if (!address_size)
f5656ead 7579 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7580
7581 if (address_size > 0
7582 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7583 {
7584 /* Only create a mask when that mask can safely be constructed
23860348 7585 in a ULONGEST variable. */
c906108c 7586 ULONGEST mask = 1;
a744cf53 7587
911c95a5 7588 mask = (mask << address_size) - 1;
c906108c
SS
7589 addr &= mask;
7590 }
7591 return addr;
7592}
7593
7594/* Determine whether the remote target supports binary downloading.
7595 This is accomplished by sending a no-op memory write of zero length
7596 to the target at the specified address. It does not suffice to send
23860348
MS
7597 the whole packet, since many stubs strip the eighth bit and
7598 subsequently compute a wrong checksum, which causes real havoc with
7599 remote_write_bytes.
7a292a7a 7600
96baa820 7601 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7602 clean. In cases like this, the user should clear "remote
23860348 7603 X-packet". */
96baa820 7604
c906108c 7605static void
fba45db2 7606check_binary_download (CORE_ADDR addr)
c906108c 7607{
d01949b6 7608 struct remote_state *rs = get_remote_state ();
24b06219 7609
4082afcc 7610 switch (packet_support (PACKET_X))
c906108c 7611 {
96baa820
JM
7612 case PACKET_DISABLE:
7613 break;
7614 case PACKET_ENABLE:
7615 break;
7616 case PACKET_SUPPORT_UNKNOWN:
7617 {
96baa820 7618 char *p;
802188a7 7619
2e9f7625 7620 p = rs->buf;
96baa820
JM
7621 *p++ = 'X';
7622 p += hexnumstr (p, (ULONGEST) addr);
7623 *p++ = ',';
7624 p += hexnumstr (p, (ULONGEST) 0);
7625 *p++ = ':';
7626 *p = '\0';
802188a7 7627
2e9f7625 7628 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7629 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7630
2e9f7625 7631 if (rs->buf[0] == '\0')
96baa820
JM
7632 {
7633 if (remote_debug)
7634 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7635 "binary downloading NOT "
7636 "supported by target\n");
444abaca 7637 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7638 }
7639 else
7640 {
7641 if (remote_debug)
7642 fprintf_unfiltered (gdb_stdlog,
64b9b334 7643 "binary downloading supported by target\n");
444abaca 7644 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7645 }
7646 break;
7647 }
c906108c
SS
7648 }
7649}
7650
124e13d9
SM
7651/* Helper function to resize the payload in order to try to get a good
7652 alignment. We try to write an amount of data such that the next write will
7653 start on an address aligned on REMOTE_ALIGN_WRITES. */
7654
7655static int
7656align_for_efficient_write (int todo, CORE_ADDR memaddr)
7657{
7658 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7659}
7660
c906108c
SS
7661/* Write memory data directly to the remote machine.
7662 This does not inform the data cache; the data cache uses this.
a76d924d 7663 HEADER is the starting part of the packet.
c906108c
SS
7664 MEMADDR is the address in the remote memory space.
7665 MYADDR is the address of the buffer in our space.
124e13d9
SM
7666 LEN_UNITS is the number of addressable units to write.
7667 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7668 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7669 should send data as binary ('X'), or hex-encoded ('M').
7670
7671 The function creates packet of the form
7672 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7673
124e13d9 7674 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7675
7676 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7677 are omitted.
7678
9b409511 7679 Return the transferred status, error or OK (an
124e13d9
SM
7680 'enum target_xfer_status' value). Save the number of addressable units
7681 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7682
7683 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7684 exchange between gdb and the stub could look like (?? in place of the
7685 checksum):
7686
7687 -> $m1000,4#??
7688 <- aaaabbbbccccdddd
7689
7690 -> $M1000,3:eeeeffffeeee#??
7691 <- OK
7692
7693 -> $m1000,4#??
7694 <- eeeeffffeeeedddd */
c906108c 7695
9b409511 7696static enum target_xfer_status
a76d924d 7697remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7698 const gdb_byte *myaddr, ULONGEST len_units,
7699 int unit_size, ULONGEST *xfered_len_units,
7700 char packet_format, int use_length)
c906108c 7701{
6d820c5c 7702 struct remote_state *rs = get_remote_state ();
cfd77fa1 7703 char *p;
a76d924d
DJ
7704 char *plen = NULL;
7705 int plenlen = 0;
124e13d9
SM
7706 int todo_units;
7707 int units_written;
7708 int payload_capacity_bytes;
7709 int payload_length_bytes;
a76d924d
DJ
7710
7711 if (packet_format != 'X' && packet_format != 'M')
7712 internal_error (__FILE__, __LINE__,
9b20d036 7713 _("remote_write_bytes_aux: bad packet format"));
c906108c 7714
124e13d9 7715 if (len_units == 0)
9b409511 7716 return TARGET_XFER_EOF;
b2182ed2 7717
124e13d9 7718 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7719
6d820c5c
DJ
7720 /* The packet buffer will be large enough for the payload;
7721 get_memory_packet_size ensures this. */
a76d924d 7722 rs->buf[0] = '\0';
c906108c 7723
a257b5bb 7724 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7725 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7726
124e13d9 7727 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7728 if (!use_length)
0df8b418 7729 /* The comma won't be used. */
124e13d9
SM
7730 payload_capacity_bytes += 1;
7731 payload_capacity_bytes -= strlen (header);
7732 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7733
a76d924d 7734 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7735
a76d924d
DJ
7736 strcat (rs->buf, header);
7737 p = rs->buf + strlen (header);
7738
7739 /* Compute a best guess of the number of bytes actually transfered. */
7740 if (packet_format == 'X')
c906108c 7741 {
23860348 7742 /* Best guess at number of bytes that will fit. */
124e13d9 7743 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7744 if (use_length)
124e13d9
SM
7745 payload_capacity_bytes -= hexnumlen (todo_units);
7746 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7747 }
7748 else
7749 {
124e13d9
SM
7750 /* Number of bytes that will fit. */
7751 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7752 if (use_length)
124e13d9
SM
7753 payload_capacity_bytes -= hexnumlen (todo_units);
7754 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7755 }
a76d924d 7756
124e13d9 7757 if (todo_units <= 0)
3de11b2e 7758 internal_error (__FILE__, __LINE__,
405f8e94 7759 _("minimum packet size too small to write data"));
802188a7 7760
6765f3e5
DJ
7761 /* If we already need another packet, then try to align the end
7762 of this packet to a useful boundary. */
124e13d9
SM
7763 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7764 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7765
a257b5bb 7766 /* Append "<memaddr>". */
917317f4
JM
7767 memaddr = remote_address_masked (memaddr);
7768 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7769
a76d924d
DJ
7770 if (use_length)
7771 {
7772 /* Append ",". */
7773 *p++ = ',';
802188a7 7774
124e13d9
SM
7775 /* Append the length and retain its location and size. It may need to be
7776 adjusted once the packet body has been created. */
a76d924d 7777 plen = p;
124e13d9 7778 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7779 p += plenlen;
7780 }
a257b5bb
AC
7781
7782 /* Append ":". */
917317f4
JM
7783 *p++ = ':';
7784 *p = '\0';
802188a7 7785
a257b5bb 7786 /* Append the packet body. */
a76d924d 7787 if (packet_format == 'X')
917317f4 7788 {
917317f4
JM
7789 /* Binary mode. Send target system values byte by byte, in
7790 increasing byte addresses. Only escape certain critical
7791 characters. */
124e13d9
SM
7792 payload_length_bytes =
7793 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7794 &units_written, payload_capacity_bytes);
6765f3e5 7795
124e13d9 7796 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7797 a second try to keep the end of the packet aligned. Don't do
7798 this if the packet is tiny. */
124e13d9 7799 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7800 {
124e13d9
SM
7801 int new_todo_units;
7802
7803 new_todo_units = align_for_efficient_write (units_written, memaddr);
7804
7805 if (new_todo_units != units_written)
7806 payload_length_bytes =
7807 remote_escape_output (myaddr, new_todo_units, unit_size,
7808 (gdb_byte *) p, &units_written,
7809 payload_capacity_bytes);
6765f3e5
DJ
7810 }
7811
124e13d9
SM
7812 p += payload_length_bytes;
7813 if (use_length && units_written < todo_units)
c906108c 7814 {
802188a7 7815 /* Escape chars have filled up the buffer prematurely,
124e13d9 7816 and we have actually sent fewer units than planned.
917317f4
JM
7817 Fix-up the length field of the packet. Use the same
7818 number of characters as before. */
124e13d9
SM
7819 plen += hexnumnstr (plen, (ULONGEST) units_written,
7820 plenlen);
917317f4 7821 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7822 }
a76d924d
DJ
7823 }
7824 else
7825 {
917317f4
JM
7826 /* Normal mode: Send target system values byte by byte, in
7827 increasing byte addresses. Each byte is encoded as a two hex
7828 value. */
124e13d9
SM
7829 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7830 units_written = todo_units;
c906108c 7831 }
802188a7 7832
2e9f7625 7833 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7834 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7835
2e9f7625 7836 if (rs->buf[0] == 'E')
00d84524 7837 return TARGET_XFER_E_IO;
802188a7 7838
124e13d9
SM
7839 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7840 send fewer units than we'd planned. */
7841 *xfered_len_units = (ULONGEST) units_written;
9b409511 7842 return TARGET_XFER_OK;
c906108c
SS
7843}
7844
a76d924d
DJ
7845/* Write memory data directly to the remote machine.
7846 This does not inform the data cache; the data cache uses this.
7847 MEMADDR is the address in the remote memory space.
7848 MYADDR is the address of the buffer in our space.
7849 LEN is the number of bytes.
7850
9b409511
YQ
7851 Return the transferred status, error or OK (an
7852 'enum target_xfer_status' value). Save the number of bytes
7853 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7854
9b409511
YQ
7855static enum target_xfer_status
7856remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7857 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7858{
7859 char *packet_format = 0;
7860
7861 /* Check whether the target supports binary download. */
7862 check_binary_download (memaddr);
7863
4082afcc 7864 switch (packet_support (PACKET_X))
a76d924d
DJ
7865 {
7866 case PACKET_ENABLE:
7867 packet_format = "X";
7868 break;
7869 case PACKET_DISABLE:
7870 packet_format = "M";
7871 break;
7872 case PACKET_SUPPORT_UNKNOWN:
7873 internal_error (__FILE__, __LINE__,
7874 _("remote_write_bytes: bad internal state"));
7875 default:
7876 internal_error (__FILE__, __LINE__, _("bad switch"));
7877 }
7878
7879 return remote_write_bytes_aux (packet_format,
124e13d9 7880 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7881 packet_format[0], 1);
a76d924d
DJ
7882}
7883
9217e74e
YQ
7884/* Read memory data directly from the remote machine.
7885 This does not use the data cache; the data cache uses this.
7886 MEMADDR is the address in the remote memory space.
7887 MYADDR is the address of the buffer in our space.
124e13d9
SM
7888 LEN_UNITS is the number of addressable memory units to read..
7889 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7890
7891 Return the transferred status, error or OK (an
7892 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7893 transferred in *XFERED_LEN_UNITS.
7894
7895 See the comment of remote_write_bytes_aux for an example of
7896 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7897
7898static enum target_xfer_status
124e13d9
SM
7899remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7900 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7901{
7902 struct remote_state *rs = get_remote_state ();
124e13d9 7903 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7904 char *p;
124e13d9
SM
7905 int todo_units;
7906 int decoded_bytes;
9217e74e 7907
124e13d9 7908 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7909 /* The packet buffer will be large enough for the payload;
7910 get_memory_packet_size ensures this. */
7911
124e13d9
SM
7912 /* Number of units that will fit. */
7913 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7914
7915 /* Construct "m"<memaddr>","<len>". */
7916 memaddr = remote_address_masked (memaddr);
7917 p = rs->buf;
7918 *p++ = 'm';
7919 p += hexnumstr (p, (ULONGEST) memaddr);
7920 *p++ = ',';
124e13d9 7921 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7922 *p = '\0';
7923 putpkt (rs->buf);
7924 getpkt (&rs->buf, &rs->buf_size, 0);
7925 if (rs->buf[0] == 'E'
7926 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7927 && rs->buf[3] == '\0')
7928 return TARGET_XFER_E_IO;
7929 /* Reply describes memory byte by byte, each byte encoded as two hex
7930 characters. */
7931 p = rs->buf;
124e13d9 7932 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7933 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7934 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7935 return TARGET_XFER_OK;
7936}
7937
b55fbac4
YQ
7938/* Using the set of read-only target sections of remote, read live
7939 read-only memory.
8acf9577
YQ
7940
7941 For interface/parameters/return description see target.h,
7942 to_xfer_partial. */
7943
7944static enum target_xfer_status
b55fbac4
YQ
7945remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7946 ULONGEST memaddr, ULONGEST len,
124e13d9 7947 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7948{
7949 struct target_section *secp;
7950 struct target_section_table *table;
7951
7952 secp = target_section_by_addr (ops, memaddr);
7953 if (secp != NULL
7954 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7955 secp->the_bfd_section)
7956 & SEC_READONLY))
7957 {
7958 struct target_section *p;
7959 ULONGEST memend = memaddr + len;
7960
7961 table = target_get_section_table (ops);
7962
7963 for (p = table->sections; p < table->sections_end; p++)
7964 {
7965 if (memaddr >= p->addr)
7966 {
7967 if (memend <= p->endaddr)
7968 {
7969 /* Entire transfer is within this section. */
124e13d9 7970 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7971 xfered_len);
8acf9577
YQ
7972 }
7973 else if (memaddr >= p->endaddr)
7974 {
7975 /* This section ends before the transfer starts. */
7976 continue;
7977 }
7978 else
7979 {
7980 /* This section overlaps the transfer. Just do half. */
7981 len = p->endaddr - memaddr;
124e13d9 7982 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7983 xfered_len);
8acf9577
YQ
7984 }
7985 }
7986 }
7987 }
7988
7989 return TARGET_XFER_EOF;
7990}
7991
9217e74e
YQ
7992/* Similar to remote_read_bytes_1, but it reads from the remote stub
7993 first if the requested memory is unavailable in traceframe.
7994 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7995
9b409511 7996static enum target_xfer_status
8acf9577 7997remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7998 gdb_byte *myaddr, ULONGEST len, int unit_size,
7999 ULONGEST *xfered_len)
c906108c 8000{
6b6aa828 8001 if (len == 0)
96c4f946 8002 return TARGET_XFER_EOF;
b2182ed2 8003
8acf9577
YQ
8004 if (get_traceframe_number () != -1)
8005 {
8006 VEC(mem_range_s) *available;
8007
8008 /* If we fail to get the set of available memory, then the
8009 target does not support querying traceframe info, and so we
8010 attempt reading from the traceframe anyway (assuming the
8011 target implements the old QTro packet then). */
8012 if (traceframe_available_memory (&available, memaddr, len))
8013 {
8014 struct cleanup *old_chain;
8015
8016 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
8017
8018 if (VEC_empty (mem_range_s, available)
8019 || VEC_index (mem_range_s, available, 0)->start != memaddr)
8020 {
8021 enum target_xfer_status res;
8022
8023 /* Don't read into the traceframe's available
8024 memory. */
8025 if (!VEC_empty (mem_range_s, available))
8026 {
8027 LONGEST oldlen = len;
8028
8029 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8030 gdb_assert (len <= oldlen);
8031 }
8032
8033 do_cleanups (old_chain);
8034
8035 /* This goes through the topmost target again. */
b55fbac4 8036 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 8037 len, unit_size, xfered_len);
8acf9577
YQ
8038 if (res == TARGET_XFER_OK)
8039 return TARGET_XFER_OK;
8040 else
8041 {
8042 /* No use trying further, we know some memory starting
8043 at MEMADDR isn't available. */
8044 *xfered_len = len;
8045 return TARGET_XFER_UNAVAILABLE;
8046 }
8047 }
8048
8049 /* Don't try to read more than how much is available, in
8050 case the target implements the deprecated QTro packet to
8051 cater for older GDBs (the target's knowledge of read-only
8052 sections may be outdated by now). */
8053 len = VEC_index (mem_range_s, available, 0)->length;
8054
8055 do_cleanups (old_chain);
8056 }
8057 }
8058
124e13d9 8059 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8060}
74531fed 8061
c906108c 8062\f
c906108c 8063
a76d924d
DJ
8064/* Sends a packet with content determined by the printf format string
8065 FORMAT and the remaining arguments, then gets the reply. Returns
8066 whether the packet was a success, a failure, or unknown. */
8067
77b64a49
PA
8068static enum packet_result remote_send_printf (const char *format, ...)
8069 ATTRIBUTE_PRINTF (1, 2);
8070
2c0b251b 8071static enum packet_result
a76d924d
DJ
8072remote_send_printf (const char *format, ...)
8073{
8074 struct remote_state *rs = get_remote_state ();
8075 int max_size = get_remote_packet_size ();
a76d924d 8076 va_list ap;
a744cf53 8077
a76d924d
DJ
8078 va_start (ap, format);
8079
8080 rs->buf[0] = '\0';
8081 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8082 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8083
8084 if (putpkt (rs->buf) < 0)
8085 error (_("Communication problem with target."));
8086
8087 rs->buf[0] = '\0';
8088 getpkt (&rs->buf, &rs->buf_size, 0);
8089
8090 return packet_check_result (rs->buf);
8091}
8092
8093static void
8094restore_remote_timeout (void *p)
8095{
8096 int value = *(int *)p;
a744cf53 8097
a76d924d
DJ
8098 remote_timeout = value;
8099}
8100
8101/* Flash writing can take quite some time. We'll set
8102 effectively infinite timeout for flash operations.
8103 In future, we'll need to decide on a better approach. */
8104static const int remote_flash_timeout = 1000;
8105
8106static void
8107remote_flash_erase (struct target_ops *ops,
8108 ULONGEST address, LONGEST length)
8109{
f5656ead 8110 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
8111 int saved_remote_timeout = remote_timeout;
8112 enum packet_result ret;
a76d924d
DJ
8113 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8114 &saved_remote_timeout);
a744cf53 8115
a76d924d
DJ
8116 remote_timeout = remote_flash_timeout;
8117
8118 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8119 phex (address, addr_size),
a76d924d
DJ
8120 phex (length, 4));
8121 switch (ret)
8122 {
8123 case PACKET_UNKNOWN:
8124 error (_("Remote target does not support flash erase"));
8125 case PACKET_ERROR:
8126 error (_("Error erasing flash with vFlashErase packet"));
8127 default:
8128 break;
8129 }
8130
8131 do_cleanups (back_to);
8132}
8133
9b409511
YQ
8134static enum target_xfer_status
8135remote_flash_write (struct target_ops *ops, ULONGEST address,
8136 ULONGEST length, ULONGEST *xfered_len,
8137 const gdb_byte *data)
a76d924d
DJ
8138{
8139 int saved_remote_timeout = remote_timeout;
9b409511 8140 enum target_xfer_status ret;
a76d924d 8141 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 8142 &saved_remote_timeout);
a76d924d
DJ
8143
8144 remote_timeout = remote_flash_timeout;
124e13d9 8145 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 8146 xfered_len,'X', 0);
a76d924d
DJ
8147 do_cleanups (back_to);
8148
8149 return ret;
8150}
8151
8152static void
8153remote_flash_done (struct target_ops *ops)
8154{
8155 int saved_remote_timeout = remote_timeout;
8156 int ret;
8157 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8158 &saved_remote_timeout);
8159
8160 remote_timeout = remote_flash_timeout;
8161 ret = remote_send_printf ("vFlashDone");
8162 do_cleanups (back_to);
8163
8164 switch (ret)
8165 {
8166 case PACKET_UNKNOWN:
8167 error (_("Remote target does not support vFlashDone"));
8168 case PACKET_ERROR:
8169 error (_("Error finishing flash operation"));
8170 default:
8171 break;
8172 }
8173}
8174
c906108c 8175static void
fba45db2 8176remote_files_info (struct target_ops *ignore)
c906108c
SS
8177{
8178 puts_filtered ("Debugging a target over a serial line.\n");
8179}
8180\f
8181/* Stuff for dealing with the packets which are part of this protocol.
8182 See comment at top of file for details. */
8183
1927e618
PA
8184/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8185 error to higher layers. Called when a serial error is detected.
8186 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8187 the system error message for errno at function entry and final dot
8188 for output compatibility with throw_perror_with_name. */
1927e618
PA
8189
8190static void
8191unpush_and_perror (const char *string)
8192{
d6cb50a2 8193 int saved_errno = errno;
1927e618
PA
8194
8195 remote_unpush_target ();
d6cb50a2
JK
8196 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8197 safe_strerror (saved_errno));
1927e618
PA
8198}
8199
0876f84a 8200/* Read a single character from the remote end. */
c906108c
SS
8201
8202static int
fba45db2 8203readchar (int timeout)
c906108c
SS
8204{
8205 int ch;
5d93a237 8206 struct remote_state *rs = get_remote_state ();
c906108c 8207
5d93a237 8208 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 8209
2acceee2 8210 if (ch >= 0)
0876f84a 8211 return ch;
2acceee2
JM
8212
8213 switch ((enum serial_rc) ch)
c906108c
SS
8214 {
8215 case SERIAL_EOF:
78a095c3 8216 remote_unpush_target ();
598d3636 8217 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8218 /* no return */
c906108c 8219 case SERIAL_ERROR:
1927e618
PA
8220 unpush_and_perror (_("Remote communication error. "
8221 "Target disconnected."));
2acceee2 8222 /* no return */
c906108c 8223 case SERIAL_TIMEOUT:
2acceee2 8224 break;
c906108c 8225 }
2acceee2 8226 return ch;
c906108c
SS
8227}
8228
c33e31fd
PA
8229/* Wrapper for serial_write that closes the target and throws if
8230 writing fails. */
8231
8232static void
8233remote_serial_write (const char *str, int len)
8234{
5d93a237
TT
8235 struct remote_state *rs = get_remote_state ();
8236
8237 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8238 {
1927e618
PA
8239 unpush_and_perror (_("Remote communication error. "
8240 "Target disconnected."));
c33e31fd
PA
8241 }
8242}
8243
6d820c5c
DJ
8244/* Send the command in *BUF to the remote machine, and read the reply
8245 into *BUF. Report an error if we get an error reply. Resize
8246 *BUF using xrealloc if necessary to hold the result, and update
8247 *SIZEOF_BUF. */
c906108c
SS
8248
8249static void
6d820c5c
DJ
8250remote_send (char **buf,
8251 long *sizeof_buf)
c906108c 8252{
6d820c5c 8253 putpkt (*buf);
c2d11a7d 8254 getpkt (buf, sizeof_buf, 0);
c906108c 8255
6d820c5c
DJ
8256 if ((*buf)[0] == 'E')
8257 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8258}
8259
6e5abd65
PA
8260/* Return a pointer to an xmalloc'ed string representing an escaped
8261 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8262 etc. The caller is responsible for releasing the returned
8263 memory. */
8264
8265static char *
8266escape_buffer (const char *buf, int n)
8267{
8268 struct cleanup *old_chain;
8269 struct ui_file *stb;
8270 char *str;
6e5abd65
PA
8271
8272 stb = mem_fileopen ();
8273 old_chain = make_cleanup_ui_file_delete (stb);
8274
6ef284bd 8275 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 8276 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
8277 do_cleanups (old_chain);
8278 return str;
8279}
8280
c906108c
SS
8281/* Display a null-terminated packet on stdout, for debugging, using C
8282 string notation. */
8283
8284static void
baa336ce 8285print_packet (const char *buf)
c906108c
SS
8286{
8287 puts_filtered ("\"");
43e526b9 8288 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8289 puts_filtered ("\"");
8290}
8291
8292int
baa336ce 8293putpkt (const char *buf)
c906108c
SS
8294{
8295 return putpkt_binary (buf, strlen (buf));
8296}
8297
8298/* Send a packet to the remote machine, with error checking. The data
23860348 8299 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8300 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8301 and for a possible /0 if we are debugging (remote_debug) and want
8302 to print the sent packet as a string. */
c906108c
SS
8303
8304static int
baa336ce 8305putpkt_binary (const char *buf, int cnt)
c906108c 8306{
2d717e4f 8307 struct remote_state *rs = get_remote_state ();
c906108c
SS
8308 int i;
8309 unsigned char csum = 0;
224c3ddb 8310 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8311 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8312
c906108c
SS
8313 int ch;
8314 int tcount = 0;
8315 char *p;
8316
e24a49d8
PA
8317 /* Catch cases like trying to read memory or listing threads while
8318 we're waiting for a stop reply. The remote server wouldn't be
8319 ready to handle this request, so we'd hang and timeout. We don't
8320 have to worry about this in synchronous mode, because in that
8321 case it's not possible to issue a command while the target is
74531fed
PA
8322 running. This is not a problem in non-stop mode, because in that
8323 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8324 if (!target_is_non_stop_p ()
8325 && target_is_async_p ()
8326 && rs->waiting_for_stop_reply)
9597b22a
DE
8327 {
8328 error (_("Cannot execute this command while the target is running.\n"
8329 "Use the \"interrupt\" command to stop the target\n"
8330 "and then try again."));
8331 }
e24a49d8 8332
2d717e4f
DJ
8333 /* We're sending out a new packet. Make sure we don't look at a
8334 stale cached response. */
8335 rs->cached_wait_status = 0;
8336
c906108c
SS
8337 /* Copy the packet into buffer BUF2, encapsulating it
8338 and giving it a checksum. */
8339
c906108c
SS
8340 p = buf2;
8341 *p++ = '$';
8342
8343 for (i = 0; i < cnt; i++)
8344 {
8345 csum += buf[i];
8346 *p++ = buf[i];
8347 }
8348 *p++ = '#';
8349 *p++ = tohex ((csum >> 4) & 0xf);
8350 *p++ = tohex (csum & 0xf);
8351
8352 /* Send it over and over until we get a positive ack. */
8353
8354 while (1)
8355 {
8356 int started_error_output = 0;
8357
8358 if (remote_debug)
8359 {
6e5abd65
PA
8360 struct cleanup *old_chain;
8361 char *str;
8362
c906108c 8363 *p = '\0';
6e5abd65
PA
8364 str = escape_buffer (buf2, p - buf2);
8365 old_chain = make_cleanup (xfree, str);
8366 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8367 gdb_flush (gdb_stdlog);
6e5abd65 8368 do_cleanups (old_chain);
c906108c 8369 }
c33e31fd 8370 remote_serial_write (buf2, p - buf2);
c906108c 8371
a6f3e723
SL
8372 /* If this is a no acks version of the remote protocol, send the
8373 packet and move on. */
8374 if (rs->noack_mode)
8375 break;
8376
74531fed
PA
8377 /* Read until either a timeout occurs (-2) or '+' is read.
8378 Handle any notification that arrives in the mean time. */
c906108c
SS
8379 while (1)
8380 {
8381 ch = readchar (remote_timeout);
8382
c5aa993b 8383 if (remote_debug)
c906108c
SS
8384 {
8385 switch (ch)
8386 {
8387 case '+':
1216fa2c 8388 case '-':
c906108c
SS
8389 case SERIAL_TIMEOUT:
8390 case '$':
74531fed 8391 case '%':
c906108c
SS
8392 if (started_error_output)
8393 {
8394 putchar_unfiltered ('\n');
8395 started_error_output = 0;
8396 }
8397 }
8398 }
8399
8400 switch (ch)
8401 {
8402 case '+':
8403 if (remote_debug)
0f71a2f6 8404 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8405 do_cleanups (old_chain);
c906108c 8406 return 1;
1216fa2c
AC
8407 case '-':
8408 if (remote_debug)
8409 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8410 /* FALLTHROUGH */
c906108c 8411 case SERIAL_TIMEOUT:
c5aa993b 8412 tcount++;
c906108c 8413 if (tcount > 3)
a5c0808e
PA
8414 {
8415 do_cleanups (old_chain);
8416 return 0;
8417 }
23860348 8418 break; /* Retransmit buffer. */
c906108c
SS
8419 case '$':
8420 {
40e3f985 8421 if (remote_debug)
2bc416ba 8422 fprintf_unfiltered (gdb_stdlog,
23860348 8423 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8424 /* It's probably an old response sent because an ACK
8425 was lost. Gobble up the packet and ack it so it
8426 doesn't get retransmitted when we resend this
8427 packet. */
6d820c5c 8428 skip_frame ();
c33e31fd 8429 remote_serial_write ("+", 1);
23860348 8430 continue; /* Now, go look for +. */
c906108c 8431 }
74531fed
PA
8432
8433 case '%':
8434 {
8435 int val;
8436
8437 /* If we got a notification, handle it, and go back to looking
8438 for an ack. */
8439 /* We've found the start of a notification. Now
8440 collect the data. */
8441 val = read_frame (&rs->buf, &rs->buf_size);
8442 if (val >= 0)
8443 {
8444 if (remote_debug)
8445 {
6e5abd65
PA
8446 struct cleanup *old_chain;
8447 char *str;
8448
8449 str = escape_buffer (rs->buf, val);
8450 old_chain = make_cleanup (xfree, str);
8451 fprintf_unfiltered (gdb_stdlog,
8452 " Notification received: %s\n",
8453 str);
8454 do_cleanups (old_chain);
74531fed 8455 }
5965e028 8456 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8457 /* We're in sync now, rewait for the ack. */
8458 tcount = 0;
8459 }
8460 else
8461 {
8462 if (remote_debug)
8463 {
8464 if (!started_error_output)
8465 {
8466 started_error_output = 1;
8467 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8468 }
8469 fputc_unfiltered (ch & 0177, gdb_stdlog);
8470 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8471 }
8472 }
8473 continue;
8474 }
8475 /* fall-through */
c906108c
SS
8476 default:
8477 if (remote_debug)
8478 {
8479 if (!started_error_output)
8480 {
8481 started_error_output = 1;
0f71a2f6 8482 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8483 }
0f71a2f6 8484 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8485 }
8486 continue;
8487 }
23860348 8488 break; /* Here to retransmit. */
c906108c
SS
8489 }
8490
8491#if 0
8492 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8493 able to get out next time we call QUIT, without anything as
8494 violent as interrupt_query. If we want to provide a way out of
8495 here without getting to the next QUIT, it should be based on
8496 hitting ^C twice as in remote_wait. */
c906108c
SS
8497 if (quit_flag)
8498 {
8499 quit_flag = 0;
8500 interrupt_query ();
8501 }
8502#endif
8503 }
a5c0808e
PA
8504
8505 do_cleanups (old_chain);
a6f3e723 8506 return 0;
c906108c
SS
8507}
8508
6d820c5c
DJ
8509/* Come here after finding the start of a frame when we expected an
8510 ack. Do our best to discard the rest of this packet. */
8511
8512static void
8513skip_frame (void)
8514{
8515 int c;
8516
8517 while (1)
8518 {
8519 c = readchar (remote_timeout);
8520 switch (c)
8521 {
8522 case SERIAL_TIMEOUT:
8523 /* Nothing we can do. */
8524 return;
8525 case '#':
8526 /* Discard the two bytes of checksum and stop. */
8527 c = readchar (remote_timeout);
8528 if (c >= 0)
8529 c = readchar (remote_timeout);
8530
8531 return;
8532 case '*': /* Run length encoding. */
8533 /* Discard the repeat count. */
8534 c = readchar (remote_timeout);
8535 if (c < 0)
8536 return;
8537 break;
8538 default:
8539 /* A regular character. */
8540 break;
8541 }
8542 }
8543}
8544
c906108c 8545/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8546 into *BUF, verifying the checksum, length, and handling run-length
8547 compression. NUL terminate the buffer. If there is not enough room,
8548 expand *BUF using xrealloc.
c906108c 8549
c2d11a7d
JM
8550 Returns -1 on error, number of characters in buffer (ignoring the
8551 trailing NULL) on success. (could be extended to return one of the
23860348 8552 SERIAL status indications). */
c2d11a7d
JM
8553
8554static long
6d820c5c
DJ
8555read_frame (char **buf_p,
8556 long *sizeof_buf)
c906108c
SS
8557{
8558 unsigned char csum;
c2d11a7d 8559 long bc;
c906108c 8560 int c;
6d820c5c 8561 char *buf = *buf_p;
a6f3e723 8562 struct remote_state *rs = get_remote_state ();
c906108c
SS
8563
8564 csum = 0;
c2d11a7d 8565 bc = 0;
c906108c
SS
8566
8567 while (1)
8568 {
8569 c = readchar (remote_timeout);
c906108c
SS
8570 switch (c)
8571 {
8572 case SERIAL_TIMEOUT:
8573 if (remote_debug)
0f71a2f6 8574 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8575 return -1;
c906108c
SS
8576 case '$':
8577 if (remote_debug)
0f71a2f6
JM
8578 fputs_filtered ("Saw new packet start in middle of old one\n",
8579 gdb_stdlog);
23860348 8580 return -1; /* Start a new packet, count retries. */
c906108c
SS
8581 case '#':
8582 {
8583 unsigned char pktcsum;
e1b09194
AC
8584 int check_0 = 0;
8585 int check_1 = 0;
c906108c 8586
c2d11a7d 8587 buf[bc] = '\0';
c906108c 8588
e1b09194
AC
8589 check_0 = readchar (remote_timeout);
8590 if (check_0 >= 0)
8591 check_1 = readchar (remote_timeout);
802188a7 8592
e1b09194
AC
8593 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8594 {
8595 if (remote_debug)
2bc416ba 8596 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8597 gdb_stdlog);
e1b09194
AC
8598 return -1;
8599 }
8600 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8601 {
8602 if (remote_debug)
2bc416ba 8603 fputs_filtered ("Communication error in checksum\n",
23860348 8604 gdb_stdlog);
40e3f985
FN
8605 return -1;
8606 }
c906108c 8607
a6f3e723
SL
8608 /* Don't recompute the checksum; with no ack packets we
8609 don't have any way to indicate a packet retransmission
8610 is necessary. */
8611 if (rs->noack_mode)
8612 return bc;
8613
e1b09194 8614 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8615 if (csum == pktcsum)
c2d11a7d 8616 return bc;
c906108c 8617
c5aa993b 8618 if (remote_debug)
c906108c 8619 {
6e5abd65
PA
8620 struct cleanup *old_chain;
8621 char *str;
8622
8623 str = escape_buffer (buf, bc);
8624 old_chain = make_cleanup (xfree, str);
8625 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8626 "Bad checksum, sentsum=0x%x, "
8627 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8628 pktcsum, csum, str);
8629 do_cleanups (old_chain);
c906108c 8630 }
c2d11a7d 8631 /* Number of characters in buffer ignoring trailing
23860348 8632 NULL. */
c2d11a7d 8633 return -1;
c906108c 8634 }
23860348 8635 case '*': /* Run length encoding. */
c2c6d25f
JM
8636 {
8637 int repeat;
c906108c 8638
a744cf53 8639 csum += c;
b4501125
AC
8640 c = readchar (remote_timeout);
8641 csum += c;
23860348 8642 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8643
23860348 8644 /* The character before ``*'' is repeated. */
c2d11a7d 8645
6d820c5c 8646 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8647 {
6d820c5c
DJ
8648 if (bc + repeat - 1 >= *sizeof_buf - 1)
8649 {
8650 /* Make some more room in the buffer. */
8651 *sizeof_buf += repeat;
224c3ddb 8652 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
8653 buf = *buf_p;
8654 }
8655
c2d11a7d
JM
8656 memset (&buf[bc], buf[bc - 1], repeat);
8657 bc += repeat;
c2c6d25f
JM
8658 continue;
8659 }
8660
c2d11a7d 8661 buf[bc] = '\0';
6d820c5c 8662 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8663 return -1;
c2c6d25f 8664 }
c906108c 8665 default:
6d820c5c 8666 if (bc >= *sizeof_buf - 1)
c906108c 8667 {
6d820c5c
DJ
8668 /* Make some more room in the buffer. */
8669 *sizeof_buf *= 2;
224c3ddb 8670 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 8671 buf = *buf_p;
c906108c
SS
8672 }
8673
6d820c5c
DJ
8674 buf[bc++] = c;
8675 csum += c;
8676 continue;
c906108c
SS
8677 }
8678 }
8679}
8680
8681/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8682 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8683 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8684 rather than timing out; this is used (in synchronous mode) to wait
8685 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8686/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8687 don't have to change all the calls to getpkt to deal with the
8688 return value, because at the moment I don't know what the right
23860348 8689 thing to do it for those. */
c906108c 8690void
6d820c5c
DJ
8691getpkt (char **buf,
8692 long *sizeof_buf,
c2d11a7d 8693 int forever)
d9fcf2fb 8694{
54887903 8695 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
8696}
8697
8698
8699/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8700 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8701 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8702 rather than timing out; this is used (in synchronous mode) to wait
8703 for a target that is is executing user code to stop. If FOREVER ==
8704 0, this function is allowed to time out gracefully and return an
74531fed
PA
8705 indication of this to the caller. Otherwise return the number of
8706 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8707 enough reason to return to the caller. *IS_NOTIF is an output
8708 boolean that indicates whether *BUF holds a notification or not
8709 (a regular packet). */
74531fed 8710
3172dc30 8711static int
74531fed 8712getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8713 int expecting_notif, int *is_notif)
c906108c 8714{
2d717e4f 8715 struct remote_state *rs = get_remote_state ();
c906108c
SS
8716 int c;
8717 int tries;
8718 int timeout;
df4b58fe 8719 int val = -1;
c906108c 8720
2d717e4f
DJ
8721 /* We're reading a new response. Make sure we don't look at a
8722 previously cached response. */
8723 rs->cached_wait_status = 0;
8724
6d820c5c 8725 strcpy (*buf, "timeout");
c906108c
SS
8726
8727 if (forever)
74531fed
PA
8728 timeout = watchdog > 0 ? watchdog : -1;
8729 else if (expecting_notif)
8730 timeout = 0; /* There should already be a char in the buffer. If
8731 not, bail out. */
c906108c
SS
8732 else
8733 timeout = remote_timeout;
8734
8735#define MAX_TRIES 3
8736
74531fed
PA
8737 /* Process any number of notifications, and then return when
8738 we get a packet. */
8739 for (;;)
c906108c 8740 {
d9c43928 8741 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8742 times. */
8743 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8744 {
74531fed
PA
8745 /* This can loop forever if the remote side sends us
8746 characters continuously, but if it pauses, we'll get
8747 SERIAL_TIMEOUT from readchar because of timeout. Then
8748 we'll count that as a retry.
8749
8750 Note that even when forever is set, we will only wait
8751 forever prior to the start of a packet. After that, we
8752 expect characters to arrive at a brisk pace. They should
8753 show up within remote_timeout intervals. */
8754 do
8755 c = readchar (timeout);
8756 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8757
8758 if (c == SERIAL_TIMEOUT)
8759 {
74531fed
PA
8760 if (expecting_notif)
8761 return -1; /* Don't complain, it's normal to not get
8762 anything in this case. */
8763
23860348 8764 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8765 {
2acceee2 8766 QUIT;
78a095c3 8767 remote_unpush_target ();
598d3636
JK
8768 throw_error (TARGET_CLOSE_ERROR,
8769 _("Watchdog timeout has expired. "
8770 "Target detached."));
c906108c 8771 }
c906108c 8772 if (remote_debug)
0f71a2f6 8773 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8774 }
74531fed
PA
8775 else
8776 {
8777 /* We've found the start of a packet or notification.
8778 Now collect the data. */
8779 val = read_frame (buf, sizeof_buf);
8780 if (val >= 0)
8781 break;
8782 }
8783
c33e31fd 8784 remote_serial_write ("-", 1);
c906108c 8785 }
c906108c 8786
74531fed
PA
8787 if (tries > MAX_TRIES)
8788 {
8789 /* We have tried hard enough, and just can't receive the
8790 packet/notification. Give up. */
8791 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8792
74531fed
PA
8793 /* Skip the ack char if we're in no-ack mode. */
8794 if (!rs->noack_mode)
c33e31fd 8795 remote_serial_write ("+", 1);
74531fed
PA
8796 return -1;
8797 }
c906108c 8798
74531fed
PA
8799 /* If we got an ordinary packet, return that to our caller. */
8800 if (c == '$')
c906108c
SS
8801 {
8802 if (remote_debug)
43e526b9 8803 {
6e5abd65
PA
8804 struct cleanup *old_chain;
8805 char *str;
8806
8807 str = escape_buffer (*buf, val);
8808 old_chain = make_cleanup (xfree, str);
8809 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8810 do_cleanups (old_chain);
43e526b9 8811 }
a6f3e723
SL
8812
8813 /* Skip the ack char if we're in no-ack mode. */
8814 if (!rs->noack_mode)
c33e31fd 8815 remote_serial_write ("+", 1);
fee9eda9
YQ
8816 if (is_notif != NULL)
8817 *is_notif = 0;
0876f84a 8818 return val;
c906108c
SS
8819 }
8820
74531fed
PA
8821 /* If we got a notification, handle it, and go back to looking
8822 for a packet. */
8823 else
8824 {
8825 gdb_assert (c == '%');
8826
8827 if (remote_debug)
8828 {
6e5abd65
PA
8829 struct cleanup *old_chain;
8830 char *str;
8831
8832 str = escape_buffer (*buf, val);
8833 old_chain = make_cleanup (xfree, str);
8834 fprintf_unfiltered (gdb_stdlog,
8835 " Notification received: %s\n",
8836 str);
8837 do_cleanups (old_chain);
74531fed 8838 }
fee9eda9
YQ
8839 if (is_notif != NULL)
8840 *is_notif = 1;
c906108c 8841
5965e028 8842 handle_notification (rs->notif_state, *buf);
c906108c 8843
74531fed 8844 /* Notifications require no acknowledgement. */
a6f3e723 8845
74531fed 8846 if (expecting_notif)
fee9eda9 8847 return val;
74531fed
PA
8848 }
8849 }
8850}
8851
8852static int
8853getpkt_sane (char **buf, long *sizeof_buf, int forever)
8854{
fee9eda9 8855 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8856}
8857
8858static int
fee9eda9
YQ
8859getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8860 int *is_notif)
74531fed 8861{
fee9eda9
YQ
8862 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8863 is_notif);
c906108c 8864}
74531fed 8865
cbb8991c
DB
8866/* Check whether EVENT is a fork event for the process specified
8867 by the pid passed in DATA, and if it is, kill the fork child. */
8868
8869static int
8870kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8871 QUEUE_ITER (stop_reply_p) *iter,
8872 stop_reply_p event,
8873 void *data)
8874{
19ba03f4 8875 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
8876 int parent_pid = *(int *) param->input;
8877
8878 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8879 {
8880 struct remote_state *rs = get_remote_state ();
8881 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8882 int res;
8883
8884 res = remote_vkill (child_pid, rs);
8885 if (res != 0)
8886 error (_("Can't kill fork child process %d"), child_pid);
8887 }
8888
8889 return 1;
8890}
8891
8892/* Kill any new fork children of process PID that haven't been
8893 processed by follow_fork. */
8894
8895static void
8896kill_new_fork_children (int pid, struct remote_state *rs)
8897{
8898 struct thread_info *thread;
8899 struct notif_client *notif = &notif_client_stop;
8900 struct queue_iter_param param;
8901
8902 /* Kill the fork child threads of any threads in process PID
8903 that are stopped at a fork event. */
8904 ALL_NON_EXITED_THREADS (thread)
8905 {
8906 struct target_waitstatus *ws = &thread->pending_follow;
8907
8908 if (is_pending_fork_parent (ws, pid, thread->ptid))
8909 {
8910 struct remote_state *rs = get_remote_state ();
8911 int child_pid = ptid_get_pid (ws->value.related_pid);
8912 int res;
8913
8914 res = remote_vkill (child_pid, rs);
8915 if (res != 0)
8916 error (_("Can't kill fork child process %d"), child_pid);
8917 }
8918 }
8919
8920 /* Check for any pending fork events (not reported or processed yet)
8921 in process PID and kill those fork child threads as well. */
8922 remote_notif_get_pending_events (notif);
8923 param.input = &pid;
8924 param.output = NULL;
8925 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8926 kill_child_of_pending_fork, &param);
8927}
8928
c906108c 8929\f
8020350c
DB
8930/* Target hook to kill the current inferior. */
8931
c906108c 8932static void
7d85a9c0 8933remote_kill (struct target_ops *ops)
43ff13b4 8934{
8020350c
DB
8935 int res = -1;
8936 int pid = ptid_get_pid (inferior_ptid);
8937 struct remote_state *rs = get_remote_state ();
0fdf84ca 8938
8020350c 8939 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 8940 {
8020350c
DB
8941 /* If we're stopped while forking and we haven't followed yet,
8942 kill the child task. We need to do this before killing the
8943 parent task because if this is a vfork then the parent will
8944 be sleeping. */
8945 kill_new_fork_children (pid, rs);
8946
8947 res = remote_vkill (pid, rs);
8948 if (res == 0)
0fdf84ca 8949 {
8020350c 8950 target_mourn_inferior ();
0fdf84ca
PA
8951 return;
8952 }
8020350c 8953 }
0fdf84ca 8954
8020350c
DB
8955 /* If we are in 'target remote' mode and we are killing the only
8956 inferior, then we will tell gdbserver to exit and unpush the
8957 target. */
8958 if (res == -1 && !remote_multi_process_p (rs)
8959 && number_of_live_inferiors () == 1)
8960 {
8961 remote_kill_k ();
8962
8963 /* We've killed the remote end, we get to mourn it. If we are
8964 not in extended mode, mourning the inferior also unpushes
8965 remote_ops from the target stack, which closes the remote
8966 connection. */
8967 target_mourn_inferior ();
8968
8969 return;
0fdf84ca 8970 }
43ff13b4 8971
8020350c 8972 error (_("Can't kill process"));
43ff13b4
JM
8973}
8974
8020350c
DB
8975/* Send a kill request to the target using the 'vKill' packet. */
8976
82f73884
PA
8977static int
8978remote_vkill (int pid, struct remote_state *rs)
8979{
4082afcc 8980 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8981 return -1;
8982
8983 /* Tell the remote target to detach. */
bba74b36 8984 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8985 putpkt (rs->buf);
8986 getpkt (&rs->buf, &rs->buf_size, 0);
8987
4082afcc
PA
8988 switch (packet_ok (rs->buf,
8989 &remote_protocol_packets[PACKET_vKill]))
8990 {
8991 case PACKET_OK:
8992 return 0;
8993 case PACKET_ERROR:
8994 return 1;
8995 case PACKET_UNKNOWN:
8996 return -1;
8997 default:
8998 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8999 }
82f73884
PA
9000}
9001
8020350c
DB
9002/* Send a kill request to the target using the 'k' packet. */
9003
82f73884 9004static void
8020350c 9005remote_kill_k (void)
82f73884 9006{
8020350c
DB
9007 /* Catch errors so the user can quit from gdb even when we
9008 aren't on speaking terms with the remote system. */
9009 TRY
82f73884 9010 {
82f73884 9011 putpkt ("k");
82f73884 9012 }
8020350c
DB
9013 CATCH (ex, RETURN_MASK_ERROR)
9014 {
9015 if (ex.error == TARGET_CLOSE_ERROR)
9016 {
9017 /* If we got an (EOF) error that caused the target
9018 to go away, then we're done, that's what we wanted.
9019 "k" is susceptible to cause a premature EOF, given
9020 that the remote server isn't actually required to
9021 reply to "k", and it can happen that it doesn't
9022 even get to reply ACK to the "k". */
9023 return;
9024 }
82f73884 9025
8020350c
DB
9026 /* Otherwise, something went wrong. We didn't actually kill
9027 the target. Just propagate the exception, and let the
9028 user or higher layers decide what to do. */
9029 throw_exception (ex);
9030 }
9031 END_CATCH
82f73884
PA
9032}
9033
c906108c 9034static void
20f796c9 9035remote_mourn (struct target_ops *target)
c906108c 9036{
8020350c 9037 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9038
8020350c
DB
9039 /* In 'target remote' mode with one inferior, we close the connection. */
9040 if (!rs->extended && number_of_live_inferiors () <= 1)
9041 {
9042 unpush_target (target);
c906108c 9043
8020350c
DB
9044 /* remote_close takes care of doing most of the clean up. */
9045 generic_mourn_inferior ();
9046 return;
9047 }
c906108c 9048
e24a49d8
PA
9049 /* In case we got here due to an error, but we're going to stay
9050 connected. */
9051 rs->waiting_for_stop_reply = 0;
9052
dc1981d7
PA
9053 /* If the current general thread belonged to the process we just
9054 detached from or has exited, the remote side current general
9055 thread becomes undefined. Considering a case like this:
9056
9057 - We just got here due to a detach.
9058 - The process that we're detaching from happens to immediately
9059 report a global breakpoint being hit in non-stop mode, in the
9060 same thread we had selected before.
9061 - GDB attaches to this process again.
9062 - This event happens to be the next event we handle.
9063
9064 GDB would consider that the current general thread didn't need to
9065 be set on the stub side (with Hg), since for all it knew,
9066 GENERAL_THREAD hadn't changed.
9067
9068 Notice that although in all-stop mode, the remote server always
9069 sets the current thread to the thread reporting the stop event,
9070 that doesn't happen in non-stop mode; in non-stop, the stub *must
9071 not* change the current thread when reporting a breakpoint hit,
9072 due to the decoupling of event reporting and event handling.
9073
9074 To keep things simple, we always invalidate our notion of the
9075 current thread. */
47f8a51d 9076 record_currthread (rs, minus_one_ptid);
dc1981d7 9077
8020350c 9078 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9079 generic_mourn_inferior ();
9080
d729566a 9081 if (!have_inferiors ())
2d717e4f 9082 {
82f73884
PA
9083 if (!remote_multi_process_p (rs))
9084 {
9085 /* Check whether the target is running now - some remote stubs
9086 automatically restart after kill. */
9087 putpkt ("?");
9088 getpkt (&rs->buf, &rs->buf_size, 0);
9089
9090 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9091 {
3e43a32a
MS
9092 /* Assume that the target has been restarted. Set
9093 inferior_ptid so that bits of core GDB realizes
9094 there's something here, e.g., so that the user can
9095 say "kill" again. */
82f73884
PA
9096 inferior_ptid = magic_null_ptid;
9097 }
82f73884 9098 }
2d717e4f
DJ
9099 }
9100}
c906108c 9101
03583c20 9102static int
2bfc0540 9103extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 9104{
4082afcc 9105 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9106}
9107
9108static void
9109extended_remote_disable_randomization (int val)
9110{
9111 struct remote_state *rs = get_remote_state ();
9112 char *reply;
9113
bba74b36
YQ
9114 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9115 val);
03583c20
UW
9116 putpkt (rs->buf);
9117 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9118 if (*reply == '\0')
9119 error (_("Target does not support QDisableRandomization."));
9120 if (strcmp (reply, "OK") != 0)
9121 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9122}
9123
2d717e4f
DJ
9124static int
9125extended_remote_run (char *args)
9126{
9127 struct remote_state *rs = get_remote_state ();
2d717e4f 9128 int len;
94585166 9129 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9130
2d717e4f
DJ
9131 /* If the user has disabled vRun support, or we have detected that
9132 support is not available, do not try it. */
4082afcc 9133 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9134 return -1;
424163ea 9135
2d717e4f
DJ
9136 strcpy (rs->buf, "vRun;");
9137 len = strlen (rs->buf);
c906108c 9138
2d717e4f
DJ
9139 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9140 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9141 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9142 strlen (remote_exec_file));
2d717e4f 9143
d1a41061 9144 gdb_assert (args != NULL);
2d717e4f
DJ
9145 if (*args)
9146 {
9147 struct cleanup *back_to;
9148 int i;
9149 char **argv;
9150
d1a41061 9151 argv = gdb_buildargv (args);
6e366df1 9152 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
9153 for (i = 0; argv[i] != NULL; i++)
9154 {
9155 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9156 error (_("Argument list too long for run packet"));
9157 rs->buf[len++] = ';';
9f1b45b0
TT
9158 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9159 strlen (argv[i]));
2d717e4f
DJ
9160 }
9161 do_cleanups (back_to);
9162 }
9163
9164 rs->buf[len++] = '\0';
9165
9166 putpkt (rs->buf);
9167 getpkt (&rs->buf, &rs->buf_size, 0);
9168
4082afcc 9169 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9170 {
4082afcc 9171 case PACKET_OK:
3405876a 9172 /* We have a wait response. All is well. */
2d717e4f 9173 return 0;
4082afcc
PA
9174 case PACKET_UNKNOWN:
9175 return -1;
9176 case PACKET_ERROR:
2d717e4f
DJ
9177 if (remote_exec_file[0] == '\0')
9178 error (_("Running the default executable on the remote target failed; "
9179 "try \"set remote exec-file\"?"));
9180 else
9181 error (_("Running \"%s\" on the remote target failed"),
9182 remote_exec_file);
4082afcc
PA
9183 default:
9184 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9185 }
c906108c
SS
9186}
9187
2d717e4f
DJ
9188/* In the extended protocol we want to be able to do things like
9189 "run" and have them basically work as expected. So we need
9190 a special create_inferior function. We support changing the
9191 executable file and the command line arguments, but not the
9192 environment. */
9193
43ff13b4 9194static void
77a19445
TT
9195extended_remote_create_inferior (struct target_ops *ops,
9196 char *exec_file, char *args,
9197 char **env, int from_tty)
43ff13b4 9198{
3405876a
PA
9199 int run_worked;
9200 char *stop_reply;
9201 struct remote_state *rs = get_remote_state ();
94585166 9202 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9203
43ff13b4 9204 /* If running asynchronously, register the target file descriptor
23860348 9205 with the event loop. */
75c99385 9206 if (target_can_async_p ())
6a3753b3 9207 target_async (1);
43ff13b4 9208
03583c20 9209 /* Disable address space randomization if requested (and supported). */
2bfc0540 9210 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9211 extended_remote_disable_randomization (disable_randomization);
9212
43ff13b4 9213 /* Now restart the remote server. */
3405876a
PA
9214 run_worked = extended_remote_run (args) != -1;
9215 if (!run_worked)
2d717e4f
DJ
9216 {
9217 /* vRun was not supported. Fail if we need it to do what the
9218 user requested. */
9219 if (remote_exec_file[0])
9220 error (_("Remote target does not support \"set remote exec-file\""));
9221 if (args[0])
9222 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9223
2d717e4f
DJ
9224 /* Fall back to "R". */
9225 extended_remote_restart ();
9226 }
424163ea 9227
6c95b8df
PA
9228 if (!have_inferiors ())
9229 {
9230 /* Clean up from the last time we ran, before we mark the target
9231 running again. This will mark breakpoints uninserted, and
9232 get_offsets may insert breakpoints. */
9233 init_thread_list ();
9234 init_wait_for_inferior ();
9235 }
45280a52 9236
3405876a
PA
9237 /* vRun's success return is a stop reply. */
9238 stop_reply = run_worked ? rs->buf : NULL;
9239 add_current_inferior_and_thread (stop_reply);
c0a2216e 9240
2d717e4f
DJ
9241 /* Get updated offsets, if the stub uses qOffsets. */
9242 get_offsets ();
2d717e4f 9243}
c906108c 9244\f
c5aa993b 9245
b775012e
LM
9246/* Given a location's target info BP_TGT and the packet buffer BUF, output
9247 the list of conditions (in agent expression bytecode format), if any, the
9248 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9249 started from BUF and ended at BUF_END. */
b775012e
LM
9250
9251static int
9252remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9253 struct bp_target_info *bp_tgt, char *buf,
9254 char *buf_end)
b775012e
LM
9255{
9256 struct agent_expr *aexpr = NULL;
9257 int i, ix;
b775012e
LM
9258
9259 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9260 return 0;
9261
9262 buf += strlen (buf);
bba74b36 9263 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9264 buf++;
9265
9266 /* Send conditions to the target and free the vector. */
9267 for (ix = 0;
9268 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9269 ix++)
9270 {
bba74b36 9271 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
9272 buf += strlen (buf);
9273 for (i = 0; i < aexpr->len; ++i)
9274 buf = pack_hex_byte (buf, aexpr->buf[i]);
9275 *buf = '\0';
9276 }
b775012e
LM
9277 return 0;
9278}
9279
d3ce09f5
SS
9280static void
9281remote_add_target_side_commands (struct gdbarch *gdbarch,
9282 struct bp_target_info *bp_tgt, char *buf)
9283{
9284 struct agent_expr *aexpr = NULL;
9285 int i, ix;
9286
9287 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9288 return;
9289
9290 buf += strlen (buf);
9291
9292 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9293 buf += strlen (buf);
9294
9295 /* Concatenate all the agent expressions that are commands into the
9296 cmds parameter. */
9297 for (ix = 0;
9298 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9299 ix++)
9300 {
9301 sprintf (buf, "X%x,", aexpr->len);
9302 buf += strlen (buf);
9303 for (i = 0; i < aexpr->len; ++i)
9304 buf = pack_hex_byte (buf, aexpr->buf[i]);
9305 *buf = '\0';
9306 }
d3ce09f5
SS
9307}
9308
8181d85f
DJ
9309/* Insert a breakpoint. On targets that have software breakpoint
9310 support, we ask the remote target to do the work; on targets
9311 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9312
9313static int
3db08215
MM
9314remote_insert_breakpoint (struct target_ops *ops,
9315 struct gdbarch *gdbarch,
a6d9a66e 9316 struct bp_target_info *bp_tgt)
c906108c 9317{
d471ea57
AC
9318 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9319 If it succeeds, then set the support to PACKET_ENABLE. If it
9320 fails, and the user has explicitly requested the Z support then
23860348 9321 report an error, otherwise, mark it disabled and go on. */
802188a7 9322
4082afcc 9323 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9324 {
0d5ed153 9325 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9326 struct remote_state *rs;
bba74b36 9327 char *p, *endbuf;
7c0f6dcc 9328 int bpsize;
4fff2411 9329
28439a30
PA
9330 /* Make sure the remote is pointing at the right process, if
9331 necessary. */
9332 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9333 set_general_process ();
9334
a1dcb23a 9335 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
9336
9337 rs = get_remote_state ();
9338 p = rs->buf;
bba74b36 9339 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9340
96baa820
JM
9341 *(p++) = 'Z';
9342 *(p++) = '0';
9343 *(p++) = ',';
7c0f6dcc 9344 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9345 p += hexnumstr (p, addr);
bba74b36 9346 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 9347
efcc2da7 9348 if (remote_supports_cond_breakpoints (ops))
bba74b36 9349 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9350
78eff0ec 9351 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9352 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9353
6d820c5c
DJ
9354 putpkt (rs->buf);
9355 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9356
6d820c5c 9357 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9358 {
d471ea57
AC
9359 case PACKET_ERROR:
9360 return -1;
9361 case PACKET_OK:
7c0f6dcc
JL
9362 bp_tgt->placed_address = addr;
9363 bp_tgt->placed_size = bpsize;
d471ea57
AC
9364 return 0;
9365 case PACKET_UNKNOWN:
9366 break;
96baa820
JM
9367 }
9368 }
c906108c 9369
0000e5cc
PA
9370 /* If this breakpoint has target-side commands but this stub doesn't
9371 support Z0 packets, throw error. */
9372 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9373 throw_error (NOT_SUPPORTED_ERROR, _("\
9374Target doesn't support breakpoints that have target side commands."));
9375
3db08215 9376 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9377}
9378
9379static int
3db08215
MM
9380remote_remove_breakpoint (struct target_ops *ops,
9381 struct gdbarch *gdbarch,
a6d9a66e 9382 struct bp_target_info *bp_tgt)
c906108c 9383{
8181d85f 9384 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9385 struct remote_state *rs = get_remote_state ();
96baa820 9386
4082afcc 9387 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9388 {
6d820c5c 9389 char *p = rs->buf;
bba74b36 9390 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9391
28439a30
PA
9392 /* Make sure the remote is pointing at the right process, if
9393 necessary. */
9394 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9395 set_general_process ();
9396
96baa820
JM
9397 *(p++) = 'z';
9398 *(p++) = '0';
9399 *(p++) = ',';
9400
8181d85f
DJ
9401 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9402 p += hexnumstr (p, addr);
bba74b36 9403 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9404
6d820c5c
DJ
9405 putpkt (rs->buf);
9406 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9407
6d820c5c 9408 return (rs->buf[0] == 'E');
96baa820
JM
9409 }
9410
3db08215 9411 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9412}
9413
f486487f 9414static enum Z_packet_type
d471ea57
AC
9415watchpoint_to_Z_packet (int type)
9416{
9417 switch (type)
9418 {
9419 case hw_write:
bb858e6a 9420 return Z_PACKET_WRITE_WP;
d471ea57
AC
9421 break;
9422 case hw_read:
bb858e6a 9423 return Z_PACKET_READ_WP;
d471ea57
AC
9424 break;
9425 case hw_access:
bb858e6a 9426 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9427 break;
9428 default:
8e65ff28 9429 internal_error (__FILE__, __LINE__,
e2e0b3e5 9430 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9431 }
9432}
9433
3c3bea1c 9434static int
f486487f
SM
9435remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9436 enum target_hw_bp_type type, struct expression *cond)
96baa820 9437{
d01949b6 9438 struct remote_state *rs = get_remote_state ();
bba74b36 9439 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9440 char *p;
d471ea57 9441 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9442
4082afcc 9443 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9444 return 1;
802188a7 9445
28439a30
PA
9446 /* Make sure the remote is pointing at the right process, if
9447 necessary. */
9448 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9449 set_general_process ();
9450
bba74b36 9451 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9452 p = strchr (rs->buf, '\0');
96baa820
JM
9453 addr = remote_address_masked (addr);
9454 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9455 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9456
6d820c5c
DJ
9457 putpkt (rs->buf);
9458 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9459
6d820c5c 9460 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9461 {
9462 case PACKET_ERROR:
d471ea57 9463 return -1;
85d721b8
PA
9464 case PACKET_UNKNOWN:
9465 return 1;
d471ea57
AC
9466 case PACKET_OK:
9467 return 0;
9468 }
8e65ff28 9469 internal_error (__FILE__, __LINE__,
e2e0b3e5 9470 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9471}
9472
283002cf
MR
9473static int
9474remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9475 CORE_ADDR start, int length)
9476{
9477 CORE_ADDR diff = remote_address_masked (addr - start);
9478
9479 return diff < length;
9480}
9481
d471ea57 9482
3c3bea1c 9483static int
f486487f
SM
9484remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9485 enum target_hw_bp_type type, struct expression *cond)
96baa820 9486{
d01949b6 9487 struct remote_state *rs = get_remote_state ();
bba74b36 9488 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9489 char *p;
d471ea57
AC
9490 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9491
4082afcc 9492 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9493 return -1;
802188a7 9494
28439a30
PA
9495 /* Make sure the remote is pointing at the right process, if
9496 necessary. */
9497 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9498 set_general_process ();
9499
bba74b36 9500 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9501 p = strchr (rs->buf, '\0');
96baa820
JM
9502 addr = remote_address_masked (addr);
9503 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9504 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9505 putpkt (rs->buf);
9506 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9507
6d820c5c 9508 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9509 {
9510 case PACKET_ERROR:
9511 case PACKET_UNKNOWN:
9512 return -1;
9513 case PACKET_OK:
9514 return 0;
9515 }
8e65ff28 9516 internal_error (__FILE__, __LINE__,
e2e0b3e5 9517 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9518}
9519
3c3bea1c 9520
501eef12 9521int remote_hw_watchpoint_limit = -1;
480a3f21 9522int remote_hw_watchpoint_length_limit = -1;
501eef12 9523int remote_hw_breakpoint_limit = -1;
d471ea57 9524
480a3f21 9525static int
31568a15
TT
9526remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9527 CORE_ADDR addr, int len)
480a3f21
PW
9528{
9529 if (remote_hw_watchpoint_length_limit == 0)
9530 return 0;
9531 else if (remote_hw_watchpoint_length_limit < 0)
9532 return 1;
9533 else if (len <= remote_hw_watchpoint_length_limit)
9534 return 1;
9535 else
9536 return 0;
9537}
9538
b9362cc7 9539static int
5461485a 9540remote_check_watch_resources (struct target_ops *self,
f486487f 9541 enum bptype type, int cnt, int ot)
96baa820 9542{
3c3bea1c
GS
9543 if (type == bp_hardware_breakpoint)
9544 {
9545 if (remote_hw_breakpoint_limit == 0)
9546 return 0;
501eef12
AC
9547 else if (remote_hw_breakpoint_limit < 0)
9548 return 1;
3c3bea1c
GS
9549 else if (cnt <= remote_hw_breakpoint_limit)
9550 return 1;
9551 }
9552 else
9553 {
9554 if (remote_hw_watchpoint_limit == 0)
9555 return 0;
501eef12
AC
9556 else if (remote_hw_watchpoint_limit < 0)
9557 return 1;
3c3bea1c
GS
9558 else if (ot)
9559 return -1;
9560 else if (cnt <= remote_hw_watchpoint_limit)
9561 return 1;
9562 }
9563 return -1;
9564}
9565
f7e6eed5
PA
9566/* The to_stopped_by_sw_breakpoint method of target remote. */
9567
9568static int
9569remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9570{
799a2abe 9571 struct thread_info *thread = inferior_thread ();
f7e6eed5 9572
799a2abe
PA
9573 return (thread->priv != NULL
9574 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9575}
9576
9577/* The to_supports_stopped_by_sw_breakpoint method of target
9578 remote. */
9579
9580static int
9581remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9582{
f7e6eed5
PA
9583 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9584}
9585
9586/* The to_stopped_by_hw_breakpoint method of target remote. */
9587
9588static int
9589remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9590{
799a2abe 9591 struct thread_info *thread = inferior_thread ();
f7e6eed5 9592
799a2abe
PA
9593 return (thread->priv != NULL
9594 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9595}
9596
9597/* The to_supports_stopped_by_hw_breakpoint method of target
9598 remote. */
9599
9600static int
9601remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9602{
f7e6eed5
PA
9603 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9604}
9605
b9362cc7 9606static int
6a109b6b 9607remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9608{
799a2abe 9609 struct thread_info *thread = inferior_thread ();
ee154bee 9610
799a2abe
PA
9611 return (thread->priv != NULL
9612 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9613}
9614
4aa7a7f5
JJ
9615static int
9616remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9617{
799a2abe 9618 struct thread_info *thread = inferior_thread ();
a744cf53 9619
799a2abe
PA
9620 if (thread->priv != NULL
9621 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9622 {
799a2abe
PA
9623 *addr_p = thread->priv->watch_data_address;
9624 return 1;
4aa7a7f5
JJ
9625 }
9626
799a2abe 9627 return 0;
3c3bea1c
GS
9628}
9629
9630
9631static int
23a26771 9632remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9633 struct bp_target_info *bp_tgt)
3c3bea1c 9634{
0d5ed153 9635 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9636 struct remote_state *rs;
bba74b36 9637 char *p, *endbuf;
dd61ec5c 9638 char *message;
0d5ed153 9639 int bpsize;
802188a7 9640
c8189ed1 9641 /* The length field should be set to the size of a breakpoint
8181d85f 9642 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9643
0d5ed153 9644 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9645
4082afcc 9646 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9647 return -1;
2bc416ba 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
4fff2411
JZ
9654 rs = get_remote_state ();
9655 p = rs->buf;
bba74b36 9656 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9657
96baa820
JM
9658 *(p++) = 'Z';
9659 *(p++) = '1';
9660 *(p++) = ',';
802188a7 9661
0d5ed153 9662 addr = remote_address_masked (addr);
96baa820 9663 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9664 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9665
efcc2da7 9666 if (remote_supports_cond_breakpoints (self))
bba74b36 9667 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9668
78eff0ec 9669 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9670 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9671
6d820c5c
DJ
9672 putpkt (rs->buf);
9673 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9674
6d820c5c 9675 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9676 {
9677 case PACKET_ERROR:
dd61ec5c
MW
9678 if (rs->buf[1] == '.')
9679 {
9680 message = strchr (rs->buf + 2, '.');
9681 if (message)
0316657e 9682 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9683 }
9684 return -1;
d471ea57
AC
9685 case PACKET_UNKNOWN:
9686 return -1;
9687 case PACKET_OK:
0d5ed153
MR
9688 bp_tgt->placed_address = addr;
9689 bp_tgt->placed_size = bpsize;
d471ea57
AC
9690 return 0;
9691 }
8e65ff28 9692 internal_error (__FILE__, __LINE__,
e2e0b3e5 9693 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9694}
9695
d471ea57 9696
802188a7 9697static int
a64dc96c 9698remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9699 struct bp_target_info *bp_tgt)
96baa820 9700{
8181d85f 9701 CORE_ADDR addr;
d01949b6 9702 struct remote_state *rs = get_remote_state ();
6d820c5c 9703 char *p = rs->buf;
bba74b36 9704 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9705
4082afcc 9706 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9707 return -1;
802188a7 9708
28439a30
PA
9709 /* Make sure the remote is pointing at the right process, if
9710 necessary. */
9711 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9712 set_general_process ();
9713
96baa820
JM
9714 *(p++) = 'z';
9715 *(p++) = '1';
9716 *(p++) = ',';
802188a7 9717
8181d85f 9718 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9719 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9720 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9721
6d820c5c
DJ
9722 putpkt (rs->buf);
9723 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9724
6d820c5c 9725 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9726 {
9727 case PACKET_ERROR:
9728 case PACKET_UNKNOWN:
9729 return -1;
9730 case PACKET_OK:
9731 return 0;
9732 }
8e65ff28 9733 internal_error (__FILE__, __LINE__,
e2e0b3e5 9734 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9735}
96baa820 9736
4a5e7a5b
PA
9737/* Verify memory using the "qCRC:" request. */
9738
9739static int
9740remote_verify_memory (struct target_ops *ops,
9741 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9742{
9743 struct remote_state *rs = get_remote_state ();
9744 unsigned long host_crc, target_crc;
9745 char *tmp;
9746
936d2992
PA
9747 /* It doesn't make sense to use qCRC if the remote target is
9748 connected but not running. */
9749 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9750 {
9751 enum packet_result result;
28439a30 9752
936d2992
PA
9753 /* Make sure the remote is pointing at the right process. */
9754 set_general_process ();
4a5e7a5b 9755
936d2992
PA
9756 /* FIXME: assumes lma can fit into long. */
9757 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9758 (long) lma, (long) size);
9759 putpkt (rs->buf);
4a5e7a5b 9760
936d2992
PA
9761 /* Be clever; compute the host_crc before waiting for target
9762 reply. */
9763 host_crc = xcrc32 (data, size, 0xffffffff);
9764
9765 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9766
936d2992
PA
9767 result = packet_ok (rs->buf,
9768 &remote_protocol_packets[PACKET_qCRC]);
9769 if (result == PACKET_ERROR)
9770 return -1;
9771 else if (result == PACKET_OK)
9772 {
9773 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9774 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9775
936d2992
PA
9776 return (host_crc == target_crc);
9777 }
9778 }
4a5e7a5b 9779
936d2992 9780 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9781}
9782
c906108c
SS
9783/* compare-sections command
9784
9785 With no arguments, compares each loadable section in the exec bfd
9786 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9787 Useful for verifying the image on the target against the exec file. */
e514a9d6 9788
c906108c 9789static void
fba45db2 9790compare_sections_command (char *args, int from_tty)
c906108c
SS
9791{
9792 asection *s;
c906108c 9793 struct cleanup *old_chain;
948f8e3d 9794 gdb_byte *sectdata;
ce359b09 9795 const char *sectname;
c906108c
SS
9796 bfd_size_type size;
9797 bfd_vma lma;
9798 int matched = 0;
9799 int mismatched = 0;
4a5e7a5b 9800 int res;
95cf3b38 9801 int read_only = 0;
c906108c
SS
9802
9803 if (!exec_bfd)
8a3fe4f8 9804 error (_("command cannot be used without an exec file"));
c906108c 9805
28439a30
PA
9806 /* Make sure the remote is pointing at the right process. */
9807 set_general_process ();
9808
95cf3b38
DT
9809 if (args != NULL && strcmp (args, "-r") == 0)
9810 {
9811 read_only = 1;
9812 args = NULL;
9813 }
9814
c5aa993b 9815 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9816 {
9817 if (!(s->flags & SEC_LOAD))
0df8b418 9818 continue; /* Skip non-loadable section. */
c906108c 9819
95cf3b38
DT
9820 if (read_only && (s->flags & SEC_READONLY) == 0)
9821 continue; /* Skip writeable sections */
9822
2c500098 9823 size = bfd_get_section_size (s);
c906108c 9824 if (size == 0)
0df8b418 9825 continue; /* Skip zero-length section. */
c906108c 9826
ce359b09 9827 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9828 if (args && strcmp (args, sectname) != 0)
0df8b418 9829 continue; /* Not the section selected by user. */
c906108c 9830
0df8b418 9831 matched = 1; /* Do this section. */
c906108c 9832 lma = s->lma;
c906108c 9833
224c3ddb 9834 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9835 old_chain = make_cleanup (xfree, sectdata);
c906108c 9836 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9837
4a5e7a5b
PA
9838 res = target_verify_memory (sectdata, lma, size);
9839
9840 if (res == -1)
5af949e3 9841 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9842 paddress (target_gdbarch (), lma),
9843 paddress (target_gdbarch (), lma + size));
c906108c 9844
5af949e3 9845 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9846 paddress (target_gdbarch (), lma),
9847 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9848 if (res)
c906108c
SS
9849 printf_filtered ("matched.\n");
9850 else
c5aa993b
JM
9851 {
9852 printf_filtered ("MIS-MATCHED!\n");
9853 mismatched++;
9854 }
c906108c
SS
9855
9856 do_cleanups (old_chain);
9857 }
9858 if (mismatched > 0)
936d2992 9859 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9860the loaded file\n"));
c906108c 9861 if (args && !matched)
a3f17187 9862 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9863}
9864
0e7f50da
UW
9865/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9866 into remote target. The number of bytes written to the remote
9867 target is returned, or -1 for error. */
9868
9b409511 9869static enum target_xfer_status
0e7f50da
UW
9870remote_write_qxfer (struct target_ops *ops, const char *object_name,
9871 const char *annex, const gdb_byte *writebuf,
9b409511 9872 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9873 struct packet_config *packet)
9874{
9875 int i, buf_len;
9876 ULONGEST n;
0e7f50da
UW
9877 struct remote_state *rs = get_remote_state ();
9878 int max_size = get_memory_write_packet_size ();
9879
9880 if (packet->support == PACKET_DISABLE)
2ed4b548 9881 return TARGET_XFER_E_IO;
0e7f50da
UW
9882
9883 /* Insert header. */
9884 i = snprintf (rs->buf, max_size,
9885 "qXfer:%s:write:%s:%s:",
9886 object_name, annex ? annex : "",
9887 phex_nz (offset, sizeof offset));
9888 max_size -= (i + 1);
9889
9890 /* Escape as much data as fits into rs->buf. */
9891 buf_len = remote_escape_output
124e13d9 9892 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9893
9894 if (putpkt_binary (rs->buf, i + buf_len) < 0
9895 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9896 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9897 return TARGET_XFER_E_IO;
0e7f50da
UW
9898
9899 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9900
9901 *xfered_len = n;
9902 return TARGET_XFER_OK;
0e7f50da
UW
9903}
9904
0876f84a
DJ
9905/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9906 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9907 number of bytes read is returned, or 0 for EOF, or -1 for error.
9908 The number of bytes read may be less than LEN without indicating an
9909 EOF. PACKET is checked and updated to indicate whether the remote
9910 target supports this object. */
9911
9b409511 9912static enum target_xfer_status
0876f84a
DJ
9913remote_read_qxfer (struct target_ops *ops, const char *object_name,
9914 const char *annex,
9915 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9916 ULONGEST *xfered_len,
0876f84a
DJ
9917 struct packet_config *packet)
9918{
0876f84a 9919 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9920 LONGEST i, n, packet_len;
9921
9922 if (packet->support == PACKET_DISABLE)
2ed4b548 9923 return TARGET_XFER_E_IO;
0876f84a
DJ
9924
9925 /* Check whether we've cached an end-of-object packet that matches
9926 this request. */
8e88304f 9927 if (rs->finished_object)
0876f84a 9928 {
8e88304f
TT
9929 if (strcmp (object_name, rs->finished_object) == 0
9930 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9931 && offset == rs->finished_offset)
9b409511
YQ
9932 return TARGET_XFER_EOF;
9933
0876f84a
DJ
9934
9935 /* Otherwise, we're now reading something different. Discard
9936 the cache. */
8e88304f
TT
9937 xfree (rs->finished_object);
9938 xfree (rs->finished_annex);
9939 rs->finished_object = NULL;
9940 rs->finished_annex = NULL;
0876f84a
DJ
9941 }
9942
9943 /* Request only enough to fit in a single packet. The actual data
9944 may not, since we don't know how much of it will need to be escaped;
9945 the target is free to respond with slightly less data. We subtract
9946 five to account for the response type and the protocol frame. */
9947 n = min (get_remote_packet_size () - 5, len);
9948 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9949 object_name, annex ? annex : "",
9950 phex_nz (offset, sizeof offset),
9951 phex_nz (n, sizeof n));
9952 i = putpkt (rs->buf);
9953 if (i < 0)
2ed4b548 9954 return TARGET_XFER_E_IO;
0876f84a
DJ
9955
9956 rs->buf[0] = '\0';
9957 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9958 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9959 return TARGET_XFER_E_IO;
0876f84a
DJ
9960
9961 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9962 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9963
9964 /* 'm' means there is (or at least might be) more data after this
9965 batch. That does not make sense unless there's at least one byte
9966 of data in this reply. */
9967 if (rs->buf[0] == 'm' && packet_len == 1)
9968 error (_("Remote qXfer reply contained no data."));
9969
9970 /* Got some data. */
bc20a4af
PA
9971 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9972 packet_len - 1, readbuf, n);
0876f84a
DJ
9973
9974 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9975 or possibly empty. If we have the final block of a non-empty
9976 object, record this fact to bypass a subsequent partial read. */
9977 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9978 {
8e88304f
TT
9979 rs->finished_object = xstrdup (object_name);
9980 rs->finished_annex = xstrdup (annex ? annex : "");
9981 rs->finished_offset = offset + i;
0876f84a
DJ
9982 }
9983
9b409511
YQ
9984 if (i == 0)
9985 return TARGET_XFER_EOF;
9986 else
9987 {
9988 *xfered_len = i;
9989 return TARGET_XFER_OK;
9990 }
0876f84a
DJ
9991}
9992
9b409511 9993static enum target_xfer_status
4b8a223f 9994remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9995 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9996 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9997 ULONGEST *xfered_len)
c906108c 9998{
82f73884 9999 struct remote_state *rs;
c906108c 10000 int i;
6d820c5c 10001 char *p2;
1e3ff5ad 10002 char query_type;
124e13d9 10003 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 10004
e6e4e701 10005 set_remote_traceframe ();
82f73884
PA
10006 set_general_thread (inferior_ptid);
10007
10008 rs = get_remote_state ();
10009
b2182ed2 10010 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
10011 if (object == TARGET_OBJECT_MEMORY)
10012 {
2d717e4f
DJ
10013 /* If the remote target is connected but not running, we should
10014 pass this request down to a lower stratum (e.g. the executable
10015 file). */
10016 if (!target_has_execution)
9b409511 10017 return TARGET_XFER_EOF;
2d717e4f 10018
21e3b9b9 10019 if (writebuf != NULL)
124e13d9
SM
10020 return remote_write_bytes (offset, writebuf, len, unit_size,
10021 xfered_len);
21e3b9b9 10022 else
124e13d9
SM
10023 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10024 xfered_len);
21e3b9b9
DJ
10025 }
10026
0df8b418 10027 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10028 if (object == TARGET_OBJECT_SPU)
10029 {
10030 if (readbuf)
10031 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
10032 xfered_len, &remote_protocol_packets
10033 [PACKET_qXfer_spu_read]);
0e7f50da
UW
10034 else
10035 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
10036 xfered_len, &remote_protocol_packets
10037 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10038 }
10039
4aa995e1
PA
10040 /* Handle extra signal info using qxfer packets. */
10041 if (object == TARGET_OBJECT_SIGNAL_INFO)
10042 {
10043 if (readbuf)
10044 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 10045 xfered_len, &remote_protocol_packets
4aa995e1
PA
10046 [PACKET_qXfer_siginfo_read]);
10047 else
3e43a32a 10048 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 10049 writebuf, offset, len, xfered_len,
4aa995e1
PA
10050 &remote_protocol_packets
10051 [PACKET_qXfer_siginfo_write]);
10052 }
10053
0fb4aa4b
PA
10054 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10055 {
10056 if (readbuf)
3e43a32a 10057 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 10058 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10059 &remote_protocol_packets
10060 [PACKET_qXfer_statictrace_read]);
10061 else
2ed4b548 10062 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10063 }
10064
a76d924d
DJ
10065 /* Only handle flash writes. */
10066 if (writebuf != NULL)
10067 {
a76d924d
DJ
10068 switch (object)
10069 {
10070 case TARGET_OBJECT_FLASH:
9b409511
YQ
10071 return remote_flash_write (ops, offset, len, xfered_len,
10072 writebuf);
a76d924d
DJ
10073
10074 default:
2ed4b548 10075 return TARGET_XFER_E_IO;
a76d924d
DJ
10076 }
10077 }
4b8a223f 10078
1e3ff5ad
AC
10079 /* Map pre-existing objects onto letters. DO NOT do this for new
10080 objects!!! Instead specify new query packets. */
10081 switch (object)
c906108c 10082 {
1e3ff5ad
AC
10083 case TARGET_OBJECT_AVR:
10084 query_type = 'R';
10085 break;
802188a7
RM
10086
10087 case TARGET_OBJECT_AUXV:
0876f84a
DJ
10088 gdb_assert (annex == NULL);
10089 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 10090 xfered_len,
0876f84a 10091 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10092
23181151
DJ
10093 case TARGET_OBJECT_AVAILABLE_FEATURES:
10094 return remote_read_qxfer
9b409511 10095 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10096 &remote_protocol_packets[PACKET_qXfer_features]);
10097
cfa9d6d9
DJ
10098 case TARGET_OBJECT_LIBRARIES:
10099 return remote_read_qxfer
9b409511 10100 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10101 &remote_protocol_packets[PACKET_qXfer_libraries]);
10102
2268b414
JK
10103 case TARGET_OBJECT_LIBRARIES_SVR4:
10104 return remote_read_qxfer
9b409511 10105 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10106 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10107
fd79ecee
DJ
10108 case TARGET_OBJECT_MEMORY_MAP:
10109 gdb_assert (annex == NULL);
10110 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 10111 xfered_len,
fd79ecee
DJ
10112 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10113
07e059b5
VP
10114 case TARGET_OBJECT_OSDATA:
10115 /* Should only get here if we're connected. */
5d93a237 10116 gdb_assert (rs->remote_desc);
07e059b5 10117 return remote_read_qxfer
9b409511 10118 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10119 &remote_protocol_packets[PACKET_qXfer_osdata]);
10120
dc146f7c
VP
10121 case TARGET_OBJECT_THREADS:
10122 gdb_assert (annex == NULL);
10123 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10124 xfered_len,
dc146f7c
VP
10125 &remote_protocol_packets[PACKET_qXfer_threads]);
10126
b3b9301e
PA
10127 case TARGET_OBJECT_TRACEFRAME_INFO:
10128 gdb_assert (annex == NULL);
10129 return remote_read_qxfer
9b409511 10130 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10131 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10132
10133 case TARGET_OBJECT_FDPIC:
10134 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10135 xfered_len,
78d85199 10136 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10137
10138 case TARGET_OBJECT_OPENVMS_UIB:
10139 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10140 xfered_len,
169081d0
TG
10141 &remote_protocol_packets[PACKET_qXfer_uib]);
10142
9accd112
MM
10143 case TARGET_OBJECT_BTRACE:
10144 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10145 xfered_len,
9accd112
MM
10146 &remote_protocol_packets[PACKET_qXfer_btrace]);
10147
f4abbc16
MM
10148 case TARGET_OBJECT_BTRACE_CONF:
10149 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10150 len, xfered_len,
10151 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10152
c78fa86a
GB
10153 case TARGET_OBJECT_EXEC_FILE:
10154 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10155 len, xfered_len,
10156 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10157
1e3ff5ad 10158 default:
2ed4b548 10159 return TARGET_XFER_E_IO;
c906108c
SS
10160 }
10161
0df8b418 10162 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10163 large enough let the caller deal with it. */
ea9c271d 10164 if (len < get_remote_packet_size ())
2ed4b548 10165 return TARGET_XFER_E_IO;
ea9c271d 10166 len = get_remote_packet_size ();
1e3ff5ad 10167
23860348 10168 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10169 if (!rs->remote_desc)
8a3fe4f8 10170 error (_("remote query is only available after target open"));
c906108c 10171
1e3ff5ad 10172 gdb_assert (annex != NULL);
4b8a223f 10173 gdb_assert (readbuf != NULL);
c906108c 10174
6d820c5c 10175 p2 = rs->buf;
c906108c
SS
10176 *p2++ = 'q';
10177 *p2++ = query_type;
10178
23860348
MS
10179 /* We used one buffer char for the remote protocol q command and
10180 another for the query type. As the remote protocol encapsulation
10181 uses 4 chars plus one extra in case we are debugging
10182 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10183 string. */
c906108c 10184 i = 0;
ea9c271d 10185 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10186 {
1e3ff5ad
AC
10187 /* Bad caller may have sent forbidden characters. */
10188 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10189 *p2++ = annex[i];
c906108c
SS
10190 i++;
10191 }
1e3ff5ad
AC
10192 *p2 = '\0';
10193 gdb_assert (annex[i] == '\0');
c906108c 10194
6d820c5c 10195 i = putpkt (rs->buf);
c5aa993b 10196 if (i < 0)
2ed4b548 10197 return TARGET_XFER_E_IO;
c906108c 10198
6d820c5c
DJ
10199 getpkt (&rs->buf, &rs->buf_size, 0);
10200 strcpy ((char *) readbuf, rs->buf);
c906108c 10201
9b409511
YQ
10202 *xfered_len = strlen ((char *) readbuf);
10203 return TARGET_XFER_OK;
c906108c
SS
10204}
10205
08388c79
DE
10206static int
10207remote_search_memory (struct target_ops* ops,
10208 CORE_ADDR start_addr, ULONGEST search_space_len,
10209 const gdb_byte *pattern, ULONGEST pattern_len,
10210 CORE_ADDR *found_addrp)
10211{
f5656ead 10212 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10213 struct remote_state *rs = get_remote_state ();
10214 int max_size = get_memory_write_packet_size ();
10215 struct packet_config *packet =
10216 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10217 /* Number of packet bytes used to encode the pattern;
10218 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10219 int escaped_pattern_len;
0df8b418 10220 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10221 int used_pattern_len;
10222 int i;
10223 int found;
10224 ULONGEST found_addr;
10225
10226 /* Don't go to the target if we don't have to.
10227 This is done before checking packet->support to avoid the possibility that
10228 a success for this edge case means the facility works in general. */
10229 if (pattern_len > search_space_len)
10230 return 0;
10231 if (pattern_len == 0)
10232 {
10233 *found_addrp = start_addr;
10234 return 1;
10235 }
10236
10237 /* If we already know the packet isn't supported, fall back to the simple
10238 way of searching memory. */
10239
4082afcc 10240 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10241 {
10242 /* Target doesn't provided special support, fall back and use the
10243 standard support (copy memory and do the search here). */
10244 return simple_search_memory (ops, start_addr, search_space_len,
10245 pattern, pattern_len, found_addrp);
10246 }
10247
28439a30
PA
10248 /* Make sure the remote is pointing at the right process. */
10249 set_general_process ();
10250
08388c79
DE
10251 /* Insert header. */
10252 i = snprintf (rs->buf, max_size,
10253 "qSearch:memory:%s;%s;",
5af949e3 10254 phex_nz (start_addr, addr_size),
08388c79
DE
10255 phex_nz (search_space_len, sizeof (search_space_len)));
10256 max_size -= (i + 1);
10257
10258 /* Escape as much data as fits into rs->buf. */
10259 escaped_pattern_len =
124e13d9 10260 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10261 &used_pattern_len, max_size);
10262
10263 /* Bail if the pattern is too large. */
10264 if (used_pattern_len != pattern_len)
9b20d036 10265 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10266
10267 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10268 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10269 || packet_ok (rs->buf, packet) != PACKET_OK)
10270 {
10271 /* The request may not have worked because the command is not
10272 supported. If so, fall back to the simple way. */
10273 if (packet->support == PACKET_DISABLE)
10274 {
10275 return simple_search_memory (ops, start_addr, search_space_len,
10276 pattern, pattern_len, found_addrp);
10277 }
10278 return -1;
10279 }
10280
10281 if (rs->buf[0] == '0')
10282 found = 0;
10283 else if (rs->buf[0] == '1')
10284 {
10285 found = 1;
10286 if (rs->buf[1] != ',')
10e0fa18 10287 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10288 unpack_varlen_hex (rs->buf + 2, &found_addr);
10289 *found_addrp = found_addr;
10290 }
10291 else
10e0fa18 10292 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10293
10294 return found;
10295}
10296
96baa820 10297static void
a30bf1f1 10298remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10299 struct ui_file *outbuf)
96baa820 10300{
d01949b6 10301 struct remote_state *rs = get_remote_state ();
2e9f7625 10302 char *p = rs->buf;
96baa820 10303
5d93a237 10304 if (!rs->remote_desc)
8a3fe4f8 10305 error (_("remote rcmd is only available after target open"));
96baa820 10306
23860348 10307 /* Send a NULL command across as an empty command. */
7be570e7
JM
10308 if (command == NULL)
10309 command = "";
10310
23860348 10311 /* The query prefix. */
2e9f7625
DJ
10312 strcpy (rs->buf, "qRcmd,");
10313 p = strchr (rs->buf, '\0');
96baa820 10314
3e43a32a
MS
10315 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10316 > get_remote_packet_size ())
8a3fe4f8 10317 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10318
23860348 10319 /* Encode the actual command. */
a30bf1f1 10320 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10321
6d820c5c 10322 if (putpkt (rs->buf) < 0)
8a3fe4f8 10323 error (_("Communication problem with target."));
96baa820
JM
10324
10325 /* get/display the response */
10326 while (1)
10327 {
2e9f7625
DJ
10328 char *buf;
10329
00bf0b85 10330 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10331 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10332 rs->buf[0] = '\0';
5b37825d
PW
10333 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10334 {
10335 /* Timeout. Continue to (try to) read responses.
10336 This is better than stopping with an error, assuming the stub
10337 is still executing the (long) monitor command.
10338 If needed, the user can interrupt gdb using C-c, obtaining
10339 an effect similar to stop on timeout. */
10340 continue;
10341 }
2e9f7625 10342 buf = rs->buf;
96baa820 10343 if (buf[0] == '\0')
8a3fe4f8 10344 error (_("Target does not support this command."));
96baa820
JM
10345 if (buf[0] == 'O' && buf[1] != 'K')
10346 {
23860348 10347 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10348 continue;
10349 }
10350 if (strcmp (buf, "OK") == 0)
10351 break;
7be570e7
JM
10352 if (strlen (buf) == 3 && buf[0] == 'E'
10353 && isdigit (buf[1]) && isdigit (buf[2]))
10354 {
8a3fe4f8 10355 error (_("Protocol error with Rcmd"));
7be570e7 10356 }
96baa820
JM
10357 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10358 {
10359 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10360
96baa820
JM
10361 fputc_unfiltered (c, outbuf);
10362 }
10363 break;
10364 }
10365}
10366
fd79ecee
DJ
10367static VEC(mem_region_s) *
10368remote_memory_map (struct target_ops *ops)
10369{
10370 VEC(mem_region_s) *result = NULL;
10371 char *text = target_read_stralloc (&current_target,
10372 TARGET_OBJECT_MEMORY_MAP, NULL);
10373
10374 if (text)
10375 {
10376 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10377
fd79ecee
DJ
10378 result = parse_memory_map (text);
10379 do_cleanups (back_to);
10380 }
10381
10382 return result;
10383}
10384
c906108c 10385static void
fba45db2 10386packet_command (char *args, int from_tty)
c906108c 10387{
d01949b6 10388 struct remote_state *rs = get_remote_state ();
c906108c 10389
5d93a237 10390 if (!rs->remote_desc)
8a3fe4f8 10391 error (_("command can only be used with remote target"));
c906108c 10392
c5aa993b 10393 if (!args)
8a3fe4f8 10394 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10395
10396 puts_filtered ("sending: ");
10397 print_packet (args);
10398 puts_filtered ("\n");
10399 putpkt (args);
10400
6d820c5c 10401 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10402 puts_filtered ("received: ");
6d820c5c 10403 print_packet (rs->buf);
c906108c
SS
10404 puts_filtered ("\n");
10405}
10406
10407#if 0
23860348 10408/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10409
a14ed312 10410static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10411
a14ed312 10412static void threadset_test_cmd (char *cmd, int tty);
c906108c 10413
a14ed312 10414static void threadalive_test (char *cmd, int tty);
c906108c 10415
a14ed312 10416static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10417
23860348 10418int get_and_display_threadinfo (threadref *ref);
c906108c 10419
a14ed312 10420static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10421
23860348 10422static int thread_display_step (threadref *ref, void *context);
c906108c 10423
a14ed312 10424static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10425
a14ed312 10426static void init_remote_threadtests (void);
c906108c 10427
23860348 10428#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10429
10430static void
fba45db2 10431threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10432{
10433 int sample_thread = SAMPLE_THREAD;
10434
a3f17187 10435 printf_filtered (_("Remote threadset test\n"));
79d7f229 10436 set_general_thread (sample_thread);
c906108c
SS
10437}
10438
10439
10440static void
fba45db2 10441threadalive_test (char *cmd, int tty)
c906108c
SS
10442{
10443 int sample_thread = SAMPLE_THREAD;
79d7f229 10444 int pid = ptid_get_pid (inferior_ptid);
ba348170 10445 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10446
79d7f229 10447 if (remote_thread_alive (ptid))
c906108c
SS
10448 printf_filtered ("PASS: Thread alive test\n");
10449 else
10450 printf_filtered ("FAIL: Thread alive test\n");
10451}
10452
23860348 10453void output_threadid (char *title, threadref *ref);
c906108c
SS
10454
10455void
fba45db2 10456output_threadid (char *title, threadref *ref)
c906108c
SS
10457{
10458 char hexid[20];
10459
23860348 10460 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10461 hexid[16] = 0;
10462 printf_filtered ("%s %s\n", title, (&hexid[0]));
10463}
10464
10465static void
fba45db2 10466threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10467{
10468 int startflag = 1;
10469 threadref nextthread;
10470 int done, result_count;
10471 threadref threadlist[3];
10472
10473 printf_filtered ("Remote Threadlist test\n");
10474 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10475 &result_count, &threadlist[0]))
10476 printf_filtered ("FAIL: threadlist test\n");
10477 else
10478 {
10479 threadref *scan = threadlist;
10480 threadref *limit = scan + result_count;
10481
10482 while (scan < limit)
10483 output_threadid (" thread ", scan++);
10484 }
10485}
10486
10487void
fba45db2 10488display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10489{
10490 output_threadid ("Threadid: ", &info->threadid);
10491 printf_filtered ("Name: %s\n ", info->shortname);
10492 printf_filtered ("State: %s\n", info->display);
10493 printf_filtered ("other: %s\n\n", info->more_display);
10494}
10495
10496int
fba45db2 10497get_and_display_threadinfo (threadref *ref)
c906108c
SS
10498{
10499 int result;
10500 int set;
10501 struct gdb_ext_thread_info threadinfo;
10502
10503 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10504 | TAG_MOREDISPLAY | TAG_DISPLAY;
10505 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10506 display_thread_info (&threadinfo);
10507 return result;
10508}
10509
10510static void
fba45db2 10511threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10512{
10513 int athread = SAMPLE_THREAD;
10514 threadref thread;
10515 int set;
10516
10517 int_to_threadref (&thread, athread);
10518 printf_filtered ("Remote Threadinfo test\n");
10519 if (!get_and_display_threadinfo (&thread))
10520 printf_filtered ("FAIL cannot get thread info\n");
10521}
10522
10523static int
fba45db2 10524thread_display_step (threadref *ref, void *context)
c906108c
SS
10525{
10526 /* output_threadid(" threadstep ",ref); *//* simple test */
10527 return get_and_display_threadinfo (ref);
10528}
10529
10530static void
fba45db2 10531threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10532{
10533 printf_filtered ("Remote Threadlist update test\n");
10534 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10535}
10536
10537static void
10538init_remote_threadtests (void)
10539{
3e43a32a
MS
10540 add_com ("tlist", class_obscure, threadlist_test_cmd,
10541 _("Fetch and print the remote list of "
10542 "thread identifiers, one pkt only"));
c906108c 10543 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10544 _("Fetch and display info about one thread"));
c906108c 10545 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10546 _("Test setting to a different thread"));
c906108c 10547 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10548 _("Iterate through updating all remote thread info"));
c906108c 10549 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10550 _(" Remote thread alive test "));
c906108c
SS
10551}
10552
10553#endif /* 0 */
10554
f3fb8c85
MS
10555/* Convert a thread ID to a string. Returns the string in a static
10556 buffer. */
10557
10558static char *
117de6a9 10559remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10560{
79d7f229 10561 static char buf[64];
82f73884 10562 struct remote_state *rs = get_remote_state ();
f3fb8c85 10563
7cee1e54
PA
10564 if (ptid_equal (ptid, null_ptid))
10565 return normal_pid_to_str (ptid);
10566 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10567 {
10568 /* Printing an inferior target id. */
10569
10570 /* When multi-process extensions are off, there's no way in the
10571 remote protocol to know the remote process id, if there's any
10572 at all. There's one exception --- when we're connected with
10573 target extended-remote, and we manually attached to a process
10574 with "attach PID". We don't record anywhere a flag that
10575 allows us to distinguish that case from the case of
10576 connecting with extended-remote and the stub already being
10577 attached to a process, and reporting yes to qAttached, hence
10578 no smart special casing here. */
10579 if (!remote_multi_process_p (rs))
10580 {
10581 xsnprintf (buf, sizeof buf, "Remote target");
10582 return buf;
10583 }
10584
10585 return normal_pid_to_str (ptid);
82f73884 10586 }
ecd0ada5 10587 else
79d7f229 10588 {
ecd0ada5
PA
10589 if (ptid_equal (magic_null_ptid, ptid))
10590 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 10591 else if (remote_multi_process_p (rs))
de0d863e
DB
10592 if (ptid_get_lwp (ptid) == 0)
10593 return normal_pid_to_str (ptid);
10594 else
10595 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10596 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10597 else
10598 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10599 ptid_get_lwp (ptid));
79d7f229
PA
10600 return buf;
10601 }
f3fb8c85
MS
10602}
10603
38691318
KB
10604/* Get the address of the thread local variable in OBJFILE which is
10605 stored at OFFSET within the thread local storage for thread PTID. */
10606
10607static CORE_ADDR
117de6a9
PA
10608remote_get_thread_local_address (struct target_ops *ops,
10609 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10610{
4082afcc 10611 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10612 {
10613 struct remote_state *rs = get_remote_state ();
6d820c5c 10614 char *p = rs->buf;
82f73884 10615 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10616 enum packet_result result;
38691318
KB
10617
10618 strcpy (p, "qGetTLSAddr:");
10619 p += strlen (p);
82f73884 10620 p = write_ptid (p, endp, ptid);
38691318
KB
10621 *p++ = ',';
10622 p += hexnumstr (p, offset);
10623 *p++ = ',';
10624 p += hexnumstr (p, lm);
10625 *p++ = '\0';
10626
6d820c5c
DJ
10627 putpkt (rs->buf);
10628 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10629 result = packet_ok (rs->buf,
10630 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10631 if (result == PACKET_OK)
38691318
KB
10632 {
10633 ULONGEST result;
10634
6d820c5c 10635 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10636 return result;
10637 }
571dd617 10638 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10639 throw_error (TLS_GENERIC_ERROR,
10640 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10641 else
109c3e39
AC
10642 throw_error (TLS_GENERIC_ERROR,
10643 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10644 }
10645 else
109c3e39
AC
10646 throw_error (TLS_GENERIC_ERROR,
10647 _("TLS not supported or disabled on this target"));
38691318
KB
10648 /* Not reached. */
10649 return 0;
10650}
10651
711e434b
PM
10652/* Provide thread local base, i.e. Thread Information Block address.
10653 Returns 1 if ptid is found and thread_local_base is non zero. */
10654
70221824 10655static int
bd7ae0f5 10656remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10657{
4082afcc 10658 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10659 {
10660 struct remote_state *rs = get_remote_state ();
10661 char *p = rs->buf;
10662 char *endp = rs->buf + get_remote_packet_size ();
10663 enum packet_result result;
10664
10665 strcpy (p, "qGetTIBAddr:");
10666 p += strlen (p);
10667 p = write_ptid (p, endp, ptid);
10668 *p++ = '\0';
10669
10670 putpkt (rs->buf);
10671 getpkt (&rs->buf, &rs->buf_size, 0);
10672 result = packet_ok (rs->buf,
10673 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10674 if (result == PACKET_OK)
10675 {
10676 ULONGEST result;
10677
10678 unpack_varlen_hex (rs->buf, &result);
10679 if (addr)
10680 *addr = (CORE_ADDR) result;
10681 return 1;
10682 }
10683 else if (result == PACKET_UNKNOWN)
10684 error (_("Remote target doesn't support qGetTIBAddr packet"));
10685 else
10686 error (_("Remote target failed to process qGetTIBAddr request"));
10687 }
10688 else
10689 error (_("qGetTIBAddr not supported or disabled on this target"));
10690 /* Not reached. */
10691 return 0;
10692}
10693
29709017
DJ
10694/* Support for inferring a target description based on the current
10695 architecture and the size of a 'g' packet. While the 'g' packet
10696 can have any size (since optional registers can be left off the
10697 end), some sizes are easily recognizable given knowledge of the
10698 approximate architecture. */
10699
10700struct remote_g_packet_guess
10701{
10702 int bytes;
10703 const struct target_desc *tdesc;
10704};
10705typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10706DEF_VEC_O(remote_g_packet_guess_s);
10707
10708struct remote_g_packet_data
10709{
10710 VEC(remote_g_packet_guess_s) *guesses;
10711};
10712
10713static struct gdbarch_data *remote_g_packet_data_handle;
10714
10715static void *
10716remote_g_packet_data_init (struct obstack *obstack)
10717{
10718 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10719}
10720
10721void
10722register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10723 const struct target_desc *tdesc)
10724{
10725 struct remote_g_packet_data *data
19ba03f4
SM
10726 = ((struct remote_g_packet_data *)
10727 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10728 struct remote_g_packet_guess new_guess, *guess;
10729 int ix;
10730
10731 gdb_assert (tdesc != NULL);
10732
10733 for (ix = 0;
10734 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10735 ix++)
10736 if (guess->bytes == bytes)
10737 internal_error (__FILE__, __LINE__,
9b20d036 10738 _("Duplicate g packet description added for size %d"),
29709017
DJ
10739 bytes);
10740
10741 new_guess.bytes = bytes;
10742 new_guess.tdesc = tdesc;
10743 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10744}
10745
d962ef82
DJ
10746/* Return 1 if remote_read_description would do anything on this target
10747 and architecture, 0 otherwise. */
10748
10749static int
10750remote_read_description_p (struct target_ops *target)
10751{
10752 struct remote_g_packet_data *data
19ba03f4
SM
10753 = ((struct remote_g_packet_data *)
10754 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10755
10756 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10757 return 1;
10758
10759 return 0;
10760}
10761
29709017
DJ
10762static const struct target_desc *
10763remote_read_description (struct target_ops *target)
10764{
10765 struct remote_g_packet_data *data
19ba03f4
SM
10766 = ((struct remote_g_packet_data *)
10767 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10768
d962ef82
DJ
10769 /* Do not try this during initial connection, when we do not know
10770 whether there is a running but stopped thread. */
10771 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10772 return target->beneath->to_read_description (target->beneath);
d962ef82 10773
29709017
DJ
10774 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10775 {
10776 struct remote_g_packet_guess *guess;
10777 int ix;
10778 int bytes = send_g_packet ();
10779
10780 for (ix = 0;
10781 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10782 ix++)
10783 if (guess->bytes == bytes)
10784 return guess->tdesc;
10785
10786 /* We discard the g packet. A minor optimization would be to
10787 hold on to it, and fill the register cache once we have selected
10788 an architecture, but it's too tricky to do safely. */
10789 }
10790
2117c711 10791 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10792}
10793
a6b151f1
DJ
10794/* Remote file transfer support. This is host-initiated I/O, not
10795 target-initiated; for target-initiated, see remote-fileio.c. */
10796
10797/* If *LEFT is at least the length of STRING, copy STRING to
10798 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10799 decrease *LEFT. Otherwise raise an error. */
10800
10801static void
10802remote_buffer_add_string (char **buffer, int *left, char *string)
10803{
10804 int len = strlen (string);
10805
10806 if (len > *left)
10807 error (_("Packet too long for target."));
10808
10809 memcpy (*buffer, string, len);
10810 *buffer += len;
10811 *left -= len;
10812
10813 /* NUL-terminate the buffer as a convenience, if there is
10814 room. */
10815 if (*left)
10816 **buffer = '\0';
10817}
10818
10819/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10820 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10821 decrease *LEFT. Otherwise raise an error. */
10822
10823static void
10824remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10825 int len)
10826{
10827 if (2 * len > *left)
10828 error (_("Packet too long for target."));
10829
10830 bin2hex (bytes, *buffer, len);
10831 *buffer += 2 * len;
10832 *left -= 2 * len;
10833
10834 /* NUL-terminate the buffer as a convenience, if there is
10835 room. */
10836 if (*left)
10837 **buffer = '\0';
10838}
10839
10840/* If *LEFT is large enough, convert VALUE to hex and add it to
10841 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10842 decrease *LEFT. Otherwise raise an error. */
10843
10844static void
10845remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10846{
10847 int len = hexnumlen (value);
10848
10849 if (len > *left)
10850 error (_("Packet too long for target."));
10851
10852 hexnumstr (*buffer, value);
10853 *buffer += len;
10854 *left -= len;
10855
10856 /* NUL-terminate the buffer as a convenience, if there is
10857 room. */
10858 if (*left)
10859 **buffer = '\0';
10860}
10861
10862/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10863 value, *REMOTE_ERRNO to the remote error number or zero if none
10864 was included, and *ATTACHMENT to point to the start of the annex
10865 if any. The length of the packet isn't needed here; there may
10866 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10867
10868 Return 0 if the packet could be parsed, -1 if it could not. If
10869 -1 is returned, the other variables may not be initialized. */
10870
10871static int
10872remote_hostio_parse_result (char *buffer, int *retcode,
10873 int *remote_errno, char **attachment)
10874{
10875 char *p, *p2;
10876
10877 *remote_errno = 0;
10878 *attachment = NULL;
10879
10880 if (buffer[0] != 'F')
10881 return -1;
10882
10883 errno = 0;
10884 *retcode = strtol (&buffer[1], &p, 16);
10885 if (errno != 0 || p == &buffer[1])
10886 return -1;
10887
10888 /* Check for ",errno". */
10889 if (*p == ',')
10890 {
10891 errno = 0;
10892 *remote_errno = strtol (p + 1, &p2, 16);
10893 if (errno != 0 || p + 1 == p2)
10894 return -1;
10895 p = p2;
10896 }
10897
10898 /* Check for ";attachment". If there is no attachment, the
10899 packet should end here. */
10900 if (*p == ';')
10901 {
10902 *attachment = p + 1;
10903 return 0;
10904 }
10905 else if (*p == '\0')
10906 return 0;
10907 else
10908 return -1;
10909}
10910
10911/* Send a prepared I/O packet to the target and read its response.
10912 The prepared packet is in the global RS->BUF before this function
10913 is called, and the answer is there when we return.
10914
10915 COMMAND_BYTES is the length of the request to send, which may include
10916 binary data. WHICH_PACKET is the packet configuration to check
10917 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10918 is set to the error number and -1 is returned. Otherwise the value
10919 returned by the function is returned.
10920
10921 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10922 attachment is expected; an error will be reported if there's a
10923 mismatch. If one is found, *ATTACHMENT will be set to point into
10924 the packet buffer and *ATTACHMENT_LEN will be set to the
10925 attachment's length. */
10926
10927static int
10928remote_hostio_send_command (int command_bytes, int which_packet,
10929 int *remote_errno, char **attachment,
10930 int *attachment_len)
10931{
10932 struct remote_state *rs = get_remote_state ();
10933 int ret, bytes_read;
10934 char *attachment_tmp;
10935
5d93a237 10936 if (!rs->remote_desc
4082afcc 10937 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10938 {
10939 *remote_errno = FILEIO_ENOSYS;
10940 return -1;
10941 }
10942
10943 putpkt_binary (rs->buf, command_bytes);
10944 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10945
10946 /* If it timed out, something is wrong. Don't try to parse the
10947 buffer. */
10948 if (bytes_read < 0)
10949 {
10950 *remote_errno = FILEIO_EINVAL;
10951 return -1;
10952 }
10953
10954 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10955 {
10956 case PACKET_ERROR:
10957 *remote_errno = FILEIO_EINVAL;
10958 return -1;
10959 case PACKET_UNKNOWN:
10960 *remote_errno = FILEIO_ENOSYS;
10961 return -1;
10962 case PACKET_OK:
10963 break;
10964 }
10965
10966 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10967 &attachment_tmp))
10968 {
10969 *remote_errno = FILEIO_EINVAL;
10970 return -1;
10971 }
10972
10973 /* Make sure we saw an attachment if and only if we expected one. */
10974 if ((attachment_tmp == NULL && attachment != NULL)
10975 || (attachment_tmp != NULL && attachment == NULL))
10976 {
10977 *remote_errno = FILEIO_EINVAL;
10978 return -1;
10979 }
10980
10981 /* If an attachment was found, it must point into the packet buffer;
10982 work out how many bytes there were. */
10983 if (attachment_tmp != NULL)
10984 {
10985 *attachment = attachment_tmp;
10986 *attachment_len = bytes_read - (*attachment - rs->buf);
10987 }
10988
10989 return ret;
10990}
10991
80152258
PA
10992/* Invalidate the readahead cache. */
10993
10994static void
10995readahead_cache_invalidate (void)
10996{
10997 struct remote_state *rs = get_remote_state ();
10998
10999 rs->readahead_cache.fd = -1;
11000}
11001
11002/* Invalidate the readahead cache if it is holding data for FD. */
11003
11004static void
11005readahead_cache_invalidate_fd (int fd)
11006{
11007 struct remote_state *rs = get_remote_state ();
11008
11009 if (rs->readahead_cache.fd == fd)
11010 rs->readahead_cache.fd = -1;
11011}
11012
15a201c8
GB
11013/* Set the filesystem remote_hostio functions that take FILENAME
11014 arguments will use. Return 0 on success, or -1 if an error
11015 occurs (and set *REMOTE_ERRNO). */
11016
11017static int
11018remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11019{
11020 struct remote_state *rs = get_remote_state ();
11021 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11022 char *p = rs->buf;
11023 int left = get_remote_packet_size () - 1;
11024 char arg[9];
11025 int ret;
11026
11027 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11028 return 0;
11029
11030 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11031 return 0;
11032
11033 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11034
11035 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11036 remote_buffer_add_string (&p, &left, arg);
11037
11038 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11039 remote_errno, NULL, NULL);
11040
11041 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11042 return 0;
11043
11044 if (ret == 0)
11045 rs->fs_pid = required_pid;
11046
11047 return ret;
11048}
11049
12e2a5fd 11050/* Implementation of to_fileio_open. */
a6b151f1
DJ
11051
11052static int
cd897586 11053remote_hostio_open (struct target_ops *self,
07c138c8 11054 struct inferior *inf, const char *filename,
4313b8c0
GB
11055 int flags, int mode, int warn_if_slow,
11056 int *remote_errno)
a6b151f1
DJ
11057{
11058 struct remote_state *rs = get_remote_state ();
11059 char *p = rs->buf;
11060 int left = get_remote_packet_size () - 1;
11061
4313b8c0
GB
11062 if (warn_if_slow)
11063 {
11064 static int warning_issued = 0;
11065
11066 printf_unfiltered (_("Reading %s from remote target...\n"),
11067 filename);
11068
11069 if (!warning_issued)
11070 {
11071 warning (_("File transfers from remote targets can be slow."
11072 " Use \"set sysroot\" to access files locally"
11073 " instead."));
11074 warning_issued = 1;
11075 }
11076 }
11077
15a201c8
GB
11078 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11079 return -1;
11080
a6b151f1
DJ
11081 remote_buffer_add_string (&p, &left, "vFile:open:");
11082
11083 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11084 strlen (filename));
11085 remote_buffer_add_string (&p, &left, ",");
11086
11087 remote_buffer_add_int (&p, &left, flags);
11088 remote_buffer_add_string (&p, &left, ",");
11089
11090 remote_buffer_add_int (&p, &left, mode);
11091
11092 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11093 remote_errno, NULL, NULL);
11094}
11095
12e2a5fd 11096/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11097
11098static int
0d866f62
TT
11099remote_hostio_pwrite (struct target_ops *self,
11100 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11101 ULONGEST offset, int *remote_errno)
11102{
11103 struct remote_state *rs = get_remote_state ();
11104 char *p = rs->buf;
11105 int left = get_remote_packet_size ();
11106 int out_len;
11107
80152258
PA
11108 readahead_cache_invalidate_fd (fd);
11109
a6b151f1
DJ
11110 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11111
11112 remote_buffer_add_int (&p, &left, fd);
11113 remote_buffer_add_string (&p, &left, ",");
11114
11115 remote_buffer_add_int (&p, &left, offset);
11116 remote_buffer_add_string (&p, &left, ",");
11117
124e13d9 11118 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11119 get_remote_packet_size () - (p - rs->buf));
11120
11121 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11122 remote_errno, NULL, NULL);
11123}
11124
80152258
PA
11125/* Helper for the implementation of to_fileio_pread. Read the file
11126 from the remote side with vFile:pread. */
a6b151f1
DJ
11127
11128static int
80152258
PA
11129remote_hostio_pread_vFile (struct target_ops *self,
11130 int fd, gdb_byte *read_buf, int len,
11131 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11132{
11133 struct remote_state *rs = get_remote_state ();
11134 char *p = rs->buf;
11135 char *attachment;
11136 int left = get_remote_packet_size ();
11137 int ret, attachment_len;
11138 int read_len;
11139
11140 remote_buffer_add_string (&p, &left, "vFile:pread:");
11141
11142 remote_buffer_add_int (&p, &left, fd);
11143 remote_buffer_add_string (&p, &left, ",");
11144
11145 remote_buffer_add_int (&p, &left, len);
11146 remote_buffer_add_string (&p, &left, ",");
11147
11148 remote_buffer_add_int (&p, &left, offset);
11149
11150 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11151 remote_errno, &attachment,
11152 &attachment_len);
11153
11154 if (ret < 0)
11155 return ret;
11156
bc20a4af 11157 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11158 read_buf, len);
11159 if (read_len != ret)
11160 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11161
11162 return ret;
11163}
11164
80152258
PA
11165/* Serve pread from the readahead cache. Returns number of bytes
11166 read, or 0 if the request can't be served from the cache. */
11167
11168static int
11169remote_hostio_pread_from_cache (struct remote_state *rs,
11170 int fd, gdb_byte *read_buf, size_t len,
11171 ULONGEST offset)
11172{
11173 struct readahead_cache *cache = &rs->readahead_cache;
11174
11175 if (cache->fd == fd
11176 && cache->offset <= offset
11177 && offset < cache->offset + cache->bufsize)
11178 {
11179 ULONGEST max = cache->offset + cache->bufsize;
11180
11181 if (offset + len > max)
11182 len = max - offset;
11183
11184 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11185 return len;
11186 }
11187
11188 return 0;
11189}
11190
11191/* Implementation of to_fileio_pread. */
11192
11193static int
11194remote_hostio_pread (struct target_ops *self,
11195 int fd, gdb_byte *read_buf, int len,
11196 ULONGEST offset, int *remote_errno)
11197{
11198 int ret;
11199 struct remote_state *rs = get_remote_state ();
11200 struct readahead_cache *cache = &rs->readahead_cache;
11201
11202 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11203 if (ret > 0)
11204 {
11205 cache->hit_count++;
11206
11207 if (remote_debug)
11208 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11209 pulongest (cache->hit_count));
11210 return ret;
11211 }
11212
11213 cache->miss_count++;
11214 if (remote_debug)
11215 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11216 pulongest (cache->miss_count));
11217
11218 cache->fd = fd;
11219 cache->offset = offset;
11220 cache->bufsize = get_remote_packet_size ();
224c3ddb 11221 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11222
11223 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11224 cache->offset, remote_errno);
11225 if (ret <= 0)
11226 {
11227 readahead_cache_invalidate_fd (fd);
11228 return ret;
11229 }
11230
11231 cache->bufsize = ret;
11232 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11233}
11234
12e2a5fd 11235/* Implementation of to_fileio_close. */
a6b151f1
DJ
11236
11237static int
df39ea25 11238remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11239{
11240 struct remote_state *rs = get_remote_state ();
11241 char *p = rs->buf;
11242 int left = get_remote_packet_size () - 1;
11243
80152258
PA
11244 readahead_cache_invalidate_fd (fd);
11245
a6b151f1
DJ
11246 remote_buffer_add_string (&p, &left, "vFile:close:");
11247
11248 remote_buffer_add_int (&p, &left, fd);
11249
11250 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11251 remote_errno, NULL, NULL);
11252}
11253
12e2a5fd 11254/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11255
11256static int
dbbca37d 11257remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11258 struct inferior *inf, const char *filename,
11259 int *remote_errno)
a6b151f1
DJ
11260{
11261 struct remote_state *rs = get_remote_state ();
11262 char *p = rs->buf;
11263 int left = get_remote_packet_size () - 1;
11264
15a201c8
GB
11265 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11266 return -1;
11267
a6b151f1
DJ
11268 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11269
11270 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11271 strlen (filename));
11272
11273 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11274 remote_errno, NULL, NULL);
11275}
11276
12e2a5fd 11277/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11278
11279static char *
fab5aa7c 11280remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11281 struct inferior *inf, const char *filename,
11282 int *remote_errno)
b9e7b9c3
UW
11283{
11284 struct remote_state *rs = get_remote_state ();
11285 char *p = rs->buf;
11286 char *attachment;
11287 int left = get_remote_packet_size ();
11288 int len, attachment_len;
11289 int read_len;
11290 char *ret;
11291
15a201c8
GB
11292 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11293 return NULL;
11294
b9e7b9c3
UW
11295 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11296
11297 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11298 strlen (filename));
11299
11300 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11301 remote_errno, &attachment,
11302 &attachment_len);
11303
11304 if (len < 0)
11305 return NULL;
11306
224c3ddb 11307 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11308
bc20a4af
PA
11309 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11310 (gdb_byte *) ret, len);
b9e7b9c3
UW
11311 if (read_len != len)
11312 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11313
11314 ret[len] = '\0';
11315 return ret;
11316}
11317
12e2a5fd 11318/* Implementation of to_fileio_fstat. */
0a93529c
GB
11319
11320static int
11321remote_hostio_fstat (struct target_ops *self,
11322 int fd, struct stat *st,
11323 int *remote_errno)
11324{
11325 struct remote_state *rs = get_remote_state ();
11326 char *p = rs->buf;
11327 int left = get_remote_packet_size ();
11328 int attachment_len, ret;
11329 char *attachment;
11330 struct fio_stat fst;
11331 int read_len;
11332
464b0089
GB
11333 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11334
11335 remote_buffer_add_int (&p, &left, fd);
11336
11337 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11338 remote_errno, &attachment,
11339 &attachment_len);
11340 if (ret < 0)
0a93529c 11341 {
464b0089
GB
11342 if (*remote_errno != FILEIO_ENOSYS)
11343 return ret;
11344
0a93529c
GB
11345 /* Strictly we should return -1, ENOSYS here, but when
11346 "set sysroot remote:" was implemented in August 2008
11347 BFD's need for a stat function was sidestepped with
11348 this hack. This was not remedied until March 2015
11349 so we retain the previous behavior to avoid breaking
11350 compatibility.
11351
11352 Note that the memset is a March 2015 addition; older
11353 GDBs set st_size *and nothing else* so the structure
11354 would have garbage in all other fields. This might
11355 break something but retaining the previous behavior
11356 here would be just too wrong. */
11357
11358 memset (st, 0, sizeof (struct stat));
11359 st->st_size = INT_MAX;
11360 return 0;
11361 }
11362
0a93529c
GB
11363 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11364 (gdb_byte *) &fst, sizeof (fst));
11365
11366 if (read_len != ret)
11367 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11368
11369 if (read_len != sizeof (fst))
11370 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11371 read_len, (int) sizeof (fst));
11372
11373 remote_fileio_to_host_stat (&fst, st);
11374
11375 return 0;
11376}
11377
12e2a5fd 11378/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11379
11380static int
11381remote_filesystem_is_local (struct target_ops *self)
11382{
11383 /* Valgrind GDB presents itself as a remote target but works
11384 on the local filesystem: it does not implement remote get
11385 and users are not expected to set a sysroot. To handle
11386 this case we treat the remote filesystem as local if the
11387 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11388 does not support vFile:open. */
a3be80c3 11389 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11390 {
11391 enum packet_support ps = packet_support (PACKET_vFile_open);
11392
11393 if (ps == PACKET_SUPPORT_UNKNOWN)
11394 {
11395 int fd, remote_errno;
11396
11397 /* Try opening a file to probe support. The supplied
11398 filename is irrelevant, we only care about whether
11399 the stub recognizes the packet or not. */
07c138c8 11400 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11401 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11402 &remote_errno);
11403
11404 if (fd >= 0)
11405 remote_hostio_close (self, fd, &remote_errno);
11406
11407 ps = packet_support (PACKET_vFile_open);
11408 }
11409
11410 if (ps == PACKET_DISABLE)
11411 {
11412 static int warning_issued = 0;
11413
11414 if (!warning_issued)
11415 {
11416 warning (_("remote target does not support file"
11417 " transfer, attempting to access files"
11418 " from local filesystem."));
11419 warning_issued = 1;
11420 }
11421
11422 return 1;
11423 }
11424 }
11425
11426 return 0;
11427}
11428
a6b151f1
DJ
11429static int
11430remote_fileio_errno_to_host (int errnum)
11431{
11432 switch (errnum)
11433 {
11434 case FILEIO_EPERM:
11435 return EPERM;
11436 case FILEIO_ENOENT:
11437 return ENOENT;
11438 case FILEIO_EINTR:
11439 return EINTR;
11440 case FILEIO_EIO:
11441 return EIO;
11442 case FILEIO_EBADF:
11443 return EBADF;
11444 case FILEIO_EACCES:
11445 return EACCES;
11446 case FILEIO_EFAULT:
11447 return EFAULT;
11448 case FILEIO_EBUSY:
11449 return EBUSY;
11450 case FILEIO_EEXIST:
11451 return EEXIST;
11452 case FILEIO_ENODEV:
11453 return ENODEV;
11454 case FILEIO_ENOTDIR:
11455 return ENOTDIR;
11456 case FILEIO_EISDIR:
11457 return EISDIR;
11458 case FILEIO_EINVAL:
11459 return EINVAL;
11460 case FILEIO_ENFILE:
11461 return ENFILE;
11462 case FILEIO_EMFILE:
11463 return EMFILE;
11464 case FILEIO_EFBIG:
11465 return EFBIG;
11466 case FILEIO_ENOSPC:
11467 return ENOSPC;
11468 case FILEIO_ESPIPE:
11469 return ESPIPE;
11470 case FILEIO_EROFS:
11471 return EROFS;
11472 case FILEIO_ENOSYS:
11473 return ENOSYS;
11474 case FILEIO_ENAMETOOLONG:
11475 return ENAMETOOLONG;
11476 }
11477 return -1;
11478}
11479
11480static char *
11481remote_hostio_error (int errnum)
11482{
11483 int host_error = remote_fileio_errno_to_host (errnum);
11484
11485 if (host_error == -1)
11486 error (_("Unknown remote I/O error %d"), errnum);
11487 else
11488 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11489}
11490
a6b151f1
DJ
11491static void
11492remote_hostio_close_cleanup (void *opaque)
11493{
11494 int fd = *(int *) opaque;
11495 int remote_errno;
11496
df39ea25 11497 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11498}
11499
11500void
11501remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11502{
11503 struct cleanup *back_to, *close_cleanup;
11504 int retcode, fd, remote_errno, bytes, io_size;
11505 FILE *file;
11506 gdb_byte *buffer;
11507 int bytes_in_buffer;
11508 int saw_eof;
11509 ULONGEST offset;
5d93a237 11510 struct remote_state *rs = get_remote_state ();
a6b151f1 11511
5d93a237 11512 if (!rs->remote_desc)
a6b151f1
DJ
11513 error (_("command can only be used with remote target"));
11514
614c279d 11515 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11516 if (file == NULL)
11517 perror_with_name (local_file);
7c8a8b04 11518 back_to = make_cleanup_fclose (file);
a6b151f1 11519
07c138c8 11520 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11521 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11522 | FILEIO_O_TRUNC),
4313b8c0 11523 0700, 0, &remote_errno);
a6b151f1
DJ
11524 if (fd == -1)
11525 remote_hostio_error (remote_errno);
11526
11527 /* Send up to this many bytes at once. They won't all fit in the
11528 remote packet limit, so we'll transfer slightly fewer. */
11529 io_size = get_remote_packet_size ();
224c3ddb 11530 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11531 make_cleanup (xfree, buffer);
11532
11533 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11534
11535 bytes_in_buffer = 0;
11536 saw_eof = 0;
11537 offset = 0;
11538 while (bytes_in_buffer || !saw_eof)
11539 {
11540 if (!saw_eof)
11541 {
3e43a32a
MS
11542 bytes = fread (buffer + bytes_in_buffer, 1,
11543 io_size - bytes_in_buffer,
a6b151f1
DJ
11544 file);
11545 if (bytes == 0)
11546 {
11547 if (ferror (file))
11548 error (_("Error reading %s."), local_file);
11549 else
11550 {
11551 /* EOF. Unless there is something still in the
11552 buffer from the last iteration, we are done. */
11553 saw_eof = 1;
11554 if (bytes_in_buffer == 0)
11555 break;
11556 }
11557 }
11558 }
11559 else
11560 bytes = 0;
11561
11562 bytes += bytes_in_buffer;
11563 bytes_in_buffer = 0;
11564
0d866f62
TT
11565 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11566 fd, buffer, bytes,
3e43a32a 11567 offset, &remote_errno);
a6b151f1
DJ
11568
11569 if (retcode < 0)
11570 remote_hostio_error (remote_errno);
11571 else if (retcode == 0)
11572 error (_("Remote write of %d bytes returned 0!"), bytes);
11573 else if (retcode < bytes)
11574 {
11575 /* Short write. Save the rest of the read data for the next
11576 write. */
11577 bytes_in_buffer = bytes - retcode;
11578 memmove (buffer, buffer + retcode, bytes_in_buffer);
11579 }
11580
11581 offset += retcode;
11582 }
11583
11584 discard_cleanups (close_cleanup);
df39ea25 11585 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11586 remote_hostio_error (remote_errno);
11587
11588 if (from_tty)
11589 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11590 do_cleanups (back_to);
11591}
11592
11593void
11594remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11595{
11596 struct cleanup *back_to, *close_cleanup;
cea39f65 11597 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11598 FILE *file;
11599 gdb_byte *buffer;
11600 ULONGEST offset;
5d93a237 11601 struct remote_state *rs = get_remote_state ();
a6b151f1 11602
5d93a237 11603 if (!rs->remote_desc)
a6b151f1
DJ
11604 error (_("command can only be used with remote target"));
11605
07c138c8 11606 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11607 remote_file, FILEIO_O_RDONLY, 0, 0,
11608 &remote_errno);
a6b151f1
DJ
11609 if (fd == -1)
11610 remote_hostio_error (remote_errno);
11611
614c279d 11612 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11613 if (file == NULL)
11614 perror_with_name (local_file);
7c8a8b04 11615 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11616
11617 /* Send up to this many bytes at once. They won't all fit in the
11618 remote packet limit, so we'll transfer slightly fewer. */
11619 io_size = get_remote_packet_size ();
224c3ddb 11620 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11621 make_cleanup (xfree, buffer);
11622
11623 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11624
11625 offset = 0;
11626 while (1)
11627 {
a3be983c
TT
11628 bytes = remote_hostio_pread (find_target_at (process_stratum),
11629 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11630 if (bytes == 0)
11631 /* Success, but no bytes, means end-of-file. */
11632 break;
11633 if (bytes == -1)
11634 remote_hostio_error (remote_errno);
11635
11636 offset += bytes;
11637
11638 bytes = fwrite (buffer, 1, bytes, file);
11639 if (bytes == 0)
11640 perror_with_name (local_file);
11641 }
11642
11643 discard_cleanups (close_cleanup);
df39ea25 11644 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11645 remote_hostio_error (remote_errno);
11646
11647 if (from_tty)
11648 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11649 do_cleanups (back_to);
11650}
11651
11652void
11653remote_file_delete (const char *remote_file, int from_tty)
11654{
11655 int retcode, remote_errno;
5d93a237 11656 struct remote_state *rs = get_remote_state ();
a6b151f1 11657
5d93a237 11658 if (!rs->remote_desc)
a6b151f1
DJ
11659 error (_("command can only be used with remote target"));
11660
dbbca37d 11661 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11662 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11663 if (retcode == -1)
11664 remote_hostio_error (remote_errno);
11665
11666 if (from_tty)
11667 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11668}
11669
11670static void
11671remote_put_command (char *args, int from_tty)
11672{
11673 struct cleanup *back_to;
11674 char **argv;
11675
d1a41061
PP
11676 if (args == NULL)
11677 error_no_arg (_("file to put"));
11678
11679 argv = gdb_buildargv (args);
a6b151f1
DJ
11680 back_to = make_cleanup_freeargv (argv);
11681 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11682 error (_("Invalid parameters to remote put"));
11683
11684 remote_file_put (argv[0], argv[1], from_tty);
11685
11686 do_cleanups (back_to);
11687}
11688
11689static void
11690remote_get_command (char *args, int from_tty)
11691{
11692 struct cleanup *back_to;
11693 char **argv;
11694
d1a41061
PP
11695 if (args == NULL)
11696 error_no_arg (_("file to get"));
11697
11698 argv = gdb_buildargv (args);
a6b151f1
DJ
11699 back_to = make_cleanup_freeargv (argv);
11700 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11701 error (_("Invalid parameters to remote get"));
11702
11703 remote_file_get (argv[0], argv[1], from_tty);
11704
11705 do_cleanups (back_to);
11706}
11707
11708static void
11709remote_delete_command (char *args, int from_tty)
11710{
11711 struct cleanup *back_to;
11712 char **argv;
11713
d1a41061
PP
11714 if (args == NULL)
11715 error_no_arg (_("file to delete"));
11716
11717 argv = gdb_buildargv (args);
a6b151f1
DJ
11718 back_to = make_cleanup_freeargv (argv);
11719 if (argv[0] == NULL || argv[1] != NULL)
11720 error (_("Invalid parameters to remote delete"));
11721
11722 remote_file_delete (argv[0], from_tty);
11723
11724 do_cleanups (back_to);
11725}
11726
11727static void
11728remote_command (char *args, int from_tty)
11729{
635c7e8a 11730 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11731}
11732
b2175913 11733static int
19db3e69 11734remote_can_execute_reverse (struct target_ops *self)
b2175913 11735{
4082afcc
PA
11736 if (packet_support (PACKET_bs) == PACKET_ENABLE
11737 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11738 return 1;
11739 else
11740 return 0;
b2175913
MS
11741}
11742
74531fed 11743static int
2a9a2795 11744remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11745{
11746 return 1;
11747}
11748
03583c20 11749static int
2bfc0540 11750remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11751{
11752 /* Only supported in extended mode. */
11753 return 0;
11754}
11755
8a305172 11756static int
86ce2668 11757remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11758{
11759 struct remote_state *rs = get_remote_state ();
a744cf53 11760
8020350c 11761 return remote_multi_process_p (rs);
8a305172
PA
11762}
11763
70221824 11764static int
782b2b07
SS
11765remote_supports_cond_tracepoints (void)
11766{
4082afcc 11767 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11768}
11769
3788aec7 11770static int
efcc2da7 11771remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11772{
4082afcc 11773 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11774}
11775
70221824 11776static int
7a697b8d
SS
11777remote_supports_fast_tracepoints (void)
11778{
4082afcc 11779 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11780}
11781
0fb4aa4b
PA
11782static int
11783remote_supports_static_tracepoints (void)
11784{
4082afcc 11785 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11786}
11787
1e4d1764
YQ
11788static int
11789remote_supports_install_in_trace (void)
11790{
4082afcc 11791 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11792}
11793
d248b706 11794static int
7d178d6a 11795remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11796{
4082afcc
PA
11797 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11798 == PACKET_ENABLE);
d248b706
KY
11799}
11800
3065dfb6 11801static int
6de37a3a 11802remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11803{
4082afcc 11804 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11805}
11806
d3ce09f5 11807static int
78eff0ec 11808remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11809{
4082afcc 11810 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11811}
11812
35b1e5cc 11813static void
ecae04e1 11814remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11815{
11816 putpkt ("QTinit");
11817 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11818 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11819 error (_("Target does not support this command."));
11820}
11821
11822static void free_actions_list (char **actions_list);
11823static void free_actions_list_cleanup_wrapper (void *);
11824static void
11825free_actions_list_cleanup_wrapper (void *al)
11826{
19ba03f4 11827 free_actions_list ((char **) al);
35b1e5cc
SS
11828}
11829
11830static void
11831free_actions_list (char **actions_list)
11832{
11833 int ndx;
11834
11835 if (actions_list == 0)
11836 return;
11837
11838 for (ndx = 0; actions_list[ndx]; ndx++)
11839 xfree (actions_list[ndx]);
11840
11841 xfree (actions_list);
11842}
11843
409873ef
SS
11844/* Recursive routine to walk through command list including loops, and
11845 download packets for each command. */
11846
11847static void
11848remote_download_command_source (int num, ULONGEST addr,
11849 struct command_line *cmds)
11850{
11851 struct remote_state *rs = get_remote_state ();
11852 struct command_line *cmd;
11853
11854 for (cmd = cmds; cmd; cmd = cmd->next)
11855 {
0df8b418 11856 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11857 strcpy (rs->buf, "QTDPsrc:");
11858 encode_source_string (num, addr, "cmd", cmd->line,
11859 rs->buf + strlen (rs->buf),
11860 rs->buf_size - strlen (rs->buf));
11861 putpkt (rs->buf);
11862 remote_get_noisy_reply (&target_buf, &target_buf_size);
11863 if (strcmp (target_buf, "OK"))
11864 warning (_("Target does not support source download."));
11865
11866 if (cmd->control_type == while_control
11867 || cmd->control_type == while_stepping_control)
11868 {
11869 remote_download_command_source (num, addr, *cmd->body_list);
11870
0df8b418 11871 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11872 strcpy (rs->buf, "QTDPsrc:");
11873 encode_source_string (num, addr, "cmd", "end",
11874 rs->buf + strlen (rs->buf),
11875 rs->buf_size - strlen (rs->buf));
11876 putpkt (rs->buf);
11877 remote_get_noisy_reply (&target_buf, &target_buf_size);
11878 if (strcmp (target_buf, "OK"))
11879 warning (_("Target does not support source download."));
11880 }
11881 }
11882}
11883
35b1e5cc 11884static void
548f7808 11885remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11886{
bba74b36 11887#define BUF_SIZE 2048
e8ba3115 11888
35b1e5cc 11889 CORE_ADDR tpaddr;
409873ef 11890 char addrbuf[40];
bba74b36 11891 char buf[BUF_SIZE];
35b1e5cc
SS
11892 char **tdp_actions;
11893 char **stepping_actions;
11894 int ndx;
11895 struct cleanup *old_chain = NULL;
11896 struct agent_expr *aexpr;
11897 struct cleanup *aexpr_chain = NULL;
11898 char *pkt;
e8ba3115 11899 struct breakpoint *b = loc->owner;
d9b3f62e 11900 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11901
dc673c81 11902 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11903 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11904 tdp_actions);
11905 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11906 stepping_actions);
11907
11908 tpaddr = loc->address;
11909 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11910 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11911 addrbuf, /* address */
11912 (b->enable_state == bp_enabled ? 'E' : 'D'),
11913 t->step_count, t->pass_count);
e8ba3115
YQ
11914 /* Fast tracepoints are mostly handled by the target, but we can
11915 tell the target how big of an instruction block should be moved
11916 around. */
11917 if (b->type == bp_fast_tracepoint)
11918 {
11919 /* Only test for support at download time; we may not know
11920 target capabilities at definition time. */
11921 if (remote_supports_fast_tracepoints ())
35b1e5cc 11922 {
6b940e6a
PL
11923 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11924 NULL))
bba74b36 11925 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11926 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11927 else
e8ba3115
YQ
11928 /* If it passed validation at definition but fails now,
11929 something is very wrong. */
11930 internal_error (__FILE__, __LINE__,
11931 _("Fast tracepoint not "
11932 "valid during download"));
35b1e5cc 11933 }
e8ba3115
YQ
11934 else
11935 /* Fast tracepoints are functionally identical to regular
11936 tracepoints, so don't take lack of support as a reason to
11937 give up on the trace run. */
11938 warning (_("Target does not support fast tracepoints, "
11939 "downloading %d as regular tracepoint"), b->number);
11940 }
11941 else if (b->type == bp_static_tracepoint)
11942 {
11943 /* Only test for support at download time; we may not know
11944 target capabilities at definition time. */
11945 if (remote_supports_static_tracepoints ())
0fb4aa4b 11946 {
e8ba3115 11947 struct static_tracepoint_marker marker;
0fb4aa4b 11948
e8ba3115
YQ
11949 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11950 strcat (buf, ":S");
0fb4aa4b 11951 else
e8ba3115 11952 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11953 }
e8ba3115
YQ
11954 else
11955 /* Fast tracepoints are functionally identical to regular
11956 tracepoints, so don't take lack of support as a reason
11957 to give up on the trace run. */
11958 error (_("Target does not support static tracepoints"));
11959 }
11960 /* If the tracepoint has a conditional, make it into an agent
11961 expression and append to the definition. */
11962 if (loc->cond)
11963 {
11964 /* Only test support at download time, we may not know target
11965 capabilities at definition time. */
11966 if (remote_supports_cond_tracepoints ())
35b1e5cc 11967 {
e8ba3115
YQ
11968 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11969 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11970 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11971 aexpr->len);
e8ba3115
YQ
11972 pkt = buf + strlen (buf);
11973 for (ndx = 0; ndx < aexpr->len; ++ndx)
11974 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11975 *pkt = '\0';
11976 do_cleanups (aexpr_chain);
35b1e5cc 11977 }
e8ba3115
YQ
11978 else
11979 warning (_("Target does not support conditional tracepoints, "
11980 "ignoring tp %d cond"), b->number);
11981 }
35b1e5cc 11982
d9b3f62e 11983 if (b->commands || *default_collect)
e8ba3115
YQ
11984 strcat (buf, "-");
11985 putpkt (buf);
11986 remote_get_noisy_reply (&target_buf, &target_buf_size);
11987 if (strcmp (target_buf, "OK"))
11988 error (_("Target does not support tracepoints."));
35b1e5cc 11989
e8ba3115
YQ
11990 /* do_single_steps (t); */
11991 if (tdp_actions)
11992 {
11993 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11994 {
e8ba3115 11995 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11996 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11997 b->number, addrbuf, /* address */
11998 tdp_actions[ndx],
11999 ((tdp_actions[ndx + 1] || stepping_actions)
12000 ? '-' : 0));
e8ba3115
YQ
12001 putpkt (buf);
12002 remote_get_noisy_reply (&target_buf,
12003 &target_buf_size);
12004 if (strcmp (target_buf, "OK"))
12005 error (_("Error on target while setting tracepoints."));
35b1e5cc 12006 }
e8ba3115
YQ
12007 }
12008 if (stepping_actions)
12009 {
12010 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 12011 {
e8ba3115 12012 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
12013 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12014 b->number, addrbuf, /* address */
12015 ((ndx == 0) ? "S" : ""),
12016 stepping_actions[ndx],
12017 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
12018 putpkt (buf);
12019 remote_get_noisy_reply (&target_buf,
12020 &target_buf_size);
12021 if (strcmp (target_buf, "OK"))
12022 error (_("Error on target while setting tracepoints."));
35b1e5cc 12023 }
e8ba3115 12024 }
409873ef 12025
4082afcc 12026 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 12027 {
f00aae0f 12028 if (b->location != NULL)
409873ef 12029 {
e8ba3115 12030 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
12031 encode_source_string (b->number, loc->address, "at",
12032 event_location_to_string (b->location),
12033 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
12034 putpkt (buf);
12035 remote_get_noisy_reply (&target_buf, &target_buf_size);
12036 if (strcmp (target_buf, "OK"))
12037 warning (_("Target does not support source download."));
409873ef 12038 }
e8ba3115
YQ
12039 if (b->cond_string)
12040 {
12041 strcpy (buf, "QTDPsrc:");
12042 encode_source_string (b->number, loc->address,
12043 "cond", b->cond_string, buf + strlen (buf),
12044 2048 - strlen (buf));
12045 putpkt (buf);
12046 remote_get_noisy_reply (&target_buf, &target_buf_size);
12047 if (strcmp (target_buf, "OK"))
12048 warning (_("Target does not support source download."));
12049 }
12050 remote_download_command_source (b->number, loc->address,
12051 breakpoint_commands (b));
35b1e5cc 12052 }
e8ba3115
YQ
12053
12054 do_cleanups (old_chain);
35b1e5cc
SS
12055}
12056
1e4d1764 12057static int
a52a8357 12058remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 12059{
1e51243a
PA
12060 struct remote_state *rs = get_remote_state ();
12061 struct trace_status *ts;
12062 int status;
12063
12064 /* Don't try to install tracepoints until we've relocated our
12065 symbols, and fetched and merged the target's tracepoint list with
12066 ours. */
12067 if (rs->starting_up)
12068 return 0;
12069
12070 ts = current_trace_status ();
8bd200f1 12071 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
12072
12073 if (status == -1 || !ts->running_known || !ts->running)
12074 return 0;
12075
12076 /* If we are in a tracing experiment, but remote stub doesn't support
12077 installing tracepoint in trace, we have to return. */
12078 if (!remote_supports_install_in_trace ())
12079 return 0;
12080
12081 return 1;
12082}
12083
12084
35b1e5cc 12085static void
559d2b81
TT
12086remote_download_trace_state_variable (struct target_ops *self,
12087 struct trace_state_variable *tsv)
35b1e5cc
SS
12088{
12089 struct remote_state *rs = get_remote_state ();
00bf0b85 12090 char *p;
35b1e5cc 12091
bba74b36
YQ
12092 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12093 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12094 tsv->builtin);
00bf0b85
SS
12095 p = rs->buf + strlen (rs->buf);
12096 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12097 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 12098 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 12099 *p++ = '\0';
35b1e5cc
SS
12100 putpkt (rs->buf);
12101 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12102 if (*target_buf == '\0')
12103 error (_("Target does not support this command."));
12104 if (strcmp (target_buf, "OK") != 0)
12105 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12106}
12107
d248b706 12108static void
46670d57
TT
12109remote_enable_tracepoint (struct target_ops *self,
12110 struct bp_location *location)
d248b706
KY
12111{
12112 struct remote_state *rs = get_remote_state ();
12113 char addr_buf[40];
12114
12115 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12116 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12117 location->owner->number, addr_buf);
d248b706
KY
12118 putpkt (rs->buf);
12119 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12120 if (*rs->buf == '\0')
12121 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12122 if (strcmp (rs->buf, "OK") != 0)
12123 error (_("Error on target while enabling tracepoint."));
12124}
12125
12126static void
780b049c
TT
12127remote_disable_tracepoint (struct target_ops *self,
12128 struct bp_location *location)
d248b706
KY
12129{
12130 struct remote_state *rs = get_remote_state ();
12131 char addr_buf[40];
12132
12133 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12134 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12135 location->owner->number, addr_buf);
d248b706
KY
12136 putpkt (rs->buf);
12137 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12138 if (*rs->buf == '\0')
12139 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12140 if (strcmp (rs->buf, "OK") != 0)
12141 error (_("Error on target while disabling tracepoint."));
12142}
12143
35b1e5cc 12144static void
583f9a86 12145remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12146{
12147 asection *s;
81b9b86e 12148 bfd *abfd = NULL;
35b1e5cc 12149 bfd_size_type size;
608bcef2 12150 bfd_vma vma;
35b1e5cc 12151 int anysecs = 0;
c2fa21f1 12152 int offset = 0;
35b1e5cc
SS
12153
12154 if (!exec_bfd)
12155 return; /* No information to give. */
12156
12157 strcpy (target_buf, "QTro");
9779ab84 12158 offset = strlen (target_buf);
35b1e5cc
SS
12159 for (s = exec_bfd->sections; s; s = s->next)
12160 {
12161 char tmp1[40], tmp2[40];
c2fa21f1 12162 int sec_length;
35b1e5cc
SS
12163
12164 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12165 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12166 (s->flags & SEC_READONLY) == 0)
12167 continue;
12168
12169 anysecs = 1;
81b9b86e 12170 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12171 size = bfd_get_section_size (s);
608bcef2
HZ
12172 sprintf_vma (tmp1, vma);
12173 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12174 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12175 if (offset + sec_length + 1 > target_buf_size)
12176 {
4082afcc 12177 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12178 warning (_("\
c2fa21f1
HZ
12179Too many sections for read-only sections definition packet."));
12180 break;
12181 }
bba74b36
YQ
12182 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12183 tmp1, tmp2);
c2fa21f1 12184 offset += sec_length;
35b1e5cc
SS
12185 }
12186 if (anysecs)
12187 {
12188 putpkt (target_buf);
12189 getpkt (&target_buf, &target_buf_size, 0);
12190 }
12191}
12192
12193static void
e2d1aae3 12194remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12195{
12196 putpkt ("QTStart");
12197 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12198 if (*target_buf == '\0')
12199 error (_("Target does not support this command."));
12200 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12201 error (_("Bogus reply from target: %s"), target_buf);
12202}
12203
12204static int
8bd200f1 12205remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12206{
953b98d1 12207 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12208 char *p = NULL;
0df8b418 12209 /* FIXME we need to get register block size some other way. */
00bf0b85 12210 extern int trace_regblock_size;
bd3eecc3
PA
12211 enum packet_result result;
12212
4082afcc 12213 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12214 return -1;
a744cf53 12215
00bf0b85
SS
12216 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12217
049dc89b
JK
12218 putpkt ("qTStatus");
12219
492d29ea 12220 TRY
67f41397
JK
12221 {
12222 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12223 }
492d29ea 12224 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12225 {
598d3636
JK
12226 if (ex.error != TARGET_CLOSE_ERROR)
12227 {
12228 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12229 return -1;
12230 }
12231 throw_exception (ex);
67f41397 12232 }
492d29ea 12233 END_CATCH
00bf0b85 12234
bd3eecc3
PA
12235 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12236
00bf0b85 12237 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12238 if (result == PACKET_UNKNOWN)
00bf0b85 12239 return -1;
35b1e5cc 12240
00bf0b85 12241 /* We're working with a live target. */
f5911ea1 12242 ts->filename = NULL;
00bf0b85 12243
00bf0b85 12244 if (*p++ != 'T')
35b1e5cc
SS
12245 error (_("Bogus trace status reply from target: %s"), target_buf);
12246
84cebc4a
YQ
12247 /* Function 'parse_trace_status' sets default value of each field of
12248 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12249 parse_trace_status (p, ts);
12250
12251 return ts->running;
35b1e5cc
SS
12252}
12253
70221824 12254static void
db90e85c 12255remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12256 struct uploaded_tp *utp)
12257{
12258 struct remote_state *rs = get_remote_state ();
f196051f
SS
12259 char *reply;
12260 struct bp_location *loc;
12261 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12262 size_t size = get_remote_packet_size ();
f196051f
SS
12263
12264 if (tp)
12265 {
12266 tp->base.hit_count = 0;
12267 tp->traceframe_usage = 0;
12268 for (loc = tp->base.loc; loc; loc = loc->next)
12269 {
12270 /* If the tracepoint was never downloaded, don't go asking for
12271 any status. */
12272 if (tp->number_on_target == 0)
12273 continue;
bba74b36
YQ
12274 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12275 phex_nz (loc->address, 0));
f196051f
SS
12276 putpkt (rs->buf);
12277 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12278 if (reply && *reply)
12279 {
12280 if (*reply == 'V')
12281 parse_tracepoint_status (reply + 1, bp, utp);
12282 }
12283 }
12284 }
12285 else if (utp)
12286 {
12287 utp->hit_count = 0;
12288 utp->traceframe_usage = 0;
bba74b36
YQ
12289 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12290 phex_nz (utp->addr, 0));
f196051f
SS
12291 putpkt (rs->buf);
12292 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12293 if (reply && *reply)
12294 {
12295 if (*reply == 'V')
12296 parse_tracepoint_status (reply + 1, bp, utp);
12297 }
12298 }
12299}
12300
35b1e5cc 12301static void
74499f1b 12302remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12303{
12304 putpkt ("QTStop");
12305 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12306 if (*target_buf == '\0')
12307 error (_("Target does not support this command."));
12308 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12309 error (_("Bogus reply from target: %s"), target_buf);
12310}
12311
12312static int
bd4c6793
TT
12313remote_trace_find (struct target_ops *self,
12314 enum trace_find_type type, int num,
cc5925ad 12315 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12316 int *tpp)
12317{
12318 struct remote_state *rs = get_remote_state ();
bba74b36 12319 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12320 char *p, *reply;
12321 int target_frameno = -1, target_tracept = -1;
12322
e6e4e701
PA
12323 /* Lookups other than by absolute frame number depend on the current
12324 trace selected, so make sure it is correct on the remote end
12325 first. */
12326 if (type != tfind_number)
12327 set_remote_traceframe ();
12328
35b1e5cc
SS
12329 p = rs->buf;
12330 strcpy (p, "QTFrame:");
12331 p = strchr (p, '\0');
12332 switch (type)
12333 {
12334 case tfind_number:
bba74b36 12335 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12336 break;
12337 case tfind_pc:
bba74b36 12338 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12339 break;
12340 case tfind_tp:
bba74b36 12341 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12342 break;
12343 case tfind_range:
bba74b36
YQ
12344 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12345 phex_nz (addr2, 0));
35b1e5cc
SS
12346 break;
12347 case tfind_outside:
bba74b36
YQ
12348 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12349 phex_nz (addr2, 0));
35b1e5cc
SS
12350 break;
12351 default:
9b20d036 12352 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12353 }
12354
12355 putpkt (rs->buf);
2f65bcb7 12356 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12357 if (*reply == '\0')
12358 error (_("Target does not support this command."));
35b1e5cc
SS
12359
12360 while (reply && *reply)
12361 switch (*reply)
12362 {
12363 case 'F':
f197e0f1
VP
12364 p = ++reply;
12365 target_frameno = (int) strtol (p, &reply, 16);
12366 if (reply == p)
12367 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12368 /* Don't update our remote traceframe number cache on failure
12369 to select a remote traceframe. */
f197e0f1
VP
12370 if (target_frameno == -1)
12371 return -1;
35b1e5cc
SS
12372 break;
12373 case 'T':
f197e0f1
VP
12374 p = ++reply;
12375 target_tracept = (int) strtol (p, &reply, 16);
12376 if (reply == p)
12377 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12378 break;
12379 case 'O': /* "OK"? */
12380 if (reply[1] == 'K' && reply[2] == '\0')
12381 reply += 2;
12382 else
12383 error (_("Bogus reply from target: %s"), reply);
12384 break;
12385 default:
12386 error (_("Bogus reply from target: %s"), reply);
12387 }
12388 if (tpp)
12389 *tpp = target_tracept;
e6e4e701 12390
262e1174 12391 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12392 return target_frameno;
12393}
12394
12395static int
4011015b
TT
12396remote_get_trace_state_variable_value (struct target_ops *self,
12397 int tsvnum, LONGEST *val)
35b1e5cc
SS
12398{
12399 struct remote_state *rs = get_remote_state ();
12400 char *reply;
12401 ULONGEST uval;
12402
e6e4e701
PA
12403 set_remote_traceframe ();
12404
bba74b36 12405 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12406 putpkt (rs->buf);
12407 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12408 if (reply && *reply)
12409 {
12410 if (*reply == 'V')
12411 {
12412 unpack_varlen_hex (reply + 1, &uval);
12413 *val = (LONGEST) uval;
12414 return 1;
12415 }
12416 }
12417 return 0;
12418}
12419
00bf0b85 12420static int
dc3decaf 12421remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12422{
12423 struct remote_state *rs = get_remote_state ();
12424 char *p, *reply;
12425
12426 p = rs->buf;
12427 strcpy (p, "QTSave:");
12428 p += strlen (p);
12429 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12430 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12431 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12432 *p++ = '\0';
12433 putpkt (rs->buf);
ad91cd99 12434 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12435 if (*reply == '\0')
ad91cd99
PA
12436 error (_("Target does not support this command."));
12437 if (strcmp (reply, "OK") != 0)
12438 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12439 return 0;
12440}
12441
12442/* This is basically a memory transfer, but needs to be its own packet
12443 because we don't know how the target actually organizes its trace
12444 memory, plus we want to be able to ask for as much as possible, but
12445 not be unhappy if we don't get as much as we ask for. */
12446
12447static LONGEST
88ee6f45
TT
12448remote_get_raw_trace_data (struct target_ops *self,
12449 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12450{
12451 struct remote_state *rs = get_remote_state ();
12452 char *reply;
12453 char *p;
12454 int rslt;
12455
12456 p = rs->buf;
12457 strcpy (p, "qTBuffer:");
12458 p += strlen (p);
12459 p += hexnumstr (p, offset);
12460 *p++ = ',';
12461 p += hexnumstr (p, len);
12462 *p++ = '\0';
12463
12464 putpkt (rs->buf);
12465 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12466 if (reply && *reply)
12467 {
12468 /* 'l' by itself means we're at the end of the buffer and
12469 there is nothing more to get. */
12470 if (*reply == 'l')
12471 return 0;
12472
12473 /* Convert the reply into binary. Limit the number of bytes to
12474 convert according to our passed-in buffer size, rather than
12475 what was returned in the packet; if the target is
12476 unexpectedly generous and gives us a bigger reply than we
12477 asked for, we don't want to crash. */
12478 rslt = hex2bin (target_buf, buf, len);
12479 return rslt;
12480 }
12481
12482 /* Something went wrong, flag as an error. */
12483 return -1;
12484}
12485
35b1e5cc 12486static void
37b25738 12487remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12488{
12489 struct remote_state *rs = get_remote_state ();
12490
4082afcc 12491 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12492 {
ad91cd99
PA
12493 char *reply;
12494
bba74b36 12495 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12496 putpkt (rs->buf);
ad91cd99
PA
12497 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12498 if (*reply == '\0')
33da3f1c 12499 error (_("Target does not support this command."));
ad91cd99
PA
12500 if (strcmp (reply, "OK") != 0)
12501 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12502 }
12503 else if (val)
12504 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12505}
12506
dc146f7c
VP
12507static int
12508remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12509{
12510 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12511
fe978cb0
PA
12512 if (info && info->priv)
12513 return info->priv->core;
dc146f7c
VP
12514 return -1;
12515}
12516
4daf5ac0 12517static void
736d5b1f 12518remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12519{
12520 struct remote_state *rs = get_remote_state ();
ad91cd99 12521 char *reply;
4daf5ac0 12522
bba74b36 12523 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12524 putpkt (rs->buf);
ad91cd99
PA
12525 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12526 if (*reply == '\0')
4daf5ac0 12527 error (_("Target does not support this command."));
ad91cd99
PA
12528 if (strcmp (reply, "OK") != 0)
12529 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12530}
12531
b3b9301e 12532static struct traceframe_info *
a893e81f 12533remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12534{
12535 char *text;
12536
12537 text = target_read_stralloc (&current_target,
12538 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12539 if (text != NULL)
12540 {
12541 struct traceframe_info *info;
12542 struct cleanup *back_to = make_cleanup (xfree, text);
12543
12544 info = parse_traceframe_info (text);
12545 do_cleanups (back_to);
12546 return info;
12547 }
12548
12549 return NULL;
12550}
12551
405f8e94
SS
12552/* Handle the qTMinFTPILen packet. Returns the minimum length of
12553 instruction on which a fast tracepoint may be placed. Returns -1
12554 if the packet is not supported, and 0 if the minimum instruction
12555 length is unknown. */
12556
12557static int
0e67620a 12558remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12559{
12560 struct remote_state *rs = get_remote_state ();
12561 char *reply;
12562
e886a173
PA
12563 /* If we're not debugging a process yet, the IPA can't be
12564 loaded. */
12565 if (!target_has_execution)
12566 return 0;
12567
12568 /* Make sure the remote is pointing at the right process. */
12569 set_general_process ();
12570
bba74b36 12571 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12572 putpkt (rs->buf);
12573 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12574 if (*reply == '\0')
12575 return -1;
12576 else
12577 {
12578 ULONGEST min_insn_len;
12579
12580 unpack_varlen_hex (reply, &min_insn_len);
12581
12582 return (int) min_insn_len;
12583 }
12584}
12585
f6f899bf 12586static void
4da384be 12587remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12588{
4082afcc 12589 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12590 {
12591 struct remote_state *rs = get_remote_state ();
12592 char *buf = rs->buf;
12593 char *endbuf = rs->buf + get_remote_packet_size ();
12594 enum packet_result result;
12595
12596 gdb_assert (val >= 0 || val == -1);
12597 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12598 /* Send -1 as literal "-1" to avoid host size dependency. */
12599 if (val < 0)
12600 {
12601 *buf++ = '-';
12602 buf += hexnumstr (buf, (ULONGEST) -val);
12603 }
12604 else
12605 buf += hexnumstr (buf, (ULONGEST) val);
12606
12607 putpkt (rs->buf);
12608 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12609 result = packet_ok (rs->buf,
12610 &remote_protocol_packets[PACKET_QTBuffer_size]);
12611
12612 if (result != PACKET_OK)
12613 warning (_("Bogus reply from target: %s"), rs->buf);
12614 }
12615}
12616
f196051f 12617static int
d9e68a2c
TT
12618remote_set_trace_notes (struct target_ops *self,
12619 const char *user, const char *notes,
ca623f82 12620 const char *stop_notes)
f196051f
SS
12621{
12622 struct remote_state *rs = get_remote_state ();
12623 char *reply;
12624 char *buf = rs->buf;
12625 char *endbuf = rs->buf + get_remote_packet_size ();
12626 int nbytes;
12627
12628 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12629 if (user)
12630 {
12631 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12632 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12633 buf += 2 * nbytes;
12634 *buf++ = ';';
12635 }
12636 if (notes)
12637 {
12638 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12639 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12640 buf += 2 * nbytes;
12641 *buf++ = ';';
12642 }
12643 if (stop_notes)
12644 {
12645 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12646 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12647 buf += 2 * nbytes;
12648 *buf++ = ';';
12649 }
12650 /* Ensure the buffer is terminated. */
12651 *buf = '\0';
12652
12653 putpkt (rs->buf);
12654 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12655 if (*reply == '\0')
12656 return 0;
12657
12658 if (strcmp (reply, "OK") != 0)
12659 error (_("Bogus reply from target: %s"), reply);
12660
12661 return 1;
12662}
12663
d1feda86 12664static int
2c152180 12665remote_use_agent (struct target_ops *self, int use)
d1feda86 12666{
4082afcc 12667 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12668 {
12669 struct remote_state *rs = get_remote_state ();
12670
12671 /* If the stub supports QAgent. */
bba74b36 12672 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12673 putpkt (rs->buf);
12674 getpkt (&rs->buf, &rs->buf_size, 0);
12675
12676 if (strcmp (rs->buf, "OK") == 0)
12677 {
12678 use_agent = use;
12679 return 1;
12680 }
12681 }
12682
12683 return 0;
12684}
12685
12686static int
fe38f897 12687remote_can_use_agent (struct target_ops *self)
d1feda86 12688{
4082afcc 12689 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12690}
12691
9accd112
MM
12692struct btrace_target_info
12693{
12694 /* The ptid of the traced thread. */
12695 ptid_t ptid;
f4abbc16
MM
12696
12697 /* The obtained branch trace configuration. */
12698 struct btrace_config conf;
9accd112
MM
12699};
12700
f4abbc16
MM
12701/* Reset our idea of our target's btrace configuration. */
12702
12703static void
12704remote_btrace_reset (void)
12705{
12706 struct remote_state *rs = get_remote_state ();
12707
12708 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12709}
12710
9accd112
MM
12711/* Check whether the target supports branch tracing. */
12712
12713static int
043c3577 12714remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12715{
4082afcc 12716 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12717 return 0;
4082afcc 12718 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12719 return 0;
12720
043c3577
MM
12721 switch (format)
12722 {
12723 case BTRACE_FORMAT_NONE:
12724 return 0;
12725
12726 case BTRACE_FORMAT_BTS:
12727 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12728
12729 case BTRACE_FORMAT_PT:
12730 /* The trace is decoded on the host. Even if our target supports it,
12731 we still need to have libipt to decode the trace. */
12732#if defined (HAVE_LIBIPT)
12733 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12734#else /* !defined (HAVE_LIBIPT) */
12735 return 0;
12736#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12737 }
12738
12739 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12740}
12741
f4abbc16
MM
12742/* Synchronize the configuration with the target. */
12743
12744static void
12745btrace_sync_conf (const struct btrace_config *conf)
12746{
d33501a5
MM
12747 struct packet_config *packet;
12748 struct remote_state *rs;
12749 char *buf, *pos, *endbuf;
12750
12751 rs = get_remote_state ();
12752 buf = rs->buf;
12753 endbuf = buf + get_remote_packet_size ();
12754
12755 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12756 if (packet_config_support (packet) == PACKET_ENABLE
12757 && conf->bts.size != rs->btrace_config.bts.size)
12758 {
12759 pos = buf;
12760 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12761 conf->bts.size);
12762
12763 putpkt (buf);
12764 getpkt (&buf, &rs->buf_size, 0);
12765
12766 if (packet_ok (buf, packet) == PACKET_ERROR)
12767 {
12768 if (buf[0] == 'E' && buf[1] == '.')
12769 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12770 else
12771 error (_("Failed to configure the BTS buffer size."));
12772 }
12773
12774 rs->btrace_config.bts.size = conf->bts.size;
12775 }
b20a6524
MM
12776
12777 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12778 if (packet_config_support (packet) == PACKET_ENABLE
12779 && conf->pt.size != rs->btrace_config.pt.size)
12780 {
12781 pos = buf;
12782 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12783 conf->pt.size);
12784
12785 putpkt (buf);
12786 getpkt (&buf, &rs->buf_size, 0);
12787
12788 if (packet_ok (buf, packet) == PACKET_ERROR)
12789 {
12790 if (buf[0] == 'E' && buf[1] == '.')
12791 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12792 else
12793 error (_("Failed to configure the trace buffer size."));
12794 }
12795
12796 rs->btrace_config.pt.size = conf->pt.size;
12797 }
f4abbc16
MM
12798}
12799
12800/* Read the current thread's btrace configuration from the target and
12801 store it into CONF. */
12802
12803static void
12804btrace_read_config (struct btrace_config *conf)
12805{
12806 char *xml;
12807
12808 xml = target_read_stralloc (&current_target,
b20a6524 12809 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12810 if (xml != NULL)
12811 {
12812 struct cleanup *cleanup;
12813
12814 cleanup = make_cleanup (xfree, xml);
12815 parse_xml_btrace_conf (conf, xml);
12816 do_cleanups (cleanup);
12817 }
12818}
12819
9accd112
MM
12820/* Enable branch tracing. */
12821
12822static struct btrace_target_info *
f4abbc16
MM
12823remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12824 const struct btrace_config *conf)
9accd112
MM
12825{
12826 struct btrace_target_info *tinfo = NULL;
b20a6524 12827 struct packet_config *packet = NULL;
9accd112
MM
12828 struct remote_state *rs = get_remote_state ();
12829 char *buf = rs->buf;
12830 char *endbuf = rs->buf + get_remote_packet_size ();
12831
b20a6524
MM
12832 switch (conf->format)
12833 {
12834 case BTRACE_FORMAT_BTS:
12835 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12836 break;
12837
12838 case BTRACE_FORMAT_PT:
12839 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12840 break;
12841 }
12842
12843 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12844 error (_("Target does not support branch tracing."));
12845
f4abbc16
MM
12846 btrace_sync_conf (conf);
12847
9accd112
MM
12848 set_general_thread (ptid);
12849
12850 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12851 putpkt (rs->buf);
12852 getpkt (&rs->buf, &rs->buf_size, 0);
12853
12854 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12855 {
12856 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12857 error (_("Could not enable branch tracing for %s: %s"),
12858 target_pid_to_str (ptid), rs->buf + 2);
12859 else
12860 error (_("Could not enable branch tracing for %s."),
12861 target_pid_to_str (ptid));
12862 }
12863
8d749320 12864 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12865 tinfo->ptid = ptid;
12866
f4abbc16
MM
12867 /* If we fail to read the configuration, we lose some information, but the
12868 tracing itself is not impacted. */
492d29ea
PA
12869 TRY
12870 {
12871 btrace_read_config (&tinfo->conf);
12872 }
12873 CATCH (err, RETURN_MASK_ERROR)
12874 {
12875 if (err.message != NULL)
12876 warning ("%s", err.message);
12877 }
12878 END_CATCH
f4abbc16 12879
9accd112
MM
12880 return tinfo;
12881}
12882
12883/* Disable branch tracing. */
12884
12885static void
25e95349
TT
12886remote_disable_btrace (struct target_ops *self,
12887 struct btrace_target_info *tinfo)
9accd112
MM
12888{
12889 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12890 struct remote_state *rs = get_remote_state ();
12891 char *buf = rs->buf;
12892 char *endbuf = rs->buf + get_remote_packet_size ();
12893
4082afcc 12894 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12895 error (_("Target does not support branch tracing."));
12896
12897 set_general_thread (tinfo->ptid);
12898
12899 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12900 putpkt (rs->buf);
12901 getpkt (&rs->buf, &rs->buf_size, 0);
12902
12903 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12904 {
12905 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12906 error (_("Could not disable branch tracing for %s: %s"),
12907 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12908 else
12909 error (_("Could not disable branch tracing for %s."),
12910 target_pid_to_str (tinfo->ptid));
12911 }
12912
12913 xfree (tinfo);
12914}
12915
12916/* Teardown branch tracing. */
12917
12918static void
1777056d
TT
12919remote_teardown_btrace (struct target_ops *self,
12920 struct btrace_target_info *tinfo)
9accd112
MM
12921{
12922 /* We must not talk to the target during teardown. */
12923 xfree (tinfo);
12924}
12925
12926/* Read the branch trace. */
12927
969c39fb 12928static enum btrace_error
39c49f83 12929remote_read_btrace (struct target_ops *self,
734b0e4b 12930 struct btrace_data *btrace,
969c39fb 12931 struct btrace_target_info *tinfo,
9accd112
MM
12932 enum btrace_read_type type)
12933{
12934 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
969c39fb 12935 struct cleanup *cleanup;
9accd112
MM
12936 const char *annex;
12937 char *xml;
12938
4082afcc 12939 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12940 error (_("Target does not support branch tracing."));
12941
12942#if !defined(HAVE_LIBEXPAT)
12943 error (_("Cannot process branch tracing result. XML parsing not supported."));
12944#endif
12945
12946 switch (type)
12947 {
864089d2 12948 case BTRACE_READ_ALL:
9accd112
MM
12949 annex = "all";
12950 break;
864089d2 12951 case BTRACE_READ_NEW:
9accd112
MM
12952 annex = "new";
12953 break;
969c39fb
MM
12954 case BTRACE_READ_DELTA:
12955 annex = "delta";
12956 break;
9accd112
MM
12957 default:
12958 internal_error (__FILE__, __LINE__,
12959 _("Bad branch tracing read type: %u."),
12960 (unsigned int) type);
12961 }
12962
12963 xml = target_read_stralloc (&current_target,
b20a6524 12964 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12965 if (xml == NULL)
12966 return BTRACE_ERR_UNKNOWN;
9accd112 12967
969c39fb 12968 cleanup = make_cleanup (xfree, xml);
734b0e4b 12969 parse_xml_btrace (btrace, xml);
969c39fb 12970 do_cleanups (cleanup);
9accd112 12971
969c39fb 12972 return BTRACE_ERR_NONE;
9accd112
MM
12973}
12974
f4abbc16
MM
12975static const struct btrace_config *
12976remote_btrace_conf (struct target_ops *self,
12977 const struct btrace_target_info *tinfo)
12978{
12979 return &tinfo->conf;
12980}
12981
ced63ec0 12982static int
5436ff03 12983remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12984{
4082afcc
PA
12985 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12986 == PACKET_ENABLE);
ced63ec0
GB
12987}
12988
9dd130a0
TT
12989/* Implementation of to_load. */
12990
12991static void
9cbe5fff 12992remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12993{
12994 generic_load (name, from_tty);
12995}
12996
c78fa86a
GB
12997/* Accepts an integer PID; returns a string representing a file that
12998 can be opened on the remote side to get the symbols for the child
12999 process. Returns NULL if the operation is not supported. */
13000
13001static char *
13002remote_pid_to_exec_file (struct target_ops *self, int pid)
13003{
13004 static char *filename = NULL;
835205d0
GB
13005 struct inferior *inf;
13006 char *annex = NULL;
c78fa86a
GB
13007
13008 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13009 return NULL;
13010
13011 if (filename != NULL)
13012 xfree (filename);
13013
835205d0
GB
13014 inf = find_inferior_pid (pid);
13015 if (inf == NULL)
13016 internal_error (__FILE__, __LINE__,
13017 _("not currently attached to process %d"), pid);
13018
13019 if (!inf->fake_pid_p)
13020 {
13021 const int annex_size = 9;
13022
224c3ddb 13023 annex = (char *) alloca (annex_size);
835205d0
GB
13024 xsnprintf (annex, annex_size, "%x", pid);
13025 }
13026
c78fa86a
GB
13027 filename = target_read_stralloc (&current_target,
13028 TARGET_OBJECT_EXEC_FILE, annex);
13029
13030 return filename;
13031}
13032
750ce8d1
YQ
13033/* Implement the to_can_do_single_step target_ops method. */
13034
13035static int
13036remote_can_do_single_step (struct target_ops *ops)
13037{
13038 /* We can only tell whether target supports single step or not by
13039 supported s and S vCont actions if the stub supports vContSupported
13040 feature. If the stub doesn't support vContSupported feature,
13041 we have conservatively to think target doesn't supports single
13042 step. */
13043 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13044 {
13045 struct remote_state *rs = get_remote_state ();
13046
13047 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13048 remote_vcont_probe (rs);
13049
13050 return rs->supports_vCont.s && rs->supports_vCont.S;
13051 }
13052 else
13053 return 0;
13054}
13055
c906108c 13056static void
fba45db2 13057init_remote_ops (void)
c906108c 13058{
c5aa993b 13059 remote_ops.to_shortname = "remote";
c906108c 13060 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 13061 remote_ops.to_doc =
c906108c 13062 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
13063Specify the serial device it is connected to\n\
13064(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
13065 remote_ops.to_open = remote_open;
13066 remote_ops.to_close = remote_close;
c906108c 13067 remote_ops.to_detach = remote_detach;
6ad8ae5c 13068 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 13069 remote_ops.to_resume = remote_resume;
c906108c
SS
13070 remote_ops.to_wait = remote_wait;
13071 remote_ops.to_fetch_registers = remote_fetch_registers;
13072 remote_ops.to_store_registers = remote_store_registers;
13073 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 13074 remote_ops.to_files_info = remote_files_info;
c906108c
SS
13075 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13076 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
13077 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13078 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13079 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13080 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
13081 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13082 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
13083 remote_ops.to_watchpoint_addr_within_range =
13084 remote_watchpoint_addr_within_range;
3c3bea1c
GS
13085 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13086 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13087 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
13088 remote_ops.to_region_ok_for_hw_watchpoint
13089 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
13090 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13091 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 13092 remote_ops.to_kill = remote_kill;
9dd130a0 13093 remote_ops.to_load = remote_load;
c906108c 13094 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 13095 remote_ops.to_pass_signals = remote_pass_signals;
82075af2 13096 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
9b224c5e 13097 remote_ops.to_program_signals = remote_program_signals;
c906108c 13098 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 13099 remote_ops.to_thread_name = remote_thread_name;
e8032dde 13100 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 13101 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 13102 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 13103 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 13104 remote_ops.to_stop = remote_stop;
bfedc46a 13105 remote_ops.to_interrupt = remote_interrupt;
abc56d60 13106 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
4b8a223f 13107 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 13108 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 13109 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 13110 remote_ops.to_log_command = serial_log_command;
38691318 13111 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 13112 remote_ops.to_stratum = process_stratum;
c35b1492
PA
13113 remote_ops.to_has_all_memory = default_child_has_all_memory;
13114 remote_ops.to_has_memory = default_child_has_memory;
13115 remote_ops.to_has_stack = default_child_has_stack;
13116 remote_ops.to_has_registers = default_child_has_registers;
13117 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 13118 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13119 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13120 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13121 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13122 remote_ops.to_flash_erase = remote_flash_erase;
13123 remote_ops.to_flash_done = remote_flash_done;
29709017 13124 remote_ops.to_read_description = remote_read_description;
08388c79 13125 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13126 remote_ops.to_can_async_p = remote_can_async_p;
13127 remote_ops.to_is_async_p = remote_is_async_p;
13128 remote_ops.to_async = remote_async;
65706a29 13129 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13130 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13131 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13132 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13133 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13134 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13135 remote_ops.to_supports_disable_randomization
13136 = remote_supports_disable_randomization;
4bd7dc42 13137 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13138 remote_ops.to_fileio_open = remote_hostio_open;
13139 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13140 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13141 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13142 remote_ops.to_fileio_close = remote_hostio_close;
13143 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13144 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13145 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13146 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13147 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13148 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13149 remote_ops.to_trace_init = remote_trace_init;
13150 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13151 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13152 remote_ops.to_download_trace_state_variable
13153 = remote_download_trace_state_variable;
d248b706
KY
13154 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13155 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13156 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13157 remote_ops.to_trace_start = remote_trace_start;
13158 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13159 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13160 remote_ops.to_trace_stop = remote_trace_stop;
13161 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13162 remote_ops.to_get_trace_state_variable_value
13163 = remote_get_trace_state_variable_value;
00bf0b85
SS
13164 remote_ops.to_save_trace_data = remote_save_trace_data;
13165 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13166 remote_ops.to_upload_trace_state_variables
13167 = remote_upload_trace_state_variables;
00bf0b85 13168 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13169 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13170 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13171 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13172 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13173 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13174 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13175 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13176 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13177 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13178 remote_ops.to_static_tracepoint_marker_at
13179 = remote_static_tracepoint_marker_at;
13180 remote_ops.to_static_tracepoint_markers_by_strid
13181 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13182 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13183 remote_ops.to_use_agent = remote_use_agent;
13184 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13185 remote_ops.to_supports_btrace = remote_supports_btrace;
13186 remote_ops.to_enable_btrace = remote_enable_btrace;
13187 remote_ops.to_disable_btrace = remote_disable_btrace;
13188 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13189 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13190 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13191 remote_ops.to_augmented_libraries_svr4_read =
13192 remote_augmented_libraries_svr4_read;
8020350c
DB
13193 remote_ops.to_follow_fork = remote_follow_fork;
13194 remote_ops.to_follow_exec = remote_follow_exec;
13195 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13196 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13197 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13198 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13199 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13200 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
c906108c
SS
13201}
13202
13203/* Set up the extended remote vector by making a copy of the standard
13204 remote vector and adding to it. */
13205
13206static void
fba45db2 13207init_extended_remote_ops (void)
c906108c
SS
13208{
13209 extended_remote_ops = remote_ops;
13210
0f71a2f6 13211 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13212 extended_remote_ops.to_longname =
c906108c 13213 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13214 extended_remote_ops.to_doc =
c906108c 13215 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13216Specify the serial device it is connected to (e.g. /dev/ttya).";
13217 extended_remote_ops.to_open = extended_remote_open;
c906108c 13218 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
2d717e4f
DJ
13219 extended_remote_ops.to_detach = extended_remote_detach;
13220 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13221 extended_remote_ops.to_post_attach = extended_remote_post_attach;
03583c20
UW
13222 extended_remote_ops.to_supports_disable_randomization
13223 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
13224}
13225
6426a772 13226static int
6a109b6b 13227remote_can_async_p (struct target_ops *ops)
6426a772 13228{
5d93a237
TT
13229 struct remote_state *rs = get_remote_state ();
13230
c6ebd6cf 13231 if (!target_async_permitted)
75c99385
PA
13232 /* We only enable async when the user specifically asks for it. */
13233 return 0;
13234
23860348 13235 /* We're async whenever the serial device is. */
5d93a237 13236 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13237}
13238
13239static int
6a109b6b 13240remote_is_async_p (struct target_ops *ops)
6426a772 13241{
5d93a237
TT
13242 struct remote_state *rs = get_remote_state ();
13243
c6ebd6cf 13244 if (!target_async_permitted)
75c99385
PA
13245 /* We only enable async when the user specifically asks for it. */
13246 return 0;
13247
23860348 13248 /* We're async whenever the serial device is. */
5d93a237 13249 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13250}
13251
2acceee2
JM
13252/* Pass the SERIAL event on and up to the client. One day this code
13253 will be able to delay notifying the client of an event until the
23860348 13254 point where an entire packet has been received. */
2acceee2 13255
2acceee2
JM
13256static serial_event_ftype remote_async_serial_handler;
13257
6426a772 13258static void
819cc324 13259remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13260{
2acceee2
JM
13261 /* Don't propogate error information up to the client. Instead let
13262 the client find out about the error by querying the target. */
6a3753b3 13263 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13264}
13265
74531fed
PA
13266static void
13267remote_async_inferior_event_handler (gdb_client_data data)
13268{
13269 inferior_event_handler (INF_REG_EVENT, NULL);
13270}
13271
2acceee2 13272static void
6a3753b3 13273remote_async (struct target_ops *ops, int enable)
2acceee2 13274{
5d93a237
TT
13275 struct remote_state *rs = get_remote_state ();
13276
6a3753b3 13277 if (enable)
2acceee2 13278 {
88b496c3 13279 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13280
13281 /* If there are pending events in the stop reply queue tell the
13282 event loop to process them. */
13283 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13284 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13285 /* For simplicity, below we clear the pending events token
13286 without remembering whether it is marked, so here we always
13287 mark it. If there's actually no pending notification to
13288 process, this ends up being a no-op (other than a spurious
13289 event-loop wakeup). */
13290 if (target_is_non_stop_p ())
13291 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13292 }
13293 else
b7d2e916
PA
13294 {
13295 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13296 /* If the core is disabling async, it doesn't want to be
13297 disturbed with target events. Clear all async event sources
13298 too. */
b7d2e916 13299 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13300 if (target_is_non_stop_p ())
13301 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13302 }
6426a772
JM
13303}
13304
65706a29
PA
13305/* Implementation of the to_thread_events method. */
13306
13307static void
13308remote_thread_events (struct target_ops *ops, int enable)
13309{
13310 struct remote_state *rs = get_remote_state ();
13311 size_t size = get_remote_packet_size ();
65706a29
PA
13312
13313 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13314 return;
13315
13316 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13317 putpkt (rs->buf);
13318 getpkt (&rs->buf, &rs->buf_size, 0);
13319
13320 switch (packet_ok (rs->buf,
13321 &remote_protocol_packets[PACKET_QThreadEvents]))
13322 {
13323 case PACKET_OK:
13324 if (strcmp (rs->buf, "OK") != 0)
13325 error (_("Remote refused setting thread events: %s"), rs->buf);
13326 break;
13327 case PACKET_ERROR:
13328 warning (_("Remote failure reply: %s"), rs->buf);
13329 break;
13330 case PACKET_UNKNOWN:
13331 break;
13332 }
13333}
13334
5a2468f5 13335static void
c2d11a7d 13336set_remote_cmd (char *args, int from_tty)
5a2468f5 13337{
635c7e8a 13338 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13339}
13340
d471ea57
AC
13341static void
13342show_remote_cmd (char *args, int from_tty)
13343{
37a105a1 13344 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13345 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13346 struct cleanup *showlist_chain;
13347 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13348 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13349
13350 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13351 for (; list != NULL; list = list->next)
13352 if (strcmp (list->name, "Z-packet") == 0)
13353 continue;
427c3a89
DJ
13354 else if (list->type == not_set_cmd)
13355 /* Alias commands are exactly like the original, except they
13356 don't have the normal type. */
13357 continue;
13358 else
37a105a1
DJ
13359 {
13360 struct cleanup *option_chain
13361 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13362
37a105a1
DJ
13363 ui_out_field_string (uiout, "name", list->name);
13364 ui_out_text (uiout, ": ");
427c3a89 13365 if (list->type == show_cmd)
5b9afe8a 13366 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
13367 else
13368 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13369 /* Close the tuple. */
13370 do_cleanups (option_chain);
13371 }
427c3a89
DJ
13372
13373 /* Close the tuple. */
13374 do_cleanups (showlist_chain);
d471ea57 13375}
5a2468f5 13376
0f71a2f6 13377
23860348 13378/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13379static void
13380remote_new_objfile (struct objfile *objfile)
13381{
5d93a237
TT
13382 struct remote_state *rs = get_remote_state ();
13383
13384 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13385 remote_check_symbols ();
dc8acb97
MS
13386}
13387
00bf0b85
SS
13388/* Pull all the tracepoints defined on the target and create local
13389 data structures representing them. We don't want to create real
13390 tracepoints yet, we don't want to mess up the user's existing
13391 collection. */
13392
13393static int
ab6617cc 13394remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13395{
00bf0b85
SS
13396 struct remote_state *rs = get_remote_state ();
13397 char *p;
d5551862 13398
00bf0b85
SS
13399 /* Ask for a first packet of tracepoint definition. */
13400 putpkt ("qTfP");
13401 getpkt (&rs->buf, &rs->buf_size, 0);
13402 p = rs->buf;
13403 while (*p && *p != 'l')
d5551862 13404 {
00bf0b85
SS
13405 parse_tracepoint_definition (p, utpp);
13406 /* Ask for another packet of tracepoint definition. */
13407 putpkt ("qTsP");
13408 getpkt (&rs->buf, &rs->buf_size, 0);
13409 p = rs->buf;
d5551862 13410 }
00bf0b85 13411 return 0;
d5551862
SS
13412}
13413
00bf0b85 13414static int
181e3713
TT
13415remote_upload_trace_state_variables (struct target_ops *self,
13416 struct uploaded_tsv **utsvp)
d5551862 13417{
00bf0b85 13418 struct remote_state *rs = get_remote_state ();
d5551862 13419 char *p;
d5551862 13420
00bf0b85
SS
13421 /* Ask for a first packet of variable definition. */
13422 putpkt ("qTfV");
d5551862
SS
13423 getpkt (&rs->buf, &rs->buf_size, 0);
13424 p = rs->buf;
00bf0b85 13425 while (*p && *p != 'l')
d5551862 13426 {
00bf0b85
SS
13427 parse_tsv_definition (p, utsvp);
13428 /* Ask for another packet of variable definition. */
13429 putpkt ("qTsV");
d5551862
SS
13430 getpkt (&rs->buf, &rs->buf_size, 0);
13431 p = rs->buf;
13432 }
00bf0b85 13433 return 0;
d5551862
SS
13434}
13435
c1e36e3e
PA
13436/* The "set/show range-stepping" show hook. */
13437
13438static void
13439show_range_stepping (struct ui_file *file, int from_tty,
13440 struct cmd_list_element *c,
13441 const char *value)
13442{
13443 fprintf_filtered (file,
13444 _("Debugger's willingness to use range stepping "
13445 "is %s.\n"), value);
13446}
13447
13448/* The "set/show range-stepping" set hook. */
13449
13450static void
13451set_range_stepping (char *ignore_args, int from_tty,
13452 struct cmd_list_element *c)
13453{
5d93a237
TT
13454 struct remote_state *rs = get_remote_state ();
13455
c1e36e3e
PA
13456 /* Whene enabling, check whether range stepping is actually
13457 supported by the target, and warn if not. */
13458 if (use_range_stepping)
13459 {
5d93a237 13460 if (rs->remote_desc != NULL)
c1e36e3e 13461 {
4082afcc 13462 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13463 remote_vcont_probe (rs);
13464
4082afcc 13465 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13466 && rs->supports_vCont.r)
13467 return;
13468 }
13469
13470 warning (_("Range stepping is not supported by the current target"));
13471 }
13472}
13473
c906108c 13474void
fba45db2 13475_initialize_remote (void)
c906108c 13476{
9a7071a8 13477 struct cmd_list_element *cmd;
6f937416 13478 const char *cmd_name;
ea9c271d 13479
0f71a2f6 13480 /* architecture specific data */
2bc416ba 13481 remote_gdbarch_data_handle =
23860348 13482 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13483 remote_g_packet_data_handle =
13484 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13485
94585166
DB
13486 remote_pspace_data
13487 = register_program_space_data_with_cleanup (NULL,
13488 remote_pspace_data_cleanup);
13489
ea9c271d
DJ
13490 /* Initialize the per-target state. At the moment there is only one
13491 of these, not one per target. Only one target is active at a
cf792862
TT
13492 time. */
13493 remote_state = new_remote_state ();
ea9c271d 13494
c906108c
SS
13495 init_remote_ops ();
13496 add_target (&remote_ops);
13497
13498 init_extended_remote_ops ();
13499 add_target (&extended_remote_ops);
cce74817 13500
dc8acb97 13501 /* Hook into new objfile notification. */
06d3b283 13502 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13503 /* We're no longer interested in notification events of an inferior
13504 when it exits. */
13505 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13506
b803fb0f 13507 /* Set up signal handlers. */
934b9bac 13508 async_sigint_remote_token =
b803fb0f 13509 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 13510 async_sigint_remote_twice_token =
6d549500 13511 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 13512
c906108c
SS
13513#if 0
13514 init_remote_threadtests ();
13515#endif
13516
722247f1 13517 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13518 /* set/show remote ... */
d471ea57 13519
1bedd215 13520 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13521Remote protocol specific variables\n\
13522Configure various remote-protocol specific variables such as\n\
1bedd215 13523the packets being used"),
cff3e48b 13524 &remote_set_cmdlist, "set remote ",
23860348 13525 0 /* allow-unknown */, &setlist);
1bedd215 13526 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13527Remote protocol specific variables\n\
13528Configure various remote-protocol specific variables such as\n\
1bedd215 13529the packets being used"),
cff3e48b 13530 &remote_show_cmdlist, "show remote ",
23860348 13531 0 /* allow-unknown */, &showlist);
5a2468f5 13532
1a966eab
AC
13533 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13534Compare section data on target to the exec file.\n\
95cf3b38
DT
13535Argument is a single section name (default: all loaded sections).\n\
13536To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13537 &cmdlist);
13538
1a966eab
AC
13539 add_cmd ("packet", class_maintenance, packet_command, _("\
13540Send an arbitrary packet to a remote target.\n\
c906108c
SS
13541 maintenance packet TEXT\n\
13542If GDB is talking to an inferior via the GDB serial protocol, then\n\
13543this command sends the string TEXT to the inferior, and displays the\n\
13544response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13545terminating `#' character and checksum."),
c906108c
SS
13546 &maintenancelist);
13547
7915a72c
AC
13548 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13549Set whether to send break if interrupted."), _("\
13550Show whether to send break if interrupted."), _("\
13551If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13552 set_remotebreak, show_remotebreak,
e707bbc2 13553 &setlist, &showlist);
9a7071a8
JB
13554 cmd_name = "remotebreak";
13555 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13556 deprecate_cmd (cmd, "set remote interrupt-sequence");
13557 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13558 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13559 deprecate_cmd (cmd, "show remote interrupt-sequence");
13560
13561 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13562 interrupt_sequence_modes, &interrupt_sequence_mode,
13563 _("\
9a7071a8
JB
13564Set interrupt sequence to remote target."), _("\
13565Show interrupt sequence to remote target."), _("\
13566Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13567 NULL, show_interrupt_sequence,
13568 &remote_set_cmdlist,
13569 &remote_show_cmdlist);
13570
13571 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13572 &interrupt_on_connect, _("\
13573Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13574Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13575If set, interrupt sequence is sent to remote target."),
13576 NULL, NULL,
13577 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13578
23860348 13579 /* Install commands for configuring memory read/write packets. */
11cf8741 13580
1a966eab
AC
13581 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13582Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13583 &setlist);
1a966eab
AC
13584 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13585Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13586 &showlist);
13587 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13588 set_memory_write_packet_size, _("\
13589Set the maximum number of bytes per memory-write packet.\n\
13590Specify the number of bytes in a packet or 0 (zero) for the\n\
13591default packet size. The actual limit is further reduced\n\
13592dependent on the target. Specify ``fixed'' to disable the\n\
13593further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13594 &remote_set_cmdlist);
13595 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13596 set_memory_read_packet_size, _("\
13597Set the maximum number of bytes per memory-read packet.\n\
13598Specify the number of bytes in a packet or 0 (zero) for the\n\
13599default packet size. The actual limit is further reduced\n\
13600dependent on the target. Specify ``fixed'' to disable the\n\
13601further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13602 &remote_set_cmdlist);
13603 add_cmd ("memory-write-packet-size", no_class,
13604 show_memory_write_packet_size,
1a966eab 13605 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13606 &remote_show_cmdlist);
13607 add_cmd ("memory-read-packet-size", no_class,
13608 show_memory_read_packet_size,
1a966eab 13609 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13610 &remote_show_cmdlist);
c906108c 13611
b3f42336 13612 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13613 &remote_hw_watchpoint_limit, _("\
13614Set the maximum number of target hardware watchpoints."), _("\
13615Show the maximum number of target hardware watchpoints."), _("\
13616Specify a negative limit for unlimited."),
3e43a32a
MS
13617 NULL, NULL, /* FIXME: i18n: The maximum
13618 number of target hardware
13619 watchpoints is %s. */
b3f42336 13620 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13621 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13622 &remote_hw_watchpoint_length_limit, _("\
13623Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13624Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13625Specify a negative limit for unlimited."),
13626 NULL, NULL, /* FIXME: i18n: The maximum
13627 length (in bytes) of a target
13628 hardware watchpoint is %s. */
13629 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13630 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13631 &remote_hw_breakpoint_limit, _("\
13632Set the maximum number of target hardware breakpoints."), _("\
13633Show the maximum number of target hardware breakpoints."), _("\
13634Specify a negative limit for unlimited."),
3e43a32a
MS
13635 NULL, NULL, /* FIXME: i18n: The maximum
13636 number of target hardware
13637 breakpoints is %s. */
b3f42336 13638 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13639
1b493192
PA
13640 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13641 &remote_address_size, _("\
4d28ad1e
AC
13642Set the maximum size of the address (in bits) in a memory packet."), _("\
13643Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13644 NULL,
13645 NULL, /* FIXME: i18n: */
13646 &setlist, &showlist);
c906108c 13647
ca4f7f8b
PA
13648 init_all_packet_configs ();
13649
444abaca 13650 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13651 "X", "binary-download", 1);
0f71a2f6 13652
444abaca 13653 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13654 "vCont", "verbose-resume", 0);
506fb367 13655
89be2091
DJ
13656 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13657 "QPassSignals", "pass-signals", 0);
13658
82075af2
JS
13659 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13660 "QCatchSyscalls", "catch-syscalls", 0);
13661
9b224c5e
PA
13662 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13663 "QProgramSignals", "program-signals", 0);
13664
444abaca 13665 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13666 "qSymbol", "symbol-lookup", 0);
dc8acb97 13667
444abaca 13668 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13669 "P", "set-register", 1);
d471ea57 13670
444abaca 13671 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13672 "p", "fetch-register", 1);
b96ec7ac 13673
444abaca 13674 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13675 "Z0", "software-breakpoint", 0);
d471ea57 13676
444abaca 13677 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13678 "Z1", "hardware-breakpoint", 0);
d471ea57 13679
444abaca 13680 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13681 "Z2", "write-watchpoint", 0);
d471ea57 13682
444abaca 13683 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13684 "Z3", "read-watchpoint", 0);
d471ea57 13685
444abaca 13686 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13687 "Z4", "access-watchpoint", 0);
d471ea57 13688
0876f84a
DJ
13689 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13690 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13691
c78fa86a
GB
13692 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13693 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13694
23181151
DJ
13695 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13696 "qXfer:features:read", "target-features", 0);
13697
cfa9d6d9
DJ
13698 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13699 "qXfer:libraries:read", "library-info", 0);
13700
2268b414
JK
13701 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13702 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13703
fd79ecee
DJ
13704 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13705 "qXfer:memory-map:read", "memory-map", 0);
13706
0e7f50da
UW
13707 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13708 "qXfer:spu:read", "read-spu-object", 0);
13709
13710 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13711 "qXfer:spu:write", "write-spu-object", 0);
13712
07e059b5
VP
13713 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13714 "qXfer:osdata:read", "osdata", 0);
13715
dc146f7c
VP
13716 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13717 "qXfer:threads:read", "threads", 0);
13718
4aa995e1
PA
13719 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13720 "qXfer:siginfo:read", "read-siginfo-object", 0);
13721
13722 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13723 "qXfer:siginfo:write", "write-siginfo-object", 0);
13724
b3b9301e
PA
13725 add_packet_config_cmd
13726 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13727 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13728
169081d0
TG
13729 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13730 "qXfer:uib:read", "unwind-info-block", 0);
13731
444abaca 13732 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13733 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13734 0);
13735
711e434b
PM
13736 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13737 "qGetTIBAddr", "get-thread-information-block-address",
13738 0);
13739
40ab02ce
MS
13740 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13741 "bc", "reverse-continue", 0);
13742
13743 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13744 "bs", "reverse-step", 0);
13745
be2a5f71
DJ
13746 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13747 "qSupported", "supported-packets", 0);
13748
08388c79
DE
13749 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13750 "qSearch:memory", "search-memory", 0);
13751
bd3eecc3
PA
13752 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13753 "qTStatus", "trace-status", 0);
13754
15a201c8
GB
13755 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13756 "vFile:setfs", "hostio-setfs", 0);
13757
a6b151f1
DJ
13758 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13759 "vFile:open", "hostio-open", 0);
13760
13761 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13762 "vFile:pread", "hostio-pread", 0);
13763
13764 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13765 "vFile:pwrite", "hostio-pwrite", 0);
13766
13767 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13768 "vFile:close", "hostio-close", 0);
13769
13770 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13771 "vFile:unlink", "hostio-unlink", 0);
13772
b9e7b9c3
UW
13773 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13774 "vFile:readlink", "hostio-readlink", 0);
13775
0a93529c
GB
13776 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13777 "vFile:fstat", "hostio-fstat", 0);
13778
2d717e4f
DJ
13779 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13780 "vAttach", "attach", 0);
13781
13782 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13783 "vRun", "run", 0);
13784
a6f3e723
SL
13785 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13786 "QStartNoAckMode", "noack", 0);
13787
82f73884
PA
13788 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13789 "vKill", "kill", 0);
13790
0b16c5cf
PA
13791 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13792 "qAttached", "query-attached", 0);
13793
782b2b07 13794 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13795 "ConditionalTracepoints",
13796 "conditional-tracepoints", 0);
3788aec7
LM
13797
13798 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13799 "ConditionalBreakpoints",
13800 "conditional-breakpoints", 0);
13801
d3ce09f5
SS
13802 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13803 "BreakpointCommands",
13804 "breakpoint-commands", 0);
13805
7a697b8d
SS
13806 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13807 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13808
409873ef
SS
13809 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13810 "TracepointSource", "TracepointSource", 0);
13811
d914c394
SS
13812 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13813 "QAllow", "allow", 0);
13814
0fb4aa4b
PA
13815 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13816 "StaticTracepoints", "static-tracepoints", 0);
13817
1e4d1764
YQ
13818 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13819 "InstallInTrace", "install-in-trace", 0);
13820
0fb4aa4b
PA
13821 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13822 "qXfer:statictrace:read", "read-sdata-object", 0);
13823
78d85199
YQ
13824 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13825 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13826
03583c20
UW
13827 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13828 "QDisableRandomization", "disable-randomization", 0);
13829
d1feda86
YQ
13830 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13831 "QAgent", "agent", 0);
13832
f6f899bf
HAQ
13833 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13834 "QTBuffer:size", "trace-buffer-size", 0);
13835
9accd112
MM
13836 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13837 "Qbtrace:off", "disable-btrace", 0);
13838
13839 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13840 "Qbtrace:bts", "enable-btrace-bts", 0);
13841
13842 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13843 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13844
13845 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13846 "qXfer:btrace", "read-btrace", 0);
13847
f4abbc16
MM
13848 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13849 "qXfer:btrace-conf", "read-btrace-conf", 0);
13850
d33501a5
MM
13851 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13852 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13853
73b8c1fd
PA
13854 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13855 "multiprocess-feature", "multiprocess-feature", 0);
13856
f7e6eed5
PA
13857 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13858 "swbreak-feature", "swbreak-feature", 0);
13859
13860 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13861 "hwbreak-feature", "hwbreak-feature", 0);
13862
89245bc0
DB
13863 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13864 "fork-event-feature", "fork-event-feature", 0);
13865
13866 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13867 "vfork-event-feature", "vfork-event-feature", 0);
13868
b20a6524
MM
13869 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13870 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13871
750ce8d1
YQ
13872 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13873 "vContSupported", "verbose-resume-supported", 0);
13874
94585166
DB
13875 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13876 "exec-event-feature", "exec-event-feature", 0);
13877
de979965
PA
13878 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13879 "vCtrlC", "ctrl-c", 0);
13880
65706a29
PA
13881 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13882 "QThreadEvents", "thread-events", 0);
13883
f2faf941
PA
13884 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13885 "N stop reply", "no-resumed-stop-reply", 0);
13886
0b736949
DB
13887 /* Assert that we've registered "set remote foo-packet" commands
13888 for all packet configs. */
ca4f7f8b
PA
13889 {
13890 int i;
13891
13892 for (i = 0; i < PACKET_MAX; i++)
13893 {
13894 /* Ideally all configs would have a command associated. Some
13895 still don't though. */
13896 int excepted;
13897
13898 switch (i)
13899 {
13900 case PACKET_QNonStop:
ca4f7f8b
PA
13901 case PACKET_EnableDisableTracepoints_feature:
13902 case PACKET_tracenz_feature:
13903 case PACKET_DisconnectedTracing_feature:
13904 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13905 case PACKET_qCRC:
13906 /* Additions to this list need to be well justified:
13907 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13908 excepted = 1;
13909 break;
13910 default:
13911 excepted = 0;
13912 break;
13913 }
13914
13915 /* This catches both forgetting to add a config command, and
13916 forgetting to remove a packet from the exception list. */
13917 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13918 }
13919 }
13920
37a105a1
DJ
13921 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13922 Z sub-packet has its own set and show commands, but users may
13923 have sets to this variable in their .gdbinit files (or in their
13924 documentation). */
e9e68a56 13925 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13926 &remote_Z_packet_detect, _("\
13927Set use of remote protocol `Z' packets"), _("\
13928Show use of remote protocol `Z' packets "), _("\
3b64bf98 13929When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13930packets."),
e9e68a56 13931 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13932 show_remote_protocol_Z_packet_cmd,
13933 /* FIXME: i18n: Use of remote protocol
13934 `Z' packets is %s. */
e9e68a56 13935 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13936
a6b151f1
DJ
13937 add_prefix_cmd ("remote", class_files, remote_command, _("\
13938Manipulate files on the remote system\n\
13939Transfer files to and from the remote target system."),
13940 &remote_cmdlist, "remote ",
13941 0 /* allow-unknown */, &cmdlist);
13942
13943 add_cmd ("put", class_files, remote_put_command,
13944 _("Copy a local file to the remote system."),
13945 &remote_cmdlist);
13946
13947 add_cmd ("get", class_files, remote_get_command,
13948 _("Copy a remote file to the local system."),
13949 &remote_cmdlist);
13950
13951 add_cmd ("delete", class_files, remote_delete_command,
13952 _("Delete a remote file."),
13953 &remote_cmdlist);
13954
2d717e4f 13955 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13956 &remote_exec_file_var, _("\
2d717e4f 13957Set the remote pathname for \"run\""), _("\
94585166
DB
13958Show the remote pathname for \"run\""), NULL,
13959 set_remote_exec_file,
13960 show_remote_exec_file,
13961 &remote_set_cmdlist,
13962 &remote_show_cmdlist);
2d717e4f 13963
c1e36e3e
PA
13964 add_setshow_boolean_cmd ("range-stepping", class_run,
13965 &use_range_stepping, _("\
13966Enable or disable range stepping."), _("\
13967Show whether target-assisted range stepping is enabled."), _("\
13968If on, and the target supports it, when stepping a source line, GDB\n\
13969tells the target to step the corresponding range of addresses itself instead\n\
13970of issuing multiple single-steps. This speeds up source level\n\
13971stepping. If off, GDB always issues single-steps, even if range\n\
13972stepping is supported by the target. The default is on."),
13973 set_range_stepping,
13974 show_range_stepping,
13975 &setlist,
13976 &showlist);
13977
449092f6
CV
13978 /* Eventually initialize fileio. See fileio.c */
13979 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13980
ba348170 13981 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13982 special ptids with it set to != 0. */
ba348170
PA
13983 magic_null_ptid = ptid_build (42000, -1, 1);
13984 not_sent_ptid = ptid_build (42000, -2, 1);
13985 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13986
13987 target_buf_size = 2048;
224c3ddb 13988 target_buf = (char *) xmalloc (target_buf_size);
c906108c 13989}
10760264 13990
This page took 3.121497 seconds and 4 git commands to generate.