Regenerate or1k opcodes file
[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
f7e6eed5
PA
1499/* Returns the packet's corresponding "set remote foo-packet" command
1500 state. See struct packet_config for more details. */
1501
1502static enum auto_boolean
1503packet_set_cmd_state (int packet)
1504{
1505 return remote_protocol_packets[packet].detect;
1506}
1507
4082afcc
PA
1508/* Returns whether a given packet or feature is supported. This takes
1509 into account the state of the corresponding "set remote foo-packet"
1510 command, which may be used to bypass auto-detection. */
dc8acb97 1511
4082afcc
PA
1512static enum packet_support
1513packet_config_support (struct packet_config *config)
1514{
1515 switch (config->detect)
444abaca 1516 {
4082afcc
PA
1517 case AUTO_BOOLEAN_TRUE:
1518 return PACKET_ENABLE;
1519 case AUTO_BOOLEAN_FALSE:
1520 return PACKET_DISABLE;
1521 case AUTO_BOOLEAN_AUTO:
1522 return config->support;
1523 default:
1524 gdb_assert_not_reached (_("bad switch"));
444abaca 1525 }
4082afcc
PA
1526}
1527
1528/* Same as packet_config_support, but takes the packet's enum value as
1529 argument. */
1530
1531static enum packet_support
1532packet_support (int packet)
1533{
1534 struct packet_config *config = &remote_protocol_packets[packet];
1535
1536 return packet_config_support (config);
dc8acb97
MS
1537}
1538
5a2468f5 1539static void
444abaca
DJ
1540show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1541 struct cmd_list_element *c,
1542 const char *value)
5a2468f5 1543{
444abaca 1544 struct packet_config *packet;
5a2468f5 1545
444abaca
DJ
1546 for (packet = remote_protocol_packets;
1547 packet < &remote_protocol_packets[PACKET_MAX];
1548 packet++)
1549 {
1550 if (&packet->detect == c->var)
1551 {
1552 show_packet_config_cmd (packet);
1553 return;
1554 }
1555 }
9b20d036 1556 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1557 c->name);
5a2468f5
JM
1558}
1559
d471ea57
AC
1560/* Should we try one of the 'Z' requests? */
1561
1562enum Z_packet_type
1563{
1564 Z_PACKET_SOFTWARE_BP,
1565 Z_PACKET_HARDWARE_BP,
1566 Z_PACKET_WRITE_WP,
1567 Z_PACKET_READ_WP,
1568 Z_PACKET_ACCESS_WP,
1569 NR_Z_PACKET_TYPES
1570};
96baa820 1571
d471ea57 1572/* For compatibility with older distributions. Provide a ``set remote
23860348 1573 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1574
7f19b9a2 1575static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1576
1577static void
fba45db2
KB
1578set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1579 struct cmd_list_element *c)
96baa820 1580{
d471ea57 1581 int i;
a744cf53 1582
d471ea57 1583 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1584 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1585}
1586
1587static void
08546159
AC
1588show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1589 struct cmd_list_element *c,
1590 const char *value)
96baa820 1591{
d471ea57 1592 int i;
a744cf53 1593
d471ea57
AC
1594 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1595 {
444abaca 1596 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1597 }
96baa820
JM
1598}
1599
4082afcc
PA
1600/* Returns true if the multi-process extensions are in effect. */
1601
1602static int
1603remote_multi_process_p (struct remote_state *rs)
1604{
1605 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1606}
1607
de0d863e
DB
1608/* Returns true if fork events are supported. */
1609
1610static int
1611remote_fork_event_p (struct remote_state *rs)
1612{
1613 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1614}
1615
c269dbdb
DB
1616/* Returns true if vfork events are supported. */
1617
1618static int
1619remote_vfork_event_p (struct remote_state *rs)
1620{
1621 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1622}
1623
d46addbb
DB
1624/* Returns true if exec events are supported. */
1625
1626static int
1627remote_exec_event_p (struct remote_state *rs)
1628{
1629 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1630}
1631
cbb8991c
DB
1632/* Insert fork catchpoint target routine. If fork events are enabled
1633 then return success, nothing more to do. */
1634
1635static int
1636remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1637{
1638 struct remote_state *rs = get_remote_state ();
1639
1640 return !remote_fork_event_p (rs);
1641}
1642
1643/* Remove fork catchpoint target routine. Nothing to do, just
1644 return success. */
1645
1646static int
1647remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1648{
1649 return 0;
1650}
1651
1652/* Insert vfork catchpoint target routine. If vfork events are enabled
1653 then return success, nothing more to do. */
1654
1655static int
1656remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1657{
1658 struct remote_state *rs = get_remote_state ();
1659
1660 return !remote_vfork_event_p (rs);
1661}
1662
1663/* Remove vfork catchpoint target routine. Nothing to do, just
1664 return success. */
1665
1666static int
1667remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1668{
1669 return 0;
1670}
1671
d46addbb
DB
1672/* Insert exec catchpoint target routine. If exec events are
1673 enabled, just return success. */
1674
1675static int
1676remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1677{
1678 struct remote_state *rs = get_remote_state ();
1679
1680 return !remote_exec_event_p (rs);
1681}
1682
1683/* Remove exec catchpoint target routine. Nothing to do, just
1684 return success. */
1685
1686static int
1687remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1688{
1689 return 0;
1690}
1691
23860348 1692/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1693static struct async_signal_handler *async_sigint_remote_twice_token;
1694static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1695
74531fed
PA
1696\f
1697/* Asynchronous signal handle registered as event loop source for
1698 when we have pending events ready to be passed to the core. */
1699
1700static struct async_event_handler *remote_async_inferior_event_token;
1701
c906108c
SS
1702\f
1703
79d7f229
PA
1704static ptid_t magic_null_ptid;
1705static ptid_t not_sent_ptid;
1706static ptid_t any_thread_ptid;
1707
0b16c5cf
PA
1708/* Find out if the stub attached to PID (and hence GDB should offer to
1709 detach instead of killing it when bailing out). */
1710
1711static int
1712remote_query_attached (int pid)
1713{
1714 struct remote_state *rs = get_remote_state ();
bba74b36 1715 size_t size = get_remote_packet_size ();
0b16c5cf 1716
4082afcc 1717 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1718 return 0;
1719
1720 if (remote_multi_process_p (rs))
bba74b36 1721 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1722 else
bba74b36 1723 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1724
1725 putpkt (rs->buf);
1726 getpkt (&rs->buf, &rs->buf_size, 0);
1727
1728 switch (packet_ok (rs->buf,
1554e9be 1729 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1730 {
1731 case PACKET_OK:
1732 if (strcmp (rs->buf, "1") == 0)
1733 return 1;
1734 break;
1735 case PACKET_ERROR:
1736 warning (_("Remote failure reply: %s"), rs->buf);
1737 break;
1738 case PACKET_UNKNOWN:
1739 break;
1740 }
1741
1742 return 0;
1743}
1744
49c62f2e
PA
1745/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1746 has been invented by GDB, instead of reported by the target. Since
1747 we can be connected to a remote system before before knowing about
1748 any inferior, mark the target with execution when we find the first
1749 inferior. If ATTACHED is 1, then we had just attached to this
1750 inferior. If it is 0, then we just created this inferior. If it
1751 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1752 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1753 attempt to open this inferior's executable as the main executable
1754 if no main executable is open already. */
1941c569
PA
1755
1756static struct inferior *
1b6e6f5c
GB
1757remote_add_inferior (int fake_pid_p, int pid, int attached,
1758 int try_open_exec)
1941c569 1759{
1941c569
PA
1760 struct inferior *inf;
1761
0b16c5cf
PA
1762 /* Check whether this process we're learning about is to be
1763 considered attached, or if is to be considered to have been
1764 spawned by the stub. */
1765 if (attached == -1)
1766 attached = remote_query_attached (pid);
1767
f5656ead 1768 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1769 {
1770 /* If the target shares code across all inferiors, then every
1771 attach adds a new inferior. */
1772 inf = add_inferior (pid);
1773
1774 /* ... and every inferior is bound to the same program space.
1775 However, each inferior may still have its own address
1776 space. */
1777 inf->aspace = maybe_new_address_space ();
1778 inf->pspace = current_program_space;
1779 }
1780 else
1781 {
1782 /* In the traditional debugging scenario, there's a 1-1 match
1783 between program/address spaces. We simply bind the inferior
1784 to the program space's address space. */
1785 inf = current_inferior ();
1786 inferior_appeared (inf, pid);
1787 }
1941c569 1788
0b16c5cf 1789 inf->attach_flag = attached;
49c62f2e 1790 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1791
1b6e6f5c
GB
1792 /* If no main executable is currently open then attempt to
1793 open the file that was executed to create this inferior. */
835205d0 1794 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1795 exec_file_locate_attach (pid, 1);
1796
1941c569
PA
1797 return inf;
1798}
1799
1800/* Add thread PTID to GDB's thread list. Tag it as executing/running
1801 according to RUNNING. */
1802
c906108c 1803static void
1941c569 1804remote_add_thread (ptid_t ptid, int running)
c906108c 1805{
b7ea362b
PA
1806 struct remote_state *rs = get_remote_state ();
1807
1808 /* GDB historically didn't pull threads in the initial connection
1809 setup. If the remote target doesn't even have a concept of
1810 threads (e.g., a bare-metal target), even if internally we
1811 consider that a single-threaded target, mentioning a new thread
1812 might be confusing to the user. Be silent then, preserving the
1813 age old behavior. */
1814 if (rs->starting_up)
1815 add_thread_silent (ptid);
1816 else
1817 add_thread (ptid);
1941c569
PA
1818
1819 set_executing (ptid, running);
1820 set_running (ptid, running);
1821}
1822
1823/* Come here when we learn about a thread id from the remote target.
1824 It may be the first time we hear about such thread, so take the
1825 opportunity to add it to GDB's thread list. In case this is the
1826 first time we're noticing its corresponding inferior, add it to
1827 GDB's inferior list as well. */
1828
1829static void
1830remote_notice_new_inferior (ptid_t currthread, int running)
1831{
c906108c
SS
1832 /* If this is a new thread, add it to GDB's thread list.
1833 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1834
1835 if (in_thread_list (currthread) && is_exited (currthread))
1836 {
1837 /* We're seeing an event on a thread id we knew had exited.
1838 This has to be a new thread reusing the old id. Add it. */
1941c569 1839 remote_add_thread (currthread, running);
82f73884
PA
1840 return;
1841 }
1842
79d7f229 1843 if (!in_thread_list (currthread))
c0a2216e 1844 {
1941c569 1845 struct inferior *inf = NULL;
bad34192 1846 int pid = ptid_get_pid (currthread);
1941c569 1847
bad34192
PA
1848 if (ptid_is_pid (inferior_ptid)
1849 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1850 {
1851 /* inferior_ptid has no thread member yet. This can happen
1852 with the vAttach -> remote_wait,"TAAthread:" path if the
1853 stub doesn't support qC. This is the first stop reported
1854 after an attach, so this is the main thread. Update the
1855 ptid in the thread list. */
bad34192
PA
1856 if (in_thread_list (pid_to_ptid (pid)))
1857 thread_change_ptid (inferior_ptid, currthread);
1858 else
1859 {
1860 remote_add_thread (currthread, running);
1861 inferior_ptid = currthread;
1862 }
dc146f7c 1863 return;
c0a2216e 1864 }
82f73884
PA
1865
1866 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1867 {
1868 /* inferior_ptid is not set yet. This can happen with the
1869 vRun -> remote_wait,"TAAthread:" path if the stub
1870 doesn't support qC. This is the first stop reported
1871 after an attach, so this is the main thread. Update the
1872 ptid in the thread list. */
dc146f7c 1873 thread_change_ptid (inferior_ptid, currthread);
82f73884 1874 return;
c0a2216e 1875 }
82f73884 1876
29c87f7f
PA
1877 /* When connecting to a target remote, or to a target
1878 extended-remote which already was debugging an inferior, we
1879 may not know about it yet. Add it before adding its child
1880 thread, so notifications are emitted in a sensible order. */
1881 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1882 {
1883 struct remote_state *rs = get_remote_state ();
1884 int fake_pid_p = !remote_multi_process_p (rs);
1885
1886 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1887 ptid_get_pid (currthread), -1, 1);
49c62f2e 1888 }
29c87f7f 1889
82f73884 1890 /* This is really a new thread. Add it. */
1941c569
PA
1891 remote_add_thread (currthread, running);
1892
1893 /* If we found a new inferior, let the common code do whatever
1894 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1895 breakpoints), unless we're just setting up an all-stop
1896 connection. */
1941c569 1897 if (inf != NULL)
b7ea362b
PA
1898 {
1899 struct remote_state *rs = get_remote_state ();
1900
6efcd9a8 1901 if (!rs->starting_up)
b7ea362b
PA
1902 notice_new_inferior (currthread, running, 0);
1903 }
c0a2216e 1904 }
c906108c
SS
1905}
1906
dc146f7c
VP
1907/* Return the private thread data, creating it if necessary. */
1908
70221824 1909static struct private_thread_info *
dc146f7c
VP
1910demand_private_info (ptid_t ptid)
1911{
1912 struct thread_info *info = find_thread_ptid (ptid);
1913
1914 gdb_assert (info);
1915
fe978cb0 1916 if (!info->priv)
dc146f7c 1917 {
8d749320 1918 info->priv = XNEW (struct private_thread_info);
dc146f7c 1919 info->private_dtor = free_private_thread_info;
fe978cb0 1920 info->priv->core = -1;
8020350c
DB
1921 info->priv->extra = NULL;
1922 info->priv->name = NULL;
dc146f7c
VP
1923 }
1924
fe978cb0 1925 return info->priv;
dc146f7c
VP
1926}
1927
74531fed
PA
1928/* Call this function as a result of
1929 1) A halt indication (T packet) containing a thread id
1930 2) A direct query of currthread
0df8b418 1931 3) Successful execution of set thread */
74531fed
PA
1932
1933static void
47f8a51d 1934record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1935{
47f8a51d 1936 rs->general_thread = currthread;
74531fed
PA
1937}
1938
89be2091
DJ
1939/* If 'QPassSignals' is supported, tell the remote stub what signals
1940 it can simply pass through to the inferior without reporting. */
1941
1942static void
94bedb42
TT
1943remote_pass_signals (struct target_ops *self,
1944 int numsigs, unsigned char *pass_signals)
89be2091 1945{
4082afcc 1946 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1947 {
1948 char *pass_packet, *p;
89be2091 1949 int count = 0, i;
747dc59d 1950 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1951
1952 gdb_assert (numsigs < 256);
1953 for (i = 0; i < numsigs; i++)
1954 {
2455069d 1955 if (pass_signals[i])
89be2091
DJ
1956 count++;
1957 }
224c3ddb 1958 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
1959 strcpy (pass_packet, "QPassSignals:");
1960 p = pass_packet + strlen (pass_packet);
1961 for (i = 0; i < numsigs; i++)
1962 {
2455069d 1963 if (pass_signals[i])
89be2091
DJ
1964 {
1965 if (i >= 16)
1966 *p++ = tohex (i >> 4);
1967 *p++ = tohex (i & 15);
1968 if (count)
1969 *p++ = ';';
1970 else
1971 break;
1972 count--;
1973 }
1974 }
1975 *p = 0;
747dc59d 1976 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1977 {
89be2091
DJ
1978 putpkt (pass_packet);
1979 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1980 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1981 if (rs->last_pass_packet)
1982 xfree (rs->last_pass_packet);
1983 rs->last_pass_packet = pass_packet;
89be2091
DJ
1984 }
1985 else
1986 xfree (pass_packet);
1987 }
1988}
1989
82075af2
JS
1990/* If 'QCatchSyscalls' is supported, tell the remote stub
1991 to report syscalls to GDB. */
1992
1993static int
1994remote_set_syscall_catchpoint (struct target_ops *self,
1995 int pid, int needed, int any_count,
1996 int table_size, int *table)
1997{
1998 char *catch_packet;
1999 enum packet_result result;
2000 int n_sysno = 0;
2001
2002 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2003 {
2004 /* Not supported. */
2005 return 1;
2006 }
2007
2008 if (needed && !any_count)
2009 {
2010 int i;
2011
2012 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2013 for (i = 0; i < table_size; i++)
2014 {
2015 if (table[i] != 0)
2016 n_sysno++;
2017 }
2018 }
2019
2020 if (remote_debug)
2021 {
2022 fprintf_unfiltered (gdb_stdlog,
2023 "remote_set_syscall_catchpoint "
2024 "pid %d needed %d any_count %d n_sysno %d\n",
2025 pid, needed, any_count, n_sysno);
2026 }
2027
2028 if (needed)
2029 {
2030 /* Prepare a packet with the sysno list, assuming max 8+1
2031 characters for a sysno. If the resulting packet size is too
2032 big, fallback on the non-selective packet. */
2033 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2034
c0518081 2035 catch_packet = (char *) xmalloc (maxpktsz);
82075af2
JS
2036 strcpy (catch_packet, "QCatchSyscalls:1");
2037 if (!any_count)
2038 {
2039 int i;
2040 char *p;
2041
2042 p = catch_packet;
2043 p += strlen (p);
2044
2045 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2046 for (i = 0; i < table_size; i++)
2047 {
2048 if (table[i] != 0)
2049 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2050 }
2051 }
2052 if (strlen (catch_packet) > get_remote_packet_size ())
2053 {
2054 /* catch_packet too big. Fallback to less efficient
2055 non selective mode, with GDB doing the filtering. */
2056 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2057 }
2058 }
2059 else
2060 catch_packet = xstrdup ("QCatchSyscalls:0");
2061
2062 {
2063 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2064 struct remote_state *rs = get_remote_state ();
2065
2066 putpkt (catch_packet);
2067 getpkt (&rs->buf, &rs->buf_size, 0);
2068 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2069 do_cleanups (old_chain);
2070 if (result == PACKET_OK)
2071 return 0;
2072 else
2073 return -1;
2074 }
2075}
2076
9b224c5e
PA
2077/* If 'QProgramSignals' is supported, tell the remote stub what
2078 signals it should pass through to the inferior when detaching. */
2079
2080static void
daf5e9b6
TT
2081remote_program_signals (struct target_ops *self,
2082 int numsigs, unsigned char *signals)
9b224c5e 2083{
4082afcc 2084 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2085 {
2086 char *packet, *p;
2087 int count = 0, i;
5e4a05c4 2088 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2089
2090 gdb_assert (numsigs < 256);
2091 for (i = 0; i < numsigs; i++)
2092 {
2093 if (signals[i])
2094 count++;
2095 }
224c3ddb 2096 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2097 strcpy (packet, "QProgramSignals:");
2098 p = packet + strlen (packet);
2099 for (i = 0; i < numsigs; i++)
2100 {
2101 if (signal_pass_state (i))
2102 {
2103 if (i >= 16)
2104 *p++ = tohex (i >> 4);
2105 *p++ = tohex (i & 15);
2106 if (count)
2107 *p++ = ';';
2108 else
2109 break;
2110 count--;
2111 }
2112 }
2113 *p = 0;
5e4a05c4
TT
2114 if (!rs->last_program_signals_packet
2115 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2116 {
9b224c5e
PA
2117 putpkt (packet);
2118 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2119 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2120 xfree (rs->last_program_signals_packet);
2121 rs->last_program_signals_packet = packet;
9b224c5e
PA
2122 }
2123 else
2124 xfree (packet);
2125 }
2126}
2127
79d7f229
PA
2128/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2129 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2130 thread. If GEN is set, set the general thread, if not, then set
2131 the step/continue thread. */
c906108c 2132static void
79d7f229 2133set_thread (struct ptid ptid, int gen)
c906108c 2134{
d01949b6 2135 struct remote_state *rs = get_remote_state ();
47f8a51d 2136 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2137 char *buf = rs->buf;
79d7f229 2138 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2139
79d7f229 2140 if (ptid_equal (state, ptid))
c906108c
SS
2141 return;
2142
79d7f229
PA
2143 *buf++ = 'H';
2144 *buf++ = gen ? 'g' : 'c';
2145 if (ptid_equal (ptid, magic_null_ptid))
2146 xsnprintf (buf, endbuf - buf, "0");
2147 else if (ptid_equal (ptid, any_thread_ptid))
2148 xsnprintf (buf, endbuf - buf, "0");
2149 else if (ptid_equal (ptid, minus_one_ptid))
2150 xsnprintf (buf, endbuf - buf, "-1");
2151 else
82f73884 2152 write_ptid (buf, endbuf, ptid);
79d7f229 2153 putpkt (rs->buf);
6d820c5c 2154 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2155 if (gen)
47f8a51d 2156 rs->general_thread = ptid;
c906108c 2157 else
47f8a51d 2158 rs->continue_thread = ptid;
c906108c 2159}
79d7f229
PA
2160
2161static void
2162set_general_thread (struct ptid ptid)
2163{
2164 set_thread (ptid, 1);
2165}
2166
2167static void
2168set_continue_thread (struct ptid ptid)
2169{
2170 set_thread (ptid, 0);
2171}
2172
3c9c4b83
PA
2173/* Change the remote current process. Which thread within the process
2174 ends up selected isn't important, as long as it is the same process
2175 as what INFERIOR_PTID points to.
2176
2177 This comes from that fact that there is no explicit notion of
2178 "selected process" in the protocol. The selected process for
2179 general operations is the process the selected general thread
2180 belongs to. */
2181
2182static void
2183set_general_process (void)
2184{
2185 struct remote_state *rs = get_remote_state ();
2186
2187 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2188 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2189 return;
2190
2191 /* We only need to change the remote current thread if it's pointing
2192 at some other process. */
47f8a51d 2193 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2194 set_general_thread (inferior_ptid);
2195}
2196
c906108c 2197\f
7d1a114c
PA
2198/* Return nonzero if this is the main thread that we made up ourselves
2199 to model non-threaded targets as single-threaded. */
c906108c
SS
2200
2201static int
7d1a114c 2202remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2203{
c0a2216e
PA
2204 if (ptid_equal (ptid, magic_null_ptid))
2205 /* The main thread is always alive. */
2206 return 1;
2207
ba348170 2208 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2209 /* The main thread is always alive. This can happen after a
2210 vAttach, if the remote side doesn't support
2211 multi-threading. */
2212 return 1;
2213
7d1a114c
PA
2214 return 0;
2215}
2216
2217/* Return nonzero if the thread PTID is still alive on the remote
2218 system. */
2219
2220static int
2221remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2222{
2223 struct remote_state *rs = get_remote_state ();
2224 char *p, *endp;
2225
2226 /* Check if this is a thread that we made up ourselves to model
2227 non-threaded targets as single-threaded. */
2228 if (remote_thread_always_alive (ops, ptid))
2229 return 1;
2230
82f73884
PA
2231 p = rs->buf;
2232 endp = rs->buf + get_remote_packet_size ();
2233
2234 *p++ = 'T';
2235 write_ptid (p, endp, ptid);
2236
2e9f7625 2237 putpkt (rs->buf);
6d820c5c 2238 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2239 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2240}
2241
79efa585
SM
2242/* Return a pointer to a thread name if we know it and NULL otherwise.
2243 The thread_info object owns the memory for the name. */
2244
2245static const char *
2246remote_thread_name (struct target_ops *ops, struct thread_info *info)
2247{
2248 if (info->priv != NULL)
2249 return info->priv->name;
2250
2251 return NULL;
2252}
2253
c906108c
SS
2254/* About these extended threadlist and threadinfo packets. They are
2255 variable length packets but, the fields within them are often fixed
2256 length. They are redundent enough to send over UDP as is the
2257 remote protocol in general. There is a matching unit test module
2258 in libstub. */
2259
23860348 2260/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2261 libstub protocol encoding, and remote.c. It is not particularly
23860348 2262 changable. */
cce74817
JM
2263
2264/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2265 Plan to fix this. */
cce74817 2266
23860348 2267typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2268
9d1f7ab2 2269/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2270 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2271
2272struct gdb_ext_thread_info
c5aa993b 2273 {
23860348 2274 threadref threadid; /* External form of thread reference. */
2bc416ba 2275 int active; /* Has state interesting to GDB?
23860348 2276 regs, stack. */
2bc416ba 2277 char display[256]; /* Brief state display, name,
cedea757 2278 blocked/suspended. */
23860348 2279 char shortname[32]; /* To be used to name threads. */
2bc416ba 2280 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2281 whatever. */
c5aa993b 2282 };
cce74817
JM
2283
2284/* The volume of remote transfers can be limited by submitting
2285 a mask containing bits specifying the desired information.
2286 Use a union of these values as the 'selection' parameter to
0df8b418 2287 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2288
2289#define TAG_THREADID 1
2290#define TAG_EXISTS 2
2291#define TAG_DISPLAY 4
2292#define TAG_THREADNAME 8
c5aa993b 2293#define TAG_MOREDISPLAY 16
cce74817 2294
23860348 2295#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2296
a14ed312 2297static char *unpack_nibble (char *buf, int *val);
cce74817 2298
a14ed312 2299static char *unpack_byte (char *buf, int *value);
cce74817 2300
a14ed312 2301static char *pack_int (char *buf, int value);
cce74817 2302
a14ed312 2303static char *unpack_int (char *buf, int *value);
cce74817 2304
a14ed312 2305static char *unpack_string (char *src, char *dest, int length);
cce74817 2306
23860348 2307static char *pack_threadid (char *pkt, threadref *id);
cce74817 2308
23860348 2309static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2310
23860348 2311void int_to_threadref (threadref *id, int value);
cce74817 2312
23860348 2313static int threadref_to_int (threadref *ref);
cce74817 2314
23860348 2315static void copy_threadref (threadref *dest, threadref *src);
cce74817 2316
23860348 2317static int threadmatch (threadref *dest, threadref *src);
cce74817 2318
2bc416ba 2319static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2320 threadref *id);
cce74817 2321
a14ed312 2322static int remote_unpack_thread_info_response (char *pkt,
23860348 2323 threadref *expectedref,
a14ed312
KB
2324 struct gdb_ext_thread_info
2325 *info);
cce74817
JM
2326
2327
2bc416ba 2328static int remote_get_threadinfo (threadref *threadid,
23860348 2329 int fieldset, /*TAG mask */
a14ed312 2330 struct gdb_ext_thread_info *info);
cce74817 2331
a14ed312
KB
2332static char *pack_threadlist_request (char *pkt, int startflag,
2333 int threadcount,
23860348 2334 threadref *nextthread);
cce74817 2335
a14ed312
KB
2336static int parse_threadlist_response (char *pkt,
2337 int result_limit,
23860348 2338 threadref *original_echo,
2bc416ba 2339 threadref *resultlist,
23860348 2340 int *doneflag);
cce74817 2341
a14ed312 2342static int remote_get_threadlist (int startflag,
23860348 2343 threadref *nextthread,
a14ed312
KB
2344 int result_limit,
2345 int *done,
2bc416ba 2346 int *result_count,
23860348 2347 threadref *threadlist);
cce74817 2348
23860348 2349typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2350
a14ed312
KB
2351static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2352 void *context, int looplimit);
cce74817 2353
23860348 2354static int remote_newthread_step (threadref *ref, void *context);
cce74817 2355
82f73884
PA
2356
2357/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2358 buffer we're allowed to write to. Returns
2359 BUF+CHARACTERS_WRITTEN. */
2360
2361static char *
2362write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2363{
2364 int pid, tid;
2365 struct remote_state *rs = get_remote_state ();
2366
2367 if (remote_multi_process_p (rs))
2368 {
2369 pid = ptid_get_pid (ptid);
2370 if (pid < 0)
2371 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2372 else
2373 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2374 }
ba348170 2375 tid = ptid_get_lwp (ptid);
82f73884
PA
2376 if (tid < 0)
2377 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2378 else
2379 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2380
2381 return buf;
2382}
2383
2384/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2385 passed the last parsed char. Returns null_ptid on error. */
2386
2387static ptid_t
2388read_ptid (char *buf, char **obuf)
2389{
2390 char *p = buf;
2391 char *pp;
2392 ULONGEST pid = 0, tid = 0;
82f73884
PA
2393
2394 if (*p == 'p')
2395 {
2396 /* Multi-process ptid. */
2397 pp = unpack_varlen_hex (p + 1, &pid);
2398 if (*pp != '.')
b37520b6 2399 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2400
2401 p = pp;
2402 pp = unpack_varlen_hex (p + 1, &tid);
2403 if (obuf)
2404 *obuf = pp;
ba348170 2405 return ptid_build (pid, tid, 0);
82f73884
PA
2406 }
2407
2408 /* No multi-process. Just a tid. */
2409 pp = unpack_varlen_hex (p, &tid);
2410
c9f35b34
KB
2411 /* Return null_ptid when no thread id is found. */
2412 if (p == pp)
2413 {
2414 if (obuf)
2415 *obuf = pp;
2416 return null_ptid;
2417 }
2418
82f73884 2419 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2420 what's in inferior_ptid, unless it's null at this point. If so,
2421 then since there's no way to know the pid of the reported
2422 threads, use the magic number. */
2423 if (ptid_equal (inferior_ptid, null_ptid))
2424 pid = ptid_get_pid (magic_null_ptid);
2425 else
2426 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2427
2428 if (obuf)
2429 *obuf = pp;
ba348170 2430 return ptid_build (pid, tid, 0);
82f73884
PA
2431}
2432
c906108c 2433static int
fba45db2 2434stubhex (int ch)
c906108c
SS
2435{
2436 if (ch >= 'a' && ch <= 'f')
2437 return ch - 'a' + 10;
2438 if (ch >= '0' && ch <= '9')
2439 return ch - '0';
2440 if (ch >= 'A' && ch <= 'F')
2441 return ch - 'A' + 10;
2442 return -1;
2443}
2444
2445static int
fba45db2 2446stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2447{
2448 int nibble;
2449 int retval = 0;
2450
2451 while (fieldlength)
2452 {
2453 nibble = stubhex (*buff++);
2454 retval |= nibble;
2455 fieldlength--;
2456 if (fieldlength)
2457 retval = retval << 4;
2458 }
2459 return retval;
2460}
2461
c906108c 2462static char *
fba45db2 2463unpack_nibble (char *buf, int *val)
c906108c 2464{
b7589f7d 2465 *val = fromhex (*buf++);
c906108c
SS
2466 return buf;
2467}
2468
c906108c 2469static char *
fba45db2 2470unpack_byte (char *buf, int *value)
c906108c
SS
2471{
2472 *value = stub_unpack_int (buf, 2);
2473 return buf + 2;
2474}
2475
2476static char *
fba45db2 2477pack_int (char *buf, int value)
c906108c
SS
2478{
2479 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2480 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2481 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2482 buf = pack_hex_byte (buf, (value & 0xff));
2483 return buf;
2484}
2485
2486static char *
fba45db2 2487unpack_int (char *buf, int *value)
c906108c
SS
2488{
2489 *value = stub_unpack_int (buf, 8);
2490 return buf + 8;
2491}
2492
23860348 2493#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2494static char *pack_string (char *pkt, char *string);
c906108c
SS
2495
2496static char *
fba45db2 2497pack_string (char *pkt, char *string)
c906108c
SS
2498{
2499 char ch;
2500 int len;
2501
2502 len = strlen (string);
2503 if (len > 200)
23860348 2504 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2505 pkt = pack_hex_byte (pkt, len);
2506 while (len-- > 0)
2507 {
2508 ch = *string++;
2509 if ((ch == '\0') || (ch == '#'))
23860348 2510 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2511 *pkt++ = ch;
2512 }
2513 return pkt;
2514}
2515#endif /* 0 (unused) */
2516
2517static char *
fba45db2 2518unpack_string (char *src, char *dest, int length)
c906108c
SS
2519{
2520 while (length--)
2521 *dest++ = *src++;
2522 *dest = '\0';
2523 return src;
2524}
2525
2526static char *
fba45db2 2527pack_threadid (char *pkt, threadref *id)
c906108c
SS
2528{
2529 char *limit;
2530 unsigned char *altid;
2531
2532 altid = (unsigned char *) id;
2533 limit = pkt + BUF_THREAD_ID_SIZE;
2534 while (pkt < limit)
2535 pkt = pack_hex_byte (pkt, *altid++);
2536 return pkt;
2537}
2538
2539
2540static char *
fba45db2 2541unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2542{
2543 char *altref;
2544 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2545 int x, y;
2546
2547 altref = (char *) id;
2548
2549 while (inbuf < limit)
2550 {
2551 x = stubhex (*inbuf++);
2552 y = stubhex (*inbuf++);
2553 *altref++ = (x << 4) | y;
2554 }
2555 return inbuf;
2556}
2557
2558/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2559 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2560 to use 64bit thread references internally. This is an adapter
2561 function. */
2562
2563void
fba45db2 2564int_to_threadref (threadref *id, int value)
c906108c
SS
2565{
2566 unsigned char *scan;
2567
2568 scan = (unsigned char *) id;
2569 {
2570 int i = 4;
2571 while (i--)
2572 *scan++ = 0;
2573 }
2574 *scan++ = (value >> 24) & 0xff;
2575 *scan++ = (value >> 16) & 0xff;
2576 *scan++ = (value >> 8) & 0xff;
2577 *scan++ = (value & 0xff);
2578}
2579
2580static int
fba45db2 2581threadref_to_int (threadref *ref)
c906108c
SS
2582{
2583 int i, value = 0;
2584 unsigned char *scan;
2585
cfd77fa1 2586 scan = *ref;
c906108c
SS
2587 scan += 4;
2588 i = 4;
2589 while (i-- > 0)
2590 value = (value << 8) | ((*scan++) & 0xff);
2591 return value;
2592}
2593
2594static void
fba45db2 2595copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2596{
2597 int i;
2598 unsigned char *csrc, *cdest;
2599
2600 csrc = (unsigned char *) src;
2601 cdest = (unsigned char *) dest;
2602 i = 8;
2603 while (i--)
2604 *cdest++ = *csrc++;
2605}
2606
2607static int
fba45db2 2608threadmatch (threadref *dest, threadref *src)
c906108c 2609{
23860348 2610 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2611#if 0
2612 unsigned char *srcp, *destp;
2613 int i, result;
2614 srcp = (char *) src;
2615 destp = (char *) dest;
2616
2617 result = 1;
2618 while (i-- > 0)
2619 result &= (*srcp++ == *destp++) ? 1 : 0;
2620 return result;
2621#endif
2622 return 1;
2623}
2624
2625/*
c5aa993b
JM
2626 threadid:1, # always request threadid
2627 context_exists:2,
2628 display:4,
2629 unique_name:8,
2630 more_display:16
2631 */
c906108c
SS
2632
2633/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2634
2635static char *
fba45db2 2636pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2637{
23860348
MS
2638 *pkt++ = 'q'; /* Info Query */
2639 *pkt++ = 'P'; /* process or thread info */
2640 pkt = pack_int (pkt, mode); /* mode */
c906108c 2641 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2642 *pkt = '\0'; /* terminate */
c906108c
SS
2643 return pkt;
2644}
2645
23860348 2646/* These values tag the fields in a thread info response packet. */
c906108c 2647/* Tagging the fields allows us to request specific fields and to
23860348 2648 add more fields as time goes by. */
c906108c 2649
23860348 2650#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2651#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2652 fetch registers and its stack? */
c5aa993b 2653#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2654#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2655#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2656 the process. */
c906108c
SS
2657
2658static int
fba45db2
KB
2659remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2660 struct gdb_ext_thread_info *info)
c906108c 2661{
d01949b6 2662 struct remote_state *rs = get_remote_state ();
c906108c 2663 int mask, length;
cfd77fa1 2664 int tag;
c906108c 2665 threadref ref;
6d820c5c 2666 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2667 int retval = 1;
2668
23860348 2669 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2670 info->active = 0;
2671 info->display[0] = '\0';
2672 info->shortname[0] = '\0';
2673 info->more_display[0] = '\0';
2674
23860348
MS
2675 /* Assume the characters indicating the packet type have been
2676 stripped. */
c906108c
SS
2677 pkt = unpack_int (pkt, &mask); /* arg mask */
2678 pkt = unpack_threadid (pkt, &ref);
2679
2680 if (mask == 0)
8a3fe4f8 2681 warning (_("Incomplete response to threadinfo request."));
c906108c 2682 if (!threadmatch (&ref, expectedref))
23860348 2683 { /* This is an answer to a different request. */
8a3fe4f8 2684 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2685 return 0;
2686 }
2687 copy_threadref (&info->threadid, &ref);
2688
23860348 2689 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2690
23860348
MS
2691 /* Packets are terminated with nulls. */
2692 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2693 {
2694 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2695 pkt = unpack_byte (pkt, &length); /* length */
2696 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2697 {
8a3fe4f8 2698 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2699 retval = 0;
2700 break;
2701 }
2702 if (tag == TAG_THREADID)
2703 {
2704 if (length != 16)
2705 {
8a3fe4f8 2706 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2707 retval = 0;
2708 break;
2709 }
2710 pkt = unpack_threadid (pkt, &ref);
2711 mask = mask & ~TAG_THREADID;
2712 continue;
2713 }
2714 if (tag == TAG_EXISTS)
2715 {
2716 info->active = stub_unpack_int (pkt, length);
2717 pkt += length;
2718 mask = mask & ~(TAG_EXISTS);
2719 if (length > 8)
2720 {
8a3fe4f8 2721 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2722 retval = 0;
2723 break;
2724 }
2725 continue;
2726 }
2727 if (tag == TAG_THREADNAME)
2728 {
2729 pkt = unpack_string (pkt, &info->shortname[0], length);
2730 mask = mask & ~TAG_THREADNAME;
2731 continue;
2732 }
2733 if (tag == TAG_DISPLAY)
2734 {
2735 pkt = unpack_string (pkt, &info->display[0], length);
2736 mask = mask & ~TAG_DISPLAY;
2737 continue;
2738 }
2739 if (tag == TAG_MOREDISPLAY)
2740 {
2741 pkt = unpack_string (pkt, &info->more_display[0], length);
2742 mask = mask & ~TAG_MOREDISPLAY;
2743 continue;
2744 }
8a3fe4f8 2745 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2746 break; /* Not a tag we know about. */
c906108c
SS
2747 }
2748 return retval;
2749}
2750
2751static int
fba45db2
KB
2752remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2753 struct gdb_ext_thread_info *info)
c906108c 2754{
d01949b6 2755 struct remote_state *rs = get_remote_state ();
c906108c 2756 int result;
c906108c 2757
2e9f7625
DJ
2758 pack_threadinfo_request (rs->buf, fieldset, threadid);
2759 putpkt (rs->buf);
6d820c5c 2760 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2761
2762 if (rs->buf[0] == '\0')
2763 return 0;
2764
2e9f7625 2765 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2766 threadid, info);
c906108c
SS
2767 return result;
2768}
2769
c906108c
SS
2770/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2771
2772static char *
fba45db2
KB
2773pack_threadlist_request (char *pkt, int startflag, int threadcount,
2774 threadref *nextthread)
c906108c
SS
2775{
2776 *pkt++ = 'q'; /* info query packet */
2777 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2778 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2779 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2780 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2781 *pkt = '\0';
2782 return pkt;
2783}
2784
2785/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2786
2787static int
fba45db2
KB
2788parse_threadlist_response (char *pkt, int result_limit,
2789 threadref *original_echo, threadref *resultlist,
2790 int *doneflag)
c906108c 2791{
d01949b6 2792 struct remote_state *rs = get_remote_state ();
c906108c
SS
2793 char *limit;
2794 int count, resultcount, done;
2795
2796 resultcount = 0;
2797 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2798 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2799 /* done parse past here */
c906108c
SS
2800 pkt = unpack_byte (pkt, &count); /* count field */
2801 pkt = unpack_nibble (pkt, &done);
2802 /* The first threadid is the argument threadid. */
2803 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2804 while ((count-- > 0) && (pkt < limit))
2805 {
2806 pkt = unpack_threadid (pkt, resultlist++);
2807 if (resultcount++ >= result_limit)
2808 break;
2809 }
2810 if (doneflag)
2811 *doneflag = done;
2812 return resultcount;
2813}
2814
6dc54d91
PA
2815/* Fetch the next batch of threads from the remote. Returns -1 if the
2816 qL packet is not supported, 0 on error and 1 on success. */
2817
c906108c 2818static int
fba45db2
KB
2819remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2820 int *done, int *result_count, threadref *threadlist)
c906108c 2821{
d01949b6 2822 struct remote_state *rs = get_remote_state ();
c906108c
SS
2823 int result = 1;
2824
23860348 2825 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2826 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2827 >= get_remote_packet_size ())
ea9c271d 2828 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2829
6d820c5c
DJ
2830 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2831 putpkt (rs->buf);
2832 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2833 if (*rs->buf == '\0')
6dc54d91
PA
2834 {
2835 /* Packet not supported. */
2836 return -1;
2837 }
2838
2839 *result_count =
2840 parse_threadlist_response (rs->buf + 2, result_limit,
2841 &rs->echo_nextthread, threadlist, done);
c906108c 2842
0d031856 2843 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2844 {
23860348
MS
2845 /* FIXME: This is a good reason to drop the packet. */
2846 /* Possably, there is a duplicate response. */
c906108c
SS
2847 /* Possabilities :
2848 retransmit immediatly - race conditions
2849 retransmit after timeout - yes
2850 exit
2851 wait for packet, then exit
2852 */
8a3fe4f8 2853 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2854 return 0; /* I choose simply exiting. */
c906108c
SS
2855 }
2856 if (*result_count <= 0)
2857 {
2858 if (*done != 1)
2859 {
8a3fe4f8 2860 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2861 result = 0;
2862 }
2863 return result; /* break; */
2864 }
2865 if (*result_count > result_limit)
2866 {
2867 *result_count = 0;
8a3fe4f8 2868 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2869 return 0;
2870 }
2871 return result;
2872}
2873
6dc54d91
PA
2874/* Fetch the list of remote threads, with the qL packet, and call
2875 STEPFUNCTION for each thread found. Stops iterating and returns 1
2876 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2877 STEPFUNCTION returns false. If the packet is not supported,
2878 returns -1. */
c906108c 2879
c906108c 2880static int
fba45db2
KB
2881remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2882 int looplimit)
c906108c 2883{
0d031856 2884 struct remote_state *rs = get_remote_state ();
c906108c
SS
2885 int done, i, result_count;
2886 int startflag = 1;
2887 int result = 1;
2888 int loopcount = 0;
c906108c
SS
2889
2890 done = 0;
2891 while (!done)
2892 {
2893 if (loopcount++ > looplimit)
2894 {
2895 result = 0;
8a3fe4f8 2896 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2897 break;
2898 }
6dc54d91
PA
2899 result = remote_get_threadlist (startflag, &rs->nextthread,
2900 MAXTHREADLISTRESULTS,
2901 &done, &result_count,
2902 rs->resultthreadlist);
2903 if (result <= 0)
2904 break;
23860348 2905 /* Clear for later iterations. */
c906108c
SS
2906 startflag = 0;
2907 /* Setup to resume next batch of thread references, set nextthread. */
2908 if (result_count >= 1)
0d031856
TT
2909 copy_threadref (&rs->nextthread,
2910 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2911 i = 0;
2912 while (result_count--)
6dc54d91
PA
2913 {
2914 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2915 {
2916 result = 0;
2917 break;
2918 }
2919 }
c906108c
SS
2920 }
2921 return result;
2922}
2923
6dc54d91
PA
2924/* A thread found on the remote target. */
2925
2926typedef struct thread_item
2927{
2928 /* The thread's PTID. */
2929 ptid_t ptid;
2930
2931 /* The thread's extra info. May be NULL. */
2932 char *extra;
2933
79efa585
SM
2934 /* The thread's name. May be NULL. */
2935 char *name;
2936
6dc54d91
PA
2937 /* The core the thread was running on. -1 if not known. */
2938 int core;
2939} thread_item_t;
2940DEF_VEC_O(thread_item_t);
2941
2942/* Context passed around to the various methods listing remote
2943 threads. As new threads are found, they're added to the ITEMS
2944 vector. */
2945
2946struct threads_listing_context
2947{
2948 /* The threads found on the remote target. */
2949 VEC (thread_item_t) *items;
2950};
2951
80134cf5
PA
2952/* Discard the contents of the constructed thread listing context. */
2953
2954static void
2955clear_threads_listing_context (void *p)
2956{
19ba03f4
SM
2957 struct threads_listing_context *context
2958 = (struct threads_listing_context *) p;
80134cf5
PA
2959 int i;
2960 struct thread_item *item;
2961
2962 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
2963 {
2964 xfree (item->extra);
2965 xfree (item->name);
2966 }
80134cf5
PA
2967
2968 VEC_free (thread_item_t, context->items);
2969}
2970
cbb8991c
DB
2971/* Remove the thread specified as the related_pid field of WS
2972 from the CONTEXT list. */
2973
2974static void
2975threads_listing_context_remove (struct target_waitstatus *ws,
2976 struct threads_listing_context *context)
2977{
2978 struct thread_item *item;
2979 int i;
2980 ptid_t child_ptid = ws->value.related_pid;
2981
2982 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2983 {
2984 if (ptid_equal (item->ptid, child_ptid))
2985 {
2986 VEC_ordered_remove (thread_item_t, context->items, i);
2987 break;
2988 }
2989 }
2990}
2991
c906108c 2992static int
6dc54d91 2993remote_newthread_step (threadref *ref, void *data)
c906108c 2994{
19ba03f4
SM
2995 struct threads_listing_context *context
2996 = (struct threads_listing_context *) data;
6dc54d91 2997 struct thread_item item;
79d7f229 2998 int pid = ptid_get_pid (inferior_ptid);
39f77062 2999
6dc54d91
PA
3000 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3001 item.core = -1;
2e3b657e 3002 item.name = NULL;
6dc54d91
PA
3003 item.extra = NULL;
3004
3005 VEC_safe_push (thread_item_t, context->items, &item);
3006
c906108c
SS
3007 return 1; /* continue iterator */
3008}
3009
3010#define CRAZY_MAX_THREADS 1000
3011
39f77062
KB
3012static ptid_t
3013remote_current_thread (ptid_t oldpid)
c906108c 3014{
d01949b6 3015 struct remote_state *rs = get_remote_state ();
c906108c
SS
3016
3017 putpkt ("qC");
6d820c5c 3018 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3019 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
3020 {
3021 char *obuf;
3022 ptid_t result;
3023
3024 result = read_ptid (&rs->buf[2], &obuf);
3025 if (*obuf != '\0' && remote_debug)
3026 fprintf_unfiltered (gdb_stdlog,
3027 "warning: garbage in qC reply\n");
3028
3029 return result;
3030 }
c906108c
SS
3031 else
3032 return oldpid;
3033}
3034
6dc54d91 3035/* List remote threads using the deprecated qL packet. */
cce74817 3036
6dc54d91
PA
3037static int
3038remote_get_threads_with_ql (struct target_ops *ops,
3039 struct threads_listing_context *context)
c906108c 3040{
6dc54d91
PA
3041 if (remote_threadlist_iterator (remote_newthread_step, context,
3042 CRAZY_MAX_THREADS) >= 0)
3043 return 1;
3044
3045 return 0;
c906108c
SS
3046}
3047
dc146f7c
VP
3048#if defined(HAVE_LIBEXPAT)
3049
dc146f7c
VP
3050static void
3051start_thread (struct gdb_xml_parser *parser,
3052 const struct gdb_xml_element *element,
3053 void *user_data, VEC(gdb_xml_value_s) *attributes)
3054{
19ba03f4
SM
3055 struct threads_listing_context *data
3056 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3057
3058 struct thread_item item;
3059 char *id;
3d2c1d41 3060 struct gdb_xml_value *attr;
dc146f7c 3061
19ba03f4 3062 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
3063 item.ptid = read_ptid (id, NULL);
3064
3d2c1d41
PA
3065 attr = xml_find_attribute (attributes, "core");
3066 if (attr != NULL)
3067 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
3068 else
3069 item.core = -1;
3070
79efa585 3071 attr = xml_find_attribute (attributes, "name");
e1961661 3072 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 3073
dc146f7c
VP
3074 item.extra = 0;
3075
3076 VEC_safe_push (thread_item_t, data->items, &item);
3077}
3078
3079static void
3080end_thread (struct gdb_xml_parser *parser,
3081 const struct gdb_xml_element *element,
3082 void *user_data, const char *body_text)
3083{
19ba03f4
SM
3084 struct threads_listing_context *data
3085 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3086
3087 if (body_text && *body_text)
2ae2a0b7 3088 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3089}
3090
3091const struct gdb_xml_attribute thread_attributes[] = {
3092 { "id", GDB_XML_AF_NONE, NULL, NULL },
3093 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3094 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3095 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3096};
3097
3098const struct gdb_xml_element thread_children[] = {
3099 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3100};
3101
3102const struct gdb_xml_element threads_children[] = {
3103 { "thread", thread_attributes, thread_children,
3104 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3105 start_thread, end_thread },
3106 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3107};
3108
3109const struct gdb_xml_element threads_elements[] = {
3110 { "threads", NULL, threads_children,
3111 GDB_XML_EF_NONE, NULL, NULL },
3112 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3113};
3114
3115#endif
3116
6dc54d91 3117/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3118
6dc54d91
PA
3119static int
3120remote_get_threads_with_qxfer (struct target_ops *ops,
3121 struct threads_listing_context *context)
0f71a2f6 3122{
dc146f7c 3123#if defined(HAVE_LIBEXPAT)
4082afcc 3124 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3125 {
6dc54d91 3126 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3127 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3128
6dc54d91 3129 if (xml != NULL && *xml != '\0')
dc146f7c 3130 {
6dc54d91
PA
3131 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3132 threads_elements, xml, context);
dc146f7c
VP
3133 }
3134
3135 do_cleanups (back_to);
6dc54d91 3136 return 1;
dc146f7c
VP
3137 }
3138#endif
3139
6dc54d91
PA
3140 return 0;
3141}
3142
3143/* List remote threads using qfThreadInfo/qsThreadInfo. */
3144
3145static int
3146remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3147 struct threads_listing_context *context)
3148{
3149 struct remote_state *rs = get_remote_state ();
3150
b80fafe3 3151 if (rs->use_threadinfo_query)
9d1f7ab2 3152 {
6dc54d91
PA
3153 char *bufp;
3154
9d1f7ab2 3155 putpkt ("qfThreadInfo");
6d820c5c 3156 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3157 bufp = rs->buf;
9d1f7ab2 3158 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3159 {
9d1f7ab2
MS
3160 while (*bufp++ == 'm') /* reply contains one or more TID */
3161 {
3162 do
3163 {
6dc54d91
PA
3164 struct thread_item item;
3165
3166 item.ptid = read_ptid (bufp, &bufp);
3167 item.core = -1;
2e3b657e 3168 item.name = NULL;
6dc54d91
PA
3169 item.extra = NULL;
3170
3171 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3172 }
3173 while (*bufp++ == ','); /* comma-separated list */
3174 putpkt ("qsThreadInfo");
6d820c5c 3175 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3176 bufp = rs->buf;
9d1f7ab2 3177 }
6dc54d91
PA
3178 return 1;
3179 }
3180 else
3181 {
3182 /* Packet not recognized. */
3183 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3184 }
3185 }
3186
6dc54d91
PA
3187 return 0;
3188}
3189
e8032dde 3190/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3191 targets. */
3192
3193static void
e8032dde 3194remote_update_thread_list (struct target_ops *ops)
6dc54d91 3195{
6dc54d91
PA
3196 struct threads_listing_context context;
3197 struct cleanup *old_chain;
ab970af1 3198 int got_list = 0;
e8032dde 3199
6dc54d91
PA
3200 context.items = NULL;
3201 old_chain = make_cleanup (clear_threads_listing_context, &context);
3202
3203 /* We have a few different mechanisms to fetch the thread list. Try
3204 them all, starting with the most preferred one first, falling
3205 back to older methods. */
3206 if (remote_get_threads_with_qxfer (ops, &context)
3207 || remote_get_threads_with_qthreadinfo (ops, &context)
3208 || remote_get_threads_with_ql (ops, &context))
3209 {
3210 int i;
3211 struct thread_item *item;
ab970af1
PA
3212 struct thread_info *tp, *tmp;
3213
3214 got_list = 1;
3215
7d1a114c
PA
3216 if (VEC_empty (thread_item_t, context.items)
3217 && remote_thread_always_alive (ops, inferior_ptid))
3218 {
3219 /* Some targets don't really support threads, but still
3220 reply an (empty) thread list in response to the thread
3221 listing packets, instead of replying "packet not
3222 supported". Exit early so we don't delete the main
3223 thread. */
3224 do_cleanups (old_chain);
3225 return;
3226 }
3227
ab970af1
PA
3228 /* CONTEXT now holds the current thread list on the remote
3229 target end. Delete GDB-side threads no longer found on the
3230 target. */
8a06aea7 3231 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3232 {
ab970af1
PA
3233 for (i = 0;
3234 VEC_iterate (thread_item_t, context.items, i, item);
3235 ++i)
3236 {
3237 if (ptid_equal (item->ptid, tp->ptid))
3238 break;
3239 }
3240
3241 if (i == VEC_length (thread_item_t, context.items))
3242 {
3243 /* Not found. */
3244 delete_thread (tp->ptid);
3245 }
cbb8991c
DB
3246 }
3247
3248 /* Remove any unreported fork child threads from CONTEXT so
3249 that we don't interfere with follow fork, which is where
3250 creation of such threads is handled. */
3251 remove_new_fork_children (&context);
74531fed 3252
ab970af1 3253 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3254 for (i = 0;
3255 VEC_iterate (thread_item_t, context.items, i, item);
3256 ++i)
3257 {
3258 if (!ptid_equal (item->ptid, null_ptid))
3259 {
3260 struct private_thread_info *info;
3261 /* In non-stop mode, we assume new found threads are
3262 running until proven otherwise with a stop reply. In
3263 all-stop, we can only get here if all threads are
3264 stopped. */
6efcd9a8 3265 int running = target_is_non_stop_p () ? 1 : 0;
6dc54d91
PA
3266
3267 remote_notice_new_inferior (item->ptid, running);
3268
3269 info = demand_private_info (item->ptid);
3270 info->core = item->core;
3271 info->extra = item->extra;
3272 item->extra = NULL;
79efa585
SM
3273 info->name = item->name;
3274 item->name = NULL;
6dc54d91
PA
3275 }
3276 }
3277 }
3278
ab970af1
PA
3279 if (!got_list)
3280 {
3281 /* If no thread listing method is supported, then query whether
3282 each known thread is alive, one by one, with the T packet.
3283 If the target doesn't support threads at all, then this is a
3284 no-op. See remote_thread_alive. */
3285 prune_threads ();
3286 }
3287
6dc54d91 3288 do_cleanups (old_chain);
9d1f7ab2
MS
3289}
3290
802188a7 3291/*
9d1f7ab2
MS
3292 * Collect a descriptive string about the given thread.
3293 * The target may say anything it wants to about the thread
3294 * (typically info about its blocked / runnable state, name, etc.).
3295 * This string will appear in the info threads display.
802188a7 3296 *
9d1f7ab2
MS
3297 * Optional: targets are not required to implement this function.
3298 */
3299
3300static char *
c15906d8 3301remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3302{
d01949b6 3303 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3304 int result;
3305 int set;
3306 threadref id;
3307 struct gdb_ext_thread_info threadinfo;
23860348 3308 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3309 int n = 0; /* position in display_buf */
3310
5d93a237 3311 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3312 internal_error (__FILE__, __LINE__,
e2e0b3e5 3313 _("remote_threads_extra_info"));
9d1f7ab2 3314
60e569b9 3315 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3316 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3317 /* This is the main thread which was added by GDB. The remote
3318 server doesn't know about it. */
3319 return NULL;
3320
4082afcc 3321 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3322 {
3323 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3324
fe978cb0
PA
3325 if (info && info->priv)
3326 return info->priv->extra;
dc146f7c
VP
3327 else
3328 return NULL;
3329 }
3330
b80fafe3 3331 if (rs->use_threadextra_query)
9d1f7ab2 3332 {
82f73884
PA
3333 char *b = rs->buf;
3334 char *endb = rs->buf + get_remote_packet_size ();
3335
3336 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3337 b += strlen (b);
3338 write_ptid (b, endb, tp->ptid);
3339
2e9f7625 3340 putpkt (rs->buf);
6d820c5c 3341 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3342 if (rs->buf[0] != 0)
9d1f7ab2 3343 {
2e9f7625
DJ
3344 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3345 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3346 display_buf [result] = '\0';
9d1f7ab2
MS
3347 return display_buf;
3348 }
0f71a2f6 3349 }
9d1f7ab2
MS
3350
3351 /* If the above query fails, fall back to the old method. */
b80fafe3 3352 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3353 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3354 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3355 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3356 if (remote_get_threadinfo (&id, set, &threadinfo))
3357 if (threadinfo.active)
0f71a2f6 3358 {
9d1f7ab2 3359 if (*threadinfo.shortname)
2bc416ba 3360 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3361 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3362 if (*threadinfo.display)
2bc416ba 3363 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3364 " State: %s,", threadinfo.display);
9d1f7ab2 3365 if (*threadinfo.more_display)
2bc416ba 3366 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3367 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3368
3369 if (n > 0)
c5aa993b 3370 {
23860348 3371 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3372 if (',' == display_buf[n-1])
3373 display_buf[n-1] = ' ';
3374 return display_buf;
c5aa993b 3375 }
0f71a2f6 3376 }
9d1f7ab2 3377 return NULL;
0f71a2f6 3378}
c906108c 3379\f
c5aa993b 3380
0fb4aa4b 3381static int
61fc905d 3382remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3383 struct static_tracepoint_marker *marker)
3384{
3385 struct remote_state *rs = get_remote_state ();
3386 char *p = rs->buf;
3387
bba74b36 3388 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3389 p += strlen (p);
3390 p += hexnumstr (p, addr);
3391 putpkt (rs->buf);
3392 getpkt (&rs->buf, &rs->buf_size, 0);
3393 p = rs->buf;
3394
3395 if (*p == 'E')
3396 error (_("Remote failure reply: %s"), p);
3397
3398 if (*p++ == 'm')
3399 {
3400 parse_static_tracepoint_marker_definition (p, &p, marker);
3401 return 1;
3402 }
3403
3404 return 0;
3405}
3406
0fb4aa4b 3407static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3408remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3409 const char *strid)
0fb4aa4b
PA
3410{
3411 struct remote_state *rs = get_remote_state ();
3412 VEC(static_tracepoint_marker_p) *markers = NULL;
3413 struct static_tracepoint_marker *marker = NULL;
3414 struct cleanup *old_chain;
3415 char *p;
3416
3417 /* Ask for a first packet of static tracepoint marker
3418 definition. */
3419 putpkt ("qTfSTM");
3420 getpkt (&rs->buf, &rs->buf_size, 0);
3421 p = rs->buf;
3422 if (*p == 'E')
3423 error (_("Remote failure reply: %s"), p);
3424
3425 old_chain = make_cleanup (free_current_marker, &marker);
3426
3427 while (*p++ == 'm')
3428 {
3429 if (marker == NULL)
3430 marker = XCNEW (struct static_tracepoint_marker);
3431
3432 do
3433 {
3434 parse_static_tracepoint_marker_definition (p, &p, marker);
3435
3436 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3437 {
3438 VEC_safe_push (static_tracepoint_marker_p,
3439 markers, marker);
3440 marker = NULL;
3441 }
3442 else
3443 {
3444 release_static_tracepoint_marker (marker);
3445 memset (marker, 0, sizeof (*marker));
3446 }
3447 }
3448 while (*p++ == ','); /* comma-separated list */
3449 /* Ask for another packet of static tracepoint definition. */
3450 putpkt ("qTsSTM");
3451 getpkt (&rs->buf, &rs->buf_size, 0);
3452 p = rs->buf;
3453 }
3454
3455 do_cleanups (old_chain);
3456 return markers;
3457}
3458
3459\f
10760264
JB
3460/* Implement the to_get_ada_task_ptid function for the remote targets. */
3461
3462static ptid_t
1e6b91a4 3463remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3464{
ba348170 3465 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3466}
3467\f
3468
24b06219 3469/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3470
3471static void
fba45db2 3472extended_remote_restart (void)
c906108c 3473{
d01949b6 3474 struct remote_state *rs = get_remote_state ();
c906108c
SS
3475
3476 /* Send the restart command; for reasons I don't understand the
3477 remote side really expects a number after the "R". */
ea9c271d 3478 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3479 putpkt (rs->buf);
c906108c 3480
ad9a8f3f 3481 remote_fileio_reset ();
c906108c
SS
3482}
3483\f
3484/* Clean up connection to a remote debugger. */
3485
c906108c 3486static void
de90e03d 3487remote_close (struct target_ops *self)
c906108c 3488{
5d93a237
TT
3489 struct remote_state *rs = get_remote_state ();
3490
3491 if (rs->remote_desc == NULL)
d3fd5342
PA
3492 return; /* already closed */
3493
3494 /* Make sure we leave stdin registered in the event loop, and we
3495 don't leave the async SIGINT signal handler installed. */
e3594fd1 3496 remote_terminal_ours (self);
ce5ce7ed 3497
5d93a237
TT
3498 serial_close (rs->remote_desc);
3499 rs->remote_desc = NULL;
ce5ce7ed
PA
3500
3501 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3502 of all the inferiors and their threads we were controlling.
3503 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3504 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3505 inferior_ptid = null_ptid;
f67fd822 3506 discard_all_inferiors ();
ce5ce7ed 3507
f48ff2a7
YQ
3508 /* We are closing the remote target, so we should discard
3509 everything of this target. */
bcc75809 3510 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3511
3512 if (remote_async_inferior_event_token)
3513 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3514
5965e028 3515 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3516
3517 trace_reset_local_state ();
c906108c
SS
3518}
3519
23860348 3520/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3521
3522static void
fba45db2 3523get_offsets (void)
c906108c 3524{
d01949b6 3525 struct remote_state *rs = get_remote_state ();
2e9f7625 3526 char *buf;
085dd6e6 3527 char *ptr;
31d99776
DJ
3528 int lose, num_segments = 0, do_sections, do_segments;
3529 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3530 struct section_offsets *offs;
31d99776
DJ
3531 struct symfile_segment_data *data;
3532
3533 if (symfile_objfile == NULL)
3534 return;
c906108c
SS
3535
3536 putpkt ("qOffsets");
6d820c5c 3537 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3538 buf = rs->buf;
c906108c
SS
3539
3540 if (buf[0] == '\000')
3541 return; /* Return silently. Stub doesn't support
23860348 3542 this command. */
c906108c
SS
3543 if (buf[0] == 'E')
3544 {
8a3fe4f8 3545 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3546 return;
3547 }
3548
3549 /* Pick up each field in turn. This used to be done with scanf, but
3550 scanf will make trouble if CORE_ADDR size doesn't match
3551 conversion directives correctly. The following code will work
3552 with any size of CORE_ADDR. */
3553 text_addr = data_addr = bss_addr = 0;
3554 ptr = buf;
3555 lose = 0;
3556
61012eef 3557 if (startswith (ptr, "Text="))
c906108c
SS
3558 {
3559 ptr += 5;
3560 /* Don't use strtol, could lose on big values. */
3561 while (*ptr && *ptr != ';')
3562 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3563
61012eef 3564 if (startswith (ptr, ";Data="))
31d99776
DJ
3565 {
3566 ptr += 6;
3567 while (*ptr && *ptr != ';')
3568 data_addr = (data_addr << 4) + fromhex (*ptr++);
3569 }
3570 else
3571 lose = 1;
3572
61012eef 3573 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3574 {
3575 ptr += 5;
3576 while (*ptr && *ptr != ';')
3577 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3578
31d99776
DJ
3579 if (bss_addr != data_addr)
3580 warning (_("Target reported unsupported offsets: %s"), buf);
3581 }
3582 else
3583 lose = 1;
3584 }
61012eef 3585 else if (startswith (ptr, "TextSeg="))
c906108c 3586 {
31d99776
DJ
3587 ptr += 8;
3588 /* Don't use strtol, could lose on big values. */
c906108c 3589 while (*ptr && *ptr != ';')
31d99776
DJ
3590 text_addr = (text_addr << 4) + fromhex (*ptr++);
3591 num_segments = 1;
3592
61012eef 3593 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3594 {
3595 ptr += 9;
3596 while (*ptr && *ptr != ';')
3597 data_addr = (data_addr << 4) + fromhex (*ptr++);
3598 num_segments++;
3599 }
c906108c
SS
3600 }
3601 else
3602 lose = 1;
3603
3604 if (lose)
8a3fe4f8 3605 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3606 else if (*ptr != '\0')
3607 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3608
802188a7 3609 offs = ((struct section_offsets *)
a39a16c4 3610 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3611 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3612 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3613
31d99776
DJ
3614 data = get_symfile_segment_data (symfile_objfile->obfd);
3615 do_segments = (data != NULL);
3616 do_sections = num_segments == 0;
c906108c 3617
28c32713 3618 if (num_segments > 0)
31d99776 3619 {
31d99776
DJ
3620 segments[0] = text_addr;
3621 segments[1] = data_addr;
3622 }
28c32713
JB
3623 /* If we have two segments, we can still try to relocate everything
3624 by assuming that the .text and .data offsets apply to the whole
3625 text and data segments. Convert the offsets given in the packet
3626 to base addresses for symfile_map_offsets_to_segments. */
3627 else if (data && data->num_segments == 2)
3628 {
3629 segments[0] = data->segment_bases[0] + text_addr;
3630 segments[1] = data->segment_bases[1] + data_addr;
3631 num_segments = 2;
3632 }
8d385431
DJ
3633 /* If the object file has only one segment, assume that it is text
3634 rather than data; main programs with no writable data are rare,
3635 but programs with no code are useless. Of course the code might
3636 have ended up in the data segment... to detect that we would need
3637 the permissions here. */
3638 else if (data && data->num_segments == 1)
3639 {
3640 segments[0] = data->segment_bases[0] + text_addr;
3641 num_segments = 1;
3642 }
28c32713
JB
3643 /* There's no way to relocate by segment. */
3644 else
3645 do_segments = 0;
31d99776
DJ
3646
3647 if (do_segments)
3648 {
3649 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3650 offs, num_segments, segments);
3651
3652 if (ret == 0 && !do_sections)
3e43a32a
MS
3653 error (_("Can not handle qOffsets TextSeg "
3654 "response with this symbol file"));
31d99776
DJ
3655
3656 if (ret > 0)
3657 do_sections = 0;
3658 }
c906108c 3659
9ef895d6
DJ
3660 if (data)
3661 free_symfile_segment_data (data);
31d99776
DJ
3662
3663 if (do_sections)
3664 {
3665 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3666
3e43a32a
MS
3667 /* This is a temporary kludge to force data and bss to use the
3668 same offsets because that's what nlmconv does now. The real
3669 solution requires changes to the stub and remote.c that I
3670 don't have time to do right now. */
31d99776
DJ
3671
3672 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3673 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3674 }
c906108c
SS
3675
3676 objfile_relocate (symfile_objfile, offs);
3677}
3678
9a7071a8
JB
3679/* Send interrupt_sequence to remote target. */
3680static void
eeae04df 3681send_interrupt_sequence (void)
9a7071a8 3682{
5d93a237
TT
3683 struct remote_state *rs = get_remote_state ();
3684
9a7071a8 3685 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3686 remote_serial_write ("\x03", 1);
9a7071a8 3687 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3688 serial_send_break (rs->remote_desc);
9a7071a8
JB
3689 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3690 {
5d93a237 3691 serial_send_break (rs->remote_desc);
c33e31fd 3692 remote_serial_write ("g", 1);
9a7071a8
JB
3693 }
3694 else
3695 internal_error (__FILE__, __LINE__,
3696 _("Invalid value for interrupt_sequence_mode: %s."),
3697 interrupt_sequence_mode);
3698}
3699
3405876a
PA
3700
3701/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3702 and extract the PTID. Returns NULL_PTID if not found. */
3703
3704static ptid_t
3705stop_reply_extract_thread (char *stop_reply)
3706{
3707 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3708 {
3709 char *p;
3710
3711 /* Txx r:val ; r:val (...) */
3712 p = &stop_reply[3];
3713
3714 /* Look for "register" named "thread". */
3715 while (*p != '\0')
3716 {
3717 char *p1;
3718
3719 p1 = strchr (p, ':');
3720 if (p1 == NULL)
3721 return null_ptid;
3722
3723 if (strncmp (p, "thread", p1 - p) == 0)
3724 return read_ptid (++p1, &p);
3725
3726 p1 = strchr (p, ';');
3727 if (p1 == NULL)
3728 return null_ptid;
3729 p1++;
3730
3731 p = p1;
3732 }
3733 }
3734
3735 return null_ptid;
3736}
3737
b7ea362b
PA
3738/* Determine the remote side's current thread. If we have a stop
3739 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3740 "thread" register we can extract the current thread from. If not,
3741 ask the remote which is the current thread with qC. The former
3742 method avoids a roundtrip. */
3743
3744static ptid_t
3745get_current_thread (char *wait_status)
3746{
6a49a997 3747 ptid_t ptid = null_ptid;
b7ea362b
PA
3748
3749 /* Note we don't use remote_parse_stop_reply as that makes use of
3750 the target architecture, which we haven't yet fully determined at
3751 this point. */
3752 if (wait_status != NULL)
3753 ptid = stop_reply_extract_thread (wait_status);
3754 if (ptid_equal (ptid, null_ptid))
3755 ptid = remote_current_thread (inferior_ptid);
3756
3757 return ptid;
3758}
3759
49c62f2e
PA
3760/* Query the remote target for which is the current thread/process,
3761 add it to our tables, and update INFERIOR_PTID. The caller is
3762 responsible for setting the state such that the remote end is ready
3405876a
PA
3763 to return the current thread.
3764
3765 This function is called after handling the '?' or 'vRun' packets,
3766 whose response is a stop reply from which we can also try
3767 extracting the thread. If the target doesn't support the explicit
3768 qC query, we infer the current thread from that stop reply, passed
3769 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3770
3771static void
3405876a 3772add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3773{
3774 struct remote_state *rs = get_remote_state ();
3775 int fake_pid_p = 0;
6a49a997 3776 ptid_t ptid;
49c62f2e
PA
3777
3778 inferior_ptid = null_ptid;
3779
b7ea362b
PA
3780 /* Now, if we have thread information, update inferior_ptid. */
3781 ptid = get_current_thread (wait_status);
3405876a 3782
49c62f2e
PA
3783 if (!ptid_equal (ptid, null_ptid))
3784 {
3785 if (!remote_multi_process_p (rs))
3786 fake_pid_p = 1;
3787
3788 inferior_ptid = ptid;
3789 }
3790 else
3791 {
3792 /* Without this, some commands which require an active target
3793 (such as kill) won't work. This variable serves (at least)
3794 double duty as both the pid of the target process (if it has
3795 such), and as a flag indicating that a target is active. */
3796 inferior_ptid = magic_null_ptid;
3797 fake_pid_p = 1;
3798 }
3799
1b6e6f5c 3800 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3801
3802 /* Add the main thread. */
3803 add_thread_silent (inferior_ptid);
3804}
3805
6efcd9a8
PA
3806/* Print info about a thread that was found already stopped on
3807 connection. */
3808
3809static void
3810print_one_stopped_thread (struct thread_info *thread)
3811{
3812 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3813
3814 switch_to_thread (thread->ptid);
3815 stop_pc = get_frame_pc (get_current_frame ());
3816 set_current_sal_from_frame (get_current_frame ());
3817
3818 thread->suspend.waitstatus_pending_p = 0;
3819
3820 if (ws->kind == TARGET_WAITKIND_STOPPED)
3821 {
3822 enum gdb_signal sig = ws->value.sig;
3823
3824 if (signal_print_state (sig))
3825 observer_notify_signal_received (sig);
3826 }
3827 observer_notify_normal_stop (NULL, 1);
3828}
3829
221e1a37
PA
3830/* Process all initial stop replies the remote side sent in response
3831 to the ? packet. These indicate threads that were already stopped
3832 on initial connection. We mark these threads as stopped and print
3833 their current frame before giving the user the prompt. */
3834
3835static void
6efcd9a8 3836process_initial_stop_replies (int from_tty)
221e1a37
PA
3837{
3838 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3839 struct inferior *inf;
3840 struct thread_info *thread;
3841 struct thread_info *selected = NULL;
3842 struct thread_info *lowest_stopped = NULL;
3843 struct thread_info *first = NULL;
221e1a37
PA
3844
3845 /* Consume the initial pending events. */
3846 while (pending_stop_replies-- > 0)
3847 {
3848 ptid_t waiton_ptid = minus_one_ptid;
3849 ptid_t event_ptid;
3850 struct target_waitstatus ws;
3851 int ignore_event = 0;
6efcd9a8 3852 struct thread_info *thread;
221e1a37
PA
3853
3854 memset (&ws, 0, sizeof (ws));
3855 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3856 if (remote_debug)
3857 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3858
3859 switch (ws.kind)
3860 {
3861 case TARGET_WAITKIND_IGNORE:
3862 case TARGET_WAITKIND_NO_RESUMED:
3863 case TARGET_WAITKIND_SIGNALLED:
3864 case TARGET_WAITKIND_EXITED:
3865 /* We shouldn't see these, but if we do, just ignore. */
3866 if (remote_debug)
3867 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3868 ignore_event = 1;
3869 break;
3870
3871 case TARGET_WAITKIND_EXECD:
3872 xfree (ws.value.execd_pathname);
3873 break;
3874 default:
3875 break;
3876 }
3877
3878 if (ignore_event)
3879 continue;
3880
6efcd9a8 3881 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3882
3883 if (ws.kind == TARGET_WAITKIND_STOPPED)
3884 {
3885 enum gdb_signal sig = ws.value.sig;
3886
3887 /* Stubs traditionally report SIGTRAP as initial signal,
3888 instead of signal 0. Suppress it. */
3889 if (sig == GDB_SIGNAL_TRAP)
3890 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3891 thread->suspend.stop_signal = sig;
3892 ws.value.sig = sig;
3893 }
221e1a37 3894
6efcd9a8
PA
3895 thread->suspend.waitstatus = ws;
3896
3897 if (ws.kind != TARGET_WAITKIND_STOPPED
3898 || ws.value.sig != GDB_SIGNAL_0)
3899 thread->suspend.waitstatus_pending_p = 1;
3900
3901 set_executing (event_ptid, 0);
3902 set_running (event_ptid, 0);
3903 }
3904
3905 /* "Notice" the new inferiors before anything related to
3906 registers/memory. */
3907 ALL_INFERIORS (inf)
3908 {
3909 if (inf->pid == 0)
3910 continue;
3911
3912 inf->needs_setup = 1;
3913
3914 if (non_stop)
3915 {
3916 thread = any_live_thread_of_process (inf->pid);
3917 notice_new_inferior (thread->ptid,
3918 thread->state == THREAD_RUNNING,
3919 from_tty);
3920 }
3921 }
3922
3923 /* If all-stop on top of non-stop, pause all threads. Note this
3924 records the threads' stop pc, so must be done after "noticing"
3925 the inferiors. */
3926 if (!non_stop)
3927 {
3928 stop_all_threads ();
3929
3930 /* If all threads of an inferior were already stopped, we
3931 haven't setup the inferior yet. */
3932 ALL_INFERIORS (inf)
3933 {
3934 if (inf->pid == 0)
3935 continue;
221e1a37 3936
6efcd9a8
PA
3937 if (inf->needs_setup)
3938 {
3939 thread = any_live_thread_of_process (inf->pid);
3940 switch_to_thread_no_regs (thread);
3941 setup_inferior (0);
3942 }
3943 }
221e1a37 3944 }
6efcd9a8
PA
3945
3946 /* Now go over all threads that are stopped, and print their current
3947 frame. If all-stop, then if there's a signalled thread, pick
3948 that as current. */
3949 ALL_NON_EXITED_THREADS (thread)
3950 {
6efcd9a8
PA
3951 if (first == NULL)
3952 first = thread;
3953
3954 if (!non_stop)
3955 set_running (thread->ptid, 0);
3956 else if (thread->state != THREAD_STOPPED)
3957 continue;
3958
6efcd9a8
PA
3959 if (selected == NULL
3960 && thread->suspend.waitstatus_pending_p)
3961 selected = thread;
3962
5d5658a1
PA
3963 if (lowest_stopped == NULL
3964 || thread->inf->num < lowest_stopped->inf->num
3965 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
3966 lowest_stopped = thread;
3967
3968 if (non_stop)
3969 print_one_stopped_thread (thread);
3970 }
3971
3972 /* In all-stop, we only print the status of one thread, and leave
3973 others with their status pending. */
3974 if (!non_stop)
3975 {
3976 thread = selected;
3977 if (thread == NULL)
3978 thread = lowest_stopped;
3979 if (thread == NULL)
3980 thread = first;
3981
3982 print_one_stopped_thread (thread);
3983 }
3984
3985 /* For "info program". */
3986 thread = inferior_thread ();
3987 if (thread->state == THREAD_STOPPED)
3988 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
3989}
3990
9cbc821d 3991static void
04bd08de 3992remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3993{
c8d104ad
PA
3994 struct remote_state *rs = get_remote_state ();
3995 struct packet_config *noack_config;
2d717e4f 3996 char *wait_status = NULL;
8621d6a9 3997
23860348 3998 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3999 QUIT;
c906108c 4000
9a7071a8
JB
4001 if (interrupt_on_connect)
4002 send_interrupt_sequence ();
4003
57e12211 4004 /* Ack any packet which the remote side has already sent. */
5d93a237 4005 serial_write (rs->remote_desc, "+", 1);
57e12211 4006
1e51243a
PA
4007 /* Signal other parts that we're going through the initial setup,
4008 and so things may not be stable yet. */
4009 rs->starting_up = 1;
4010
c8d104ad
PA
4011 /* The first packet we send to the target is the optional "supported
4012 packets" request. If the target can answer this, it will tell us
4013 which later probes to skip. */
4014 remote_query_supported ();
4015
d914c394 4016 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4017 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 4018 remote_set_permissions (target);
d914c394 4019
c8d104ad
PA
4020 /* Next, we possibly activate noack mode.
4021
4022 If the QStartNoAckMode packet configuration is set to AUTO,
4023 enable noack mode if the stub reported a wish for it with
4024 qSupported.
4025
4026 If set to TRUE, then enable noack mode even if the stub didn't
4027 report it in qSupported. If the stub doesn't reply OK, the
4028 session ends with an error.
4029
4030 If FALSE, then don't activate noack mode, regardless of what the
4031 stub claimed should be the default with qSupported. */
4032
4033 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4034 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4035 {
4036 putpkt ("QStartNoAckMode");
4037 getpkt (&rs->buf, &rs->buf_size, 0);
4038 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4039 rs->noack_mode = 1;
4040 }
4041
04bd08de 4042 if (extended_p)
5fe04517
PA
4043 {
4044 /* Tell the remote that we are using the extended protocol. */
4045 putpkt ("!");
4046 getpkt (&rs->buf, &rs->buf_size, 0);
4047 }
4048
9b224c5e
PA
4049 /* Let the target know which signals it is allowed to pass down to
4050 the program. */
4051 update_signals_program_target ();
4052
d962ef82
DJ
4053 /* Next, if the target can specify a description, read it. We do
4054 this before anything involving memory or registers. */
4055 target_find_description ();
4056
6c95b8df
PA
4057 /* Next, now that we know something about the target, update the
4058 address spaces in the program spaces. */
4059 update_address_spaces ();
4060
50c71eaf
PA
4061 /* On OSs where the list of libraries is global to all
4062 processes, we fetch them early. */
f5656ead 4063 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 4064 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 4065
6efcd9a8 4066 if (target_is_non_stop_p ())
74531fed 4067 {
4082afcc 4068 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4069 error (_("Non-stop mode requested, but remote "
4070 "does not support non-stop"));
74531fed
PA
4071
4072 putpkt ("QNonStop:1");
4073 getpkt (&rs->buf, &rs->buf_size, 0);
4074
4075 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4076 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4077
4078 /* Find about threads and processes the stub is already
4079 controlling. We default to adding them in the running state.
4080 The '?' query below will then tell us about which threads are
4081 stopped. */
e8032dde 4082 remote_update_thread_list (target);
74531fed 4083 }
4082afcc 4084 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4085 {
4086 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4087 Request it explicitly. */
74531fed
PA
4088 putpkt ("QNonStop:0");
4089 getpkt (&rs->buf, &rs->buf_size, 0);
4090
4091 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4092 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4093 }
4094
a0743c90
YQ
4095 /* Upload TSVs regardless of whether the target is running or not. The
4096 remote stub, such as GDBserver, may have some predefined or builtin
4097 TSVs, even if the target is not running. */
8bd200f1 4098 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4099 {
4100 struct uploaded_tsv *uploaded_tsvs = NULL;
4101
181e3713 4102 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4103 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4104 }
4105
2d717e4f
DJ
4106 /* Check whether the target is running now. */
4107 putpkt ("?");
4108 getpkt (&rs->buf, &rs->buf_size, 0);
4109
6efcd9a8 4110 if (!target_is_non_stop_p ())
2d717e4f 4111 {
74531fed 4112 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4113 {
04bd08de 4114 if (!extended_p)
74531fed 4115 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4116
4117 /* We're connected, but not running. Drop out before we
4118 call start_remote. */
e278ad5b 4119 rs->starting_up = 0;
c35b1492 4120 return;
2d717e4f
DJ
4121 }
4122 else
74531fed 4123 {
74531fed 4124 /* Save the reply for later. */
224c3ddb 4125 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4126 strcpy (wait_status, rs->buf);
4127 }
4128
b7ea362b 4129 /* Fetch thread list. */
e8032dde 4130 target_update_thread_list ();
b7ea362b 4131
74531fed
PA
4132 /* Let the stub know that we want it to return the thread. */
4133 set_continue_thread (minus_one_ptid);
4134
b7ea362b
PA
4135 if (thread_count () == 0)
4136 {
4137 /* Target has no concept of threads at all. GDB treats
4138 non-threaded target as single-threaded; add a main
4139 thread. */
4140 add_current_inferior_and_thread (wait_status);
4141 }
4142 else
4143 {
4144 /* We have thread information; select the thread the target
4145 says should be current. If we're reconnecting to a
4146 multi-threaded program, this will ideally be the thread
4147 that last reported an event before GDB disconnected. */
4148 inferior_ptid = get_current_thread (wait_status);
4149 if (ptid_equal (inferior_ptid, null_ptid))
4150 {
4151 /* Odd... The target was able to list threads, but not
4152 tell us which thread was current (no "thread"
4153 register in T stop reply?). Just pick the first
4154 thread in the thread list then. */
c9f35b34
KB
4155
4156 if (remote_debug)
4157 fprintf_unfiltered (gdb_stdlog,
4158 "warning: couldn't determine remote "
4159 "current thread; picking first in list.\n");
4160
b7ea362b
PA
4161 inferior_ptid = thread_list->ptid;
4162 }
4163 }
74531fed 4164
6e586cc5
YQ
4165 /* init_wait_for_inferior should be called before get_offsets in order
4166 to manage `inserted' flag in bp loc in a correct state.
4167 breakpoint_init_inferior, called from init_wait_for_inferior, set
4168 `inserted' flag to 0, while before breakpoint_re_set, called from
4169 start_remote, set `inserted' flag to 1. In the initialization of
4170 inferior, breakpoint_init_inferior should be called first, and then
4171 breakpoint_re_set can be called. If this order is broken, state of
4172 `inserted' flag is wrong, and cause some problems on breakpoint
4173 manipulation. */
4174 init_wait_for_inferior ();
4175
74531fed
PA
4176 get_offsets (); /* Get text, data & bss offsets. */
4177
d962ef82
DJ
4178 /* If we could not find a description using qXfer, and we know
4179 how to do it some other way, try again. This is not
4180 supported for non-stop; it could be, but it is tricky if
4181 there are no stopped threads when we connect. */
04bd08de 4182 if (remote_read_description_p (target)
f5656ead 4183 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4184 {
4185 target_clear_description ();
4186 target_find_description ();
4187 }
4188
74531fed
PA
4189 /* Use the previously fetched status. */
4190 gdb_assert (wait_status != NULL);
4191 strcpy (rs->buf, wait_status);
4192 rs->cached_wait_status = 1;
4193
4194 immediate_quit--;
04bd08de 4195 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4196 }
4197 else
4198 {
68c97600
PA
4199 /* Clear WFI global state. Do this before finding about new
4200 threads and inferiors, and setting the current inferior.
4201 Otherwise we would clear the proceed status of the current
4202 inferior when we want its stop_soon state to be preserved
4203 (see notice_new_inferior). */
4204 init_wait_for_inferior ();
4205
74531fed
PA
4206 /* In non-stop, we will either get an "OK", meaning that there
4207 are no stopped threads at this time; or, a regular stop
4208 reply. In the latter case, there may be more than one thread
4209 stopped --- we pull them all out using the vStopped
4210 mechanism. */
4211 if (strcmp (rs->buf, "OK") != 0)
4212 {
722247f1 4213 struct notif_client *notif = &notif_client_stop;
2d717e4f 4214
722247f1
YQ
4215 /* remote_notif_get_pending_replies acks this one, and gets
4216 the rest out. */
f48ff2a7 4217 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4218 = remote_notif_parse (notif, rs->buf);
4219 remote_notif_get_pending_events (notif);
74531fed 4220 }
2d717e4f 4221
74531fed
PA
4222 if (thread_count () == 0)
4223 {
04bd08de 4224 if (!extended_p)
74531fed 4225 error (_("The target is not running (try extended-remote?)"));
82f73884 4226
c35b1492
PA
4227 /* We're connected, but not running. Drop out before we
4228 call start_remote. */
e278ad5b 4229 rs->starting_up = 0;
c35b1492
PA
4230 return;
4231 }
74531fed 4232
74531fed
PA
4233 /* In non-stop mode, any cached wait status will be stored in
4234 the stop reply queue. */
4235 gdb_assert (wait_status == NULL);
f0223081 4236
2455069d 4237 /* Report all signals during attach/startup. */
94bedb42 4238 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4239
4240 /* If there are already stopped threads, mark them stopped and
4241 report their stops before giving the prompt to the user. */
6efcd9a8 4242 process_initial_stop_replies (from_tty);
221e1a37
PA
4243
4244 if (target_can_async_p ())
4245 target_async (1);
74531fed 4246 }
c8d104ad 4247
c8d104ad
PA
4248 /* If we connected to a live target, do some additional setup. */
4249 if (target_has_execution)
4250 {
f4ccffad 4251 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4252 remote_check_symbols ();
c8d104ad 4253 }
50c71eaf 4254
d5551862
SS
4255 /* Possibly the target has been engaged in a trace run started
4256 previously; find out where things are at. */
8bd200f1 4257 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4258 {
00bf0b85 4259 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4260
00bf0b85
SS
4261 if (current_trace_status ()->running)
4262 printf_filtered (_("Trace is already running on the target.\n"));
4263
ab6617cc 4264 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4265
4266 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4267 }
4268
1e51243a
PA
4269 /* The thread and inferior lists are now synchronized with the
4270 target, our symbols have been relocated, and we're merged the
4271 target's tracepoints with ours. We're done with basic start
4272 up. */
4273 rs->starting_up = 0;
4274
a25a5a45
PA
4275 /* Maybe breakpoints are global and need to be inserted now. */
4276 if (breakpoints_should_be_inserted_now ())
50c71eaf 4277 insert_breakpoints ();
c906108c
SS
4278}
4279
4280/* Open a connection to a remote debugger.
4281 NAME is the filename used for communication. */
4282
4283static void
014f9477 4284remote_open (const char *name, int from_tty)
c906108c 4285{
75c99385 4286 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4287}
4288
c906108c
SS
4289/* Open a connection to a remote debugger using the extended
4290 remote gdb protocol. NAME is the filename used for communication. */
4291
4292static void
014f9477 4293extended_remote_open (const char *name, int from_tty)
c906108c 4294{
75c99385 4295 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4296}
4297
ca4f7f8b
PA
4298/* Reset all packets back to "unknown support". Called when opening a
4299 new connection to a remote target. */
c906108c 4300
d471ea57 4301static void
ca4f7f8b 4302reset_all_packet_configs_support (void)
d471ea57
AC
4303{
4304 int i;
a744cf53 4305
444abaca 4306 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4307 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4308}
4309
ca4f7f8b
PA
4310/* Initialize all packet configs. */
4311
4312static void
4313init_all_packet_configs (void)
4314{
4315 int i;
4316
4317 for (i = 0; i < PACKET_MAX; i++)
4318 {
4319 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4320 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4321 }
4322}
4323
23860348 4324/* Symbol look-up. */
dc8acb97
MS
4325
4326static void
36d25514 4327remote_check_symbols (void)
dc8acb97 4328{
d01949b6 4329 struct remote_state *rs = get_remote_state ();
dc8acb97 4330 char *msg, *reply, *tmp;
dc8acb97 4331 int end;
a5c0808e 4332 struct cleanup *old_chain;
dc8acb97 4333
63154eca
PA
4334 /* The remote side has no concept of inferiors that aren't running
4335 yet, it only knows about running processes. If we're connected
4336 but our current inferior is not running, we should not invite the
4337 remote target to request symbol lookups related to its
4338 (unrelated) current process. */
4339 if (!target_has_execution)
4340 return;
4341
4082afcc 4342 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4343 return;
4344
63154eca
PA
4345 /* Make sure the remote is pointing at the right process. Note
4346 there's no way to select "no process". */
3c9c4b83
PA
4347 set_general_process ();
4348
6d820c5c
DJ
4349 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4350 because we need both at the same time. */
224c3ddb 4351 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4352 old_chain = make_cleanup (xfree, msg);
6d820c5c 4353
23860348 4354 /* Invite target to request symbol lookups. */
dc8acb97
MS
4355
4356 putpkt ("qSymbol::");
6d820c5c
DJ
4357 getpkt (&rs->buf, &rs->buf_size, 0);
4358 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 4359 reply = rs->buf;
dc8acb97 4360
61012eef 4361 while (startswith (reply, "qSymbol:"))
dc8acb97 4362 {
77e371c0
TT
4363 struct bound_minimal_symbol sym;
4364
dc8acb97 4365 tmp = &reply[8];
cfd77fa1 4366 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4367 msg[end] = '\0';
4368 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4369 if (sym.minsym == NULL)
ea9c271d 4370 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4371 else
2bbe3cc1 4372 {
f5656ead 4373 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4374 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4375
4376 /* If this is a function address, return the start of code
4377 instead of any data function descriptor. */
f5656ead 4378 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4379 sym_addr,
4380 &current_target);
4381
4382 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4383 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4384 }
4385
dc8acb97 4386 putpkt (msg);
6d820c5c 4387 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4388 reply = rs->buf;
dc8acb97 4389 }
a5c0808e
PA
4390
4391 do_cleanups (old_chain);
dc8acb97
MS
4392}
4393
9db8d71f 4394static struct serial *
baa336ce 4395remote_serial_open (const char *name)
9db8d71f
DJ
4396{
4397 static int udp_warning = 0;
4398
4399 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4400 of in ser-tcp.c, because it is the remote protocol assuming that the
4401 serial connection is reliable and not the serial connection promising
4402 to be. */
61012eef 4403 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4404 {
3e43a32a
MS
4405 warning (_("The remote protocol may be unreliable over UDP.\n"
4406 "Some events may be lost, rendering further debugging "
4407 "impossible."));
9db8d71f
DJ
4408 udp_warning = 1;
4409 }
4410
4411 return serial_open (name);
4412}
4413
d914c394
SS
4414/* Inform the target of our permission settings. The permission flags
4415 work without this, but if the target knows the settings, it can do
4416 a couple things. First, it can add its own check, to catch cases
4417 that somehow manage to get by the permissions checks in target
4418 methods. Second, if the target is wired to disallow particular
4419 settings (for instance, a system in the field that is not set up to
4420 be able to stop at a breakpoint), it can object to any unavailable
4421 permissions. */
4422
4423void
c378d69d 4424remote_set_permissions (struct target_ops *self)
d914c394
SS
4425{
4426 struct remote_state *rs = get_remote_state ();
4427
bba74b36
YQ
4428 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4429 "WriteReg:%x;WriteMem:%x;"
4430 "InsertBreak:%x;InsertTrace:%x;"
4431 "InsertFastTrace:%x;Stop:%x",
4432 may_write_registers, may_write_memory,
4433 may_insert_breakpoints, may_insert_tracepoints,
4434 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4435 putpkt (rs->buf);
4436 getpkt (&rs->buf, &rs->buf_size, 0);
4437
4438 /* If the target didn't like the packet, warn the user. Do not try
4439 to undo the user's settings, that would just be maddening. */
4440 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4441 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4442}
4443
be2a5f71
DJ
4444/* This type describes each known response to the qSupported
4445 packet. */
4446struct protocol_feature
4447{
4448 /* The name of this protocol feature. */
4449 const char *name;
4450
4451 /* The default for this protocol feature. */
4452 enum packet_support default_support;
4453
4454 /* The function to call when this feature is reported, or after
4455 qSupported processing if the feature is not supported.
4456 The first argument points to this structure. The second
4457 argument indicates whether the packet requested support be
4458 enabled, disabled, or probed (or the default, if this function
4459 is being called at the end of processing and this feature was
4460 not reported). The third argument may be NULL; if not NULL, it
4461 is a NUL-terminated string taken from the packet following
4462 this feature's name and an equals sign. */
4463 void (*func) (const struct protocol_feature *, enum packet_support,
4464 const char *);
4465
4466 /* The corresponding packet for this feature. Only used if
4467 FUNC is remote_supported_packet. */
4468 int packet;
4469};
4470
be2a5f71
DJ
4471static void
4472remote_supported_packet (const struct protocol_feature *feature,
4473 enum packet_support support,
4474 const char *argument)
4475{
4476 if (argument)
4477 {
4478 warning (_("Remote qSupported response supplied an unexpected value for"
4479 " \"%s\"."), feature->name);
4480 return;
4481 }
4482
4082afcc 4483 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4484}
be2a5f71
DJ
4485
4486static void
4487remote_packet_size (const struct protocol_feature *feature,
4488 enum packet_support support, const char *value)
4489{
4490 struct remote_state *rs = get_remote_state ();
4491
4492 int packet_size;
4493 char *value_end;
4494
4495 if (support != PACKET_ENABLE)
4496 return;
4497
4498 if (value == NULL || *value == '\0')
4499 {
4500 warning (_("Remote target reported \"%s\" without a size."),
4501 feature->name);
4502 return;
4503 }
4504
4505 errno = 0;
4506 packet_size = strtol (value, &value_end, 16);
4507 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4508 {
4509 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4510 feature->name, value);
4511 return;
4512 }
4513
be2a5f71
DJ
4514 /* Record the new maximum packet size. */
4515 rs->explicit_packet_size = packet_size;
4516}
4517
dc473cfb 4518static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4519 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4520 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4521 PACKET_qXfer_auxv },
c78fa86a
GB
4522 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4523 PACKET_qXfer_exec_file },
23181151
DJ
4524 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4525 PACKET_qXfer_features },
cfa9d6d9
DJ
4526 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4527 PACKET_qXfer_libraries },
2268b414
JK
4528 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4529 PACKET_qXfer_libraries_svr4 },
ced63ec0 4530 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4531 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4532 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4533 PACKET_qXfer_memory_map },
4de6483e
UW
4534 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4535 PACKET_qXfer_spu_read },
4536 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4537 PACKET_qXfer_spu_write },
07e059b5
VP
4538 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4539 PACKET_qXfer_osdata },
dc146f7c
VP
4540 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4541 PACKET_qXfer_threads },
b3b9301e
PA
4542 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4543 PACKET_qXfer_traceframe_info },
89be2091
DJ
4544 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4545 PACKET_QPassSignals },
82075af2
JS
4546 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4547 PACKET_QCatchSyscalls },
9b224c5e
PA
4548 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4549 PACKET_QProgramSignals },
a6f3e723
SL
4550 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4551 PACKET_QStartNoAckMode },
4082afcc
PA
4552 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4553 PACKET_multiprocess_feature },
4554 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4555 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4556 PACKET_qXfer_siginfo_read },
4557 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4558 PACKET_qXfer_siginfo_write },
4082afcc 4559 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4560 PACKET_ConditionalTracepoints },
4082afcc 4561 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4562 PACKET_ConditionalBreakpoints },
4082afcc 4563 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4564 PACKET_BreakpointCommands },
4082afcc 4565 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4566 PACKET_FastTracepoints },
4082afcc 4567 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4568 PACKET_StaticTracepoints },
4082afcc 4569 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4570 PACKET_InstallInTrace},
4082afcc
PA
4571 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4572 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4573 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4574 PACKET_bc },
4575 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4576 PACKET_bs },
409873ef
SS
4577 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4578 PACKET_TracepointSource },
d914c394
SS
4579 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4580 PACKET_QAllow },
4082afcc
PA
4581 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4582 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4583 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4584 PACKET_qXfer_fdpic },
169081d0
TG
4585 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4586 PACKET_qXfer_uib },
03583c20
UW
4587 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4588 PACKET_QDisableRandomization },
d1feda86 4589 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4590 { "QTBuffer:size", PACKET_DISABLE,
4591 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4592 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4593 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4594 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4595 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4596 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4597 PACKET_qXfer_btrace },
4598 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4599 PACKET_qXfer_btrace_conf },
4600 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4601 PACKET_Qbtrace_conf_bts_size },
4602 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4603 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4604 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4605 PACKET_fork_event_feature },
4606 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4607 PACKET_vfork_event_feature },
94585166
DB
4608 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4609 PACKET_exec_event_feature },
b20a6524 4610 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4611 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4612 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4613 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4614 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4615};
4616
c8d5aac9
L
4617static char *remote_support_xml;
4618
4619/* Register string appended to "xmlRegisters=" in qSupported query. */
4620
4621void
6e39997a 4622register_remote_support_xml (const char *xml)
c8d5aac9
L
4623{
4624#if defined(HAVE_LIBEXPAT)
4625 if (remote_support_xml == NULL)
c4f7c687 4626 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4627 else
4628 {
4629 char *copy = xstrdup (remote_support_xml + 13);
4630 char *p = strtok (copy, ",");
4631
4632 do
4633 {
4634 if (strcmp (p, xml) == 0)
4635 {
4636 /* already there */
4637 xfree (copy);
4638 return;
4639 }
4640 }
4641 while ((p = strtok (NULL, ",")) != NULL);
4642 xfree (copy);
4643
94b0dee1
PA
4644 remote_support_xml = reconcat (remote_support_xml,
4645 remote_support_xml, ",", xml,
4646 (char *) NULL);
c8d5aac9
L
4647 }
4648#endif
4649}
4650
4651static char *
4652remote_query_supported_append (char *msg, const char *append)
4653{
4654 if (msg)
94b0dee1 4655 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4656 else
4657 return xstrdup (append);
4658}
4659
be2a5f71
DJ
4660static void
4661remote_query_supported (void)
4662{
4663 struct remote_state *rs = get_remote_state ();
4664 char *next;
4665 int i;
4666 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4667
4668 /* The packet support flags are handled differently for this packet
4669 than for most others. We treat an error, a disabled packet, and
4670 an empty response identically: any features which must be reported
4671 to be used will be automatically disabled. An empty buffer
4672 accomplishes this, since that is also the representation for a list
4673 containing no features. */
4674
4675 rs->buf[0] = 0;
4082afcc 4676 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4677 {
c8d5aac9 4678 char *q = NULL;
94b0dee1 4679 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4680
73b8c1fd
PA
4681 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4682 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4683
f7e6eed5
PA
4684 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4685 q = remote_query_supported_append (q, "swbreak+");
4686 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4687 q = remote_query_supported_append (q, "hwbreak+");
4688
dde08ee1
PA
4689 q = remote_query_supported_append (q, "qRelocInsn+");
4690
8020350c
DB
4691 if (packet_set_cmd_state (PACKET_fork_event_feature)
4692 != AUTO_BOOLEAN_FALSE)
4693 q = remote_query_supported_append (q, "fork-events+");
4694 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4695 != AUTO_BOOLEAN_FALSE)
4696 q = remote_query_supported_append (q, "vfork-events+");
4697 if (packet_set_cmd_state (PACKET_exec_event_feature)
4698 != AUTO_BOOLEAN_FALSE)
4699 q = remote_query_supported_append (q, "exec-events+");
89245bc0 4700
750ce8d1
YQ
4701 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4702 q = remote_query_supported_append (q, "vContSupported+");
4703
65706a29
PA
4704 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4705 q = remote_query_supported_append (q, "QThreadEvents+");
4706
f2faf941
PA
4707 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4708 q = remote_query_supported_append (q, "no-resumed+");
4709
b35d5edb
PA
4710 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4711 the qSupported:xmlRegisters=i386 handling. */
4712 if (remote_support_xml != NULL)
4713 q = remote_query_supported_append (q, remote_support_xml);
4714
dde08ee1
PA
4715 q = reconcat (q, "qSupported:", q, (char *) NULL);
4716 putpkt (q);
82f73884 4717
94b0dee1
PA
4718 do_cleanups (old_chain);
4719
be2a5f71
DJ
4720 getpkt (&rs->buf, &rs->buf_size, 0);
4721
4722 /* If an error occured, warn, but do not return - just reset the
4723 buffer to empty and go on to disable features. */
4724 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4725 == PACKET_ERROR)
4726 {
4727 warning (_("Remote failure reply: %s"), rs->buf);
4728 rs->buf[0] = 0;
4729 }
4730 }
4731
4732 memset (seen, 0, sizeof (seen));
4733
4734 next = rs->buf;
4735 while (*next)
4736 {
4737 enum packet_support is_supported;
4738 char *p, *end, *name_end, *value;
4739
4740 /* First separate out this item from the rest of the packet. If
4741 there's another item after this, we overwrite the separator
4742 (terminated strings are much easier to work with). */
4743 p = next;
4744 end = strchr (p, ';');
4745 if (end == NULL)
4746 {
4747 end = p + strlen (p);
4748 next = end;
4749 }
4750 else
4751 {
89be2091
DJ
4752 *end = '\0';
4753 next = end + 1;
4754
be2a5f71
DJ
4755 if (end == p)
4756 {
4757 warning (_("empty item in \"qSupported\" response"));
4758 continue;
4759 }
be2a5f71
DJ
4760 }
4761
4762 name_end = strchr (p, '=');
4763 if (name_end)
4764 {
4765 /* This is a name=value entry. */
4766 is_supported = PACKET_ENABLE;
4767 value = name_end + 1;
4768 *name_end = '\0';
4769 }
4770 else
4771 {
4772 value = NULL;
4773 switch (end[-1])
4774 {
4775 case '+':
4776 is_supported = PACKET_ENABLE;
4777 break;
4778
4779 case '-':
4780 is_supported = PACKET_DISABLE;
4781 break;
4782
4783 case '?':
4784 is_supported = PACKET_SUPPORT_UNKNOWN;
4785 break;
4786
4787 default:
3e43a32a
MS
4788 warning (_("unrecognized item \"%s\" "
4789 "in \"qSupported\" response"), p);
be2a5f71
DJ
4790 continue;
4791 }
4792 end[-1] = '\0';
4793 }
4794
4795 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4796 if (strcmp (remote_protocol_features[i].name, p) == 0)
4797 {
4798 const struct protocol_feature *feature;
4799
4800 seen[i] = 1;
4801 feature = &remote_protocol_features[i];
4802 feature->func (feature, is_supported, value);
4803 break;
4804 }
4805 }
4806
4807 /* If we increased the packet size, make sure to increase the global
4808 buffer size also. We delay this until after parsing the entire
4809 qSupported packet, because this is the same buffer we were
4810 parsing. */
4811 if (rs->buf_size < rs->explicit_packet_size)
4812 {
4813 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4814 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4815 }
4816
4817 /* Handle the defaults for unmentioned features. */
4818 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4819 if (!seen[i])
4820 {
4821 const struct protocol_feature *feature;
4822
4823 feature = &remote_protocol_features[i];
4824 feature->func (feature, feature->default_support, NULL);
4825 }
4826}
4827
78a095c3
JK
4828/* Remove any of the remote.c targets from target stack. Upper targets depend
4829 on it so remove them first. */
4830
4831static void
4832remote_unpush_target (void)
4833{
915ef8b1 4834 pop_all_targets_at_and_above (process_stratum);
78a095c3 4835}
be2a5f71 4836
c906108c 4837static void
014f9477 4838remote_open_1 (const char *name, int from_tty,
3e43a32a 4839 struct target_ops *target, int extended_p)
c906108c 4840{
d01949b6 4841 struct remote_state *rs = get_remote_state ();
a6f3e723 4842
c906108c 4843 if (name == 0)
8a3fe4f8 4844 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4845 "serial device is attached to the remote system\n"
8a3fe4f8 4846 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4847
23860348 4848 /* See FIXME above. */
c6ebd6cf 4849 if (!target_async_permitted)
92d1e331 4850 wait_forever_enabled_p = 1;
6426a772 4851
2d717e4f 4852 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4853 Ask this question first, before target_preopen has a chance to kill
4854 anything. */
5d93a237 4855 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4856 {
78a095c3
JK
4857 if (from_tty
4858 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4859 error (_("Still connected."));
4860 }
4861
78a095c3 4862 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4863 target_preopen (from_tty);
4864
89be2091 4865 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4866 xfree (rs->last_pass_packet);
4867 rs->last_pass_packet = NULL;
89be2091 4868
9b224c5e
PA
4869 /* Make sure we send the program signals list the next time we
4870 resume. */
5e4a05c4
TT
4871 xfree (rs->last_program_signals_packet);
4872 rs->last_program_signals_packet = NULL;
9b224c5e 4873
ad9a8f3f 4874 remote_fileio_reset ();
1dd41f16
NS
4875 reopen_exec_file ();
4876 reread_symbols ();
4877
5d93a237
TT
4878 rs->remote_desc = remote_serial_open (name);
4879 if (!rs->remote_desc)
c906108c
SS
4880 perror_with_name (name);
4881
4882 if (baud_rate != -1)
4883 {
5d93a237 4884 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4885 {
9b74d5d3
KB
4886 /* The requested speed could not be set. Error out to
4887 top level after closing remote_desc. Take care to
4888 set remote_desc to NULL to avoid closing remote_desc
4889 more than once. */
5d93a237
TT
4890 serial_close (rs->remote_desc);
4891 rs->remote_desc = NULL;
c906108c
SS
4892 perror_with_name (name);
4893 }
4894 }
4895
236af5e3 4896 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4897 serial_raw (rs->remote_desc);
c906108c
SS
4898
4899 /* If there is something sitting in the buffer we might take it as a
4900 response to a command, which would be bad. */
5d93a237 4901 serial_flush_input (rs->remote_desc);
c906108c
SS
4902
4903 if (from_tty)
4904 {
4905 puts_filtered ("Remote debugging using ");
4906 puts_filtered (name);
4907 puts_filtered ("\n");
4908 }
23860348 4909 push_target (target); /* Switch to using remote target now. */
c906108c 4910
74531fed
PA
4911 /* Register extra event sources in the event loop. */
4912 remote_async_inferior_event_token
4913 = create_async_event_handler (remote_async_inferior_event_handler,
4914 NULL);
5965e028 4915 rs->notif_state = remote_notif_state_allocate ();
74531fed 4916
be2a5f71
DJ
4917 /* Reset the target state; these things will be queried either by
4918 remote_query_supported or as they are needed. */
ca4f7f8b 4919 reset_all_packet_configs_support ();
74531fed 4920 rs->cached_wait_status = 0;
be2a5f71 4921 rs->explicit_packet_size = 0;
a6f3e723 4922 rs->noack_mode = 0;
82f73884 4923 rs->extended = extended_p;
e24a49d8 4924 rs->waiting_for_stop_reply = 0;
3a29589a 4925 rs->ctrlc_pending_p = 0;
802188a7 4926
47f8a51d
TT
4927 rs->general_thread = not_sent_ptid;
4928 rs->continue_thread = not_sent_ptid;
262e1174 4929 rs->remote_traceframe_number = -1;
c906108c 4930
9d1f7ab2 4931 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4932 rs->use_threadinfo_query = 1;
4933 rs->use_threadextra_query = 1;
9d1f7ab2 4934
80152258
PA
4935 readahead_cache_invalidate ();
4936
c6ebd6cf 4937 if (target_async_permitted)
92d1e331 4938 {
23860348 4939 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4940 remote_async_terminal_ours_p = 1;
4941
4942 /* FIXME: cagney/1999-09-23: During the initial connection it is
4943 assumed that the target is already ready and able to respond to
0df8b418 4944 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4945 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4946 around this. Eventually a mechanism that allows
92d1e331 4947 wait_for_inferior() to expect/get timeouts will be
23860348 4948 implemented. */
92d1e331
DJ
4949 wait_forever_enabled_p = 0;
4950 }
4951
23860348 4952 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4953 no_shared_libraries (NULL, 0);
f78f6cf1 4954
74531fed
PA
4955 /* Start afresh. */
4956 init_thread_list ();
4957
36918e70 4958 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4959 target (we'd otherwise be in an inconsistent state) and then
4960 propogate the error on up the exception chain. This ensures that
4961 the caller doesn't stumble along blindly assuming that the
4962 function succeeded. The CLI doesn't have this problem but other
4963 UI's, such as MI do.
36918e70
AC
4964
4965 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4966 this function should return an error indication letting the
ce2826aa 4967 caller restore the previous state. Unfortunately the command
36918e70
AC
4968 ``target remote'' is directly wired to this function making that
4969 impossible. On a positive note, the CLI side of this problem has
4970 been fixed - the function set_cmd_context() makes it possible for
4971 all the ``target ....'' commands to share a common callback
4972 function. See cli-dump.c. */
109c3e39 4973 {
2d717e4f 4974
492d29ea 4975 TRY
04bd08de
TT
4976 {
4977 remote_start_remote (from_tty, target, extended_p);
4978 }
492d29ea 4979 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4980 {
c8d104ad
PA
4981 /* Pop the partially set up target - unless something else did
4982 already before throwing the exception. */
5d93a237 4983 if (rs->remote_desc != NULL)
78a095c3 4984 remote_unpush_target ();
c6ebd6cf 4985 if (target_async_permitted)
109c3e39
AC
4986 wait_forever_enabled_p = 1;
4987 throw_exception (ex);
4988 }
492d29ea 4989 END_CATCH
109c3e39 4990 }
c906108c 4991
f4abbc16
MM
4992 remote_btrace_reset ();
4993
c6ebd6cf 4994 if (target_async_permitted)
92d1e331 4995 wait_forever_enabled_p = 1;
43ff13b4
JM
4996}
4997
de0d863e
DB
4998/* Detach the specified process. */
4999
5000static void
5001remote_detach_pid (int pid)
5002{
5003 struct remote_state *rs = get_remote_state ();
5004
5005 if (remote_multi_process_p (rs))
5006 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5007 else
5008 strcpy (rs->buf, "D");
5009
5010 putpkt (rs->buf);
5011 getpkt (&rs->buf, &rs->buf_size, 0);
5012
5013 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5014 ;
5015 else if (rs->buf[0] == '\0')
5016 error (_("Remote doesn't know how to detach"));
5017 else
5018 error (_("Can't detach process."));
5019}
5020
5021/* This detaches a program to which we previously attached, using
5022 inferior_ptid to identify the process. After this is done, GDB
5023 can be used to debug some other program. We better not have left
5024 any breakpoints in the target program or it'll die when it hits
5025 one. */
c906108c
SS
5026
5027static void
de0d863e 5028remote_detach_1 (const char *args, int from_tty)
c906108c 5029{
82f73884 5030 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5031 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5032 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5033 int is_fork_parent;
c906108c
SS
5034
5035 if (args)
8a3fe4f8 5036 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 5037
2d717e4f
DJ
5038 if (!target_has_execution)
5039 error (_("No process to detach from."));
5040
7cee1e54
PA
5041 if (from_tty)
5042 {
5043 char *exec_file = get_exec_file (0);
5044 if (exec_file == NULL)
5045 exec_file = "";
5046 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
5047 target_pid_to_str (pid_to_ptid (pid)));
5048 gdb_flush (gdb_stdout);
5049 }
5050
c906108c 5051 /* Tell the remote target to detach. */
de0d863e 5052 remote_detach_pid (pid);
82f73884 5053
8020350c
DB
5054 /* Exit only if this is the only active inferior. */
5055 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5056 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5057
de0d863e
DB
5058 /* Check to see if we are detaching a fork parent. Note that if we
5059 are detaching a fork child, tp == NULL. */
5060 is_fork_parent = (tp != NULL
5061 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5062
5063 /* If doing detach-on-fork, we don't mourn, because that will delete
5064 breakpoints that should be available for the followed inferior. */
5065 if (!is_fork_parent)
5066 target_mourn_inferior ();
5067 else
5068 {
5069 inferior_ptid = null_ptid;
5070 detach_inferior (pid);
5071 }
2d717e4f
DJ
5072}
5073
5074static void
52554a0e 5075remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5076{
de0d863e 5077 remote_detach_1 (args, from_tty);
2d717e4f
DJ
5078}
5079
5080static void
52554a0e 5081extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5082{
de0d863e
DB
5083 remote_detach_1 (args, from_tty);
5084}
5085
5086/* Target follow-fork function for remote targets. On entry, and
5087 at return, the current inferior is the fork parent.
5088
5089 Note that although this is currently only used for extended-remote,
5090 it is named remote_follow_fork in anticipation of using it for the
5091 remote target as well. */
5092
5093static int
5094remote_follow_fork (struct target_ops *ops, int follow_child,
5095 int detach_fork)
5096{
5097 struct remote_state *rs = get_remote_state ();
c269dbdb 5098 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5099
c269dbdb
DB
5100 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5101 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5102 {
5103 /* When following the parent and detaching the child, we detach
5104 the child here. For the case of following the child and
5105 detaching the parent, the detach is done in the target-
5106 independent follow fork code in infrun.c. We can't use
5107 target_detach when detaching an unfollowed child because
5108 the client side doesn't know anything about the child. */
5109 if (detach_fork && !follow_child)
5110 {
5111 /* Detach the fork child. */
5112 ptid_t child_ptid;
5113 pid_t child_pid;
5114
5115 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5116 child_pid = ptid_get_pid (child_ptid);
5117
5118 remote_detach_pid (child_pid);
5119 detach_inferior (child_pid);
5120 }
5121 }
5122 return 0;
c906108c
SS
5123}
5124
94585166
DB
5125/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5126 in the program space of the new inferior. On entry and at return the
5127 current inferior is the exec'ing inferior. INF is the new exec'd
5128 inferior, which may be the same as the exec'ing inferior unless
5129 follow-exec-mode is "new". */
5130
5131static void
5132remote_follow_exec (struct target_ops *ops,
5133 struct inferior *inf, char *execd_pathname)
5134{
5135 /* We know that this is a target file name, so if it has the "target:"
5136 prefix we strip it off before saving it in the program space. */
5137 if (is_target_filename (execd_pathname))
5138 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5139
5140 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5141}
5142
6ad8ae5c
DJ
5143/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5144
43ff13b4 5145static void
fee354ee 5146remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5147{
43ff13b4 5148 if (args)
2d717e4f 5149 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5150
8020350c
DB
5151 /* Make sure we unpush even the extended remote targets. Calling
5152 target_mourn_inferior won't unpush, and remote_mourn won't
5153 unpush if there is more than one inferior left. */
5154 unpush_target (target);
5155 generic_mourn_inferior ();
2d717e4f 5156
43ff13b4
JM
5157 if (from_tty)
5158 puts_filtered ("Ending remote debugging.\n");
5159}
5160
2d717e4f
DJ
5161/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5162 be chatty about it. */
5163
5164static void
20f796c9
GB
5165extended_remote_attach (struct target_ops *target, const char *args,
5166 int from_tty)
2d717e4f
DJ
5167{
5168 struct remote_state *rs = get_remote_state ();
be86555c 5169 int pid;
96ef3384 5170 char *wait_status = NULL;
2d717e4f 5171
74164c56 5172 pid = parse_pid_to_attach (args);
2d717e4f 5173
74164c56
JK
5174 /* Remote PID can be freely equal to getpid, do not check it here the same
5175 way as in other targets. */
2d717e4f 5176
4082afcc 5177 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5178 error (_("This target does not support attaching to a process"));
5179
7cee1e54
PA
5180 if (from_tty)
5181 {
5182 char *exec_file = get_exec_file (0);
5183
5184 if (exec_file)
5185 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5186 target_pid_to_str (pid_to_ptid (pid)));
5187 else
5188 printf_unfiltered (_("Attaching to %s\n"),
5189 target_pid_to_str (pid_to_ptid (pid)));
5190
5191 gdb_flush (gdb_stdout);
5192 }
5193
bba74b36 5194 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5195 putpkt (rs->buf);
5196 getpkt (&rs->buf, &rs->buf_size, 0);
5197
4082afcc
PA
5198 switch (packet_ok (rs->buf,
5199 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5200 {
4082afcc 5201 case PACKET_OK:
6efcd9a8 5202 if (!target_is_non_stop_p ())
74531fed
PA
5203 {
5204 /* Save the reply for later. */
224c3ddb 5205 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5206 strcpy (wait_status, rs->buf);
5207 }
5208 else if (strcmp (rs->buf, "OK") != 0)
5209 error (_("Attaching to %s failed with: %s"),
5210 target_pid_to_str (pid_to_ptid (pid)),
5211 rs->buf);
4082afcc
PA
5212 break;
5213 case PACKET_UNKNOWN:
5214 error (_("This target does not support attaching to a process"));
5215 default:
5216 error (_("Attaching to %s failed"),
5217 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5218 }
2d717e4f 5219
1b6e6f5c 5220 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5221
2d717e4f 5222 inferior_ptid = pid_to_ptid (pid);
79d7f229 5223
6efcd9a8 5224 if (target_is_non_stop_p ())
bad34192
PA
5225 {
5226 struct thread_info *thread;
79d7f229 5227
bad34192 5228 /* Get list of threads. */
e8032dde 5229 remote_update_thread_list (target);
82f73884 5230
bad34192
PA
5231 thread = first_thread_of_process (pid);
5232 if (thread)
5233 inferior_ptid = thread->ptid;
5234 else
5235 inferior_ptid = pid_to_ptid (pid);
5236
5237 /* Invalidate our notion of the remote current thread. */
47f8a51d 5238 record_currthread (rs, minus_one_ptid);
bad34192 5239 }
74531fed 5240 else
bad34192
PA
5241 {
5242 /* Now, if we have thread information, update inferior_ptid. */
5243 inferior_ptid = remote_current_thread (inferior_ptid);
5244
5245 /* Add the main thread to the thread list. */
5246 add_thread_silent (inferior_ptid);
5247 }
c0a2216e 5248
96ef3384
UW
5249 /* Next, if the target can specify a description, read it. We do
5250 this before anything involving memory or registers. */
5251 target_find_description ();
5252
6efcd9a8 5253 if (!target_is_non_stop_p ())
74531fed
PA
5254 {
5255 /* Use the previously fetched status. */
5256 gdb_assert (wait_status != NULL);
5257
5258 if (target_can_async_p ())
5259 {
722247f1
YQ
5260 struct notif_event *reply
5261 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5262
722247f1 5263 push_stop_reply ((struct stop_reply *) reply);
74531fed 5264
6a3753b3 5265 target_async (1);
74531fed
PA
5266 }
5267 else
5268 {
5269 gdb_assert (wait_status != NULL);
5270 strcpy (rs->buf, wait_status);
5271 rs->cached_wait_status = 1;
5272 }
5273 }
5274 else
5275 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5276}
5277
b9c1d481
AS
5278/* Implementation of the to_post_attach method. */
5279
5280static void
5281extended_remote_post_attach (struct target_ops *ops, int pid)
5282{
6efcd9a8
PA
5283 /* Get text, data & bss offsets. */
5284 get_offsets ();
5285
b9c1d481
AS
5286 /* In certain cases GDB might not have had the chance to start
5287 symbol lookup up until now. This could happen if the debugged
5288 binary is not using shared libraries, the vsyscall page is not
5289 present (on Linux) and the binary itself hadn't changed since the
5290 debugging process was started. */
5291 if (symfile_objfile != NULL)
5292 remote_check_symbols();
5293}
5294
c906108c 5295\f
506fb367
DJ
5296/* Check for the availability of vCont. This function should also check
5297 the response. */
c906108c
SS
5298
5299static void
6d820c5c 5300remote_vcont_probe (struct remote_state *rs)
c906108c 5301{
2e9f7625 5302 char *buf;
6d820c5c 5303
2e9f7625
DJ
5304 strcpy (rs->buf, "vCont?");
5305 putpkt (rs->buf);
6d820c5c 5306 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5307 buf = rs->buf;
c906108c 5308
506fb367 5309 /* Make sure that the features we assume are supported. */
61012eef 5310 if (startswith (buf, "vCont"))
506fb367
DJ
5311 {
5312 char *p = &buf[5];
750ce8d1 5313 int support_c, support_C;
506fb367 5314
750ce8d1
YQ
5315 rs->supports_vCont.s = 0;
5316 rs->supports_vCont.S = 0;
506fb367
DJ
5317 support_c = 0;
5318 support_C = 0;
d458bd84 5319 rs->supports_vCont.t = 0;
c1e36e3e 5320 rs->supports_vCont.r = 0;
506fb367
DJ
5321 while (p && *p == ';')
5322 {
5323 p++;
5324 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5325 rs->supports_vCont.s = 1;
506fb367 5326 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5327 rs->supports_vCont.S = 1;
506fb367
DJ
5328 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5329 support_c = 1;
5330 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5331 support_C = 1;
74531fed 5332 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5333 rs->supports_vCont.t = 1;
c1e36e3e
PA
5334 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5335 rs->supports_vCont.r = 1;
506fb367
DJ
5336
5337 p = strchr (p, ';');
5338 }
c906108c 5339
750ce8d1
YQ
5340 /* If c, and C are not all supported, we can't use vCont. Clearing
5341 BUF will make packet_ok disable the packet. */
5342 if (!support_c || !support_C)
506fb367
DJ
5343 buf[0] = 0;
5344 }
c906108c 5345
444abaca 5346 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5347}
c906108c 5348
0d8f58ca
PA
5349/* Helper function for building "vCont" resumptions. Write a
5350 resumption to P. ENDP points to one-passed-the-end of the buffer
5351 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5352 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5353 resumed thread should be single-stepped and/or signalled. If PTID
5354 equals minus_one_ptid, then all threads are resumed; if PTID
5355 represents a process, then all threads of the process are resumed;
5356 the thread to be stepped and/or signalled is given in the global
5357 INFERIOR_PTID. */
5358
5359static char *
5360append_resumption (char *p, char *endp,
2ea28649 5361 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5362{
5363 struct remote_state *rs = get_remote_state ();
5364
a493e3e2 5365 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5366 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5367 else if (step
5368 /* GDB is willing to range step. */
5369 && use_range_stepping
5370 /* Target supports range stepping. */
5371 && rs->supports_vCont.r
5372 /* We don't currently support range stepping multiple
5373 threads with a wildcard (though the protocol allows it,
5374 so stubs shouldn't make an active effort to forbid
5375 it). */
5376 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5377 {
5378 struct thread_info *tp;
5379
5380 if (ptid_equal (ptid, minus_one_ptid))
5381 {
5382 /* If we don't know about the target thread's tid, then
5383 we're resuming magic_null_ptid (see caller). */
5384 tp = find_thread_ptid (magic_null_ptid);
5385 }
5386 else
5387 tp = find_thread_ptid (ptid);
5388 gdb_assert (tp != NULL);
5389
5390 if (tp->control.may_range_step)
5391 {
5392 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5393
5394 p += xsnprintf (p, endp - p, ";r%s,%s",
5395 phex_nz (tp->control.step_range_start,
5396 addr_size),
5397 phex_nz (tp->control.step_range_end,
5398 addr_size));
5399 }
5400 else
5401 p += xsnprintf (p, endp - p, ";s");
5402 }
0d8f58ca
PA
5403 else if (step)
5404 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5405 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5406 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5407 else
5408 p += xsnprintf (p, endp - p, ";c");
5409
5410 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5411 {
5412 ptid_t nptid;
5413
5414 /* All (-1) threads of process. */
ba348170 5415 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5416
5417 p += xsnprintf (p, endp - p, ":");
5418 p = write_ptid (p, endp, nptid);
5419 }
5420 else if (!ptid_equal (ptid, minus_one_ptid))
5421 {
5422 p += xsnprintf (p, endp - p, ":");
5423 p = write_ptid (p, endp, ptid);
5424 }
5425
5426 return p;
5427}
5428
799a2abe
PA
5429/* Clear the thread's private info on resume. */
5430
5431static void
5432resume_clear_thread_private_info (struct thread_info *thread)
5433{
5434 if (thread->priv != NULL)
5435 {
5436 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5437 thread->priv->watch_data_address = 0;
5438 }
5439}
5440
e5ef252a
PA
5441/* Append a vCont continue-with-signal action for threads that have a
5442 non-zero stop signal. */
5443
5444static char *
5445append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5446{
5447 struct thread_info *thread;
5448
034f788c 5449 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5450 if (ptid_match (thread->ptid, ptid)
5451 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5452 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5453 {
5454 p = append_resumption (p, endp, thread->ptid,
5455 0, thread->suspend.stop_signal);
5456 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5457 resume_clear_thread_private_info (thread);
e5ef252a
PA
5458 }
5459
5460 return p;
5461}
5462
506fb367
DJ
5463/* Resume the remote inferior by using a "vCont" packet. The thread
5464 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5465 resumed thread should be single-stepped and/or signalled. If PTID
5466 equals minus_one_ptid, then all threads are resumed; the thread to
5467 be stepped and/or signalled is given in the global INFERIOR_PTID.
5468 This function returns non-zero iff it resumes the inferior.
44eaed12 5469
506fb367
DJ
5470 This function issues a strict subset of all possible vCont commands at the
5471 moment. */
44eaed12 5472
506fb367 5473static int
2ea28649 5474remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5475{
5476 struct remote_state *rs = get_remote_state ();
82f73884
PA
5477 char *p;
5478 char *endp;
44eaed12 5479
4082afcc 5480 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5481 remote_vcont_probe (rs);
44eaed12 5482
4082afcc 5483 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5484 return 0;
44eaed12 5485
82f73884
PA
5486 p = rs->buf;
5487 endp = rs->buf + get_remote_packet_size ();
5488
506fb367
DJ
5489 /* If we could generate a wider range of packets, we'd have to worry
5490 about overflowing BUF. Should there be a generic
5491 "multi-part-packet" packet? */
5492
0d8f58ca
PA
5493 p += xsnprintf (p, endp - p, "vCont");
5494
79d7f229 5495 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5496 {
79d7f229
PA
5497 /* MAGIC_NULL_PTID means that we don't have any active threads,
5498 so we don't have any TID numbers the inferior will
5499 understand. Make sure to only send forms that do not specify
5500 a TID. */
a9cbf802 5501 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5502 }
0d8f58ca 5503 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5504 {
0d8f58ca
PA
5505 /* Resume all threads (of all processes, or of a single
5506 process), with preference for INFERIOR_PTID. This assumes
5507 inferior_ptid belongs to the set of all threads we are about
5508 to resume. */
a493e3e2 5509 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5510 {
0d8f58ca
PA
5511 /* Step inferior_ptid, with or without signal. */
5512 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5513 }
0d8f58ca 5514
e5ef252a
PA
5515 /* Also pass down any pending signaled resumption for other
5516 threads not the current. */
5517 p = append_pending_thread_resumptions (p, endp, ptid);
5518
0d8f58ca 5519 /* And continue others without a signal. */
a493e3e2 5520 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5521 }
5522 else
506fb367
DJ
5523 {
5524 /* Scheduler locking; resume only PTID. */
a9cbf802 5525 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5526 }
c906108c 5527
82f73884
PA
5528 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5529 putpkt (rs->buf);
506fb367 5530
6efcd9a8 5531 if (target_is_non_stop_p ())
74531fed
PA
5532 {
5533 /* In non-stop, the stub replies to vCont with "OK". The stop
5534 reply will be reported asynchronously by means of a `%Stop'
5535 notification. */
5536 getpkt (&rs->buf, &rs->buf_size, 0);
5537 if (strcmp (rs->buf, "OK") != 0)
5538 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5539 }
5540
506fb367 5541 return 1;
c906108c 5542}
43ff13b4 5543
506fb367
DJ
5544/* Tell the remote machine to resume. */
5545
43ff13b4 5546static void
28439f5e 5547remote_resume (struct target_ops *ops,
2ea28649 5548 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5549{
d01949b6 5550 struct remote_state *rs = get_remote_state ();
2e9f7625 5551 char *buf;
799a2abe 5552 struct thread_info *thread;
43ff13b4 5553
722247f1
YQ
5554 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5555 (explained in remote-notif.c:handle_notification) so
5556 remote_notif_process is not called. We need find a place where
5557 it is safe to start a 'vNotif' sequence. It is good to do it
5558 before resuming inferior, because inferior was stopped and no RSP
5559 traffic at that moment. */
6efcd9a8 5560 if (!target_is_non_stop_p ())
5965e028 5561 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5562
b73be471 5563 rs->last_sent_signal = siggnal;
280ceea3 5564 rs->last_sent_step = step;
43ff13b4 5565
506fb367 5566 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5567 /* No reverse support (yet) for vCont. */
5568 if (execution_direction != EXEC_REVERSE)
5569 if (remote_vcont_resume (ptid, step, siggnal))
5570 goto done;
506fb367 5571
79d7f229
PA
5572 /* All other supported resume packets do use Hc, so set the continue
5573 thread. */
5574 if (ptid_equal (ptid, minus_one_ptid))
5575 set_continue_thread (any_thread_ptid);
506fb367 5576 else
79d7f229 5577 set_continue_thread (ptid);
506fb367 5578
799a2abe
PA
5579 ALL_NON_EXITED_THREADS (thread)
5580 resume_clear_thread_private_info (thread);
5581
2e9f7625 5582 buf = rs->buf;
b2175913
MS
5583 if (execution_direction == EXEC_REVERSE)
5584 {
5585 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5586 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5587 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5588 siggnal);
40ab02ce 5589
4082afcc 5590 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5591 error (_("Remote reverse-step not supported."));
4082afcc 5592 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5593 error (_("Remote reverse-continue not supported."));
40ab02ce 5594
b2175913
MS
5595 strcpy (buf, step ? "bs" : "bc");
5596 }
a493e3e2 5597 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5598 {
5599 buf[0] = step ? 'S' : 'C';
c5aa993b 5600 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5601 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5602 buf[3] = '\0';
5603 }
5604 else
c5aa993b 5605 strcpy (buf, step ? "s" : "c");
506fb367 5606
44eaed12 5607 putpkt (buf);
43ff13b4 5608
75c99385 5609 done:
2acceee2 5610 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5611 with the event loop. NOTE: this is the one place where all the
5612 execution commands end up. We could alternatively do this in each
23860348 5613 of the execution commands in infcmd.c. */
2acceee2
JM
5614 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5615 into infcmd.c in order to allow inferior function calls to work
23860348 5616 NOT asynchronously. */
362646f5 5617 if (target_can_async_p ())
6a3753b3 5618 target_async (1);
e24a49d8
PA
5619
5620 /* We've just told the target to resume. The remote server will
5621 wait for the inferior to stop, and then send a stop reply. In
5622 the mean time, we can't start another command/query ourselves
74531fed
PA
5623 because the stub wouldn't be ready to process it. This applies
5624 only to the base all-stop protocol, however. In non-stop (which
5625 only supports vCont), the stub replies with an "OK", and is
5626 immediate able to process further serial input. */
6efcd9a8 5627 if (!target_is_non_stop_p ())
74531fed 5628 rs->waiting_for_stop_reply = 1;
43ff13b4 5629}
c906108c 5630\f
43ff13b4
JM
5631
5632/* Set up the signal handler for SIGINT, while the target is
23860348 5633 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5634static void
934b9bac 5635async_initialize_sigint_signal_handler (void)
43ff13b4 5636{
934b9bac 5637 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5638}
5639
23860348 5640/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5641static void
934b9bac 5642async_handle_remote_sigint (int sig)
43ff13b4 5643{
934b9bac 5644 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5645 /* Note we need to go through gdb_call_async_signal_handler in order
5646 to wake up the event loop on Windows. */
5647 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5648}
5649
5650/* Signal handler for SIGINT, installed after SIGINT has already been
5651 sent once. It will take effect the second time that the user sends
23860348 5652 a ^C. */
43ff13b4 5653static void
934b9bac 5654async_handle_remote_sigint_twice (int sig)
43ff13b4 5655{
934b9bac 5656 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5657 /* See note in async_handle_remote_sigint. */
5658 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5659}
5660
abc56d60
PA
5661/* Implementation of to_check_pending_interrupt. */
5662
5663static void
5664remote_check_pending_interrupt (struct target_ops *self)
5665{
5666 struct async_signal_handler *token = async_sigint_remote_twice_token;
5667
5668 if (async_signal_handler_is_marked (token))
5669 {
5670 clear_async_signal_handler (token);
5671 call_async_signal_handler (token);
5672 }
5673}
5674
6426a772 5675/* Perform the real interruption of the target execution, in response
23860348 5676 to a ^C. */
c5aa993b 5677static void
fba45db2 5678async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5679{
5680 if (remote_debug)
248fd3bf 5681 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5682
de979965 5683 target_interrupt (inferior_ptid);
43ff13b4
JM
5684}
5685
0df8b418 5686/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5687 up on the target alltogether. */
47e1ce27 5688static void
fba45db2 5689async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5690{
2df3850c 5691 if (remote_debug)
248fd3bf 5692 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5693
5694 interrupt_query ();
43ff13b4
JM
5695}
5696
5697/* Reinstall the usual SIGINT handlers, after the target has
23860348 5698 stopped. */
6426a772 5699static void
934b9bac 5700async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5701{
5702 signal (SIGINT, handle_sigint);
43ff13b4
JM
5703}
5704
c906108c
SS
5705/* Send ^C to target to halt it. Target will respond, and send us a
5706 packet. */
507f3c78 5707static void (*ofunc) (int);
c906108c 5708
bfedc46a
PA
5709/* The command line interface's interrupt routine. This function is installed
5710 as a signal handler for SIGINT. The first time a user requests an
5711 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5712 response from the target (it didn't stop when the user requested it),
23860348 5713 we ask the user if he'd like to detach from the target. */
bfedc46a 5714
c906108c 5715static void
934b9bac 5716sync_remote_interrupt (int signo)
c906108c 5717{
23860348 5718 /* If this doesn't work, try more severe steps. */
934b9bac 5719 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5720
934b9bac 5721 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5722}
5723
5724/* The user typed ^C twice. */
5725
5726static void
934b9bac 5727sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5728{
5729 signal (signo, ofunc);
934b9bac
JK
5730 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5731 signal (signo, sync_remote_interrupt);
c906108c 5732}
7a292a7a 5733
74531fed
PA
5734/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5735 thread, all threads of a remote process, or all threads of all
5736 processes. */
5737
5738static void
5739remote_stop_ns (ptid_t ptid)
5740{
5741 struct remote_state *rs = get_remote_state ();
5742 char *p = rs->buf;
5743 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5744
4082afcc 5745 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5746 remote_vcont_probe (rs);
5747
d458bd84 5748 if (!rs->supports_vCont.t)
74531fed
PA
5749 error (_("Remote server does not support stopping threads"));
5750
f91d3df5
PA
5751 if (ptid_equal (ptid, minus_one_ptid)
5752 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5753 p += xsnprintf (p, endp - p, "vCont;t");
5754 else
5755 {
5756 ptid_t nptid;
5757
74531fed
PA
5758 p += xsnprintf (p, endp - p, "vCont;t:");
5759
5760 if (ptid_is_pid (ptid))
5761 /* All (-1) threads of process. */
ba348170 5762 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5763 else
5764 {
5765 /* Small optimization: if we already have a stop reply for
5766 this thread, no use in telling the stub we want this
5767 stopped. */
5768 if (peek_stop_reply (ptid))
5769 return;
5770
5771 nptid = ptid;
5772 }
5773
a9cbf802 5774 write_ptid (p, endp, nptid);
74531fed
PA
5775 }
5776
5777 /* In non-stop, we get an immediate OK reply. The stop reply will
5778 come in asynchronously by notification. */
5779 putpkt (rs->buf);
5780 getpkt (&rs->buf, &rs->buf_size, 0);
5781 if (strcmp (rs->buf, "OK") != 0)
5782 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5783}
5784
bfedc46a
PA
5785/* All-stop version of target_interrupt. Sends a break or a ^C to
5786 interrupt the remote target. It is undefined which thread of which
5787 process reports the interrupt. */
74531fed
PA
5788
5789static void
de979965 5790remote_interrupt_as (void)
74531fed
PA
5791{
5792 struct remote_state *rs = get_remote_state ();
5793
3a29589a
DJ
5794 rs->ctrlc_pending_p = 1;
5795
74531fed
PA
5796 /* If the inferior is stopped already, but the core didn't know
5797 about it yet, just ignore the request. The cached wait status
5798 will be collected in remote_wait. */
5799 if (rs->cached_wait_status)
5800 return;
5801
9a7071a8
JB
5802 /* Send interrupt_sequence to remote target. */
5803 send_interrupt_sequence ();
74531fed
PA
5804}
5805
de979965
PA
5806/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5807 the remote target. It is undefined which thread of which process
5808 reports the interrupt. Returns true if the packet is supported by
5809 the server, false otherwise. */
5810
5811static int
5812remote_interrupt_ns (void)
5813{
5814 struct remote_state *rs = get_remote_state ();
5815 char *p = rs->buf;
5816 char *endp = rs->buf + get_remote_packet_size ();
5817
5818 xsnprintf (p, endp - p, "vCtrlC");
5819
5820 /* In non-stop, we get an immediate OK reply. The stop reply will
5821 come in asynchronously by notification. */
5822 putpkt (rs->buf);
5823 getpkt (&rs->buf, &rs->buf_size, 0);
5824
5825 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5826 {
5827 case PACKET_OK:
5828 break;
5829 case PACKET_UNKNOWN:
5830 return 0;
5831 case PACKET_ERROR:
5832 error (_("Interrupting target failed: %s"), rs->buf);
5833 }
5834
5835 return 1;
5836}
5837
bfedc46a 5838/* Implement the to_stop function for the remote targets. */
74531fed 5839
c906108c 5840static void
1eab8a48 5841remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5842{
7a292a7a 5843 if (remote_debug)
0f71a2f6 5844 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5845
6efcd9a8 5846 if (target_is_non_stop_p ())
74531fed 5847 remote_stop_ns (ptid);
c906108c 5848 else
bfedc46a
PA
5849 {
5850 /* We don't currently have a way to transparently pause the
5851 remote target in all-stop mode. Interrupt it instead. */
de979965 5852 remote_interrupt_as ();
bfedc46a
PA
5853 }
5854}
5855
5856/* Implement the to_interrupt function for the remote targets. */
5857
5858static void
5859remote_interrupt (struct target_ops *self, ptid_t ptid)
5860{
5861 if (remote_debug)
5862 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5863
de979965 5864 if (non_stop)
bfedc46a 5865 {
de979965 5866 /* In non-stop mode, we always stop with no signal instead. */
bfedc46a
PA
5867 remote_stop_ns (ptid);
5868 }
5869 else
de979965
PA
5870 {
5871 /* In all-stop, we emulate ^C-ing the remote target's
5872 terminal. */
5873 if (target_is_non_stop_p ())
5874 {
5875 if (!remote_interrupt_ns ())
5876 {
5877 /* No support for ^C-ing the remote target. Stop it
5878 (with no signal) instead. */
5879 remote_stop_ns (ptid);
5880 }
5881 }
5882 else
5883 remote_interrupt_as ();
5884 }
c906108c
SS
5885}
5886
5887/* Ask the user what to do when an interrupt is received. */
5888
5889static void
fba45db2 5890interrupt_query (void)
c906108c 5891{
abc56d60
PA
5892 struct remote_state *rs = get_remote_state ();
5893 struct cleanup *old_chain;
5894
5895 old_chain = make_cleanup_restore_target_terminal ();
c906108c
SS
5896 target_terminal_ours ();
5897
abc56d60 5898 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5899 {
abc56d60
PA
5900 if (query (_("The target is not responding to interrupt requests.\n"
5901 "Stop debugging it? ")))
74531fed 5902 {
78a095c3 5903 remote_unpush_target ();
abc56d60 5904 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5905 }
5906 }
abc56d60
PA
5907 else
5908 {
5909 if (query (_("Interrupted while waiting for the program.\n"
5910 "Give up waiting? ")))
5911 quit ();
5912 }
c906108c 5913
abc56d60 5914 do_cleanups (old_chain);
c906108c
SS
5915}
5916
6426a772
JM
5917/* Enable/disable target terminal ownership. Most targets can use
5918 terminal groups to control terminal ownership. Remote targets are
5919 different in that explicit transfer of ownership to/from GDB/target
23860348 5920 is required. */
6426a772
JM
5921
5922static void
d2f640d4 5923remote_terminal_inferior (struct target_ops *self)
6426a772 5924{
c6ebd6cf 5925 if (!target_async_permitted)
75c99385
PA
5926 /* Nothing to do. */
5927 return;
5928
d9d2d8b6
PA
5929 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5930 idempotent. The event-loop GDB talking to an asynchronous target
5931 with a synchronous command calls this function from both
5932 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5933 transfer the terminal to the target when it shouldn't this guard
5934 can go away. */
6426a772
JM
5935 if (!remote_async_terminal_ours_p)
5936 return;
5937 delete_file_handler (input_fd);
5938 remote_async_terminal_ours_p = 0;
934b9bac 5939 async_initialize_sigint_signal_handler ();
6426a772
JM
5940 /* NOTE: At this point we could also register our selves as the
5941 recipient of all input. Any characters typed could then be
23860348 5942 passed on down to the target. */
6426a772
JM
5943}
5944
5945static void
e3594fd1 5946remote_terminal_ours (struct target_ops *self)
6426a772 5947{
c6ebd6cf 5948 if (!target_async_permitted)
75c99385
PA
5949 /* Nothing to do. */
5950 return;
5951
5952 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5953 if (remote_async_terminal_ours_p)
5954 return;
934b9bac 5955 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5956 add_file_handler (input_fd, stdin_event_handler, 0);
5957 remote_async_terminal_ours_p = 1;
5958}
5959
176a6961 5960static void
917317f4 5961remote_console_output (char *msg)
c906108c
SS
5962{
5963 char *p;
5964
c5aa993b 5965 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5966 {
5967 char tb[2];
5968 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5969
c906108c
SS
5970 tb[0] = c;
5971 tb[1] = 0;
43ff13b4 5972 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5973 }
00db5b94
PA
5974 gdb_flush (gdb_stdtarg);
5975}
74531fed
PA
5976
5977typedef struct cached_reg
5978{
5979 int num;
5980 gdb_byte data[MAX_REGISTER_SIZE];
5981} cached_reg_t;
5982
5983DEF_VEC_O(cached_reg_t);
5984
722247f1 5985typedef struct stop_reply
74531fed 5986{
722247f1 5987 struct notif_event base;
74531fed 5988
722247f1 5989 /* The identifier of the thread about this event */
74531fed
PA
5990 ptid_t ptid;
5991
340e3c99 5992 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5993 connection, represented by a remote_state object, is closed,
5994 all the associated stop_reply events should be released. */
5995 struct remote_state *rs;
5996
74531fed
PA
5997 struct target_waitstatus ws;
5998
15148d6a
PA
5999 /* Expedited registers. This makes remote debugging a bit more
6000 efficient for those targets that provide critical registers as
6001 part of their normal status mechanism (as another roundtrip to
6002 fetch them is avoided). */
74531fed
PA
6003 VEC(cached_reg_t) *regcache;
6004
f7e6eed5
PA
6005 enum target_stop_reason stop_reason;
6006
74531fed
PA
6007 CORE_ADDR watch_data_address;
6008
dc146f7c 6009 int core;
722247f1 6010} *stop_reply_p;
a744cf53 6011
722247f1
YQ
6012DECLARE_QUEUE_P (stop_reply_p);
6013DEFINE_QUEUE_P (stop_reply_p);
6014/* The list of already fetched and acknowledged stop events. This
6015 queue is used for notification Stop, and other notifications
6016 don't need queue for their events, because the notification events
6017 of Stop can't be consumed immediately, so that events should be
6018 queued first, and be consumed by remote_wait_{ns,as} one per
6019 time. Other notifications can consume their events immediately,
6020 so queue is not needed for them. */
6021static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
6022
6023static void
6024stop_reply_xfree (struct stop_reply *r)
6025{
f48ff2a7 6026 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6027}
6028
221e1a37
PA
6029/* Return the length of the stop reply queue. */
6030
6031static int
6032stop_reply_queue_length (void)
6033{
6034 return QUEUE_length (stop_reply_p, stop_reply_queue);
6035}
6036
722247f1
YQ
6037static void
6038remote_notif_stop_parse (struct notif_client *self, char *buf,
6039 struct notif_event *event)
6040{
6041 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6042}
6043
6044static void
6045remote_notif_stop_ack (struct notif_client *self, char *buf,
6046 struct notif_event *event)
6047{
6048 struct stop_reply *stop_reply = (struct stop_reply *) event;
6049
6050 /* acknowledge */
6051 putpkt ((char *) self->ack_command);
6052
6053 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6054 /* We got an unknown stop reply. */
6055 error (_("Unknown stop reply"));
6056
6057 push_stop_reply (stop_reply);
6058}
6059
6060static int
6061remote_notif_stop_can_get_pending_events (struct notif_client *self)
6062{
6063 /* We can't get pending events in remote_notif_process for
6064 notification stop, and we have to do this in remote_wait_ns
6065 instead. If we fetch all queued events from stub, remote stub
6066 may exit and we have no chance to process them back in
6067 remote_wait_ns. */
6068 mark_async_event_handler (remote_async_inferior_event_token);
6069 return 0;
6070}
6071
6072static void
6073stop_reply_dtr (struct notif_event *event)
6074{
6075 struct stop_reply *r = (struct stop_reply *) event;
6076
6077 VEC_free (cached_reg_t, r->regcache);
6078}
6079
6080static struct notif_event *
6081remote_notif_stop_alloc_reply (void)
6082{
8d749320
SM
6083 /* We cast to a pointer to the "base class". */
6084 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6085
6086 r->dtr = stop_reply_dtr;
6087
6088 return r;
6089}
6090
6091/* A client of notification Stop. */
6092
6093struct notif_client notif_client_stop =
6094{
6095 "Stop",
6096 "vStopped",
6097 remote_notif_stop_parse,
6098 remote_notif_stop_ack,
6099 remote_notif_stop_can_get_pending_events,
6100 remote_notif_stop_alloc_reply,
f48ff2a7 6101 REMOTE_NOTIF_STOP,
722247f1
YQ
6102};
6103
6104/* A parameter to pass data in and out. */
6105
6106struct queue_iter_param
6107{
6108 void *input;
6109 struct stop_reply *output;
6110};
6111
cbb8991c
DB
6112/* Determine if THREAD is a pending fork parent thread. ARG contains
6113 the pid of the process that owns the threads we want to check, or
6114 -1 if we want to check all threads. */
6115
6116static int
6117is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6118 ptid_t thread_ptid)
6119{
6120 if (ws->kind == TARGET_WAITKIND_FORKED
6121 || ws->kind == TARGET_WAITKIND_VFORKED)
6122 {
6123 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6124 return 1;
6125 }
6126
6127 return 0;
6128}
6129
6130/* Check whether EVENT is a fork event, and if it is, remove the
6131 fork child from the context list passed in DATA. */
6132
6133static int
6134remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6135 QUEUE_ITER (stop_reply_p) *iter,
6136 stop_reply_p event,
6137 void *data)
6138{
19ba03f4
SM
6139 struct queue_iter_param *param = (struct queue_iter_param *) data;
6140 struct threads_listing_context *context
6141 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6142
6143 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6144 || event->ws.kind == TARGET_WAITKIND_VFORKED
6145 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6146 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6147
6148 return 1;
6149}
6150
6151/* If CONTEXT contains any fork child threads that have not been
6152 reported yet, remove them from the CONTEXT list. If such a
6153 thread exists it is because we are stopped at a fork catchpoint
6154 and have not yet called follow_fork, which will set up the
6155 host-side data structures for the new process. */
6156
6157static void
6158remove_new_fork_children (struct threads_listing_context *context)
6159{
6160 struct thread_info * thread;
6161 int pid = -1;
6162 struct notif_client *notif = &notif_client_stop;
6163 struct queue_iter_param param;
6164
6165 /* For any threads stopped at a fork event, remove the corresponding
6166 fork child threads from the CONTEXT list. */
6167 ALL_NON_EXITED_THREADS (thread)
6168 {
4041ed77
DB
6169 struct target_waitstatus *ws;
6170
6171 if (thread->suspend.waitstatus_pending_p)
6172 ws = &thread->suspend.waitstatus;
6173 else
6174 ws = &thread->pending_follow;
cbb8991c
DB
6175
6176 if (is_pending_fork_parent (ws, pid, thread->ptid))
6177 {
6178 threads_listing_context_remove (ws, context);
6179 }
6180 }
6181
6182 /* Check for any pending fork events (not reported or processed yet)
6183 in process PID and remove those fork child threads from the
6184 CONTEXT list as well. */
6185 remote_notif_get_pending_events (notif);
6186 param.input = context;
6187 param.output = NULL;
6188 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6189 remove_child_of_pending_fork, &param);
6190}
6191
f48ff2a7
YQ
6192/* Remove stop replies in the queue if its pid is equal to the given
6193 inferior's pid. */
722247f1
YQ
6194
6195static int
f48ff2a7
YQ
6196remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6197 QUEUE_ITER (stop_reply_p) *iter,
6198 stop_reply_p event,
6199 void *data)
722247f1 6200{
19ba03f4
SM
6201 struct queue_iter_param *param = (struct queue_iter_param *) data;
6202 struct inferior *inf = (struct inferior *) param->input;
722247f1 6203
f48ff2a7 6204 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6205 {
6206 stop_reply_xfree (event);
6207 QUEUE_remove_elem (stop_reply_p, q, iter);
6208 }
6209
6210 return 1;
6211}
6212
f48ff2a7 6213/* Discard all pending stop replies of inferior INF. */
c906108c 6214
74531fed 6215static void
5f4cf0bb 6216discard_pending_stop_replies (struct inferior *inf)
c906108c 6217{
722247f1 6218 struct queue_iter_param param;
f48ff2a7
YQ
6219 struct stop_reply *reply;
6220 struct remote_state *rs = get_remote_state ();
6221 struct remote_notif_state *rns = rs->notif_state;
6222
6223 /* This function can be notified when an inferior exists. When the
6224 target is not remote, the notification state is NULL. */
6225 if (rs->remote_desc == NULL)
6226 return;
6227
6228 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6229
74531fed 6230 /* Discard the in-flight notification. */
f48ff2a7 6231 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6232 {
722247f1 6233 stop_reply_xfree (reply);
f48ff2a7 6234 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6235 }
c906108c 6236
722247f1
YQ
6237 param.input = inf;
6238 param.output = NULL;
74531fed
PA
6239 /* Discard the stop replies we have already pulled with
6240 vStopped. */
722247f1 6241 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6242 remove_stop_reply_for_inferior, &param);
6243}
6244
bcc75809
YQ
6245/* If its remote state is equal to the given remote state,
6246 remove EVENT from the stop reply queue. */
6247
6248static int
6249remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6250 QUEUE_ITER (stop_reply_p) *iter,
6251 stop_reply_p event,
6252 void *data)
6253{
19ba03f4
SM
6254 struct queue_iter_param *param = (struct queue_iter_param *) data;
6255 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6256
6257 if (event->rs == rs)
6258 {
6259 stop_reply_xfree (event);
6260 QUEUE_remove_elem (stop_reply_p, q, iter);
6261 }
6262
6263 return 1;
6264}
6265
6266/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6267
6268static void
bcc75809 6269discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6270{
6271 struct queue_iter_param param;
6272
bcc75809 6273 param.input = rs;
f48ff2a7
YQ
6274 param.output = NULL;
6275 /* Discard the stop replies we have already pulled with
6276 vStopped. */
6277 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6278 remove_stop_reply_of_remote_state, &param);
722247f1 6279}
74531fed 6280
722247f1
YQ
6281/* A parameter to pass data in and out. */
6282
6283static int
6284remote_notif_remove_once_on_match (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 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6291
6292 if (ptid_match (event->ptid, *ptid))
6293 {
6294 param->output = event;
6295 QUEUE_remove_elem (stop_reply_p, q, iter);
6296 return 0;
c8e38a49 6297 }
722247f1
YQ
6298
6299 return 1;
74531fed 6300}
43ff13b4 6301
722247f1
YQ
6302/* Remove the first reply in 'stop_reply_queue' which matches
6303 PTID. */
2e9f7625 6304
722247f1
YQ
6305static struct stop_reply *
6306remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6307{
722247f1
YQ
6308 struct queue_iter_param param;
6309
6310 param.input = &ptid;
6311 param.output = NULL;
6312
6313 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6314 remote_notif_remove_once_on_match, &param);
6315 if (notif_debug)
6316 fprintf_unfiltered (gdb_stdlog,
6317 "notif: discard queued event: 'Stop' in %s\n",
6318 target_pid_to_str (ptid));
a744cf53 6319
722247f1 6320 return param.output;
74531fed 6321}
75c99385 6322
74531fed
PA
6323/* Look for a queued stop reply belonging to PTID. If one is found,
6324 remove it from the queue, and return it. Returns NULL if none is
6325 found. If there are still queued events left to process, tell the
6326 event loop to get back to target_wait soon. */
e24a49d8 6327
74531fed
PA
6328static struct stop_reply *
6329queued_stop_reply (ptid_t ptid)
6330{
722247f1 6331 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6332
722247f1 6333 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6334 /* There's still at least an event left. */
6335 mark_async_event_handler (remote_async_inferior_event_token);
6336
722247f1 6337 return r;
74531fed
PA
6338}
6339
6340/* Push a fully parsed stop reply in the stop reply queue. Since we
6341 know that we now have at least one queued event left to pass to the
6342 core side, tell the event loop to get back to target_wait soon. */
6343
6344static void
6345push_stop_reply (struct stop_reply *new_event)
6346{
722247f1 6347 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6348
722247f1
YQ
6349 if (notif_debug)
6350 fprintf_unfiltered (gdb_stdlog,
6351 "notif: push 'Stop' %s to queue %d\n",
6352 target_pid_to_str (new_event->ptid),
6353 QUEUE_length (stop_reply_p,
6354 stop_reply_queue));
74531fed
PA
6355
6356 mark_async_event_handler (remote_async_inferior_event_token);
6357}
6358
722247f1
YQ
6359static int
6360stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6361 QUEUE_ITER (stop_reply_p) *iter,
6362 struct stop_reply *event,
6363 void *data)
6364{
19ba03f4 6365 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6366
6367 return !(ptid_equal (*ptid, event->ptid)
6368 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6369}
6370
74531fed
PA
6371/* Returns true if we have a stop reply for PTID. */
6372
6373static int
6374peek_stop_reply (ptid_t ptid)
6375{
722247f1
YQ
6376 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6377 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6378}
6379
26d56a93
SL
6380/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6381 starting with P and ending with PEND matches PREFIX. */
6382
6383static int
6384strprefix (const char *p, const char *pend, const char *prefix)
6385{
6386 for ( ; p < pend; p++, prefix++)
6387 if (*p != *prefix)
6388 return 0;
6389 return *prefix == '\0';
6390}
6391
74531fed
PA
6392/* Parse the stop reply in BUF. Either the function succeeds, and the
6393 result is stored in EVENT, or throws an error. */
6394
6395static void
6396remote_parse_stop_reply (char *buf, struct stop_reply *event)
6397{
6398 struct remote_arch_state *rsa = get_remote_arch_state ();
6399 ULONGEST addr;
6400 char *p;
94585166 6401 int skipregs = 0;
74531fed
PA
6402
6403 event->ptid = null_ptid;
bcc75809 6404 event->rs = get_remote_state ();
74531fed
PA
6405 event->ws.kind = TARGET_WAITKIND_IGNORE;
6406 event->ws.value.integer = 0;
f7e6eed5 6407 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6408 event->regcache = NULL;
dc146f7c 6409 event->core = -1;
74531fed
PA
6410
6411 switch (buf[0])
6412 {
6413 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6414 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6415 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6416 ss = signal number
6417 n... = register number
6418 r... = register contents
6419 */
6420
6421 p = &buf[3]; /* after Txx */
6422 while (*p)
6423 {
6424 char *p1;
cea39f65 6425 int fieldsize;
43ff13b4 6426
1f10ba14
PA
6427 p1 = strchr (p, ':');
6428 if (p1 == NULL)
6429 error (_("Malformed packet(a) (missing colon): %s\n\
6430Packet: '%s'\n"),
6431 p, buf);
6432 if (p == p1)
6433 error (_("Malformed packet(a) (missing register number): %s\n\
6434Packet: '%s'\n"),
6435 p, buf);
3c3bea1c 6436
1f10ba14
PA
6437 /* Some "registers" are actually extended stop information.
6438 Note if you're adding a new entry here: GDB 7.9 and
6439 earlier assume that all register "numbers" that start
6440 with an hex digit are real register numbers. Make sure
6441 the server only sends such a packet if it knows the
6442 client understands it. */
c8e38a49 6443
26d56a93 6444 if (strprefix (p, p1, "thread"))
1f10ba14 6445 event->ptid = read_ptid (++p1, &p);
82075af2
JS
6446 else if (strprefix (p, p1, "syscall_entry"))
6447 {
6448 ULONGEST sysno;
6449
6450 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6451 p = unpack_varlen_hex (++p1, &sysno);
6452 event->ws.value.syscall_number = (int) sysno;
6453 }
6454 else if (strprefix (p, p1, "syscall_return"))
6455 {
6456 ULONGEST sysno;
6457
6458 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6459 p = unpack_varlen_hex (++p1, &sysno);
6460 event->ws.value.syscall_number = (int) sysno;
6461 }
26d56a93
SL
6462 else if (strprefix (p, p1, "watch")
6463 || strprefix (p, p1, "rwatch")
6464 || strprefix (p, p1, "awatch"))
cea39f65 6465 {
f7e6eed5 6466 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6467 p = unpack_varlen_hex (++p1, &addr);
6468 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6469 }
26d56a93 6470 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6471 {
6472 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6473
6474 /* Make sure the stub doesn't forget to indicate support
6475 with qSupported. */
6476 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6477 error (_("Unexpected swbreak stop reason"));
6478
6479 /* The value part is documented as "must be empty",
6480 though we ignore it, in case we ever decide to make
6481 use of it in a backward compatible way. */
8424cc97 6482 p = strchrnul (p1 + 1, ';');
f7e6eed5 6483 }
26d56a93 6484 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6485 {
6486 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6487
6488 /* Make sure the stub doesn't forget to indicate support
6489 with qSupported. */
6490 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6491 error (_("Unexpected hwbreak stop reason"));
6492
6493 /* See above. */
8424cc97 6494 p = strchrnul (p1 + 1, ';');
f7e6eed5 6495 }
26d56a93 6496 else if (strprefix (p, p1, "library"))
cea39f65 6497 {
1f10ba14 6498 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 6499 p = strchrnul (p1 + 1, ';');
1f10ba14 6500 }
26d56a93 6501 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6502 {
6503 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6504 /* p1 will indicate "begin" or "end", but it makes
6505 no difference for now, so ignore it. */
8424cc97 6506 p = strchrnul (p1 + 1, ';');
1f10ba14 6507 }
26d56a93 6508 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6509 {
6510 ULONGEST c;
a744cf53 6511
1f10ba14
PA
6512 p = unpack_varlen_hex (++p1, &c);
6513 event->core = c;
cea39f65 6514 }
26d56a93 6515 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6516 {
6517 event->ws.value.related_pid = read_ptid (++p1, &p);
6518 event->ws.kind = TARGET_WAITKIND_FORKED;
6519 }
26d56a93 6520 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6521 {
6522 event->ws.value.related_pid = read_ptid (++p1, &p);
6523 event->ws.kind = TARGET_WAITKIND_VFORKED;
6524 }
26d56a93 6525 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6526 {
6527 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 6528 p = strchrnul (p1 + 1, ';');
c269dbdb 6529 }
6ab24463 6530 else if (strprefix (p, p1, "exec"))
94585166
DB
6531 {
6532 ULONGEST ignored;
6533 char pathname[PATH_MAX];
6534 int pathlen;
6535
6536 /* Determine the length of the execd pathname. */
6537 p = unpack_varlen_hex (++p1, &ignored);
6538 pathlen = (p - p1) / 2;
6539
6540 /* Save the pathname for event reporting and for
6541 the next run command. */
6542 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6543 pathname[pathlen] = '\0';
6544
6545 /* This is freed during event handling. */
6546 event->ws.value.execd_pathname = xstrdup (pathname);
6547 event->ws.kind = TARGET_WAITKIND_EXECD;
6548
6549 /* Skip the registers included in this packet, since
6550 they may be for an architecture different from the
6551 one used by the original program. */
6552 skipregs = 1;
6553 }
65706a29
PA
6554 else if (strprefix (p, p1, "create"))
6555 {
6556 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 6557 p = strchrnul (p1 + 1, ';');
65706a29 6558 }
cea39f65
MS
6559 else
6560 {
1f10ba14
PA
6561 ULONGEST pnum;
6562 char *p_temp;
6563
94585166
DB
6564 if (skipregs)
6565 {
8424cc97 6566 p = strchrnul (p1 + 1, ';');
94585166
DB
6567 p++;
6568 continue;
6569 }
6570
1f10ba14
PA
6571 /* Maybe a real ``P'' register number. */
6572 p_temp = unpack_varlen_hex (p, &pnum);
6573 /* If the first invalid character is the colon, we got a
6574 register number. Otherwise, it's an unknown stop
6575 reason. */
6576 if (p_temp == p1)
6577 {
6578 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6579 cached_reg_t cached_reg;
43ff13b4 6580
1f10ba14
PA
6581 if (reg == NULL)
6582 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6583Packet: '%s'\n"),
1f10ba14 6584 hex_string (pnum), p, buf);
c8e38a49 6585
1f10ba14 6586 cached_reg.num = reg->regnum;
4100683b 6587
1f10ba14
PA
6588 p = p1 + 1;
6589 fieldsize = hex2bin (p, cached_reg.data,
6590 register_size (target_gdbarch (),
6591 reg->regnum));
6592 p += 2 * fieldsize;
6593 if (fieldsize < register_size (target_gdbarch (),
6594 reg->regnum))
6595 warning (_("Remote reply is too short: %s"), buf);
74531fed 6596
1f10ba14
PA
6597 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6598 }
6599 else
6600 {
6601 /* Not a number. Silently skip unknown optional
6602 info. */
8424cc97 6603 p = strchrnul (p1 + 1, ';');
1f10ba14 6604 }
cea39f65 6605 }
c8e38a49 6606
cea39f65
MS
6607 if (*p != ';')
6608 error (_("Remote register badly formatted: %s\nhere: %s"),
6609 buf, p);
6610 ++p;
6611 }
5b5596ff
PA
6612
6613 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6614 break;
6615
c8e38a49
PA
6616 /* fall through */
6617 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6618 {
6619 int sig;
6620
6621 event->ws.kind = TARGET_WAITKIND_STOPPED;
6622 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6623 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6624 event->ws.value.sig = (enum gdb_signal) sig;
6625 else
6626 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6627 }
c8e38a49 6628 break;
65706a29
PA
6629 case 'w': /* Thread exited. */
6630 {
6631 char *p;
6632 ULONGEST value;
6633
6634 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6635 p = unpack_varlen_hex (&buf[1], &value);
6636 event->ws.value.integer = value;
6637 if (*p != ';')
6638 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 6639 event->ptid = read_ptid (++p, NULL);
65706a29
PA
6640 break;
6641 }
c8e38a49
PA
6642 case 'W': /* Target exited. */
6643 case 'X':
6644 {
6645 char *p;
6646 int pid;
6647 ULONGEST value;
82f73884 6648
c8e38a49
PA
6649 /* GDB used to accept only 2 hex chars here. Stubs should
6650 only send more if they detect GDB supports multi-process
6651 support. */
6652 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6653
c8e38a49
PA
6654 if (buf[0] == 'W')
6655 {
6656 /* The remote process exited. */
74531fed
PA
6657 event->ws.kind = TARGET_WAITKIND_EXITED;
6658 event->ws.value.integer = value;
c8e38a49
PA
6659 }
6660 else
6661 {
6662 /* The remote process exited with a signal. */
74531fed 6663 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6664 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6665 event->ws.value.sig = (enum gdb_signal) value;
6666 else
6667 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6668 }
82f73884 6669
c8e38a49
PA
6670 /* If no process is specified, assume inferior_ptid. */
6671 pid = ptid_get_pid (inferior_ptid);
6672 if (*p == '\0')
6673 ;
6674 else if (*p == ';')
6675 {
6676 p++;
6677
0b24eb2d 6678 if (*p == '\0')
82f73884 6679 ;
61012eef 6680 else if (startswith (p, "process:"))
82f73884 6681 {
c8e38a49 6682 ULONGEST upid;
a744cf53 6683
c8e38a49
PA
6684 p += sizeof ("process:") - 1;
6685 unpack_varlen_hex (p, &upid);
6686 pid = upid;
82f73884
PA
6687 }
6688 else
6689 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6690 }
c8e38a49
PA
6691 else
6692 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6693 event->ptid = pid_to_ptid (pid);
6694 }
6695 break;
f2faf941
PA
6696 case 'N':
6697 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6698 event->ptid = minus_one_ptid;
6699 break;
74531fed
PA
6700 }
6701
6efcd9a8 6702 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
6703 error (_("No process or thread specified in stop reply: %s"), buf);
6704}
6705
722247f1
YQ
6706/* When the stub wants to tell GDB about a new notification reply, it
6707 sends a notification (%Stop, for example). Those can come it at
6708 any time, hence, we have to make sure that any pending
6709 putpkt/getpkt sequence we're making is finished, before querying
6710 the stub for more events with the corresponding ack command
6711 (vStopped, for example). E.g., if we started a vStopped sequence
6712 immediately upon receiving the notification, something like this
6713 could happen:
74531fed
PA
6714
6715 1.1) --> Hg 1
6716 1.2) <-- OK
6717 1.3) --> g
6718 1.4) <-- %Stop
6719 1.5) --> vStopped
6720 1.6) <-- (registers reply to step #1.3)
6721
6722 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6723 query.
6724
796cb314 6725 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6726 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6727 doing whatever we were doing:
6728
6729 2.1) --> Hg 1
6730 2.2) <-- OK
6731 2.3) --> g
6732 2.4) <-- %Stop
6733 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6734 2.5) <-- (registers reply to step #2.3)
6735
6736 Eventualy after step #2.5, we return to the event loop, which
6737 notices there's an event on the
6738 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6739 associated callback --- the function below. At this point, we're
6740 always safe to start a vStopped sequence. :
6741
6742 2.6) --> vStopped
6743 2.7) <-- T05 thread:2
6744 2.8) --> vStopped
6745 2.9) --> OK
6746*/
6747
722247f1
YQ
6748void
6749remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6750{
6751 struct remote_state *rs = get_remote_state ();
74531fed 6752
f48ff2a7 6753 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6754 {
722247f1
YQ
6755 if (notif_debug)
6756 fprintf_unfiltered (gdb_stdlog,
6757 "notif: process: '%s' ack pending event\n",
6758 nc->name);
74531fed 6759
722247f1 6760 /* acknowledge */
f48ff2a7
YQ
6761 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6762 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6763
6764 while (1)
6765 {
6766 getpkt (&rs->buf, &rs->buf_size, 0);
6767 if (strcmp (rs->buf, "OK") == 0)
6768 break;
6769 else
722247f1 6770 remote_notif_ack (nc, rs->buf);
74531fed
PA
6771 }
6772 }
722247f1
YQ
6773 else
6774 {
6775 if (notif_debug)
6776 fprintf_unfiltered (gdb_stdlog,
6777 "notif: process: '%s' no pending reply\n",
6778 nc->name);
6779 }
74531fed
PA
6780}
6781
74531fed
PA
6782/* Called when it is decided that STOP_REPLY holds the info of the
6783 event that is to be returned to the core. This function always
6784 destroys STOP_REPLY. */
6785
6786static ptid_t
6787process_stop_reply (struct stop_reply *stop_reply,
6788 struct target_waitstatus *status)
6789{
6790 ptid_t ptid;
6791
6792 *status = stop_reply->ws;
6793 ptid = stop_reply->ptid;
6794
6795 /* If no thread/process was reported by the stub, assume the current
6796 inferior. */
6797 if (ptid_equal (ptid, null_ptid))
6798 ptid = inferior_ptid;
6799
5f3563ea 6800 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
6801 && status->kind != TARGET_WAITKIND_SIGNALLED
6802 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 6803 {
799a2abe 6804 struct private_thread_info *remote_thr;
ee154bee 6805
5f3563ea
PA
6806 /* Expedited registers. */
6807 if (stop_reply->regcache)
6808 {
217f1f79 6809 struct regcache *regcache
f5656ead 6810 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6811 cached_reg_t *reg;
6812 int ix;
6813
6814 for (ix = 0;
6815 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6816 ix++)
217f1f79 6817 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6818 VEC_free (cached_reg_t, stop_reply->regcache);
6819 }
74531fed 6820
1941c569 6821 remote_notice_new_inferior (ptid, 0);
799a2abe
PA
6822 remote_thr = demand_private_info (ptid);
6823 remote_thr->core = stop_reply->core;
6824 remote_thr->stop_reason = stop_reply->stop_reason;
6825 remote_thr->watch_data_address = stop_reply->watch_data_address;
74531fed
PA
6826 }
6827
74531fed
PA
6828 stop_reply_xfree (stop_reply);
6829 return ptid;
6830}
6831
6832/* The non-stop mode version of target_wait. */
6833
6834static ptid_t
47608cb1 6835remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6836{
6837 struct remote_state *rs = get_remote_state ();
74531fed
PA
6838 struct stop_reply *stop_reply;
6839 int ret;
fee9eda9 6840 int is_notif = 0;
74531fed
PA
6841
6842 /* If in non-stop mode, get out of getpkt even if a
6843 notification is received. */
6844
6845 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6846 0 /* forever */, &is_notif);
74531fed
PA
6847 while (1)
6848 {
fee9eda9 6849 if (ret != -1 && !is_notif)
74531fed
PA
6850 switch (rs->buf[0])
6851 {
6852 case 'E': /* Error of some sort. */
6853 /* We're out of sync with the target now. Did it continue
6854 or not? We can't tell which thread it was in non-stop,
6855 so just ignore this. */
6856 warning (_("Remote failure reply: %s"), rs->buf);
6857 break;
6858 case 'O': /* Console output. */
6859 remote_console_output (rs->buf + 1);
6860 break;
6861 default:
6862 warning (_("Invalid remote reply: %s"), rs->buf);
6863 break;
6864 }
6865
6866 /* Acknowledge a pending stop reply that may have arrived in the
6867 mean time. */
f48ff2a7 6868 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6869 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6870
6871 /* If indeed we noticed a stop reply, we're done. */
6872 stop_reply = queued_stop_reply (ptid);
6873 if (stop_reply != NULL)
6874 return process_stop_reply (stop_reply, status);
6875
47608cb1 6876 /* Still no event. If we're just polling for an event, then
74531fed 6877 return to the event loop. */
47608cb1 6878 if (options & TARGET_WNOHANG)
74531fed
PA
6879 {
6880 status->kind = TARGET_WAITKIND_IGNORE;
6881 return minus_one_ptid;
6882 }
6883
47608cb1 6884 /* Otherwise do a blocking wait. */
74531fed 6885 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6886 1 /* forever */, &is_notif);
74531fed
PA
6887 }
6888}
6889
6890/* Wait until the remote machine stops, then return, storing status in
6891 STATUS just as `wait' would. */
6892
6893static ptid_t
47608cb1 6894remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6895{
6896 struct remote_state *rs = get_remote_state ();
74531fed 6897 ptid_t event_ptid = null_ptid;
cea39f65 6898 char *buf;
74531fed
PA
6899 struct stop_reply *stop_reply;
6900
47608cb1
PA
6901 again:
6902
74531fed
PA
6903 status->kind = TARGET_WAITKIND_IGNORE;
6904 status->value.integer = 0;
6905
6906 stop_reply = queued_stop_reply (ptid);
6907 if (stop_reply != NULL)
6908 return process_stop_reply (stop_reply, status);
6909
6910 if (rs->cached_wait_status)
6911 /* Use the cached wait status, but only once. */
6912 rs->cached_wait_status = 0;
6913 else
6914 {
6915 int ret;
722247f1 6916 int is_notif;
567420d1
PA
6917 int forever = ((options & TARGET_WNOHANG) == 0
6918 && wait_forever_enabled_p);
6919
6920 if (!rs->waiting_for_stop_reply)
6921 {
6922 status->kind = TARGET_WAITKIND_NO_RESUMED;
6923 return minus_one_ptid;
6924 }
74531fed
PA
6925
6926 if (!target_is_async_p ())
6927 {
934b9bac 6928 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6929 /* If the user hit C-c before this packet, or between packets,
6930 pretend that it was hit right here. */
522002f9 6931 if (check_quit_flag ())
74531fed 6932 {
522002f9 6933 clear_quit_flag ();
934b9bac 6934 sync_remote_interrupt (SIGINT);
74531fed
PA
6935 }
6936 }
6937
6938 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6939 _never_ wait for ever -> test on target_is_async_p().
6940 However, before we do that we need to ensure that the caller
6941 knows how to take the target into/out of async mode. */
722247f1 6942 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6943 forever, &is_notif);
722247f1 6944
5e1b953b
SDJ
6945 if (!target_is_async_p ())
6946 signal (SIGINT, ofunc);
6947
722247f1
YQ
6948 /* GDB gets a notification. Return to core as this event is
6949 not interesting. */
6950 if (ret != -1 && is_notif)
6951 return minus_one_ptid;
567420d1
PA
6952
6953 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6954 return minus_one_ptid;
74531fed
PA
6955 }
6956
6957 buf = rs->buf;
6958
3a29589a
DJ
6959 /* Assume that the target has acknowledged Ctrl-C unless we receive
6960 an 'F' or 'O' packet. */
6961 if (buf[0] != 'F' && buf[0] != 'O')
6962 rs->ctrlc_pending_p = 0;
6963
74531fed
PA
6964 switch (buf[0])
6965 {
6966 case 'E': /* Error of some sort. */
6967 /* We're out of sync with the target now. Did it continue or
6968 not? Not is more likely, so report a stop. */
29090fb6
LM
6969 rs->waiting_for_stop_reply = 0;
6970
74531fed
PA
6971 warning (_("Remote failure reply: %s"), buf);
6972 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6973 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6974 break;
6975 case 'F': /* File-I/O request. */
e42e5352
YQ
6976 /* GDB may access the inferior memory while handling the File-I/O
6977 request, but we don't want GDB accessing memory while waiting
6978 for a stop reply. See the comments in putpkt_binary. Set
6979 waiting_for_stop_reply to 0 temporarily. */
6980 rs->waiting_for_stop_reply = 0;
3a29589a
DJ
6981 remote_fileio_request (buf, rs->ctrlc_pending_p);
6982 rs->ctrlc_pending_p = 0;
e42e5352
YQ
6983 /* GDB handled the File-I/O request, and the target is running
6984 again. Keep waiting for events. */
6985 rs->waiting_for_stop_reply = 1;
74531fed 6986 break;
f2faf941 6987 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 6988 {
29090fb6
LM
6989 struct stop_reply *stop_reply;
6990
6991 /* There is a stop reply to handle. */
6992 rs->waiting_for_stop_reply = 0;
6993
6994 stop_reply
722247f1
YQ
6995 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6996 rs->buf);
74531fed 6997
74531fed 6998 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6999 break;
7000 }
7001 case 'O': /* Console output. */
7002 remote_console_output (buf + 1);
c8e38a49
PA
7003 break;
7004 case '\0':
b73be471 7005 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7006 {
7007 /* Zero length reply means that we tried 'S' or 'C' and the
7008 remote system doesn't support it. */
7009 target_terminal_ours_for_output ();
7010 printf_filtered
7011 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7012 gdb_signal_to_name (rs->last_sent_signal));
7013 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
7014 target_terminal_inferior ();
7015
280ceea3 7016 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49 7017 putpkt ((char *) buf);
c8e38a49 7018 break;
43ff13b4 7019 }
c8e38a49
PA
7020 /* else fallthrough */
7021 default:
7022 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7023 break;
43ff13b4 7024 }
c8e38a49 7025
f2faf941
PA
7026 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7027 return minus_one_ptid;
7028 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7029 {
7030 /* Nothing interesting happened. If we're doing a non-blocking
7031 poll, we're done. Otherwise, go back to waiting. */
7032 if (options & TARGET_WNOHANG)
7033 return minus_one_ptid;
7034 else
7035 goto again;
7036 }
74531fed
PA
7037 else if (status->kind != TARGET_WAITKIND_EXITED
7038 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7039 {
7040 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7041 record_currthread (rs, event_ptid);
82f73884
PA
7042 else
7043 event_ptid = inferior_ptid;
43ff13b4 7044 }
74531fed
PA
7045 else
7046 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7047 record_currthread (rs, minus_one_ptid);
79d7f229 7048
82f73884 7049 return event_ptid;
43ff13b4
JM
7050}
7051
74531fed
PA
7052/* Wait until the remote machine stops, then return, storing status in
7053 STATUS just as `wait' would. */
7054
c8e38a49 7055static ptid_t
117de6a9 7056remote_wait (struct target_ops *ops,
47608cb1 7057 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7058{
7059 ptid_t event_ptid;
7060
6efcd9a8 7061 if (target_is_non_stop_p ())
47608cb1 7062 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7063 else
47608cb1 7064 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7065
d9d41e78 7066 if (target_is_async_p ())
c8e38a49 7067 {
74531fed
PA
7068 /* If there are are events left in the queue tell the event loop
7069 to return here. */
722247f1 7070 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7071 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7072 }
c8e38a49
PA
7073
7074 return event_ptid;
7075}
7076
74ca34ce 7077/* Fetch a single register using a 'p' packet. */
c906108c 7078
b96ec7ac 7079static int
56be3814 7080fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
7081{
7082 struct remote_state *rs = get_remote_state ();
2e9f7625 7083 char *buf, *p;
b96ec7ac
AC
7084 char regp[MAX_REGISTER_SIZE];
7085 int i;
7086
4082afcc 7087 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7088 return 0;
7089
7090 if (reg->pnum == -1)
7091 return 0;
7092
2e9f7625 7093 p = rs->buf;
fcad0fa4 7094 *p++ = 'p';
74ca34ce 7095 p += hexnumstr (p, reg->pnum);
fcad0fa4 7096 *p++ = '\0';
1f4437a4
MS
7097 putpkt (rs->buf);
7098 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7099
2e9f7625
DJ
7100 buf = rs->buf;
7101
74ca34ce
DJ
7102 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7103 {
7104 case PACKET_OK:
7105 break;
7106 case PACKET_UNKNOWN:
7107 return 0;
7108 case PACKET_ERROR:
27a9c0bf
MS
7109 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7110 gdbarch_register_name (get_regcache_arch (regcache),
7111 reg->regnum),
7112 buf);
74ca34ce 7113 }
3f9a994c
JB
7114
7115 /* If this register is unfetchable, tell the regcache. */
7116 if (buf[0] == 'x')
8480adf2 7117 {
56be3814 7118 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7119 return 1;
b96ec7ac 7120 }
b96ec7ac 7121
3f9a994c
JB
7122 /* Otherwise, parse and supply the value. */
7123 p = buf;
7124 i = 0;
7125 while (p[0] != 0)
7126 {
7127 if (p[1] == 0)
74ca34ce 7128 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7129
7130 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7131 p += 2;
7132 }
56be3814 7133 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7134 return 1;
b96ec7ac
AC
7135}
7136
74ca34ce
DJ
7137/* Fetch the registers included in the target's 'g' packet. */
7138
29709017
DJ
7139static int
7140send_g_packet (void)
c906108c 7141{
d01949b6 7142 struct remote_state *rs = get_remote_state ();
cea39f65 7143 int buf_len;
c906108c 7144
bba74b36 7145 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7146 remote_send (&rs->buf, &rs->buf_size);
c906108c 7147
29709017
DJ
7148 /* We can get out of synch in various cases. If the first character
7149 in the buffer is not a hex character, assume that has happened
7150 and try to fetch another packet to read. */
7151 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7152 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7153 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7154 && rs->buf[0] != 'x') /* New: unavailable register value. */
7155 {
7156 if (remote_debug)
7157 fprintf_unfiltered (gdb_stdlog,
7158 "Bad register packet; fetching a new packet\n");
7159 getpkt (&rs->buf, &rs->buf_size, 0);
7160 }
7161
74ca34ce
DJ
7162 buf_len = strlen (rs->buf);
7163
7164 /* Sanity check the received packet. */
7165 if (buf_len % 2 != 0)
7166 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7167
7168 return buf_len / 2;
7169}
7170
7171static void
56be3814 7172process_g_packet (struct regcache *regcache)
29709017 7173{
4a22f64d 7174 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7175 struct remote_state *rs = get_remote_state ();
7176 struct remote_arch_state *rsa = get_remote_arch_state ();
7177 int i, buf_len;
7178 char *p;
7179 char *regs;
7180
7181 buf_len = strlen (rs->buf);
7182
7183 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7184 if (buf_len > 2 * rsa->sizeof_g_packet)
7185 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7186
7187 /* Save the size of the packet sent to us by the target. It is used
7188 as a heuristic when determining the max size of packets that the
7189 target can safely receive. */
7190 if (rsa->actual_register_packet_size == 0)
7191 rsa->actual_register_packet_size = buf_len;
7192
7193 /* If this is smaller than we guessed the 'g' packet would be,
7194 update our records. A 'g' reply that doesn't include a register's
7195 value implies either that the register is not available, or that
7196 the 'p' packet must be used. */
7197 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7198 {
74ca34ce
DJ
7199 rsa->sizeof_g_packet = buf_len / 2;
7200
4a22f64d 7201 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7202 {
74ca34ce
DJ
7203 if (rsa->regs[i].pnum == -1)
7204 continue;
7205
7206 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7207 rsa->regs[i].in_g_packet = 0;
b96ec7ac 7208 else
74ca34ce 7209 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7210 }
74ca34ce 7211 }
b323314b 7212
224c3ddb 7213 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7214
7215 /* Unimplemented registers read as all bits zero. */
ea9c271d 7216 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7217
c906108c
SS
7218 /* Reply describes registers byte by byte, each byte encoded as two
7219 hex characters. Suck them all up, then supply them to the
7220 register cacheing/storage mechanism. */
7221
74ca34ce 7222 p = rs->buf;
ea9c271d 7223 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7224 {
74ca34ce
DJ
7225 if (p[0] == 0 || p[1] == 0)
7226 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7227 internal_error (__FILE__, __LINE__,
9b20d036 7228 _("unexpected end of 'g' packet reply"));
74ca34ce 7229
c906108c 7230 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7231 regs[i] = 0; /* 'x' */
c906108c
SS
7232 else
7233 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7234 p += 2;
7235 }
7236
a744cf53
MS
7237 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7238 {
7239 struct packet_reg *r = &rsa->regs[i];
7240
7241 if (r->in_g_packet)
7242 {
7243 if (r->offset * 2 >= strlen (rs->buf))
7244 /* This shouldn't happen - we adjusted in_g_packet above. */
7245 internal_error (__FILE__, __LINE__,
9b20d036 7246 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7247 else if (rs->buf[r->offset * 2] == 'x')
7248 {
7249 gdb_assert (r->offset * 2 < strlen (rs->buf));
7250 /* The register isn't available, mark it as such (at
7251 the same time setting the value to zero). */
7252 regcache_raw_supply (regcache, r->regnum, NULL);
7253 }
7254 else
7255 regcache_raw_supply (regcache, r->regnum,
7256 regs + r->offset);
7257 }
7258 }
c906108c
SS
7259}
7260
29709017 7261static void
56be3814 7262fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7263{
7264 send_g_packet ();
56be3814 7265 process_g_packet (regcache);
29709017
DJ
7266}
7267
e6e4e701
PA
7268/* Make the remote selected traceframe match GDB's selected
7269 traceframe. */
7270
7271static void
7272set_remote_traceframe (void)
7273{
7274 int newnum;
262e1174 7275 struct remote_state *rs = get_remote_state ();
e6e4e701 7276
262e1174 7277 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7278 return;
7279
7280 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7281 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7282
7283 newnum = target_trace_find (tfind_number,
7284 get_traceframe_number (), 0, 0, NULL);
7285
7286 /* Should not happen. If it does, all bets are off. */
7287 if (newnum != get_traceframe_number ())
7288 warning (_("could not set remote traceframe"));
7289}
7290
74ca34ce 7291static void
28439f5e
PA
7292remote_fetch_registers (struct target_ops *ops,
7293 struct regcache *regcache, int regnum)
74ca34ce 7294{
74ca34ce
DJ
7295 struct remote_arch_state *rsa = get_remote_arch_state ();
7296 int i;
7297
e6e4e701 7298 set_remote_traceframe ();
79d7f229 7299 set_general_thread (inferior_ptid);
74ca34ce
DJ
7300
7301 if (regnum >= 0)
7302 {
7303 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7304
74ca34ce
DJ
7305 gdb_assert (reg != NULL);
7306
7307 /* If this register might be in the 'g' packet, try that first -
7308 we are likely to read more than one register. If this is the
7309 first 'g' packet, we might be overly optimistic about its
7310 contents, so fall back to 'p'. */
7311 if (reg->in_g_packet)
7312 {
56be3814 7313 fetch_registers_using_g (regcache);
74ca34ce
DJ
7314 if (reg->in_g_packet)
7315 return;
7316 }
7317
56be3814 7318 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7319 return;
7320
7321 /* This register is not available. */
56be3814 7322 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7323
7324 return;
7325 }
7326
56be3814 7327 fetch_registers_using_g (regcache);
74ca34ce 7328
4a22f64d 7329 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7330 if (!rsa->regs[i].in_g_packet)
56be3814 7331 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7332 {
7333 /* This register is not available. */
56be3814 7334 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7335 }
7336}
7337
c906108c
SS
7338/* Prepare to store registers. Since we may send them all (using a
7339 'G' request), we have to read out the ones we don't want to change
7340 first. */
7341
c5aa993b 7342static void
f32dbf8c 7343remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7344{
ea9c271d 7345 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7346 int i;
cfd77fa1 7347 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7348
c906108c 7349 /* Make sure the entire registers array is valid. */
4082afcc 7350 switch (packet_support (PACKET_P))
5a2468f5
JM
7351 {
7352 case PACKET_DISABLE:
7353 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7354 /* Make sure all the necessary registers are cached. */
4a22f64d 7355 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7356 if (rsa->regs[i].in_g_packet)
316f2060 7357 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7358 break;
7359 case PACKET_ENABLE:
7360 break;
7361 }
7362}
7363
ad10f812 7364/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7365 packet was not recognized. */
5a2468f5
JM
7366
7367static int
1f4437a4
MS
7368store_register_using_P (const struct regcache *regcache,
7369 struct packet_reg *reg)
5a2468f5 7370{
4a22f64d 7371 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7372 struct remote_state *rs = get_remote_state ();
5a2468f5 7373 /* Try storing a single register. */
6d820c5c 7374 char *buf = rs->buf;
cfd77fa1 7375 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7376 char *p;
5a2468f5 7377
4082afcc 7378 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7379 return 0;
7380
7381 if (reg->pnum == -1)
7382 return 0;
7383
ea9c271d 7384 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7385 p = buf + strlen (buf);
56be3814 7386 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7387 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7388 putpkt (rs->buf);
7389 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7390
74ca34ce
DJ
7391 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7392 {
7393 case PACKET_OK:
7394 return 1;
7395 case PACKET_ERROR:
27a9c0bf
MS
7396 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7397 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7398 case PACKET_UNKNOWN:
7399 return 0;
7400 default:
7401 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7402 }
c906108c
SS
7403}
7404
23860348
MS
7405/* Store register REGNUM, or all registers if REGNUM == -1, from the
7406 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7407
7408static void
56be3814 7409store_registers_using_G (const struct regcache *regcache)
c906108c 7410{
d01949b6 7411 struct remote_state *rs = get_remote_state ();
ea9c271d 7412 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7413 gdb_byte *regs;
c906108c
SS
7414 char *p;
7415
193cb69f
AC
7416 /* Extract all the registers in the regcache copying them into a
7417 local buffer. */
7418 {
b323314b 7419 int i;
a744cf53 7420
224c3ddb 7421 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7422 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7423 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7424 {
ea9c271d 7425 struct packet_reg *r = &rsa->regs[i];
a744cf53 7426
b323314b 7427 if (r->in_g_packet)
56be3814 7428 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7429 }
7430 }
c906108c
SS
7431
7432 /* Command describes registers byte by byte,
7433 each byte encoded as two hex characters. */
6d820c5c 7434 p = rs->buf;
193cb69f 7435 *p++ = 'G';
74ca34ce
DJ
7436 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7437 updated. */
7438 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7439 putpkt (rs->buf);
7440 getpkt (&rs->buf, &rs->buf_size, 0);
7441 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7442 error (_("Could not write registers; remote failure reply '%s'"),
7443 rs->buf);
c906108c 7444}
74ca34ce
DJ
7445
7446/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7447 of the register cache buffer. FIXME: ignores errors. */
7448
7449static void
28439f5e
PA
7450remote_store_registers (struct target_ops *ops,
7451 struct regcache *regcache, int regnum)
74ca34ce 7452{
74ca34ce
DJ
7453 struct remote_arch_state *rsa = get_remote_arch_state ();
7454 int i;
7455
e6e4e701 7456 set_remote_traceframe ();
79d7f229 7457 set_general_thread (inferior_ptid);
74ca34ce
DJ
7458
7459 if (regnum >= 0)
7460 {
7461 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7462
74ca34ce
DJ
7463 gdb_assert (reg != NULL);
7464
7465 /* Always prefer to store registers using the 'P' packet if
7466 possible; we often change only a small number of registers.
7467 Sometimes we change a larger number; we'd need help from a
7468 higher layer to know to use 'G'. */
56be3814 7469 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7470 return;
7471
7472 /* For now, don't complain if we have no way to write the
7473 register. GDB loses track of unavailable registers too
7474 easily. Some day, this may be an error. We don't have
0df8b418 7475 any way to read the register, either... */
74ca34ce
DJ
7476 if (!reg->in_g_packet)
7477 return;
7478
56be3814 7479 store_registers_using_G (regcache);
74ca34ce
DJ
7480 return;
7481 }
7482
56be3814 7483 store_registers_using_G (regcache);
74ca34ce 7484
4a22f64d 7485 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7486 if (!rsa->regs[i].in_g_packet)
56be3814 7487 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7488 /* See above for why we do not issue an error here. */
7489 continue;
7490}
c906108c
SS
7491\f
7492
7493/* Return the number of hex digits in num. */
7494
7495static int
fba45db2 7496hexnumlen (ULONGEST num)
c906108c
SS
7497{
7498 int i;
7499
7500 for (i = 0; num != 0; i++)
7501 num >>= 4;
7502
7503 return max (i, 1);
7504}
7505
2df3850c 7506/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7507
7508static int
fba45db2 7509hexnumstr (char *buf, ULONGEST num)
c906108c 7510{
c906108c 7511 int len = hexnumlen (num);
a744cf53 7512
2df3850c
JM
7513 return hexnumnstr (buf, num, len);
7514}
7515
c906108c 7516
2df3850c 7517/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7518
2df3850c 7519static int
fba45db2 7520hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7521{
7522 int i;
7523
7524 buf[width] = '\0';
7525
7526 for (i = width - 1; i >= 0; i--)
c906108c 7527 {
c5aa993b 7528 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7529 num >>= 4;
7530 }
7531
2df3850c 7532 return width;
c906108c
SS
7533}
7534
23860348 7535/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7536
7537static CORE_ADDR
fba45db2 7538remote_address_masked (CORE_ADDR addr)
c906108c 7539{
883b9c6c 7540 unsigned int address_size = remote_address_size;
a744cf53 7541
911c95a5
UW
7542 /* If "remoteaddresssize" was not set, default to target address size. */
7543 if (!address_size)
f5656ead 7544 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7545
7546 if (address_size > 0
7547 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7548 {
7549 /* Only create a mask when that mask can safely be constructed
23860348 7550 in a ULONGEST variable. */
c906108c 7551 ULONGEST mask = 1;
a744cf53 7552
911c95a5 7553 mask = (mask << address_size) - 1;
c906108c
SS
7554 addr &= mask;
7555 }
7556 return addr;
7557}
7558
7559/* Determine whether the remote target supports binary downloading.
7560 This is accomplished by sending a no-op memory write of zero length
7561 to the target at the specified address. It does not suffice to send
23860348
MS
7562 the whole packet, since many stubs strip the eighth bit and
7563 subsequently compute a wrong checksum, which causes real havoc with
7564 remote_write_bytes.
7a292a7a 7565
96baa820 7566 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7567 clean. In cases like this, the user should clear "remote
23860348 7568 X-packet". */
96baa820 7569
c906108c 7570static void
fba45db2 7571check_binary_download (CORE_ADDR addr)
c906108c 7572{
d01949b6 7573 struct remote_state *rs = get_remote_state ();
24b06219 7574
4082afcc 7575 switch (packet_support (PACKET_X))
c906108c 7576 {
96baa820
JM
7577 case PACKET_DISABLE:
7578 break;
7579 case PACKET_ENABLE:
7580 break;
7581 case PACKET_SUPPORT_UNKNOWN:
7582 {
96baa820 7583 char *p;
802188a7 7584
2e9f7625 7585 p = rs->buf;
96baa820
JM
7586 *p++ = 'X';
7587 p += hexnumstr (p, (ULONGEST) addr);
7588 *p++ = ',';
7589 p += hexnumstr (p, (ULONGEST) 0);
7590 *p++ = ':';
7591 *p = '\0';
802188a7 7592
2e9f7625 7593 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7594 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7595
2e9f7625 7596 if (rs->buf[0] == '\0')
96baa820
JM
7597 {
7598 if (remote_debug)
7599 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7600 "binary downloading NOT "
7601 "supported by target\n");
444abaca 7602 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7603 }
7604 else
7605 {
7606 if (remote_debug)
7607 fprintf_unfiltered (gdb_stdlog,
64b9b334 7608 "binary downloading supported by target\n");
444abaca 7609 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7610 }
7611 break;
7612 }
c906108c
SS
7613 }
7614}
7615
124e13d9
SM
7616/* Helper function to resize the payload in order to try to get a good
7617 alignment. We try to write an amount of data such that the next write will
7618 start on an address aligned on REMOTE_ALIGN_WRITES. */
7619
7620static int
7621align_for_efficient_write (int todo, CORE_ADDR memaddr)
7622{
7623 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7624}
7625
c906108c
SS
7626/* Write memory data directly to the remote machine.
7627 This does not inform the data cache; the data cache uses this.
a76d924d 7628 HEADER is the starting part of the packet.
c906108c
SS
7629 MEMADDR is the address in the remote memory space.
7630 MYADDR is the address of the buffer in our space.
124e13d9
SM
7631 LEN_UNITS is the number of addressable units to write.
7632 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7633 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7634 should send data as binary ('X'), or hex-encoded ('M').
7635
7636 The function creates packet of the form
7637 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7638
124e13d9 7639 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7640
7641 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7642 are omitted.
7643
9b409511 7644 Return the transferred status, error or OK (an
124e13d9
SM
7645 'enum target_xfer_status' value). Save the number of addressable units
7646 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7647
7648 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7649 exchange between gdb and the stub could look like (?? in place of the
7650 checksum):
7651
7652 -> $m1000,4#??
7653 <- aaaabbbbccccdddd
7654
7655 -> $M1000,3:eeeeffffeeee#??
7656 <- OK
7657
7658 -> $m1000,4#??
7659 <- eeeeffffeeeedddd */
c906108c 7660
9b409511 7661static enum target_xfer_status
a76d924d 7662remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7663 const gdb_byte *myaddr, ULONGEST len_units,
7664 int unit_size, ULONGEST *xfered_len_units,
7665 char packet_format, int use_length)
c906108c 7666{
6d820c5c 7667 struct remote_state *rs = get_remote_state ();
cfd77fa1 7668 char *p;
a76d924d
DJ
7669 char *plen = NULL;
7670 int plenlen = 0;
124e13d9
SM
7671 int todo_units;
7672 int units_written;
7673 int payload_capacity_bytes;
7674 int payload_length_bytes;
a76d924d
DJ
7675
7676 if (packet_format != 'X' && packet_format != 'M')
7677 internal_error (__FILE__, __LINE__,
9b20d036 7678 _("remote_write_bytes_aux: bad packet format"));
c906108c 7679
124e13d9 7680 if (len_units == 0)
9b409511 7681 return TARGET_XFER_EOF;
b2182ed2 7682
124e13d9 7683 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7684
6d820c5c
DJ
7685 /* The packet buffer will be large enough for the payload;
7686 get_memory_packet_size ensures this. */
a76d924d 7687 rs->buf[0] = '\0';
c906108c 7688
a257b5bb 7689 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7690 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7691
124e13d9 7692 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7693 if (!use_length)
0df8b418 7694 /* The comma won't be used. */
124e13d9
SM
7695 payload_capacity_bytes += 1;
7696 payload_capacity_bytes -= strlen (header);
7697 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7698
a76d924d 7699 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7700
a76d924d
DJ
7701 strcat (rs->buf, header);
7702 p = rs->buf + strlen (header);
7703
7704 /* Compute a best guess of the number of bytes actually transfered. */
7705 if (packet_format == 'X')
c906108c 7706 {
23860348 7707 /* Best guess at number of bytes that will fit. */
124e13d9 7708 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7709 if (use_length)
124e13d9
SM
7710 payload_capacity_bytes -= hexnumlen (todo_units);
7711 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7712 }
7713 else
7714 {
124e13d9
SM
7715 /* Number of bytes that will fit. */
7716 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7717 if (use_length)
124e13d9
SM
7718 payload_capacity_bytes -= hexnumlen (todo_units);
7719 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7720 }
a76d924d 7721
124e13d9 7722 if (todo_units <= 0)
3de11b2e 7723 internal_error (__FILE__, __LINE__,
405f8e94 7724 _("minimum packet size too small to write data"));
802188a7 7725
6765f3e5
DJ
7726 /* If we already need another packet, then try to align the end
7727 of this packet to a useful boundary. */
124e13d9
SM
7728 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7729 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7730
a257b5bb 7731 /* Append "<memaddr>". */
917317f4
JM
7732 memaddr = remote_address_masked (memaddr);
7733 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7734
a76d924d
DJ
7735 if (use_length)
7736 {
7737 /* Append ",". */
7738 *p++ = ',';
802188a7 7739
124e13d9
SM
7740 /* Append the length and retain its location and size. It may need to be
7741 adjusted once the packet body has been created. */
a76d924d 7742 plen = p;
124e13d9 7743 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7744 p += plenlen;
7745 }
a257b5bb
AC
7746
7747 /* Append ":". */
917317f4
JM
7748 *p++ = ':';
7749 *p = '\0';
802188a7 7750
a257b5bb 7751 /* Append the packet body. */
a76d924d 7752 if (packet_format == 'X')
917317f4 7753 {
917317f4
JM
7754 /* Binary mode. Send target system values byte by byte, in
7755 increasing byte addresses. Only escape certain critical
7756 characters. */
124e13d9
SM
7757 payload_length_bytes =
7758 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7759 &units_written, payload_capacity_bytes);
6765f3e5 7760
124e13d9 7761 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7762 a second try to keep the end of the packet aligned. Don't do
7763 this if the packet is tiny. */
124e13d9 7764 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7765 {
124e13d9
SM
7766 int new_todo_units;
7767
7768 new_todo_units = align_for_efficient_write (units_written, memaddr);
7769
7770 if (new_todo_units != units_written)
7771 payload_length_bytes =
7772 remote_escape_output (myaddr, new_todo_units, unit_size,
7773 (gdb_byte *) p, &units_written,
7774 payload_capacity_bytes);
6765f3e5
DJ
7775 }
7776
124e13d9
SM
7777 p += payload_length_bytes;
7778 if (use_length && units_written < todo_units)
c906108c 7779 {
802188a7 7780 /* Escape chars have filled up the buffer prematurely,
124e13d9 7781 and we have actually sent fewer units than planned.
917317f4
JM
7782 Fix-up the length field of the packet. Use the same
7783 number of characters as before. */
124e13d9
SM
7784 plen += hexnumnstr (plen, (ULONGEST) units_written,
7785 plenlen);
917317f4 7786 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7787 }
a76d924d
DJ
7788 }
7789 else
7790 {
917317f4
JM
7791 /* Normal mode: Send target system values byte by byte, in
7792 increasing byte addresses. Each byte is encoded as a two hex
7793 value. */
124e13d9
SM
7794 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7795 units_written = todo_units;
c906108c 7796 }
802188a7 7797
2e9f7625 7798 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7799 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7800
2e9f7625 7801 if (rs->buf[0] == 'E')
00d84524 7802 return TARGET_XFER_E_IO;
802188a7 7803
124e13d9
SM
7804 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7805 send fewer units than we'd planned. */
7806 *xfered_len_units = (ULONGEST) units_written;
9b409511 7807 return TARGET_XFER_OK;
c906108c
SS
7808}
7809
a76d924d
DJ
7810/* Write memory data directly to the remote machine.
7811 This does not inform the data cache; the data cache uses this.
7812 MEMADDR is the address in the remote memory space.
7813 MYADDR is the address of the buffer in our space.
7814 LEN is the number of bytes.
7815
9b409511
YQ
7816 Return the transferred status, error or OK (an
7817 'enum target_xfer_status' value). Save the number of bytes
7818 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7819
9b409511
YQ
7820static enum target_xfer_status
7821remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7822 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7823{
7824 char *packet_format = 0;
7825
7826 /* Check whether the target supports binary download. */
7827 check_binary_download (memaddr);
7828
4082afcc 7829 switch (packet_support (PACKET_X))
a76d924d
DJ
7830 {
7831 case PACKET_ENABLE:
7832 packet_format = "X";
7833 break;
7834 case PACKET_DISABLE:
7835 packet_format = "M";
7836 break;
7837 case PACKET_SUPPORT_UNKNOWN:
7838 internal_error (__FILE__, __LINE__,
7839 _("remote_write_bytes: bad internal state"));
7840 default:
7841 internal_error (__FILE__, __LINE__, _("bad switch"));
7842 }
7843
7844 return remote_write_bytes_aux (packet_format,
124e13d9 7845 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7846 packet_format[0], 1);
a76d924d
DJ
7847}
7848
9217e74e
YQ
7849/* Read memory data directly from the remote machine.
7850 This does not use the data cache; the data cache uses this.
7851 MEMADDR is the address in the remote memory space.
7852 MYADDR is the address of the buffer in our space.
124e13d9
SM
7853 LEN_UNITS is the number of addressable memory units to read..
7854 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7855
7856 Return the transferred status, error or OK (an
7857 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7858 transferred in *XFERED_LEN_UNITS.
7859
7860 See the comment of remote_write_bytes_aux for an example of
7861 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7862
7863static enum target_xfer_status
124e13d9
SM
7864remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7865 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7866{
7867 struct remote_state *rs = get_remote_state ();
124e13d9 7868 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7869 char *p;
124e13d9
SM
7870 int todo_units;
7871 int decoded_bytes;
9217e74e 7872
124e13d9 7873 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7874 /* The packet buffer will be large enough for the payload;
7875 get_memory_packet_size ensures this. */
7876
124e13d9
SM
7877 /* Number of units that will fit. */
7878 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7879
7880 /* Construct "m"<memaddr>","<len>". */
7881 memaddr = remote_address_masked (memaddr);
7882 p = rs->buf;
7883 *p++ = 'm';
7884 p += hexnumstr (p, (ULONGEST) memaddr);
7885 *p++ = ',';
124e13d9 7886 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7887 *p = '\0';
7888 putpkt (rs->buf);
7889 getpkt (&rs->buf, &rs->buf_size, 0);
7890 if (rs->buf[0] == 'E'
7891 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7892 && rs->buf[3] == '\0')
7893 return TARGET_XFER_E_IO;
7894 /* Reply describes memory byte by byte, each byte encoded as two hex
7895 characters. */
7896 p = rs->buf;
124e13d9 7897 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7898 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7899 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7900 return TARGET_XFER_OK;
7901}
7902
b55fbac4
YQ
7903/* Using the set of read-only target sections of remote, read live
7904 read-only memory.
8acf9577
YQ
7905
7906 For interface/parameters/return description see target.h,
7907 to_xfer_partial. */
7908
7909static enum target_xfer_status
b55fbac4
YQ
7910remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7911 ULONGEST memaddr, ULONGEST len,
124e13d9 7912 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7913{
7914 struct target_section *secp;
7915 struct target_section_table *table;
7916
7917 secp = target_section_by_addr (ops, memaddr);
7918 if (secp != NULL
7919 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7920 secp->the_bfd_section)
7921 & SEC_READONLY))
7922 {
7923 struct target_section *p;
7924 ULONGEST memend = memaddr + len;
7925
7926 table = target_get_section_table (ops);
7927
7928 for (p = table->sections; p < table->sections_end; p++)
7929 {
7930 if (memaddr >= p->addr)
7931 {
7932 if (memend <= p->endaddr)
7933 {
7934 /* Entire transfer is within this section. */
124e13d9 7935 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7936 xfered_len);
8acf9577
YQ
7937 }
7938 else if (memaddr >= p->endaddr)
7939 {
7940 /* This section ends before the transfer starts. */
7941 continue;
7942 }
7943 else
7944 {
7945 /* This section overlaps the transfer. Just do half. */
7946 len = p->endaddr - memaddr;
124e13d9 7947 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7948 xfered_len);
8acf9577
YQ
7949 }
7950 }
7951 }
7952 }
7953
7954 return TARGET_XFER_EOF;
7955}
7956
9217e74e
YQ
7957/* Similar to remote_read_bytes_1, but it reads from the remote stub
7958 first if the requested memory is unavailable in traceframe.
7959 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7960
9b409511 7961static enum target_xfer_status
8acf9577 7962remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7963 gdb_byte *myaddr, ULONGEST len, int unit_size,
7964 ULONGEST *xfered_len)
c906108c 7965{
6b6aa828 7966 if (len == 0)
96c4f946 7967 return TARGET_XFER_EOF;
b2182ed2 7968
8acf9577
YQ
7969 if (get_traceframe_number () != -1)
7970 {
7971 VEC(mem_range_s) *available;
7972
7973 /* If we fail to get the set of available memory, then the
7974 target does not support querying traceframe info, and so we
7975 attempt reading from the traceframe anyway (assuming the
7976 target implements the old QTro packet then). */
7977 if (traceframe_available_memory (&available, memaddr, len))
7978 {
7979 struct cleanup *old_chain;
7980
7981 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7982
7983 if (VEC_empty (mem_range_s, available)
7984 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7985 {
7986 enum target_xfer_status res;
7987
7988 /* Don't read into the traceframe's available
7989 memory. */
7990 if (!VEC_empty (mem_range_s, available))
7991 {
7992 LONGEST oldlen = len;
7993
7994 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7995 gdb_assert (len <= oldlen);
7996 }
7997
7998 do_cleanups (old_chain);
7999
8000 /* This goes through the topmost target again. */
b55fbac4 8001 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 8002 len, unit_size, xfered_len);
8acf9577
YQ
8003 if (res == TARGET_XFER_OK)
8004 return TARGET_XFER_OK;
8005 else
8006 {
8007 /* No use trying further, we know some memory starting
8008 at MEMADDR isn't available. */
8009 *xfered_len = len;
8010 return TARGET_XFER_UNAVAILABLE;
8011 }
8012 }
8013
8014 /* Don't try to read more than how much is available, in
8015 case the target implements the deprecated QTro packet to
8016 cater for older GDBs (the target's knowledge of read-only
8017 sections may be outdated by now). */
8018 len = VEC_index (mem_range_s, available, 0)->length;
8019
8020 do_cleanups (old_chain);
8021 }
8022 }
8023
124e13d9 8024 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8025}
74531fed 8026
c906108c 8027\f
c906108c 8028
a76d924d
DJ
8029/* Sends a packet with content determined by the printf format string
8030 FORMAT and the remaining arguments, then gets the reply. Returns
8031 whether the packet was a success, a failure, or unknown. */
8032
77b64a49
PA
8033static enum packet_result remote_send_printf (const char *format, ...)
8034 ATTRIBUTE_PRINTF (1, 2);
8035
2c0b251b 8036static enum packet_result
a76d924d
DJ
8037remote_send_printf (const char *format, ...)
8038{
8039 struct remote_state *rs = get_remote_state ();
8040 int max_size = get_remote_packet_size ();
a76d924d 8041 va_list ap;
a744cf53 8042
a76d924d
DJ
8043 va_start (ap, format);
8044
8045 rs->buf[0] = '\0';
8046 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8047 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8048
8049 if (putpkt (rs->buf) < 0)
8050 error (_("Communication problem with target."));
8051
8052 rs->buf[0] = '\0';
8053 getpkt (&rs->buf, &rs->buf_size, 0);
8054
8055 return packet_check_result (rs->buf);
8056}
8057
8058static void
8059restore_remote_timeout (void *p)
8060{
8061 int value = *(int *)p;
a744cf53 8062
a76d924d
DJ
8063 remote_timeout = value;
8064}
8065
8066/* Flash writing can take quite some time. We'll set
8067 effectively infinite timeout for flash operations.
8068 In future, we'll need to decide on a better approach. */
8069static const int remote_flash_timeout = 1000;
8070
8071static void
8072remote_flash_erase (struct target_ops *ops,
8073 ULONGEST address, LONGEST length)
8074{
f5656ead 8075 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
8076 int saved_remote_timeout = remote_timeout;
8077 enum packet_result ret;
a76d924d
DJ
8078 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8079 &saved_remote_timeout);
a744cf53 8080
a76d924d
DJ
8081 remote_timeout = remote_flash_timeout;
8082
8083 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8084 phex (address, addr_size),
a76d924d
DJ
8085 phex (length, 4));
8086 switch (ret)
8087 {
8088 case PACKET_UNKNOWN:
8089 error (_("Remote target does not support flash erase"));
8090 case PACKET_ERROR:
8091 error (_("Error erasing flash with vFlashErase packet"));
8092 default:
8093 break;
8094 }
8095
8096 do_cleanups (back_to);
8097}
8098
9b409511
YQ
8099static enum target_xfer_status
8100remote_flash_write (struct target_ops *ops, ULONGEST address,
8101 ULONGEST length, ULONGEST *xfered_len,
8102 const gdb_byte *data)
a76d924d
DJ
8103{
8104 int saved_remote_timeout = remote_timeout;
9b409511 8105 enum target_xfer_status ret;
a76d924d 8106 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 8107 &saved_remote_timeout);
a76d924d
DJ
8108
8109 remote_timeout = remote_flash_timeout;
124e13d9 8110 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 8111 xfered_len,'X', 0);
a76d924d
DJ
8112 do_cleanups (back_to);
8113
8114 return ret;
8115}
8116
8117static void
8118remote_flash_done (struct target_ops *ops)
8119{
8120 int saved_remote_timeout = remote_timeout;
8121 int ret;
8122 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8123 &saved_remote_timeout);
8124
8125 remote_timeout = remote_flash_timeout;
8126 ret = remote_send_printf ("vFlashDone");
8127 do_cleanups (back_to);
8128
8129 switch (ret)
8130 {
8131 case PACKET_UNKNOWN:
8132 error (_("Remote target does not support vFlashDone"));
8133 case PACKET_ERROR:
8134 error (_("Error finishing flash operation"));
8135 default:
8136 break;
8137 }
8138}
8139
c906108c 8140static void
fba45db2 8141remote_files_info (struct target_ops *ignore)
c906108c
SS
8142{
8143 puts_filtered ("Debugging a target over a serial line.\n");
8144}
8145\f
8146/* Stuff for dealing with the packets which are part of this protocol.
8147 See comment at top of file for details. */
8148
1927e618
PA
8149/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8150 error to higher layers. Called when a serial error is detected.
8151 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8152 the system error message for errno at function entry and final dot
8153 for output compatibility with throw_perror_with_name. */
1927e618
PA
8154
8155static void
8156unpush_and_perror (const char *string)
8157{
d6cb50a2 8158 int saved_errno = errno;
1927e618
PA
8159
8160 remote_unpush_target ();
d6cb50a2
JK
8161 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8162 safe_strerror (saved_errno));
1927e618
PA
8163}
8164
0876f84a 8165/* Read a single character from the remote end. */
c906108c
SS
8166
8167static int
fba45db2 8168readchar (int timeout)
c906108c
SS
8169{
8170 int ch;
5d93a237 8171 struct remote_state *rs = get_remote_state ();
c906108c 8172
5d93a237 8173 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 8174
2acceee2 8175 if (ch >= 0)
0876f84a 8176 return ch;
2acceee2
JM
8177
8178 switch ((enum serial_rc) ch)
c906108c
SS
8179 {
8180 case SERIAL_EOF:
78a095c3 8181 remote_unpush_target ();
598d3636 8182 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8183 /* no return */
c906108c 8184 case SERIAL_ERROR:
1927e618
PA
8185 unpush_and_perror (_("Remote communication error. "
8186 "Target disconnected."));
2acceee2 8187 /* no return */
c906108c 8188 case SERIAL_TIMEOUT:
2acceee2 8189 break;
c906108c 8190 }
2acceee2 8191 return ch;
c906108c
SS
8192}
8193
c33e31fd
PA
8194/* Wrapper for serial_write that closes the target and throws if
8195 writing fails. */
8196
8197static void
8198remote_serial_write (const char *str, int len)
8199{
5d93a237
TT
8200 struct remote_state *rs = get_remote_state ();
8201
8202 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8203 {
1927e618
PA
8204 unpush_and_perror (_("Remote communication error. "
8205 "Target disconnected."));
c33e31fd
PA
8206 }
8207}
8208
6d820c5c
DJ
8209/* Send the command in *BUF to the remote machine, and read the reply
8210 into *BUF. Report an error if we get an error reply. Resize
8211 *BUF using xrealloc if necessary to hold the result, and update
8212 *SIZEOF_BUF. */
c906108c
SS
8213
8214static void
6d820c5c
DJ
8215remote_send (char **buf,
8216 long *sizeof_buf)
c906108c 8217{
6d820c5c 8218 putpkt (*buf);
c2d11a7d 8219 getpkt (buf, sizeof_buf, 0);
c906108c 8220
6d820c5c
DJ
8221 if ((*buf)[0] == 'E')
8222 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8223}
8224
6e5abd65
PA
8225/* Return a pointer to an xmalloc'ed string representing an escaped
8226 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8227 etc. The caller is responsible for releasing the returned
8228 memory. */
8229
8230static char *
8231escape_buffer (const char *buf, int n)
8232{
8233 struct cleanup *old_chain;
8234 struct ui_file *stb;
8235 char *str;
6e5abd65
PA
8236
8237 stb = mem_fileopen ();
8238 old_chain = make_cleanup_ui_file_delete (stb);
8239
6ef284bd 8240 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 8241 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
8242 do_cleanups (old_chain);
8243 return str;
8244}
8245
c906108c
SS
8246/* Display a null-terminated packet on stdout, for debugging, using C
8247 string notation. */
8248
8249static void
baa336ce 8250print_packet (const char *buf)
c906108c
SS
8251{
8252 puts_filtered ("\"");
43e526b9 8253 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8254 puts_filtered ("\"");
8255}
8256
8257int
baa336ce 8258putpkt (const char *buf)
c906108c
SS
8259{
8260 return putpkt_binary (buf, strlen (buf));
8261}
8262
8263/* Send a packet to the remote machine, with error checking. The data
23860348 8264 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8265 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8266 and for a possible /0 if we are debugging (remote_debug) and want
8267 to print the sent packet as a string. */
c906108c
SS
8268
8269static int
baa336ce 8270putpkt_binary (const char *buf, int cnt)
c906108c 8271{
2d717e4f 8272 struct remote_state *rs = get_remote_state ();
c906108c
SS
8273 int i;
8274 unsigned char csum = 0;
224c3ddb 8275 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8276 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8277
c906108c
SS
8278 int ch;
8279 int tcount = 0;
8280 char *p;
8281
e24a49d8
PA
8282 /* Catch cases like trying to read memory or listing threads while
8283 we're waiting for a stop reply. The remote server wouldn't be
8284 ready to handle this request, so we'd hang and timeout. We don't
8285 have to worry about this in synchronous mode, because in that
8286 case it's not possible to issue a command while the target is
74531fed
PA
8287 running. This is not a problem in non-stop mode, because in that
8288 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8289 if (!target_is_non_stop_p ()
8290 && target_is_async_p ()
8291 && rs->waiting_for_stop_reply)
9597b22a
DE
8292 {
8293 error (_("Cannot execute this command while the target is running.\n"
8294 "Use the \"interrupt\" command to stop the target\n"
8295 "and then try again."));
8296 }
e24a49d8 8297
2d717e4f
DJ
8298 /* We're sending out a new packet. Make sure we don't look at a
8299 stale cached response. */
8300 rs->cached_wait_status = 0;
8301
c906108c
SS
8302 /* Copy the packet into buffer BUF2, encapsulating it
8303 and giving it a checksum. */
8304
c906108c
SS
8305 p = buf2;
8306 *p++ = '$';
8307
8308 for (i = 0; i < cnt; i++)
8309 {
8310 csum += buf[i];
8311 *p++ = buf[i];
8312 }
8313 *p++ = '#';
8314 *p++ = tohex ((csum >> 4) & 0xf);
8315 *p++ = tohex (csum & 0xf);
8316
8317 /* Send it over and over until we get a positive ack. */
8318
8319 while (1)
8320 {
8321 int started_error_output = 0;
8322
8323 if (remote_debug)
8324 {
6e5abd65
PA
8325 struct cleanup *old_chain;
8326 char *str;
8327
c906108c 8328 *p = '\0';
6e5abd65
PA
8329 str = escape_buffer (buf2, p - buf2);
8330 old_chain = make_cleanup (xfree, str);
8331 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8332 gdb_flush (gdb_stdlog);
6e5abd65 8333 do_cleanups (old_chain);
c906108c 8334 }
c33e31fd 8335 remote_serial_write (buf2, p - buf2);
c906108c 8336
a6f3e723
SL
8337 /* If this is a no acks version of the remote protocol, send the
8338 packet and move on. */
8339 if (rs->noack_mode)
8340 break;
8341
74531fed
PA
8342 /* Read until either a timeout occurs (-2) or '+' is read.
8343 Handle any notification that arrives in the mean time. */
c906108c
SS
8344 while (1)
8345 {
8346 ch = readchar (remote_timeout);
8347
c5aa993b 8348 if (remote_debug)
c906108c
SS
8349 {
8350 switch (ch)
8351 {
8352 case '+':
1216fa2c 8353 case '-':
c906108c
SS
8354 case SERIAL_TIMEOUT:
8355 case '$':
74531fed 8356 case '%':
c906108c
SS
8357 if (started_error_output)
8358 {
8359 putchar_unfiltered ('\n');
8360 started_error_output = 0;
8361 }
8362 }
8363 }
8364
8365 switch (ch)
8366 {
8367 case '+':
8368 if (remote_debug)
0f71a2f6 8369 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8370 do_cleanups (old_chain);
c906108c 8371 return 1;
1216fa2c
AC
8372 case '-':
8373 if (remote_debug)
8374 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8375 /* FALLTHROUGH */
c906108c 8376 case SERIAL_TIMEOUT:
c5aa993b 8377 tcount++;
c906108c 8378 if (tcount > 3)
a5c0808e
PA
8379 {
8380 do_cleanups (old_chain);
8381 return 0;
8382 }
23860348 8383 break; /* Retransmit buffer. */
c906108c
SS
8384 case '$':
8385 {
40e3f985 8386 if (remote_debug)
2bc416ba 8387 fprintf_unfiltered (gdb_stdlog,
23860348 8388 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8389 /* It's probably an old response sent because an ACK
8390 was lost. Gobble up the packet and ack it so it
8391 doesn't get retransmitted when we resend this
8392 packet. */
6d820c5c 8393 skip_frame ();
c33e31fd 8394 remote_serial_write ("+", 1);
23860348 8395 continue; /* Now, go look for +. */
c906108c 8396 }
74531fed
PA
8397
8398 case '%':
8399 {
8400 int val;
8401
8402 /* If we got a notification, handle it, and go back to looking
8403 for an ack. */
8404 /* We've found the start of a notification. Now
8405 collect the data. */
8406 val = read_frame (&rs->buf, &rs->buf_size);
8407 if (val >= 0)
8408 {
8409 if (remote_debug)
8410 {
6e5abd65
PA
8411 struct cleanup *old_chain;
8412 char *str;
8413
8414 str = escape_buffer (rs->buf, val);
8415 old_chain = make_cleanup (xfree, str);
8416 fprintf_unfiltered (gdb_stdlog,
8417 " Notification received: %s\n",
8418 str);
8419 do_cleanups (old_chain);
74531fed 8420 }
5965e028 8421 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8422 /* We're in sync now, rewait for the ack. */
8423 tcount = 0;
8424 }
8425 else
8426 {
8427 if (remote_debug)
8428 {
8429 if (!started_error_output)
8430 {
8431 started_error_output = 1;
8432 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8433 }
8434 fputc_unfiltered (ch & 0177, gdb_stdlog);
8435 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8436 }
8437 }
8438 continue;
8439 }
8440 /* fall-through */
c906108c
SS
8441 default:
8442 if (remote_debug)
8443 {
8444 if (!started_error_output)
8445 {
8446 started_error_output = 1;
0f71a2f6 8447 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8448 }
0f71a2f6 8449 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8450 }
8451 continue;
8452 }
23860348 8453 break; /* Here to retransmit. */
c906108c
SS
8454 }
8455
8456#if 0
8457 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8458 able to get out next time we call QUIT, without anything as
8459 violent as interrupt_query. If we want to provide a way out of
8460 here without getting to the next QUIT, it should be based on
8461 hitting ^C twice as in remote_wait. */
c906108c
SS
8462 if (quit_flag)
8463 {
8464 quit_flag = 0;
8465 interrupt_query ();
8466 }
8467#endif
8468 }
a5c0808e
PA
8469
8470 do_cleanups (old_chain);
a6f3e723 8471 return 0;
c906108c
SS
8472}
8473
6d820c5c
DJ
8474/* Come here after finding the start of a frame when we expected an
8475 ack. Do our best to discard the rest of this packet. */
8476
8477static void
8478skip_frame (void)
8479{
8480 int c;
8481
8482 while (1)
8483 {
8484 c = readchar (remote_timeout);
8485 switch (c)
8486 {
8487 case SERIAL_TIMEOUT:
8488 /* Nothing we can do. */
8489 return;
8490 case '#':
8491 /* Discard the two bytes of checksum and stop. */
8492 c = readchar (remote_timeout);
8493 if (c >= 0)
8494 c = readchar (remote_timeout);
8495
8496 return;
8497 case '*': /* Run length encoding. */
8498 /* Discard the repeat count. */
8499 c = readchar (remote_timeout);
8500 if (c < 0)
8501 return;
8502 break;
8503 default:
8504 /* A regular character. */
8505 break;
8506 }
8507 }
8508}
8509
c906108c 8510/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8511 into *BUF, verifying the checksum, length, and handling run-length
8512 compression. NUL terminate the buffer. If there is not enough room,
8513 expand *BUF using xrealloc.
c906108c 8514
c2d11a7d
JM
8515 Returns -1 on error, number of characters in buffer (ignoring the
8516 trailing NULL) on success. (could be extended to return one of the
23860348 8517 SERIAL status indications). */
c2d11a7d
JM
8518
8519static long
6d820c5c
DJ
8520read_frame (char **buf_p,
8521 long *sizeof_buf)
c906108c
SS
8522{
8523 unsigned char csum;
c2d11a7d 8524 long bc;
c906108c 8525 int c;
6d820c5c 8526 char *buf = *buf_p;
a6f3e723 8527 struct remote_state *rs = get_remote_state ();
c906108c
SS
8528
8529 csum = 0;
c2d11a7d 8530 bc = 0;
c906108c
SS
8531
8532 while (1)
8533 {
8534 c = readchar (remote_timeout);
c906108c
SS
8535 switch (c)
8536 {
8537 case SERIAL_TIMEOUT:
8538 if (remote_debug)
0f71a2f6 8539 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8540 return -1;
c906108c
SS
8541 case '$':
8542 if (remote_debug)
0f71a2f6
JM
8543 fputs_filtered ("Saw new packet start in middle of old one\n",
8544 gdb_stdlog);
23860348 8545 return -1; /* Start a new packet, count retries. */
c906108c
SS
8546 case '#':
8547 {
8548 unsigned char pktcsum;
e1b09194
AC
8549 int check_0 = 0;
8550 int check_1 = 0;
c906108c 8551
c2d11a7d 8552 buf[bc] = '\0';
c906108c 8553
e1b09194
AC
8554 check_0 = readchar (remote_timeout);
8555 if (check_0 >= 0)
8556 check_1 = readchar (remote_timeout);
802188a7 8557
e1b09194
AC
8558 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8559 {
8560 if (remote_debug)
2bc416ba 8561 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8562 gdb_stdlog);
e1b09194
AC
8563 return -1;
8564 }
8565 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8566 {
8567 if (remote_debug)
2bc416ba 8568 fputs_filtered ("Communication error in checksum\n",
23860348 8569 gdb_stdlog);
40e3f985
FN
8570 return -1;
8571 }
c906108c 8572
a6f3e723
SL
8573 /* Don't recompute the checksum; with no ack packets we
8574 don't have any way to indicate a packet retransmission
8575 is necessary. */
8576 if (rs->noack_mode)
8577 return bc;
8578
e1b09194 8579 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8580 if (csum == pktcsum)
c2d11a7d 8581 return bc;
c906108c 8582
c5aa993b 8583 if (remote_debug)
c906108c 8584 {
6e5abd65
PA
8585 struct cleanup *old_chain;
8586 char *str;
8587
8588 str = escape_buffer (buf, bc);
8589 old_chain = make_cleanup (xfree, str);
8590 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8591 "Bad checksum, sentsum=0x%x, "
8592 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8593 pktcsum, csum, str);
8594 do_cleanups (old_chain);
c906108c 8595 }
c2d11a7d 8596 /* Number of characters in buffer ignoring trailing
23860348 8597 NULL. */
c2d11a7d 8598 return -1;
c906108c 8599 }
23860348 8600 case '*': /* Run length encoding. */
c2c6d25f
JM
8601 {
8602 int repeat;
c906108c 8603
a744cf53 8604 csum += c;
b4501125
AC
8605 c = readchar (remote_timeout);
8606 csum += c;
23860348 8607 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8608
23860348 8609 /* The character before ``*'' is repeated. */
c2d11a7d 8610
6d820c5c 8611 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8612 {
6d820c5c
DJ
8613 if (bc + repeat - 1 >= *sizeof_buf - 1)
8614 {
8615 /* Make some more room in the buffer. */
8616 *sizeof_buf += repeat;
224c3ddb 8617 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
8618 buf = *buf_p;
8619 }
8620
c2d11a7d
JM
8621 memset (&buf[bc], buf[bc - 1], repeat);
8622 bc += repeat;
c2c6d25f
JM
8623 continue;
8624 }
8625
c2d11a7d 8626 buf[bc] = '\0';
6d820c5c 8627 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8628 return -1;
c2c6d25f 8629 }
c906108c 8630 default:
6d820c5c 8631 if (bc >= *sizeof_buf - 1)
c906108c 8632 {
6d820c5c
DJ
8633 /* Make some more room in the buffer. */
8634 *sizeof_buf *= 2;
224c3ddb 8635 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 8636 buf = *buf_p;
c906108c
SS
8637 }
8638
6d820c5c
DJ
8639 buf[bc++] = c;
8640 csum += c;
8641 continue;
c906108c
SS
8642 }
8643 }
8644}
8645
8646/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8647 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8648 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8649 rather than timing out; this is used (in synchronous mode) to wait
8650 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8651/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8652 don't have to change all the calls to getpkt to deal with the
8653 return value, because at the moment I don't know what the right
23860348 8654 thing to do it for those. */
c906108c 8655void
6d820c5c
DJ
8656getpkt (char **buf,
8657 long *sizeof_buf,
c2d11a7d 8658 int forever)
d9fcf2fb 8659{
54887903 8660 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
8661}
8662
8663
8664/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8665 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8666 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8667 rather than timing out; this is used (in synchronous mode) to wait
8668 for a target that is is executing user code to stop. If FOREVER ==
8669 0, this function is allowed to time out gracefully and return an
74531fed
PA
8670 indication of this to the caller. Otherwise return the number of
8671 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8672 enough reason to return to the caller. *IS_NOTIF is an output
8673 boolean that indicates whether *BUF holds a notification or not
8674 (a regular packet). */
74531fed 8675
3172dc30 8676static int
74531fed 8677getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8678 int expecting_notif, int *is_notif)
c906108c 8679{
2d717e4f 8680 struct remote_state *rs = get_remote_state ();
c906108c
SS
8681 int c;
8682 int tries;
8683 int timeout;
df4b58fe 8684 int val = -1;
c906108c 8685
2d717e4f
DJ
8686 /* We're reading a new response. Make sure we don't look at a
8687 previously cached response. */
8688 rs->cached_wait_status = 0;
8689
6d820c5c 8690 strcpy (*buf, "timeout");
c906108c
SS
8691
8692 if (forever)
74531fed
PA
8693 timeout = watchdog > 0 ? watchdog : -1;
8694 else if (expecting_notif)
8695 timeout = 0; /* There should already be a char in the buffer. If
8696 not, bail out. */
c906108c
SS
8697 else
8698 timeout = remote_timeout;
8699
8700#define MAX_TRIES 3
8701
74531fed
PA
8702 /* Process any number of notifications, and then return when
8703 we get a packet. */
8704 for (;;)
c906108c 8705 {
d9c43928 8706 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8707 times. */
8708 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8709 {
74531fed
PA
8710 /* This can loop forever if the remote side sends us
8711 characters continuously, but if it pauses, we'll get
8712 SERIAL_TIMEOUT from readchar because of timeout. Then
8713 we'll count that as a retry.
8714
8715 Note that even when forever is set, we will only wait
8716 forever prior to the start of a packet. After that, we
8717 expect characters to arrive at a brisk pace. They should
8718 show up within remote_timeout intervals. */
8719 do
8720 c = readchar (timeout);
8721 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8722
8723 if (c == SERIAL_TIMEOUT)
8724 {
74531fed
PA
8725 if (expecting_notif)
8726 return -1; /* Don't complain, it's normal to not get
8727 anything in this case. */
8728
23860348 8729 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8730 {
2acceee2 8731 QUIT;
78a095c3 8732 remote_unpush_target ();
598d3636
JK
8733 throw_error (TARGET_CLOSE_ERROR,
8734 _("Watchdog timeout has expired. "
8735 "Target detached."));
c906108c 8736 }
c906108c 8737 if (remote_debug)
0f71a2f6 8738 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8739 }
74531fed
PA
8740 else
8741 {
8742 /* We've found the start of a packet or notification.
8743 Now collect the data. */
8744 val = read_frame (buf, sizeof_buf);
8745 if (val >= 0)
8746 break;
8747 }
8748
c33e31fd 8749 remote_serial_write ("-", 1);
c906108c 8750 }
c906108c 8751
74531fed
PA
8752 if (tries > MAX_TRIES)
8753 {
8754 /* We have tried hard enough, and just can't receive the
8755 packet/notification. Give up. */
8756 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8757
74531fed
PA
8758 /* Skip the ack char if we're in no-ack mode. */
8759 if (!rs->noack_mode)
c33e31fd 8760 remote_serial_write ("+", 1);
74531fed
PA
8761 return -1;
8762 }
c906108c 8763
74531fed
PA
8764 /* If we got an ordinary packet, return that to our caller. */
8765 if (c == '$')
c906108c
SS
8766 {
8767 if (remote_debug)
43e526b9 8768 {
6e5abd65
PA
8769 struct cleanup *old_chain;
8770 char *str;
8771
8772 str = escape_buffer (*buf, val);
8773 old_chain = make_cleanup (xfree, str);
8774 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8775 do_cleanups (old_chain);
43e526b9 8776 }
a6f3e723
SL
8777
8778 /* Skip the ack char if we're in no-ack mode. */
8779 if (!rs->noack_mode)
c33e31fd 8780 remote_serial_write ("+", 1);
fee9eda9
YQ
8781 if (is_notif != NULL)
8782 *is_notif = 0;
0876f84a 8783 return val;
c906108c
SS
8784 }
8785
74531fed
PA
8786 /* If we got a notification, handle it, and go back to looking
8787 for a packet. */
8788 else
8789 {
8790 gdb_assert (c == '%');
8791
8792 if (remote_debug)
8793 {
6e5abd65
PA
8794 struct cleanup *old_chain;
8795 char *str;
8796
8797 str = escape_buffer (*buf, val);
8798 old_chain = make_cleanup (xfree, str);
8799 fprintf_unfiltered (gdb_stdlog,
8800 " Notification received: %s\n",
8801 str);
8802 do_cleanups (old_chain);
74531fed 8803 }
fee9eda9
YQ
8804 if (is_notif != NULL)
8805 *is_notif = 1;
c906108c 8806
5965e028 8807 handle_notification (rs->notif_state, *buf);
c906108c 8808
74531fed 8809 /* Notifications require no acknowledgement. */
a6f3e723 8810
74531fed 8811 if (expecting_notif)
fee9eda9 8812 return val;
74531fed
PA
8813 }
8814 }
8815}
8816
8817static int
8818getpkt_sane (char **buf, long *sizeof_buf, int forever)
8819{
fee9eda9 8820 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8821}
8822
8823static int
fee9eda9
YQ
8824getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8825 int *is_notif)
74531fed 8826{
fee9eda9
YQ
8827 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8828 is_notif);
c906108c 8829}
74531fed 8830
cbb8991c
DB
8831/* Check whether EVENT is a fork event for the process specified
8832 by the pid passed in DATA, and if it is, kill the fork child. */
8833
8834static int
8835kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8836 QUEUE_ITER (stop_reply_p) *iter,
8837 stop_reply_p event,
8838 void *data)
8839{
19ba03f4 8840 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
8841 int parent_pid = *(int *) param->input;
8842
8843 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8844 {
8845 struct remote_state *rs = get_remote_state ();
8846 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8847 int res;
8848
8849 res = remote_vkill (child_pid, rs);
8850 if (res != 0)
8851 error (_("Can't kill fork child process %d"), child_pid);
8852 }
8853
8854 return 1;
8855}
8856
8857/* Kill any new fork children of process PID that haven't been
8858 processed by follow_fork. */
8859
8860static void
8861kill_new_fork_children (int pid, struct remote_state *rs)
8862{
8863 struct thread_info *thread;
8864 struct notif_client *notif = &notif_client_stop;
8865 struct queue_iter_param param;
8866
8867 /* Kill the fork child threads of any threads in process PID
8868 that are stopped at a fork event. */
8869 ALL_NON_EXITED_THREADS (thread)
8870 {
8871 struct target_waitstatus *ws = &thread->pending_follow;
8872
8873 if (is_pending_fork_parent (ws, pid, thread->ptid))
8874 {
8875 struct remote_state *rs = get_remote_state ();
8876 int child_pid = ptid_get_pid (ws->value.related_pid);
8877 int res;
8878
8879 res = remote_vkill (child_pid, rs);
8880 if (res != 0)
8881 error (_("Can't kill fork child process %d"), child_pid);
8882 }
8883 }
8884
8885 /* Check for any pending fork events (not reported or processed yet)
8886 in process PID and kill those fork child threads as well. */
8887 remote_notif_get_pending_events (notif);
8888 param.input = &pid;
8889 param.output = NULL;
8890 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8891 kill_child_of_pending_fork, &param);
8892}
8893
c906108c 8894\f
8020350c
DB
8895/* Target hook to kill the current inferior. */
8896
c906108c 8897static void
7d85a9c0 8898remote_kill (struct target_ops *ops)
43ff13b4 8899{
8020350c
DB
8900 int res = -1;
8901 int pid = ptid_get_pid (inferior_ptid);
8902 struct remote_state *rs = get_remote_state ();
0fdf84ca 8903
8020350c 8904 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 8905 {
8020350c
DB
8906 /* If we're stopped while forking and we haven't followed yet,
8907 kill the child task. We need to do this before killing the
8908 parent task because if this is a vfork then the parent will
8909 be sleeping. */
8910 kill_new_fork_children (pid, rs);
8911
8912 res = remote_vkill (pid, rs);
8913 if (res == 0)
0fdf84ca 8914 {
8020350c 8915 target_mourn_inferior ();
0fdf84ca
PA
8916 return;
8917 }
8020350c 8918 }
0fdf84ca 8919
8020350c
DB
8920 /* If we are in 'target remote' mode and we are killing the only
8921 inferior, then we will tell gdbserver to exit and unpush the
8922 target. */
8923 if (res == -1 && !remote_multi_process_p (rs)
8924 && number_of_live_inferiors () == 1)
8925 {
8926 remote_kill_k ();
8927
8928 /* We've killed the remote end, we get to mourn it. If we are
8929 not in extended mode, mourning the inferior also unpushes
8930 remote_ops from the target stack, which closes the remote
8931 connection. */
8932 target_mourn_inferior ();
8933
8934 return;
0fdf84ca 8935 }
43ff13b4 8936
8020350c 8937 error (_("Can't kill process"));
43ff13b4
JM
8938}
8939
8020350c
DB
8940/* Send a kill request to the target using the 'vKill' packet. */
8941
82f73884
PA
8942static int
8943remote_vkill (int pid, struct remote_state *rs)
8944{
4082afcc 8945 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8946 return -1;
8947
8948 /* Tell the remote target to detach. */
bba74b36 8949 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8950 putpkt (rs->buf);
8951 getpkt (&rs->buf, &rs->buf_size, 0);
8952
4082afcc
PA
8953 switch (packet_ok (rs->buf,
8954 &remote_protocol_packets[PACKET_vKill]))
8955 {
8956 case PACKET_OK:
8957 return 0;
8958 case PACKET_ERROR:
8959 return 1;
8960 case PACKET_UNKNOWN:
8961 return -1;
8962 default:
8963 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8964 }
82f73884
PA
8965}
8966
8020350c
DB
8967/* Send a kill request to the target using the 'k' packet. */
8968
82f73884 8969static void
8020350c 8970remote_kill_k (void)
82f73884 8971{
8020350c
DB
8972 /* Catch errors so the user can quit from gdb even when we
8973 aren't on speaking terms with the remote system. */
8974 TRY
82f73884 8975 {
82f73884 8976 putpkt ("k");
82f73884 8977 }
8020350c
DB
8978 CATCH (ex, RETURN_MASK_ERROR)
8979 {
8980 if (ex.error == TARGET_CLOSE_ERROR)
8981 {
8982 /* If we got an (EOF) error that caused the target
8983 to go away, then we're done, that's what we wanted.
8984 "k" is susceptible to cause a premature EOF, given
8985 that the remote server isn't actually required to
8986 reply to "k", and it can happen that it doesn't
8987 even get to reply ACK to the "k". */
8988 return;
8989 }
82f73884 8990
8020350c
DB
8991 /* Otherwise, something went wrong. We didn't actually kill
8992 the target. Just propagate the exception, and let the
8993 user or higher layers decide what to do. */
8994 throw_exception (ex);
8995 }
8996 END_CATCH
82f73884
PA
8997}
8998
c906108c 8999static void
20f796c9 9000remote_mourn (struct target_ops *target)
c906108c 9001{
8020350c 9002 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9003
8020350c
DB
9004 /* In 'target remote' mode with one inferior, we close the connection. */
9005 if (!rs->extended && number_of_live_inferiors () <= 1)
9006 {
9007 unpush_target (target);
c906108c 9008
8020350c
DB
9009 /* remote_close takes care of doing most of the clean up. */
9010 generic_mourn_inferior ();
9011 return;
9012 }
c906108c 9013
e24a49d8
PA
9014 /* In case we got here due to an error, but we're going to stay
9015 connected. */
9016 rs->waiting_for_stop_reply = 0;
9017
dc1981d7
PA
9018 /* If the current general thread belonged to the process we just
9019 detached from or has exited, the remote side current general
9020 thread becomes undefined. Considering a case like this:
9021
9022 - We just got here due to a detach.
9023 - The process that we're detaching from happens to immediately
9024 report a global breakpoint being hit in non-stop mode, in the
9025 same thread we had selected before.
9026 - GDB attaches to this process again.
9027 - This event happens to be the next event we handle.
9028
9029 GDB would consider that the current general thread didn't need to
9030 be set on the stub side (with Hg), since for all it knew,
9031 GENERAL_THREAD hadn't changed.
9032
9033 Notice that although in all-stop mode, the remote server always
9034 sets the current thread to the thread reporting the stop event,
9035 that doesn't happen in non-stop mode; in non-stop, the stub *must
9036 not* change the current thread when reporting a breakpoint hit,
9037 due to the decoupling of event reporting and event handling.
9038
9039 To keep things simple, we always invalidate our notion of the
9040 current thread. */
47f8a51d 9041 record_currthread (rs, minus_one_ptid);
dc1981d7 9042
8020350c 9043 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9044 generic_mourn_inferior ();
9045
d729566a 9046 if (!have_inferiors ())
2d717e4f 9047 {
82f73884
PA
9048 if (!remote_multi_process_p (rs))
9049 {
9050 /* Check whether the target is running now - some remote stubs
9051 automatically restart after kill. */
9052 putpkt ("?");
9053 getpkt (&rs->buf, &rs->buf_size, 0);
9054
9055 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9056 {
3e43a32a
MS
9057 /* Assume that the target has been restarted. Set
9058 inferior_ptid so that bits of core GDB realizes
9059 there's something here, e.g., so that the user can
9060 say "kill" again. */
82f73884
PA
9061 inferior_ptid = magic_null_ptid;
9062 }
82f73884 9063 }
2d717e4f
DJ
9064 }
9065}
c906108c 9066
03583c20 9067static int
2bfc0540 9068extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 9069{
4082afcc 9070 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9071}
9072
9073static void
9074extended_remote_disable_randomization (int val)
9075{
9076 struct remote_state *rs = get_remote_state ();
9077 char *reply;
9078
bba74b36
YQ
9079 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9080 val);
03583c20
UW
9081 putpkt (rs->buf);
9082 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9083 if (*reply == '\0')
9084 error (_("Target does not support QDisableRandomization."));
9085 if (strcmp (reply, "OK") != 0)
9086 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9087}
9088
2d717e4f
DJ
9089static int
9090extended_remote_run (char *args)
9091{
9092 struct remote_state *rs = get_remote_state ();
2d717e4f 9093 int len;
94585166 9094 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9095
2d717e4f
DJ
9096 /* If the user has disabled vRun support, or we have detected that
9097 support is not available, do not try it. */
4082afcc 9098 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9099 return -1;
424163ea 9100
2d717e4f
DJ
9101 strcpy (rs->buf, "vRun;");
9102 len = strlen (rs->buf);
c906108c 9103
2d717e4f
DJ
9104 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9105 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9106 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9107 strlen (remote_exec_file));
2d717e4f 9108
d1a41061 9109 gdb_assert (args != NULL);
2d717e4f
DJ
9110 if (*args)
9111 {
9112 struct cleanup *back_to;
9113 int i;
9114 char **argv;
9115
d1a41061 9116 argv = gdb_buildargv (args);
6e366df1 9117 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
9118 for (i = 0; argv[i] != NULL; i++)
9119 {
9120 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9121 error (_("Argument list too long for run packet"));
9122 rs->buf[len++] = ';';
9f1b45b0
TT
9123 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9124 strlen (argv[i]));
2d717e4f
DJ
9125 }
9126 do_cleanups (back_to);
9127 }
9128
9129 rs->buf[len++] = '\0';
9130
9131 putpkt (rs->buf);
9132 getpkt (&rs->buf, &rs->buf_size, 0);
9133
4082afcc 9134 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9135 {
4082afcc 9136 case PACKET_OK:
3405876a 9137 /* We have a wait response. All is well. */
2d717e4f 9138 return 0;
4082afcc
PA
9139 case PACKET_UNKNOWN:
9140 return -1;
9141 case PACKET_ERROR:
2d717e4f
DJ
9142 if (remote_exec_file[0] == '\0')
9143 error (_("Running the default executable on the remote target failed; "
9144 "try \"set remote exec-file\"?"));
9145 else
9146 error (_("Running \"%s\" on the remote target failed"),
9147 remote_exec_file);
4082afcc
PA
9148 default:
9149 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9150 }
c906108c
SS
9151}
9152
2d717e4f
DJ
9153/* In the extended protocol we want to be able to do things like
9154 "run" and have them basically work as expected. So we need
9155 a special create_inferior function. We support changing the
9156 executable file and the command line arguments, but not the
9157 environment. */
9158
43ff13b4 9159static void
77a19445
TT
9160extended_remote_create_inferior (struct target_ops *ops,
9161 char *exec_file, char *args,
9162 char **env, int from_tty)
43ff13b4 9163{
3405876a
PA
9164 int run_worked;
9165 char *stop_reply;
9166 struct remote_state *rs = get_remote_state ();
94585166 9167 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9168
43ff13b4 9169 /* If running asynchronously, register the target file descriptor
23860348 9170 with the event loop. */
75c99385 9171 if (target_can_async_p ())
6a3753b3 9172 target_async (1);
43ff13b4 9173
03583c20 9174 /* Disable address space randomization if requested (and supported). */
2bfc0540 9175 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9176 extended_remote_disable_randomization (disable_randomization);
9177
43ff13b4 9178 /* Now restart the remote server. */
3405876a
PA
9179 run_worked = extended_remote_run (args) != -1;
9180 if (!run_worked)
2d717e4f
DJ
9181 {
9182 /* vRun was not supported. Fail if we need it to do what the
9183 user requested. */
9184 if (remote_exec_file[0])
9185 error (_("Remote target does not support \"set remote exec-file\""));
9186 if (args[0])
9187 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9188
2d717e4f
DJ
9189 /* Fall back to "R". */
9190 extended_remote_restart ();
9191 }
424163ea 9192
6c95b8df
PA
9193 if (!have_inferiors ())
9194 {
9195 /* Clean up from the last time we ran, before we mark the target
9196 running again. This will mark breakpoints uninserted, and
9197 get_offsets may insert breakpoints. */
9198 init_thread_list ();
9199 init_wait_for_inferior ();
9200 }
45280a52 9201
3405876a
PA
9202 /* vRun's success return is a stop reply. */
9203 stop_reply = run_worked ? rs->buf : NULL;
9204 add_current_inferior_and_thread (stop_reply);
c0a2216e 9205
2d717e4f
DJ
9206 /* Get updated offsets, if the stub uses qOffsets. */
9207 get_offsets ();
2d717e4f 9208}
c906108c 9209\f
c5aa993b 9210
b775012e
LM
9211/* Given a location's target info BP_TGT and the packet buffer BUF, output
9212 the list of conditions (in agent expression bytecode format), if any, the
9213 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9214 started from BUF and ended at BUF_END. */
b775012e
LM
9215
9216static int
9217remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9218 struct bp_target_info *bp_tgt, char *buf,
9219 char *buf_end)
b775012e
LM
9220{
9221 struct agent_expr *aexpr = NULL;
9222 int i, ix;
b775012e
LM
9223
9224 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9225 return 0;
9226
9227 buf += strlen (buf);
bba74b36 9228 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9229 buf++;
9230
9231 /* Send conditions to the target and free the vector. */
9232 for (ix = 0;
9233 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9234 ix++)
9235 {
bba74b36 9236 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
9237 buf += strlen (buf);
9238 for (i = 0; i < aexpr->len; ++i)
9239 buf = pack_hex_byte (buf, aexpr->buf[i]);
9240 *buf = '\0';
9241 }
b775012e
LM
9242 return 0;
9243}
9244
d3ce09f5
SS
9245static void
9246remote_add_target_side_commands (struct gdbarch *gdbarch,
9247 struct bp_target_info *bp_tgt, char *buf)
9248{
9249 struct agent_expr *aexpr = NULL;
9250 int i, ix;
9251
9252 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9253 return;
9254
9255 buf += strlen (buf);
9256
9257 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9258 buf += strlen (buf);
9259
9260 /* Concatenate all the agent expressions that are commands into the
9261 cmds parameter. */
9262 for (ix = 0;
9263 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9264 ix++)
9265 {
9266 sprintf (buf, "X%x,", aexpr->len);
9267 buf += strlen (buf);
9268 for (i = 0; i < aexpr->len; ++i)
9269 buf = pack_hex_byte (buf, aexpr->buf[i]);
9270 *buf = '\0';
9271 }
d3ce09f5
SS
9272}
9273
8181d85f
DJ
9274/* Insert a breakpoint. On targets that have software breakpoint
9275 support, we ask the remote target to do the work; on targets
9276 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9277
9278static int
3db08215
MM
9279remote_insert_breakpoint (struct target_ops *ops,
9280 struct gdbarch *gdbarch,
a6d9a66e 9281 struct bp_target_info *bp_tgt)
c906108c 9282{
d471ea57
AC
9283 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9284 If it succeeds, then set the support to PACKET_ENABLE. If it
9285 fails, and the user has explicitly requested the Z support then
23860348 9286 report an error, otherwise, mark it disabled and go on. */
802188a7 9287
4082afcc 9288 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9289 {
0d5ed153 9290 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9291 struct remote_state *rs;
bba74b36 9292 char *p, *endbuf;
7c0f6dcc 9293 int bpsize;
4fff2411 9294
28439a30
PA
9295 /* Make sure the remote is pointing at the right process, if
9296 necessary. */
9297 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9298 set_general_process ();
9299
a1dcb23a 9300 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
9301
9302 rs = get_remote_state ();
9303 p = rs->buf;
bba74b36 9304 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9305
96baa820
JM
9306 *(p++) = 'Z';
9307 *(p++) = '0';
9308 *(p++) = ',';
7c0f6dcc 9309 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9310 p += hexnumstr (p, addr);
bba74b36 9311 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 9312
efcc2da7 9313 if (remote_supports_cond_breakpoints (ops))
bba74b36 9314 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9315
78eff0ec 9316 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9317 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9318
6d820c5c
DJ
9319 putpkt (rs->buf);
9320 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9321
6d820c5c 9322 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9323 {
d471ea57
AC
9324 case PACKET_ERROR:
9325 return -1;
9326 case PACKET_OK:
7c0f6dcc
JL
9327 bp_tgt->placed_address = addr;
9328 bp_tgt->placed_size = bpsize;
d471ea57
AC
9329 return 0;
9330 case PACKET_UNKNOWN:
9331 break;
96baa820
JM
9332 }
9333 }
c906108c 9334
0000e5cc
PA
9335 /* If this breakpoint has target-side commands but this stub doesn't
9336 support Z0 packets, throw error. */
9337 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9338 throw_error (NOT_SUPPORTED_ERROR, _("\
9339Target doesn't support breakpoints that have target side commands."));
9340
3db08215 9341 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9342}
9343
9344static int
3db08215
MM
9345remote_remove_breakpoint (struct target_ops *ops,
9346 struct gdbarch *gdbarch,
a6d9a66e 9347 struct bp_target_info *bp_tgt)
c906108c 9348{
8181d85f 9349 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9350 struct remote_state *rs = get_remote_state ();
96baa820 9351
4082afcc 9352 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9353 {
6d820c5c 9354 char *p = rs->buf;
bba74b36 9355 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9356
28439a30
PA
9357 /* Make sure the remote is pointing at the right process, if
9358 necessary. */
9359 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9360 set_general_process ();
9361
96baa820
JM
9362 *(p++) = 'z';
9363 *(p++) = '0';
9364 *(p++) = ',';
9365
8181d85f
DJ
9366 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9367 p += hexnumstr (p, addr);
bba74b36 9368 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9369
6d820c5c
DJ
9370 putpkt (rs->buf);
9371 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9372
6d820c5c 9373 return (rs->buf[0] == 'E');
96baa820
JM
9374 }
9375
3db08215 9376 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9377}
9378
f486487f 9379static enum Z_packet_type
d471ea57
AC
9380watchpoint_to_Z_packet (int type)
9381{
9382 switch (type)
9383 {
9384 case hw_write:
bb858e6a 9385 return Z_PACKET_WRITE_WP;
d471ea57
AC
9386 break;
9387 case hw_read:
bb858e6a 9388 return Z_PACKET_READ_WP;
d471ea57
AC
9389 break;
9390 case hw_access:
bb858e6a 9391 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9392 break;
9393 default:
8e65ff28 9394 internal_error (__FILE__, __LINE__,
e2e0b3e5 9395 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9396 }
9397}
9398
3c3bea1c 9399static int
f486487f
SM
9400remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9401 enum target_hw_bp_type type, struct expression *cond)
96baa820 9402{
d01949b6 9403 struct remote_state *rs = get_remote_state ();
bba74b36 9404 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9405 char *p;
d471ea57 9406 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9407
4082afcc 9408 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9409 return 1;
802188a7 9410
28439a30
PA
9411 /* Make sure the remote is pointing at the right process, if
9412 necessary. */
9413 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9414 set_general_process ();
9415
bba74b36 9416 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9417 p = strchr (rs->buf, '\0');
96baa820
JM
9418 addr = remote_address_masked (addr);
9419 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9420 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9421
6d820c5c
DJ
9422 putpkt (rs->buf);
9423 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9424
6d820c5c 9425 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9426 {
9427 case PACKET_ERROR:
d471ea57 9428 return -1;
85d721b8
PA
9429 case PACKET_UNKNOWN:
9430 return 1;
d471ea57
AC
9431 case PACKET_OK:
9432 return 0;
9433 }
8e65ff28 9434 internal_error (__FILE__, __LINE__,
e2e0b3e5 9435 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9436}
9437
283002cf
MR
9438static int
9439remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9440 CORE_ADDR start, int length)
9441{
9442 CORE_ADDR diff = remote_address_masked (addr - start);
9443
9444 return diff < length;
9445}
9446
d471ea57 9447
3c3bea1c 9448static int
f486487f
SM
9449remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9450 enum target_hw_bp_type type, struct expression *cond)
96baa820 9451{
d01949b6 9452 struct remote_state *rs = get_remote_state ();
bba74b36 9453 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9454 char *p;
d471ea57
AC
9455 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9456
4082afcc 9457 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9458 return -1;
802188a7 9459
28439a30
PA
9460 /* Make sure the remote is pointing at the right process, if
9461 necessary. */
9462 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9463 set_general_process ();
9464
bba74b36 9465 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9466 p = strchr (rs->buf, '\0');
96baa820
JM
9467 addr = remote_address_masked (addr);
9468 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9469 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9470 putpkt (rs->buf);
9471 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9472
6d820c5c 9473 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9474 {
9475 case PACKET_ERROR:
9476 case PACKET_UNKNOWN:
9477 return -1;
9478 case PACKET_OK:
9479 return 0;
9480 }
8e65ff28 9481 internal_error (__FILE__, __LINE__,
e2e0b3e5 9482 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9483}
9484
3c3bea1c 9485
501eef12 9486int remote_hw_watchpoint_limit = -1;
480a3f21 9487int remote_hw_watchpoint_length_limit = -1;
501eef12 9488int remote_hw_breakpoint_limit = -1;
d471ea57 9489
480a3f21 9490static int
31568a15
TT
9491remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9492 CORE_ADDR addr, int len)
480a3f21
PW
9493{
9494 if (remote_hw_watchpoint_length_limit == 0)
9495 return 0;
9496 else if (remote_hw_watchpoint_length_limit < 0)
9497 return 1;
9498 else if (len <= remote_hw_watchpoint_length_limit)
9499 return 1;
9500 else
9501 return 0;
9502}
9503
b9362cc7 9504static int
5461485a 9505remote_check_watch_resources (struct target_ops *self,
f486487f 9506 enum bptype type, int cnt, int ot)
96baa820 9507{
3c3bea1c
GS
9508 if (type == bp_hardware_breakpoint)
9509 {
9510 if (remote_hw_breakpoint_limit == 0)
9511 return 0;
501eef12
AC
9512 else if (remote_hw_breakpoint_limit < 0)
9513 return 1;
3c3bea1c
GS
9514 else if (cnt <= remote_hw_breakpoint_limit)
9515 return 1;
9516 }
9517 else
9518 {
9519 if (remote_hw_watchpoint_limit == 0)
9520 return 0;
501eef12
AC
9521 else if (remote_hw_watchpoint_limit < 0)
9522 return 1;
3c3bea1c
GS
9523 else if (ot)
9524 return -1;
9525 else if (cnt <= remote_hw_watchpoint_limit)
9526 return 1;
9527 }
9528 return -1;
9529}
9530
f7e6eed5
PA
9531/* The to_stopped_by_sw_breakpoint method of target remote. */
9532
9533static int
9534remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9535{
799a2abe 9536 struct thread_info *thread = inferior_thread ();
f7e6eed5 9537
799a2abe
PA
9538 return (thread->priv != NULL
9539 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9540}
9541
9542/* The to_supports_stopped_by_sw_breakpoint method of target
9543 remote. */
9544
9545static int
9546remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9547{
f7e6eed5
PA
9548 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9549}
9550
9551/* The to_stopped_by_hw_breakpoint method of target remote. */
9552
9553static int
9554remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9555{
799a2abe 9556 struct thread_info *thread = inferior_thread ();
f7e6eed5 9557
799a2abe
PA
9558 return (thread->priv != NULL
9559 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9560}
9561
9562/* The to_supports_stopped_by_hw_breakpoint method of target
9563 remote. */
9564
9565static int
9566remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9567{
f7e6eed5
PA
9568 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9569}
9570
b9362cc7 9571static int
6a109b6b 9572remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9573{
799a2abe 9574 struct thread_info *thread = inferior_thread ();
ee154bee 9575
799a2abe
PA
9576 return (thread->priv != NULL
9577 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9578}
9579
4aa7a7f5
JJ
9580static int
9581remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9582{
799a2abe 9583 struct thread_info *thread = inferior_thread ();
a744cf53 9584
799a2abe
PA
9585 if (thread->priv != NULL
9586 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9587 {
799a2abe
PA
9588 *addr_p = thread->priv->watch_data_address;
9589 return 1;
4aa7a7f5
JJ
9590 }
9591
799a2abe 9592 return 0;
3c3bea1c
GS
9593}
9594
9595
9596static int
23a26771 9597remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9598 struct bp_target_info *bp_tgt)
3c3bea1c 9599{
0d5ed153 9600 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9601 struct remote_state *rs;
bba74b36 9602 char *p, *endbuf;
dd61ec5c 9603 char *message;
0d5ed153 9604 int bpsize;
802188a7 9605
c8189ed1 9606 /* The length field should be set to the size of a breakpoint
8181d85f 9607 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9608
0d5ed153 9609 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9610
4082afcc 9611 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9612 return -1;
2bc416ba 9613
28439a30
PA
9614 /* Make sure the remote is pointing at the right process, if
9615 necessary. */
9616 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9617 set_general_process ();
9618
4fff2411
JZ
9619 rs = get_remote_state ();
9620 p = rs->buf;
bba74b36 9621 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9622
96baa820
JM
9623 *(p++) = 'Z';
9624 *(p++) = '1';
9625 *(p++) = ',';
802188a7 9626
0d5ed153 9627 addr = remote_address_masked (addr);
96baa820 9628 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9629 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9630
efcc2da7 9631 if (remote_supports_cond_breakpoints (self))
bba74b36 9632 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9633
78eff0ec 9634 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9635 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9636
6d820c5c
DJ
9637 putpkt (rs->buf);
9638 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9639
6d820c5c 9640 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9641 {
9642 case PACKET_ERROR:
dd61ec5c
MW
9643 if (rs->buf[1] == '.')
9644 {
9645 message = strchr (rs->buf + 2, '.');
9646 if (message)
0316657e 9647 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9648 }
9649 return -1;
d471ea57
AC
9650 case PACKET_UNKNOWN:
9651 return -1;
9652 case PACKET_OK:
0d5ed153
MR
9653 bp_tgt->placed_address = addr;
9654 bp_tgt->placed_size = bpsize;
d471ea57
AC
9655 return 0;
9656 }
8e65ff28 9657 internal_error (__FILE__, __LINE__,
e2e0b3e5 9658 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9659}
9660
d471ea57 9661
802188a7 9662static int
a64dc96c 9663remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9664 struct bp_target_info *bp_tgt)
96baa820 9665{
8181d85f 9666 CORE_ADDR addr;
d01949b6 9667 struct remote_state *rs = get_remote_state ();
6d820c5c 9668 char *p = rs->buf;
bba74b36 9669 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9670
4082afcc 9671 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9672 return -1;
802188a7 9673
28439a30
PA
9674 /* Make sure the remote is pointing at the right process, if
9675 necessary. */
9676 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9677 set_general_process ();
9678
96baa820
JM
9679 *(p++) = 'z';
9680 *(p++) = '1';
9681 *(p++) = ',';
802188a7 9682
8181d85f 9683 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9684 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9685 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9686
6d820c5c
DJ
9687 putpkt (rs->buf);
9688 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9689
6d820c5c 9690 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9691 {
9692 case PACKET_ERROR:
9693 case PACKET_UNKNOWN:
9694 return -1;
9695 case PACKET_OK:
9696 return 0;
9697 }
8e65ff28 9698 internal_error (__FILE__, __LINE__,
e2e0b3e5 9699 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9700}
96baa820 9701
4a5e7a5b
PA
9702/* Verify memory using the "qCRC:" request. */
9703
9704static int
9705remote_verify_memory (struct target_ops *ops,
9706 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9707{
9708 struct remote_state *rs = get_remote_state ();
9709 unsigned long host_crc, target_crc;
9710 char *tmp;
9711
936d2992
PA
9712 /* It doesn't make sense to use qCRC if the remote target is
9713 connected but not running. */
9714 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9715 {
9716 enum packet_result result;
28439a30 9717
936d2992
PA
9718 /* Make sure the remote is pointing at the right process. */
9719 set_general_process ();
4a5e7a5b 9720
936d2992
PA
9721 /* FIXME: assumes lma can fit into long. */
9722 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9723 (long) lma, (long) size);
9724 putpkt (rs->buf);
4a5e7a5b 9725
936d2992
PA
9726 /* Be clever; compute the host_crc before waiting for target
9727 reply. */
9728 host_crc = xcrc32 (data, size, 0xffffffff);
9729
9730 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9731
936d2992
PA
9732 result = packet_ok (rs->buf,
9733 &remote_protocol_packets[PACKET_qCRC]);
9734 if (result == PACKET_ERROR)
9735 return -1;
9736 else if (result == PACKET_OK)
9737 {
9738 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9739 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9740
936d2992
PA
9741 return (host_crc == target_crc);
9742 }
9743 }
4a5e7a5b 9744
936d2992 9745 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9746}
9747
c906108c
SS
9748/* compare-sections command
9749
9750 With no arguments, compares each loadable section in the exec bfd
9751 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9752 Useful for verifying the image on the target against the exec file. */
e514a9d6 9753
c906108c 9754static void
fba45db2 9755compare_sections_command (char *args, int from_tty)
c906108c
SS
9756{
9757 asection *s;
c906108c 9758 struct cleanup *old_chain;
948f8e3d 9759 gdb_byte *sectdata;
ce359b09 9760 const char *sectname;
c906108c
SS
9761 bfd_size_type size;
9762 bfd_vma lma;
9763 int matched = 0;
9764 int mismatched = 0;
4a5e7a5b 9765 int res;
95cf3b38 9766 int read_only = 0;
c906108c
SS
9767
9768 if (!exec_bfd)
8a3fe4f8 9769 error (_("command cannot be used without an exec file"));
c906108c 9770
28439a30
PA
9771 /* Make sure the remote is pointing at the right process. */
9772 set_general_process ();
9773
95cf3b38
DT
9774 if (args != NULL && strcmp (args, "-r") == 0)
9775 {
9776 read_only = 1;
9777 args = NULL;
9778 }
9779
c5aa993b 9780 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9781 {
9782 if (!(s->flags & SEC_LOAD))
0df8b418 9783 continue; /* Skip non-loadable section. */
c906108c 9784
95cf3b38
DT
9785 if (read_only && (s->flags & SEC_READONLY) == 0)
9786 continue; /* Skip writeable sections */
9787
2c500098 9788 size = bfd_get_section_size (s);
c906108c 9789 if (size == 0)
0df8b418 9790 continue; /* Skip zero-length section. */
c906108c 9791
ce359b09 9792 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9793 if (args && strcmp (args, sectname) != 0)
0df8b418 9794 continue; /* Not the section selected by user. */
c906108c 9795
0df8b418 9796 matched = 1; /* Do this section. */
c906108c 9797 lma = s->lma;
c906108c 9798
224c3ddb 9799 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9800 old_chain = make_cleanup (xfree, sectdata);
c906108c 9801 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9802
4a5e7a5b
PA
9803 res = target_verify_memory (sectdata, lma, size);
9804
9805 if (res == -1)
5af949e3 9806 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9807 paddress (target_gdbarch (), lma),
9808 paddress (target_gdbarch (), lma + size));
c906108c 9809
5af949e3 9810 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9811 paddress (target_gdbarch (), lma),
9812 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9813 if (res)
c906108c
SS
9814 printf_filtered ("matched.\n");
9815 else
c5aa993b
JM
9816 {
9817 printf_filtered ("MIS-MATCHED!\n");
9818 mismatched++;
9819 }
c906108c
SS
9820
9821 do_cleanups (old_chain);
9822 }
9823 if (mismatched > 0)
936d2992 9824 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9825the loaded file\n"));
c906108c 9826 if (args && !matched)
a3f17187 9827 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9828}
9829
0e7f50da
UW
9830/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9831 into remote target. The number of bytes written to the remote
9832 target is returned, or -1 for error. */
9833
9b409511 9834static enum target_xfer_status
0e7f50da
UW
9835remote_write_qxfer (struct target_ops *ops, const char *object_name,
9836 const char *annex, const gdb_byte *writebuf,
9b409511 9837 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9838 struct packet_config *packet)
9839{
9840 int i, buf_len;
9841 ULONGEST n;
0e7f50da
UW
9842 struct remote_state *rs = get_remote_state ();
9843 int max_size = get_memory_write_packet_size ();
9844
9845 if (packet->support == PACKET_DISABLE)
2ed4b548 9846 return TARGET_XFER_E_IO;
0e7f50da
UW
9847
9848 /* Insert header. */
9849 i = snprintf (rs->buf, max_size,
9850 "qXfer:%s:write:%s:%s:",
9851 object_name, annex ? annex : "",
9852 phex_nz (offset, sizeof offset));
9853 max_size -= (i + 1);
9854
9855 /* Escape as much data as fits into rs->buf. */
9856 buf_len = remote_escape_output
124e13d9 9857 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9858
9859 if (putpkt_binary (rs->buf, i + buf_len) < 0
9860 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9861 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9862 return TARGET_XFER_E_IO;
0e7f50da
UW
9863
9864 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9865
9866 *xfered_len = n;
9867 return TARGET_XFER_OK;
0e7f50da
UW
9868}
9869
0876f84a
DJ
9870/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9871 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9872 number of bytes read is returned, or 0 for EOF, or -1 for error.
9873 The number of bytes read may be less than LEN without indicating an
9874 EOF. PACKET is checked and updated to indicate whether the remote
9875 target supports this object. */
9876
9b409511 9877static enum target_xfer_status
0876f84a
DJ
9878remote_read_qxfer (struct target_ops *ops, const char *object_name,
9879 const char *annex,
9880 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9881 ULONGEST *xfered_len,
0876f84a
DJ
9882 struct packet_config *packet)
9883{
0876f84a 9884 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9885 LONGEST i, n, packet_len;
9886
9887 if (packet->support == PACKET_DISABLE)
2ed4b548 9888 return TARGET_XFER_E_IO;
0876f84a
DJ
9889
9890 /* Check whether we've cached an end-of-object packet that matches
9891 this request. */
8e88304f 9892 if (rs->finished_object)
0876f84a 9893 {
8e88304f
TT
9894 if (strcmp (object_name, rs->finished_object) == 0
9895 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9896 && offset == rs->finished_offset)
9b409511
YQ
9897 return TARGET_XFER_EOF;
9898
0876f84a
DJ
9899
9900 /* Otherwise, we're now reading something different. Discard
9901 the cache. */
8e88304f
TT
9902 xfree (rs->finished_object);
9903 xfree (rs->finished_annex);
9904 rs->finished_object = NULL;
9905 rs->finished_annex = NULL;
0876f84a
DJ
9906 }
9907
9908 /* Request only enough to fit in a single packet. The actual data
9909 may not, since we don't know how much of it will need to be escaped;
9910 the target is free to respond with slightly less data. We subtract
9911 five to account for the response type and the protocol frame. */
9912 n = min (get_remote_packet_size () - 5, len);
9913 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9914 object_name, annex ? annex : "",
9915 phex_nz (offset, sizeof offset),
9916 phex_nz (n, sizeof n));
9917 i = putpkt (rs->buf);
9918 if (i < 0)
2ed4b548 9919 return TARGET_XFER_E_IO;
0876f84a
DJ
9920
9921 rs->buf[0] = '\0';
9922 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9923 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9924 return TARGET_XFER_E_IO;
0876f84a
DJ
9925
9926 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9927 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9928
9929 /* 'm' means there is (or at least might be) more data after this
9930 batch. That does not make sense unless there's at least one byte
9931 of data in this reply. */
9932 if (rs->buf[0] == 'm' && packet_len == 1)
9933 error (_("Remote qXfer reply contained no data."));
9934
9935 /* Got some data. */
bc20a4af
PA
9936 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9937 packet_len - 1, readbuf, n);
0876f84a
DJ
9938
9939 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9940 or possibly empty. If we have the final block of a non-empty
9941 object, record this fact to bypass a subsequent partial read. */
9942 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9943 {
8e88304f
TT
9944 rs->finished_object = xstrdup (object_name);
9945 rs->finished_annex = xstrdup (annex ? annex : "");
9946 rs->finished_offset = offset + i;
0876f84a
DJ
9947 }
9948
9b409511
YQ
9949 if (i == 0)
9950 return TARGET_XFER_EOF;
9951 else
9952 {
9953 *xfered_len = i;
9954 return TARGET_XFER_OK;
9955 }
0876f84a
DJ
9956}
9957
9b409511 9958static enum target_xfer_status
4b8a223f 9959remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9960 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9961 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9962 ULONGEST *xfered_len)
c906108c 9963{
82f73884 9964 struct remote_state *rs;
c906108c 9965 int i;
6d820c5c 9966 char *p2;
1e3ff5ad 9967 char query_type;
124e13d9 9968 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9969
e6e4e701 9970 set_remote_traceframe ();
82f73884
PA
9971 set_general_thread (inferior_ptid);
9972
9973 rs = get_remote_state ();
9974
b2182ed2 9975 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9976 if (object == TARGET_OBJECT_MEMORY)
9977 {
2d717e4f
DJ
9978 /* If the remote target is connected but not running, we should
9979 pass this request down to a lower stratum (e.g. the executable
9980 file). */
9981 if (!target_has_execution)
9b409511 9982 return TARGET_XFER_EOF;
2d717e4f 9983
21e3b9b9 9984 if (writebuf != NULL)
124e13d9
SM
9985 return remote_write_bytes (offset, writebuf, len, unit_size,
9986 xfered_len);
21e3b9b9 9987 else
124e13d9
SM
9988 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9989 xfered_len);
21e3b9b9
DJ
9990 }
9991
0df8b418 9992 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9993 if (object == TARGET_OBJECT_SPU)
9994 {
9995 if (readbuf)
9996 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9997 xfered_len, &remote_protocol_packets
9998 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9999 else
10000 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
10001 xfered_len, &remote_protocol_packets
10002 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10003 }
10004
4aa995e1
PA
10005 /* Handle extra signal info using qxfer packets. */
10006 if (object == TARGET_OBJECT_SIGNAL_INFO)
10007 {
10008 if (readbuf)
10009 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 10010 xfered_len, &remote_protocol_packets
4aa995e1
PA
10011 [PACKET_qXfer_siginfo_read]);
10012 else
3e43a32a 10013 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 10014 writebuf, offset, len, xfered_len,
4aa995e1
PA
10015 &remote_protocol_packets
10016 [PACKET_qXfer_siginfo_write]);
10017 }
10018
0fb4aa4b
PA
10019 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10020 {
10021 if (readbuf)
3e43a32a 10022 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 10023 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10024 &remote_protocol_packets
10025 [PACKET_qXfer_statictrace_read]);
10026 else
2ed4b548 10027 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10028 }
10029
a76d924d
DJ
10030 /* Only handle flash writes. */
10031 if (writebuf != NULL)
10032 {
a76d924d
DJ
10033 switch (object)
10034 {
10035 case TARGET_OBJECT_FLASH:
9b409511
YQ
10036 return remote_flash_write (ops, offset, len, xfered_len,
10037 writebuf);
a76d924d
DJ
10038
10039 default:
2ed4b548 10040 return TARGET_XFER_E_IO;
a76d924d
DJ
10041 }
10042 }
4b8a223f 10043
1e3ff5ad
AC
10044 /* Map pre-existing objects onto letters. DO NOT do this for new
10045 objects!!! Instead specify new query packets. */
10046 switch (object)
c906108c 10047 {
1e3ff5ad
AC
10048 case TARGET_OBJECT_AVR:
10049 query_type = 'R';
10050 break;
802188a7
RM
10051
10052 case TARGET_OBJECT_AUXV:
0876f84a
DJ
10053 gdb_assert (annex == NULL);
10054 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 10055 xfered_len,
0876f84a 10056 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10057
23181151
DJ
10058 case TARGET_OBJECT_AVAILABLE_FEATURES:
10059 return remote_read_qxfer
9b409511 10060 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10061 &remote_protocol_packets[PACKET_qXfer_features]);
10062
cfa9d6d9
DJ
10063 case TARGET_OBJECT_LIBRARIES:
10064 return remote_read_qxfer
9b409511 10065 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10066 &remote_protocol_packets[PACKET_qXfer_libraries]);
10067
2268b414
JK
10068 case TARGET_OBJECT_LIBRARIES_SVR4:
10069 return remote_read_qxfer
9b409511 10070 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10071 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10072
fd79ecee
DJ
10073 case TARGET_OBJECT_MEMORY_MAP:
10074 gdb_assert (annex == NULL);
10075 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 10076 xfered_len,
fd79ecee
DJ
10077 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10078
07e059b5
VP
10079 case TARGET_OBJECT_OSDATA:
10080 /* Should only get here if we're connected. */
5d93a237 10081 gdb_assert (rs->remote_desc);
07e059b5 10082 return remote_read_qxfer
9b409511 10083 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10084 &remote_protocol_packets[PACKET_qXfer_osdata]);
10085
dc146f7c
VP
10086 case TARGET_OBJECT_THREADS:
10087 gdb_assert (annex == NULL);
10088 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10089 xfered_len,
dc146f7c
VP
10090 &remote_protocol_packets[PACKET_qXfer_threads]);
10091
b3b9301e
PA
10092 case TARGET_OBJECT_TRACEFRAME_INFO:
10093 gdb_assert (annex == NULL);
10094 return remote_read_qxfer
9b409511 10095 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10096 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10097
10098 case TARGET_OBJECT_FDPIC:
10099 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10100 xfered_len,
78d85199 10101 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10102
10103 case TARGET_OBJECT_OPENVMS_UIB:
10104 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10105 xfered_len,
169081d0
TG
10106 &remote_protocol_packets[PACKET_qXfer_uib]);
10107
9accd112
MM
10108 case TARGET_OBJECT_BTRACE:
10109 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10110 xfered_len,
9accd112
MM
10111 &remote_protocol_packets[PACKET_qXfer_btrace]);
10112
f4abbc16
MM
10113 case TARGET_OBJECT_BTRACE_CONF:
10114 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10115 len, xfered_len,
10116 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10117
c78fa86a
GB
10118 case TARGET_OBJECT_EXEC_FILE:
10119 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10120 len, xfered_len,
10121 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10122
1e3ff5ad 10123 default:
2ed4b548 10124 return TARGET_XFER_E_IO;
c906108c
SS
10125 }
10126
0df8b418 10127 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10128 large enough let the caller deal with it. */
ea9c271d 10129 if (len < get_remote_packet_size ())
2ed4b548 10130 return TARGET_XFER_E_IO;
ea9c271d 10131 len = get_remote_packet_size ();
1e3ff5ad 10132
23860348 10133 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10134 if (!rs->remote_desc)
8a3fe4f8 10135 error (_("remote query is only available after target open"));
c906108c 10136
1e3ff5ad 10137 gdb_assert (annex != NULL);
4b8a223f 10138 gdb_assert (readbuf != NULL);
c906108c 10139
6d820c5c 10140 p2 = rs->buf;
c906108c
SS
10141 *p2++ = 'q';
10142 *p2++ = query_type;
10143
23860348
MS
10144 /* We used one buffer char for the remote protocol q command and
10145 another for the query type. As the remote protocol encapsulation
10146 uses 4 chars plus one extra in case we are debugging
10147 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10148 string. */
c906108c 10149 i = 0;
ea9c271d 10150 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10151 {
1e3ff5ad
AC
10152 /* Bad caller may have sent forbidden characters. */
10153 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10154 *p2++ = annex[i];
c906108c
SS
10155 i++;
10156 }
1e3ff5ad
AC
10157 *p2 = '\0';
10158 gdb_assert (annex[i] == '\0');
c906108c 10159
6d820c5c 10160 i = putpkt (rs->buf);
c5aa993b 10161 if (i < 0)
2ed4b548 10162 return TARGET_XFER_E_IO;
c906108c 10163
6d820c5c
DJ
10164 getpkt (&rs->buf, &rs->buf_size, 0);
10165 strcpy ((char *) readbuf, rs->buf);
c906108c 10166
9b409511
YQ
10167 *xfered_len = strlen ((char *) readbuf);
10168 return TARGET_XFER_OK;
c906108c
SS
10169}
10170
08388c79
DE
10171static int
10172remote_search_memory (struct target_ops* ops,
10173 CORE_ADDR start_addr, ULONGEST search_space_len,
10174 const gdb_byte *pattern, ULONGEST pattern_len,
10175 CORE_ADDR *found_addrp)
10176{
f5656ead 10177 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10178 struct remote_state *rs = get_remote_state ();
10179 int max_size = get_memory_write_packet_size ();
10180 struct packet_config *packet =
10181 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10182 /* Number of packet bytes used to encode the pattern;
10183 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10184 int escaped_pattern_len;
0df8b418 10185 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10186 int used_pattern_len;
10187 int i;
10188 int found;
10189 ULONGEST found_addr;
10190
10191 /* Don't go to the target if we don't have to.
10192 This is done before checking packet->support to avoid the possibility that
10193 a success for this edge case means the facility works in general. */
10194 if (pattern_len > search_space_len)
10195 return 0;
10196 if (pattern_len == 0)
10197 {
10198 *found_addrp = start_addr;
10199 return 1;
10200 }
10201
10202 /* If we already know the packet isn't supported, fall back to the simple
10203 way of searching memory. */
10204
4082afcc 10205 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10206 {
10207 /* Target doesn't provided special support, fall back and use the
10208 standard support (copy memory and do the search here). */
10209 return simple_search_memory (ops, start_addr, search_space_len,
10210 pattern, pattern_len, found_addrp);
10211 }
10212
28439a30
PA
10213 /* Make sure the remote is pointing at the right process. */
10214 set_general_process ();
10215
08388c79
DE
10216 /* Insert header. */
10217 i = snprintf (rs->buf, max_size,
10218 "qSearch:memory:%s;%s;",
5af949e3 10219 phex_nz (start_addr, addr_size),
08388c79
DE
10220 phex_nz (search_space_len, sizeof (search_space_len)));
10221 max_size -= (i + 1);
10222
10223 /* Escape as much data as fits into rs->buf. */
10224 escaped_pattern_len =
124e13d9 10225 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10226 &used_pattern_len, max_size);
10227
10228 /* Bail if the pattern is too large. */
10229 if (used_pattern_len != pattern_len)
9b20d036 10230 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10231
10232 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10233 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10234 || packet_ok (rs->buf, packet) != PACKET_OK)
10235 {
10236 /* The request may not have worked because the command is not
10237 supported. If so, fall back to the simple way. */
10238 if (packet->support == PACKET_DISABLE)
10239 {
10240 return simple_search_memory (ops, start_addr, search_space_len,
10241 pattern, pattern_len, found_addrp);
10242 }
10243 return -1;
10244 }
10245
10246 if (rs->buf[0] == '0')
10247 found = 0;
10248 else if (rs->buf[0] == '1')
10249 {
10250 found = 1;
10251 if (rs->buf[1] != ',')
10e0fa18 10252 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10253 unpack_varlen_hex (rs->buf + 2, &found_addr);
10254 *found_addrp = found_addr;
10255 }
10256 else
10e0fa18 10257 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10258
10259 return found;
10260}
10261
96baa820 10262static void
a30bf1f1 10263remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10264 struct ui_file *outbuf)
96baa820 10265{
d01949b6 10266 struct remote_state *rs = get_remote_state ();
2e9f7625 10267 char *p = rs->buf;
96baa820 10268
5d93a237 10269 if (!rs->remote_desc)
8a3fe4f8 10270 error (_("remote rcmd is only available after target open"));
96baa820 10271
23860348 10272 /* Send a NULL command across as an empty command. */
7be570e7
JM
10273 if (command == NULL)
10274 command = "";
10275
23860348 10276 /* The query prefix. */
2e9f7625
DJ
10277 strcpy (rs->buf, "qRcmd,");
10278 p = strchr (rs->buf, '\0');
96baa820 10279
3e43a32a
MS
10280 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10281 > get_remote_packet_size ())
8a3fe4f8 10282 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10283
23860348 10284 /* Encode the actual command. */
a30bf1f1 10285 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10286
6d820c5c 10287 if (putpkt (rs->buf) < 0)
8a3fe4f8 10288 error (_("Communication problem with target."));
96baa820
JM
10289
10290 /* get/display the response */
10291 while (1)
10292 {
2e9f7625
DJ
10293 char *buf;
10294
00bf0b85 10295 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10296 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10297 rs->buf[0] = '\0';
5b37825d
PW
10298 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10299 {
10300 /* Timeout. Continue to (try to) read responses.
10301 This is better than stopping with an error, assuming the stub
10302 is still executing the (long) monitor command.
10303 If needed, the user can interrupt gdb using C-c, obtaining
10304 an effect similar to stop on timeout. */
10305 continue;
10306 }
2e9f7625 10307 buf = rs->buf;
96baa820 10308 if (buf[0] == '\0')
8a3fe4f8 10309 error (_("Target does not support this command."));
96baa820
JM
10310 if (buf[0] == 'O' && buf[1] != 'K')
10311 {
23860348 10312 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10313 continue;
10314 }
10315 if (strcmp (buf, "OK") == 0)
10316 break;
7be570e7
JM
10317 if (strlen (buf) == 3 && buf[0] == 'E'
10318 && isdigit (buf[1]) && isdigit (buf[2]))
10319 {
8a3fe4f8 10320 error (_("Protocol error with Rcmd"));
7be570e7 10321 }
96baa820
JM
10322 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10323 {
10324 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10325
96baa820
JM
10326 fputc_unfiltered (c, outbuf);
10327 }
10328 break;
10329 }
10330}
10331
fd79ecee
DJ
10332static VEC(mem_region_s) *
10333remote_memory_map (struct target_ops *ops)
10334{
10335 VEC(mem_region_s) *result = NULL;
10336 char *text = target_read_stralloc (&current_target,
10337 TARGET_OBJECT_MEMORY_MAP, NULL);
10338
10339 if (text)
10340 {
10341 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10342
fd79ecee
DJ
10343 result = parse_memory_map (text);
10344 do_cleanups (back_to);
10345 }
10346
10347 return result;
10348}
10349
c906108c 10350static void
fba45db2 10351packet_command (char *args, int from_tty)
c906108c 10352{
d01949b6 10353 struct remote_state *rs = get_remote_state ();
c906108c 10354
5d93a237 10355 if (!rs->remote_desc)
8a3fe4f8 10356 error (_("command can only be used with remote target"));
c906108c 10357
c5aa993b 10358 if (!args)
8a3fe4f8 10359 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10360
10361 puts_filtered ("sending: ");
10362 print_packet (args);
10363 puts_filtered ("\n");
10364 putpkt (args);
10365
6d820c5c 10366 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10367 puts_filtered ("received: ");
6d820c5c 10368 print_packet (rs->buf);
c906108c
SS
10369 puts_filtered ("\n");
10370}
10371
10372#if 0
23860348 10373/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10374
a14ed312 10375static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10376
a14ed312 10377static void threadset_test_cmd (char *cmd, int tty);
c906108c 10378
a14ed312 10379static void threadalive_test (char *cmd, int tty);
c906108c 10380
a14ed312 10381static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10382
23860348 10383int get_and_display_threadinfo (threadref *ref);
c906108c 10384
a14ed312 10385static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10386
23860348 10387static int thread_display_step (threadref *ref, void *context);
c906108c 10388
a14ed312 10389static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10390
a14ed312 10391static void init_remote_threadtests (void);
c906108c 10392
23860348 10393#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10394
10395static void
fba45db2 10396threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10397{
10398 int sample_thread = SAMPLE_THREAD;
10399
a3f17187 10400 printf_filtered (_("Remote threadset test\n"));
79d7f229 10401 set_general_thread (sample_thread);
c906108c
SS
10402}
10403
10404
10405static void
fba45db2 10406threadalive_test (char *cmd, int tty)
c906108c
SS
10407{
10408 int sample_thread = SAMPLE_THREAD;
79d7f229 10409 int pid = ptid_get_pid (inferior_ptid);
ba348170 10410 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10411
79d7f229 10412 if (remote_thread_alive (ptid))
c906108c
SS
10413 printf_filtered ("PASS: Thread alive test\n");
10414 else
10415 printf_filtered ("FAIL: Thread alive test\n");
10416}
10417
23860348 10418void output_threadid (char *title, threadref *ref);
c906108c
SS
10419
10420void
fba45db2 10421output_threadid (char *title, threadref *ref)
c906108c
SS
10422{
10423 char hexid[20];
10424
23860348 10425 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10426 hexid[16] = 0;
10427 printf_filtered ("%s %s\n", title, (&hexid[0]));
10428}
10429
10430static void
fba45db2 10431threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10432{
10433 int startflag = 1;
10434 threadref nextthread;
10435 int done, result_count;
10436 threadref threadlist[3];
10437
10438 printf_filtered ("Remote Threadlist test\n");
10439 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10440 &result_count, &threadlist[0]))
10441 printf_filtered ("FAIL: threadlist test\n");
10442 else
10443 {
10444 threadref *scan = threadlist;
10445 threadref *limit = scan + result_count;
10446
10447 while (scan < limit)
10448 output_threadid (" thread ", scan++);
10449 }
10450}
10451
10452void
fba45db2 10453display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10454{
10455 output_threadid ("Threadid: ", &info->threadid);
10456 printf_filtered ("Name: %s\n ", info->shortname);
10457 printf_filtered ("State: %s\n", info->display);
10458 printf_filtered ("other: %s\n\n", info->more_display);
10459}
10460
10461int
fba45db2 10462get_and_display_threadinfo (threadref *ref)
c906108c
SS
10463{
10464 int result;
10465 int set;
10466 struct gdb_ext_thread_info threadinfo;
10467
10468 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10469 | TAG_MOREDISPLAY | TAG_DISPLAY;
10470 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10471 display_thread_info (&threadinfo);
10472 return result;
10473}
10474
10475static void
fba45db2 10476threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10477{
10478 int athread = SAMPLE_THREAD;
10479 threadref thread;
10480 int set;
10481
10482 int_to_threadref (&thread, athread);
10483 printf_filtered ("Remote Threadinfo test\n");
10484 if (!get_and_display_threadinfo (&thread))
10485 printf_filtered ("FAIL cannot get thread info\n");
10486}
10487
10488static int
fba45db2 10489thread_display_step (threadref *ref, void *context)
c906108c
SS
10490{
10491 /* output_threadid(" threadstep ",ref); *//* simple test */
10492 return get_and_display_threadinfo (ref);
10493}
10494
10495static void
fba45db2 10496threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10497{
10498 printf_filtered ("Remote Threadlist update test\n");
10499 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10500}
10501
10502static void
10503init_remote_threadtests (void)
10504{
3e43a32a
MS
10505 add_com ("tlist", class_obscure, threadlist_test_cmd,
10506 _("Fetch and print the remote list of "
10507 "thread identifiers, one pkt only"));
c906108c 10508 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10509 _("Fetch and display info about one thread"));
c906108c 10510 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10511 _("Test setting to a different thread"));
c906108c 10512 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10513 _("Iterate through updating all remote thread info"));
c906108c 10514 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10515 _(" Remote thread alive test "));
c906108c
SS
10516}
10517
10518#endif /* 0 */
10519
f3fb8c85
MS
10520/* Convert a thread ID to a string. Returns the string in a static
10521 buffer. */
10522
10523static char *
117de6a9 10524remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10525{
79d7f229 10526 static char buf[64];
82f73884 10527 struct remote_state *rs = get_remote_state ();
f3fb8c85 10528
7cee1e54
PA
10529 if (ptid_equal (ptid, null_ptid))
10530 return normal_pid_to_str (ptid);
10531 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10532 {
10533 /* Printing an inferior target id. */
10534
10535 /* When multi-process extensions are off, there's no way in the
10536 remote protocol to know the remote process id, if there's any
10537 at all. There's one exception --- when we're connected with
10538 target extended-remote, and we manually attached to a process
10539 with "attach PID". We don't record anywhere a flag that
10540 allows us to distinguish that case from the case of
10541 connecting with extended-remote and the stub already being
10542 attached to a process, and reporting yes to qAttached, hence
10543 no smart special casing here. */
10544 if (!remote_multi_process_p (rs))
10545 {
10546 xsnprintf (buf, sizeof buf, "Remote target");
10547 return buf;
10548 }
10549
10550 return normal_pid_to_str (ptid);
82f73884 10551 }
ecd0ada5 10552 else
79d7f229 10553 {
ecd0ada5
PA
10554 if (ptid_equal (magic_null_ptid, ptid))
10555 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 10556 else if (remote_multi_process_p (rs))
de0d863e
DB
10557 if (ptid_get_lwp (ptid) == 0)
10558 return normal_pid_to_str (ptid);
10559 else
10560 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10561 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10562 else
10563 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10564 ptid_get_lwp (ptid));
79d7f229
PA
10565 return buf;
10566 }
f3fb8c85
MS
10567}
10568
38691318
KB
10569/* Get the address of the thread local variable in OBJFILE which is
10570 stored at OFFSET within the thread local storage for thread PTID. */
10571
10572static CORE_ADDR
117de6a9
PA
10573remote_get_thread_local_address (struct target_ops *ops,
10574 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10575{
4082afcc 10576 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10577 {
10578 struct remote_state *rs = get_remote_state ();
6d820c5c 10579 char *p = rs->buf;
82f73884 10580 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10581 enum packet_result result;
38691318
KB
10582
10583 strcpy (p, "qGetTLSAddr:");
10584 p += strlen (p);
82f73884 10585 p = write_ptid (p, endp, ptid);
38691318
KB
10586 *p++ = ',';
10587 p += hexnumstr (p, offset);
10588 *p++ = ',';
10589 p += hexnumstr (p, lm);
10590 *p++ = '\0';
10591
6d820c5c
DJ
10592 putpkt (rs->buf);
10593 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10594 result = packet_ok (rs->buf,
10595 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10596 if (result == PACKET_OK)
38691318
KB
10597 {
10598 ULONGEST result;
10599
6d820c5c 10600 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10601 return result;
10602 }
571dd617 10603 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10604 throw_error (TLS_GENERIC_ERROR,
10605 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10606 else
109c3e39
AC
10607 throw_error (TLS_GENERIC_ERROR,
10608 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10609 }
10610 else
109c3e39
AC
10611 throw_error (TLS_GENERIC_ERROR,
10612 _("TLS not supported or disabled on this target"));
38691318
KB
10613 /* Not reached. */
10614 return 0;
10615}
10616
711e434b
PM
10617/* Provide thread local base, i.e. Thread Information Block address.
10618 Returns 1 if ptid is found and thread_local_base is non zero. */
10619
70221824 10620static int
bd7ae0f5 10621remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10622{
4082afcc 10623 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10624 {
10625 struct remote_state *rs = get_remote_state ();
10626 char *p = rs->buf;
10627 char *endp = rs->buf + get_remote_packet_size ();
10628 enum packet_result result;
10629
10630 strcpy (p, "qGetTIBAddr:");
10631 p += strlen (p);
10632 p = write_ptid (p, endp, ptid);
10633 *p++ = '\0';
10634
10635 putpkt (rs->buf);
10636 getpkt (&rs->buf, &rs->buf_size, 0);
10637 result = packet_ok (rs->buf,
10638 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10639 if (result == PACKET_OK)
10640 {
10641 ULONGEST result;
10642
10643 unpack_varlen_hex (rs->buf, &result);
10644 if (addr)
10645 *addr = (CORE_ADDR) result;
10646 return 1;
10647 }
10648 else if (result == PACKET_UNKNOWN)
10649 error (_("Remote target doesn't support qGetTIBAddr packet"));
10650 else
10651 error (_("Remote target failed to process qGetTIBAddr request"));
10652 }
10653 else
10654 error (_("qGetTIBAddr not supported or disabled on this target"));
10655 /* Not reached. */
10656 return 0;
10657}
10658
29709017
DJ
10659/* Support for inferring a target description based on the current
10660 architecture and the size of a 'g' packet. While the 'g' packet
10661 can have any size (since optional registers can be left off the
10662 end), some sizes are easily recognizable given knowledge of the
10663 approximate architecture. */
10664
10665struct remote_g_packet_guess
10666{
10667 int bytes;
10668 const struct target_desc *tdesc;
10669};
10670typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10671DEF_VEC_O(remote_g_packet_guess_s);
10672
10673struct remote_g_packet_data
10674{
10675 VEC(remote_g_packet_guess_s) *guesses;
10676};
10677
10678static struct gdbarch_data *remote_g_packet_data_handle;
10679
10680static void *
10681remote_g_packet_data_init (struct obstack *obstack)
10682{
10683 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10684}
10685
10686void
10687register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10688 const struct target_desc *tdesc)
10689{
10690 struct remote_g_packet_data *data
19ba03f4
SM
10691 = ((struct remote_g_packet_data *)
10692 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10693 struct remote_g_packet_guess new_guess, *guess;
10694 int ix;
10695
10696 gdb_assert (tdesc != NULL);
10697
10698 for (ix = 0;
10699 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10700 ix++)
10701 if (guess->bytes == bytes)
10702 internal_error (__FILE__, __LINE__,
9b20d036 10703 _("Duplicate g packet description added for size %d"),
29709017
DJ
10704 bytes);
10705
10706 new_guess.bytes = bytes;
10707 new_guess.tdesc = tdesc;
10708 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10709}
10710
d962ef82
DJ
10711/* Return 1 if remote_read_description would do anything on this target
10712 and architecture, 0 otherwise. */
10713
10714static int
10715remote_read_description_p (struct target_ops *target)
10716{
10717 struct remote_g_packet_data *data
19ba03f4
SM
10718 = ((struct remote_g_packet_data *)
10719 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10720
10721 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10722 return 1;
10723
10724 return 0;
10725}
10726
29709017
DJ
10727static const struct target_desc *
10728remote_read_description (struct target_ops *target)
10729{
10730 struct remote_g_packet_data *data
19ba03f4
SM
10731 = ((struct remote_g_packet_data *)
10732 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10733
d962ef82
DJ
10734 /* Do not try this during initial connection, when we do not know
10735 whether there is a running but stopped thread. */
10736 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10737 return target->beneath->to_read_description (target->beneath);
d962ef82 10738
29709017
DJ
10739 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10740 {
10741 struct remote_g_packet_guess *guess;
10742 int ix;
10743 int bytes = send_g_packet ();
10744
10745 for (ix = 0;
10746 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10747 ix++)
10748 if (guess->bytes == bytes)
10749 return guess->tdesc;
10750
10751 /* We discard the g packet. A minor optimization would be to
10752 hold on to it, and fill the register cache once we have selected
10753 an architecture, but it's too tricky to do safely. */
10754 }
10755
2117c711 10756 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10757}
10758
a6b151f1
DJ
10759/* Remote file transfer support. This is host-initiated I/O, not
10760 target-initiated; for target-initiated, see remote-fileio.c. */
10761
10762/* If *LEFT is at least the length of STRING, copy STRING to
10763 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10764 decrease *LEFT. Otherwise raise an error. */
10765
10766static void
10767remote_buffer_add_string (char **buffer, int *left, char *string)
10768{
10769 int len = strlen (string);
10770
10771 if (len > *left)
10772 error (_("Packet too long for target."));
10773
10774 memcpy (*buffer, string, len);
10775 *buffer += len;
10776 *left -= len;
10777
10778 /* NUL-terminate the buffer as a convenience, if there is
10779 room. */
10780 if (*left)
10781 **buffer = '\0';
10782}
10783
10784/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10785 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10786 decrease *LEFT. Otherwise raise an error. */
10787
10788static void
10789remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10790 int len)
10791{
10792 if (2 * len > *left)
10793 error (_("Packet too long for target."));
10794
10795 bin2hex (bytes, *buffer, len);
10796 *buffer += 2 * len;
10797 *left -= 2 * len;
10798
10799 /* NUL-terminate the buffer as a convenience, if there is
10800 room. */
10801 if (*left)
10802 **buffer = '\0';
10803}
10804
10805/* If *LEFT is large enough, convert VALUE to hex and add it to
10806 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10807 decrease *LEFT. Otherwise raise an error. */
10808
10809static void
10810remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10811{
10812 int len = hexnumlen (value);
10813
10814 if (len > *left)
10815 error (_("Packet too long for target."));
10816
10817 hexnumstr (*buffer, value);
10818 *buffer += len;
10819 *left -= len;
10820
10821 /* NUL-terminate the buffer as a convenience, if there is
10822 room. */
10823 if (*left)
10824 **buffer = '\0';
10825}
10826
10827/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10828 value, *REMOTE_ERRNO to the remote error number or zero if none
10829 was included, and *ATTACHMENT to point to the start of the annex
10830 if any. The length of the packet isn't needed here; there may
10831 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10832
10833 Return 0 if the packet could be parsed, -1 if it could not. If
10834 -1 is returned, the other variables may not be initialized. */
10835
10836static int
10837remote_hostio_parse_result (char *buffer, int *retcode,
10838 int *remote_errno, char **attachment)
10839{
10840 char *p, *p2;
10841
10842 *remote_errno = 0;
10843 *attachment = NULL;
10844
10845 if (buffer[0] != 'F')
10846 return -1;
10847
10848 errno = 0;
10849 *retcode = strtol (&buffer[1], &p, 16);
10850 if (errno != 0 || p == &buffer[1])
10851 return -1;
10852
10853 /* Check for ",errno". */
10854 if (*p == ',')
10855 {
10856 errno = 0;
10857 *remote_errno = strtol (p + 1, &p2, 16);
10858 if (errno != 0 || p + 1 == p2)
10859 return -1;
10860 p = p2;
10861 }
10862
10863 /* Check for ";attachment". If there is no attachment, the
10864 packet should end here. */
10865 if (*p == ';')
10866 {
10867 *attachment = p + 1;
10868 return 0;
10869 }
10870 else if (*p == '\0')
10871 return 0;
10872 else
10873 return -1;
10874}
10875
10876/* Send a prepared I/O packet to the target and read its response.
10877 The prepared packet is in the global RS->BUF before this function
10878 is called, and the answer is there when we return.
10879
10880 COMMAND_BYTES is the length of the request to send, which may include
10881 binary data. WHICH_PACKET is the packet configuration to check
10882 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10883 is set to the error number and -1 is returned. Otherwise the value
10884 returned by the function is returned.
10885
10886 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10887 attachment is expected; an error will be reported if there's a
10888 mismatch. If one is found, *ATTACHMENT will be set to point into
10889 the packet buffer and *ATTACHMENT_LEN will be set to the
10890 attachment's length. */
10891
10892static int
10893remote_hostio_send_command (int command_bytes, int which_packet,
10894 int *remote_errno, char **attachment,
10895 int *attachment_len)
10896{
10897 struct remote_state *rs = get_remote_state ();
10898 int ret, bytes_read;
10899 char *attachment_tmp;
10900
5d93a237 10901 if (!rs->remote_desc
4082afcc 10902 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10903 {
10904 *remote_errno = FILEIO_ENOSYS;
10905 return -1;
10906 }
10907
10908 putpkt_binary (rs->buf, command_bytes);
10909 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10910
10911 /* If it timed out, something is wrong. Don't try to parse the
10912 buffer. */
10913 if (bytes_read < 0)
10914 {
10915 *remote_errno = FILEIO_EINVAL;
10916 return -1;
10917 }
10918
10919 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10920 {
10921 case PACKET_ERROR:
10922 *remote_errno = FILEIO_EINVAL;
10923 return -1;
10924 case PACKET_UNKNOWN:
10925 *remote_errno = FILEIO_ENOSYS;
10926 return -1;
10927 case PACKET_OK:
10928 break;
10929 }
10930
10931 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10932 &attachment_tmp))
10933 {
10934 *remote_errno = FILEIO_EINVAL;
10935 return -1;
10936 }
10937
10938 /* Make sure we saw an attachment if and only if we expected one. */
10939 if ((attachment_tmp == NULL && attachment != NULL)
10940 || (attachment_tmp != NULL && attachment == NULL))
10941 {
10942 *remote_errno = FILEIO_EINVAL;
10943 return -1;
10944 }
10945
10946 /* If an attachment was found, it must point into the packet buffer;
10947 work out how many bytes there were. */
10948 if (attachment_tmp != NULL)
10949 {
10950 *attachment = attachment_tmp;
10951 *attachment_len = bytes_read - (*attachment - rs->buf);
10952 }
10953
10954 return ret;
10955}
10956
80152258
PA
10957/* Invalidate the readahead cache. */
10958
10959static void
10960readahead_cache_invalidate (void)
10961{
10962 struct remote_state *rs = get_remote_state ();
10963
10964 rs->readahead_cache.fd = -1;
10965}
10966
10967/* Invalidate the readahead cache if it is holding data for FD. */
10968
10969static void
10970readahead_cache_invalidate_fd (int fd)
10971{
10972 struct remote_state *rs = get_remote_state ();
10973
10974 if (rs->readahead_cache.fd == fd)
10975 rs->readahead_cache.fd = -1;
10976}
10977
15a201c8
GB
10978/* Set the filesystem remote_hostio functions that take FILENAME
10979 arguments will use. Return 0 on success, or -1 if an error
10980 occurs (and set *REMOTE_ERRNO). */
10981
10982static int
10983remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10984{
10985 struct remote_state *rs = get_remote_state ();
10986 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10987 char *p = rs->buf;
10988 int left = get_remote_packet_size () - 1;
10989 char arg[9];
10990 int ret;
10991
10992 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10993 return 0;
10994
10995 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10996 return 0;
10997
10998 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10999
11000 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11001 remote_buffer_add_string (&p, &left, arg);
11002
11003 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11004 remote_errno, NULL, NULL);
11005
11006 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11007 return 0;
11008
11009 if (ret == 0)
11010 rs->fs_pid = required_pid;
11011
11012 return ret;
11013}
11014
12e2a5fd 11015/* Implementation of to_fileio_open. */
a6b151f1
DJ
11016
11017static int
cd897586 11018remote_hostio_open (struct target_ops *self,
07c138c8 11019 struct inferior *inf, const char *filename,
4313b8c0
GB
11020 int flags, int mode, int warn_if_slow,
11021 int *remote_errno)
a6b151f1
DJ
11022{
11023 struct remote_state *rs = get_remote_state ();
11024 char *p = rs->buf;
11025 int left = get_remote_packet_size () - 1;
11026
4313b8c0
GB
11027 if (warn_if_slow)
11028 {
11029 static int warning_issued = 0;
11030
11031 printf_unfiltered (_("Reading %s from remote target...\n"),
11032 filename);
11033
11034 if (!warning_issued)
11035 {
11036 warning (_("File transfers from remote targets can be slow."
11037 " Use \"set sysroot\" to access files locally"
11038 " instead."));
11039 warning_issued = 1;
11040 }
11041 }
11042
15a201c8
GB
11043 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11044 return -1;
11045
a6b151f1
DJ
11046 remote_buffer_add_string (&p, &left, "vFile:open:");
11047
11048 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11049 strlen (filename));
11050 remote_buffer_add_string (&p, &left, ",");
11051
11052 remote_buffer_add_int (&p, &left, flags);
11053 remote_buffer_add_string (&p, &left, ",");
11054
11055 remote_buffer_add_int (&p, &left, mode);
11056
11057 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11058 remote_errno, NULL, NULL);
11059}
11060
12e2a5fd 11061/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11062
11063static int
0d866f62
TT
11064remote_hostio_pwrite (struct target_ops *self,
11065 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11066 ULONGEST offset, int *remote_errno)
11067{
11068 struct remote_state *rs = get_remote_state ();
11069 char *p = rs->buf;
11070 int left = get_remote_packet_size ();
11071 int out_len;
11072
80152258
PA
11073 readahead_cache_invalidate_fd (fd);
11074
a6b151f1
DJ
11075 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11076
11077 remote_buffer_add_int (&p, &left, fd);
11078 remote_buffer_add_string (&p, &left, ",");
11079
11080 remote_buffer_add_int (&p, &left, offset);
11081 remote_buffer_add_string (&p, &left, ",");
11082
124e13d9 11083 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11084 get_remote_packet_size () - (p - rs->buf));
11085
11086 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11087 remote_errno, NULL, NULL);
11088}
11089
80152258
PA
11090/* Helper for the implementation of to_fileio_pread. Read the file
11091 from the remote side with vFile:pread. */
a6b151f1
DJ
11092
11093static int
80152258
PA
11094remote_hostio_pread_vFile (struct target_ops *self,
11095 int fd, gdb_byte *read_buf, int len,
11096 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11097{
11098 struct remote_state *rs = get_remote_state ();
11099 char *p = rs->buf;
11100 char *attachment;
11101 int left = get_remote_packet_size ();
11102 int ret, attachment_len;
11103 int read_len;
11104
11105 remote_buffer_add_string (&p, &left, "vFile:pread:");
11106
11107 remote_buffer_add_int (&p, &left, fd);
11108 remote_buffer_add_string (&p, &left, ",");
11109
11110 remote_buffer_add_int (&p, &left, len);
11111 remote_buffer_add_string (&p, &left, ",");
11112
11113 remote_buffer_add_int (&p, &left, offset);
11114
11115 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11116 remote_errno, &attachment,
11117 &attachment_len);
11118
11119 if (ret < 0)
11120 return ret;
11121
bc20a4af 11122 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11123 read_buf, len);
11124 if (read_len != ret)
11125 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11126
11127 return ret;
11128}
11129
80152258
PA
11130/* Serve pread from the readahead cache. Returns number of bytes
11131 read, or 0 if the request can't be served from the cache. */
11132
11133static int
11134remote_hostio_pread_from_cache (struct remote_state *rs,
11135 int fd, gdb_byte *read_buf, size_t len,
11136 ULONGEST offset)
11137{
11138 struct readahead_cache *cache = &rs->readahead_cache;
11139
11140 if (cache->fd == fd
11141 && cache->offset <= offset
11142 && offset < cache->offset + cache->bufsize)
11143 {
11144 ULONGEST max = cache->offset + cache->bufsize;
11145
11146 if (offset + len > max)
11147 len = max - offset;
11148
11149 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11150 return len;
11151 }
11152
11153 return 0;
11154}
11155
11156/* Implementation of to_fileio_pread. */
11157
11158static int
11159remote_hostio_pread (struct target_ops *self,
11160 int fd, gdb_byte *read_buf, int len,
11161 ULONGEST offset, int *remote_errno)
11162{
11163 int ret;
11164 struct remote_state *rs = get_remote_state ();
11165 struct readahead_cache *cache = &rs->readahead_cache;
11166
11167 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11168 if (ret > 0)
11169 {
11170 cache->hit_count++;
11171
11172 if (remote_debug)
11173 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11174 pulongest (cache->hit_count));
11175 return ret;
11176 }
11177
11178 cache->miss_count++;
11179 if (remote_debug)
11180 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11181 pulongest (cache->miss_count));
11182
11183 cache->fd = fd;
11184 cache->offset = offset;
11185 cache->bufsize = get_remote_packet_size ();
224c3ddb 11186 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11187
11188 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11189 cache->offset, remote_errno);
11190 if (ret <= 0)
11191 {
11192 readahead_cache_invalidate_fd (fd);
11193 return ret;
11194 }
11195
11196 cache->bufsize = ret;
11197 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11198}
11199
12e2a5fd 11200/* Implementation of to_fileio_close. */
a6b151f1
DJ
11201
11202static int
df39ea25 11203remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11204{
11205 struct remote_state *rs = get_remote_state ();
11206 char *p = rs->buf;
11207 int left = get_remote_packet_size () - 1;
11208
80152258
PA
11209 readahead_cache_invalidate_fd (fd);
11210
a6b151f1
DJ
11211 remote_buffer_add_string (&p, &left, "vFile:close:");
11212
11213 remote_buffer_add_int (&p, &left, fd);
11214
11215 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11216 remote_errno, NULL, NULL);
11217}
11218
12e2a5fd 11219/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11220
11221static int
dbbca37d 11222remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11223 struct inferior *inf, const char *filename,
11224 int *remote_errno)
a6b151f1
DJ
11225{
11226 struct remote_state *rs = get_remote_state ();
11227 char *p = rs->buf;
11228 int left = get_remote_packet_size () - 1;
11229
15a201c8
GB
11230 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11231 return -1;
11232
a6b151f1
DJ
11233 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11234
11235 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11236 strlen (filename));
11237
11238 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11239 remote_errno, NULL, NULL);
11240}
11241
12e2a5fd 11242/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11243
11244static char *
fab5aa7c 11245remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11246 struct inferior *inf, const char *filename,
11247 int *remote_errno)
b9e7b9c3
UW
11248{
11249 struct remote_state *rs = get_remote_state ();
11250 char *p = rs->buf;
11251 char *attachment;
11252 int left = get_remote_packet_size ();
11253 int len, attachment_len;
11254 int read_len;
11255 char *ret;
11256
15a201c8
GB
11257 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11258 return NULL;
11259
b9e7b9c3
UW
11260 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11261
11262 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11263 strlen (filename));
11264
11265 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11266 remote_errno, &attachment,
11267 &attachment_len);
11268
11269 if (len < 0)
11270 return NULL;
11271
224c3ddb 11272 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11273
bc20a4af
PA
11274 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11275 (gdb_byte *) ret, len);
b9e7b9c3
UW
11276 if (read_len != len)
11277 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11278
11279 ret[len] = '\0';
11280 return ret;
11281}
11282
12e2a5fd 11283/* Implementation of to_fileio_fstat. */
0a93529c
GB
11284
11285static int
11286remote_hostio_fstat (struct target_ops *self,
11287 int fd, struct stat *st,
11288 int *remote_errno)
11289{
11290 struct remote_state *rs = get_remote_state ();
11291 char *p = rs->buf;
11292 int left = get_remote_packet_size ();
11293 int attachment_len, ret;
11294 char *attachment;
11295 struct fio_stat fst;
11296 int read_len;
11297
464b0089
GB
11298 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11299
11300 remote_buffer_add_int (&p, &left, fd);
11301
11302 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11303 remote_errno, &attachment,
11304 &attachment_len);
11305 if (ret < 0)
0a93529c 11306 {
464b0089
GB
11307 if (*remote_errno != FILEIO_ENOSYS)
11308 return ret;
11309
0a93529c
GB
11310 /* Strictly we should return -1, ENOSYS here, but when
11311 "set sysroot remote:" was implemented in August 2008
11312 BFD's need for a stat function was sidestepped with
11313 this hack. This was not remedied until March 2015
11314 so we retain the previous behavior to avoid breaking
11315 compatibility.
11316
11317 Note that the memset is a March 2015 addition; older
11318 GDBs set st_size *and nothing else* so the structure
11319 would have garbage in all other fields. This might
11320 break something but retaining the previous behavior
11321 here would be just too wrong. */
11322
11323 memset (st, 0, sizeof (struct stat));
11324 st->st_size = INT_MAX;
11325 return 0;
11326 }
11327
0a93529c
GB
11328 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11329 (gdb_byte *) &fst, sizeof (fst));
11330
11331 if (read_len != ret)
11332 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11333
11334 if (read_len != sizeof (fst))
11335 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11336 read_len, (int) sizeof (fst));
11337
11338 remote_fileio_to_host_stat (&fst, st);
11339
11340 return 0;
11341}
11342
12e2a5fd 11343/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11344
11345static int
11346remote_filesystem_is_local (struct target_ops *self)
11347{
11348 /* Valgrind GDB presents itself as a remote target but works
11349 on the local filesystem: it does not implement remote get
11350 and users are not expected to set a sysroot. To handle
11351 this case we treat the remote filesystem as local if the
11352 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11353 does not support vFile:open. */
a3be80c3 11354 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11355 {
11356 enum packet_support ps = packet_support (PACKET_vFile_open);
11357
11358 if (ps == PACKET_SUPPORT_UNKNOWN)
11359 {
11360 int fd, remote_errno;
11361
11362 /* Try opening a file to probe support. The supplied
11363 filename is irrelevant, we only care about whether
11364 the stub recognizes the packet or not. */
07c138c8 11365 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11366 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11367 &remote_errno);
11368
11369 if (fd >= 0)
11370 remote_hostio_close (self, fd, &remote_errno);
11371
11372 ps = packet_support (PACKET_vFile_open);
11373 }
11374
11375 if (ps == PACKET_DISABLE)
11376 {
11377 static int warning_issued = 0;
11378
11379 if (!warning_issued)
11380 {
11381 warning (_("remote target does not support file"
11382 " transfer, attempting to access files"
11383 " from local filesystem."));
11384 warning_issued = 1;
11385 }
11386
11387 return 1;
11388 }
11389 }
11390
11391 return 0;
11392}
11393
a6b151f1
DJ
11394static int
11395remote_fileio_errno_to_host (int errnum)
11396{
11397 switch (errnum)
11398 {
11399 case FILEIO_EPERM:
11400 return EPERM;
11401 case FILEIO_ENOENT:
11402 return ENOENT;
11403 case FILEIO_EINTR:
11404 return EINTR;
11405 case FILEIO_EIO:
11406 return EIO;
11407 case FILEIO_EBADF:
11408 return EBADF;
11409 case FILEIO_EACCES:
11410 return EACCES;
11411 case FILEIO_EFAULT:
11412 return EFAULT;
11413 case FILEIO_EBUSY:
11414 return EBUSY;
11415 case FILEIO_EEXIST:
11416 return EEXIST;
11417 case FILEIO_ENODEV:
11418 return ENODEV;
11419 case FILEIO_ENOTDIR:
11420 return ENOTDIR;
11421 case FILEIO_EISDIR:
11422 return EISDIR;
11423 case FILEIO_EINVAL:
11424 return EINVAL;
11425 case FILEIO_ENFILE:
11426 return ENFILE;
11427 case FILEIO_EMFILE:
11428 return EMFILE;
11429 case FILEIO_EFBIG:
11430 return EFBIG;
11431 case FILEIO_ENOSPC:
11432 return ENOSPC;
11433 case FILEIO_ESPIPE:
11434 return ESPIPE;
11435 case FILEIO_EROFS:
11436 return EROFS;
11437 case FILEIO_ENOSYS:
11438 return ENOSYS;
11439 case FILEIO_ENAMETOOLONG:
11440 return ENAMETOOLONG;
11441 }
11442 return -1;
11443}
11444
11445static char *
11446remote_hostio_error (int errnum)
11447{
11448 int host_error = remote_fileio_errno_to_host (errnum);
11449
11450 if (host_error == -1)
11451 error (_("Unknown remote I/O error %d"), errnum);
11452 else
11453 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11454}
11455
a6b151f1
DJ
11456static void
11457remote_hostio_close_cleanup (void *opaque)
11458{
11459 int fd = *(int *) opaque;
11460 int remote_errno;
11461
df39ea25 11462 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11463}
11464
11465void
11466remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11467{
11468 struct cleanup *back_to, *close_cleanup;
11469 int retcode, fd, remote_errno, bytes, io_size;
11470 FILE *file;
11471 gdb_byte *buffer;
11472 int bytes_in_buffer;
11473 int saw_eof;
11474 ULONGEST offset;
5d93a237 11475 struct remote_state *rs = get_remote_state ();
a6b151f1 11476
5d93a237 11477 if (!rs->remote_desc)
a6b151f1
DJ
11478 error (_("command can only be used with remote target"));
11479
614c279d 11480 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11481 if (file == NULL)
11482 perror_with_name (local_file);
7c8a8b04 11483 back_to = make_cleanup_fclose (file);
a6b151f1 11484
07c138c8 11485 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11486 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11487 | FILEIO_O_TRUNC),
4313b8c0 11488 0700, 0, &remote_errno);
a6b151f1
DJ
11489 if (fd == -1)
11490 remote_hostio_error (remote_errno);
11491
11492 /* Send up to this many bytes at once. They won't all fit in the
11493 remote packet limit, so we'll transfer slightly fewer. */
11494 io_size = get_remote_packet_size ();
224c3ddb 11495 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11496 make_cleanup (xfree, buffer);
11497
11498 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11499
11500 bytes_in_buffer = 0;
11501 saw_eof = 0;
11502 offset = 0;
11503 while (bytes_in_buffer || !saw_eof)
11504 {
11505 if (!saw_eof)
11506 {
3e43a32a
MS
11507 bytes = fread (buffer + bytes_in_buffer, 1,
11508 io_size - bytes_in_buffer,
a6b151f1
DJ
11509 file);
11510 if (bytes == 0)
11511 {
11512 if (ferror (file))
11513 error (_("Error reading %s."), local_file);
11514 else
11515 {
11516 /* EOF. Unless there is something still in the
11517 buffer from the last iteration, we are done. */
11518 saw_eof = 1;
11519 if (bytes_in_buffer == 0)
11520 break;
11521 }
11522 }
11523 }
11524 else
11525 bytes = 0;
11526
11527 bytes += bytes_in_buffer;
11528 bytes_in_buffer = 0;
11529
0d866f62
TT
11530 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11531 fd, buffer, bytes,
3e43a32a 11532 offset, &remote_errno);
a6b151f1
DJ
11533
11534 if (retcode < 0)
11535 remote_hostio_error (remote_errno);
11536 else if (retcode == 0)
11537 error (_("Remote write of %d bytes returned 0!"), bytes);
11538 else if (retcode < bytes)
11539 {
11540 /* Short write. Save the rest of the read data for the next
11541 write. */
11542 bytes_in_buffer = bytes - retcode;
11543 memmove (buffer, buffer + retcode, bytes_in_buffer);
11544 }
11545
11546 offset += retcode;
11547 }
11548
11549 discard_cleanups (close_cleanup);
df39ea25 11550 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11551 remote_hostio_error (remote_errno);
11552
11553 if (from_tty)
11554 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11555 do_cleanups (back_to);
11556}
11557
11558void
11559remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11560{
11561 struct cleanup *back_to, *close_cleanup;
cea39f65 11562 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11563 FILE *file;
11564 gdb_byte *buffer;
11565 ULONGEST offset;
5d93a237 11566 struct remote_state *rs = get_remote_state ();
a6b151f1 11567
5d93a237 11568 if (!rs->remote_desc)
a6b151f1
DJ
11569 error (_("command can only be used with remote target"));
11570
07c138c8 11571 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11572 remote_file, FILEIO_O_RDONLY, 0, 0,
11573 &remote_errno);
a6b151f1
DJ
11574 if (fd == -1)
11575 remote_hostio_error (remote_errno);
11576
614c279d 11577 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11578 if (file == NULL)
11579 perror_with_name (local_file);
7c8a8b04 11580 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11581
11582 /* Send up to this many bytes at once. They won't all fit in the
11583 remote packet limit, so we'll transfer slightly fewer. */
11584 io_size = get_remote_packet_size ();
224c3ddb 11585 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11586 make_cleanup (xfree, buffer);
11587
11588 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11589
11590 offset = 0;
11591 while (1)
11592 {
a3be983c
TT
11593 bytes = remote_hostio_pread (find_target_at (process_stratum),
11594 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11595 if (bytes == 0)
11596 /* Success, but no bytes, means end-of-file. */
11597 break;
11598 if (bytes == -1)
11599 remote_hostio_error (remote_errno);
11600
11601 offset += bytes;
11602
11603 bytes = fwrite (buffer, 1, bytes, file);
11604 if (bytes == 0)
11605 perror_with_name (local_file);
11606 }
11607
11608 discard_cleanups (close_cleanup);
df39ea25 11609 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11610 remote_hostio_error (remote_errno);
11611
11612 if (from_tty)
11613 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11614 do_cleanups (back_to);
11615}
11616
11617void
11618remote_file_delete (const char *remote_file, int from_tty)
11619{
11620 int retcode, remote_errno;
5d93a237 11621 struct remote_state *rs = get_remote_state ();
a6b151f1 11622
5d93a237 11623 if (!rs->remote_desc)
a6b151f1
DJ
11624 error (_("command can only be used with remote target"));
11625
dbbca37d 11626 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11627 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11628 if (retcode == -1)
11629 remote_hostio_error (remote_errno);
11630
11631 if (from_tty)
11632 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11633}
11634
11635static void
11636remote_put_command (char *args, int from_tty)
11637{
11638 struct cleanup *back_to;
11639 char **argv;
11640
d1a41061
PP
11641 if (args == NULL)
11642 error_no_arg (_("file to put"));
11643
11644 argv = gdb_buildargv (args);
a6b151f1
DJ
11645 back_to = make_cleanup_freeargv (argv);
11646 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11647 error (_("Invalid parameters to remote put"));
11648
11649 remote_file_put (argv[0], argv[1], from_tty);
11650
11651 do_cleanups (back_to);
11652}
11653
11654static void
11655remote_get_command (char *args, int from_tty)
11656{
11657 struct cleanup *back_to;
11658 char **argv;
11659
d1a41061
PP
11660 if (args == NULL)
11661 error_no_arg (_("file to get"));
11662
11663 argv = gdb_buildargv (args);
a6b151f1
DJ
11664 back_to = make_cleanup_freeargv (argv);
11665 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11666 error (_("Invalid parameters to remote get"));
11667
11668 remote_file_get (argv[0], argv[1], from_tty);
11669
11670 do_cleanups (back_to);
11671}
11672
11673static void
11674remote_delete_command (char *args, int from_tty)
11675{
11676 struct cleanup *back_to;
11677 char **argv;
11678
d1a41061
PP
11679 if (args == NULL)
11680 error_no_arg (_("file to delete"));
11681
11682 argv = gdb_buildargv (args);
a6b151f1
DJ
11683 back_to = make_cleanup_freeargv (argv);
11684 if (argv[0] == NULL || argv[1] != NULL)
11685 error (_("Invalid parameters to remote delete"));
11686
11687 remote_file_delete (argv[0], from_tty);
11688
11689 do_cleanups (back_to);
11690}
11691
11692static void
11693remote_command (char *args, int from_tty)
11694{
635c7e8a 11695 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11696}
11697
b2175913 11698static int
19db3e69 11699remote_can_execute_reverse (struct target_ops *self)
b2175913 11700{
4082afcc
PA
11701 if (packet_support (PACKET_bs) == PACKET_ENABLE
11702 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11703 return 1;
11704 else
11705 return 0;
b2175913
MS
11706}
11707
74531fed 11708static int
2a9a2795 11709remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11710{
11711 return 1;
11712}
11713
03583c20 11714static int
2bfc0540 11715remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11716{
11717 /* Only supported in extended mode. */
11718 return 0;
11719}
11720
8a305172 11721static int
86ce2668 11722remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11723{
11724 struct remote_state *rs = get_remote_state ();
a744cf53 11725
8020350c 11726 return remote_multi_process_p (rs);
8a305172
PA
11727}
11728
70221824 11729static int
782b2b07
SS
11730remote_supports_cond_tracepoints (void)
11731{
4082afcc 11732 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11733}
11734
3788aec7 11735static int
efcc2da7 11736remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11737{
4082afcc 11738 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11739}
11740
70221824 11741static int
7a697b8d
SS
11742remote_supports_fast_tracepoints (void)
11743{
4082afcc 11744 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11745}
11746
0fb4aa4b
PA
11747static int
11748remote_supports_static_tracepoints (void)
11749{
4082afcc 11750 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11751}
11752
1e4d1764
YQ
11753static int
11754remote_supports_install_in_trace (void)
11755{
4082afcc 11756 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11757}
11758
d248b706 11759static int
7d178d6a 11760remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11761{
4082afcc
PA
11762 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11763 == PACKET_ENABLE);
d248b706
KY
11764}
11765
3065dfb6 11766static int
6de37a3a 11767remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11768{
4082afcc 11769 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11770}
11771
d3ce09f5 11772static int
78eff0ec 11773remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11774{
4082afcc 11775 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11776}
11777
35b1e5cc 11778static void
ecae04e1 11779remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11780{
11781 putpkt ("QTinit");
11782 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11783 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11784 error (_("Target does not support this command."));
11785}
11786
11787static void free_actions_list (char **actions_list);
11788static void free_actions_list_cleanup_wrapper (void *);
11789static void
11790free_actions_list_cleanup_wrapper (void *al)
11791{
19ba03f4 11792 free_actions_list ((char **) al);
35b1e5cc
SS
11793}
11794
11795static void
11796free_actions_list (char **actions_list)
11797{
11798 int ndx;
11799
11800 if (actions_list == 0)
11801 return;
11802
11803 for (ndx = 0; actions_list[ndx]; ndx++)
11804 xfree (actions_list[ndx]);
11805
11806 xfree (actions_list);
11807}
11808
409873ef
SS
11809/* Recursive routine to walk through command list including loops, and
11810 download packets for each command. */
11811
11812static void
11813remote_download_command_source (int num, ULONGEST addr,
11814 struct command_line *cmds)
11815{
11816 struct remote_state *rs = get_remote_state ();
11817 struct command_line *cmd;
11818
11819 for (cmd = cmds; cmd; cmd = cmd->next)
11820 {
0df8b418 11821 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11822 strcpy (rs->buf, "QTDPsrc:");
11823 encode_source_string (num, addr, "cmd", cmd->line,
11824 rs->buf + strlen (rs->buf),
11825 rs->buf_size - strlen (rs->buf));
11826 putpkt (rs->buf);
11827 remote_get_noisy_reply (&target_buf, &target_buf_size);
11828 if (strcmp (target_buf, "OK"))
11829 warning (_("Target does not support source download."));
11830
11831 if (cmd->control_type == while_control
11832 || cmd->control_type == while_stepping_control)
11833 {
11834 remote_download_command_source (num, addr, *cmd->body_list);
11835
0df8b418 11836 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11837 strcpy (rs->buf, "QTDPsrc:");
11838 encode_source_string (num, addr, "cmd", "end",
11839 rs->buf + strlen (rs->buf),
11840 rs->buf_size - strlen (rs->buf));
11841 putpkt (rs->buf);
11842 remote_get_noisy_reply (&target_buf, &target_buf_size);
11843 if (strcmp (target_buf, "OK"))
11844 warning (_("Target does not support source download."));
11845 }
11846 }
11847}
11848
35b1e5cc 11849static void
548f7808 11850remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11851{
bba74b36 11852#define BUF_SIZE 2048
e8ba3115 11853
35b1e5cc 11854 CORE_ADDR tpaddr;
409873ef 11855 char addrbuf[40];
bba74b36 11856 char buf[BUF_SIZE];
35b1e5cc
SS
11857 char **tdp_actions;
11858 char **stepping_actions;
11859 int ndx;
11860 struct cleanup *old_chain = NULL;
11861 struct agent_expr *aexpr;
11862 struct cleanup *aexpr_chain = NULL;
11863 char *pkt;
e8ba3115 11864 struct breakpoint *b = loc->owner;
d9b3f62e 11865 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11866
dc673c81 11867 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11868 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11869 tdp_actions);
11870 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11871 stepping_actions);
11872
11873 tpaddr = loc->address;
11874 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11875 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11876 addrbuf, /* address */
11877 (b->enable_state == bp_enabled ? 'E' : 'D'),
11878 t->step_count, t->pass_count);
e8ba3115
YQ
11879 /* Fast tracepoints are mostly handled by the target, but we can
11880 tell the target how big of an instruction block should be moved
11881 around. */
11882 if (b->type == bp_fast_tracepoint)
11883 {
11884 /* Only test for support at download time; we may not know
11885 target capabilities at definition time. */
11886 if (remote_supports_fast_tracepoints ())
35b1e5cc 11887 {
6b940e6a
PL
11888 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11889 NULL))
bba74b36 11890 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11891 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11892 else
e8ba3115
YQ
11893 /* If it passed validation at definition but fails now,
11894 something is very wrong. */
11895 internal_error (__FILE__, __LINE__,
11896 _("Fast tracepoint not "
11897 "valid during download"));
35b1e5cc 11898 }
e8ba3115
YQ
11899 else
11900 /* Fast tracepoints are functionally identical to regular
11901 tracepoints, so don't take lack of support as a reason to
11902 give up on the trace run. */
11903 warning (_("Target does not support fast tracepoints, "
11904 "downloading %d as regular tracepoint"), b->number);
11905 }
11906 else if (b->type == bp_static_tracepoint)
11907 {
11908 /* Only test for support at download time; we may not know
11909 target capabilities at definition time. */
11910 if (remote_supports_static_tracepoints ())
0fb4aa4b 11911 {
e8ba3115 11912 struct static_tracepoint_marker marker;
0fb4aa4b 11913
e8ba3115
YQ
11914 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11915 strcat (buf, ":S");
0fb4aa4b 11916 else
e8ba3115 11917 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11918 }
e8ba3115
YQ
11919 else
11920 /* Fast tracepoints are functionally identical to regular
11921 tracepoints, so don't take lack of support as a reason
11922 to give up on the trace run. */
11923 error (_("Target does not support static tracepoints"));
11924 }
11925 /* If the tracepoint has a conditional, make it into an agent
11926 expression and append to the definition. */
11927 if (loc->cond)
11928 {
11929 /* Only test support at download time, we may not know target
11930 capabilities at definition time. */
11931 if (remote_supports_cond_tracepoints ())
35b1e5cc 11932 {
e8ba3115
YQ
11933 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11934 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11935 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11936 aexpr->len);
e8ba3115
YQ
11937 pkt = buf + strlen (buf);
11938 for (ndx = 0; ndx < aexpr->len; ++ndx)
11939 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11940 *pkt = '\0';
11941 do_cleanups (aexpr_chain);
35b1e5cc 11942 }
e8ba3115
YQ
11943 else
11944 warning (_("Target does not support conditional tracepoints, "
11945 "ignoring tp %d cond"), b->number);
11946 }
35b1e5cc 11947
d9b3f62e 11948 if (b->commands || *default_collect)
e8ba3115
YQ
11949 strcat (buf, "-");
11950 putpkt (buf);
11951 remote_get_noisy_reply (&target_buf, &target_buf_size);
11952 if (strcmp (target_buf, "OK"))
11953 error (_("Target does not support tracepoints."));
35b1e5cc 11954
e8ba3115
YQ
11955 /* do_single_steps (t); */
11956 if (tdp_actions)
11957 {
11958 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11959 {
e8ba3115 11960 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11961 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11962 b->number, addrbuf, /* address */
11963 tdp_actions[ndx],
11964 ((tdp_actions[ndx + 1] || stepping_actions)
11965 ? '-' : 0));
e8ba3115
YQ
11966 putpkt (buf);
11967 remote_get_noisy_reply (&target_buf,
11968 &target_buf_size);
11969 if (strcmp (target_buf, "OK"))
11970 error (_("Error on target while setting tracepoints."));
35b1e5cc 11971 }
e8ba3115
YQ
11972 }
11973 if (stepping_actions)
11974 {
11975 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11976 {
e8ba3115 11977 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11978 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11979 b->number, addrbuf, /* address */
11980 ((ndx == 0) ? "S" : ""),
11981 stepping_actions[ndx],
11982 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11983 putpkt (buf);
11984 remote_get_noisy_reply (&target_buf,
11985 &target_buf_size);
11986 if (strcmp (target_buf, "OK"))
11987 error (_("Error on target while setting tracepoints."));
35b1e5cc 11988 }
e8ba3115 11989 }
409873ef 11990
4082afcc 11991 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11992 {
f00aae0f 11993 if (b->location != NULL)
409873ef 11994 {
e8ba3115 11995 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11996 encode_source_string (b->number, loc->address, "at",
11997 event_location_to_string (b->location),
11998 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11999 putpkt (buf);
12000 remote_get_noisy_reply (&target_buf, &target_buf_size);
12001 if (strcmp (target_buf, "OK"))
12002 warning (_("Target does not support source download."));
409873ef 12003 }
e8ba3115
YQ
12004 if (b->cond_string)
12005 {
12006 strcpy (buf, "QTDPsrc:");
12007 encode_source_string (b->number, loc->address,
12008 "cond", b->cond_string, buf + strlen (buf),
12009 2048 - strlen (buf));
12010 putpkt (buf);
12011 remote_get_noisy_reply (&target_buf, &target_buf_size);
12012 if (strcmp (target_buf, "OK"))
12013 warning (_("Target does not support source download."));
12014 }
12015 remote_download_command_source (b->number, loc->address,
12016 breakpoint_commands (b));
35b1e5cc 12017 }
e8ba3115
YQ
12018
12019 do_cleanups (old_chain);
35b1e5cc
SS
12020}
12021
1e4d1764 12022static int
a52a8357 12023remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 12024{
1e51243a
PA
12025 struct remote_state *rs = get_remote_state ();
12026 struct trace_status *ts;
12027 int status;
12028
12029 /* Don't try to install tracepoints until we've relocated our
12030 symbols, and fetched and merged the target's tracepoint list with
12031 ours. */
12032 if (rs->starting_up)
12033 return 0;
12034
12035 ts = current_trace_status ();
8bd200f1 12036 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
12037
12038 if (status == -1 || !ts->running_known || !ts->running)
12039 return 0;
12040
12041 /* If we are in a tracing experiment, but remote stub doesn't support
12042 installing tracepoint in trace, we have to return. */
12043 if (!remote_supports_install_in_trace ())
12044 return 0;
12045
12046 return 1;
12047}
12048
12049
35b1e5cc 12050static void
559d2b81
TT
12051remote_download_trace_state_variable (struct target_ops *self,
12052 struct trace_state_variable *tsv)
35b1e5cc
SS
12053{
12054 struct remote_state *rs = get_remote_state ();
00bf0b85 12055 char *p;
35b1e5cc 12056
bba74b36
YQ
12057 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12058 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12059 tsv->builtin);
00bf0b85
SS
12060 p = rs->buf + strlen (rs->buf);
12061 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12062 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 12063 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 12064 *p++ = '\0';
35b1e5cc
SS
12065 putpkt (rs->buf);
12066 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12067 if (*target_buf == '\0')
12068 error (_("Target does not support this command."));
12069 if (strcmp (target_buf, "OK") != 0)
12070 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12071}
12072
d248b706 12073static void
46670d57
TT
12074remote_enable_tracepoint (struct target_ops *self,
12075 struct bp_location *location)
d248b706
KY
12076{
12077 struct remote_state *rs = get_remote_state ();
12078 char addr_buf[40];
12079
12080 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12081 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12082 location->owner->number, addr_buf);
d248b706
KY
12083 putpkt (rs->buf);
12084 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12085 if (*rs->buf == '\0')
12086 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12087 if (strcmp (rs->buf, "OK") != 0)
12088 error (_("Error on target while enabling tracepoint."));
12089}
12090
12091static void
780b049c
TT
12092remote_disable_tracepoint (struct target_ops *self,
12093 struct bp_location *location)
d248b706
KY
12094{
12095 struct remote_state *rs = get_remote_state ();
12096 char addr_buf[40];
12097
12098 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12099 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12100 location->owner->number, addr_buf);
d248b706
KY
12101 putpkt (rs->buf);
12102 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12103 if (*rs->buf == '\0')
12104 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12105 if (strcmp (rs->buf, "OK") != 0)
12106 error (_("Error on target while disabling tracepoint."));
12107}
12108
35b1e5cc 12109static void
583f9a86 12110remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12111{
12112 asection *s;
81b9b86e 12113 bfd *abfd = NULL;
35b1e5cc 12114 bfd_size_type size;
608bcef2 12115 bfd_vma vma;
35b1e5cc 12116 int anysecs = 0;
c2fa21f1 12117 int offset = 0;
35b1e5cc
SS
12118
12119 if (!exec_bfd)
12120 return; /* No information to give. */
12121
12122 strcpy (target_buf, "QTro");
9779ab84 12123 offset = strlen (target_buf);
35b1e5cc
SS
12124 for (s = exec_bfd->sections; s; s = s->next)
12125 {
12126 char tmp1[40], tmp2[40];
c2fa21f1 12127 int sec_length;
35b1e5cc
SS
12128
12129 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12130 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12131 (s->flags & SEC_READONLY) == 0)
12132 continue;
12133
12134 anysecs = 1;
81b9b86e 12135 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12136 size = bfd_get_section_size (s);
608bcef2
HZ
12137 sprintf_vma (tmp1, vma);
12138 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12139 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12140 if (offset + sec_length + 1 > target_buf_size)
12141 {
4082afcc 12142 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12143 warning (_("\
c2fa21f1
HZ
12144Too many sections for read-only sections definition packet."));
12145 break;
12146 }
bba74b36
YQ
12147 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12148 tmp1, tmp2);
c2fa21f1 12149 offset += sec_length;
35b1e5cc
SS
12150 }
12151 if (anysecs)
12152 {
12153 putpkt (target_buf);
12154 getpkt (&target_buf, &target_buf_size, 0);
12155 }
12156}
12157
12158static void
e2d1aae3 12159remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12160{
12161 putpkt ("QTStart");
12162 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12163 if (*target_buf == '\0')
12164 error (_("Target does not support this command."));
12165 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12166 error (_("Bogus reply from target: %s"), target_buf);
12167}
12168
12169static int
8bd200f1 12170remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12171{
953b98d1 12172 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12173 char *p = NULL;
0df8b418 12174 /* FIXME we need to get register block size some other way. */
00bf0b85 12175 extern int trace_regblock_size;
bd3eecc3
PA
12176 enum packet_result result;
12177
4082afcc 12178 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12179 return -1;
a744cf53 12180
00bf0b85
SS
12181 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12182
049dc89b
JK
12183 putpkt ("qTStatus");
12184
492d29ea 12185 TRY
67f41397
JK
12186 {
12187 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12188 }
492d29ea 12189 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12190 {
598d3636
JK
12191 if (ex.error != TARGET_CLOSE_ERROR)
12192 {
12193 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12194 return -1;
12195 }
12196 throw_exception (ex);
67f41397 12197 }
492d29ea 12198 END_CATCH
00bf0b85 12199
bd3eecc3
PA
12200 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12201
00bf0b85 12202 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12203 if (result == PACKET_UNKNOWN)
00bf0b85 12204 return -1;
35b1e5cc 12205
00bf0b85 12206 /* We're working with a live target. */
f5911ea1 12207 ts->filename = NULL;
00bf0b85 12208
00bf0b85 12209 if (*p++ != 'T')
35b1e5cc
SS
12210 error (_("Bogus trace status reply from target: %s"), target_buf);
12211
84cebc4a
YQ
12212 /* Function 'parse_trace_status' sets default value of each field of
12213 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12214 parse_trace_status (p, ts);
12215
12216 return ts->running;
35b1e5cc
SS
12217}
12218
70221824 12219static void
db90e85c 12220remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12221 struct uploaded_tp *utp)
12222{
12223 struct remote_state *rs = get_remote_state ();
f196051f
SS
12224 char *reply;
12225 struct bp_location *loc;
12226 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12227 size_t size = get_remote_packet_size ();
f196051f
SS
12228
12229 if (tp)
12230 {
12231 tp->base.hit_count = 0;
12232 tp->traceframe_usage = 0;
12233 for (loc = tp->base.loc; loc; loc = loc->next)
12234 {
12235 /* If the tracepoint was never downloaded, don't go asking for
12236 any status. */
12237 if (tp->number_on_target == 0)
12238 continue;
bba74b36
YQ
12239 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12240 phex_nz (loc->address, 0));
f196051f
SS
12241 putpkt (rs->buf);
12242 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12243 if (reply && *reply)
12244 {
12245 if (*reply == 'V')
12246 parse_tracepoint_status (reply + 1, bp, utp);
12247 }
12248 }
12249 }
12250 else if (utp)
12251 {
12252 utp->hit_count = 0;
12253 utp->traceframe_usage = 0;
bba74b36
YQ
12254 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12255 phex_nz (utp->addr, 0));
f196051f
SS
12256 putpkt (rs->buf);
12257 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12258 if (reply && *reply)
12259 {
12260 if (*reply == 'V')
12261 parse_tracepoint_status (reply + 1, bp, utp);
12262 }
12263 }
12264}
12265
35b1e5cc 12266static void
74499f1b 12267remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12268{
12269 putpkt ("QTStop");
12270 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12271 if (*target_buf == '\0')
12272 error (_("Target does not support this command."));
12273 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12274 error (_("Bogus reply from target: %s"), target_buf);
12275}
12276
12277static int
bd4c6793
TT
12278remote_trace_find (struct target_ops *self,
12279 enum trace_find_type type, int num,
cc5925ad 12280 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12281 int *tpp)
12282{
12283 struct remote_state *rs = get_remote_state ();
bba74b36 12284 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12285 char *p, *reply;
12286 int target_frameno = -1, target_tracept = -1;
12287
e6e4e701
PA
12288 /* Lookups other than by absolute frame number depend on the current
12289 trace selected, so make sure it is correct on the remote end
12290 first. */
12291 if (type != tfind_number)
12292 set_remote_traceframe ();
12293
35b1e5cc
SS
12294 p = rs->buf;
12295 strcpy (p, "QTFrame:");
12296 p = strchr (p, '\0');
12297 switch (type)
12298 {
12299 case tfind_number:
bba74b36 12300 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12301 break;
12302 case tfind_pc:
bba74b36 12303 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12304 break;
12305 case tfind_tp:
bba74b36 12306 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12307 break;
12308 case tfind_range:
bba74b36
YQ
12309 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12310 phex_nz (addr2, 0));
35b1e5cc
SS
12311 break;
12312 case tfind_outside:
bba74b36
YQ
12313 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12314 phex_nz (addr2, 0));
35b1e5cc
SS
12315 break;
12316 default:
9b20d036 12317 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12318 }
12319
12320 putpkt (rs->buf);
2f65bcb7 12321 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12322 if (*reply == '\0')
12323 error (_("Target does not support this command."));
35b1e5cc
SS
12324
12325 while (reply && *reply)
12326 switch (*reply)
12327 {
12328 case 'F':
f197e0f1
VP
12329 p = ++reply;
12330 target_frameno = (int) strtol (p, &reply, 16);
12331 if (reply == p)
12332 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12333 /* Don't update our remote traceframe number cache on failure
12334 to select a remote traceframe. */
f197e0f1
VP
12335 if (target_frameno == -1)
12336 return -1;
35b1e5cc
SS
12337 break;
12338 case 'T':
f197e0f1
VP
12339 p = ++reply;
12340 target_tracept = (int) strtol (p, &reply, 16);
12341 if (reply == p)
12342 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12343 break;
12344 case 'O': /* "OK"? */
12345 if (reply[1] == 'K' && reply[2] == '\0')
12346 reply += 2;
12347 else
12348 error (_("Bogus reply from target: %s"), reply);
12349 break;
12350 default:
12351 error (_("Bogus reply from target: %s"), reply);
12352 }
12353 if (tpp)
12354 *tpp = target_tracept;
e6e4e701 12355
262e1174 12356 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12357 return target_frameno;
12358}
12359
12360static int
4011015b
TT
12361remote_get_trace_state_variable_value (struct target_ops *self,
12362 int tsvnum, LONGEST *val)
35b1e5cc
SS
12363{
12364 struct remote_state *rs = get_remote_state ();
12365 char *reply;
12366 ULONGEST uval;
12367
e6e4e701
PA
12368 set_remote_traceframe ();
12369
bba74b36 12370 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12371 putpkt (rs->buf);
12372 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12373 if (reply && *reply)
12374 {
12375 if (*reply == 'V')
12376 {
12377 unpack_varlen_hex (reply + 1, &uval);
12378 *val = (LONGEST) uval;
12379 return 1;
12380 }
12381 }
12382 return 0;
12383}
12384
00bf0b85 12385static int
dc3decaf 12386remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12387{
12388 struct remote_state *rs = get_remote_state ();
12389 char *p, *reply;
12390
12391 p = rs->buf;
12392 strcpy (p, "QTSave:");
12393 p += strlen (p);
12394 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12395 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12396 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12397 *p++ = '\0';
12398 putpkt (rs->buf);
ad91cd99 12399 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12400 if (*reply == '\0')
ad91cd99
PA
12401 error (_("Target does not support this command."));
12402 if (strcmp (reply, "OK") != 0)
12403 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12404 return 0;
12405}
12406
12407/* This is basically a memory transfer, but needs to be its own packet
12408 because we don't know how the target actually organizes its trace
12409 memory, plus we want to be able to ask for as much as possible, but
12410 not be unhappy if we don't get as much as we ask for. */
12411
12412static LONGEST
88ee6f45
TT
12413remote_get_raw_trace_data (struct target_ops *self,
12414 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12415{
12416 struct remote_state *rs = get_remote_state ();
12417 char *reply;
12418 char *p;
12419 int rslt;
12420
12421 p = rs->buf;
12422 strcpy (p, "qTBuffer:");
12423 p += strlen (p);
12424 p += hexnumstr (p, offset);
12425 *p++ = ',';
12426 p += hexnumstr (p, len);
12427 *p++ = '\0';
12428
12429 putpkt (rs->buf);
12430 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12431 if (reply && *reply)
12432 {
12433 /* 'l' by itself means we're at the end of the buffer and
12434 there is nothing more to get. */
12435 if (*reply == 'l')
12436 return 0;
12437
12438 /* Convert the reply into binary. Limit the number of bytes to
12439 convert according to our passed-in buffer size, rather than
12440 what was returned in the packet; if the target is
12441 unexpectedly generous and gives us a bigger reply than we
12442 asked for, we don't want to crash. */
12443 rslt = hex2bin (target_buf, buf, len);
12444 return rslt;
12445 }
12446
12447 /* Something went wrong, flag as an error. */
12448 return -1;
12449}
12450
35b1e5cc 12451static void
37b25738 12452remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12453{
12454 struct remote_state *rs = get_remote_state ();
12455
4082afcc 12456 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12457 {
ad91cd99
PA
12458 char *reply;
12459
bba74b36 12460 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12461 putpkt (rs->buf);
ad91cd99
PA
12462 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12463 if (*reply == '\0')
33da3f1c 12464 error (_("Target does not support this command."));
ad91cd99
PA
12465 if (strcmp (reply, "OK") != 0)
12466 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12467 }
12468 else if (val)
12469 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12470}
12471
dc146f7c
VP
12472static int
12473remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12474{
12475 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12476
fe978cb0
PA
12477 if (info && info->priv)
12478 return info->priv->core;
dc146f7c
VP
12479 return -1;
12480}
12481
4daf5ac0 12482static void
736d5b1f 12483remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12484{
12485 struct remote_state *rs = get_remote_state ();
ad91cd99 12486 char *reply;
4daf5ac0 12487
bba74b36 12488 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12489 putpkt (rs->buf);
ad91cd99
PA
12490 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12491 if (*reply == '\0')
4daf5ac0 12492 error (_("Target does not support this command."));
ad91cd99
PA
12493 if (strcmp (reply, "OK") != 0)
12494 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12495}
12496
b3b9301e 12497static struct traceframe_info *
a893e81f 12498remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12499{
12500 char *text;
12501
12502 text = target_read_stralloc (&current_target,
12503 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12504 if (text != NULL)
12505 {
12506 struct traceframe_info *info;
12507 struct cleanup *back_to = make_cleanup (xfree, text);
12508
12509 info = parse_traceframe_info (text);
12510 do_cleanups (back_to);
12511 return info;
12512 }
12513
12514 return NULL;
12515}
12516
405f8e94
SS
12517/* Handle the qTMinFTPILen packet. Returns the minimum length of
12518 instruction on which a fast tracepoint may be placed. Returns -1
12519 if the packet is not supported, and 0 if the minimum instruction
12520 length is unknown. */
12521
12522static int
0e67620a 12523remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12524{
12525 struct remote_state *rs = get_remote_state ();
12526 char *reply;
12527
e886a173
PA
12528 /* If we're not debugging a process yet, the IPA can't be
12529 loaded. */
12530 if (!target_has_execution)
12531 return 0;
12532
12533 /* Make sure the remote is pointing at the right process. */
12534 set_general_process ();
12535
bba74b36 12536 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12537 putpkt (rs->buf);
12538 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12539 if (*reply == '\0')
12540 return -1;
12541 else
12542 {
12543 ULONGEST min_insn_len;
12544
12545 unpack_varlen_hex (reply, &min_insn_len);
12546
12547 return (int) min_insn_len;
12548 }
12549}
12550
f6f899bf 12551static void
4da384be 12552remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12553{
4082afcc 12554 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12555 {
12556 struct remote_state *rs = get_remote_state ();
12557 char *buf = rs->buf;
12558 char *endbuf = rs->buf + get_remote_packet_size ();
12559 enum packet_result result;
12560
12561 gdb_assert (val >= 0 || val == -1);
12562 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12563 /* Send -1 as literal "-1" to avoid host size dependency. */
12564 if (val < 0)
12565 {
12566 *buf++ = '-';
12567 buf += hexnumstr (buf, (ULONGEST) -val);
12568 }
12569 else
12570 buf += hexnumstr (buf, (ULONGEST) val);
12571
12572 putpkt (rs->buf);
12573 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12574 result = packet_ok (rs->buf,
12575 &remote_protocol_packets[PACKET_QTBuffer_size]);
12576
12577 if (result != PACKET_OK)
12578 warning (_("Bogus reply from target: %s"), rs->buf);
12579 }
12580}
12581
f196051f 12582static int
d9e68a2c
TT
12583remote_set_trace_notes (struct target_ops *self,
12584 const char *user, const char *notes,
ca623f82 12585 const char *stop_notes)
f196051f
SS
12586{
12587 struct remote_state *rs = get_remote_state ();
12588 char *reply;
12589 char *buf = rs->buf;
12590 char *endbuf = rs->buf + get_remote_packet_size ();
12591 int nbytes;
12592
12593 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12594 if (user)
12595 {
12596 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12597 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12598 buf += 2 * nbytes;
12599 *buf++ = ';';
12600 }
12601 if (notes)
12602 {
12603 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12604 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12605 buf += 2 * nbytes;
12606 *buf++ = ';';
12607 }
12608 if (stop_notes)
12609 {
12610 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12611 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12612 buf += 2 * nbytes;
12613 *buf++ = ';';
12614 }
12615 /* Ensure the buffer is terminated. */
12616 *buf = '\0';
12617
12618 putpkt (rs->buf);
12619 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12620 if (*reply == '\0')
12621 return 0;
12622
12623 if (strcmp (reply, "OK") != 0)
12624 error (_("Bogus reply from target: %s"), reply);
12625
12626 return 1;
12627}
12628
d1feda86 12629static int
2c152180 12630remote_use_agent (struct target_ops *self, int use)
d1feda86 12631{
4082afcc 12632 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12633 {
12634 struct remote_state *rs = get_remote_state ();
12635
12636 /* If the stub supports QAgent. */
bba74b36 12637 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12638 putpkt (rs->buf);
12639 getpkt (&rs->buf, &rs->buf_size, 0);
12640
12641 if (strcmp (rs->buf, "OK") == 0)
12642 {
12643 use_agent = use;
12644 return 1;
12645 }
12646 }
12647
12648 return 0;
12649}
12650
12651static int
fe38f897 12652remote_can_use_agent (struct target_ops *self)
d1feda86 12653{
4082afcc 12654 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12655}
12656
9accd112
MM
12657struct btrace_target_info
12658{
12659 /* The ptid of the traced thread. */
12660 ptid_t ptid;
f4abbc16
MM
12661
12662 /* The obtained branch trace configuration. */
12663 struct btrace_config conf;
9accd112
MM
12664};
12665
f4abbc16
MM
12666/* Reset our idea of our target's btrace configuration. */
12667
12668static void
12669remote_btrace_reset (void)
12670{
12671 struct remote_state *rs = get_remote_state ();
12672
12673 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12674}
12675
9accd112
MM
12676/* Check whether the target supports branch tracing. */
12677
12678static int
043c3577 12679remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12680{
4082afcc 12681 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12682 return 0;
4082afcc 12683 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12684 return 0;
12685
043c3577
MM
12686 switch (format)
12687 {
12688 case BTRACE_FORMAT_NONE:
12689 return 0;
12690
12691 case BTRACE_FORMAT_BTS:
12692 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12693
12694 case BTRACE_FORMAT_PT:
12695 /* The trace is decoded on the host. Even if our target supports it,
12696 we still need to have libipt to decode the trace. */
12697#if defined (HAVE_LIBIPT)
12698 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12699#else /* !defined (HAVE_LIBIPT) */
12700 return 0;
12701#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12702 }
12703
12704 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12705}
12706
f4abbc16
MM
12707/* Synchronize the configuration with the target. */
12708
12709static void
12710btrace_sync_conf (const struct btrace_config *conf)
12711{
d33501a5
MM
12712 struct packet_config *packet;
12713 struct remote_state *rs;
12714 char *buf, *pos, *endbuf;
12715
12716 rs = get_remote_state ();
12717 buf = rs->buf;
12718 endbuf = buf + get_remote_packet_size ();
12719
12720 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12721 if (packet_config_support (packet) == PACKET_ENABLE
12722 && conf->bts.size != rs->btrace_config.bts.size)
12723 {
12724 pos = buf;
12725 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12726 conf->bts.size);
12727
12728 putpkt (buf);
12729 getpkt (&buf, &rs->buf_size, 0);
12730
12731 if (packet_ok (buf, packet) == PACKET_ERROR)
12732 {
12733 if (buf[0] == 'E' && buf[1] == '.')
12734 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12735 else
12736 error (_("Failed to configure the BTS buffer size."));
12737 }
12738
12739 rs->btrace_config.bts.size = conf->bts.size;
12740 }
b20a6524
MM
12741
12742 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12743 if (packet_config_support (packet) == PACKET_ENABLE
12744 && conf->pt.size != rs->btrace_config.pt.size)
12745 {
12746 pos = buf;
12747 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12748 conf->pt.size);
12749
12750 putpkt (buf);
12751 getpkt (&buf, &rs->buf_size, 0);
12752
12753 if (packet_ok (buf, packet) == PACKET_ERROR)
12754 {
12755 if (buf[0] == 'E' && buf[1] == '.')
12756 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12757 else
12758 error (_("Failed to configure the trace buffer size."));
12759 }
12760
12761 rs->btrace_config.pt.size = conf->pt.size;
12762 }
f4abbc16
MM
12763}
12764
12765/* Read the current thread's btrace configuration from the target and
12766 store it into CONF. */
12767
12768static void
12769btrace_read_config (struct btrace_config *conf)
12770{
12771 char *xml;
12772
12773 xml = target_read_stralloc (&current_target,
b20a6524 12774 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12775 if (xml != NULL)
12776 {
12777 struct cleanup *cleanup;
12778
12779 cleanup = make_cleanup (xfree, xml);
12780 parse_xml_btrace_conf (conf, xml);
12781 do_cleanups (cleanup);
12782 }
12783}
12784
9accd112
MM
12785/* Enable branch tracing. */
12786
12787static struct btrace_target_info *
f4abbc16
MM
12788remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12789 const struct btrace_config *conf)
9accd112
MM
12790{
12791 struct btrace_target_info *tinfo = NULL;
b20a6524 12792 struct packet_config *packet = NULL;
9accd112
MM
12793 struct remote_state *rs = get_remote_state ();
12794 char *buf = rs->buf;
12795 char *endbuf = rs->buf + get_remote_packet_size ();
12796
b20a6524
MM
12797 switch (conf->format)
12798 {
12799 case BTRACE_FORMAT_BTS:
12800 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12801 break;
12802
12803 case BTRACE_FORMAT_PT:
12804 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12805 break;
12806 }
12807
12808 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12809 error (_("Target does not support branch tracing."));
12810
f4abbc16
MM
12811 btrace_sync_conf (conf);
12812
9accd112
MM
12813 set_general_thread (ptid);
12814
12815 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12816 putpkt (rs->buf);
12817 getpkt (&rs->buf, &rs->buf_size, 0);
12818
12819 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12820 {
12821 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12822 error (_("Could not enable branch tracing for %s: %s"),
12823 target_pid_to_str (ptid), rs->buf + 2);
12824 else
12825 error (_("Could not enable branch tracing for %s."),
12826 target_pid_to_str (ptid));
12827 }
12828
8d749320 12829 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12830 tinfo->ptid = ptid;
12831
f4abbc16
MM
12832 /* If we fail to read the configuration, we lose some information, but the
12833 tracing itself is not impacted. */
492d29ea
PA
12834 TRY
12835 {
12836 btrace_read_config (&tinfo->conf);
12837 }
12838 CATCH (err, RETURN_MASK_ERROR)
12839 {
12840 if (err.message != NULL)
12841 warning ("%s", err.message);
12842 }
12843 END_CATCH
f4abbc16 12844
9accd112
MM
12845 return tinfo;
12846}
12847
12848/* Disable branch tracing. */
12849
12850static void
25e95349
TT
12851remote_disable_btrace (struct target_ops *self,
12852 struct btrace_target_info *tinfo)
9accd112
MM
12853{
12854 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12855 struct remote_state *rs = get_remote_state ();
12856 char *buf = rs->buf;
12857 char *endbuf = rs->buf + get_remote_packet_size ();
12858
4082afcc 12859 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12860 error (_("Target does not support branch tracing."));
12861
12862 set_general_thread (tinfo->ptid);
12863
12864 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12865 putpkt (rs->buf);
12866 getpkt (&rs->buf, &rs->buf_size, 0);
12867
12868 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12869 {
12870 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12871 error (_("Could not disable branch tracing for %s: %s"),
12872 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12873 else
12874 error (_("Could not disable branch tracing for %s."),
12875 target_pid_to_str (tinfo->ptid));
12876 }
12877
12878 xfree (tinfo);
12879}
12880
12881/* Teardown branch tracing. */
12882
12883static void
1777056d
TT
12884remote_teardown_btrace (struct target_ops *self,
12885 struct btrace_target_info *tinfo)
9accd112
MM
12886{
12887 /* We must not talk to the target during teardown. */
12888 xfree (tinfo);
12889}
12890
12891/* Read the branch trace. */
12892
969c39fb 12893static enum btrace_error
39c49f83 12894remote_read_btrace (struct target_ops *self,
734b0e4b 12895 struct btrace_data *btrace,
969c39fb 12896 struct btrace_target_info *tinfo,
9accd112
MM
12897 enum btrace_read_type type)
12898{
12899 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
969c39fb 12900 struct cleanup *cleanup;
9accd112
MM
12901 const char *annex;
12902 char *xml;
12903
4082afcc 12904 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12905 error (_("Target does not support branch tracing."));
12906
12907#if !defined(HAVE_LIBEXPAT)
12908 error (_("Cannot process branch tracing result. XML parsing not supported."));
12909#endif
12910
12911 switch (type)
12912 {
864089d2 12913 case BTRACE_READ_ALL:
9accd112
MM
12914 annex = "all";
12915 break;
864089d2 12916 case BTRACE_READ_NEW:
9accd112
MM
12917 annex = "new";
12918 break;
969c39fb
MM
12919 case BTRACE_READ_DELTA:
12920 annex = "delta";
12921 break;
9accd112
MM
12922 default:
12923 internal_error (__FILE__, __LINE__,
12924 _("Bad branch tracing read type: %u."),
12925 (unsigned int) type);
12926 }
12927
12928 xml = target_read_stralloc (&current_target,
b20a6524 12929 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12930 if (xml == NULL)
12931 return BTRACE_ERR_UNKNOWN;
9accd112 12932
969c39fb 12933 cleanup = make_cleanup (xfree, xml);
734b0e4b 12934 parse_xml_btrace (btrace, xml);
969c39fb 12935 do_cleanups (cleanup);
9accd112 12936
969c39fb 12937 return BTRACE_ERR_NONE;
9accd112
MM
12938}
12939
f4abbc16
MM
12940static const struct btrace_config *
12941remote_btrace_conf (struct target_ops *self,
12942 const struct btrace_target_info *tinfo)
12943{
12944 return &tinfo->conf;
12945}
12946
ced63ec0 12947static int
5436ff03 12948remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12949{
4082afcc
PA
12950 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12951 == PACKET_ENABLE);
ced63ec0
GB
12952}
12953
9dd130a0
TT
12954/* Implementation of to_load. */
12955
12956static void
9cbe5fff 12957remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12958{
12959 generic_load (name, from_tty);
12960}
12961
c78fa86a
GB
12962/* Accepts an integer PID; returns a string representing a file that
12963 can be opened on the remote side to get the symbols for the child
12964 process. Returns NULL if the operation is not supported. */
12965
12966static char *
12967remote_pid_to_exec_file (struct target_ops *self, int pid)
12968{
12969 static char *filename = NULL;
835205d0
GB
12970 struct inferior *inf;
12971 char *annex = NULL;
c78fa86a
GB
12972
12973 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12974 return NULL;
12975
12976 if (filename != NULL)
12977 xfree (filename);
12978
835205d0
GB
12979 inf = find_inferior_pid (pid);
12980 if (inf == NULL)
12981 internal_error (__FILE__, __LINE__,
12982 _("not currently attached to process %d"), pid);
12983
12984 if (!inf->fake_pid_p)
12985 {
12986 const int annex_size = 9;
12987
224c3ddb 12988 annex = (char *) alloca (annex_size);
835205d0
GB
12989 xsnprintf (annex, annex_size, "%x", pid);
12990 }
12991
c78fa86a
GB
12992 filename = target_read_stralloc (&current_target,
12993 TARGET_OBJECT_EXEC_FILE, annex);
12994
12995 return filename;
12996}
12997
750ce8d1
YQ
12998/* Implement the to_can_do_single_step target_ops method. */
12999
13000static int
13001remote_can_do_single_step (struct target_ops *ops)
13002{
13003 /* We can only tell whether target supports single step or not by
13004 supported s and S vCont actions if the stub supports vContSupported
13005 feature. If the stub doesn't support vContSupported feature,
13006 we have conservatively to think target doesn't supports single
13007 step. */
13008 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13009 {
13010 struct remote_state *rs = get_remote_state ();
13011
13012 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13013 remote_vcont_probe (rs);
13014
13015 return rs->supports_vCont.s && rs->supports_vCont.S;
13016 }
13017 else
13018 return 0;
13019}
13020
c906108c 13021static void
fba45db2 13022init_remote_ops (void)
c906108c 13023{
c5aa993b 13024 remote_ops.to_shortname = "remote";
c906108c 13025 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 13026 remote_ops.to_doc =
c906108c 13027 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
13028Specify the serial device it is connected to\n\
13029(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
13030 remote_ops.to_open = remote_open;
13031 remote_ops.to_close = remote_close;
c906108c 13032 remote_ops.to_detach = remote_detach;
6ad8ae5c 13033 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 13034 remote_ops.to_resume = remote_resume;
c906108c
SS
13035 remote_ops.to_wait = remote_wait;
13036 remote_ops.to_fetch_registers = remote_fetch_registers;
13037 remote_ops.to_store_registers = remote_store_registers;
13038 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 13039 remote_ops.to_files_info = remote_files_info;
c906108c
SS
13040 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13041 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
13042 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13043 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13044 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13045 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
13046 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13047 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
13048 remote_ops.to_watchpoint_addr_within_range =
13049 remote_watchpoint_addr_within_range;
3c3bea1c
GS
13050 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13051 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13052 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
13053 remote_ops.to_region_ok_for_hw_watchpoint
13054 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
13055 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13056 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 13057 remote_ops.to_kill = remote_kill;
9dd130a0 13058 remote_ops.to_load = remote_load;
c906108c 13059 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 13060 remote_ops.to_pass_signals = remote_pass_signals;
82075af2 13061 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
9b224c5e 13062 remote_ops.to_program_signals = remote_program_signals;
c906108c 13063 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 13064 remote_ops.to_thread_name = remote_thread_name;
e8032dde 13065 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 13066 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 13067 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 13068 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 13069 remote_ops.to_stop = remote_stop;
bfedc46a 13070 remote_ops.to_interrupt = remote_interrupt;
abc56d60 13071 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
4b8a223f 13072 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 13073 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 13074 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 13075 remote_ops.to_log_command = serial_log_command;
38691318 13076 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 13077 remote_ops.to_stratum = process_stratum;
c35b1492
PA
13078 remote_ops.to_has_all_memory = default_child_has_all_memory;
13079 remote_ops.to_has_memory = default_child_has_memory;
13080 remote_ops.to_has_stack = default_child_has_stack;
13081 remote_ops.to_has_registers = default_child_has_registers;
13082 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 13083 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13084 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13085 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13086 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13087 remote_ops.to_flash_erase = remote_flash_erase;
13088 remote_ops.to_flash_done = remote_flash_done;
29709017 13089 remote_ops.to_read_description = remote_read_description;
08388c79 13090 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13091 remote_ops.to_can_async_p = remote_can_async_p;
13092 remote_ops.to_is_async_p = remote_is_async_p;
13093 remote_ops.to_async = remote_async;
65706a29 13094 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13095 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13096 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13097 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13098 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13099 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13100 remote_ops.to_supports_disable_randomization
13101 = remote_supports_disable_randomization;
4bd7dc42 13102 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13103 remote_ops.to_fileio_open = remote_hostio_open;
13104 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13105 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13106 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13107 remote_ops.to_fileio_close = remote_hostio_close;
13108 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13109 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13110 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13111 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13112 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13113 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13114 remote_ops.to_trace_init = remote_trace_init;
13115 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13116 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13117 remote_ops.to_download_trace_state_variable
13118 = remote_download_trace_state_variable;
d248b706
KY
13119 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13120 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13121 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13122 remote_ops.to_trace_start = remote_trace_start;
13123 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13124 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13125 remote_ops.to_trace_stop = remote_trace_stop;
13126 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13127 remote_ops.to_get_trace_state_variable_value
13128 = remote_get_trace_state_variable_value;
00bf0b85
SS
13129 remote_ops.to_save_trace_data = remote_save_trace_data;
13130 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13131 remote_ops.to_upload_trace_state_variables
13132 = remote_upload_trace_state_variables;
00bf0b85 13133 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13134 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13135 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13136 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13137 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13138 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13139 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13140 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13141 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13142 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13143 remote_ops.to_static_tracepoint_marker_at
13144 = remote_static_tracepoint_marker_at;
13145 remote_ops.to_static_tracepoint_markers_by_strid
13146 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13147 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13148 remote_ops.to_use_agent = remote_use_agent;
13149 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13150 remote_ops.to_supports_btrace = remote_supports_btrace;
13151 remote_ops.to_enable_btrace = remote_enable_btrace;
13152 remote_ops.to_disable_btrace = remote_disable_btrace;
13153 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13154 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13155 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13156 remote_ops.to_augmented_libraries_svr4_read =
13157 remote_augmented_libraries_svr4_read;
8020350c
DB
13158 remote_ops.to_follow_fork = remote_follow_fork;
13159 remote_ops.to_follow_exec = remote_follow_exec;
13160 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13161 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13162 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13163 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13164 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13165 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
c906108c
SS
13166}
13167
13168/* Set up the extended remote vector by making a copy of the standard
13169 remote vector and adding to it. */
13170
13171static void
fba45db2 13172init_extended_remote_ops (void)
c906108c
SS
13173{
13174 extended_remote_ops = remote_ops;
13175
0f71a2f6 13176 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13177 extended_remote_ops.to_longname =
c906108c 13178 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13179 extended_remote_ops.to_doc =
c906108c 13180 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13181Specify the serial device it is connected to (e.g. /dev/ttya).";
13182 extended_remote_ops.to_open = extended_remote_open;
c906108c 13183 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
2d717e4f
DJ
13184 extended_remote_ops.to_detach = extended_remote_detach;
13185 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13186 extended_remote_ops.to_post_attach = extended_remote_post_attach;
03583c20
UW
13187 extended_remote_ops.to_supports_disable_randomization
13188 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
13189}
13190
6426a772 13191static int
6a109b6b 13192remote_can_async_p (struct target_ops *ops)
6426a772 13193{
5d93a237
TT
13194 struct remote_state *rs = get_remote_state ();
13195
c6ebd6cf 13196 if (!target_async_permitted)
75c99385
PA
13197 /* We only enable async when the user specifically asks for it. */
13198 return 0;
13199
23860348 13200 /* We're async whenever the serial device is. */
5d93a237 13201 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13202}
13203
13204static int
6a109b6b 13205remote_is_async_p (struct target_ops *ops)
6426a772 13206{
5d93a237
TT
13207 struct remote_state *rs = get_remote_state ();
13208
c6ebd6cf 13209 if (!target_async_permitted)
75c99385
PA
13210 /* We only enable async when the user specifically asks for it. */
13211 return 0;
13212
23860348 13213 /* We're async whenever the serial device is. */
5d93a237 13214 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13215}
13216
2acceee2
JM
13217/* Pass the SERIAL event on and up to the client. One day this code
13218 will be able to delay notifying the client of an event until the
23860348 13219 point where an entire packet has been received. */
2acceee2 13220
2acceee2
JM
13221static serial_event_ftype remote_async_serial_handler;
13222
6426a772 13223static void
819cc324 13224remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13225{
2acceee2
JM
13226 /* Don't propogate error information up to the client. Instead let
13227 the client find out about the error by querying the target. */
6a3753b3 13228 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13229}
13230
74531fed
PA
13231static void
13232remote_async_inferior_event_handler (gdb_client_data data)
13233{
13234 inferior_event_handler (INF_REG_EVENT, NULL);
13235}
13236
2acceee2 13237static void
6a3753b3 13238remote_async (struct target_ops *ops, int enable)
2acceee2 13239{
5d93a237
TT
13240 struct remote_state *rs = get_remote_state ();
13241
6a3753b3 13242 if (enable)
2acceee2 13243 {
88b496c3 13244 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13245
13246 /* If there are pending events in the stop reply queue tell the
13247 event loop to process them. */
13248 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13249 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13250 /* For simplicity, below we clear the pending events token
13251 without remembering whether it is marked, so here we always
13252 mark it. If there's actually no pending notification to
13253 process, this ends up being a no-op (other than a spurious
13254 event-loop wakeup). */
13255 if (target_is_non_stop_p ())
13256 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13257 }
13258 else
b7d2e916
PA
13259 {
13260 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13261 /* If the core is disabling async, it doesn't want to be
13262 disturbed with target events. Clear all async event sources
13263 too. */
b7d2e916 13264 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13265 if (target_is_non_stop_p ())
13266 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13267 }
6426a772
JM
13268}
13269
65706a29
PA
13270/* Implementation of the to_thread_events method. */
13271
13272static void
13273remote_thread_events (struct target_ops *ops, int enable)
13274{
13275 struct remote_state *rs = get_remote_state ();
13276 size_t size = get_remote_packet_size ();
65706a29
PA
13277
13278 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13279 return;
13280
13281 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13282 putpkt (rs->buf);
13283 getpkt (&rs->buf, &rs->buf_size, 0);
13284
13285 switch (packet_ok (rs->buf,
13286 &remote_protocol_packets[PACKET_QThreadEvents]))
13287 {
13288 case PACKET_OK:
13289 if (strcmp (rs->buf, "OK") != 0)
13290 error (_("Remote refused setting thread events: %s"), rs->buf);
13291 break;
13292 case PACKET_ERROR:
13293 warning (_("Remote failure reply: %s"), rs->buf);
13294 break;
13295 case PACKET_UNKNOWN:
13296 break;
13297 }
13298}
13299
5a2468f5 13300static void
c2d11a7d 13301set_remote_cmd (char *args, int from_tty)
5a2468f5 13302{
635c7e8a 13303 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13304}
13305
d471ea57
AC
13306static void
13307show_remote_cmd (char *args, int from_tty)
13308{
37a105a1 13309 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13310 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13311 struct cleanup *showlist_chain;
13312 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13313 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13314
13315 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13316 for (; list != NULL; list = list->next)
13317 if (strcmp (list->name, "Z-packet") == 0)
13318 continue;
427c3a89
DJ
13319 else if (list->type == not_set_cmd)
13320 /* Alias commands are exactly like the original, except they
13321 don't have the normal type. */
13322 continue;
13323 else
37a105a1
DJ
13324 {
13325 struct cleanup *option_chain
13326 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13327
37a105a1
DJ
13328 ui_out_field_string (uiout, "name", list->name);
13329 ui_out_text (uiout, ": ");
427c3a89 13330 if (list->type == show_cmd)
5b9afe8a 13331 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
13332 else
13333 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13334 /* Close the tuple. */
13335 do_cleanups (option_chain);
13336 }
427c3a89
DJ
13337
13338 /* Close the tuple. */
13339 do_cleanups (showlist_chain);
d471ea57 13340}
5a2468f5 13341
0f71a2f6 13342
23860348 13343/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13344static void
13345remote_new_objfile (struct objfile *objfile)
13346{
5d93a237
TT
13347 struct remote_state *rs = get_remote_state ();
13348
13349 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13350 remote_check_symbols ();
dc8acb97
MS
13351}
13352
00bf0b85
SS
13353/* Pull all the tracepoints defined on the target and create local
13354 data structures representing them. We don't want to create real
13355 tracepoints yet, we don't want to mess up the user's existing
13356 collection. */
13357
13358static int
ab6617cc 13359remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13360{
00bf0b85
SS
13361 struct remote_state *rs = get_remote_state ();
13362 char *p;
d5551862 13363
00bf0b85
SS
13364 /* Ask for a first packet of tracepoint definition. */
13365 putpkt ("qTfP");
13366 getpkt (&rs->buf, &rs->buf_size, 0);
13367 p = rs->buf;
13368 while (*p && *p != 'l')
d5551862 13369 {
00bf0b85
SS
13370 parse_tracepoint_definition (p, utpp);
13371 /* Ask for another packet of tracepoint definition. */
13372 putpkt ("qTsP");
13373 getpkt (&rs->buf, &rs->buf_size, 0);
13374 p = rs->buf;
d5551862 13375 }
00bf0b85 13376 return 0;
d5551862
SS
13377}
13378
00bf0b85 13379static int
181e3713
TT
13380remote_upload_trace_state_variables (struct target_ops *self,
13381 struct uploaded_tsv **utsvp)
d5551862 13382{
00bf0b85 13383 struct remote_state *rs = get_remote_state ();
d5551862 13384 char *p;
d5551862 13385
00bf0b85
SS
13386 /* Ask for a first packet of variable definition. */
13387 putpkt ("qTfV");
d5551862
SS
13388 getpkt (&rs->buf, &rs->buf_size, 0);
13389 p = rs->buf;
00bf0b85 13390 while (*p && *p != 'l')
d5551862 13391 {
00bf0b85
SS
13392 parse_tsv_definition (p, utsvp);
13393 /* Ask for another packet of variable definition. */
13394 putpkt ("qTsV");
d5551862
SS
13395 getpkt (&rs->buf, &rs->buf_size, 0);
13396 p = rs->buf;
13397 }
00bf0b85 13398 return 0;
d5551862
SS
13399}
13400
c1e36e3e
PA
13401/* The "set/show range-stepping" show hook. */
13402
13403static void
13404show_range_stepping (struct ui_file *file, int from_tty,
13405 struct cmd_list_element *c,
13406 const char *value)
13407{
13408 fprintf_filtered (file,
13409 _("Debugger's willingness to use range stepping "
13410 "is %s.\n"), value);
13411}
13412
13413/* The "set/show range-stepping" set hook. */
13414
13415static void
13416set_range_stepping (char *ignore_args, int from_tty,
13417 struct cmd_list_element *c)
13418{
5d93a237
TT
13419 struct remote_state *rs = get_remote_state ();
13420
c1e36e3e
PA
13421 /* Whene enabling, check whether range stepping is actually
13422 supported by the target, and warn if not. */
13423 if (use_range_stepping)
13424 {
5d93a237 13425 if (rs->remote_desc != NULL)
c1e36e3e 13426 {
4082afcc 13427 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13428 remote_vcont_probe (rs);
13429
4082afcc 13430 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13431 && rs->supports_vCont.r)
13432 return;
13433 }
13434
13435 warning (_("Range stepping is not supported by the current target"));
13436 }
13437}
13438
c906108c 13439void
fba45db2 13440_initialize_remote (void)
c906108c 13441{
9a7071a8 13442 struct cmd_list_element *cmd;
6f937416 13443 const char *cmd_name;
ea9c271d 13444
0f71a2f6 13445 /* architecture specific data */
2bc416ba 13446 remote_gdbarch_data_handle =
23860348 13447 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13448 remote_g_packet_data_handle =
13449 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13450
94585166
DB
13451 remote_pspace_data
13452 = register_program_space_data_with_cleanup (NULL,
13453 remote_pspace_data_cleanup);
13454
ea9c271d
DJ
13455 /* Initialize the per-target state. At the moment there is only one
13456 of these, not one per target. Only one target is active at a
cf792862
TT
13457 time. */
13458 remote_state = new_remote_state ();
ea9c271d 13459
c906108c
SS
13460 init_remote_ops ();
13461 add_target (&remote_ops);
13462
13463 init_extended_remote_ops ();
13464 add_target (&extended_remote_ops);
cce74817 13465
dc8acb97 13466 /* Hook into new objfile notification. */
06d3b283 13467 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13468 /* We're no longer interested in notification events of an inferior
13469 when it exits. */
13470 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13471
b803fb0f 13472 /* Set up signal handlers. */
934b9bac 13473 async_sigint_remote_token =
b803fb0f 13474 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 13475 async_sigint_remote_twice_token =
6d549500 13476 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 13477
c906108c
SS
13478#if 0
13479 init_remote_threadtests ();
13480#endif
13481
722247f1 13482 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13483 /* set/show remote ... */
d471ea57 13484
1bedd215 13485 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13486Remote protocol specific variables\n\
13487Configure various remote-protocol specific variables such as\n\
1bedd215 13488the packets being used"),
cff3e48b 13489 &remote_set_cmdlist, "set remote ",
23860348 13490 0 /* allow-unknown */, &setlist);
1bedd215 13491 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13492Remote protocol specific variables\n\
13493Configure various remote-protocol specific variables such as\n\
1bedd215 13494the packets being used"),
cff3e48b 13495 &remote_show_cmdlist, "show remote ",
23860348 13496 0 /* allow-unknown */, &showlist);
5a2468f5 13497
1a966eab
AC
13498 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13499Compare section data on target to the exec file.\n\
95cf3b38
DT
13500Argument is a single section name (default: all loaded sections).\n\
13501To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13502 &cmdlist);
13503
1a966eab
AC
13504 add_cmd ("packet", class_maintenance, packet_command, _("\
13505Send an arbitrary packet to a remote target.\n\
c906108c
SS
13506 maintenance packet TEXT\n\
13507If GDB is talking to an inferior via the GDB serial protocol, then\n\
13508this command sends the string TEXT to the inferior, and displays the\n\
13509response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13510terminating `#' character and checksum."),
c906108c
SS
13511 &maintenancelist);
13512
7915a72c
AC
13513 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13514Set whether to send break if interrupted."), _("\
13515Show whether to send break if interrupted."), _("\
13516If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13517 set_remotebreak, show_remotebreak,
e707bbc2 13518 &setlist, &showlist);
9a7071a8
JB
13519 cmd_name = "remotebreak";
13520 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13521 deprecate_cmd (cmd, "set remote interrupt-sequence");
13522 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13523 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13524 deprecate_cmd (cmd, "show remote interrupt-sequence");
13525
13526 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13527 interrupt_sequence_modes, &interrupt_sequence_mode,
13528 _("\
9a7071a8
JB
13529Set interrupt sequence to remote target."), _("\
13530Show interrupt sequence to remote target."), _("\
13531Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13532 NULL, show_interrupt_sequence,
13533 &remote_set_cmdlist,
13534 &remote_show_cmdlist);
13535
13536 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13537 &interrupt_on_connect, _("\
13538Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13539Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13540If set, interrupt sequence is sent to remote target."),
13541 NULL, NULL,
13542 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13543
23860348 13544 /* Install commands for configuring memory read/write packets. */
11cf8741 13545
1a966eab
AC
13546 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13547Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13548 &setlist);
1a966eab
AC
13549 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13550Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13551 &showlist);
13552 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13553 set_memory_write_packet_size, _("\
13554Set the maximum number of bytes per memory-write packet.\n\
13555Specify the number of bytes in a packet or 0 (zero) for the\n\
13556default packet size. The actual limit is further reduced\n\
13557dependent on the target. Specify ``fixed'' to disable the\n\
13558further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13559 &remote_set_cmdlist);
13560 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13561 set_memory_read_packet_size, _("\
13562Set the maximum number of bytes per memory-read packet.\n\
13563Specify the number of bytes in a packet or 0 (zero) for the\n\
13564default packet size. The actual limit is further reduced\n\
13565dependent on the target. Specify ``fixed'' to disable the\n\
13566further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13567 &remote_set_cmdlist);
13568 add_cmd ("memory-write-packet-size", no_class,
13569 show_memory_write_packet_size,
1a966eab 13570 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13571 &remote_show_cmdlist);
13572 add_cmd ("memory-read-packet-size", no_class,
13573 show_memory_read_packet_size,
1a966eab 13574 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13575 &remote_show_cmdlist);
c906108c 13576
b3f42336 13577 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13578 &remote_hw_watchpoint_limit, _("\
13579Set the maximum number of target hardware watchpoints."), _("\
13580Show the maximum number of target hardware watchpoints."), _("\
13581Specify a negative limit for unlimited."),
3e43a32a
MS
13582 NULL, NULL, /* FIXME: i18n: The maximum
13583 number of target hardware
13584 watchpoints is %s. */
b3f42336 13585 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13586 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13587 &remote_hw_watchpoint_length_limit, _("\
13588Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13589Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13590Specify a negative limit for unlimited."),
13591 NULL, NULL, /* FIXME: i18n: The maximum
13592 length (in bytes) of a target
13593 hardware watchpoint is %s. */
13594 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13595 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13596 &remote_hw_breakpoint_limit, _("\
13597Set the maximum number of target hardware breakpoints."), _("\
13598Show the maximum number of target hardware breakpoints."), _("\
13599Specify a negative limit for unlimited."),
3e43a32a
MS
13600 NULL, NULL, /* FIXME: i18n: The maximum
13601 number of target hardware
13602 breakpoints is %s. */
b3f42336 13603 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13604
1b493192
PA
13605 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13606 &remote_address_size, _("\
4d28ad1e
AC
13607Set the maximum size of the address (in bits) in a memory packet."), _("\
13608Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13609 NULL,
13610 NULL, /* FIXME: i18n: */
13611 &setlist, &showlist);
c906108c 13612
ca4f7f8b
PA
13613 init_all_packet_configs ();
13614
444abaca 13615 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13616 "X", "binary-download", 1);
0f71a2f6 13617
444abaca 13618 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13619 "vCont", "verbose-resume", 0);
506fb367 13620
89be2091
DJ
13621 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13622 "QPassSignals", "pass-signals", 0);
13623
82075af2
JS
13624 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13625 "QCatchSyscalls", "catch-syscalls", 0);
13626
9b224c5e
PA
13627 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13628 "QProgramSignals", "program-signals", 0);
13629
444abaca 13630 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13631 "qSymbol", "symbol-lookup", 0);
dc8acb97 13632
444abaca 13633 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13634 "P", "set-register", 1);
d471ea57 13635
444abaca 13636 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13637 "p", "fetch-register", 1);
b96ec7ac 13638
444abaca 13639 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13640 "Z0", "software-breakpoint", 0);
d471ea57 13641
444abaca 13642 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13643 "Z1", "hardware-breakpoint", 0);
d471ea57 13644
444abaca 13645 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13646 "Z2", "write-watchpoint", 0);
d471ea57 13647
444abaca 13648 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13649 "Z3", "read-watchpoint", 0);
d471ea57 13650
444abaca 13651 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13652 "Z4", "access-watchpoint", 0);
d471ea57 13653
0876f84a
DJ
13654 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13655 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13656
c78fa86a
GB
13657 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13658 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13659
23181151
DJ
13660 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13661 "qXfer:features:read", "target-features", 0);
13662
cfa9d6d9
DJ
13663 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13664 "qXfer:libraries:read", "library-info", 0);
13665
2268b414
JK
13666 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13667 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13668
fd79ecee
DJ
13669 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13670 "qXfer:memory-map:read", "memory-map", 0);
13671
0e7f50da
UW
13672 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13673 "qXfer:spu:read", "read-spu-object", 0);
13674
13675 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13676 "qXfer:spu:write", "write-spu-object", 0);
13677
07e059b5
VP
13678 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13679 "qXfer:osdata:read", "osdata", 0);
13680
dc146f7c
VP
13681 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13682 "qXfer:threads:read", "threads", 0);
13683
4aa995e1
PA
13684 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13685 "qXfer:siginfo:read", "read-siginfo-object", 0);
13686
13687 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13688 "qXfer:siginfo:write", "write-siginfo-object", 0);
13689
b3b9301e
PA
13690 add_packet_config_cmd
13691 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13692 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13693
169081d0
TG
13694 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13695 "qXfer:uib:read", "unwind-info-block", 0);
13696
444abaca 13697 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13698 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13699 0);
13700
711e434b
PM
13701 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13702 "qGetTIBAddr", "get-thread-information-block-address",
13703 0);
13704
40ab02ce
MS
13705 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13706 "bc", "reverse-continue", 0);
13707
13708 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13709 "bs", "reverse-step", 0);
13710
be2a5f71
DJ
13711 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13712 "qSupported", "supported-packets", 0);
13713
08388c79
DE
13714 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13715 "qSearch:memory", "search-memory", 0);
13716
bd3eecc3
PA
13717 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13718 "qTStatus", "trace-status", 0);
13719
15a201c8
GB
13720 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13721 "vFile:setfs", "hostio-setfs", 0);
13722
a6b151f1
DJ
13723 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13724 "vFile:open", "hostio-open", 0);
13725
13726 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13727 "vFile:pread", "hostio-pread", 0);
13728
13729 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13730 "vFile:pwrite", "hostio-pwrite", 0);
13731
13732 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13733 "vFile:close", "hostio-close", 0);
13734
13735 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13736 "vFile:unlink", "hostio-unlink", 0);
13737
b9e7b9c3
UW
13738 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13739 "vFile:readlink", "hostio-readlink", 0);
13740
0a93529c
GB
13741 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13742 "vFile:fstat", "hostio-fstat", 0);
13743
2d717e4f
DJ
13744 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13745 "vAttach", "attach", 0);
13746
13747 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13748 "vRun", "run", 0);
13749
a6f3e723
SL
13750 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13751 "QStartNoAckMode", "noack", 0);
13752
82f73884
PA
13753 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13754 "vKill", "kill", 0);
13755
0b16c5cf
PA
13756 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13757 "qAttached", "query-attached", 0);
13758
782b2b07 13759 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13760 "ConditionalTracepoints",
13761 "conditional-tracepoints", 0);
3788aec7
LM
13762
13763 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13764 "ConditionalBreakpoints",
13765 "conditional-breakpoints", 0);
13766
d3ce09f5
SS
13767 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13768 "BreakpointCommands",
13769 "breakpoint-commands", 0);
13770
7a697b8d
SS
13771 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13772 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13773
409873ef
SS
13774 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13775 "TracepointSource", "TracepointSource", 0);
13776
d914c394
SS
13777 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13778 "QAllow", "allow", 0);
13779
0fb4aa4b
PA
13780 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13781 "StaticTracepoints", "static-tracepoints", 0);
13782
1e4d1764
YQ
13783 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13784 "InstallInTrace", "install-in-trace", 0);
13785
0fb4aa4b
PA
13786 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13787 "qXfer:statictrace:read", "read-sdata-object", 0);
13788
78d85199
YQ
13789 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13790 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13791
03583c20
UW
13792 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13793 "QDisableRandomization", "disable-randomization", 0);
13794
d1feda86
YQ
13795 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13796 "QAgent", "agent", 0);
13797
f6f899bf
HAQ
13798 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13799 "QTBuffer:size", "trace-buffer-size", 0);
13800
9accd112
MM
13801 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13802 "Qbtrace:off", "disable-btrace", 0);
13803
13804 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13805 "Qbtrace:bts", "enable-btrace-bts", 0);
13806
13807 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13808 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13809
13810 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13811 "qXfer:btrace", "read-btrace", 0);
13812
f4abbc16
MM
13813 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13814 "qXfer:btrace-conf", "read-btrace-conf", 0);
13815
d33501a5
MM
13816 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13817 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13818
73b8c1fd
PA
13819 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13820 "multiprocess-feature", "multiprocess-feature", 0);
13821
f7e6eed5
PA
13822 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13823 "swbreak-feature", "swbreak-feature", 0);
13824
13825 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13826 "hwbreak-feature", "hwbreak-feature", 0);
13827
89245bc0
DB
13828 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13829 "fork-event-feature", "fork-event-feature", 0);
13830
13831 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13832 "vfork-event-feature", "vfork-event-feature", 0);
13833
b20a6524
MM
13834 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13835 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13836
750ce8d1
YQ
13837 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13838 "vContSupported", "verbose-resume-supported", 0);
13839
94585166
DB
13840 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13841 "exec-event-feature", "exec-event-feature", 0);
13842
de979965
PA
13843 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13844 "vCtrlC", "ctrl-c", 0);
13845
65706a29
PA
13846 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13847 "QThreadEvents", "thread-events", 0);
13848
f2faf941
PA
13849 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13850 "N stop reply", "no-resumed-stop-reply", 0);
13851
0b736949
DB
13852 /* Assert that we've registered "set remote foo-packet" commands
13853 for all packet configs. */
ca4f7f8b
PA
13854 {
13855 int i;
13856
13857 for (i = 0; i < PACKET_MAX; i++)
13858 {
13859 /* Ideally all configs would have a command associated. Some
13860 still don't though. */
13861 int excepted;
13862
13863 switch (i)
13864 {
13865 case PACKET_QNonStop:
ca4f7f8b
PA
13866 case PACKET_EnableDisableTracepoints_feature:
13867 case PACKET_tracenz_feature:
13868 case PACKET_DisconnectedTracing_feature:
13869 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13870 case PACKET_qCRC:
13871 /* Additions to this list need to be well justified:
13872 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13873 excepted = 1;
13874 break;
13875 default:
13876 excepted = 0;
13877 break;
13878 }
13879
13880 /* This catches both forgetting to add a config command, and
13881 forgetting to remove a packet from the exception list. */
13882 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13883 }
13884 }
13885
37a105a1
DJ
13886 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13887 Z sub-packet has its own set and show commands, but users may
13888 have sets to this variable in their .gdbinit files (or in their
13889 documentation). */
e9e68a56 13890 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13891 &remote_Z_packet_detect, _("\
13892Set use of remote protocol `Z' packets"), _("\
13893Show use of remote protocol `Z' packets "), _("\
3b64bf98 13894When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13895packets."),
e9e68a56 13896 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13897 show_remote_protocol_Z_packet_cmd,
13898 /* FIXME: i18n: Use of remote protocol
13899 `Z' packets is %s. */
e9e68a56 13900 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13901
a6b151f1
DJ
13902 add_prefix_cmd ("remote", class_files, remote_command, _("\
13903Manipulate files on the remote system\n\
13904Transfer files to and from the remote target system."),
13905 &remote_cmdlist, "remote ",
13906 0 /* allow-unknown */, &cmdlist);
13907
13908 add_cmd ("put", class_files, remote_put_command,
13909 _("Copy a local file to the remote system."),
13910 &remote_cmdlist);
13911
13912 add_cmd ("get", class_files, remote_get_command,
13913 _("Copy a remote file to the local system."),
13914 &remote_cmdlist);
13915
13916 add_cmd ("delete", class_files, remote_delete_command,
13917 _("Delete a remote file."),
13918 &remote_cmdlist);
13919
2d717e4f 13920 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13921 &remote_exec_file_var, _("\
2d717e4f 13922Set the remote pathname for \"run\""), _("\
94585166
DB
13923Show the remote pathname for \"run\""), NULL,
13924 set_remote_exec_file,
13925 show_remote_exec_file,
13926 &remote_set_cmdlist,
13927 &remote_show_cmdlist);
2d717e4f 13928
c1e36e3e
PA
13929 add_setshow_boolean_cmd ("range-stepping", class_run,
13930 &use_range_stepping, _("\
13931Enable or disable range stepping."), _("\
13932Show whether target-assisted range stepping is enabled."), _("\
13933If on, and the target supports it, when stepping a source line, GDB\n\
13934tells the target to step the corresponding range of addresses itself instead\n\
13935of issuing multiple single-steps. This speeds up source level\n\
13936stepping. If off, GDB always issues single-steps, even if range\n\
13937stepping is supported by the target. The default is on."),
13938 set_range_stepping,
13939 show_range_stepping,
13940 &setlist,
13941 &showlist);
13942
449092f6
CV
13943 /* Eventually initialize fileio. See fileio.c */
13944 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13945
ba348170 13946 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13947 special ptids with it set to != 0. */
ba348170
PA
13948 magic_null_ptid = ptid_build (42000, -1, 1);
13949 not_sent_ptid = ptid_build (42000, -2, 1);
13950 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13951
13952 target_buf_size = 2048;
224c3ddb 13953 target_buf = (char *) xmalloc (target_buf_size);
c906108c 13954}
10760264 13955
This page took 3.363713 seconds and 4 git commands to generate.