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