]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
[testsuite] Fix tiemout fail in gdb.fortran/vla-value.exp
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
618f726f 3 Copyright (C) 1988-2016 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
35b1e5cc 73
0df8b418 74/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
75static char *target_buf;
76static long target_buf_size;
35b1e5cc 77
94585166
DB
78/* Per-program-space data key. */
79static const struct program_space_data *remote_pspace_data;
80
81/* The variable registered as the control variable used by the
82 remote exec-file commands. While the remote exec-file setting is
83 per-program-space, the set/show machinery uses this as the
84 location of the remote exec-file value. */
85static char *remote_exec_file_var;
86
6765f3e5
DJ
87/* The size to align memory write packets, when practical. The protocol
88 does not guarantee any alignment, and gdb will generate short
89 writes and unaligned writes, but even as a best-effort attempt this
90 can improve bulk transfers. For instance, if a write is misaligned
91 relative to the target's data bus, the stub may need to make an extra
92 round trip fetching data from the target. This doesn't make a
93 huge difference, but it's easy to do, so we try to be helpful.
94
95 The alignment chosen is arbitrary; usually data bus width is
96 important here, not the possibly larger cache line size. */
97enum { REMOTE_ALIGN_WRITES = 16 };
98
23860348 99/* Prototypes for local functions. */
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{
769 int sizeof_g_packet;
770 struct packet_reg *regs;
771 struct cleanup *old_chain;
772
773 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
774
224c3ddb 775 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
c21236dc
PA
776 old_chain = make_cleanup (xfree, regs);
777
778 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
779
780 *pnum = regs[regnum].pnum;
781 *poffset = regs[regnum].offset;
782
783 do_cleanups (old_chain);
784
785 return *pnum != -1;
786}
787
788static void *
789init_remote_state (struct gdbarch *gdbarch)
790{
791 struct remote_state *rs = get_remote_state_raw ();
792 struct remote_arch_state *rsa;
793
794 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
795
796 /* Use the architecture to build a regnum<->pnum table, which will be
797 1:1 unless a feature set specifies otherwise. */
798 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
799 gdbarch_num_regs (gdbarch),
800 struct packet_reg);
801
74ca34ce
DJ
802 /* Record the maximum possible size of the g packet - it may turn out
803 to be smaller. */
c21236dc 804 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 805
0df8b418 806 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
807 remote stubs have a hardwired buffer size of 400 bytes
808 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
809 as the maximum packet-size to ensure that the packet and an extra
810 NUL character can always fit in the buffer. This stops GDB
811 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
812 already a full buffer (As of 1999-12-04 that was most stubs). */
813 rsa->remote_packet_size = 400 - 1;
d01949b6 814
ea9c271d
DJ
815 /* This one is filled in when a ``g'' packet is received. */
816 rsa->actual_register_packet_size = 0;
817
818 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
819 default, adjust the size accordingly. Remember that each byte is
820 encoded as two characters. 32 is the overhead for the packet
821 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 822 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 823 little. */
ea9c271d
DJ
824 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
825 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 826
ea9c271d
DJ
827 /* Make sure that the packet buffer is plenty big enough for
828 this architecture. */
829 if (rs->buf_size < rsa->remote_packet_size)
830 {
831 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 832 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 833 }
6d820c5c 834
ea9c271d
DJ
835 return rsa;
836}
837
838/* Return the current allowed size of a remote packet. This is
839 inferred from the current architecture, and should be used to
840 limit the length of outgoing packets. */
841static long
842get_remote_packet_size (void)
843{
be2a5f71 844 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
845 struct remote_arch_state *rsa = get_remote_arch_state ();
846
be2a5f71
DJ
847 if (rs->explicit_packet_size)
848 return rs->explicit_packet_size;
849
ea9c271d 850 return rsa->remote_packet_size;
d01949b6
AC
851}
852
ad10f812 853static struct packet_reg *
ea9c271d 854packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 855{
f5656ead 856 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
857 return NULL;
858 else
ad10f812 859 {
ea9c271d 860 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 861
b323314b
AC
862 gdb_assert (r->regnum == regnum);
863 return r;
ad10f812 864 }
ad10f812
AC
865}
866
867static struct packet_reg *
ea9c271d 868packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 869{
b323314b 870 int i;
a744cf53 871
f5656ead 872 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 873 {
ea9c271d 874 struct packet_reg *r = &rsa->regs[i];
a744cf53 875
b323314b
AC
876 if (r->pnum == pnum)
877 return r;
ad10f812
AC
878 }
879 return NULL;
d01949b6
AC
880}
881
c906108c
SS
882static struct target_ops remote_ops;
883
884static struct target_ops extended_remote_ops;
885
6426a772
JM
886/* FIXME: cagney/1999-09-23: Even though getpkt was called with
887 ``forever'' still use the normal timeout mechanism. This is
888 currently used by the ASYNC code to guarentee that target reads
889 during the initial connect always time-out. Once getpkt has been
890 modified to return a timeout indication and, in turn
891 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 892 this can go away. */
6426a772
JM
893static int wait_forever_enabled_p = 1;
894
9a7071a8
JB
895/* Allow the user to specify what sequence to send to the remote
896 when he requests a program interruption: Although ^C is usually
897 what remote systems expect (this is the default, here), it is
898 sometimes preferable to send a break. On other systems such
899 as the Linux kernel, a break followed by g, which is Magic SysRq g
900 is required in order to interrupt the execution. */
901const char interrupt_sequence_control_c[] = "Ctrl-C";
902const char interrupt_sequence_break[] = "BREAK";
903const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 904static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
905 {
906 interrupt_sequence_control_c,
907 interrupt_sequence_break,
908 interrupt_sequence_break_g,
909 NULL
910 };
911static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
912
913static void
914show_interrupt_sequence (struct ui_file *file, int from_tty,
915 struct cmd_list_element *c,
916 const char *value)
917{
918 if (interrupt_sequence_mode == interrupt_sequence_control_c)
919 fprintf_filtered (file,
920 _("Send the ASCII ETX character (Ctrl-c) "
921 "to the remote target to interrupt the "
922 "execution of the program.\n"));
923 else if (interrupt_sequence_mode == interrupt_sequence_break)
924 fprintf_filtered (file,
925 _("send a break signal to the remote target "
926 "to interrupt the execution of the program.\n"));
927 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
928 fprintf_filtered (file,
929 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
930 "the remote target to interrupt the execution "
931 "of Linux kernel.\n"));
932 else
933 internal_error (__FILE__, __LINE__,
934 _("Invalid value for interrupt_sequence_mode: %s."),
935 interrupt_sequence_mode);
936}
6426a772 937
9a7071a8
JB
938/* This boolean variable specifies whether interrupt_sequence is sent
939 to the remote target when gdb connects to it.
940 This is mostly needed when you debug the Linux kernel: The Linux kernel
941 expects BREAK g which is Magic SysRq g for connecting gdb. */
942static int interrupt_on_connect = 0;
c906108c 943
9a7071a8
JB
944/* This variable is used to implement the "set/show remotebreak" commands.
945 Since these commands are now deprecated in favor of "set/show remote
946 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
947static int remote_break;
948
9a7071a8
JB
949static void
950set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
951{
952 if (remote_break)
953 interrupt_sequence_mode = interrupt_sequence_break;
954 else
955 interrupt_sequence_mode = interrupt_sequence_control_c;
956}
957
958static void
959show_remotebreak (struct ui_file *file, int from_tty,
960 struct cmd_list_element *c,
961 const char *value)
962{
963}
964
c906108c
SS
965/* This variable sets the number of bits in an address that are to be
966 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 967 leading zeros, the entire address would be sent. This variable
c906108c
SS
968 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
969 initial implementation of remote.c restricted the address sent in
970 memory packets to ``host::sizeof long'' bytes - (typically 32
971 bits). Consequently, for 64 bit targets, the upper 32 bits of an
972 address was never sent. Since fixing this bug may cause a break in
973 some remote targets this variable is principly provided to
23860348 974 facilitate backward compatibility. */
c906108c 975
883b9c6c 976static unsigned int remote_address_size;
c906108c 977
75c99385
PA
978/* Temporary to track who currently owns the terminal. See
979 remote_terminal_* for more details. */
6426a772
JM
980
981static int remote_async_terminal_ours_p;
982
11cf8741 983\f
11cf8741 984/* User configurable variables for the number of characters in a
ea9c271d
DJ
985 memory read/write packet. MIN (rsa->remote_packet_size,
986 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 987 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
988 (speed up transfers). The variables ``preferred_*'' (the user
989 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 990 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
991
992struct memory_packet_config
993{
994 char *name;
995 long size;
996 int fixed_p;
997};
998
a5c0808e
PA
999/* The default max memory-write-packet-size. The 16k is historical.
1000 (It came from older GDB's using alloca for buffers and the
1001 knowledge (folklore?) that some hosts don't cope very well with
1002 large alloca calls.) */
1003#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1004
1005/* The minimum remote packet size for memory transfers. Ensures we
1006 can write at least one byte. */
1007#define MIN_MEMORY_PACKET_SIZE 20
1008
11cf8741
JM
1009/* Compute the current size of a read/write packet. Since this makes
1010 use of ``actual_register_packet_size'' the computation is dynamic. */
1011
1012static long
1013get_memory_packet_size (struct memory_packet_config *config)
1014{
d01949b6 1015 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
1016 struct remote_arch_state *rsa = get_remote_arch_state ();
1017
11cf8741
JM
1018 long what_they_get;
1019 if (config->fixed_p)
1020 {
1021 if (config->size <= 0)
a5c0808e 1022 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1023 else
1024 what_they_get = config->size;
1025 }
1026 else
1027 {
ea9c271d 1028 what_they_get = get_remote_packet_size ();
23860348 1029 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1030 if (config->size > 0
1031 && what_they_get > config->size)
1032 what_they_get = config->size;
be2a5f71
DJ
1033
1034 /* Limit it to the size of the targets ``g'' response unless we have
1035 permission from the stub to use a larger packet size. */
1036 if (rs->explicit_packet_size == 0
1037 && rsa->actual_register_packet_size > 0
1038 && what_they_get > rsa->actual_register_packet_size)
1039 what_they_get = rsa->actual_register_packet_size;
11cf8741 1040 }
a5c0808e
PA
1041 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1042 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1043
1044 /* Make sure there is room in the global buffer for this packet
1045 (including its trailing NUL byte). */
1046 if (rs->buf_size < what_they_get + 1)
1047 {
1048 rs->buf_size = 2 * what_they_get;
224c3ddb 1049 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1050 }
1051
11cf8741
JM
1052 return what_they_get;
1053}
1054
0df8b418 1055/* Update the size of a read/write packet. If they user wants
23860348 1056 something really big then do a sanity check. */
11cf8741
JM
1057
1058static void
1059set_memory_packet_size (char *args, struct memory_packet_config *config)
1060{
1061 int fixed_p = config->fixed_p;
1062 long size = config->size;
a744cf53 1063
11cf8741 1064 if (args == NULL)
8a3fe4f8 1065 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1066 else if (strcmp (args, "hard") == 0
1067 || strcmp (args, "fixed") == 0)
1068 fixed_p = 1;
1069 else if (strcmp (args, "soft") == 0
1070 || strcmp (args, "limit") == 0)
1071 fixed_p = 0;
1072 else
1073 {
1074 char *end;
a744cf53 1075
11cf8741
JM
1076 size = strtoul (args, &end, 0);
1077 if (args == end)
8a3fe4f8 1078 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1079
1080 /* Instead of explicitly capping the size of a packet to or
1081 disallowing it, the user is allowed to set the size to
1082 something arbitrarily large. */
11cf8741 1083 }
a5c0808e
PA
1084
1085 /* So that the query shows the correct value. */
1086 if (size <= 0)
1087 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1088
23860348 1089 /* Extra checks? */
11cf8741
JM
1090 if (fixed_p && !config->fixed_p)
1091 {
e2e0b3e5
AC
1092 if (! query (_("The target may not be able to correctly handle a %s\n"
1093 "of %ld bytes. Change the packet size? "),
11cf8741 1094 config->name, size))
8a3fe4f8 1095 error (_("Packet size not changed."));
11cf8741 1096 }
23860348 1097 /* Update the config. */
11cf8741
JM
1098 config->fixed_p = fixed_p;
1099 config->size = size;
1100}
1101
1102static void
1103show_memory_packet_size (struct memory_packet_config *config)
1104{
a3f17187 1105 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1106 if (config->fixed_p)
a3f17187 1107 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1108 get_memory_packet_size (config));
1109 else
a3f17187 1110 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1111 get_memory_packet_size (config));
1112}
1113
1114static struct memory_packet_config memory_write_packet_config =
1115{
1116 "memory-write-packet-size",
1117};
1118
1119static void
1120set_memory_write_packet_size (char *args, int from_tty)
1121{
1122 set_memory_packet_size (args, &memory_write_packet_config);
1123}
1124
1125static void
1126show_memory_write_packet_size (char *args, int from_tty)
1127{
1128 show_memory_packet_size (&memory_write_packet_config);
1129}
1130
1131static long
1132get_memory_write_packet_size (void)
1133{
1134 return get_memory_packet_size (&memory_write_packet_config);
1135}
1136
1137static struct memory_packet_config memory_read_packet_config =
1138{
1139 "memory-read-packet-size",
1140};
1141
1142static void
1143set_memory_read_packet_size (char *args, int from_tty)
1144{
1145 set_memory_packet_size (args, &memory_read_packet_config);
1146}
1147
1148static void
1149show_memory_read_packet_size (char *args, int from_tty)
1150{
1151 show_memory_packet_size (&memory_read_packet_config);
1152}
1153
1154static long
1155get_memory_read_packet_size (void)
1156{
1157 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1158
11cf8741
JM
1159 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1160 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1161 increased beyond this. */
1162 if (size > get_remote_packet_size ())
1163 size = get_remote_packet_size ();
11cf8741
JM
1164 return size;
1165}
1166
11cf8741 1167\f
5a2468f5 1168/* Generic configuration support for packets the stub optionally
0df8b418 1169 supports. Allows the user to specify the use of the packet as well
23860348 1170 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1171
1172enum packet_support
1173 {
1174 PACKET_SUPPORT_UNKNOWN = 0,
1175 PACKET_ENABLE,
1176 PACKET_DISABLE
1177 };
1178
5a2468f5
JM
1179struct packet_config
1180 {
bb572ddd
DJ
1181 const char *name;
1182 const char *title;
4082afcc
PA
1183
1184 /* If auto, GDB auto-detects support for this packet or feature,
1185 either through qSupported, or by trying the packet and looking
1186 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1187 packet. If false, the packet is disabled. Configs that don't
1188 have an associated command always have this set to auto. */
7f19b9a2 1189 enum auto_boolean detect;
4082afcc
PA
1190
1191 /* Does the target support this packet? */
5a2468f5
JM
1192 enum packet_support support;
1193 };
1194
d471ea57 1195/* Analyze a packet's return value and update the packet config
23860348 1196 accordingly. */
d471ea57
AC
1197
1198enum packet_result
1199{
1200 PACKET_ERROR,
1201 PACKET_OK,
1202 PACKET_UNKNOWN
1203};
1204
4082afcc
PA
1205static enum packet_support packet_config_support (struct packet_config *config);
1206static enum packet_support packet_support (int packet);
5a2468f5
JM
1207
1208static void
fba45db2 1209show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1210{
1211 char *support = "internal-error";
a744cf53 1212
4082afcc 1213 switch (packet_config_support (config))
5a2468f5
JM
1214 {
1215 case PACKET_ENABLE:
1216 support = "enabled";
1217 break;
1218 case PACKET_DISABLE:
1219 support = "disabled";
1220 break;
1221 case PACKET_SUPPORT_UNKNOWN:
1222 support = "unknown";
1223 break;
1224 }
1225 switch (config->detect)
1226 {
7f19b9a2 1227 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1228 printf_filtered (_("Support for the `%s' packet "
1229 "is auto-detected, currently %s.\n"),
37a105a1 1230 config->name, support);
5a2468f5 1231 break;
7f19b9a2
AC
1232 case AUTO_BOOLEAN_TRUE:
1233 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1234 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1235 config->name, support);
8e248173 1236 break;
5a2468f5
JM
1237 }
1238}
1239
1240static void
bb572ddd
DJ
1241add_packet_config_cmd (struct packet_config *config, const char *name,
1242 const char *title, int legacy)
d471ea57 1243{
5a2468f5
JM
1244 char *set_doc;
1245 char *show_doc;
d471ea57 1246 char *cmd_name;
3ed07be4 1247
5a2468f5
JM
1248 config->name = name;
1249 config->title = title;
b435e160
AC
1250 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1251 name, title);
3e43a32a
MS
1252 show_doc = xstrprintf ("Show current use of remote "
1253 "protocol `%s' (%s) packet",
b435e160 1254 name, title);
d471ea57 1255 /* set/show TITLE-packet {auto,on,off} */
b435e160 1256 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1257 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1258 &config->detect, set_doc,
1259 show_doc, NULL, /* help_doc */
4082afcc 1260 NULL,
bb572ddd
DJ
1261 show_remote_protocol_packet_cmd,
1262 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1263 /* The command code copies the documentation strings. */
1264 xfree (set_doc);
1265 xfree (show_doc);
23860348 1266 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1267 if (legacy)
1268 {
1269 char *legacy_name;
a744cf53 1270
b435e160 1271 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1272 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1273 &remote_set_cmdlist);
d471ea57 1274 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1275 &remote_show_cmdlist);
d471ea57 1276 }
5a2468f5
JM
1277}
1278
d471ea57 1279static enum packet_result
a76d924d 1280packet_check_result (const char *buf)
5a2468f5 1281{
d471ea57 1282 if (buf[0] != '\0')
5a2468f5 1283 {
d471ea57 1284 /* The stub recognized the packet request. Check that the
23860348 1285 operation succeeded. */
a76d924d
DJ
1286 if (buf[0] == 'E'
1287 && isxdigit (buf[1]) && isxdigit (buf[2])
1288 && buf[3] == '\0')
1289 /* "Enn" - definitly an error. */
1290 return PACKET_ERROR;
1291
1292 /* Always treat "E." as an error. This will be used for
1293 more verbose error messages, such as E.memtypes. */
1294 if (buf[0] == 'E' && buf[1] == '.')
1295 return PACKET_ERROR;
1296
1297 /* The packet may or may not be OK. Just assume it is. */
1298 return PACKET_OK;
1299 }
1300 else
1301 /* The stub does not support the packet. */
1302 return PACKET_UNKNOWN;
1303}
1304
1305static enum packet_result
1306packet_ok (const char *buf, struct packet_config *config)
1307{
1308 enum packet_result result;
1309
4082afcc
PA
1310 if (config->detect != AUTO_BOOLEAN_TRUE
1311 && config->support == PACKET_DISABLE)
1312 internal_error (__FILE__, __LINE__,
1313 _("packet_ok: attempt to use a disabled packet"));
1314
a76d924d
DJ
1315 result = packet_check_result (buf);
1316 switch (result)
1317 {
1318 case PACKET_OK:
1319 case PACKET_ERROR:
1320 /* The stub recognized the packet request. */
4082afcc 1321 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1322 {
d471ea57
AC
1323 if (remote_debug)
1324 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1325 "Packet %s (%s) is supported\n",
1326 config->name, config->title);
d471ea57 1327 config->support = PACKET_ENABLE;
d471ea57 1328 }
a76d924d
DJ
1329 break;
1330 case PACKET_UNKNOWN:
23860348 1331 /* The stub does not support the packet. */
4082afcc
PA
1332 if (config->detect == AUTO_BOOLEAN_AUTO
1333 && config->support == PACKET_ENABLE)
d471ea57 1334 {
4082afcc
PA
1335 /* If the stub previously indicated that the packet was
1336 supported then there is a protocol error. */
1337 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1338 config->name, config->title);
1339 }
1340 else if (config->detect == AUTO_BOOLEAN_TRUE)
1341 {
1342 /* The user set it wrong. */
1343 error (_("Enabled packet %s (%s) not recognized by stub"),
1344 config->name, config->title);
d471ea57 1345 }
4082afcc
PA
1346
1347 if (remote_debug)
1348 fprintf_unfiltered (gdb_stdlog,
1349 "Packet %s (%s) is NOT supported\n",
1350 config->name, config->title);
1351 config->support = PACKET_DISABLE;
a76d924d 1352 break;
5a2468f5 1353 }
a76d924d
DJ
1354
1355 return result;
5a2468f5
JM
1356}
1357
444abaca
DJ
1358enum {
1359 PACKET_vCont = 0,
1360 PACKET_X,
1361 PACKET_qSymbol,
1362 PACKET_P,
1363 PACKET_p,
1364 PACKET_Z0,
1365 PACKET_Z1,
1366 PACKET_Z2,
1367 PACKET_Z3,
1368 PACKET_Z4,
15a201c8 1369 PACKET_vFile_setfs,
a6b151f1
DJ
1370 PACKET_vFile_open,
1371 PACKET_vFile_pread,
1372 PACKET_vFile_pwrite,
1373 PACKET_vFile_close,
1374 PACKET_vFile_unlink,
b9e7b9c3 1375 PACKET_vFile_readlink,
0a93529c 1376 PACKET_vFile_fstat,
0876f84a 1377 PACKET_qXfer_auxv,
23181151 1378 PACKET_qXfer_features,
c78fa86a 1379 PACKET_qXfer_exec_file,
cfa9d6d9 1380 PACKET_qXfer_libraries,
2268b414 1381 PACKET_qXfer_libraries_svr4,
fd79ecee 1382 PACKET_qXfer_memory_map,
0e7f50da
UW
1383 PACKET_qXfer_spu_read,
1384 PACKET_qXfer_spu_write,
07e059b5 1385 PACKET_qXfer_osdata,
dc146f7c 1386 PACKET_qXfer_threads,
0fb4aa4b 1387 PACKET_qXfer_statictrace_read,
b3b9301e 1388 PACKET_qXfer_traceframe_info,
169081d0 1389 PACKET_qXfer_uib,
711e434b 1390 PACKET_qGetTIBAddr,
444abaca 1391 PACKET_qGetTLSAddr,
be2a5f71 1392 PACKET_qSupported,
bd3eecc3 1393 PACKET_qTStatus,
89be2091 1394 PACKET_QPassSignals,
82075af2 1395 PACKET_QCatchSyscalls,
9b224c5e 1396 PACKET_QProgramSignals,
936d2992 1397 PACKET_qCRC,
08388c79 1398 PACKET_qSearch_memory,
2d717e4f
DJ
1399 PACKET_vAttach,
1400 PACKET_vRun,
a6f3e723 1401 PACKET_QStartNoAckMode,
82f73884 1402 PACKET_vKill,
4aa995e1
PA
1403 PACKET_qXfer_siginfo_read,
1404 PACKET_qXfer_siginfo_write,
0b16c5cf 1405 PACKET_qAttached,
4082afcc
PA
1406
1407 /* Support for conditional tracepoints. */
782b2b07 1408 PACKET_ConditionalTracepoints,
4082afcc
PA
1409
1410 /* Support for target-side breakpoint conditions. */
3788aec7 1411 PACKET_ConditionalBreakpoints,
4082afcc
PA
1412
1413 /* Support for target-side breakpoint commands. */
d3ce09f5 1414 PACKET_BreakpointCommands,
4082afcc
PA
1415
1416 /* Support for fast tracepoints. */
7a697b8d 1417 PACKET_FastTracepoints,
4082afcc
PA
1418
1419 /* Support for static tracepoints. */
0fb4aa4b 1420 PACKET_StaticTracepoints,
4082afcc
PA
1421
1422 /* Support for installing tracepoints while a trace experiment is
1423 running. */
1e4d1764 1424 PACKET_InstallInTrace,
4082afcc 1425
40ab02ce
MS
1426 PACKET_bc,
1427 PACKET_bs,
409873ef 1428 PACKET_TracepointSource,
d914c394 1429 PACKET_QAllow,
78d85199 1430 PACKET_qXfer_fdpic,
03583c20 1431 PACKET_QDisableRandomization,
d1feda86 1432 PACKET_QAgent,
f6f899bf 1433 PACKET_QTBuffer_size,
9accd112
MM
1434 PACKET_Qbtrace_off,
1435 PACKET_Qbtrace_bts,
b20a6524 1436 PACKET_Qbtrace_pt,
9accd112 1437 PACKET_qXfer_btrace,
4082afcc
PA
1438
1439 /* Support for the QNonStop packet. */
1440 PACKET_QNonStop,
1441
65706a29
PA
1442 /* Support for the QThreadEvents packet. */
1443 PACKET_QThreadEvents,
1444
4082afcc
PA
1445 /* Support for multi-process extensions. */
1446 PACKET_multiprocess_feature,
1447
1448 /* Support for enabling and disabling tracepoints while a trace
1449 experiment is running. */
1450 PACKET_EnableDisableTracepoints_feature,
1451
1452 /* Support for collecting strings using the tracenz bytecode. */
1453 PACKET_tracenz_feature,
1454
1455 /* Support for continuing to run a trace experiment while GDB is
1456 disconnected. */
1457 PACKET_DisconnectedTracing_feature,
1458
1459 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1460 PACKET_augmented_libraries_svr4_read_feature,
1461
f4abbc16
MM
1462 /* Support for the qXfer:btrace-conf:read packet. */
1463 PACKET_qXfer_btrace_conf,
1464
d33501a5
MM
1465 /* Support for the Qbtrace-conf:bts:size packet. */
1466 PACKET_Qbtrace_conf_bts_size,
1467
f7e6eed5
PA
1468 /* Support for swbreak+ feature. */
1469 PACKET_swbreak_feature,
1470
1471 /* Support for hwbreak+ feature. */
1472 PACKET_hwbreak_feature,
1473
89245bc0
DB
1474 /* Support for fork events. */
1475 PACKET_fork_event_feature,
1476
1477 /* Support for vfork events. */
1478 PACKET_vfork_event_feature,
1479
b20a6524
MM
1480 /* Support for the Qbtrace-conf:pt:size packet. */
1481 PACKET_Qbtrace_conf_pt_size,
1482
94585166
DB
1483 /* Support for exec events. */
1484 PACKET_exec_event_feature,
1485
750ce8d1
YQ
1486 /* Support for query supported vCont actions. */
1487 PACKET_vContSupported,
1488
de979965
PA
1489 /* Support remote CTRL-C. */
1490 PACKET_vCtrlC,
1491
f2faf941
PA
1492 /* Support TARGET_WAITKIND_NO_RESUMED. */
1493 PACKET_no_resumed,
1494
444abaca
DJ
1495 PACKET_MAX
1496};
506fb367 1497
444abaca 1498static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1499
f7e6eed5
PA
1500/* Returns the packet's corresponding "set remote foo-packet" command
1501 state. See struct packet_config for more details. */
1502
1503static enum auto_boolean
1504packet_set_cmd_state (int packet)
1505{
1506 return remote_protocol_packets[packet].detect;
1507}
1508
4082afcc
PA
1509/* Returns whether a given packet or feature is supported. This takes
1510 into account the state of the corresponding "set remote foo-packet"
1511 command, which may be used to bypass auto-detection. */
dc8acb97 1512
4082afcc
PA
1513static enum packet_support
1514packet_config_support (struct packet_config *config)
1515{
1516 switch (config->detect)
444abaca 1517 {
4082afcc
PA
1518 case AUTO_BOOLEAN_TRUE:
1519 return PACKET_ENABLE;
1520 case AUTO_BOOLEAN_FALSE:
1521 return PACKET_DISABLE;
1522 case AUTO_BOOLEAN_AUTO:
1523 return config->support;
1524 default:
1525 gdb_assert_not_reached (_("bad switch"));
444abaca 1526 }
4082afcc
PA
1527}
1528
1529/* Same as packet_config_support, but takes the packet's enum value as
1530 argument. */
1531
1532static enum packet_support
1533packet_support (int packet)
1534{
1535 struct packet_config *config = &remote_protocol_packets[packet];
1536
1537 return packet_config_support (config);
dc8acb97
MS
1538}
1539
5a2468f5 1540static void
444abaca
DJ
1541show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1542 struct cmd_list_element *c,
1543 const char *value)
5a2468f5 1544{
444abaca 1545 struct packet_config *packet;
5a2468f5 1546
444abaca
DJ
1547 for (packet = remote_protocol_packets;
1548 packet < &remote_protocol_packets[PACKET_MAX];
1549 packet++)
1550 {
1551 if (&packet->detect == c->var)
1552 {
1553 show_packet_config_cmd (packet);
1554 return;
1555 }
1556 }
9b20d036 1557 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1558 c->name);
5a2468f5
JM
1559}
1560
d471ea57
AC
1561/* Should we try one of the 'Z' requests? */
1562
1563enum Z_packet_type
1564{
1565 Z_PACKET_SOFTWARE_BP,
1566 Z_PACKET_HARDWARE_BP,
1567 Z_PACKET_WRITE_WP,
1568 Z_PACKET_READ_WP,
1569 Z_PACKET_ACCESS_WP,
1570 NR_Z_PACKET_TYPES
1571};
96baa820 1572
d471ea57 1573/* For compatibility with older distributions. Provide a ``set remote
23860348 1574 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1575
7f19b9a2 1576static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1577
1578static void
fba45db2
KB
1579set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1580 struct cmd_list_element *c)
96baa820 1581{
d471ea57 1582 int i;
a744cf53 1583
d471ea57 1584 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1585 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1586}
1587
1588static void
08546159
AC
1589show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1590 struct cmd_list_element *c,
1591 const char *value)
96baa820 1592{
d471ea57 1593 int i;
a744cf53 1594
d471ea57
AC
1595 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1596 {
444abaca 1597 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1598 }
96baa820
JM
1599}
1600
4082afcc
PA
1601/* Returns true if the multi-process extensions are in effect. */
1602
1603static int
1604remote_multi_process_p (struct remote_state *rs)
1605{
1606 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1607}
1608
de0d863e
DB
1609/* Returns true if fork events are supported. */
1610
1611static int
1612remote_fork_event_p (struct remote_state *rs)
1613{
1614 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1615}
1616
c269dbdb
DB
1617/* Returns true if vfork events are supported. */
1618
1619static int
1620remote_vfork_event_p (struct remote_state *rs)
1621{
1622 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1623}
1624
d46addbb
DB
1625/* Returns true if exec events are supported. */
1626
1627static int
1628remote_exec_event_p (struct remote_state *rs)
1629{
1630 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1631}
1632
cbb8991c
DB
1633/* Insert fork catchpoint target routine. If fork events are enabled
1634 then return success, nothing more to do. */
1635
1636static int
1637remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1638{
1639 struct remote_state *rs = get_remote_state ();
1640
1641 return !remote_fork_event_p (rs);
1642}
1643
1644/* Remove fork catchpoint target routine. Nothing to do, just
1645 return success. */
1646
1647static int
1648remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1649{
1650 return 0;
1651}
1652
1653/* Insert vfork catchpoint target routine. If vfork events are enabled
1654 then return success, nothing more to do. */
1655
1656static int
1657remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1658{
1659 struct remote_state *rs = get_remote_state ();
1660
1661 return !remote_vfork_event_p (rs);
1662}
1663
1664/* Remove vfork catchpoint target routine. Nothing to do, just
1665 return success. */
1666
1667static int
1668remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1669{
1670 return 0;
1671}
1672
d46addbb
DB
1673/* Insert exec catchpoint target routine. If exec events are
1674 enabled, just return success. */
1675
1676static int
1677remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1678{
1679 struct remote_state *rs = get_remote_state ();
1680
1681 return !remote_exec_event_p (rs);
1682}
1683
1684/* Remove exec catchpoint target routine. Nothing to do, just
1685 return success. */
1686
1687static int
1688remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1689{
1690 return 0;
1691}
1692
23860348 1693/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1694static struct async_signal_handler *async_sigint_remote_twice_token;
1695static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1696
74531fed
PA
1697\f
1698/* Asynchronous signal handle registered as event loop source for
1699 when we have pending events ready to be passed to the core. */
1700
1701static struct async_event_handler *remote_async_inferior_event_token;
1702
c906108c
SS
1703\f
1704
79d7f229
PA
1705static ptid_t magic_null_ptid;
1706static ptid_t not_sent_ptid;
1707static ptid_t any_thread_ptid;
1708
0b16c5cf
PA
1709/* Find out if the stub attached to PID (and hence GDB should offer to
1710 detach instead of killing it when bailing out). */
1711
1712static int
1713remote_query_attached (int pid)
1714{
1715 struct remote_state *rs = get_remote_state ();
bba74b36 1716 size_t size = get_remote_packet_size ();
0b16c5cf 1717
4082afcc 1718 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1719 return 0;
1720
1721 if (remote_multi_process_p (rs))
bba74b36 1722 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1723 else
bba74b36 1724 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1725
1726 putpkt (rs->buf);
1727 getpkt (&rs->buf, &rs->buf_size, 0);
1728
1729 switch (packet_ok (rs->buf,
1554e9be 1730 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1731 {
1732 case PACKET_OK:
1733 if (strcmp (rs->buf, "1") == 0)
1734 return 1;
1735 break;
1736 case PACKET_ERROR:
1737 warning (_("Remote failure reply: %s"), rs->buf);
1738 break;
1739 case PACKET_UNKNOWN:
1740 break;
1741 }
1742
1743 return 0;
1744}
1745
49c62f2e
PA
1746/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1747 has been invented by GDB, instead of reported by the target. Since
1748 we can be connected to a remote system before before knowing about
1749 any inferior, mark the target with execution when we find the first
1750 inferior. If ATTACHED is 1, then we had just attached to this
1751 inferior. If it is 0, then we just created this inferior. If it
1752 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1753 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1754 attempt to open this inferior's executable as the main executable
1755 if no main executable is open already. */
1941c569
PA
1756
1757static struct inferior *
1b6e6f5c
GB
1758remote_add_inferior (int fake_pid_p, int pid, int attached,
1759 int try_open_exec)
1941c569 1760{
1941c569
PA
1761 struct inferior *inf;
1762
0b16c5cf
PA
1763 /* Check whether this process we're learning about is to be
1764 considered attached, or if is to be considered to have been
1765 spawned by the stub. */
1766 if (attached == -1)
1767 attached = remote_query_attached (pid);
1768
f5656ead 1769 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1770 {
1771 /* If the target shares code across all inferiors, then every
1772 attach adds a new inferior. */
1773 inf = add_inferior (pid);
1774
1775 /* ... and every inferior is bound to the same program space.
1776 However, each inferior may still have its own address
1777 space. */
1778 inf->aspace = maybe_new_address_space ();
1779 inf->pspace = current_program_space;
1780 }
1781 else
1782 {
1783 /* In the traditional debugging scenario, there's a 1-1 match
1784 between program/address spaces. We simply bind the inferior
1785 to the program space's address space. */
1786 inf = current_inferior ();
1787 inferior_appeared (inf, pid);
1788 }
1941c569 1789
0b16c5cf 1790 inf->attach_flag = attached;
49c62f2e 1791 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1792
1b6e6f5c
GB
1793 /* If no main executable is currently open then attempt to
1794 open the file that was executed to create this inferior. */
835205d0 1795 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1796 exec_file_locate_attach (pid, 1);
1797
1941c569
PA
1798 return inf;
1799}
1800
1801/* Add thread PTID to GDB's thread list. Tag it as executing/running
1802 according to RUNNING. */
1803
c906108c 1804static void
1941c569 1805remote_add_thread (ptid_t ptid, int running)
c906108c 1806{
b7ea362b
PA
1807 struct remote_state *rs = get_remote_state ();
1808
1809 /* GDB historically didn't pull threads in the initial connection
1810 setup. If the remote target doesn't even have a concept of
1811 threads (e.g., a bare-metal target), even if internally we
1812 consider that a single-threaded target, mentioning a new thread
1813 might be confusing to the user. Be silent then, preserving the
1814 age old behavior. */
1815 if (rs->starting_up)
1816 add_thread_silent (ptid);
1817 else
1818 add_thread (ptid);
1941c569
PA
1819
1820 set_executing (ptid, running);
1821 set_running (ptid, running);
1822}
1823
1824/* Come here when we learn about a thread id from the remote target.
1825 It may be the first time we hear about such thread, so take the
1826 opportunity to add it to GDB's thread list. In case this is the
1827 first time we're noticing its corresponding inferior, add it to
1828 GDB's inferior list as well. */
1829
1830static void
1831remote_notice_new_inferior (ptid_t currthread, int running)
1832{
c906108c
SS
1833 /* If this is a new thread, add it to GDB's thread list.
1834 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1835
1836 if (in_thread_list (currthread) && is_exited (currthread))
1837 {
1838 /* We're seeing an event on a thread id we knew had exited.
1839 This has to be a new thread reusing the old id. Add it. */
1941c569 1840 remote_add_thread (currthread, running);
82f73884
PA
1841 return;
1842 }
1843
79d7f229 1844 if (!in_thread_list (currthread))
c0a2216e 1845 {
1941c569 1846 struct inferior *inf = NULL;
bad34192 1847 int pid = ptid_get_pid (currthread);
1941c569 1848
bad34192
PA
1849 if (ptid_is_pid (inferior_ptid)
1850 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1851 {
1852 /* inferior_ptid has no thread member yet. This can happen
1853 with the vAttach -> remote_wait,"TAAthread:" path if the
1854 stub doesn't support qC. This is the first stop reported
1855 after an attach, so this is the main thread. Update the
1856 ptid in the thread list. */
bad34192
PA
1857 if (in_thread_list (pid_to_ptid (pid)))
1858 thread_change_ptid (inferior_ptid, currthread);
1859 else
1860 {
1861 remote_add_thread (currthread, running);
1862 inferior_ptid = currthread;
1863 }
dc146f7c 1864 return;
c0a2216e 1865 }
82f73884
PA
1866
1867 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1868 {
1869 /* inferior_ptid is not set yet. This can happen with the
1870 vRun -> remote_wait,"TAAthread:" path if the stub
1871 doesn't support qC. This is the first stop reported
1872 after an attach, so this is the main thread. Update the
1873 ptid in the thread list. */
dc146f7c 1874 thread_change_ptid (inferior_ptid, currthread);
82f73884 1875 return;
c0a2216e 1876 }
82f73884 1877
29c87f7f
PA
1878 /* When connecting to a target remote, or to a target
1879 extended-remote which already was debugging an inferior, we
1880 may not know about it yet. Add it before adding its child
1881 thread, so notifications are emitted in a sensible order. */
1882 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1883 {
1884 struct remote_state *rs = get_remote_state ();
1885 int fake_pid_p = !remote_multi_process_p (rs);
1886
1887 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1888 ptid_get_pid (currthread), -1, 1);
49c62f2e 1889 }
29c87f7f 1890
82f73884 1891 /* This is really a new thread. Add it. */
1941c569
PA
1892 remote_add_thread (currthread, running);
1893
1894 /* If we found a new inferior, let the common code do whatever
1895 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1896 breakpoints), unless we're just setting up an all-stop
1897 connection. */
1941c569 1898 if (inf != NULL)
b7ea362b
PA
1899 {
1900 struct remote_state *rs = get_remote_state ();
1901
6efcd9a8 1902 if (!rs->starting_up)
b7ea362b
PA
1903 notice_new_inferior (currthread, running, 0);
1904 }
c0a2216e 1905 }
c906108c
SS
1906}
1907
dc146f7c
VP
1908/* Return the private thread data, creating it if necessary. */
1909
70221824 1910static struct private_thread_info *
dc146f7c
VP
1911demand_private_info (ptid_t ptid)
1912{
1913 struct thread_info *info = find_thread_ptid (ptid);
1914
1915 gdb_assert (info);
1916
fe978cb0 1917 if (!info->priv)
dc146f7c 1918 {
8d749320 1919 info->priv = XNEW (struct private_thread_info);
dc146f7c 1920 info->private_dtor = free_private_thread_info;
fe978cb0 1921 info->priv->core = -1;
8020350c
DB
1922 info->priv->extra = NULL;
1923 info->priv->name = NULL;
dc146f7c
VP
1924 }
1925
fe978cb0 1926 return info->priv;
dc146f7c
VP
1927}
1928
74531fed
PA
1929/* Call this function as a result of
1930 1) A halt indication (T packet) containing a thread id
1931 2) A direct query of currthread
0df8b418 1932 3) Successful execution of set thread */
74531fed
PA
1933
1934static void
47f8a51d 1935record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1936{
47f8a51d 1937 rs->general_thread = currthread;
74531fed
PA
1938}
1939
89be2091
DJ
1940/* If 'QPassSignals' is supported, tell the remote stub what signals
1941 it can simply pass through to the inferior without reporting. */
1942
1943static void
94bedb42
TT
1944remote_pass_signals (struct target_ops *self,
1945 int numsigs, unsigned char *pass_signals)
89be2091 1946{
4082afcc 1947 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1948 {
1949 char *pass_packet, *p;
89be2091 1950 int count = 0, i;
747dc59d 1951 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1952
1953 gdb_assert (numsigs < 256);
1954 for (i = 0; i < numsigs; i++)
1955 {
2455069d 1956 if (pass_signals[i])
89be2091
DJ
1957 count++;
1958 }
224c3ddb 1959 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
1960 strcpy (pass_packet, "QPassSignals:");
1961 p = pass_packet + strlen (pass_packet);
1962 for (i = 0; i < numsigs; i++)
1963 {
2455069d 1964 if (pass_signals[i])
89be2091
DJ
1965 {
1966 if (i >= 16)
1967 *p++ = tohex (i >> 4);
1968 *p++ = tohex (i & 15);
1969 if (count)
1970 *p++ = ';';
1971 else
1972 break;
1973 count--;
1974 }
1975 }
1976 *p = 0;
747dc59d 1977 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1978 {
89be2091
DJ
1979 putpkt (pass_packet);
1980 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1981 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1982 if (rs->last_pass_packet)
1983 xfree (rs->last_pass_packet);
1984 rs->last_pass_packet = pass_packet;
89be2091
DJ
1985 }
1986 else
1987 xfree (pass_packet);
1988 }
1989}
1990
82075af2
JS
1991/* If 'QCatchSyscalls' is supported, tell the remote stub
1992 to report syscalls to GDB. */
1993
1994static int
1995remote_set_syscall_catchpoint (struct target_ops *self,
1996 int pid, int needed, int any_count,
1997 int table_size, int *table)
1998{
1999 char *catch_packet;
2000 enum packet_result result;
2001 int n_sysno = 0;
2002
2003 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2004 {
2005 /* Not supported. */
2006 return 1;
2007 }
2008
2009 if (needed && !any_count)
2010 {
2011 int i;
2012
2013 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2014 for (i = 0; i < table_size; i++)
2015 {
2016 if (table[i] != 0)
2017 n_sysno++;
2018 }
2019 }
2020
2021 if (remote_debug)
2022 {
2023 fprintf_unfiltered (gdb_stdlog,
2024 "remote_set_syscall_catchpoint "
2025 "pid %d needed %d any_count %d n_sysno %d\n",
2026 pid, needed, any_count, n_sysno);
2027 }
2028
2029 if (needed)
2030 {
2031 /* Prepare a packet with the sysno list, assuming max 8+1
2032 characters for a sysno. If the resulting packet size is too
2033 big, fallback on the non-selective packet. */
2034 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2035
c0518081 2036 catch_packet = (char *) xmalloc (maxpktsz);
82075af2
JS
2037 strcpy (catch_packet, "QCatchSyscalls:1");
2038 if (!any_count)
2039 {
2040 int i;
2041 char *p;
2042
2043 p = catch_packet;
2044 p += strlen (p);
2045
2046 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2047 for (i = 0; i < table_size; i++)
2048 {
2049 if (table[i] != 0)
2050 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2051 }
2052 }
2053 if (strlen (catch_packet) > get_remote_packet_size ())
2054 {
2055 /* catch_packet too big. Fallback to less efficient
2056 non selective mode, with GDB doing the filtering. */
2057 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2058 }
2059 }
2060 else
2061 catch_packet = xstrdup ("QCatchSyscalls:0");
2062
2063 {
2064 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2065 struct remote_state *rs = get_remote_state ();
2066
2067 putpkt (catch_packet);
2068 getpkt (&rs->buf, &rs->buf_size, 0);
2069 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2070 do_cleanups (old_chain);
2071 if (result == PACKET_OK)
2072 return 0;
2073 else
2074 return -1;
2075 }
2076}
2077
9b224c5e
PA
2078/* If 'QProgramSignals' is supported, tell the remote stub what
2079 signals it should pass through to the inferior when detaching. */
2080
2081static void
daf5e9b6
TT
2082remote_program_signals (struct target_ops *self,
2083 int numsigs, unsigned char *signals)
9b224c5e 2084{
4082afcc 2085 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2086 {
2087 char *packet, *p;
2088 int count = 0, i;
5e4a05c4 2089 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2090
2091 gdb_assert (numsigs < 256);
2092 for (i = 0; i < numsigs; i++)
2093 {
2094 if (signals[i])
2095 count++;
2096 }
224c3ddb 2097 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2098 strcpy (packet, "QProgramSignals:");
2099 p = packet + strlen (packet);
2100 for (i = 0; i < numsigs; i++)
2101 {
2102 if (signal_pass_state (i))
2103 {
2104 if (i >= 16)
2105 *p++ = tohex (i >> 4);
2106 *p++ = tohex (i & 15);
2107 if (count)
2108 *p++ = ';';
2109 else
2110 break;
2111 count--;
2112 }
2113 }
2114 *p = 0;
5e4a05c4
TT
2115 if (!rs->last_program_signals_packet
2116 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2117 {
9b224c5e
PA
2118 putpkt (packet);
2119 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2120 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2121 xfree (rs->last_program_signals_packet);
2122 rs->last_program_signals_packet = packet;
9b224c5e
PA
2123 }
2124 else
2125 xfree (packet);
2126 }
2127}
2128
79d7f229
PA
2129/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2130 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2131 thread. If GEN is set, set the general thread, if not, then set
2132 the step/continue thread. */
c906108c 2133static void
79d7f229 2134set_thread (struct ptid ptid, int gen)
c906108c 2135{
d01949b6 2136 struct remote_state *rs = get_remote_state ();
47f8a51d 2137 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2138 char *buf = rs->buf;
79d7f229 2139 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2140
79d7f229 2141 if (ptid_equal (state, ptid))
c906108c
SS
2142 return;
2143
79d7f229
PA
2144 *buf++ = 'H';
2145 *buf++ = gen ? 'g' : 'c';
2146 if (ptid_equal (ptid, magic_null_ptid))
2147 xsnprintf (buf, endbuf - buf, "0");
2148 else if (ptid_equal (ptid, any_thread_ptid))
2149 xsnprintf (buf, endbuf - buf, "0");
2150 else if (ptid_equal (ptid, minus_one_ptid))
2151 xsnprintf (buf, endbuf - buf, "-1");
2152 else
82f73884 2153 write_ptid (buf, endbuf, ptid);
79d7f229 2154 putpkt (rs->buf);
6d820c5c 2155 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2156 if (gen)
47f8a51d 2157 rs->general_thread = ptid;
c906108c 2158 else
47f8a51d 2159 rs->continue_thread = ptid;
c906108c 2160}
79d7f229
PA
2161
2162static void
2163set_general_thread (struct ptid ptid)
2164{
2165 set_thread (ptid, 1);
2166}
2167
2168static void
2169set_continue_thread (struct ptid ptid)
2170{
2171 set_thread (ptid, 0);
2172}
2173
3c9c4b83
PA
2174/* Change the remote current process. Which thread within the process
2175 ends up selected isn't important, as long as it is the same process
2176 as what INFERIOR_PTID points to.
2177
2178 This comes from that fact that there is no explicit notion of
2179 "selected process" in the protocol. The selected process for
2180 general operations is the process the selected general thread
2181 belongs to. */
2182
2183static void
2184set_general_process (void)
2185{
2186 struct remote_state *rs = get_remote_state ();
2187
2188 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2189 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2190 return;
2191
2192 /* We only need to change the remote current thread if it's pointing
2193 at some other process. */
47f8a51d 2194 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2195 set_general_thread (inferior_ptid);
2196}
2197
c906108c 2198\f
7d1a114c
PA
2199/* Return nonzero if this is the main thread that we made up ourselves
2200 to model non-threaded targets as single-threaded. */
c906108c
SS
2201
2202static int
7d1a114c 2203remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2204{
6d820c5c 2205 struct remote_state *rs = get_remote_state ();
82f73884 2206 char *p, *endp;
c906108c 2207
c0a2216e
PA
2208 if (ptid_equal (ptid, magic_null_ptid))
2209 /* The main thread is always alive. */
2210 return 1;
2211
ba348170 2212 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2213 /* The main thread is always alive. This can happen after a
2214 vAttach, if the remote side doesn't support
2215 multi-threading. */
2216 return 1;
2217
7d1a114c
PA
2218 return 0;
2219}
2220
2221/* Return nonzero if the thread PTID is still alive on the remote
2222 system. */
2223
2224static int
2225remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2226{
2227 struct remote_state *rs = get_remote_state ();
2228 char *p, *endp;
2229
2230 /* Check if this is a thread that we made up ourselves to model
2231 non-threaded targets as single-threaded. */
2232 if (remote_thread_always_alive (ops, ptid))
2233 return 1;
2234
82f73884
PA
2235 p = rs->buf;
2236 endp = rs->buf + get_remote_packet_size ();
2237
2238 *p++ = 'T';
2239 write_ptid (p, endp, ptid);
2240
2e9f7625 2241 putpkt (rs->buf);
6d820c5c 2242 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2243 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2244}
2245
79efa585
SM
2246/* Return a pointer to a thread name if we know it and NULL otherwise.
2247 The thread_info object owns the memory for the name. */
2248
2249static const char *
2250remote_thread_name (struct target_ops *ops, struct thread_info *info)
2251{
2252 if (info->priv != NULL)
2253 return info->priv->name;
2254
2255 return NULL;
2256}
2257
c906108c
SS
2258/* About these extended threadlist and threadinfo packets. They are
2259 variable length packets but, the fields within them are often fixed
2260 length. They are redundent enough to send over UDP as is the
2261 remote protocol in general. There is a matching unit test module
2262 in libstub. */
2263
23860348 2264/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2265 libstub protocol encoding, and remote.c. It is not particularly
23860348 2266 changable. */
cce74817
JM
2267
2268/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2269 Plan to fix this. */
cce74817 2270
23860348 2271typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2272
9d1f7ab2 2273/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2274 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2275
2276struct gdb_ext_thread_info
c5aa993b 2277 {
23860348 2278 threadref threadid; /* External form of thread reference. */
2bc416ba 2279 int active; /* Has state interesting to GDB?
23860348 2280 regs, stack. */
2bc416ba 2281 char display[256]; /* Brief state display, name,
cedea757 2282 blocked/suspended. */
23860348 2283 char shortname[32]; /* To be used to name threads. */
2bc416ba 2284 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2285 whatever. */
c5aa993b 2286 };
cce74817
JM
2287
2288/* The volume of remote transfers can be limited by submitting
2289 a mask containing bits specifying the desired information.
2290 Use a union of these values as the 'selection' parameter to
0df8b418 2291 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2292
2293#define TAG_THREADID 1
2294#define TAG_EXISTS 2
2295#define TAG_DISPLAY 4
2296#define TAG_THREADNAME 8
c5aa993b 2297#define TAG_MOREDISPLAY 16
cce74817 2298
23860348 2299#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2300
a14ed312 2301static char *unpack_nibble (char *buf, int *val);
cce74817 2302
a14ed312 2303static char *unpack_byte (char *buf, int *value);
cce74817 2304
a14ed312 2305static char *pack_int (char *buf, int value);
cce74817 2306
a14ed312 2307static char *unpack_int (char *buf, int *value);
cce74817 2308
a14ed312 2309static char *unpack_string (char *src, char *dest, int length);
cce74817 2310
23860348 2311static char *pack_threadid (char *pkt, threadref *id);
cce74817 2312
23860348 2313static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2314
23860348 2315void int_to_threadref (threadref *id, int value);
cce74817 2316
23860348 2317static int threadref_to_int (threadref *ref);
cce74817 2318
23860348 2319static void copy_threadref (threadref *dest, threadref *src);
cce74817 2320
23860348 2321static int threadmatch (threadref *dest, threadref *src);
cce74817 2322
2bc416ba 2323static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2324 threadref *id);
cce74817 2325
a14ed312 2326static int remote_unpack_thread_info_response (char *pkt,
23860348 2327 threadref *expectedref,
a14ed312
KB
2328 struct gdb_ext_thread_info
2329 *info);
cce74817
JM
2330
2331
2bc416ba 2332static int remote_get_threadinfo (threadref *threadid,
23860348 2333 int fieldset, /*TAG mask */
a14ed312 2334 struct gdb_ext_thread_info *info);
cce74817 2335
a14ed312
KB
2336static char *pack_threadlist_request (char *pkt, int startflag,
2337 int threadcount,
23860348 2338 threadref *nextthread);
cce74817 2339
a14ed312
KB
2340static int parse_threadlist_response (char *pkt,
2341 int result_limit,
23860348 2342 threadref *original_echo,
2bc416ba 2343 threadref *resultlist,
23860348 2344 int *doneflag);
cce74817 2345
a14ed312 2346static int remote_get_threadlist (int startflag,
23860348 2347 threadref *nextthread,
a14ed312
KB
2348 int result_limit,
2349 int *done,
2bc416ba 2350 int *result_count,
23860348 2351 threadref *threadlist);
cce74817 2352
23860348 2353typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2354
a14ed312
KB
2355static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2356 void *context, int looplimit);
cce74817 2357
23860348 2358static int remote_newthread_step (threadref *ref, void *context);
cce74817 2359
82f73884
PA
2360
2361/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2362 buffer we're allowed to write to. Returns
2363 BUF+CHARACTERS_WRITTEN. */
2364
2365static char *
2366write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2367{
2368 int pid, tid;
2369 struct remote_state *rs = get_remote_state ();
2370
2371 if (remote_multi_process_p (rs))
2372 {
2373 pid = ptid_get_pid (ptid);
2374 if (pid < 0)
2375 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2376 else
2377 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2378 }
ba348170 2379 tid = ptid_get_lwp (ptid);
82f73884
PA
2380 if (tid < 0)
2381 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2382 else
2383 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2384
2385 return buf;
2386}
2387
2388/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2389 passed the last parsed char. Returns null_ptid on error. */
2390
2391static ptid_t
2392read_ptid (char *buf, char **obuf)
2393{
2394 char *p = buf;
2395 char *pp;
2396 ULONGEST pid = 0, tid = 0;
82f73884
PA
2397
2398 if (*p == 'p')
2399 {
2400 /* Multi-process ptid. */
2401 pp = unpack_varlen_hex (p + 1, &pid);
2402 if (*pp != '.')
b37520b6 2403 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2404
2405 p = pp;
2406 pp = unpack_varlen_hex (p + 1, &tid);
2407 if (obuf)
2408 *obuf = pp;
ba348170 2409 return ptid_build (pid, tid, 0);
82f73884
PA
2410 }
2411
2412 /* No multi-process. Just a tid. */
2413 pp = unpack_varlen_hex (p, &tid);
2414
c9f35b34
KB
2415 /* Return null_ptid when no thread id is found. */
2416 if (p == pp)
2417 {
2418 if (obuf)
2419 *obuf = pp;
2420 return null_ptid;
2421 }
2422
82f73884 2423 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2424 what's in inferior_ptid, unless it's null at this point. If so,
2425 then since there's no way to know the pid of the reported
2426 threads, use the magic number. */
2427 if (ptid_equal (inferior_ptid, null_ptid))
2428 pid = ptid_get_pid (magic_null_ptid);
2429 else
2430 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2431
2432 if (obuf)
2433 *obuf = pp;
ba348170 2434 return ptid_build (pid, tid, 0);
82f73884
PA
2435}
2436
c906108c 2437static int
fba45db2 2438stubhex (int ch)
c906108c
SS
2439{
2440 if (ch >= 'a' && ch <= 'f')
2441 return ch - 'a' + 10;
2442 if (ch >= '0' && ch <= '9')
2443 return ch - '0';
2444 if (ch >= 'A' && ch <= 'F')
2445 return ch - 'A' + 10;
2446 return -1;
2447}
2448
2449static int
fba45db2 2450stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2451{
2452 int nibble;
2453 int retval = 0;
2454
2455 while (fieldlength)
2456 {
2457 nibble = stubhex (*buff++);
2458 retval |= nibble;
2459 fieldlength--;
2460 if (fieldlength)
2461 retval = retval << 4;
2462 }
2463 return retval;
2464}
2465
c906108c 2466static char *
fba45db2 2467unpack_nibble (char *buf, int *val)
c906108c 2468{
b7589f7d 2469 *val = fromhex (*buf++);
c906108c
SS
2470 return buf;
2471}
2472
c906108c 2473static char *
fba45db2 2474unpack_byte (char *buf, int *value)
c906108c
SS
2475{
2476 *value = stub_unpack_int (buf, 2);
2477 return buf + 2;
2478}
2479
2480static char *
fba45db2 2481pack_int (char *buf, int value)
c906108c
SS
2482{
2483 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2484 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2485 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2486 buf = pack_hex_byte (buf, (value & 0xff));
2487 return buf;
2488}
2489
2490static char *
fba45db2 2491unpack_int (char *buf, int *value)
c906108c
SS
2492{
2493 *value = stub_unpack_int (buf, 8);
2494 return buf + 8;
2495}
2496
23860348 2497#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2498static char *pack_string (char *pkt, char *string);
c906108c
SS
2499
2500static char *
fba45db2 2501pack_string (char *pkt, char *string)
c906108c
SS
2502{
2503 char ch;
2504 int len;
2505
2506 len = strlen (string);
2507 if (len > 200)
23860348 2508 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2509 pkt = pack_hex_byte (pkt, len);
2510 while (len-- > 0)
2511 {
2512 ch = *string++;
2513 if ((ch == '\0') || (ch == '#'))
23860348 2514 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2515 *pkt++ = ch;
2516 }
2517 return pkt;
2518}
2519#endif /* 0 (unused) */
2520
2521static char *
fba45db2 2522unpack_string (char *src, char *dest, int length)
c906108c
SS
2523{
2524 while (length--)
2525 *dest++ = *src++;
2526 *dest = '\0';
2527 return src;
2528}
2529
2530static char *
fba45db2 2531pack_threadid (char *pkt, threadref *id)
c906108c
SS
2532{
2533 char *limit;
2534 unsigned char *altid;
2535
2536 altid = (unsigned char *) id;
2537 limit = pkt + BUF_THREAD_ID_SIZE;
2538 while (pkt < limit)
2539 pkt = pack_hex_byte (pkt, *altid++);
2540 return pkt;
2541}
2542
2543
2544static char *
fba45db2 2545unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2546{
2547 char *altref;
2548 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2549 int x, y;
2550
2551 altref = (char *) id;
2552
2553 while (inbuf < limit)
2554 {
2555 x = stubhex (*inbuf++);
2556 y = stubhex (*inbuf++);
2557 *altref++ = (x << 4) | y;
2558 }
2559 return inbuf;
2560}
2561
2562/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2563 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2564 to use 64bit thread references internally. This is an adapter
2565 function. */
2566
2567void
fba45db2 2568int_to_threadref (threadref *id, int value)
c906108c
SS
2569{
2570 unsigned char *scan;
2571
2572 scan = (unsigned char *) id;
2573 {
2574 int i = 4;
2575 while (i--)
2576 *scan++ = 0;
2577 }
2578 *scan++ = (value >> 24) & 0xff;
2579 *scan++ = (value >> 16) & 0xff;
2580 *scan++ = (value >> 8) & 0xff;
2581 *scan++ = (value & 0xff);
2582}
2583
2584static int
fba45db2 2585threadref_to_int (threadref *ref)
c906108c
SS
2586{
2587 int i, value = 0;
2588 unsigned char *scan;
2589
cfd77fa1 2590 scan = *ref;
c906108c
SS
2591 scan += 4;
2592 i = 4;
2593 while (i-- > 0)
2594 value = (value << 8) | ((*scan++) & 0xff);
2595 return value;
2596}
2597
2598static void
fba45db2 2599copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2600{
2601 int i;
2602 unsigned char *csrc, *cdest;
2603
2604 csrc = (unsigned char *) src;
2605 cdest = (unsigned char *) dest;
2606 i = 8;
2607 while (i--)
2608 *cdest++ = *csrc++;
2609}
2610
2611static int
fba45db2 2612threadmatch (threadref *dest, threadref *src)
c906108c 2613{
23860348 2614 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2615#if 0
2616 unsigned char *srcp, *destp;
2617 int i, result;
2618 srcp = (char *) src;
2619 destp = (char *) dest;
2620
2621 result = 1;
2622 while (i-- > 0)
2623 result &= (*srcp++ == *destp++) ? 1 : 0;
2624 return result;
2625#endif
2626 return 1;
2627}
2628
2629/*
c5aa993b
JM
2630 threadid:1, # always request threadid
2631 context_exists:2,
2632 display:4,
2633 unique_name:8,
2634 more_display:16
2635 */
c906108c
SS
2636
2637/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2638
2639static char *
fba45db2 2640pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2641{
23860348
MS
2642 *pkt++ = 'q'; /* Info Query */
2643 *pkt++ = 'P'; /* process or thread info */
2644 pkt = pack_int (pkt, mode); /* mode */
c906108c 2645 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2646 *pkt = '\0'; /* terminate */
c906108c
SS
2647 return pkt;
2648}
2649
23860348 2650/* These values tag the fields in a thread info response packet. */
c906108c 2651/* Tagging the fields allows us to request specific fields and to
23860348 2652 add more fields as time goes by. */
c906108c 2653
23860348 2654#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2655#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2656 fetch registers and its stack? */
c5aa993b 2657#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2658#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2659#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2660 the process. */
c906108c
SS
2661
2662static int
fba45db2
KB
2663remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2664 struct gdb_ext_thread_info *info)
c906108c 2665{
d01949b6 2666 struct remote_state *rs = get_remote_state ();
c906108c 2667 int mask, length;
cfd77fa1 2668 int tag;
c906108c 2669 threadref ref;
6d820c5c 2670 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2671 int retval = 1;
2672
23860348 2673 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2674 info->active = 0;
2675 info->display[0] = '\0';
2676 info->shortname[0] = '\0';
2677 info->more_display[0] = '\0';
2678
23860348
MS
2679 /* Assume the characters indicating the packet type have been
2680 stripped. */
c906108c
SS
2681 pkt = unpack_int (pkt, &mask); /* arg mask */
2682 pkt = unpack_threadid (pkt, &ref);
2683
2684 if (mask == 0)
8a3fe4f8 2685 warning (_("Incomplete response to threadinfo request."));
c906108c 2686 if (!threadmatch (&ref, expectedref))
23860348 2687 { /* This is an answer to a different request. */
8a3fe4f8 2688 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2689 return 0;
2690 }
2691 copy_threadref (&info->threadid, &ref);
2692
23860348 2693 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2694
23860348
MS
2695 /* Packets are terminated with nulls. */
2696 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2697 {
2698 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2699 pkt = unpack_byte (pkt, &length); /* length */
2700 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2701 {
8a3fe4f8 2702 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2703 retval = 0;
2704 break;
2705 }
2706 if (tag == TAG_THREADID)
2707 {
2708 if (length != 16)
2709 {
8a3fe4f8 2710 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2711 retval = 0;
2712 break;
2713 }
2714 pkt = unpack_threadid (pkt, &ref);
2715 mask = mask & ~TAG_THREADID;
2716 continue;
2717 }
2718 if (tag == TAG_EXISTS)
2719 {
2720 info->active = stub_unpack_int (pkt, length);
2721 pkt += length;
2722 mask = mask & ~(TAG_EXISTS);
2723 if (length > 8)
2724 {
8a3fe4f8 2725 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2726 retval = 0;
2727 break;
2728 }
2729 continue;
2730 }
2731 if (tag == TAG_THREADNAME)
2732 {
2733 pkt = unpack_string (pkt, &info->shortname[0], length);
2734 mask = mask & ~TAG_THREADNAME;
2735 continue;
2736 }
2737 if (tag == TAG_DISPLAY)
2738 {
2739 pkt = unpack_string (pkt, &info->display[0], length);
2740 mask = mask & ~TAG_DISPLAY;
2741 continue;
2742 }
2743 if (tag == TAG_MOREDISPLAY)
2744 {
2745 pkt = unpack_string (pkt, &info->more_display[0], length);
2746 mask = mask & ~TAG_MOREDISPLAY;
2747 continue;
2748 }
8a3fe4f8 2749 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2750 break; /* Not a tag we know about. */
c906108c
SS
2751 }
2752 return retval;
2753}
2754
2755static int
fba45db2
KB
2756remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2757 struct gdb_ext_thread_info *info)
c906108c 2758{
d01949b6 2759 struct remote_state *rs = get_remote_state ();
c906108c 2760 int result;
c906108c 2761
2e9f7625
DJ
2762 pack_threadinfo_request (rs->buf, fieldset, threadid);
2763 putpkt (rs->buf);
6d820c5c 2764 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2765
2766 if (rs->buf[0] == '\0')
2767 return 0;
2768
2e9f7625 2769 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2770 threadid, info);
c906108c
SS
2771 return result;
2772}
2773
c906108c
SS
2774/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2775
2776static char *
fba45db2
KB
2777pack_threadlist_request (char *pkt, int startflag, int threadcount,
2778 threadref *nextthread)
c906108c
SS
2779{
2780 *pkt++ = 'q'; /* info query packet */
2781 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2782 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2783 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2784 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2785 *pkt = '\0';
2786 return pkt;
2787}
2788
2789/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2790
2791static int
fba45db2
KB
2792parse_threadlist_response (char *pkt, int result_limit,
2793 threadref *original_echo, threadref *resultlist,
2794 int *doneflag)
c906108c 2795{
d01949b6 2796 struct remote_state *rs = get_remote_state ();
c906108c
SS
2797 char *limit;
2798 int count, resultcount, done;
2799
2800 resultcount = 0;
2801 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2802 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2803 /* done parse past here */
c906108c
SS
2804 pkt = unpack_byte (pkt, &count); /* count field */
2805 pkt = unpack_nibble (pkt, &done);
2806 /* The first threadid is the argument threadid. */
2807 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2808 while ((count-- > 0) && (pkt < limit))
2809 {
2810 pkt = unpack_threadid (pkt, resultlist++);
2811 if (resultcount++ >= result_limit)
2812 break;
2813 }
2814 if (doneflag)
2815 *doneflag = done;
2816 return resultcount;
2817}
2818
6dc54d91
PA
2819/* Fetch the next batch of threads from the remote. Returns -1 if the
2820 qL packet is not supported, 0 on error and 1 on success. */
2821
c906108c 2822static int
fba45db2
KB
2823remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2824 int *done, int *result_count, threadref *threadlist)
c906108c 2825{
d01949b6 2826 struct remote_state *rs = get_remote_state ();
c906108c
SS
2827 int result = 1;
2828
23860348 2829 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2830 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2831 >= get_remote_packet_size ())
ea9c271d 2832 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2833
6d820c5c
DJ
2834 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2835 putpkt (rs->buf);
2836 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2837 if (*rs->buf == '\0')
6dc54d91
PA
2838 {
2839 /* Packet not supported. */
2840 return -1;
2841 }
2842
2843 *result_count =
2844 parse_threadlist_response (rs->buf + 2, result_limit,
2845 &rs->echo_nextthread, threadlist, done);
c906108c 2846
0d031856 2847 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2848 {
23860348
MS
2849 /* FIXME: This is a good reason to drop the packet. */
2850 /* Possably, there is a duplicate response. */
c906108c
SS
2851 /* Possabilities :
2852 retransmit immediatly - race conditions
2853 retransmit after timeout - yes
2854 exit
2855 wait for packet, then exit
2856 */
8a3fe4f8 2857 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2858 return 0; /* I choose simply exiting. */
c906108c
SS
2859 }
2860 if (*result_count <= 0)
2861 {
2862 if (*done != 1)
2863 {
8a3fe4f8 2864 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2865 result = 0;
2866 }
2867 return result; /* break; */
2868 }
2869 if (*result_count > result_limit)
2870 {
2871 *result_count = 0;
8a3fe4f8 2872 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2873 return 0;
2874 }
2875 return result;
2876}
2877
6dc54d91
PA
2878/* Fetch the list of remote threads, with the qL packet, and call
2879 STEPFUNCTION for each thread found. Stops iterating and returns 1
2880 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2881 STEPFUNCTION returns false. If the packet is not supported,
2882 returns -1. */
c906108c 2883
c906108c 2884static int
fba45db2
KB
2885remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2886 int looplimit)
c906108c 2887{
0d031856 2888 struct remote_state *rs = get_remote_state ();
c906108c
SS
2889 int done, i, result_count;
2890 int startflag = 1;
2891 int result = 1;
2892 int loopcount = 0;
c906108c
SS
2893
2894 done = 0;
2895 while (!done)
2896 {
2897 if (loopcount++ > looplimit)
2898 {
2899 result = 0;
8a3fe4f8 2900 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2901 break;
2902 }
6dc54d91
PA
2903 result = remote_get_threadlist (startflag, &rs->nextthread,
2904 MAXTHREADLISTRESULTS,
2905 &done, &result_count,
2906 rs->resultthreadlist);
2907 if (result <= 0)
2908 break;
23860348 2909 /* Clear for later iterations. */
c906108c
SS
2910 startflag = 0;
2911 /* Setup to resume next batch of thread references, set nextthread. */
2912 if (result_count >= 1)
0d031856
TT
2913 copy_threadref (&rs->nextthread,
2914 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2915 i = 0;
2916 while (result_count--)
6dc54d91
PA
2917 {
2918 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2919 {
2920 result = 0;
2921 break;
2922 }
2923 }
c906108c
SS
2924 }
2925 return result;
2926}
2927
6dc54d91
PA
2928/* A thread found on the remote target. */
2929
2930typedef struct thread_item
2931{
2932 /* The thread's PTID. */
2933 ptid_t ptid;
2934
2935 /* The thread's extra info. May be NULL. */
2936 char *extra;
2937
79efa585
SM
2938 /* The thread's name. May be NULL. */
2939 char *name;
2940
6dc54d91
PA
2941 /* The core the thread was running on. -1 if not known. */
2942 int core;
2943} thread_item_t;
2944DEF_VEC_O(thread_item_t);
2945
2946/* Context passed around to the various methods listing remote
2947 threads. As new threads are found, they're added to the ITEMS
2948 vector. */
2949
2950struct threads_listing_context
2951{
2952 /* The threads found on the remote target. */
2953 VEC (thread_item_t) *items;
2954};
2955
80134cf5
PA
2956/* Discard the contents of the constructed thread listing context. */
2957
2958static void
2959clear_threads_listing_context (void *p)
2960{
19ba03f4
SM
2961 struct threads_listing_context *context
2962 = (struct threads_listing_context *) p;
80134cf5
PA
2963 int i;
2964 struct thread_item *item;
2965
2966 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
2967 {
2968 xfree (item->extra);
2969 xfree (item->name);
2970 }
80134cf5
PA
2971
2972 VEC_free (thread_item_t, context->items);
2973}
2974
cbb8991c
DB
2975/* Remove the thread specified as the related_pid field of WS
2976 from the CONTEXT list. */
2977
2978static void
2979threads_listing_context_remove (struct target_waitstatus *ws,
2980 struct threads_listing_context *context)
2981{
2982 struct thread_item *item;
2983 int i;
2984 ptid_t child_ptid = ws->value.related_pid;
2985
2986 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2987 {
2988 if (ptid_equal (item->ptid, child_ptid))
2989 {
2990 VEC_ordered_remove (thread_item_t, context->items, i);
2991 break;
2992 }
2993 }
2994}
2995
c906108c 2996static int
6dc54d91 2997remote_newthread_step (threadref *ref, void *data)
c906108c 2998{
19ba03f4
SM
2999 struct threads_listing_context *context
3000 = (struct threads_listing_context *) data;
6dc54d91 3001 struct thread_item item;
79d7f229 3002 int pid = ptid_get_pid (inferior_ptid);
39f77062 3003
6dc54d91
PA
3004 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3005 item.core = -1;
2e3b657e 3006 item.name = NULL;
6dc54d91
PA
3007 item.extra = NULL;
3008
3009 VEC_safe_push (thread_item_t, context->items, &item);
3010
c906108c
SS
3011 return 1; /* continue iterator */
3012}
3013
3014#define CRAZY_MAX_THREADS 1000
3015
39f77062
KB
3016static ptid_t
3017remote_current_thread (ptid_t oldpid)
c906108c 3018{
d01949b6 3019 struct remote_state *rs = get_remote_state ();
c906108c
SS
3020
3021 putpkt ("qC");
6d820c5c 3022 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3023 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
3024 {
3025 char *obuf;
3026 ptid_t result;
3027
3028 result = read_ptid (&rs->buf[2], &obuf);
3029 if (*obuf != '\0' && remote_debug)
3030 fprintf_unfiltered (gdb_stdlog,
3031 "warning: garbage in qC reply\n");
3032
3033 return result;
3034 }
c906108c
SS
3035 else
3036 return oldpid;
3037}
3038
6dc54d91 3039/* List remote threads using the deprecated qL packet. */
cce74817 3040
6dc54d91
PA
3041static int
3042remote_get_threads_with_ql (struct target_ops *ops,
3043 struct threads_listing_context *context)
c906108c 3044{
6dc54d91
PA
3045 if (remote_threadlist_iterator (remote_newthread_step, context,
3046 CRAZY_MAX_THREADS) >= 0)
3047 return 1;
3048
3049 return 0;
c906108c
SS
3050}
3051
dc146f7c
VP
3052#if defined(HAVE_LIBEXPAT)
3053
dc146f7c
VP
3054static void
3055start_thread (struct gdb_xml_parser *parser,
3056 const struct gdb_xml_element *element,
3057 void *user_data, VEC(gdb_xml_value_s) *attributes)
3058{
19ba03f4
SM
3059 struct threads_listing_context *data
3060 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3061
3062 struct thread_item item;
3063 char *id;
3d2c1d41 3064 struct gdb_xml_value *attr;
dc146f7c 3065
19ba03f4 3066 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
3067 item.ptid = read_ptid (id, NULL);
3068
3d2c1d41
PA
3069 attr = xml_find_attribute (attributes, "core");
3070 if (attr != NULL)
3071 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
3072 else
3073 item.core = -1;
3074
79efa585 3075 attr = xml_find_attribute (attributes, "name");
e1961661 3076 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 3077
dc146f7c
VP
3078 item.extra = 0;
3079
3080 VEC_safe_push (thread_item_t, data->items, &item);
3081}
3082
3083static void
3084end_thread (struct gdb_xml_parser *parser,
3085 const struct gdb_xml_element *element,
3086 void *user_data, const char *body_text)
3087{
19ba03f4
SM
3088 struct threads_listing_context *data
3089 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3090
3091 if (body_text && *body_text)
2ae2a0b7 3092 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3093}
3094
3095const struct gdb_xml_attribute thread_attributes[] = {
3096 { "id", GDB_XML_AF_NONE, NULL, NULL },
3097 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3098 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3099 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3100};
3101
3102const struct gdb_xml_element thread_children[] = {
3103 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3104};
3105
3106const struct gdb_xml_element threads_children[] = {
3107 { "thread", thread_attributes, thread_children,
3108 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3109 start_thread, end_thread },
3110 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3111};
3112
3113const struct gdb_xml_element threads_elements[] = {
3114 { "threads", NULL, threads_children,
3115 GDB_XML_EF_NONE, NULL, NULL },
3116 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3117};
3118
3119#endif
3120
6dc54d91 3121/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3122
6dc54d91
PA
3123static int
3124remote_get_threads_with_qxfer (struct target_ops *ops,
3125 struct threads_listing_context *context)
0f71a2f6 3126{
dc146f7c 3127#if defined(HAVE_LIBEXPAT)
4082afcc 3128 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3129 {
6dc54d91 3130 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3131 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3132
6dc54d91 3133 if (xml != NULL && *xml != '\0')
dc146f7c 3134 {
6dc54d91
PA
3135 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3136 threads_elements, xml, context);
dc146f7c
VP
3137 }
3138
3139 do_cleanups (back_to);
6dc54d91 3140 return 1;
dc146f7c
VP
3141 }
3142#endif
3143
6dc54d91
PA
3144 return 0;
3145}
3146
3147/* List remote threads using qfThreadInfo/qsThreadInfo. */
3148
3149static int
3150remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3151 struct threads_listing_context *context)
3152{
3153 struct remote_state *rs = get_remote_state ();
3154
b80fafe3 3155 if (rs->use_threadinfo_query)
9d1f7ab2 3156 {
6dc54d91
PA
3157 char *bufp;
3158
9d1f7ab2 3159 putpkt ("qfThreadInfo");
6d820c5c 3160 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3161 bufp = rs->buf;
9d1f7ab2 3162 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3163 {
9d1f7ab2
MS
3164 while (*bufp++ == 'm') /* reply contains one or more TID */
3165 {
3166 do
3167 {
6dc54d91
PA
3168 struct thread_item item;
3169
3170 item.ptid = read_ptid (bufp, &bufp);
3171 item.core = -1;
2e3b657e 3172 item.name = NULL;
6dc54d91
PA
3173 item.extra = NULL;
3174
3175 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3176 }
3177 while (*bufp++ == ','); /* comma-separated list */
3178 putpkt ("qsThreadInfo");
6d820c5c 3179 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3180 bufp = rs->buf;
9d1f7ab2 3181 }
6dc54d91
PA
3182 return 1;
3183 }
3184 else
3185 {
3186 /* Packet not recognized. */
3187 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3188 }
3189 }
3190
6dc54d91
PA
3191 return 0;
3192}
3193
e8032dde 3194/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3195 targets. */
3196
3197static void
e8032dde 3198remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
3199{
3200 struct remote_state *rs = get_remote_state ();
3201 struct threads_listing_context context;
3202 struct cleanup *old_chain;
ab970af1 3203 int got_list = 0;
e8032dde 3204
6dc54d91
PA
3205 context.items = NULL;
3206 old_chain = make_cleanup (clear_threads_listing_context, &context);
3207
3208 /* We have a few different mechanisms to fetch the thread list. Try
3209 them all, starting with the most preferred one first, falling
3210 back to older methods. */
3211 if (remote_get_threads_with_qxfer (ops, &context)
3212 || remote_get_threads_with_qthreadinfo (ops, &context)
3213 || remote_get_threads_with_ql (ops, &context))
3214 {
3215 int i;
3216 struct thread_item *item;
ab970af1
PA
3217 struct thread_info *tp, *tmp;
3218
3219 got_list = 1;
3220
7d1a114c
PA
3221 if (VEC_empty (thread_item_t, context.items)
3222 && remote_thread_always_alive (ops, inferior_ptid))
3223 {
3224 /* Some targets don't really support threads, but still
3225 reply an (empty) thread list in response to the thread
3226 listing packets, instead of replying "packet not
3227 supported". Exit early so we don't delete the main
3228 thread. */
3229 do_cleanups (old_chain);
3230 return;
3231 }
3232
ab970af1
PA
3233 /* CONTEXT now holds the current thread list on the remote
3234 target end. Delete GDB-side threads no longer found on the
3235 target. */
8a06aea7 3236 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3237 {
ab970af1
PA
3238 for (i = 0;
3239 VEC_iterate (thread_item_t, context.items, i, item);
3240 ++i)
3241 {
3242 if (ptid_equal (item->ptid, tp->ptid))
3243 break;
3244 }
3245
3246 if (i == VEC_length (thread_item_t, context.items))
3247 {
3248 /* Not found. */
3249 delete_thread (tp->ptid);
3250 }
cbb8991c
DB
3251 }
3252
3253 /* Remove any unreported fork child threads from CONTEXT so
3254 that we don't interfere with follow fork, which is where
3255 creation of such threads is handled. */
3256 remove_new_fork_children (&context);
74531fed 3257
ab970af1 3258 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3259 for (i = 0;
3260 VEC_iterate (thread_item_t, context.items, i, item);
3261 ++i)
3262 {
3263 if (!ptid_equal (item->ptid, null_ptid))
3264 {
3265 struct private_thread_info *info;
3266 /* In non-stop mode, we assume new found threads are
3267 running until proven otherwise with a stop reply. In
3268 all-stop, we can only get here if all threads are
3269 stopped. */
6efcd9a8 3270 int running = target_is_non_stop_p () ? 1 : 0;
6dc54d91
PA
3271
3272 remote_notice_new_inferior (item->ptid, running);
3273
3274 info = demand_private_info (item->ptid);
3275 info->core = item->core;
3276 info->extra = item->extra;
3277 item->extra = NULL;
79efa585
SM
3278 info->name = item->name;
3279 item->name = NULL;
6dc54d91
PA
3280 }
3281 }
3282 }
3283
ab970af1
PA
3284 if (!got_list)
3285 {
3286 /* If no thread listing method is supported, then query whether
3287 each known thread is alive, one by one, with the T packet.
3288 If the target doesn't support threads at all, then this is a
3289 no-op. See remote_thread_alive. */
3290 prune_threads ();
3291 }
3292
6dc54d91 3293 do_cleanups (old_chain);
9d1f7ab2
MS
3294}
3295
802188a7 3296/*
9d1f7ab2
MS
3297 * Collect a descriptive string about the given thread.
3298 * The target may say anything it wants to about the thread
3299 * (typically info about its blocked / runnable state, name, etc.).
3300 * This string will appear in the info threads display.
802188a7 3301 *
9d1f7ab2
MS
3302 * Optional: targets are not required to implement this function.
3303 */
3304
3305static char *
c15906d8 3306remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3307{
d01949b6 3308 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3309 int result;
3310 int set;
3311 threadref id;
3312 struct gdb_ext_thread_info threadinfo;
23860348 3313 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3314 int n = 0; /* position in display_buf */
3315
5d93a237 3316 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3317 internal_error (__FILE__, __LINE__,
e2e0b3e5 3318 _("remote_threads_extra_info"));
9d1f7ab2 3319
60e569b9 3320 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3321 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3322 /* This is the main thread which was added by GDB. The remote
3323 server doesn't know about it. */
3324 return NULL;
3325
4082afcc 3326 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3327 {
3328 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3329
fe978cb0
PA
3330 if (info && info->priv)
3331 return info->priv->extra;
dc146f7c
VP
3332 else
3333 return NULL;
3334 }
3335
b80fafe3 3336 if (rs->use_threadextra_query)
9d1f7ab2 3337 {
82f73884
PA
3338 char *b = rs->buf;
3339 char *endb = rs->buf + get_remote_packet_size ();
3340
3341 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3342 b += strlen (b);
3343 write_ptid (b, endb, tp->ptid);
3344
2e9f7625 3345 putpkt (rs->buf);
6d820c5c 3346 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3347 if (rs->buf[0] != 0)
9d1f7ab2 3348 {
2e9f7625
DJ
3349 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3350 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3351 display_buf [result] = '\0';
9d1f7ab2
MS
3352 return display_buf;
3353 }
0f71a2f6 3354 }
9d1f7ab2
MS
3355
3356 /* If the above query fails, fall back to the old method. */
b80fafe3 3357 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3358 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3359 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3360 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3361 if (remote_get_threadinfo (&id, set, &threadinfo))
3362 if (threadinfo.active)
0f71a2f6 3363 {
9d1f7ab2 3364 if (*threadinfo.shortname)
2bc416ba 3365 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3366 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3367 if (*threadinfo.display)
2bc416ba 3368 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3369 " State: %s,", threadinfo.display);
9d1f7ab2 3370 if (*threadinfo.more_display)
2bc416ba 3371 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3372 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3373
3374 if (n > 0)
c5aa993b 3375 {
23860348 3376 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3377 if (',' == display_buf[n-1])
3378 display_buf[n-1] = ' ';
3379 return display_buf;
c5aa993b 3380 }
0f71a2f6 3381 }
9d1f7ab2 3382 return NULL;
0f71a2f6 3383}
c906108c 3384\f
c5aa993b 3385
0fb4aa4b 3386static int
61fc905d 3387remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3388 struct static_tracepoint_marker *marker)
3389{
3390 struct remote_state *rs = get_remote_state ();
3391 char *p = rs->buf;
3392
bba74b36 3393 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3394 p += strlen (p);
3395 p += hexnumstr (p, addr);
3396 putpkt (rs->buf);
3397 getpkt (&rs->buf, &rs->buf_size, 0);
3398 p = rs->buf;
3399
3400 if (*p == 'E')
3401 error (_("Remote failure reply: %s"), p);
3402
3403 if (*p++ == 'm')
3404 {
3405 parse_static_tracepoint_marker_definition (p, &p, marker);
3406 return 1;
3407 }
3408
3409 return 0;
3410}
3411
0fb4aa4b 3412static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3413remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3414 const char *strid)
0fb4aa4b
PA
3415{
3416 struct remote_state *rs = get_remote_state ();
3417 VEC(static_tracepoint_marker_p) *markers = NULL;
3418 struct static_tracepoint_marker *marker = NULL;
3419 struct cleanup *old_chain;
3420 char *p;
3421
3422 /* Ask for a first packet of static tracepoint marker
3423 definition. */
3424 putpkt ("qTfSTM");
3425 getpkt (&rs->buf, &rs->buf_size, 0);
3426 p = rs->buf;
3427 if (*p == 'E')
3428 error (_("Remote failure reply: %s"), p);
3429
3430 old_chain = make_cleanup (free_current_marker, &marker);
3431
3432 while (*p++ == 'm')
3433 {
3434 if (marker == NULL)
3435 marker = XCNEW (struct static_tracepoint_marker);
3436
3437 do
3438 {
3439 parse_static_tracepoint_marker_definition (p, &p, marker);
3440
3441 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3442 {
3443 VEC_safe_push (static_tracepoint_marker_p,
3444 markers, marker);
3445 marker = NULL;
3446 }
3447 else
3448 {
3449 release_static_tracepoint_marker (marker);
3450 memset (marker, 0, sizeof (*marker));
3451 }
3452 }
3453 while (*p++ == ','); /* comma-separated list */
3454 /* Ask for another packet of static tracepoint definition. */
3455 putpkt ("qTsSTM");
3456 getpkt (&rs->buf, &rs->buf_size, 0);
3457 p = rs->buf;
3458 }
3459
3460 do_cleanups (old_chain);
3461 return markers;
3462}
3463
3464\f
10760264
JB
3465/* Implement the to_get_ada_task_ptid function for the remote targets. */
3466
3467static ptid_t
1e6b91a4 3468remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3469{
ba348170 3470 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3471}
3472\f
3473
24b06219 3474/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3475
3476static void
fba45db2 3477extended_remote_restart (void)
c906108c 3478{
d01949b6 3479 struct remote_state *rs = get_remote_state ();
c906108c
SS
3480
3481 /* Send the restart command; for reasons I don't understand the
3482 remote side really expects a number after the "R". */
ea9c271d 3483 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3484 putpkt (rs->buf);
c906108c 3485
ad9a8f3f 3486 remote_fileio_reset ();
c906108c
SS
3487}
3488\f
3489/* Clean up connection to a remote debugger. */
3490
c906108c 3491static void
de90e03d 3492remote_close (struct target_ops *self)
c906108c 3493{
5d93a237
TT
3494 struct remote_state *rs = get_remote_state ();
3495
3496 if (rs->remote_desc == NULL)
d3fd5342
PA
3497 return; /* already closed */
3498
3499 /* Make sure we leave stdin registered in the event loop, and we
3500 don't leave the async SIGINT signal handler installed. */
e3594fd1 3501 remote_terminal_ours (self);
ce5ce7ed 3502
5d93a237
TT
3503 serial_close (rs->remote_desc);
3504 rs->remote_desc = NULL;
ce5ce7ed
PA
3505
3506 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3507 of all the inferiors and their threads we were controlling.
3508 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3509 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3510 inferior_ptid = null_ptid;
f67fd822 3511 discard_all_inferiors ();
ce5ce7ed 3512
f48ff2a7
YQ
3513 /* We are closing the remote target, so we should discard
3514 everything of this target. */
bcc75809 3515 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3516
3517 if (remote_async_inferior_event_token)
3518 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3519
5965e028 3520 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3521
3522 trace_reset_local_state ();
c906108c
SS
3523}
3524
23860348 3525/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3526
3527static void
fba45db2 3528get_offsets (void)
c906108c 3529{
d01949b6 3530 struct remote_state *rs = get_remote_state ();
2e9f7625 3531 char *buf;
085dd6e6 3532 char *ptr;
31d99776
DJ
3533 int lose, num_segments = 0, do_sections, do_segments;
3534 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3535 struct section_offsets *offs;
31d99776
DJ
3536 struct symfile_segment_data *data;
3537
3538 if (symfile_objfile == NULL)
3539 return;
c906108c
SS
3540
3541 putpkt ("qOffsets");
6d820c5c 3542 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3543 buf = rs->buf;
c906108c
SS
3544
3545 if (buf[0] == '\000')
3546 return; /* Return silently. Stub doesn't support
23860348 3547 this command. */
c906108c
SS
3548 if (buf[0] == 'E')
3549 {
8a3fe4f8 3550 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3551 return;
3552 }
3553
3554 /* Pick up each field in turn. This used to be done with scanf, but
3555 scanf will make trouble if CORE_ADDR size doesn't match
3556 conversion directives correctly. The following code will work
3557 with any size of CORE_ADDR. */
3558 text_addr = data_addr = bss_addr = 0;
3559 ptr = buf;
3560 lose = 0;
3561
61012eef 3562 if (startswith (ptr, "Text="))
c906108c
SS
3563 {
3564 ptr += 5;
3565 /* Don't use strtol, could lose on big values. */
3566 while (*ptr && *ptr != ';')
3567 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3568
61012eef 3569 if (startswith (ptr, ";Data="))
31d99776
DJ
3570 {
3571 ptr += 6;
3572 while (*ptr && *ptr != ';')
3573 data_addr = (data_addr << 4) + fromhex (*ptr++);
3574 }
3575 else
3576 lose = 1;
3577
61012eef 3578 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3579 {
3580 ptr += 5;
3581 while (*ptr && *ptr != ';')
3582 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3583
31d99776
DJ
3584 if (bss_addr != data_addr)
3585 warning (_("Target reported unsupported offsets: %s"), buf);
3586 }
3587 else
3588 lose = 1;
3589 }
61012eef 3590 else if (startswith (ptr, "TextSeg="))
c906108c 3591 {
31d99776
DJ
3592 ptr += 8;
3593 /* Don't use strtol, could lose on big values. */
c906108c 3594 while (*ptr && *ptr != ';')
31d99776
DJ
3595 text_addr = (text_addr << 4) + fromhex (*ptr++);
3596 num_segments = 1;
3597
61012eef 3598 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3599 {
3600 ptr += 9;
3601 while (*ptr && *ptr != ';')
3602 data_addr = (data_addr << 4) + fromhex (*ptr++);
3603 num_segments++;
3604 }
c906108c
SS
3605 }
3606 else
3607 lose = 1;
3608
3609 if (lose)
8a3fe4f8 3610 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3611 else if (*ptr != '\0')
3612 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3613
802188a7 3614 offs = ((struct section_offsets *)
a39a16c4 3615 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3616 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3617 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3618
31d99776
DJ
3619 data = get_symfile_segment_data (symfile_objfile->obfd);
3620 do_segments = (data != NULL);
3621 do_sections = num_segments == 0;
c906108c 3622
28c32713 3623 if (num_segments > 0)
31d99776 3624 {
31d99776
DJ
3625 segments[0] = text_addr;
3626 segments[1] = data_addr;
3627 }
28c32713
JB
3628 /* If we have two segments, we can still try to relocate everything
3629 by assuming that the .text and .data offsets apply to the whole
3630 text and data segments. Convert the offsets given in the packet
3631 to base addresses for symfile_map_offsets_to_segments. */
3632 else if (data && data->num_segments == 2)
3633 {
3634 segments[0] = data->segment_bases[0] + text_addr;
3635 segments[1] = data->segment_bases[1] + data_addr;
3636 num_segments = 2;
3637 }
8d385431
DJ
3638 /* If the object file has only one segment, assume that it is text
3639 rather than data; main programs with no writable data are rare,
3640 but programs with no code are useless. Of course the code might
3641 have ended up in the data segment... to detect that we would need
3642 the permissions here. */
3643 else if (data && data->num_segments == 1)
3644 {
3645 segments[0] = data->segment_bases[0] + text_addr;
3646 num_segments = 1;
3647 }
28c32713
JB
3648 /* There's no way to relocate by segment. */
3649 else
3650 do_segments = 0;
31d99776
DJ
3651
3652 if (do_segments)
3653 {
3654 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3655 offs, num_segments, segments);
3656
3657 if (ret == 0 && !do_sections)
3e43a32a
MS
3658 error (_("Can not handle qOffsets TextSeg "
3659 "response with this symbol file"));
31d99776
DJ
3660
3661 if (ret > 0)
3662 do_sections = 0;
3663 }
c906108c 3664
9ef895d6
DJ
3665 if (data)
3666 free_symfile_segment_data (data);
31d99776
DJ
3667
3668 if (do_sections)
3669 {
3670 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3671
3e43a32a
MS
3672 /* This is a temporary kludge to force data and bss to use the
3673 same offsets because that's what nlmconv does now. The real
3674 solution requires changes to the stub and remote.c that I
3675 don't have time to do right now. */
31d99776
DJ
3676
3677 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3678 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3679 }
c906108c
SS
3680
3681 objfile_relocate (symfile_objfile, offs);
3682}
3683
9a7071a8
JB
3684/* Send interrupt_sequence to remote target. */
3685static void
eeae04df 3686send_interrupt_sequence (void)
9a7071a8 3687{
5d93a237
TT
3688 struct remote_state *rs = get_remote_state ();
3689
9a7071a8 3690 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3691 remote_serial_write ("\x03", 1);
9a7071a8 3692 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3693 serial_send_break (rs->remote_desc);
9a7071a8
JB
3694 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3695 {
5d93a237 3696 serial_send_break (rs->remote_desc);
c33e31fd 3697 remote_serial_write ("g", 1);
9a7071a8
JB
3698 }
3699 else
3700 internal_error (__FILE__, __LINE__,
3701 _("Invalid value for interrupt_sequence_mode: %s."),
3702 interrupt_sequence_mode);
3703}
3704
3405876a
PA
3705
3706/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3707 and extract the PTID. Returns NULL_PTID if not found. */
3708
3709static ptid_t
3710stop_reply_extract_thread (char *stop_reply)
3711{
3712 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3713 {
3714 char *p;
3715
3716 /* Txx r:val ; r:val (...) */
3717 p = &stop_reply[3];
3718
3719 /* Look for "register" named "thread". */
3720 while (*p != '\0')
3721 {
3722 char *p1;
3723
3724 p1 = strchr (p, ':');
3725 if (p1 == NULL)
3726 return null_ptid;
3727
3728 if (strncmp (p, "thread", p1 - p) == 0)
3729 return read_ptid (++p1, &p);
3730
3731 p1 = strchr (p, ';');
3732 if (p1 == NULL)
3733 return null_ptid;
3734 p1++;
3735
3736 p = p1;
3737 }
3738 }
3739
3740 return null_ptid;
3741}
3742
b7ea362b
PA
3743/* Determine the remote side's current thread. If we have a stop
3744 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3745 "thread" register we can extract the current thread from. If not,
3746 ask the remote which is the current thread with qC. The former
3747 method avoids a roundtrip. */
3748
3749static ptid_t
3750get_current_thread (char *wait_status)
3751{
6a49a997 3752 ptid_t ptid = null_ptid;
b7ea362b
PA
3753
3754 /* Note we don't use remote_parse_stop_reply as that makes use of
3755 the target architecture, which we haven't yet fully determined at
3756 this point. */
3757 if (wait_status != NULL)
3758 ptid = stop_reply_extract_thread (wait_status);
3759 if (ptid_equal (ptid, null_ptid))
3760 ptid = remote_current_thread (inferior_ptid);
3761
3762 return ptid;
3763}
3764
49c62f2e
PA
3765/* Query the remote target for which is the current thread/process,
3766 add it to our tables, and update INFERIOR_PTID. The caller is
3767 responsible for setting the state such that the remote end is ready
3405876a
PA
3768 to return the current thread.
3769
3770 This function is called after handling the '?' or 'vRun' packets,
3771 whose response is a stop reply from which we can also try
3772 extracting the thread. If the target doesn't support the explicit
3773 qC query, we infer the current thread from that stop reply, passed
3774 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3775
3776static void
3405876a 3777add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3778{
3779 struct remote_state *rs = get_remote_state ();
3780 int fake_pid_p = 0;
6a49a997 3781 ptid_t ptid;
49c62f2e
PA
3782
3783 inferior_ptid = null_ptid;
3784
b7ea362b
PA
3785 /* Now, if we have thread information, update inferior_ptid. */
3786 ptid = get_current_thread (wait_status);
3405876a 3787
49c62f2e
PA
3788 if (!ptid_equal (ptid, null_ptid))
3789 {
3790 if (!remote_multi_process_p (rs))
3791 fake_pid_p = 1;
3792
3793 inferior_ptid = ptid;
3794 }
3795 else
3796 {
3797 /* Without this, some commands which require an active target
3798 (such as kill) won't work. This variable serves (at least)
3799 double duty as both the pid of the target process (if it has
3800 such), and as a flag indicating that a target is active. */
3801 inferior_ptid = magic_null_ptid;
3802 fake_pid_p = 1;
3803 }
3804
1b6e6f5c 3805 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3806
3807 /* Add the main thread. */
3808 add_thread_silent (inferior_ptid);
3809}
3810
6efcd9a8
PA
3811/* Print info about a thread that was found already stopped on
3812 connection. */
3813
3814static void
3815print_one_stopped_thread (struct thread_info *thread)
3816{
3817 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3818
3819 switch_to_thread (thread->ptid);
3820 stop_pc = get_frame_pc (get_current_frame ());
3821 set_current_sal_from_frame (get_current_frame ());
3822
3823 thread->suspend.waitstatus_pending_p = 0;
3824
3825 if (ws->kind == TARGET_WAITKIND_STOPPED)
3826 {
3827 enum gdb_signal sig = ws->value.sig;
3828
3829 if (signal_print_state (sig))
3830 observer_notify_signal_received (sig);
3831 }
3832 observer_notify_normal_stop (NULL, 1);
3833}
3834
221e1a37
PA
3835/* Process all initial stop replies the remote side sent in response
3836 to the ? packet. These indicate threads that were already stopped
3837 on initial connection. We mark these threads as stopped and print
3838 their current frame before giving the user the prompt. */
3839
3840static void
6efcd9a8 3841process_initial_stop_replies (int from_tty)
221e1a37
PA
3842{
3843 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3844 struct inferior *inf;
3845 struct thread_info *thread;
3846 struct thread_info *selected = NULL;
3847 struct thread_info *lowest_stopped = NULL;
3848 struct thread_info *first = NULL;
221e1a37
PA
3849
3850 /* Consume the initial pending events. */
3851 while (pending_stop_replies-- > 0)
3852 {
3853 ptid_t waiton_ptid = minus_one_ptid;
3854 ptid_t event_ptid;
3855 struct target_waitstatus ws;
3856 int ignore_event = 0;
6efcd9a8 3857 struct thread_info *thread;
221e1a37
PA
3858
3859 memset (&ws, 0, sizeof (ws));
3860 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3861 if (remote_debug)
3862 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3863
3864 switch (ws.kind)
3865 {
3866 case TARGET_WAITKIND_IGNORE:
3867 case TARGET_WAITKIND_NO_RESUMED:
3868 case TARGET_WAITKIND_SIGNALLED:
3869 case TARGET_WAITKIND_EXITED:
3870 /* We shouldn't see these, but if we do, just ignore. */
3871 if (remote_debug)
3872 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3873 ignore_event = 1;
3874 break;
3875
3876 case TARGET_WAITKIND_EXECD:
3877 xfree (ws.value.execd_pathname);
3878 break;
3879 default:
3880 break;
3881 }
3882
3883 if (ignore_event)
3884 continue;
3885
6efcd9a8 3886 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3887
3888 if (ws.kind == TARGET_WAITKIND_STOPPED)
3889 {
3890 enum gdb_signal sig = ws.value.sig;
3891
3892 /* Stubs traditionally report SIGTRAP as initial signal,
3893 instead of signal 0. Suppress it. */
3894 if (sig == GDB_SIGNAL_TRAP)
3895 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3896 thread->suspend.stop_signal = sig;
3897 ws.value.sig = sig;
3898 }
221e1a37 3899
6efcd9a8
PA
3900 thread->suspend.waitstatus = ws;
3901
3902 if (ws.kind != TARGET_WAITKIND_STOPPED
3903 || ws.value.sig != GDB_SIGNAL_0)
3904 thread->suspend.waitstatus_pending_p = 1;
3905
3906 set_executing (event_ptid, 0);
3907 set_running (event_ptid, 0);
3908 }
3909
3910 /* "Notice" the new inferiors before anything related to
3911 registers/memory. */
3912 ALL_INFERIORS (inf)
3913 {
3914 if (inf->pid == 0)
3915 continue;
3916
3917 inf->needs_setup = 1;
3918
3919 if (non_stop)
3920 {
3921 thread = any_live_thread_of_process (inf->pid);
3922 notice_new_inferior (thread->ptid,
3923 thread->state == THREAD_RUNNING,
3924 from_tty);
3925 }
3926 }
3927
3928 /* If all-stop on top of non-stop, pause all threads. Note this
3929 records the threads' stop pc, so must be done after "noticing"
3930 the inferiors. */
3931 if (!non_stop)
3932 {
3933 stop_all_threads ();
3934
3935 /* If all threads of an inferior were already stopped, we
3936 haven't setup the inferior yet. */
3937 ALL_INFERIORS (inf)
3938 {
3939 if (inf->pid == 0)
3940 continue;
221e1a37 3941
6efcd9a8
PA
3942 if (inf->needs_setup)
3943 {
3944 thread = any_live_thread_of_process (inf->pid);
3945 switch_to_thread_no_regs (thread);
3946 setup_inferior (0);
3947 }
3948 }
221e1a37 3949 }
6efcd9a8
PA
3950
3951 /* Now go over all threads that are stopped, and print their current
3952 frame. If all-stop, then if there's a signalled thread, pick
3953 that as current. */
3954 ALL_NON_EXITED_THREADS (thread)
3955 {
3956 struct target_waitstatus *ws;
3957
3958 if (first == NULL)
3959 first = thread;
3960
3961 if (!non_stop)
3962 set_running (thread->ptid, 0);
3963 else if (thread->state != THREAD_STOPPED)
3964 continue;
3965
3966 ws = &thread->suspend.waitstatus;
3967
3968 if (selected == NULL
3969 && thread->suspend.waitstatus_pending_p)
3970 selected = thread;
3971
5d5658a1
PA
3972 if (lowest_stopped == NULL
3973 || thread->inf->num < lowest_stopped->inf->num
3974 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
3975 lowest_stopped = thread;
3976
3977 if (non_stop)
3978 print_one_stopped_thread (thread);
3979 }
3980
3981 /* In all-stop, we only print the status of one thread, and leave
3982 others with their status pending. */
3983 if (!non_stop)
3984 {
3985 thread = selected;
3986 if (thread == NULL)
3987 thread = lowest_stopped;
3988 if (thread == NULL)
3989 thread = first;
3990
3991 print_one_stopped_thread (thread);
3992 }
3993
3994 /* For "info program". */
3995 thread = inferior_thread ();
3996 if (thread->state == THREAD_STOPPED)
3997 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
3998}
3999
9cbc821d 4000static void
04bd08de 4001remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 4002{
c8d104ad
PA
4003 struct remote_state *rs = get_remote_state ();
4004 struct packet_config *noack_config;
2d717e4f 4005 char *wait_status = NULL;
8621d6a9 4006
23860348 4007 immediate_quit++; /* Allow user to interrupt it. */
522002f9 4008 QUIT;
c906108c 4009
9a7071a8
JB
4010 if (interrupt_on_connect)
4011 send_interrupt_sequence ();
4012
57e12211 4013 /* Ack any packet which the remote side has already sent. */
5d93a237 4014 serial_write (rs->remote_desc, "+", 1);
57e12211 4015
1e51243a
PA
4016 /* Signal other parts that we're going through the initial setup,
4017 and so things may not be stable yet. */
4018 rs->starting_up = 1;
4019
c8d104ad
PA
4020 /* The first packet we send to the target is the optional "supported
4021 packets" request. If the target can answer this, it will tell us
4022 which later probes to skip. */
4023 remote_query_supported ();
4024
d914c394 4025 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4026 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 4027 remote_set_permissions (target);
d914c394 4028
c8d104ad
PA
4029 /* Next, we possibly activate noack mode.
4030
4031 If the QStartNoAckMode packet configuration is set to AUTO,
4032 enable noack mode if the stub reported a wish for it with
4033 qSupported.
4034
4035 If set to TRUE, then enable noack mode even if the stub didn't
4036 report it in qSupported. If the stub doesn't reply OK, the
4037 session ends with an error.
4038
4039 If FALSE, then don't activate noack mode, regardless of what the
4040 stub claimed should be the default with qSupported. */
4041
4042 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4043 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4044 {
4045 putpkt ("QStartNoAckMode");
4046 getpkt (&rs->buf, &rs->buf_size, 0);
4047 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4048 rs->noack_mode = 1;
4049 }
4050
04bd08de 4051 if (extended_p)
5fe04517
PA
4052 {
4053 /* Tell the remote that we are using the extended protocol. */
4054 putpkt ("!");
4055 getpkt (&rs->buf, &rs->buf_size, 0);
4056 }
4057
9b224c5e
PA
4058 /* Let the target know which signals it is allowed to pass down to
4059 the program. */
4060 update_signals_program_target ();
4061
d962ef82
DJ
4062 /* Next, if the target can specify a description, read it. We do
4063 this before anything involving memory or registers. */
4064 target_find_description ();
4065
6c95b8df
PA
4066 /* Next, now that we know something about the target, update the
4067 address spaces in the program spaces. */
4068 update_address_spaces ();
4069
50c71eaf
PA
4070 /* On OSs where the list of libraries is global to all
4071 processes, we fetch them early. */
f5656ead 4072 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 4073 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 4074
6efcd9a8 4075 if (target_is_non_stop_p ())
74531fed 4076 {
4082afcc 4077 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4078 error (_("Non-stop mode requested, but remote "
4079 "does not support non-stop"));
74531fed
PA
4080
4081 putpkt ("QNonStop:1");
4082 getpkt (&rs->buf, &rs->buf_size, 0);
4083
4084 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4085 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4086
4087 /* Find about threads and processes the stub is already
4088 controlling. We default to adding them in the running state.
4089 The '?' query below will then tell us about which threads are
4090 stopped. */
e8032dde 4091 remote_update_thread_list (target);
74531fed 4092 }
4082afcc 4093 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4094 {
4095 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4096 Request it explicitly. */
74531fed
PA
4097 putpkt ("QNonStop:0");
4098 getpkt (&rs->buf, &rs->buf_size, 0);
4099
4100 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4101 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4102 }
4103
a0743c90
YQ
4104 /* Upload TSVs regardless of whether the target is running or not. The
4105 remote stub, such as GDBserver, may have some predefined or builtin
4106 TSVs, even if the target is not running. */
8bd200f1 4107 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4108 {
4109 struct uploaded_tsv *uploaded_tsvs = NULL;
4110
181e3713 4111 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4112 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4113 }
4114
2d717e4f
DJ
4115 /* Check whether the target is running now. */
4116 putpkt ("?");
4117 getpkt (&rs->buf, &rs->buf_size, 0);
4118
6efcd9a8 4119 if (!target_is_non_stop_p ())
2d717e4f 4120 {
e714e1bf
UW
4121 ptid_t ptid;
4122 int fake_pid_p = 0;
4123 struct inferior *inf;
4124
74531fed 4125 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4126 {
04bd08de 4127 if (!extended_p)
74531fed 4128 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4129
4130 /* We're connected, but not running. Drop out before we
4131 call start_remote. */
e278ad5b 4132 rs->starting_up = 0;
c35b1492 4133 return;
2d717e4f
DJ
4134 }
4135 else
74531fed 4136 {
74531fed 4137 /* Save the reply for later. */
224c3ddb 4138 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4139 strcpy (wait_status, rs->buf);
4140 }
4141
b7ea362b 4142 /* Fetch thread list. */
e8032dde 4143 target_update_thread_list ();
b7ea362b 4144
74531fed
PA
4145 /* Let the stub know that we want it to return the thread. */
4146 set_continue_thread (minus_one_ptid);
4147
b7ea362b
PA
4148 if (thread_count () == 0)
4149 {
4150 /* Target has no concept of threads at all. GDB treats
4151 non-threaded target as single-threaded; add a main
4152 thread. */
4153 add_current_inferior_and_thread (wait_status);
4154 }
4155 else
4156 {
4157 /* We have thread information; select the thread the target
4158 says should be current. If we're reconnecting to a
4159 multi-threaded program, this will ideally be the thread
4160 that last reported an event before GDB disconnected. */
4161 inferior_ptid = get_current_thread (wait_status);
4162 if (ptid_equal (inferior_ptid, null_ptid))
4163 {
4164 /* Odd... The target was able to list threads, but not
4165 tell us which thread was current (no "thread"
4166 register in T stop reply?). Just pick the first
4167 thread in the thread list then. */
c9f35b34
KB
4168
4169 if (remote_debug)
4170 fprintf_unfiltered (gdb_stdlog,
4171 "warning: couldn't determine remote "
4172 "current thread; picking first in list.\n");
4173
b7ea362b
PA
4174 inferior_ptid = thread_list->ptid;
4175 }
4176 }
74531fed 4177
6e586cc5
YQ
4178 /* init_wait_for_inferior should be called before get_offsets in order
4179 to manage `inserted' flag in bp loc in a correct state.
4180 breakpoint_init_inferior, called from init_wait_for_inferior, set
4181 `inserted' flag to 0, while before breakpoint_re_set, called from
4182 start_remote, set `inserted' flag to 1. In the initialization of
4183 inferior, breakpoint_init_inferior should be called first, and then
4184 breakpoint_re_set can be called. If this order is broken, state of
4185 `inserted' flag is wrong, and cause some problems on breakpoint
4186 manipulation. */
4187 init_wait_for_inferior ();
4188
74531fed
PA
4189 get_offsets (); /* Get text, data & bss offsets. */
4190
d962ef82
DJ
4191 /* If we could not find a description using qXfer, and we know
4192 how to do it some other way, try again. This is not
4193 supported for non-stop; it could be, but it is tricky if
4194 there are no stopped threads when we connect. */
04bd08de 4195 if (remote_read_description_p (target)
f5656ead 4196 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4197 {
4198 target_clear_description ();
4199 target_find_description ();
4200 }
4201
74531fed
PA
4202 /* Use the previously fetched status. */
4203 gdb_assert (wait_status != NULL);
4204 strcpy (rs->buf, wait_status);
4205 rs->cached_wait_status = 1;
4206
4207 immediate_quit--;
04bd08de 4208 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4209 }
4210 else
4211 {
68c97600
PA
4212 /* Clear WFI global state. Do this before finding about new
4213 threads and inferiors, and setting the current inferior.
4214 Otherwise we would clear the proceed status of the current
4215 inferior when we want its stop_soon state to be preserved
4216 (see notice_new_inferior). */
4217 init_wait_for_inferior ();
4218
74531fed
PA
4219 /* In non-stop, we will either get an "OK", meaning that there
4220 are no stopped threads at this time; or, a regular stop
4221 reply. In the latter case, there may be more than one thread
4222 stopped --- we pull them all out using the vStopped
4223 mechanism. */
4224 if (strcmp (rs->buf, "OK") != 0)
4225 {
722247f1 4226 struct notif_client *notif = &notif_client_stop;
2d717e4f 4227
722247f1
YQ
4228 /* remote_notif_get_pending_replies acks this one, and gets
4229 the rest out. */
f48ff2a7 4230 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4231 = remote_notif_parse (notif, rs->buf);
4232 remote_notif_get_pending_events (notif);
74531fed 4233 }
2d717e4f 4234
74531fed
PA
4235 if (thread_count () == 0)
4236 {
04bd08de 4237 if (!extended_p)
74531fed 4238 error (_("The target is not running (try extended-remote?)"));
82f73884 4239
c35b1492
PA
4240 /* We're connected, but not running. Drop out before we
4241 call start_remote. */
e278ad5b 4242 rs->starting_up = 0;
c35b1492
PA
4243 return;
4244 }
74531fed 4245
74531fed
PA
4246 /* In non-stop mode, any cached wait status will be stored in
4247 the stop reply queue. */
4248 gdb_assert (wait_status == NULL);
f0223081 4249
2455069d 4250 /* Report all signals during attach/startup. */
94bedb42 4251 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4252
4253 /* If there are already stopped threads, mark them stopped and
4254 report their stops before giving the prompt to the user. */
6efcd9a8 4255 process_initial_stop_replies (from_tty);
221e1a37
PA
4256
4257 if (target_can_async_p ())
4258 target_async (1);
74531fed 4259 }
c8d104ad 4260
c8d104ad
PA
4261 /* If we connected to a live target, do some additional setup. */
4262 if (target_has_execution)
4263 {
f4ccffad 4264 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4265 remote_check_symbols ();
c8d104ad 4266 }
50c71eaf 4267
d5551862
SS
4268 /* Possibly the target has been engaged in a trace run started
4269 previously; find out where things are at. */
8bd200f1 4270 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4271 {
00bf0b85 4272 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4273
00bf0b85
SS
4274 if (current_trace_status ()->running)
4275 printf_filtered (_("Trace is already running on the target.\n"));
4276
ab6617cc 4277 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4278
4279 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4280 }
4281
1e51243a
PA
4282 /* The thread and inferior lists are now synchronized with the
4283 target, our symbols have been relocated, and we're merged the
4284 target's tracepoints with ours. We're done with basic start
4285 up. */
4286 rs->starting_up = 0;
4287
a25a5a45
PA
4288 /* Maybe breakpoints are global and need to be inserted now. */
4289 if (breakpoints_should_be_inserted_now ())
50c71eaf 4290 insert_breakpoints ();
c906108c
SS
4291}
4292
4293/* Open a connection to a remote debugger.
4294 NAME is the filename used for communication. */
4295
4296static void
014f9477 4297remote_open (const char *name, int from_tty)
c906108c 4298{
75c99385 4299 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4300}
4301
c906108c
SS
4302/* Open a connection to a remote debugger using the extended
4303 remote gdb protocol. NAME is the filename used for communication. */
4304
4305static void
014f9477 4306extended_remote_open (const char *name, int from_tty)
c906108c 4307{
75c99385 4308 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4309}
4310
ca4f7f8b
PA
4311/* Reset all packets back to "unknown support". Called when opening a
4312 new connection to a remote target. */
c906108c 4313
d471ea57 4314static void
ca4f7f8b 4315reset_all_packet_configs_support (void)
d471ea57
AC
4316{
4317 int i;
a744cf53 4318
444abaca 4319 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4320 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4321}
4322
ca4f7f8b
PA
4323/* Initialize all packet configs. */
4324
4325static void
4326init_all_packet_configs (void)
4327{
4328 int i;
4329
4330 for (i = 0; i < PACKET_MAX; i++)
4331 {
4332 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4333 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4334 }
4335}
4336
23860348 4337/* Symbol look-up. */
dc8acb97
MS
4338
4339static void
36d25514 4340remote_check_symbols (void)
dc8acb97 4341{
d01949b6 4342 struct remote_state *rs = get_remote_state ();
dc8acb97 4343 char *msg, *reply, *tmp;
3b7344d5 4344 struct bound_minimal_symbol sym;
dc8acb97 4345 int end;
a5c0808e 4346 struct cleanup *old_chain;
dc8acb97 4347
63154eca
PA
4348 /* The remote side has no concept of inferiors that aren't running
4349 yet, it only knows about running processes. If we're connected
4350 but our current inferior is not running, we should not invite the
4351 remote target to request symbol lookups related to its
4352 (unrelated) current process. */
4353 if (!target_has_execution)
4354 return;
4355
4082afcc 4356 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4357 return;
4358
63154eca
PA
4359 /* Make sure the remote is pointing at the right process. Note
4360 there's no way to select "no process". */
3c9c4b83
PA
4361 set_general_process ();
4362
6d820c5c
DJ
4363 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4364 because we need both at the same time. */
224c3ddb 4365 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4366 old_chain = make_cleanup (xfree, msg);
6d820c5c 4367
23860348 4368 /* Invite target to request symbol lookups. */
dc8acb97
MS
4369
4370 putpkt ("qSymbol::");
6d820c5c
DJ
4371 getpkt (&rs->buf, &rs->buf_size, 0);
4372 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 4373 reply = rs->buf;
dc8acb97 4374
61012eef 4375 while (startswith (reply, "qSymbol:"))
dc8acb97 4376 {
77e371c0
TT
4377 struct bound_minimal_symbol sym;
4378
dc8acb97 4379 tmp = &reply[8];
cfd77fa1 4380 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4381 msg[end] = '\0';
4382 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4383 if (sym.minsym == NULL)
ea9c271d 4384 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4385 else
2bbe3cc1 4386 {
f5656ead 4387 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4388 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4389
4390 /* If this is a function address, return the start of code
4391 instead of any data function descriptor. */
f5656ead 4392 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4393 sym_addr,
4394 &current_target);
4395
4396 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4397 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4398 }
4399
dc8acb97 4400 putpkt (msg);
6d820c5c 4401 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4402 reply = rs->buf;
dc8acb97 4403 }
a5c0808e
PA
4404
4405 do_cleanups (old_chain);
dc8acb97
MS
4406}
4407
9db8d71f 4408static struct serial *
baa336ce 4409remote_serial_open (const char *name)
9db8d71f
DJ
4410{
4411 static int udp_warning = 0;
4412
4413 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4414 of in ser-tcp.c, because it is the remote protocol assuming that the
4415 serial connection is reliable and not the serial connection promising
4416 to be. */
61012eef 4417 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4418 {
3e43a32a
MS
4419 warning (_("The remote protocol may be unreliable over UDP.\n"
4420 "Some events may be lost, rendering further debugging "
4421 "impossible."));
9db8d71f
DJ
4422 udp_warning = 1;
4423 }
4424
4425 return serial_open (name);
4426}
4427
d914c394
SS
4428/* Inform the target of our permission settings. The permission flags
4429 work without this, but if the target knows the settings, it can do
4430 a couple things. First, it can add its own check, to catch cases
4431 that somehow manage to get by the permissions checks in target
4432 methods. Second, if the target is wired to disallow particular
4433 settings (for instance, a system in the field that is not set up to
4434 be able to stop at a breakpoint), it can object to any unavailable
4435 permissions. */
4436
4437void
c378d69d 4438remote_set_permissions (struct target_ops *self)
d914c394
SS
4439{
4440 struct remote_state *rs = get_remote_state ();
4441
bba74b36
YQ
4442 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4443 "WriteReg:%x;WriteMem:%x;"
4444 "InsertBreak:%x;InsertTrace:%x;"
4445 "InsertFastTrace:%x;Stop:%x",
4446 may_write_registers, may_write_memory,
4447 may_insert_breakpoints, may_insert_tracepoints,
4448 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4449 putpkt (rs->buf);
4450 getpkt (&rs->buf, &rs->buf_size, 0);
4451
4452 /* If the target didn't like the packet, warn the user. Do not try
4453 to undo the user's settings, that would just be maddening. */
4454 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4455 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4456}
4457
be2a5f71
DJ
4458/* This type describes each known response to the qSupported
4459 packet. */
4460struct protocol_feature
4461{
4462 /* The name of this protocol feature. */
4463 const char *name;
4464
4465 /* The default for this protocol feature. */
4466 enum packet_support default_support;
4467
4468 /* The function to call when this feature is reported, or after
4469 qSupported processing if the feature is not supported.
4470 The first argument points to this structure. The second
4471 argument indicates whether the packet requested support be
4472 enabled, disabled, or probed (or the default, if this function
4473 is being called at the end of processing and this feature was
4474 not reported). The third argument may be NULL; if not NULL, it
4475 is a NUL-terminated string taken from the packet following
4476 this feature's name and an equals sign. */
4477 void (*func) (const struct protocol_feature *, enum packet_support,
4478 const char *);
4479
4480 /* The corresponding packet for this feature. Only used if
4481 FUNC is remote_supported_packet. */
4482 int packet;
4483};
4484
be2a5f71
DJ
4485static void
4486remote_supported_packet (const struct protocol_feature *feature,
4487 enum packet_support support,
4488 const char *argument)
4489{
4490 if (argument)
4491 {
4492 warning (_("Remote qSupported response supplied an unexpected value for"
4493 " \"%s\"."), feature->name);
4494 return;
4495 }
4496
4082afcc 4497 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4498}
be2a5f71
DJ
4499
4500static void
4501remote_packet_size (const struct protocol_feature *feature,
4502 enum packet_support support, const char *value)
4503{
4504 struct remote_state *rs = get_remote_state ();
4505
4506 int packet_size;
4507 char *value_end;
4508
4509 if (support != PACKET_ENABLE)
4510 return;
4511
4512 if (value == NULL || *value == '\0')
4513 {
4514 warning (_("Remote target reported \"%s\" without a size."),
4515 feature->name);
4516 return;
4517 }
4518
4519 errno = 0;
4520 packet_size = strtol (value, &value_end, 16);
4521 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4522 {
4523 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4524 feature->name, value);
4525 return;
4526 }
4527
be2a5f71
DJ
4528 /* Record the new maximum packet size. */
4529 rs->explicit_packet_size = packet_size;
4530}
4531
dc473cfb 4532static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4533 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4534 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4535 PACKET_qXfer_auxv },
c78fa86a
GB
4536 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4537 PACKET_qXfer_exec_file },
23181151
DJ
4538 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4539 PACKET_qXfer_features },
cfa9d6d9
DJ
4540 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4541 PACKET_qXfer_libraries },
2268b414
JK
4542 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4543 PACKET_qXfer_libraries_svr4 },
ced63ec0 4544 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4545 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4546 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4547 PACKET_qXfer_memory_map },
4de6483e
UW
4548 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4549 PACKET_qXfer_spu_read },
4550 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4551 PACKET_qXfer_spu_write },
07e059b5
VP
4552 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4553 PACKET_qXfer_osdata },
dc146f7c
VP
4554 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4555 PACKET_qXfer_threads },
b3b9301e
PA
4556 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4557 PACKET_qXfer_traceframe_info },
89be2091
DJ
4558 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4559 PACKET_QPassSignals },
82075af2
JS
4560 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4561 PACKET_QCatchSyscalls },
9b224c5e
PA
4562 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4563 PACKET_QProgramSignals },
a6f3e723
SL
4564 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4565 PACKET_QStartNoAckMode },
4082afcc
PA
4566 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4567 PACKET_multiprocess_feature },
4568 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4569 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4570 PACKET_qXfer_siginfo_read },
4571 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4572 PACKET_qXfer_siginfo_write },
4082afcc 4573 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4574 PACKET_ConditionalTracepoints },
4082afcc 4575 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4576 PACKET_ConditionalBreakpoints },
4082afcc 4577 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4578 PACKET_BreakpointCommands },
4082afcc 4579 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4580 PACKET_FastTracepoints },
4082afcc 4581 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4582 PACKET_StaticTracepoints },
4082afcc 4583 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4584 PACKET_InstallInTrace},
4082afcc
PA
4585 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4586 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4587 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4588 PACKET_bc },
4589 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4590 PACKET_bs },
409873ef
SS
4591 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4592 PACKET_TracepointSource },
d914c394
SS
4593 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4594 PACKET_QAllow },
4082afcc
PA
4595 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4596 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4597 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4598 PACKET_qXfer_fdpic },
169081d0
TG
4599 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4600 PACKET_qXfer_uib },
03583c20
UW
4601 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4602 PACKET_QDisableRandomization },
d1feda86 4603 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4604 { "QTBuffer:size", PACKET_DISABLE,
4605 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4606 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4607 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4608 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4609 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4610 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4611 PACKET_qXfer_btrace },
4612 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4613 PACKET_qXfer_btrace_conf },
4614 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4615 PACKET_Qbtrace_conf_bts_size },
4616 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4617 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4618 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4619 PACKET_fork_event_feature },
4620 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4621 PACKET_vfork_event_feature },
94585166
DB
4622 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4623 PACKET_exec_event_feature },
b20a6524 4624 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4625 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4626 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4627 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4628 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4629};
4630
c8d5aac9
L
4631static char *remote_support_xml;
4632
4633/* Register string appended to "xmlRegisters=" in qSupported query. */
4634
4635void
6e39997a 4636register_remote_support_xml (const char *xml)
c8d5aac9
L
4637{
4638#if defined(HAVE_LIBEXPAT)
4639 if (remote_support_xml == NULL)
c4f7c687 4640 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4641 else
4642 {
4643 char *copy = xstrdup (remote_support_xml + 13);
4644 char *p = strtok (copy, ",");
4645
4646 do
4647 {
4648 if (strcmp (p, xml) == 0)
4649 {
4650 /* already there */
4651 xfree (copy);
4652 return;
4653 }
4654 }
4655 while ((p = strtok (NULL, ",")) != NULL);
4656 xfree (copy);
4657
94b0dee1
PA
4658 remote_support_xml = reconcat (remote_support_xml,
4659 remote_support_xml, ",", xml,
4660 (char *) NULL);
c8d5aac9
L
4661 }
4662#endif
4663}
4664
4665static char *
4666remote_query_supported_append (char *msg, const char *append)
4667{
4668 if (msg)
94b0dee1 4669 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4670 else
4671 return xstrdup (append);
4672}
4673
be2a5f71
DJ
4674static void
4675remote_query_supported (void)
4676{
4677 struct remote_state *rs = get_remote_state ();
4678 char *next;
4679 int i;
4680 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4681
4682 /* The packet support flags are handled differently for this packet
4683 than for most others. We treat an error, a disabled packet, and
4684 an empty response identically: any features which must be reported
4685 to be used will be automatically disabled. An empty buffer
4686 accomplishes this, since that is also the representation for a list
4687 containing no features. */
4688
4689 rs->buf[0] = 0;
4082afcc 4690 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4691 {
c8d5aac9 4692 char *q = NULL;
94b0dee1 4693 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4694
73b8c1fd
PA
4695 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4696 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4697
f7e6eed5
PA
4698 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4699 q = remote_query_supported_append (q, "swbreak+");
4700 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4701 q = remote_query_supported_append (q, "hwbreak+");
4702
dde08ee1
PA
4703 q = remote_query_supported_append (q, "qRelocInsn+");
4704
8020350c
DB
4705 if (packet_set_cmd_state (PACKET_fork_event_feature)
4706 != AUTO_BOOLEAN_FALSE)
4707 q = remote_query_supported_append (q, "fork-events+");
4708 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4709 != AUTO_BOOLEAN_FALSE)
4710 q = remote_query_supported_append (q, "vfork-events+");
4711 if (packet_set_cmd_state (PACKET_exec_event_feature)
4712 != AUTO_BOOLEAN_FALSE)
4713 q = remote_query_supported_append (q, "exec-events+");
89245bc0 4714
750ce8d1
YQ
4715 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4716 q = remote_query_supported_append (q, "vContSupported+");
4717
65706a29
PA
4718 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4719 q = remote_query_supported_append (q, "QThreadEvents+");
4720
f2faf941
PA
4721 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4722 q = remote_query_supported_append (q, "no-resumed+");
4723
b35d5edb
PA
4724 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4725 the qSupported:xmlRegisters=i386 handling. */
4726 if (remote_support_xml != NULL)
4727 q = remote_query_supported_append (q, remote_support_xml);
4728
dde08ee1
PA
4729 q = reconcat (q, "qSupported:", q, (char *) NULL);
4730 putpkt (q);
82f73884 4731
94b0dee1
PA
4732 do_cleanups (old_chain);
4733
be2a5f71
DJ
4734 getpkt (&rs->buf, &rs->buf_size, 0);
4735
4736 /* If an error occured, warn, but do not return - just reset the
4737 buffer to empty and go on to disable features. */
4738 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4739 == PACKET_ERROR)
4740 {
4741 warning (_("Remote failure reply: %s"), rs->buf);
4742 rs->buf[0] = 0;
4743 }
4744 }
4745
4746 memset (seen, 0, sizeof (seen));
4747
4748 next = rs->buf;
4749 while (*next)
4750 {
4751 enum packet_support is_supported;
4752 char *p, *end, *name_end, *value;
4753
4754 /* First separate out this item from the rest of the packet. If
4755 there's another item after this, we overwrite the separator
4756 (terminated strings are much easier to work with). */
4757 p = next;
4758 end = strchr (p, ';');
4759 if (end == NULL)
4760 {
4761 end = p + strlen (p);
4762 next = end;
4763 }
4764 else
4765 {
89be2091
DJ
4766 *end = '\0';
4767 next = end + 1;
4768
be2a5f71
DJ
4769 if (end == p)
4770 {
4771 warning (_("empty item in \"qSupported\" response"));
4772 continue;
4773 }
be2a5f71
DJ
4774 }
4775
4776 name_end = strchr (p, '=');
4777 if (name_end)
4778 {
4779 /* This is a name=value entry. */
4780 is_supported = PACKET_ENABLE;
4781 value = name_end + 1;
4782 *name_end = '\0';
4783 }
4784 else
4785 {
4786 value = NULL;
4787 switch (end[-1])
4788 {
4789 case '+':
4790 is_supported = PACKET_ENABLE;
4791 break;
4792
4793 case '-':
4794 is_supported = PACKET_DISABLE;
4795 break;
4796
4797 case '?':
4798 is_supported = PACKET_SUPPORT_UNKNOWN;
4799 break;
4800
4801 default:
3e43a32a
MS
4802 warning (_("unrecognized item \"%s\" "
4803 "in \"qSupported\" response"), p);
be2a5f71
DJ
4804 continue;
4805 }
4806 end[-1] = '\0';
4807 }
4808
4809 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4810 if (strcmp (remote_protocol_features[i].name, p) == 0)
4811 {
4812 const struct protocol_feature *feature;
4813
4814 seen[i] = 1;
4815 feature = &remote_protocol_features[i];
4816 feature->func (feature, is_supported, value);
4817 break;
4818 }
4819 }
4820
4821 /* If we increased the packet size, make sure to increase the global
4822 buffer size also. We delay this until after parsing the entire
4823 qSupported packet, because this is the same buffer we were
4824 parsing. */
4825 if (rs->buf_size < rs->explicit_packet_size)
4826 {
4827 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4828 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4829 }
4830
4831 /* Handle the defaults for unmentioned features. */
4832 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4833 if (!seen[i])
4834 {
4835 const struct protocol_feature *feature;
4836
4837 feature = &remote_protocol_features[i];
4838 feature->func (feature, feature->default_support, NULL);
4839 }
4840}
4841
78a095c3
JK
4842/* Remove any of the remote.c targets from target stack. Upper targets depend
4843 on it so remove them first. */
4844
4845static void
4846remote_unpush_target (void)
4847{
915ef8b1 4848 pop_all_targets_at_and_above (process_stratum);
78a095c3 4849}
be2a5f71 4850
c906108c 4851static void
014f9477 4852remote_open_1 (const char *name, int from_tty,
3e43a32a 4853 struct target_ops *target, int extended_p)
c906108c 4854{
d01949b6 4855 struct remote_state *rs = get_remote_state ();
a6f3e723 4856
c906108c 4857 if (name == 0)
8a3fe4f8 4858 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4859 "serial device is attached to the remote system\n"
8a3fe4f8 4860 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4861
23860348 4862 /* See FIXME above. */
c6ebd6cf 4863 if (!target_async_permitted)
92d1e331 4864 wait_forever_enabled_p = 1;
6426a772 4865
2d717e4f 4866 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4867 Ask this question first, before target_preopen has a chance to kill
4868 anything. */
5d93a237 4869 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4870 {
78a095c3
JK
4871 if (from_tty
4872 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4873 error (_("Still connected."));
4874 }
4875
78a095c3 4876 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4877 target_preopen (from_tty);
4878
89be2091 4879 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4880 xfree (rs->last_pass_packet);
4881 rs->last_pass_packet = NULL;
89be2091 4882
9b224c5e
PA
4883 /* Make sure we send the program signals list the next time we
4884 resume. */
5e4a05c4
TT
4885 xfree (rs->last_program_signals_packet);
4886 rs->last_program_signals_packet = NULL;
9b224c5e 4887
ad9a8f3f 4888 remote_fileio_reset ();
1dd41f16
NS
4889 reopen_exec_file ();
4890 reread_symbols ();
4891
5d93a237
TT
4892 rs->remote_desc = remote_serial_open (name);
4893 if (!rs->remote_desc)
c906108c
SS
4894 perror_with_name (name);
4895
4896 if (baud_rate != -1)
4897 {
5d93a237 4898 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4899 {
9b74d5d3
KB
4900 /* The requested speed could not be set. Error out to
4901 top level after closing remote_desc. Take care to
4902 set remote_desc to NULL to avoid closing remote_desc
4903 more than once. */
5d93a237
TT
4904 serial_close (rs->remote_desc);
4905 rs->remote_desc = NULL;
c906108c
SS
4906 perror_with_name (name);
4907 }
4908 }
4909
236af5e3 4910 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4911 serial_raw (rs->remote_desc);
c906108c
SS
4912
4913 /* If there is something sitting in the buffer we might take it as a
4914 response to a command, which would be bad. */
5d93a237 4915 serial_flush_input (rs->remote_desc);
c906108c
SS
4916
4917 if (from_tty)
4918 {
4919 puts_filtered ("Remote debugging using ");
4920 puts_filtered (name);
4921 puts_filtered ("\n");
4922 }
23860348 4923 push_target (target); /* Switch to using remote target now. */
c906108c 4924
74531fed
PA
4925 /* Register extra event sources in the event loop. */
4926 remote_async_inferior_event_token
4927 = create_async_event_handler (remote_async_inferior_event_handler,
4928 NULL);
5965e028 4929 rs->notif_state = remote_notif_state_allocate ();
74531fed 4930
be2a5f71
DJ
4931 /* Reset the target state; these things will be queried either by
4932 remote_query_supported or as they are needed. */
ca4f7f8b 4933 reset_all_packet_configs_support ();
74531fed 4934 rs->cached_wait_status = 0;
be2a5f71 4935 rs->explicit_packet_size = 0;
a6f3e723 4936 rs->noack_mode = 0;
82f73884 4937 rs->extended = extended_p;
e24a49d8 4938 rs->waiting_for_stop_reply = 0;
3a29589a 4939 rs->ctrlc_pending_p = 0;
802188a7 4940
47f8a51d
TT
4941 rs->general_thread = not_sent_ptid;
4942 rs->continue_thread = not_sent_ptid;
262e1174 4943 rs->remote_traceframe_number = -1;
c906108c 4944
9d1f7ab2 4945 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4946 rs->use_threadinfo_query = 1;
4947 rs->use_threadextra_query = 1;
9d1f7ab2 4948
80152258
PA
4949 readahead_cache_invalidate ();
4950
c6ebd6cf 4951 if (target_async_permitted)
92d1e331 4952 {
23860348 4953 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4954 remote_async_terminal_ours_p = 1;
4955
4956 /* FIXME: cagney/1999-09-23: During the initial connection it is
4957 assumed that the target is already ready and able to respond to
0df8b418 4958 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4959 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4960 around this. Eventually a mechanism that allows
92d1e331 4961 wait_for_inferior() to expect/get timeouts will be
23860348 4962 implemented. */
92d1e331
DJ
4963 wait_forever_enabled_p = 0;
4964 }
4965
23860348 4966 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4967 no_shared_libraries (NULL, 0);
f78f6cf1 4968
74531fed
PA
4969 /* Start afresh. */
4970 init_thread_list ();
4971
36918e70 4972 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4973 target (we'd otherwise be in an inconsistent state) and then
4974 propogate the error on up the exception chain. This ensures that
4975 the caller doesn't stumble along blindly assuming that the
4976 function succeeded. The CLI doesn't have this problem but other
4977 UI's, such as MI do.
36918e70
AC
4978
4979 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4980 this function should return an error indication letting the
ce2826aa 4981 caller restore the previous state. Unfortunately the command
36918e70
AC
4982 ``target remote'' is directly wired to this function making that
4983 impossible. On a positive note, the CLI side of this problem has
4984 been fixed - the function set_cmd_context() makes it possible for
4985 all the ``target ....'' commands to share a common callback
4986 function. See cli-dump.c. */
109c3e39 4987 {
2d717e4f 4988
492d29ea 4989 TRY
04bd08de
TT
4990 {
4991 remote_start_remote (from_tty, target, extended_p);
4992 }
492d29ea 4993 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4994 {
c8d104ad
PA
4995 /* Pop the partially set up target - unless something else did
4996 already before throwing the exception. */
5d93a237 4997 if (rs->remote_desc != NULL)
78a095c3 4998 remote_unpush_target ();
c6ebd6cf 4999 if (target_async_permitted)
109c3e39
AC
5000 wait_forever_enabled_p = 1;
5001 throw_exception (ex);
5002 }
492d29ea 5003 END_CATCH
109c3e39 5004 }
c906108c 5005
f4abbc16
MM
5006 remote_btrace_reset ();
5007
c6ebd6cf 5008 if (target_async_permitted)
92d1e331 5009 wait_forever_enabled_p = 1;
43ff13b4
JM
5010}
5011
de0d863e
DB
5012/* Detach the specified process. */
5013
5014static void
5015remote_detach_pid (int pid)
5016{
5017 struct remote_state *rs = get_remote_state ();
5018
5019 if (remote_multi_process_p (rs))
5020 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5021 else
5022 strcpy (rs->buf, "D");
5023
5024 putpkt (rs->buf);
5025 getpkt (&rs->buf, &rs->buf_size, 0);
5026
5027 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5028 ;
5029 else if (rs->buf[0] == '\0')
5030 error (_("Remote doesn't know how to detach"));
5031 else
5032 error (_("Can't detach process."));
5033}
5034
5035/* This detaches a program to which we previously attached, using
5036 inferior_ptid to identify the process. After this is done, GDB
5037 can be used to debug some other program. We better not have left
5038 any breakpoints in the target program or it'll die when it hits
5039 one. */
c906108c
SS
5040
5041static void
de0d863e 5042remote_detach_1 (const char *args, int from_tty)
c906108c 5043{
82f73884 5044 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5045 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5046 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5047 int is_fork_parent;
c906108c
SS
5048
5049 if (args)
8a3fe4f8 5050 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 5051
2d717e4f
DJ
5052 if (!target_has_execution)
5053 error (_("No process to detach from."));
5054
7cee1e54
PA
5055 if (from_tty)
5056 {
5057 char *exec_file = get_exec_file (0);
5058 if (exec_file == NULL)
5059 exec_file = "";
5060 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
5061 target_pid_to_str (pid_to_ptid (pid)));
5062 gdb_flush (gdb_stdout);
5063 }
5064
c906108c 5065 /* Tell the remote target to detach. */
de0d863e 5066 remote_detach_pid (pid);
82f73884 5067
8020350c
DB
5068 /* Exit only if this is the only active inferior. */
5069 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5070 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5071
de0d863e
DB
5072 /* Check to see if we are detaching a fork parent. Note that if we
5073 are detaching a fork child, tp == NULL. */
5074 is_fork_parent = (tp != NULL
5075 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5076
5077 /* If doing detach-on-fork, we don't mourn, because that will delete
5078 breakpoints that should be available for the followed inferior. */
5079 if (!is_fork_parent)
5080 target_mourn_inferior ();
5081 else
5082 {
5083 inferior_ptid = null_ptid;
5084 detach_inferior (pid);
5085 }
2d717e4f
DJ
5086}
5087
5088static void
52554a0e 5089remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5090{
de0d863e 5091 remote_detach_1 (args, from_tty);
2d717e4f
DJ
5092}
5093
5094static void
52554a0e 5095extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5096{
de0d863e
DB
5097 remote_detach_1 (args, from_tty);
5098}
5099
5100/* Target follow-fork function for remote targets. On entry, and
5101 at return, the current inferior is the fork parent.
5102
5103 Note that although this is currently only used for extended-remote,
5104 it is named remote_follow_fork in anticipation of using it for the
5105 remote target as well. */
5106
5107static int
5108remote_follow_fork (struct target_ops *ops, int follow_child,
5109 int detach_fork)
5110{
5111 struct remote_state *rs = get_remote_state ();
c269dbdb 5112 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5113
c269dbdb
DB
5114 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5115 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5116 {
5117 /* When following the parent and detaching the child, we detach
5118 the child here. For the case of following the child and
5119 detaching the parent, the detach is done in the target-
5120 independent follow fork code in infrun.c. We can't use
5121 target_detach when detaching an unfollowed child because
5122 the client side doesn't know anything about the child. */
5123 if (detach_fork && !follow_child)
5124 {
5125 /* Detach the fork child. */
5126 ptid_t child_ptid;
5127 pid_t child_pid;
5128
5129 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5130 child_pid = ptid_get_pid (child_ptid);
5131
5132 remote_detach_pid (child_pid);
5133 detach_inferior (child_pid);
5134 }
5135 }
5136 return 0;
c906108c
SS
5137}
5138
94585166
DB
5139/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5140 in the program space of the new inferior. On entry and at return the
5141 current inferior is the exec'ing inferior. INF is the new exec'd
5142 inferior, which may be the same as the exec'ing inferior unless
5143 follow-exec-mode is "new". */
5144
5145static void
5146remote_follow_exec (struct target_ops *ops,
5147 struct inferior *inf, char *execd_pathname)
5148{
5149 /* We know that this is a target file name, so if it has the "target:"
5150 prefix we strip it off before saving it in the program space. */
5151 if (is_target_filename (execd_pathname))
5152 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5153
5154 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5155}
5156
6ad8ae5c
DJ
5157/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5158
43ff13b4 5159static void
fee354ee 5160remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5161{
43ff13b4 5162 if (args)
2d717e4f 5163 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5164
8020350c
DB
5165 /* Make sure we unpush even the extended remote targets. Calling
5166 target_mourn_inferior won't unpush, and remote_mourn won't
5167 unpush if there is more than one inferior left. */
5168 unpush_target (target);
5169 generic_mourn_inferior ();
2d717e4f 5170
43ff13b4
JM
5171 if (from_tty)
5172 puts_filtered ("Ending remote debugging.\n");
5173}
5174
2d717e4f
DJ
5175/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5176 be chatty about it. */
5177
5178static void
20f796c9
GB
5179extended_remote_attach (struct target_ops *target, const char *args,
5180 int from_tty)
2d717e4f
DJ
5181{
5182 struct remote_state *rs = get_remote_state ();
be86555c 5183 int pid;
96ef3384 5184 char *wait_status = NULL;
2d717e4f 5185
74164c56 5186 pid = parse_pid_to_attach (args);
2d717e4f 5187
74164c56
JK
5188 /* Remote PID can be freely equal to getpid, do not check it here the same
5189 way as in other targets. */
2d717e4f 5190
4082afcc 5191 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5192 error (_("This target does not support attaching to a process"));
5193
7cee1e54
PA
5194 if (from_tty)
5195 {
5196 char *exec_file = get_exec_file (0);
5197
5198 if (exec_file)
5199 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5200 target_pid_to_str (pid_to_ptid (pid)));
5201 else
5202 printf_unfiltered (_("Attaching to %s\n"),
5203 target_pid_to_str (pid_to_ptid (pid)));
5204
5205 gdb_flush (gdb_stdout);
5206 }
5207
bba74b36 5208 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5209 putpkt (rs->buf);
5210 getpkt (&rs->buf, &rs->buf_size, 0);
5211
4082afcc
PA
5212 switch (packet_ok (rs->buf,
5213 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5214 {
4082afcc 5215 case PACKET_OK:
6efcd9a8 5216 if (!target_is_non_stop_p ())
74531fed
PA
5217 {
5218 /* Save the reply for later. */
224c3ddb 5219 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5220 strcpy (wait_status, rs->buf);
5221 }
5222 else if (strcmp (rs->buf, "OK") != 0)
5223 error (_("Attaching to %s failed with: %s"),
5224 target_pid_to_str (pid_to_ptid (pid)),
5225 rs->buf);
4082afcc
PA
5226 break;
5227 case PACKET_UNKNOWN:
5228 error (_("This target does not support attaching to a process"));
5229 default:
5230 error (_("Attaching to %s failed"),
5231 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5232 }
2d717e4f 5233
1b6e6f5c 5234 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5235
2d717e4f 5236 inferior_ptid = pid_to_ptid (pid);
79d7f229 5237
6efcd9a8 5238 if (target_is_non_stop_p ())
bad34192
PA
5239 {
5240 struct thread_info *thread;
79d7f229 5241
bad34192 5242 /* Get list of threads. */
e8032dde 5243 remote_update_thread_list (target);
82f73884 5244
bad34192
PA
5245 thread = first_thread_of_process (pid);
5246 if (thread)
5247 inferior_ptid = thread->ptid;
5248 else
5249 inferior_ptid = pid_to_ptid (pid);
5250
5251 /* Invalidate our notion of the remote current thread. */
47f8a51d 5252 record_currthread (rs, minus_one_ptid);
bad34192 5253 }
74531fed 5254 else
bad34192
PA
5255 {
5256 /* Now, if we have thread information, update inferior_ptid. */
5257 inferior_ptid = remote_current_thread (inferior_ptid);
5258
5259 /* Add the main thread to the thread list. */
5260 add_thread_silent (inferior_ptid);
5261 }
c0a2216e 5262
96ef3384
UW
5263 /* Next, if the target can specify a description, read it. We do
5264 this before anything involving memory or registers. */
5265 target_find_description ();
5266
6efcd9a8 5267 if (!target_is_non_stop_p ())
74531fed
PA
5268 {
5269 /* Use the previously fetched status. */
5270 gdb_assert (wait_status != NULL);
5271
5272 if (target_can_async_p ())
5273 {
722247f1
YQ
5274 struct notif_event *reply
5275 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5276
722247f1 5277 push_stop_reply ((struct stop_reply *) reply);
74531fed 5278
6a3753b3 5279 target_async (1);
74531fed
PA
5280 }
5281 else
5282 {
5283 gdb_assert (wait_status != NULL);
5284 strcpy (rs->buf, wait_status);
5285 rs->cached_wait_status = 1;
5286 }
5287 }
5288 else
5289 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5290}
5291
b9c1d481
AS
5292/* Implementation of the to_post_attach method. */
5293
5294static void
5295extended_remote_post_attach (struct target_ops *ops, int pid)
5296{
6efcd9a8
PA
5297 /* Get text, data & bss offsets. */
5298 get_offsets ();
5299
b9c1d481
AS
5300 /* In certain cases GDB might not have had the chance to start
5301 symbol lookup up until now. This could happen if the debugged
5302 binary is not using shared libraries, the vsyscall page is not
5303 present (on Linux) and the binary itself hadn't changed since the
5304 debugging process was started. */
5305 if (symfile_objfile != NULL)
5306 remote_check_symbols();
5307}
5308
c906108c 5309\f
506fb367
DJ
5310/* Check for the availability of vCont. This function should also check
5311 the response. */
c906108c
SS
5312
5313static void
6d820c5c 5314remote_vcont_probe (struct remote_state *rs)
c906108c 5315{
2e9f7625 5316 char *buf;
6d820c5c 5317
2e9f7625
DJ
5318 strcpy (rs->buf, "vCont?");
5319 putpkt (rs->buf);
6d820c5c 5320 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5321 buf = rs->buf;
c906108c 5322
506fb367 5323 /* Make sure that the features we assume are supported. */
61012eef 5324 if (startswith (buf, "vCont"))
506fb367
DJ
5325 {
5326 char *p = &buf[5];
750ce8d1 5327 int support_c, support_C;
506fb367 5328
750ce8d1
YQ
5329 rs->supports_vCont.s = 0;
5330 rs->supports_vCont.S = 0;
506fb367
DJ
5331 support_c = 0;
5332 support_C = 0;
d458bd84 5333 rs->supports_vCont.t = 0;
c1e36e3e 5334 rs->supports_vCont.r = 0;
506fb367
DJ
5335 while (p && *p == ';')
5336 {
5337 p++;
5338 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5339 rs->supports_vCont.s = 1;
506fb367 5340 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5341 rs->supports_vCont.S = 1;
506fb367
DJ
5342 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5343 support_c = 1;
5344 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5345 support_C = 1;
74531fed 5346 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5347 rs->supports_vCont.t = 1;
c1e36e3e
PA
5348 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5349 rs->supports_vCont.r = 1;
506fb367
DJ
5350
5351 p = strchr (p, ';');
5352 }
c906108c 5353
750ce8d1
YQ
5354 /* If c, and C are not all supported, we can't use vCont. Clearing
5355 BUF will make packet_ok disable the packet. */
5356 if (!support_c || !support_C)
506fb367
DJ
5357 buf[0] = 0;
5358 }
c906108c 5359
444abaca 5360 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5361}
c906108c 5362
0d8f58ca
PA
5363/* Helper function for building "vCont" resumptions. Write a
5364 resumption to P. ENDP points to one-passed-the-end of the buffer
5365 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5366 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5367 resumed thread should be single-stepped and/or signalled. If PTID
5368 equals minus_one_ptid, then all threads are resumed; if PTID
5369 represents a process, then all threads of the process are resumed;
5370 the thread to be stepped and/or signalled is given in the global
5371 INFERIOR_PTID. */
5372
5373static char *
5374append_resumption (char *p, char *endp,
2ea28649 5375 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5376{
5377 struct remote_state *rs = get_remote_state ();
5378
a493e3e2 5379 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5380 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5381 else if (step
5382 /* GDB is willing to range step. */
5383 && use_range_stepping
5384 /* Target supports range stepping. */
5385 && rs->supports_vCont.r
5386 /* We don't currently support range stepping multiple
5387 threads with a wildcard (though the protocol allows it,
5388 so stubs shouldn't make an active effort to forbid
5389 it). */
5390 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5391 {
5392 struct thread_info *tp;
5393
5394 if (ptid_equal (ptid, minus_one_ptid))
5395 {
5396 /* If we don't know about the target thread's tid, then
5397 we're resuming magic_null_ptid (see caller). */
5398 tp = find_thread_ptid (magic_null_ptid);
5399 }
5400 else
5401 tp = find_thread_ptid (ptid);
5402 gdb_assert (tp != NULL);
5403
5404 if (tp->control.may_range_step)
5405 {
5406 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5407
5408 p += xsnprintf (p, endp - p, ";r%s,%s",
5409 phex_nz (tp->control.step_range_start,
5410 addr_size),
5411 phex_nz (tp->control.step_range_end,
5412 addr_size));
5413 }
5414 else
5415 p += xsnprintf (p, endp - p, ";s");
5416 }
0d8f58ca
PA
5417 else if (step)
5418 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5419 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5420 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5421 else
5422 p += xsnprintf (p, endp - p, ";c");
5423
5424 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5425 {
5426 ptid_t nptid;
5427
5428 /* All (-1) threads of process. */
ba348170 5429 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5430
5431 p += xsnprintf (p, endp - p, ":");
5432 p = write_ptid (p, endp, nptid);
5433 }
5434 else if (!ptid_equal (ptid, minus_one_ptid))
5435 {
5436 p += xsnprintf (p, endp - p, ":");
5437 p = write_ptid (p, endp, ptid);
5438 }
5439
5440 return p;
5441}
5442
799a2abe
PA
5443/* Clear the thread's private info on resume. */
5444
5445static void
5446resume_clear_thread_private_info (struct thread_info *thread)
5447{
5448 if (thread->priv != NULL)
5449 {
5450 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5451 thread->priv->watch_data_address = 0;
5452 }
5453}
5454
e5ef252a
PA
5455/* Append a vCont continue-with-signal action for threads that have a
5456 non-zero stop signal. */
5457
5458static char *
5459append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5460{
5461 struct thread_info *thread;
5462
034f788c 5463 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5464 if (ptid_match (thread->ptid, ptid)
5465 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5466 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5467 {
5468 p = append_resumption (p, endp, thread->ptid,
5469 0, thread->suspend.stop_signal);
5470 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5471 resume_clear_thread_private_info (thread);
e5ef252a
PA
5472 }
5473
5474 return p;
5475}
5476
506fb367
DJ
5477/* Resume the remote inferior by using a "vCont" packet. The thread
5478 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5479 resumed thread should be single-stepped and/or signalled. If PTID
5480 equals minus_one_ptid, then all threads are resumed; the thread to
5481 be stepped and/or signalled is given in the global INFERIOR_PTID.
5482 This function returns non-zero iff it resumes the inferior.
44eaed12 5483
506fb367
DJ
5484 This function issues a strict subset of all possible vCont commands at the
5485 moment. */
44eaed12 5486
506fb367 5487static int
2ea28649 5488remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5489{
5490 struct remote_state *rs = get_remote_state ();
82f73884
PA
5491 char *p;
5492 char *endp;
44eaed12 5493
4082afcc 5494 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5495 remote_vcont_probe (rs);
44eaed12 5496
4082afcc 5497 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5498 return 0;
44eaed12 5499
82f73884
PA
5500 p = rs->buf;
5501 endp = rs->buf + get_remote_packet_size ();
5502
506fb367
DJ
5503 /* If we could generate a wider range of packets, we'd have to worry
5504 about overflowing BUF. Should there be a generic
5505 "multi-part-packet" packet? */
5506
0d8f58ca
PA
5507 p += xsnprintf (p, endp - p, "vCont");
5508
79d7f229 5509 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5510 {
79d7f229
PA
5511 /* MAGIC_NULL_PTID means that we don't have any active threads,
5512 so we don't have any TID numbers the inferior will
5513 understand. Make sure to only send forms that do not specify
5514 a TID. */
a9cbf802 5515 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5516 }
0d8f58ca 5517 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5518 {
0d8f58ca
PA
5519 /* Resume all threads (of all processes, or of a single
5520 process), with preference for INFERIOR_PTID. This assumes
5521 inferior_ptid belongs to the set of all threads we are about
5522 to resume. */
a493e3e2 5523 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5524 {
0d8f58ca
PA
5525 /* Step inferior_ptid, with or without signal. */
5526 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5527 }
0d8f58ca 5528
e5ef252a
PA
5529 /* Also pass down any pending signaled resumption for other
5530 threads not the current. */
5531 p = append_pending_thread_resumptions (p, endp, ptid);
5532
0d8f58ca 5533 /* And continue others without a signal. */
a493e3e2 5534 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5535 }
5536 else
506fb367
DJ
5537 {
5538 /* Scheduler locking; resume only PTID. */
a9cbf802 5539 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5540 }
c906108c 5541
82f73884
PA
5542 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5543 putpkt (rs->buf);
506fb367 5544
6efcd9a8 5545 if (target_is_non_stop_p ())
74531fed
PA
5546 {
5547 /* In non-stop, the stub replies to vCont with "OK". The stop
5548 reply will be reported asynchronously by means of a `%Stop'
5549 notification. */
5550 getpkt (&rs->buf, &rs->buf_size, 0);
5551 if (strcmp (rs->buf, "OK") != 0)
5552 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5553 }
5554
506fb367 5555 return 1;
c906108c 5556}
43ff13b4 5557
506fb367
DJ
5558/* Tell the remote machine to resume. */
5559
43ff13b4 5560static void
28439f5e 5561remote_resume (struct target_ops *ops,
2ea28649 5562 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5563{
d01949b6 5564 struct remote_state *rs = get_remote_state ();
2e9f7625 5565 char *buf;
799a2abe 5566 struct thread_info *thread;
43ff13b4 5567
722247f1
YQ
5568 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5569 (explained in remote-notif.c:handle_notification) so
5570 remote_notif_process is not called. We need find a place where
5571 it is safe to start a 'vNotif' sequence. It is good to do it
5572 before resuming inferior, because inferior was stopped and no RSP
5573 traffic at that moment. */
6efcd9a8 5574 if (!target_is_non_stop_p ())
5965e028 5575 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5576
b73be471 5577 rs->last_sent_signal = siggnal;
280ceea3 5578 rs->last_sent_step = step;
43ff13b4 5579
506fb367 5580 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5581 /* No reverse support (yet) for vCont. */
5582 if (execution_direction != EXEC_REVERSE)
5583 if (remote_vcont_resume (ptid, step, siggnal))
5584 goto done;
506fb367 5585
79d7f229
PA
5586 /* All other supported resume packets do use Hc, so set the continue
5587 thread. */
5588 if (ptid_equal (ptid, minus_one_ptid))
5589 set_continue_thread (any_thread_ptid);
506fb367 5590 else
79d7f229 5591 set_continue_thread (ptid);
506fb367 5592
799a2abe
PA
5593 ALL_NON_EXITED_THREADS (thread)
5594 resume_clear_thread_private_info (thread);
5595
2e9f7625 5596 buf = rs->buf;
b2175913
MS
5597 if (execution_direction == EXEC_REVERSE)
5598 {
5599 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5600 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5601 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5602 siggnal);
40ab02ce 5603
4082afcc 5604 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5605 error (_("Remote reverse-step not supported."));
4082afcc 5606 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5607 error (_("Remote reverse-continue not supported."));
40ab02ce 5608
b2175913
MS
5609 strcpy (buf, step ? "bs" : "bc");
5610 }
a493e3e2 5611 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5612 {
5613 buf[0] = step ? 'S' : 'C';
c5aa993b 5614 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5615 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5616 buf[3] = '\0';
5617 }
5618 else
c5aa993b 5619 strcpy (buf, step ? "s" : "c");
506fb367 5620
44eaed12 5621 putpkt (buf);
43ff13b4 5622
75c99385 5623 done:
2acceee2 5624 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5625 with the event loop. NOTE: this is the one place where all the
5626 execution commands end up. We could alternatively do this in each
23860348 5627 of the execution commands in infcmd.c. */
2acceee2
JM
5628 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5629 into infcmd.c in order to allow inferior function calls to work
23860348 5630 NOT asynchronously. */
362646f5 5631 if (target_can_async_p ())
6a3753b3 5632 target_async (1);
e24a49d8
PA
5633
5634 /* We've just told the target to resume. The remote server will
5635 wait for the inferior to stop, and then send a stop reply. In
5636 the mean time, we can't start another command/query ourselves
74531fed
PA
5637 because the stub wouldn't be ready to process it. This applies
5638 only to the base all-stop protocol, however. In non-stop (which
5639 only supports vCont), the stub replies with an "OK", and is
5640 immediate able to process further serial input. */
6efcd9a8 5641 if (!target_is_non_stop_p ())
74531fed 5642 rs->waiting_for_stop_reply = 1;
43ff13b4 5643}
c906108c 5644\f
43ff13b4
JM
5645
5646/* Set up the signal handler for SIGINT, while the target is
23860348 5647 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5648static void
934b9bac 5649async_initialize_sigint_signal_handler (void)
43ff13b4 5650{
934b9bac 5651 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5652}
5653
23860348 5654/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5655static void
934b9bac 5656async_handle_remote_sigint (int sig)
43ff13b4 5657{
934b9bac 5658 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5659 /* Note we need to go through gdb_call_async_signal_handler in order
5660 to wake up the event loop on Windows. */
5661 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5662}
5663
5664/* Signal handler for SIGINT, installed after SIGINT has already been
5665 sent once. It will take effect the second time that the user sends
23860348 5666 a ^C. */
43ff13b4 5667static void
934b9bac 5668async_handle_remote_sigint_twice (int sig)
43ff13b4 5669{
934b9bac 5670 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5671 /* See note in async_handle_remote_sigint. */
5672 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5673}
5674
abc56d60
PA
5675/* Implementation of to_check_pending_interrupt. */
5676
5677static void
5678remote_check_pending_interrupt (struct target_ops *self)
5679{
5680 struct async_signal_handler *token = async_sigint_remote_twice_token;
5681
5682 if (async_signal_handler_is_marked (token))
5683 {
5684 clear_async_signal_handler (token);
5685 call_async_signal_handler (token);
5686 }
5687}
5688
6426a772 5689/* Perform the real interruption of the target execution, in response
23860348 5690 to a ^C. */
c5aa993b 5691static void
fba45db2 5692async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5693{
5694 if (remote_debug)
248fd3bf 5695 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5696
de979965 5697 target_interrupt (inferior_ptid);
43ff13b4
JM
5698}
5699
0df8b418 5700/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5701 up on the target alltogether. */
47e1ce27 5702static void
fba45db2 5703async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5704{
2df3850c 5705 if (remote_debug)
248fd3bf 5706 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5707
5708 interrupt_query ();
43ff13b4
JM
5709}
5710
5711/* Reinstall the usual SIGINT handlers, after the target has
23860348 5712 stopped. */
6426a772 5713static void
934b9bac 5714async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5715{
5716 signal (SIGINT, handle_sigint);
43ff13b4
JM
5717}
5718
c906108c
SS
5719/* Send ^C to target to halt it. Target will respond, and send us a
5720 packet. */
507f3c78 5721static void (*ofunc) (int);
c906108c 5722
bfedc46a
PA
5723/* The command line interface's interrupt routine. This function is installed
5724 as a signal handler for SIGINT. The first time a user requests an
5725 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5726 response from the target (it didn't stop when the user requested it),
23860348 5727 we ask the user if he'd like to detach from the target. */
bfedc46a 5728
c906108c 5729static void
934b9bac 5730sync_remote_interrupt (int signo)
c906108c 5731{
23860348 5732 /* If this doesn't work, try more severe steps. */
934b9bac 5733 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5734
934b9bac 5735 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5736}
5737
5738/* The user typed ^C twice. */
5739
5740static void
934b9bac 5741sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5742{
5743 signal (signo, ofunc);
934b9bac
JK
5744 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5745 signal (signo, sync_remote_interrupt);
c906108c 5746}
7a292a7a 5747
74531fed
PA
5748/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5749 thread, all threads of a remote process, or all threads of all
5750 processes. */
5751
5752static void
5753remote_stop_ns (ptid_t ptid)
5754{
5755 struct remote_state *rs = get_remote_state ();
5756 char *p = rs->buf;
5757 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5758
4082afcc 5759 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5760 remote_vcont_probe (rs);
5761
d458bd84 5762 if (!rs->supports_vCont.t)
74531fed
PA
5763 error (_("Remote server does not support stopping threads"));
5764
f91d3df5
PA
5765 if (ptid_equal (ptid, minus_one_ptid)
5766 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5767 p += xsnprintf (p, endp - p, "vCont;t");
5768 else
5769 {
5770 ptid_t nptid;
5771
74531fed
PA
5772 p += xsnprintf (p, endp - p, "vCont;t:");
5773
5774 if (ptid_is_pid (ptid))
5775 /* All (-1) threads of process. */
ba348170 5776 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5777 else
5778 {
5779 /* Small optimization: if we already have a stop reply for
5780 this thread, no use in telling the stub we want this
5781 stopped. */
5782 if (peek_stop_reply (ptid))
5783 return;
5784
5785 nptid = ptid;
5786 }
5787
a9cbf802 5788 write_ptid (p, endp, nptid);
74531fed
PA
5789 }
5790
5791 /* In non-stop, we get an immediate OK reply. The stop reply will
5792 come in asynchronously by notification. */
5793 putpkt (rs->buf);
5794 getpkt (&rs->buf, &rs->buf_size, 0);
5795 if (strcmp (rs->buf, "OK") != 0)
5796 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5797}
5798
bfedc46a
PA
5799/* All-stop version of target_interrupt. Sends a break or a ^C to
5800 interrupt the remote target. It is undefined which thread of which
5801 process reports the interrupt. */
74531fed
PA
5802
5803static void
de979965 5804remote_interrupt_as (void)
74531fed
PA
5805{
5806 struct remote_state *rs = get_remote_state ();
5807
3a29589a
DJ
5808 rs->ctrlc_pending_p = 1;
5809
74531fed
PA
5810 /* If the inferior is stopped already, but the core didn't know
5811 about it yet, just ignore the request. The cached wait status
5812 will be collected in remote_wait. */
5813 if (rs->cached_wait_status)
5814 return;
5815
9a7071a8
JB
5816 /* Send interrupt_sequence to remote target. */
5817 send_interrupt_sequence ();
74531fed
PA
5818}
5819
de979965
PA
5820/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5821 the remote target. It is undefined which thread of which process
5822 reports the interrupt. Returns true if the packet is supported by
5823 the server, false otherwise. */
5824
5825static int
5826remote_interrupt_ns (void)
5827{
5828 struct remote_state *rs = get_remote_state ();
5829 char *p = rs->buf;
5830 char *endp = rs->buf + get_remote_packet_size ();
5831
5832 xsnprintf (p, endp - p, "vCtrlC");
5833
5834 /* In non-stop, we get an immediate OK reply. The stop reply will
5835 come in asynchronously by notification. */
5836 putpkt (rs->buf);
5837 getpkt (&rs->buf, &rs->buf_size, 0);
5838
5839 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5840 {
5841 case PACKET_OK:
5842 break;
5843 case PACKET_UNKNOWN:
5844 return 0;
5845 case PACKET_ERROR:
5846 error (_("Interrupting target failed: %s"), rs->buf);
5847 }
5848
5849 return 1;
5850}
5851
bfedc46a 5852/* Implement the to_stop function for the remote targets. */
74531fed 5853
c906108c 5854static void
1eab8a48 5855remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5856{
7a292a7a 5857 if (remote_debug)
0f71a2f6 5858 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5859
6efcd9a8 5860 if (target_is_non_stop_p ())
74531fed 5861 remote_stop_ns (ptid);
c906108c 5862 else
bfedc46a
PA
5863 {
5864 /* We don't currently have a way to transparently pause the
5865 remote target in all-stop mode. Interrupt it instead. */
de979965 5866 remote_interrupt_as ();
bfedc46a
PA
5867 }
5868}
5869
5870/* Implement the to_interrupt function for the remote targets. */
5871
5872static void
5873remote_interrupt (struct target_ops *self, ptid_t ptid)
5874{
5875 if (remote_debug)
5876 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5877
de979965 5878 if (non_stop)
bfedc46a 5879 {
de979965 5880 /* In non-stop mode, we always stop with no signal instead. */
bfedc46a
PA
5881 remote_stop_ns (ptid);
5882 }
5883 else
de979965
PA
5884 {
5885 /* In all-stop, we emulate ^C-ing the remote target's
5886 terminal. */
5887 if (target_is_non_stop_p ())
5888 {
5889 if (!remote_interrupt_ns ())
5890 {
5891 /* No support for ^C-ing the remote target. Stop it
5892 (with no signal) instead. */
5893 remote_stop_ns (ptid);
5894 }
5895 }
5896 else
5897 remote_interrupt_as ();
5898 }
c906108c
SS
5899}
5900
5901/* Ask the user what to do when an interrupt is received. */
5902
5903static void
fba45db2 5904interrupt_query (void)
c906108c 5905{
abc56d60
PA
5906 struct remote_state *rs = get_remote_state ();
5907 struct cleanup *old_chain;
5908
5909 old_chain = make_cleanup_restore_target_terminal ();
c906108c
SS
5910 target_terminal_ours ();
5911
abc56d60 5912 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5913 {
abc56d60
PA
5914 if (query (_("The target is not responding to interrupt requests.\n"
5915 "Stop debugging it? ")))
74531fed 5916 {
78a095c3 5917 remote_unpush_target ();
abc56d60 5918 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5919 }
5920 }
abc56d60
PA
5921 else
5922 {
5923 if (query (_("Interrupted while waiting for the program.\n"
5924 "Give up waiting? ")))
5925 quit ();
5926 }
c906108c 5927
abc56d60 5928 do_cleanups (old_chain);
c906108c
SS
5929}
5930
6426a772
JM
5931/* Enable/disable target terminal ownership. Most targets can use
5932 terminal groups to control terminal ownership. Remote targets are
5933 different in that explicit transfer of ownership to/from GDB/target
23860348 5934 is required. */
6426a772
JM
5935
5936static void
d2f640d4 5937remote_terminal_inferior (struct target_ops *self)
6426a772 5938{
c6ebd6cf 5939 if (!target_async_permitted)
75c99385
PA
5940 /* Nothing to do. */
5941 return;
5942
d9d2d8b6
PA
5943 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5944 idempotent. The event-loop GDB talking to an asynchronous target
5945 with a synchronous command calls this function from both
5946 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5947 transfer the terminal to the target when it shouldn't this guard
5948 can go away. */
6426a772
JM
5949 if (!remote_async_terminal_ours_p)
5950 return;
5951 delete_file_handler (input_fd);
5952 remote_async_terminal_ours_p = 0;
934b9bac 5953 async_initialize_sigint_signal_handler ();
6426a772
JM
5954 /* NOTE: At this point we could also register our selves as the
5955 recipient of all input. Any characters typed could then be
23860348 5956 passed on down to the target. */
6426a772
JM
5957}
5958
5959static void
e3594fd1 5960remote_terminal_ours (struct target_ops *self)
6426a772 5961{
c6ebd6cf 5962 if (!target_async_permitted)
75c99385
PA
5963 /* Nothing to do. */
5964 return;
5965
5966 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5967 if (remote_async_terminal_ours_p)
5968 return;
934b9bac 5969 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5970 add_file_handler (input_fd, stdin_event_handler, 0);
5971 remote_async_terminal_ours_p = 1;
5972}
5973
176a6961 5974static void
917317f4 5975remote_console_output (char *msg)
c906108c
SS
5976{
5977 char *p;
5978
c5aa993b 5979 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5980 {
5981 char tb[2];
5982 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5983
c906108c
SS
5984 tb[0] = c;
5985 tb[1] = 0;
43ff13b4 5986 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5987 }
00db5b94
PA
5988 gdb_flush (gdb_stdtarg);
5989}
74531fed
PA
5990
5991typedef struct cached_reg
5992{
5993 int num;
5994 gdb_byte data[MAX_REGISTER_SIZE];
5995} cached_reg_t;
5996
5997DEF_VEC_O(cached_reg_t);
5998
722247f1 5999typedef struct stop_reply
74531fed 6000{
722247f1 6001 struct notif_event base;
74531fed 6002
722247f1 6003 /* The identifier of the thread about this event */
74531fed
PA
6004 ptid_t ptid;
6005
340e3c99 6006 /* The remote state this event is associated with. When the remote
bcc75809
YQ
6007 connection, represented by a remote_state object, is closed,
6008 all the associated stop_reply events should be released. */
6009 struct remote_state *rs;
6010
74531fed
PA
6011 struct target_waitstatus ws;
6012
15148d6a
PA
6013 /* Expedited registers. This makes remote debugging a bit more
6014 efficient for those targets that provide critical registers as
6015 part of their normal status mechanism (as another roundtrip to
6016 fetch them is avoided). */
74531fed
PA
6017 VEC(cached_reg_t) *regcache;
6018
f7e6eed5
PA
6019 enum target_stop_reason stop_reason;
6020
74531fed
PA
6021 CORE_ADDR watch_data_address;
6022
dc146f7c 6023 int core;
722247f1 6024} *stop_reply_p;
a744cf53 6025
722247f1
YQ
6026DECLARE_QUEUE_P (stop_reply_p);
6027DEFINE_QUEUE_P (stop_reply_p);
6028/* The list of already fetched and acknowledged stop events. This
6029 queue is used for notification Stop, and other notifications
6030 don't need queue for their events, because the notification events
6031 of Stop can't be consumed immediately, so that events should be
6032 queued first, and be consumed by remote_wait_{ns,as} one per
6033 time. Other notifications can consume their events immediately,
6034 so queue is not needed for them. */
6035static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
6036
6037static void
6038stop_reply_xfree (struct stop_reply *r)
6039{
f48ff2a7 6040 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
6041}
6042
221e1a37
PA
6043/* Return the length of the stop reply queue. */
6044
6045static int
6046stop_reply_queue_length (void)
6047{
6048 return QUEUE_length (stop_reply_p, stop_reply_queue);
6049}
6050
722247f1
YQ
6051static void
6052remote_notif_stop_parse (struct notif_client *self, char *buf,
6053 struct notif_event *event)
6054{
6055 remote_parse_stop_reply (buf, (struct stop_reply *) event);
6056}
6057
6058static void
6059remote_notif_stop_ack (struct notif_client *self, char *buf,
6060 struct notif_event *event)
6061{
6062 struct stop_reply *stop_reply = (struct stop_reply *) event;
6063
6064 /* acknowledge */
6065 putpkt ((char *) self->ack_command);
6066
6067 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6068 /* We got an unknown stop reply. */
6069 error (_("Unknown stop reply"));
6070
6071 push_stop_reply (stop_reply);
6072}
6073
6074static int
6075remote_notif_stop_can_get_pending_events (struct notif_client *self)
6076{
6077 /* We can't get pending events in remote_notif_process for
6078 notification stop, and we have to do this in remote_wait_ns
6079 instead. If we fetch all queued events from stub, remote stub
6080 may exit and we have no chance to process them back in
6081 remote_wait_ns. */
6082 mark_async_event_handler (remote_async_inferior_event_token);
6083 return 0;
6084}
6085
6086static void
6087stop_reply_dtr (struct notif_event *event)
6088{
6089 struct stop_reply *r = (struct stop_reply *) event;
6090
6091 VEC_free (cached_reg_t, r->regcache);
6092}
6093
6094static struct notif_event *
6095remote_notif_stop_alloc_reply (void)
6096{
8d749320
SM
6097 /* We cast to a pointer to the "base class". */
6098 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6099
6100 r->dtr = stop_reply_dtr;
6101
6102 return r;
6103}
6104
6105/* A client of notification Stop. */
6106
6107struct notif_client notif_client_stop =
6108{
6109 "Stop",
6110 "vStopped",
6111 remote_notif_stop_parse,
6112 remote_notif_stop_ack,
6113 remote_notif_stop_can_get_pending_events,
6114 remote_notif_stop_alloc_reply,
f48ff2a7 6115 REMOTE_NOTIF_STOP,
722247f1
YQ
6116};
6117
6118/* A parameter to pass data in and out. */
6119
6120struct queue_iter_param
6121{
6122 void *input;
6123 struct stop_reply *output;
6124};
6125
cbb8991c
DB
6126/* Determine if THREAD is a pending fork parent thread. ARG contains
6127 the pid of the process that owns the threads we want to check, or
6128 -1 if we want to check all threads. */
6129
6130static int
6131is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6132 ptid_t thread_ptid)
6133{
6134 if (ws->kind == TARGET_WAITKIND_FORKED
6135 || ws->kind == TARGET_WAITKIND_VFORKED)
6136 {
6137 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6138 return 1;
6139 }
6140
6141 return 0;
6142}
6143
6144/* Check whether EVENT is a fork event, and if it is, remove the
6145 fork child from the context list passed in DATA. */
6146
6147static int
6148remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6149 QUEUE_ITER (stop_reply_p) *iter,
6150 stop_reply_p event,
6151 void *data)
6152{
19ba03f4
SM
6153 struct queue_iter_param *param = (struct queue_iter_param *) data;
6154 struct threads_listing_context *context
6155 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6156
6157 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6158 || event->ws.kind == TARGET_WAITKIND_VFORKED
6159 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6160 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6161
6162 return 1;
6163}
6164
6165/* If CONTEXT contains any fork child threads that have not been
6166 reported yet, remove them from the CONTEXT list. If such a
6167 thread exists it is because we are stopped at a fork catchpoint
6168 and have not yet called follow_fork, which will set up the
6169 host-side data structures for the new process. */
6170
6171static void
6172remove_new_fork_children (struct threads_listing_context *context)
6173{
6174 struct thread_info * thread;
6175 int pid = -1;
6176 struct notif_client *notif = &notif_client_stop;
6177 struct queue_iter_param param;
6178
6179 /* For any threads stopped at a fork event, remove the corresponding
6180 fork child threads from the CONTEXT list. */
6181 ALL_NON_EXITED_THREADS (thread)
6182 {
6183 struct target_waitstatus *ws = &thread->pending_follow;
6184
6185 if (is_pending_fork_parent (ws, pid, thread->ptid))
6186 {
6187 threads_listing_context_remove (ws, context);
6188 }
6189 }
6190
6191 /* Check for any pending fork events (not reported or processed yet)
6192 in process PID and remove those fork child threads from the
6193 CONTEXT list as well. */
6194 remote_notif_get_pending_events (notif);
6195 param.input = context;
6196 param.output = NULL;
6197 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6198 remove_child_of_pending_fork, &param);
6199}
6200
f48ff2a7
YQ
6201/* Remove stop replies in the queue if its pid is equal to the given
6202 inferior's pid. */
722247f1
YQ
6203
6204static int
f48ff2a7
YQ
6205remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6206 QUEUE_ITER (stop_reply_p) *iter,
6207 stop_reply_p event,
6208 void *data)
722247f1 6209{
19ba03f4
SM
6210 struct queue_iter_param *param = (struct queue_iter_param *) data;
6211 struct inferior *inf = (struct inferior *) param->input;
722247f1 6212
f48ff2a7 6213 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6214 {
6215 stop_reply_xfree (event);
6216 QUEUE_remove_elem (stop_reply_p, q, iter);
6217 }
6218
6219 return 1;
6220}
6221
f48ff2a7 6222/* Discard all pending stop replies of inferior INF. */
c906108c 6223
74531fed 6224static void
5f4cf0bb 6225discard_pending_stop_replies (struct inferior *inf)
c906108c 6226{
722247f1
YQ
6227 int i;
6228 struct queue_iter_param param;
f48ff2a7
YQ
6229 struct stop_reply *reply;
6230 struct remote_state *rs = get_remote_state ();
6231 struct remote_notif_state *rns = rs->notif_state;
6232
6233 /* This function can be notified when an inferior exists. When the
6234 target is not remote, the notification state is NULL. */
6235 if (rs->remote_desc == NULL)
6236 return;
6237
6238 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6239
74531fed 6240 /* Discard the in-flight notification. */
f48ff2a7 6241 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6242 {
722247f1 6243 stop_reply_xfree (reply);
f48ff2a7 6244 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6245 }
c906108c 6246
722247f1
YQ
6247 param.input = inf;
6248 param.output = NULL;
74531fed
PA
6249 /* Discard the stop replies we have already pulled with
6250 vStopped. */
722247f1 6251 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6252 remove_stop_reply_for_inferior, &param);
6253}
6254
bcc75809
YQ
6255/* If its remote state is equal to the given remote state,
6256 remove EVENT from the stop reply queue. */
6257
6258static int
6259remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6260 QUEUE_ITER (stop_reply_p) *iter,
6261 stop_reply_p event,
6262 void *data)
6263{
19ba03f4
SM
6264 struct queue_iter_param *param = (struct queue_iter_param *) data;
6265 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6266
6267 if (event->rs == rs)
6268 {
6269 stop_reply_xfree (event);
6270 QUEUE_remove_elem (stop_reply_p, q, iter);
6271 }
6272
6273 return 1;
6274}
6275
6276/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6277
6278static void
bcc75809 6279discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6280{
6281 struct queue_iter_param param;
6282
bcc75809 6283 param.input = rs;
f48ff2a7
YQ
6284 param.output = NULL;
6285 /* Discard the stop replies we have already pulled with
6286 vStopped. */
6287 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6288 remove_stop_reply_of_remote_state, &param);
722247f1 6289}
74531fed 6290
722247f1
YQ
6291/* A parameter to pass data in and out. */
6292
6293static int
6294remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6295 QUEUE_ITER (stop_reply_p) *iter,
6296 stop_reply_p event,
6297 void *data)
6298{
19ba03f4
SM
6299 struct queue_iter_param *param = (struct queue_iter_param *) data;
6300 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6301
6302 if (ptid_match (event->ptid, *ptid))
6303 {
6304 param->output = event;
6305 QUEUE_remove_elem (stop_reply_p, q, iter);
6306 return 0;
c8e38a49 6307 }
722247f1
YQ
6308
6309 return 1;
74531fed 6310}
43ff13b4 6311
722247f1
YQ
6312/* Remove the first reply in 'stop_reply_queue' which matches
6313 PTID. */
2e9f7625 6314
722247f1
YQ
6315static struct stop_reply *
6316remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6317{
722247f1
YQ
6318 struct queue_iter_param param;
6319
6320 param.input = &ptid;
6321 param.output = NULL;
6322
6323 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6324 remote_notif_remove_once_on_match, &param);
6325 if (notif_debug)
6326 fprintf_unfiltered (gdb_stdlog,
6327 "notif: discard queued event: 'Stop' in %s\n",
6328 target_pid_to_str (ptid));
a744cf53 6329
722247f1 6330 return param.output;
74531fed 6331}
75c99385 6332
74531fed
PA
6333/* Look for a queued stop reply belonging to PTID. If one is found,
6334 remove it from the queue, and return it. Returns NULL if none is
6335 found. If there are still queued events left to process, tell the
6336 event loop to get back to target_wait soon. */
e24a49d8 6337
74531fed
PA
6338static struct stop_reply *
6339queued_stop_reply (ptid_t ptid)
6340{
722247f1 6341 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6342
722247f1 6343 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6344 /* There's still at least an event left. */
6345 mark_async_event_handler (remote_async_inferior_event_token);
6346
722247f1 6347 return r;
74531fed
PA
6348}
6349
6350/* Push a fully parsed stop reply in the stop reply queue. Since we
6351 know that we now have at least one queued event left to pass to the
6352 core side, tell the event loop to get back to target_wait soon. */
6353
6354static void
6355push_stop_reply (struct stop_reply *new_event)
6356{
722247f1 6357 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6358
722247f1
YQ
6359 if (notif_debug)
6360 fprintf_unfiltered (gdb_stdlog,
6361 "notif: push 'Stop' %s to queue %d\n",
6362 target_pid_to_str (new_event->ptid),
6363 QUEUE_length (stop_reply_p,
6364 stop_reply_queue));
74531fed
PA
6365
6366 mark_async_event_handler (remote_async_inferior_event_token);
6367}
6368
722247f1
YQ
6369static int
6370stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6371 QUEUE_ITER (stop_reply_p) *iter,
6372 struct stop_reply *event,
6373 void *data)
6374{
19ba03f4 6375 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6376
6377 return !(ptid_equal (*ptid, event->ptid)
6378 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6379}
6380
74531fed
PA
6381/* Returns true if we have a stop reply for PTID. */
6382
6383static int
6384peek_stop_reply (ptid_t ptid)
6385{
722247f1
YQ
6386 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6387 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6388}
6389
1f10ba14
PA
6390/* Skip PACKET until the next semi-colon (or end of string). */
6391
6392static char *
6393skip_to_semicolon (char *p)
6394{
6395 while (*p != '\0' && *p != ';')
6396 p++;
6397 return p;
6398}
6399
26d56a93
SL
6400/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6401 starting with P and ending with PEND matches PREFIX. */
6402
6403static int
6404strprefix (const char *p, const char *pend, const char *prefix)
6405{
6406 for ( ; p < pend; p++, prefix++)
6407 if (*p != *prefix)
6408 return 0;
6409 return *prefix == '\0';
6410}
6411
74531fed
PA
6412/* Parse the stop reply in BUF. Either the function succeeds, and the
6413 result is stored in EVENT, or throws an error. */
6414
6415static void
6416remote_parse_stop_reply (char *buf, struct stop_reply *event)
6417{
6418 struct remote_arch_state *rsa = get_remote_arch_state ();
6419 ULONGEST addr;
6420 char *p;
94585166 6421 int skipregs = 0;
74531fed
PA
6422
6423 event->ptid = null_ptid;
bcc75809 6424 event->rs = get_remote_state ();
74531fed
PA
6425 event->ws.kind = TARGET_WAITKIND_IGNORE;
6426 event->ws.value.integer = 0;
f7e6eed5 6427 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6428 event->regcache = NULL;
dc146f7c 6429 event->core = -1;
74531fed
PA
6430
6431 switch (buf[0])
6432 {
6433 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6434 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6435 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6436 ss = signal number
6437 n... = register number
6438 r... = register contents
6439 */
6440
6441 p = &buf[3]; /* after Txx */
6442 while (*p)
6443 {
6444 char *p1;
cea39f65 6445 int fieldsize;
43ff13b4 6446
1f10ba14
PA
6447 p1 = strchr (p, ':');
6448 if (p1 == NULL)
6449 error (_("Malformed packet(a) (missing colon): %s\n\
6450Packet: '%s'\n"),
6451 p, buf);
6452 if (p == p1)
6453 error (_("Malformed packet(a) (missing register number): %s\n\
6454Packet: '%s'\n"),
6455 p, buf);
3c3bea1c 6456
1f10ba14
PA
6457 /* Some "registers" are actually extended stop information.
6458 Note if you're adding a new entry here: GDB 7.9 and
6459 earlier assume that all register "numbers" that start
6460 with an hex digit are real register numbers. Make sure
6461 the server only sends such a packet if it knows the
6462 client understands it. */
c8e38a49 6463
26d56a93 6464 if (strprefix (p, p1, "thread"))
1f10ba14 6465 event->ptid = read_ptid (++p1, &p);
82075af2
JS
6466 else if (strprefix (p, p1, "syscall_entry"))
6467 {
6468 ULONGEST sysno;
6469
6470 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6471 p = unpack_varlen_hex (++p1, &sysno);
6472 event->ws.value.syscall_number = (int) sysno;
6473 }
6474 else if (strprefix (p, p1, "syscall_return"))
6475 {
6476 ULONGEST sysno;
6477
6478 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6479 p = unpack_varlen_hex (++p1, &sysno);
6480 event->ws.value.syscall_number = (int) sysno;
6481 }
26d56a93
SL
6482 else if (strprefix (p, p1, "watch")
6483 || strprefix (p, p1, "rwatch")
6484 || strprefix (p, p1, "awatch"))
cea39f65 6485 {
f7e6eed5 6486 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6487 p = unpack_varlen_hex (++p1, &addr);
6488 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6489 }
26d56a93 6490 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6491 {
6492 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6493
6494 /* Make sure the stub doesn't forget to indicate support
6495 with qSupported. */
6496 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6497 error (_("Unexpected swbreak stop reason"));
6498
6499 /* The value part is documented as "must be empty",
6500 though we ignore it, in case we ever decide to make
6501 use of it in a backward compatible way. */
6502 p = skip_to_semicolon (p1 + 1);
6503 }
26d56a93 6504 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6505 {
6506 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6507
6508 /* Make sure the stub doesn't forget to indicate support
6509 with qSupported. */
6510 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6511 error (_("Unexpected hwbreak stop reason"));
6512
6513 /* See above. */
6514 p = skip_to_semicolon (p1 + 1);
6515 }
26d56a93 6516 else if (strprefix (p, p1, "library"))
cea39f65 6517 {
1f10ba14
PA
6518 event->ws.kind = TARGET_WAITKIND_LOADED;
6519 p = skip_to_semicolon (p1 + 1);
6520 }
26d56a93 6521 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6522 {
6523 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6524 /* p1 will indicate "begin" or "end", but it makes
6525 no difference for now, so ignore it. */
6526 p = skip_to_semicolon (p1 + 1);
6527 }
26d56a93 6528 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6529 {
6530 ULONGEST c;
a744cf53 6531
1f10ba14
PA
6532 p = unpack_varlen_hex (++p1, &c);
6533 event->core = c;
cea39f65 6534 }
26d56a93 6535 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6536 {
6537 event->ws.value.related_pid = read_ptid (++p1, &p);
6538 event->ws.kind = TARGET_WAITKIND_FORKED;
6539 }
26d56a93 6540 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6541 {
6542 event->ws.value.related_pid = read_ptid (++p1, &p);
6543 event->ws.kind = TARGET_WAITKIND_VFORKED;
6544 }
26d56a93 6545 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6546 {
6547 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6548 p = skip_to_semicolon (p1 + 1);
6549 }
6ab24463 6550 else if (strprefix (p, p1, "exec"))
94585166
DB
6551 {
6552 ULONGEST ignored;
6553 char pathname[PATH_MAX];
6554 int pathlen;
6555
6556 /* Determine the length of the execd pathname. */
6557 p = unpack_varlen_hex (++p1, &ignored);
6558 pathlen = (p - p1) / 2;
6559
6560 /* Save the pathname for event reporting and for
6561 the next run command. */
6562 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6563 pathname[pathlen] = '\0';
6564
6565 /* This is freed during event handling. */
6566 event->ws.value.execd_pathname = xstrdup (pathname);
6567 event->ws.kind = TARGET_WAITKIND_EXECD;
6568
6569 /* Skip the registers included in this packet, since
6570 they may be for an architecture different from the
6571 one used by the original program. */
6572 skipregs = 1;
6573 }
65706a29
PA
6574 else if (strprefix (p, p1, "create"))
6575 {
6576 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6577 p = skip_to_semicolon (p1 + 1);
6578 }
cea39f65
MS
6579 else
6580 {
1f10ba14
PA
6581 ULONGEST pnum;
6582 char *p_temp;
6583
94585166
DB
6584 if (skipregs)
6585 {
6586 p = skip_to_semicolon (p1 + 1);
6587 p++;
6588 continue;
6589 }
6590
1f10ba14
PA
6591 /* Maybe a real ``P'' register number. */
6592 p_temp = unpack_varlen_hex (p, &pnum);
6593 /* If the first invalid character is the colon, we got a
6594 register number. Otherwise, it's an unknown stop
6595 reason. */
6596 if (p_temp == p1)
6597 {
6598 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6599 cached_reg_t cached_reg;
43ff13b4 6600
1f10ba14
PA
6601 if (reg == NULL)
6602 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6603Packet: '%s'\n"),
1f10ba14 6604 hex_string (pnum), p, buf);
c8e38a49 6605
1f10ba14 6606 cached_reg.num = reg->regnum;
4100683b 6607
1f10ba14
PA
6608 p = p1 + 1;
6609 fieldsize = hex2bin (p, cached_reg.data,
6610 register_size (target_gdbarch (),
6611 reg->regnum));
6612 p += 2 * fieldsize;
6613 if (fieldsize < register_size (target_gdbarch (),
6614 reg->regnum))
6615 warning (_("Remote reply is too short: %s"), buf);
74531fed 6616
1f10ba14
PA
6617 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6618 }
6619 else
6620 {
6621 /* Not a number. Silently skip unknown optional
6622 info. */
6623 p = skip_to_semicolon (p1 + 1);
6624 }
cea39f65 6625 }
c8e38a49 6626
cea39f65
MS
6627 if (*p != ';')
6628 error (_("Remote register badly formatted: %s\nhere: %s"),
6629 buf, p);
6630 ++p;
6631 }
5b5596ff
PA
6632
6633 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6634 break;
6635
c8e38a49
PA
6636 /* fall through */
6637 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6638 {
6639 int sig;
6640
6641 event->ws.kind = TARGET_WAITKIND_STOPPED;
6642 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6643 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6644 event->ws.value.sig = (enum gdb_signal) sig;
6645 else
6646 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6647 }
c8e38a49 6648 break;
65706a29
PA
6649 case 'w': /* Thread exited. */
6650 {
6651 char *p;
6652 ULONGEST value;
6653
6654 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6655 p = unpack_varlen_hex (&buf[1], &value);
6656 event->ws.value.integer = value;
6657 if (*p != ';')
6658 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 6659 event->ptid = read_ptid (++p, NULL);
65706a29
PA
6660 break;
6661 }
c8e38a49
PA
6662 case 'W': /* Target exited. */
6663 case 'X':
6664 {
6665 char *p;
6666 int pid;
6667 ULONGEST value;
82f73884 6668
c8e38a49
PA
6669 /* GDB used to accept only 2 hex chars here. Stubs should
6670 only send more if they detect GDB supports multi-process
6671 support. */
6672 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6673
c8e38a49
PA
6674 if (buf[0] == 'W')
6675 {
6676 /* The remote process exited. */
74531fed
PA
6677 event->ws.kind = TARGET_WAITKIND_EXITED;
6678 event->ws.value.integer = value;
c8e38a49
PA
6679 }
6680 else
6681 {
6682 /* The remote process exited with a signal. */
74531fed 6683 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6684 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6685 event->ws.value.sig = (enum gdb_signal) value;
6686 else
6687 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6688 }
82f73884 6689
c8e38a49
PA
6690 /* If no process is specified, assume inferior_ptid. */
6691 pid = ptid_get_pid (inferior_ptid);
6692 if (*p == '\0')
6693 ;
6694 else if (*p == ';')
6695 {
6696 p++;
6697
0b24eb2d 6698 if (*p == '\0')
82f73884 6699 ;
61012eef 6700 else if (startswith (p, "process:"))
82f73884 6701 {
c8e38a49 6702 ULONGEST upid;
a744cf53 6703
c8e38a49
PA
6704 p += sizeof ("process:") - 1;
6705 unpack_varlen_hex (p, &upid);
6706 pid = upid;
82f73884
PA
6707 }
6708 else
6709 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6710 }
c8e38a49
PA
6711 else
6712 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6713 event->ptid = pid_to_ptid (pid);
6714 }
6715 break;
f2faf941
PA
6716 case 'N':
6717 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6718 event->ptid = minus_one_ptid;
6719 break;
74531fed
PA
6720 }
6721
6efcd9a8 6722 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
6723 error (_("No process or thread specified in stop reply: %s"), buf);
6724}
6725
722247f1
YQ
6726/* When the stub wants to tell GDB about a new notification reply, it
6727 sends a notification (%Stop, for example). Those can come it at
6728 any time, hence, we have to make sure that any pending
6729 putpkt/getpkt sequence we're making is finished, before querying
6730 the stub for more events with the corresponding ack command
6731 (vStopped, for example). E.g., if we started a vStopped sequence
6732 immediately upon receiving the notification, something like this
6733 could happen:
74531fed
PA
6734
6735 1.1) --> Hg 1
6736 1.2) <-- OK
6737 1.3) --> g
6738 1.4) <-- %Stop
6739 1.5) --> vStopped
6740 1.6) <-- (registers reply to step #1.3)
6741
6742 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6743 query.
6744
796cb314 6745 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6746 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6747 doing whatever we were doing:
6748
6749 2.1) --> Hg 1
6750 2.2) <-- OK
6751 2.3) --> g
6752 2.4) <-- %Stop
6753 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6754 2.5) <-- (registers reply to step #2.3)
6755
6756 Eventualy after step #2.5, we return to the event loop, which
6757 notices there's an event on the
6758 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6759 associated callback --- the function below. At this point, we're
6760 always safe to start a vStopped sequence. :
6761
6762 2.6) --> vStopped
6763 2.7) <-- T05 thread:2
6764 2.8) --> vStopped
6765 2.9) --> OK
6766*/
6767
722247f1
YQ
6768void
6769remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6770{
6771 struct remote_state *rs = get_remote_state ();
74531fed 6772
f48ff2a7 6773 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6774 {
722247f1
YQ
6775 if (notif_debug)
6776 fprintf_unfiltered (gdb_stdlog,
6777 "notif: process: '%s' ack pending event\n",
6778 nc->name);
74531fed 6779
722247f1 6780 /* acknowledge */
f48ff2a7
YQ
6781 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6782 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6783
6784 while (1)
6785 {
6786 getpkt (&rs->buf, &rs->buf_size, 0);
6787 if (strcmp (rs->buf, "OK") == 0)
6788 break;
6789 else
722247f1 6790 remote_notif_ack (nc, rs->buf);
74531fed
PA
6791 }
6792 }
722247f1
YQ
6793 else
6794 {
6795 if (notif_debug)
6796 fprintf_unfiltered (gdb_stdlog,
6797 "notif: process: '%s' no pending reply\n",
6798 nc->name);
6799 }
74531fed
PA
6800}
6801
74531fed
PA
6802/* Called when it is decided that STOP_REPLY holds the info of the
6803 event that is to be returned to the core. This function always
6804 destroys STOP_REPLY. */
6805
6806static ptid_t
6807process_stop_reply (struct stop_reply *stop_reply,
6808 struct target_waitstatus *status)
6809{
6810 ptid_t ptid;
6811
6812 *status = stop_reply->ws;
6813 ptid = stop_reply->ptid;
6814
6815 /* If no thread/process was reported by the stub, assume the current
6816 inferior. */
6817 if (ptid_equal (ptid, null_ptid))
6818 ptid = inferior_ptid;
6819
5f3563ea 6820 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
6821 && status->kind != TARGET_WAITKIND_SIGNALLED
6822 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 6823 {
ee154bee 6824 struct remote_state *rs = get_remote_state ();
799a2abe 6825 struct private_thread_info *remote_thr;
ee154bee 6826
5f3563ea
PA
6827 /* Expedited registers. */
6828 if (stop_reply->regcache)
6829 {
217f1f79 6830 struct regcache *regcache
f5656ead 6831 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6832 cached_reg_t *reg;
6833 int ix;
6834
6835 for (ix = 0;
6836 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6837 ix++)
217f1f79 6838 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6839 VEC_free (cached_reg_t, stop_reply->regcache);
6840 }
74531fed 6841
1941c569 6842 remote_notice_new_inferior (ptid, 0);
799a2abe
PA
6843 remote_thr = demand_private_info (ptid);
6844 remote_thr->core = stop_reply->core;
6845 remote_thr->stop_reason = stop_reply->stop_reason;
6846 remote_thr->watch_data_address = stop_reply->watch_data_address;
74531fed
PA
6847 }
6848
74531fed
PA
6849 stop_reply_xfree (stop_reply);
6850 return ptid;
6851}
6852
6853/* The non-stop mode version of target_wait. */
6854
6855static ptid_t
47608cb1 6856remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6857{
6858 struct remote_state *rs = get_remote_state ();
74531fed
PA
6859 struct stop_reply *stop_reply;
6860 int ret;
fee9eda9 6861 int is_notif = 0;
74531fed
PA
6862
6863 /* If in non-stop mode, get out of getpkt even if a
6864 notification is received. */
6865
6866 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6867 0 /* forever */, &is_notif);
74531fed
PA
6868 while (1)
6869 {
fee9eda9 6870 if (ret != -1 && !is_notif)
74531fed
PA
6871 switch (rs->buf[0])
6872 {
6873 case 'E': /* Error of some sort. */
6874 /* We're out of sync with the target now. Did it continue
6875 or not? We can't tell which thread it was in non-stop,
6876 so just ignore this. */
6877 warning (_("Remote failure reply: %s"), rs->buf);
6878 break;
6879 case 'O': /* Console output. */
6880 remote_console_output (rs->buf + 1);
6881 break;
6882 default:
6883 warning (_("Invalid remote reply: %s"), rs->buf);
6884 break;
6885 }
6886
6887 /* Acknowledge a pending stop reply that may have arrived in the
6888 mean time. */
f48ff2a7 6889 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6890 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6891
6892 /* If indeed we noticed a stop reply, we're done. */
6893 stop_reply = queued_stop_reply (ptid);
6894 if (stop_reply != NULL)
6895 return process_stop_reply (stop_reply, status);
6896
47608cb1 6897 /* Still no event. If we're just polling for an event, then
74531fed 6898 return to the event loop. */
47608cb1 6899 if (options & TARGET_WNOHANG)
74531fed
PA
6900 {
6901 status->kind = TARGET_WAITKIND_IGNORE;
6902 return minus_one_ptid;
6903 }
6904
47608cb1 6905 /* Otherwise do a blocking wait. */
74531fed 6906 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6907 1 /* forever */, &is_notif);
74531fed
PA
6908 }
6909}
6910
6911/* Wait until the remote machine stops, then return, storing status in
6912 STATUS just as `wait' would. */
6913
6914static ptid_t
47608cb1 6915remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6916{
6917 struct remote_state *rs = get_remote_state ();
74531fed 6918 ptid_t event_ptid = null_ptid;
cea39f65 6919 char *buf;
74531fed
PA
6920 struct stop_reply *stop_reply;
6921
47608cb1
PA
6922 again:
6923
74531fed
PA
6924 status->kind = TARGET_WAITKIND_IGNORE;
6925 status->value.integer = 0;
6926
6927 stop_reply = queued_stop_reply (ptid);
6928 if (stop_reply != NULL)
6929 return process_stop_reply (stop_reply, status);
6930
6931 if (rs->cached_wait_status)
6932 /* Use the cached wait status, but only once. */
6933 rs->cached_wait_status = 0;
6934 else
6935 {
6936 int ret;
722247f1 6937 int is_notif;
567420d1
PA
6938 int forever = ((options & TARGET_WNOHANG) == 0
6939 && wait_forever_enabled_p);
6940
6941 if (!rs->waiting_for_stop_reply)
6942 {
6943 status->kind = TARGET_WAITKIND_NO_RESUMED;
6944 return minus_one_ptid;
6945 }
74531fed
PA
6946
6947 if (!target_is_async_p ())
6948 {
934b9bac 6949 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6950 /* If the user hit C-c before this packet, or between packets,
6951 pretend that it was hit right here. */
522002f9 6952 if (check_quit_flag ())
74531fed 6953 {
522002f9 6954 clear_quit_flag ();
934b9bac 6955 sync_remote_interrupt (SIGINT);
74531fed
PA
6956 }
6957 }
6958
6959 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6960 _never_ wait for ever -> test on target_is_async_p().
6961 However, before we do that we need to ensure that the caller
6962 knows how to take the target into/out of async mode. */
722247f1 6963 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6964 forever, &is_notif);
722247f1 6965
5e1b953b
SDJ
6966 if (!target_is_async_p ())
6967 signal (SIGINT, ofunc);
6968
722247f1
YQ
6969 /* GDB gets a notification. Return to core as this event is
6970 not interesting. */
6971 if (ret != -1 && is_notif)
6972 return minus_one_ptid;
567420d1
PA
6973
6974 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6975 return minus_one_ptid;
74531fed
PA
6976 }
6977
6978 buf = rs->buf;
6979
3a29589a
DJ
6980 /* Assume that the target has acknowledged Ctrl-C unless we receive
6981 an 'F' or 'O' packet. */
6982 if (buf[0] != 'F' && buf[0] != 'O')
6983 rs->ctrlc_pending_p = 0;
6984
74531fed
PA
6985 switch (buf[0])
6986 {
6987 case 'E': /* Error of some sort. */
6988 /* We're out of sync with the target now. Did it continue or
6989 not? Not is more likely, so report a stop. */
29090fb6
LM
6990 rs->waiting_for_stop_reply = 0;
6991
74531fed
PA
6992 warning (_("Remote failure reply: %s"), buf);
6993 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6994 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6995 break;
6996 case 'F': /* File-I/O request. */
3a29589a
DJ
6997 remote_fileio_request (buf, rs->ctrlc_pending_p);
6998 rs->ctrlc_pending_p = 0;
74531fed 6999 break;
f2faf941 7000 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 7001 {
29090fb6
LM
7002 struct stop_reply *stop_reply;
7003
7004 /* There is a stop reply to handle. */
7005 rs->waiting_for_stop_reply = 0;
7006
7007 stop_reply
722247f1
YQ
7008 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7009 rs->buf);
74531fed 7010
74531fed 7011 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
7012 break;
7013 }
7014 case 'O': /* Console output. */
7015 remote_console_output (buf + 1);
c8e38a49
PA
7016 break;
7017 case '\0':
b73be471 7018 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
7019 {
7020 /* Zero length reply means that we tried 'S' or 'C' and the
7021 remote system doesn't support it. */
7022 target_terminal_ours_for_output ();
7023 printf_filtered
7024 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
7025 gdb_signal_to_name (rs->last_sent_signal));
7026 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
7027 target_terminal_inferior ();
7028
280ceea3 7029 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49 7030 putpkt ((char *) buf);
c8e38a49 7031 break;
43ff13b4 7032 }
c8e38a49
PA
7033 /* else fallthrough */
7034 default:
7035 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 7036 break;
43ff13b4 7037 }
c8e38a49 7038
f2faf941
PA
7039 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7040 return minus_one_ptid;
7041 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
7042 {
7043 /* Nothing interesting happened. If we're doing a non-blocking
7044 poll, we're done. Otherwise, go back to waiting. */
7045 if (options & TARGET_WNOHANG)
7046 return minus_one_ptid;
7047 else
7048 goto again;
7049 }
74531fed
PA
7050 else if (status->kind != TARGET_WAITKIND_EXITED
7051 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
7052 {
7053 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 7054 record_currthread (rs, event_ptid);
82f73884
PA
7055 else
7056 event_ptid = inferior_ptid;
43ff13b4 7057 }
74531fed
PA
7058 else
7059 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 7060 record_currthread (rs, minus_one_ptid);
79d7f229 7061
82f73884 7062 return event_ptid;
43ff13b4
JM
7063}
7064
74531fed
PA
7065/* Wait until the remote machine stops, then return, storing status in
7066 STATUS just as `wait' would. */
7067
c8e38a49 7068static ptid_t
117de6a9 7069remote_wait (struct target_ops *ops,
47608cb1 7070 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7071{
7072 ptid_t event_ptid;
7073
6efcd9a8 7074 if (target_is_non_stop_p ())
47608cb1 7075 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7076 else
47608cb1 7077 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7078
d9d41e78 7079 if (target_is_async_p ())
c8e38a49 7080 {
74531fed
PA
7081 /* If there are are events left in the queue tell the event loop
7082 to return here. */
722247f1 7083 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7084 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7085 }
c8e38a49
PA
7086
7087 return event_ptid;
7088}
7089
74ca34ce 7090/* Fetch a single register using a 'p' packet. */
c906108c 7091
b96ec7ac 7092static int
56be3814 7093fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
7094{
7095 struct remote_state *rs = get_remote_state ();
2e9f7625 7096 char *buf, *p;
b96ec7ac
AC
7097 char regp[MAX_REGISTER_SIZE];
7098 int i;
7099
4082afcc 7100 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7101 return 0;
7102
7103 if (reg->pnum == -1)
7104 return 0;
7105
2e9f7625 7106 p = rs->buf;
fcad0fa4 7107 *p++ = 'p';
74ca34ce 7108 p += hexnumstr (p, reg->pnum);
fcad0fa4 7109 *p++ = '\0';
1f4437a4
MS
7110 putpkt (rs->buf);
7111 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7112
2e9f7625
DJ
7113 buf = rs->buf;
7114
74ca34ce
DJ
7115 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7116 {
7117 case PACKET_OK:
7118 break;
7119 case PACKET_UNKNOWN:
7120 return 0;
7121 case PACKET_ERROR:
27a9c0bf
MS
7122 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7123 gdbarch_register_name (get_regcache_arch (regcache),
7124 reg->regnum),
7125 buf);
74ca34ce 7126 }
3f9a994c
JB
7127
7128 /* If this register is unfetchable, tell the regcache. */
7129 if (buf[0] == 'x')
8480adf2 7130 {
56be3814 7131 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7132 return 1;
b96ec7ac 7133 }
b96ec7ac 7134
3f9a994c
JB
7135 /* Otherwise, parse and supply the value. */
7136 p = buf;
7137 i = 0;
7138 while (p[0] != 0)
7139 {
7140 if (p[1] == 0)
74ca34ce 7141 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7142
7143 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7144 p += 2;
7145 }
56be3814 7146 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7147 return 1;
b96ec7ac
AC
7148}
7149
74ca34ce
DJ
7150/* Fetch the registers included in the target's 'g' packet. */
7151
29709017
DJ
7152static int
7153send_g_packet (void)
c906108c 7154{
d01949b6 7155 struct remote_state *rs = get_remote_state ();
cea39f65 7156 int buf_len;
c906108c 7157
bba74b36 7158 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7159 remote_send (&rs->buf, &rs->buf_size);
c906108c 7160
29709017
DJ
7161 /* We can get out of synch in various cases. If the first character
7162 in the buffer is not a hex character, assume that has happened
7163 and try to fetch another packet to read. */
7164 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7165 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7166 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7167 && rs->buf[0] != 'x') /* New: unavailable register value. */
7168 {
7169 if (remote_debug)
7170 fprintf_unfiltered (gdb_stdlog,
7171 "Bad register packet; fetching a new packet\n");
7172 getpkt (&rs->buf, &rs->buf_size, 0);
7173 }
7174
74ca34ce
DJ
7175 buf_len = strlen (rs->buf);
7176
7177 /* Sanity check the received packet. */
7178 if (buf_len % 2 != 0)
7179 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7180
7181 return buf_len / 2;
7182}
7183
7184static void
56be3814 7185process_g_packet (struct regcache *regcache)
29709017 7186{
4a22f64d 7187 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7188 struct remote_state *rs = get_remote_state ();
7189 struct remote_arch_state *rsa = get_remote_arch_state ();
7190 int i, buf_len;
7191 char *p;
7192 char *regs;
7193
7194 buf_len = strlen (rs->buf);
7195
7196 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7197 if (buf_len > 2 * rsa->sizeof_g_packet)
7198 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7199
7200 /* Save the size of the packet sent to us by the target. It is used
7201 as a heuristic when determining the max size of packets that the
7202 target can safely receive. */
7203 if (rsa->actual_register_packet_size == 0)
7204 rsa->actual_register_packet_size = buf_len;
7205
7206 /* If this is smaller than we guessed the 'g' packet would be,
7207 update our records. A 'g' reply that doesn't include a register's
7208 value implies either that the register is not available, or that
7209 the 'p' packet must be used. */
7210 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7211 {
74ca34ce
DJ
7212 rsa->sizeof_g_packet = buf_len / 2;
7213
4a22f64d 7214 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7215 {
74ca34ce
DJ
7216 if (rsa->regs[i].pnum == -1)
7217 continue;
7218
7219 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7220 rsa->regs[i].in_g_packet = 0;
b96ec7ac 7221 else
74ca34ce 7222 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7223 }
74ca34ce 7224 }
b323314b 7225
224c3ddb 7226 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7227
7228 /* Unimplemented registers read as all bits zero. */
ea9c271d 7229 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7230
c906108c
SS
7231 /* Reply describes registers byte by byte, each byte encoded as two
7232 hex characters. Suck them all up, then supply them to the
7233 register cacheing/storage mechanism. */
7234
74ca34ce 7235 p = rs->buf;
ea9c271d 7236 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7237 {
74ca34ce
DJ
7238 if (p[0] == 0 || p[1] == 0)
7239 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7240 internal_error (__FILE__, __LINE__,
9b20d036 7241 _("unexpected end of 'g' packet reply"));
74ca34ce 7242
c906108c 7243 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7244 regs[i] = 0; /* 'x' */
c906108c
SS
7245 else
7246 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7247 p += 2;
7248 }
7249
a744cf53
MS
7250 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7251 {
7252 struct packet_reg *r = &rsa->regs[i];
7253
7254 if (r->in_g_packet)
7255 {
7256 if (r->offset * 2 >= strlen (rs->buf))
7257 /* This shouldn't happen - we adjusted in_g_packet above. */
7258 internal_error (__FILE__, __LINE__,
9b20d036 7259 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7260 else if (rs->buf[r->offset * 2] == 'x')
7261 {
7262 gdb_assert (r->offset * 2 < strlen (rs->buf));
7263 /* The register isn't available, mark it as such (at
7264 the same time setting the value to zero). */
7265 regcache_raw_supply (regcache, r->regnum, NULL);
7266 }
7267 else
7268 regcache_raw_supply (regcache, r->regnum,
7269 regs + r->offset);
7270 }
7271 }
c906108c
SS
7272}
7273
29709017 7274static void
56be3814 7275fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7276{
7277 send_g_packet ();
56be3814 7278 process_g_packet (regcache);
29709017
DJ
7279}
7280
e6e4e701
PA
7281/* Make the remote selected traceframe match GDB's selected
7282 traceframe. */
7283
7284static void
7285set_remote_traceframe (void)
7286{
7287 int newnum;
262e1174 7288 struct remote_state *rs = get_remote_state ();
e6e4e701 7289
262e1174 7290 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7291 return;
7292
7293 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7294 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7295
7296 newnum = target_trace_find (tfind_number,
7297 get_traceframe_number (), 0, 0, NULL);
7298
7299 /* Should not happen. If it does, all bets are off. */
7300 if (newnum != get_traceframe_number ())
7301 warning (_("could not set remote traceframe"));
7302}
7303
74ca34ce 7304static void
28439f5e
PA
7305remote_fetch_registers (struct target_ops *ops,
7306 struct regcache *regcache, int regnum)
74ca34ce 7307{
74ca34ce
DJ
7308 struct remote_arch_state *rsa = get_remote_arch_state ();
7309 int i;
7310
e6e4e701 7311 set_remote_traceframe ();
79d7f229 7312 set_general_thread (inferior_ptid);
74ca34ce
DJ
7313
7314 if (regnum >= 0)
7315 {
7316 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7317
74ca34ce
DJ
7318 gdb_assert (reg != NULL);
7319
7320 /* If this register might be in the 'g' packet, try that first -
7321 we are likely to read more than one register. If this is the
7322 first 'g' packet, we might be overly optimistic about its
7323 contents, so fall back to 'p'. */
7324 if (reg->in_g_packet)
7325 {
56be3814 7326 fetch_registers_using_g (regcache);
74ca34ce
DJ
7327 if (reg->in_g_packet)
7328 return;
7329 }
7330
56be3814 7331 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7332 return;
7333
7334 /* This register is not available. */
56be3814 7335 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7336
7337 return;
7338 }
7339
56be3814 7340 fetch_registers_using_g (regcache);
74ca34ce 7341
4a22f64d 7342 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7343 if (!rsa->regs[i].in_g_packet)
56be3814 7344 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7345 {
7346 /* This register is not available. */
56be3814 7347 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7348 }
7349}
7350
c906108c
SS
7351/* Prepare to store registers. Since we may send them all (using a
7352 'G' request), we have to read out the ones we don't want to change
7353 first. */
7354
c5aa993b 7355static void
f32dbf8c 7356remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7357{
ea9c271d 7358 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7359 int i;
cfd77fa1 7360 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7361
c906108c 7362 /* Make sure the entire registers array is valid. */
4082afcc 7363 switch (packet_support (PACKET_P))
5a2468f5
JM
7364 {
7365 case PACKET_DISABLE:
7366 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7367 /* Make sure all the necessary registers are cached. */
4a22f64d 7368 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7369 if (rsa->regs[i].in_g_packet)
316f2060 7370 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7371 break;
7372 case PACKET_ENABLE:
7373 break;
7374 }
7375}
7376
ad10f812 7377/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7378 packet was not recognized. */
5a2468f5
JM
7379
7380static int
1f4437a4
MS
7381store_register_using_P (const struct regcache *regcache,
7382 struct packet_reg *reg)
5a2468f5 7383{
4a22f64d 7384 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7385 struct remote_state *rs = get_remote_state ();
5a2468f5 7386 /* Try storing a single register. */
6d820c5c 7387 char *buf = rs->buf;
cfd77fa1 7388 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7389 char *p;
5a2468f5 7390
4082afcc 7391 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7392 return 0;
7393
7394 if (reg->pnum == -1)
7395 return 0;
7396
ea9c271d 7397 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7398 p = buf + strlen (buf);
56be3814 7399 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7400 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7401 putpkt (rs->buf);
7402 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7403
74ca34ce
DJ
7404 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7405 {
7406 case PACKET_OK:
7407 return 1;
7408 case PACKET_ERROR:
27a9c0bf
MS
7409 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7410 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7411 case PACKET_UNKNOWN:
7412 return 0;
7413 default:
7414 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7415 }
c906108c
SS
7416}
7417
23860348
MS
7418/* Store register REGNUM, or all registers if REGNUM == -1, from the
7419 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7420
7421static void
56be3814 7422store_registers_using_G (const struct regcache *regcache)
c906108c 7423{
d01949b6 7424 struct remote_state *rs = get_remote_state ();
ea9c271d 7425 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7426 gdb_byte *regs;
c906108c
SS
7427 char *p;
7428
193cb69f
AC
7429 /* Extract all the registers in the regcache copying them into a
7430 local buffer. */
7431 {
b323314b 7432 int i;
a744cf53 7433
224c3ddb 7434 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7435 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7436 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7437 {
ea9c271d 7438 struct packet_reg *r = &rsa->regs[i];
a744cf53 7439
b323314b 7440 if (r->in_g_packet)
56be3814 7441 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7442 }
7443 }
c906108c
SS
7444
7445 /* Command describes registers byte by byte,
7446 each byte encoded as two hex characters. */
6d820c5c 7447 p = rs->buf;
193cb69f 7448 *p++ = 'G';
74ca34ce
DJ
7449 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7450 updated. */
7451 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7452 putpkt (rs->buf);
7453 getpkt (&rs->buf, &rs->buf_size, 0);
7454 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7455 error (_("Could not write registers; remote failure reply '%s'"),
7456 rs->buf);
c906108c 7457}
74ca34ce
DJ
7458
7459/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7460 of the register cache buffer. FIXME: ignores errors. */
7461
7462static void
28439f5e
PA
7463remote_store_registers (struct target_ops *ops,
7464 struct regcache *regcache, int regnum)
74ca34ce 7465{
74ca34ce
DJ
7466 struct remote_arch_state *rsa = get_remote_arch_state ();
7467 int i;
7468
e6e4e701 7469 set_remote_traceframe ();
79d7f229 7470 set_general_thread (inferior_ptid);
74ca34ce
DJ
7471
7472 if (regnum >= 0)
7473 {
7474 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7475
74ca34ce
DJ
7476 gdb_assert (reg != NULL);
7477
7478 /* Always prefer to store registers using the 'P' packet if
7479 possible; we often change only a small number of registers.
7480 Sometimes we change a larger number; we'd need help from a
7481 higher layer to know to use 'G'. */
56be3814 7482 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7483 return;
7484
7485 /* For now, don't complain if we have no way to write the
7486 register. GDB loses track of unavailable registers too
7487 easily. Some day, this may be an error. We don't have
0df8b418 7488 any way to read the register, either... */
74ca34ce
DJ
7489 if (!reg->in_g_packet)
7490 return;
7491
56be3814 7492 store_registers_using_G (regcache);
74ca34ce
DJ
7493 return;
7494 }
7495
56be3814 7496 store_registers_using_G (regcache);
74ca34ce 7497
4a22f64d 7498 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7499 if (!rsa->regs[i].in_g_packet)
56be3814 7500 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7501 /* See above for why we do not issue an error here. */
7502 continue;
7503}
c906108c
SS
7504\f
7505
7506/* Return the number of hex digits in num. */
7507
7508static int
fba45db2 7509hexnumlen (ULONGEST num)
c906108c
SS
7510{
7511 int i;
7512
7513 for (i = 0; num != 0; i++)
7514 num >>= 4;
7515
7516 return max (i, 1);
7517}
7518
2df3850c 7519/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7520
7521static int
fba45db2 7522hexnumstr (char *buf, ULONGEST num)
c906108c 7523{
c906108c 7524 int len = hexnumlen (num);
a744cf53 7525
2df3850c
JM
7526 return hexnumnstr (buf, num, len);
7527}
7528
c906108c 7529
2df3850c 7530/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7531
2df3850c 7532static int
fba45db2 7533hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7534{
7535 int i;
7536
7537 buf[width] = '\0';
7538
7539 for (i = width - 1; i >= 0; i--)
c906108c 7540 {
c5aa993b 7541 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7542 num >>= 4;
7543 }
7544
2df3850c 7545 return width;
c906108c
SS
7546}
7547
23860348 7548/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7549
7550static CORE_ADDR
fba45db2 7551remote_address_masked (CORE_ADDR addr)
c906108c 7552{
883b9c6c 7553 unsigned int address_size = remote_address_size;
a744cf53 7554
911c95a5
UW
7555 /* If "remoteaddresssize" was not set, default to target address size. */
7556 if (!address_size)
f5656ead 7557 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7558
7559 if (address_size > 0
7560 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7561 {
7562 /* Only create a mask when that mask can safely be constructed
23860348 7563 in a ULONGEST variable. */
c906108c 7564 ULONGEST mask = 1;
a744cf53 7565
911c95a5 7566 mask = (mask << address_size) - 1;
c906108c
SS
7567 addr &= mask;
7568 }
7569 return addr;
7570}
7571
7572/* Determine whether the remote target supports binary downloading.
7573 This is accomplished by sending a no-op memory write of zero length
7574 to the target at the specified address. It does not suffice to send
23860348
MS
7575 the whole packet, since many stubs strip the eighth bit and
7576 subsequently compute a wrong checksum, which causes real havoc with
7577 remote_write_bytes.
7a292a7a 7578
96baa820 7579 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7580 clean. In cases like this, the user should clear "remote
23860348 7581 X-packet". */
96baa820 7582
c906108c 7583static void
fba45db2 7584check_binary_download (CORE_ADDR addr)
c906108c 7585{
d01949b6 7586 struct remote_state *rs = get_remote_state ();
24b06219 7587
4082afcc 7588 switch (packet_support (PACKET_X))
c906108c 7589 {
96baa820
JM
7590 case PACKET_DISABLE:
7591 break;
7592 case PACKET_ENABLE:
7593 break;
7594 case PACKET_SUPPORT_UNKNOWN:
7595 {
96baa820 7596 char *p;
802188a7 7597
2e9f7625 7598 p = rs->buf;
96baa820
JM
7599 *p++ = 'X';
7600 p += hexnumstr (p, (ULONGEST) addr);
7601 *p++ = ',';
7602 p += hexnumstr (p, (ULONGEST) 0);
7603 *p++ = ':';
7604 *p = '\0';
802188a7 7605
2e9f7625 7606 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7607 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7608
2e9f7625 7609 if (rs->buf[0] == '\0')
96baa820
JM
7610 {
7611 if (remote_debug)
7612 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7613 "binary downloading NOT "
7614 "supported by target\n");
444abaca 7615 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7616 }
7617 else
7618 {
7619 if (remote_debug)
7620 fprintf_unfiltered (gdb_stdlog,
64b9b334 7621 "binary downloading supported by target\n");
444abaca 7622 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7623 }
7624 break;
7625 }
c906108c
SS
7626 }
7627}
7628
124e13d9
SM
7629/* Helper function to resize the payload in order to try to get a good
7630 alignment. We try to write an amount of data such that the next write will
7631 start on an address aligned on REMOTE_ALIGN_WRITES. */
7632
7633static int
7634align_for_efficient_write (int todo, CORE_ADDR memaddr)
7635{
7636 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7637}
7638
c906108c
SS
7639/* Write memory data directly to the remote machine.
7640 This does not inform the data cache; the data cache uses this.
a76d924d 7641 HEADER is the starting part of the packet.
c906108c
SS
7642 MEMADDR is the address in the remote memory space.
7643 MYADDR is the address of the buffer in our space.
124e13d9
SM
7644 LEN_UNITS is the number of addressable units to write.
7645 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7646 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7647 should send data as binary ('X'), or hex-encoded ('M').
7648
7649 The function creates packet of the form
7650 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7651
124e13d9 7652 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7653
7654 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7655 are omitted.
7656
9b409511 7657 Return the transferred status, error or OK (an
124e13d9
SM
7658 'enum target_xfer_status' value). Save the number of addressable units
7659 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7660
7661 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7662 exchange between gdb and the stub could look like (?? in place of the
7663 checksum):
7664
7665 -> $m1000,4#??
7666 <- aaaabbbbccccdddd
7667
7668 -> $M1000,3:eeeeffffeeee#??
7669 <- OK
7670
7671 -> $m1000,4#??
7672 <- eeeeffffeeeedddd */
c906108c 7673
9b409511 7674static enum target_xfer_status
a76d924d 7675remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7676 const gdb_byte *myaddr, ULONGEST len_units,
7677 int unit_size, ULONGEST *xfered_len_units,
7678 char packet_format, int use_length)
c906108c 7679{
6d820c5c 7680 struct remote_state *rs = get_remote_state ();
cfd77fa1 7681 char *p;
a76d924d
DJ
7682 char *plen = NULL;
7683 int plenlen = 0;
124e13d9
SM
7684 int todo_units;
7685 int units_written;
7686 int payload_capacity_bytes;
7687 int payload_length_bytes;
a76d924d
DJ
7688
7689 if (packet_format != 'X' && packet_format != 'M')
7690 internal_error (__FILE__, __LINE__,
9b20d036 7691 _("remote_write_bytes_aux: bad packet format"));
c906108c 7692
124e13d9 7693 if (len_units == 0)
9b409511 7694 return TARGET_XFER_EOF;
b2182ed2 7695
124e13d9 7696 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7697
6d820c5c
DJ
7698 /* The packet buffer will be large enough for the payload;
7699 get_memory_packet_size ensures this. */
a76d924d 7700 rs->buf[0] = '\0';
c906108c 7701
a257b5bb 7702 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7703 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7704
124e13d9 7705 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7706 if (!use_length)
0df8b418 7707 /* The comma won't be used. */
124e13d9
SM
7708 payload_capacity_bytes += 1;
7709 payload_capacity_bytes -= strlen (header);
7710 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7711
a76d924d 7712 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7713
a76d924d
DJ
7714 strcat (rs->buf, header);
7715 p = rs->buf + strlen (header);
7716
7717 /* Compute a best guess of the number of bytes actually transfered. */
7718 if (packet_format == 'X')
c906108c 7719 {
23860348 7720 /* Best guess at number of bytes that will fit. */
124e13d9 7721 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7722 if (use_length)
124e13d9
SM
7723 payload_capacity_bytes -= hexnumlen (todo_units);
7724 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7725 }
7726 else
7727 {
124e13d9
SM
7728 /* Number of bytes that will fit. */
7729 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7730 if (use_length)
124e13d9
SM
7731 payload_capacity_bytes -= hexnumlen (todo_units);
7732 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7733 }
a76d924d 7734
124e13d9 7735 if (todo_units <= 0)
3de11b2e 7736 internal_error (__FILE__, __LINE__,
405f8e94 7737 _("minimum packet size too small to write data"));
802188a7 7738
6765f3e5
DJ
7739 /* If we already need another packet, then try to align the end
7740 of this packet to a useful boundary. */
124e13d9
SM
7741 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7742 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7743
a257b5bb 7744 /* Append "<memaddr>". */
917317f4
JM
7745 memaddr = remote_address_masked (memaddr);
7746 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7747
a76d924d
DJ
7748 if (use_length)
7749 {
7750 /* Append ",". */
7751 *p++ = ',';
802188a7 7752
124e13d9
SM
7753 /* Append the length and retain its location and size. It may need to be
7754 adjusted once the packet body has been created. */
a76d924d 7755 plen = p;
124e13d9 7756 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7757 p += plenlen;
7758 }
a257b5bb
AC
7759
7760 /* Append ":". */
917317f4
JM
7761 *p++ = ':';
7762 *p = '\0';
802188a7 7763
a257b5bb 7764 /* Append the packet body. */
a76d924d 7765 if (packet_format == 'X')
917317f4 7766 {
917317f4
JM
7767 /* Binary mode. Send target system values byte by byte, in
7768 increasing byte addresses. Only escape certain critical
7769 characters. */
124e13d9
SM
7770 payload_length_bytes =
7771 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7772 &units_written, payload_capacity_bytes);
6765f3e5 7773
124e13d9 7774 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7775 a second try to keep the end of the packet aligned. Don't do
7776 this if the packet is tiny. */
124e13d9 7777 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7778 {
124e13d9
SM
7779 int new_todo_units;
7780
7781 new_todo_units = align_for_efficient_write (units_written, memaddr);
7782
7783 if (new_todo_units != units_written)
7784 payload_length_bytes =
7785 remote_escape_output (myaddr, new_todo_units, unit_size,
7786 (gdb_byte *) p, &units_written,
7787 payload_capacity_bytes);
6765f3e5
DJ
7788 }
7789
124e13d9
SM
7790 p += payload_length_bytes;
7791 if (use_length && units_written < todo_units)
c906108c 7792 {
802188a7 7793 /* Escape chars have filled up the buffer prematurely,
124e13d9 7794 and we have actually sent fewer units than planned.
917317f4
JM
7795 Fix-up the length field of the packet. Use the same
7796 number of characters as before. */
124e13d9
SM
7797 plen += hexnumnstr (plen, (ULONGEST) units_written,
7798 plenlen);
917317f4 7799 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7800 }
a76d924d
DJ
7801 }
7802 else
7803 {
917317f4
JM
7804 /* Normal mode: Send target system values byte by byte, in
7805 increasing byte addresses. Each byte is encoded as a two hex
7806 value. */
124e13d9
SM
7807 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7808 units_written = todo_units;
c906108c 7809 }
802188a7 7810
2e9f7625 7811 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7812 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7813
2e9f7625 7814 if (rs->buf[0] == 'E')
00d84524 7815 return TARGET_XFER_E_IO;
802188a7 7816
124e13d9
SM
7817 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7818 send fewer units than we'd planned. */
7819 *xfered_len_units = (ULONGEST) units_written;
9b409511 7820 return TARGET_XFER_OK;
c906108c
SS
7821}
7822
a76d924d
DJ
7823/* Write memory data directly to the remote machine.
7824 This does not inform the data cache; the data cache uses this.
7825 MEMADDR is the address in the remote memory space.
7826 MYADDR is the address of the buffer in our space.
7827 LEN is the number of bytes.
7828
9b409511
YQ
7829 Return the transferred status, error or OK (an
7830 'enum target_xfer_status' value). Save the number of bytes
7831 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7832
9b409511
YQ
7833static enum target_xfer_status
7834remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7835 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7836{
7837 char *packet_format = 0;
7838
7839 /* Check whether the target supports binary download. */
7840 check_binary_download (memaddr);
7841
4082afcc 7842 switch (packet_support (PACKET_X))
a76d924d
DJ
7843 {
7844 case PACKET_ENABLE:
7845 packet_format = "X";
7846 break;
7847 case PACKET_DISABLE:
7848 packet_format = "M";
7849 break;
7850 case PACKET_SUPPORT_UNKNOWN:
7851 internal_error (__FILE__, __LINE__,
7852 _("remote_write_bytes: bad internal state"));
7853 default:
7854 internal_error (__FILE__, __LINE__, _("bad switch"));
7855 }
7856
7857 return remote_write_bytes_aux (packet_format,
124e13d9 7858 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7859 packet_format[0], 1);
a76d924d
DJ
7860}
7861
9217e74e
YQ
7862/* Read memory data directly from the remote machine.
7863 This does not use the data cache; the data cache uses this.
7864 MEMADDR is the address in the remote memory space.
7865 MYADDR is the address of the buffer in our space.
124e13d9
SM
7866 LEN_UNITS is the number of addressable memory units to read..
7867 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7868
7869 Return the transferred status, error or OK (an
7870 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7871 transferred in *XFERED_LEN_UNITS.
7872
7873 See the comment of remote_write_bytes_aux for an example of
7874 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7875
7876static enum target_xfer_status
124e13d9
SM
7877remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7878 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7879{
7880 struct remote_state *rs = get_remote_state ();
124e13d9 7881 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7882 char *p;
124e13d9
SM
7883 int todo_units;
7884 int decoded_bytes;
9217e74e 7885
124e13d9 7886 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7887 /* The packet buffer will be large enough for the payload;
7888 get_memory_packet_size ensures this. */
7889
124e13d9
SM
7890 /* Number of units that will fit. */
7891 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7892
7893 /* Construct "m"<memaddr>","<len>". */
7894 memaddr = remote_address_masked (memaddr);
7895 p = rs->buf;
7896 *p++ = 'm';
7897 p += hexnumstr (p, (ULONGEST) memaddr);
7898 *p++ = ',';
124e13d9 7899 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7900 *p = '\0';
7901 putpkt (rs->buf);
7902 getpkt (&rs->buf, &rs->buf_size, 0);
7903 if (rs->buf[0] == 'E'
7904 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7905 && rs->buf[3] == '\0')
7906 return TARGET_XFER_E_IO;
7907 /* Reply describes memory byte by byte, each byte encoded as two hex
7908 characters. */
7909 p = rs->buf;
124e13d9 7910 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7911 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7912 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7913 return TARGET_XFER_OK;
7914}
7915
b55fbac4
YQ
7916/* Using the set of read-only target sections of remote, read live
7917 read-only memory.
8acf9577
YQ
7918
7919 For interface/parameters/return description see target.h,
7920 to_xfer_partial. */
7921
7922static enum target_xfer_status
b55fbac4
YQ
7923remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7924 ULONGEST memaddr, ULONGEST len,
124e13d9 7925 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7926{
7927 struct target_section *secp;
7928 struct target_section_table *table;
7929
7930 secp = target_section_by_addr (ops, memaddr);
7931 if (secp != NULL
7932 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7933 secp->the_bfd_section)
7934 & SEC_READONLY))
7935 {
7936 struct target_section *p;
7937 ULONGEST memend = memaddr + len;
7938
7939 table = target_get_section_table (ops);
7940
7941 for (p = table->sections; p < table->sections_end; p++)
7942 {
7943 if (memaddr >= p->addr)
7944 {
7945 if (memend <= p->endaddr)
7946 {
7947 /* Entire transfer is within this section. */
124e13d9 7948 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7949 xfered_len);
8acf9577
YQ
7950 }
7951 else if (memaddr >= p->endaddr)
7952 {
7953 /* This section ends before the transfer starts. */
7954 continue;
7955 }
7956 else
7957 {
7958 /* This section overlaps the transfer. Just do half. */
7959 len = p->endaddr - memaddr;
124e13d9 7960 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7961 xfered_len);
8acf9577
YQ
7962 }
7963 }
7964 }
7965 }
7966
7967 return TARGET_XFER_EOF;
7968}
7969
9217e74e
YQ
7970/* Similar to remote_read_bytes_1, but it reads from the remote stub
7971 first if the requested memory is unavailable in traceframe.
7972 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7973
9b409511 7974static enum target_xfer_status
8acf9577 7975remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7976 gdb_byte *myaddr, ULONGEST len, int unit_size,
7977 ULONGEST *xfered_len)
c906108c 7978{
6b6aa828 7979 if (len == 0)
96c4f946 7980 return TARGET_XFER_EOF;
b2182ed2 7981
8acf9577
YQ
7982 if (get_traceframe_number () != -1)
7983 {
7984 VEC(mem_range_s) *available;
7985
7986 /* If we fail to get the set of available memory, then the
7987 target does not support querying traceframe info, and so we
7988 attempt reading from the traceframe anyway (assuming the
7989 target implements the old QTro packet then). */
7990 if (traceframe_available_memory (&available, memaddr, len))
7991 {
7992 struct cleanup *old_chain;
7993
7994 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7995
7996 if (VEC_empty (mem_range_s, available)
7997 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7998 {
7999 enum target_xfer_status res;
8000
8001 /* Don't read into the traceframe's available
8002 memory. */
8003 if (!VEC_empty (mem_range_s, available))
8004 {
8005 LONGEST oldlen = len;
8006
8007 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
8008 gdb_assert (len <= oldlen);
8009 }
8010
8011 do_cleanups (old_chain);
8012
8013 /* This goes through the topmost target again. */
b55fbac4 8014 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 8015 len, unit_size, xfered_len);
8acf9577
YQ
8016 if (res == TARGET_XFER_OK)
8017 return TARGET_XFER_OK;
8018 else
8019 {
8020 /* No use trying further, we know some memory starting
8021 at MEMADDR isn't available. */
8022 *xfered_len = len;
8023 return TARGET_XFER_UNAVAILABLE;
8024 }
8025 }
8026
8027 /* Don't try to read more than how much is available, in
8028 case the target implements the deprecated QTro packet to
8029 cater for older GDBs (the target's knowledge of read-only
8030 sections may be outdated by now). */
8031 len = VEC_index (mem_range_s, available, 0)->length;
8032
8033 do_cleanups (old_chain);
8034 }
8035 }
8036
124e13d9 8037 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 8038}
74531fed 8039
c906108c 8040\f
c906108c 8041
a76d924d
DJ
8042/* Sends a packet with content determined by the printf format string
8043 FORMAT and the remaining arguments, then gets the reply. Returns
8044 whether the packet was a success, a failure, or unknown. */
8045
77b64a49
PA
8046static enum packet_result remote_send_printf (const char *format, ...)
8047 ATTRIBUTE_PRINTF (1, 2);
8048
2c0b251b 8049static enum packet_result
a76d924d
DJ
8050remote_send_printf (const char *format, ...)
8051{
8052 struct remote_state *rs = get_remote_state ();
8053 int max_size = get_remote_packet_size ();
a76d924d 8054 va_list ap;
a744cf53 8055
a76d924d
DJ
8056 va_start (ap, format);
8057
8058 rs->buf[0] = '\0';
8059 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 8060 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
8061
8062 if (putpkt (rs->buf) < 0)
8063 error (_("Communication problem with target."));
8064
8065 rs->buf[0] = '\0';
8066 getpkt (&rs->buf, &rs->buf_size, 0);
8067
8068 return packet_check_result (rs->buf);
8069}
8070
8071static void
8072restore_remote_timeout (void *p)
8073{
8074 int value = *(int *)p;
a744cf53 8075
a76d924d
DJ
8076 remote_timeout = value;
8077}
8078
8079/* Flash writing can take quite some time. We'll set
8080 effectively infinite timeout for flash operations.
8081 In future, we'll need to decide on a better approach. */
8082static const int remote_flash_timeout = 1000;
8083
8084static void
8085remote_flash_erase (struct target_ops *ops,
8086 ULONGEST address, LONGEST length)
8087{
f5656ead 8088 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
8089 int saved_remote_timeout = remote_timeout;
8090 enum packet_result ret;
a76d924d
DJ
8091 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8092 &saved_remote_timeout);
a744cf53 8093
a76d924d
DJ
8094 remote_timeout = remote_flash_timeout;
8095
8096 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8097 phex (address, addr_size),
a76d924d
DJ
8098 phex (length, 4));
8099 switch (ret)
8100 {
8101 case PACKET_UNKNOWN:
8102 error (_("Remote target does not support flash erase"));
8103 case PACKET_ERROR:
8104 error (_("Error erasing flash with vFlashErase packet"));
8105 default:
8106 break;
8107 }
8108
8109 do_cleanups (back_to);
8110}
8111
9b409511
YQ
8112static enum target_xfer_status
8113remote_flash_write (struct target_ops *ops, ULONGEST address,
8114 ULONGEST length, ULONGEST *xfered_len,
8115 const gdb_byte *data)
a76d924d
DJ
8116{
8117 int saved_remote_timeout = remote_timeout;
9b409511 8118 enum target_xfer_status ret;
a76d924d 8119 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 8120 &saved_remote_timeout);
a76d924d
DJ
8121
8122 remote_timeout = remote_flash_timeout;
124e13d9 8123 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 8124 xfered_len,'X', 0);
a76d924d
DJ
8125 do_cleanups (back_to);
8126
8127 return ret;
8128}
8129
8130static void
8131remote_flash_done (struct target_ops *ops)
8132{
8133 int saved_remote_timeout = remote_timeout;
8134 int ret;
8135 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8136 &saved_remote_timeout);
8137
8138 remote_timeout = remote_flash_timeout;
8139 ret = remote_send_printf ("vFlashDone");
8140 do_cleanups (back_to);
8141
8142 switch (ret)
8143 {
8144 case PACKET_UNKNOWN:
8145 error (_("Remote target does not support vFlashDone"));
8146 case PACKET_ERROR:
8147 error (_("Error finishing flash operation"));
8148 default:
8149 break;
8150 }
8151}
8152
c906108c 8153static void
fba45db2 8154remote_files_info (struct target_ops *ignore)
c906108c
SS
8155{
8156 puts_filtered ("Debugging a target over a serial line.\n");
8157}
8158\f
8159/* Stuff for dealing with the packets which are part of this protocol.
8160 See comment at top of file for details. */
8161
1927e618
PA
8162/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8163 error to higher layers. Called when a serial error is detected.
8164 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8165 the system error message for errno at function entry and final dot
8166 for output compatibility with throw_perror_with_name. */
1927e618
PA
8167
8168static void
8169unpush_and_perror (const char *string)
8170{
d6cb50a2 8171 int saved_errno = errno;
1927e618
PA
8172
8173 remote_unpush_target ();
d6cb50a2
JK
8174 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8175 safe_strerror (saved_errno));
1927e618
PA
8176}
8177
0876f84a 8178/* Read a single character from the remote end. */
c906108c
SS
8179
8180static int
fba45db2 8181readchar (int timeout)
c906108c
SS
8182{
8183 int ch;
5d93a237 8184 struct remote_state *rs = get_remote_state ();
c906108c 8185
5d93a237 8186 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 8187
2acceee2 8188 if (ch >= 0)
0876f84a 8189 return ch;
2acceee2
JM
8190
8191 switch ((enum serial_rc) ch)
c906108c
SS
8192 {
8193 case SERIAL_EOF:
78a095c3 8194 remote_unpush_target ();
598d3636 8195 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8196 /* no return */
c906108c 8197 case SERIAL_ERROR:
1927e618
PA
8198 unpush_and_perror (_("Remote communication error. "
8199 "Target disconnected."));
2acceee2 8200 /* no return */
c906108c 8201 case SERIAL_TIMEOUT:
2acceee2 8202 break;
c906108c 8203 }
2acceee2 8204 return ch;
c906108c
SS
8205}
8206
c33e31fd
PA
8207/* Wrapper for serial_write that closes the target and throws if
8208 writing fails. */
8209
8210static void
8211remote_serial_write (const char *str, int len)
8212{
5d93a237
TT
8213 struct remote_state *rs = get_remote_state ();
8214
8215 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8216 {
1927e618
PA
8217 unpush_and_perror (_("Remote communication error. "
8218 "Target disconnected."));
c33e31fd
PA
8219 }
8220}
8221
6d820c5c
DJ
8222/* Send the command in *BUF to the remote machine, and read the reply
8223 into *BUF. Report an error if we get an error reply. Resize
8224 *BUF using xrealloc if necessary to hold the result, and update
8225 *SIZEOF_BUF. */
c906108c
SS
8226
8227static void
6d820c5c
DJ
8228remote_send (char **buf,
8229 long *sizeof_buf)
c906108c 8230{
6d820c5c 8231 putpkt (*buf);
c2d11a7d 8232 getpkt (buf, sizeof_buf, 0);
c906108c 8233
6d820c5c
DJ
8234 if ((*buf)[0] == 'E')
8235 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8236}
8237
6e5abd65
PA
8238/* Return a pointer to an xmalloc'ed string representing an escaped
8239 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8240 etc. The caller is responsible for releasing the returned
8241 memory. */
8242
8243static char *
8244escape_buffer (const char *buf, int n)
8245{
8246 struct cleanup *old_chain;
8247 struct ui_file *stb;
8248 char *str;
6e5abd65
PA
8249
8250 stb = mem_fileopen ();
8251 old_chain = make_cleanup_ui_file_delete (stb);
8252
6ef284bd 8253 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 8254 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
8255 do_cleanups (old_chain);
8256 return str;
8257}
8258
c906108c
SS
8259/* Display a null-terminated packet on stdout, for debugging, using C
8260 string notation. */
8261
8262static void
baa336ce 8263print_packet (const char *buf)
c906108c
SS
8264{
8265 puts_filtered ("\"");
43e526b9 8266 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8267 puts_filtered ("\"");
8268}
8269
8270int
baa336ce 8271putpkt (const char *buf)
c906108c
SS
8272{
8273 return putpkt_binary (buf, strlen (buf));
8274}
8275
8276/* Send a packet to the remote machine, with error checking. The data
23860348 8277 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8278 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8279 and for a possible /0 if we are debugging (remote_debug) and want
8280 to print the sent packet as a string. */
c906108c
SS
8281
8282static int
baa336ce 8283putpkt_binary (const char *buf, int cnt)
c906108c 8284{
2d717e4f 8285 struct remote_state *rs = get_remote_state ();
c906108c
SS
8286 int i;
8287 unsigned char csum = 0;
224c3ddb 8288 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8289 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8290
c906108c
SS
8291 int ch;
8292 int tcount = 0;
8293 char *p;
dd61ec5c 8294 char *message;
c906108c 8295
e24a49d8
PA
8296 /* Catch cases like trying to read memory or listing threads while
8297 we're waiting for a stop reply. The remote server wouldn't be
8298 ready to handle this request, so we'd hang and timeout. We don't
8299 have to worry about this in synchronous mode, because in that
8300 case it's not possible to issue a command while the target is
74531fed
PA
8301 running. This is not a problem in non-stop mode, because in that
8302 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8303 if (!target_is_non_stop_p ()
8304 && target_is_async_p ()
8305 && rs->waiting_for_stop_reply)
9597b22a
DE
8306 {
8307 error (_("Cannot execute this command while the target is running.\n"
8308 "Use the \"interrupt\" command to stop the target\n"
8309 "and then try again."));
8310 }
e24a49d8 8311
2d717e4f
DJ
8312 /* We're sending out a new packet. Make sure we don't look at a
8313 stale cached response. */
8314 rs->cached_wait_status = 0;
8315
c906108c
SS
8316 /* Copy the packet into buffer BUF2, encapsulating it
8317 and giving it a checksum. */
8318
c906108c
SS
8319 p = buf2;
8320 *p++ = '$';
8321
8322 for (i = 0; i < cnt; i++)
8323 {
8324 csum += buf[i];
8325 *p++ = buf[i];
8326 }
8327 *p++ = '#';
8328 *p++ = tohex ((csum >> 4) & 0xf);
8329 *p++ = tohex (csum & 0xf);
8330
8331 /* Send it over and over until we get a positive ack. */
8332
8333 while (1)
8334 {
8335 int started_error_output = 0;
8336
8337 if (remote_debug)
8338 {
6e5abd65
PA
8339 struct cleanup *old_chain;
8340 char *str;
8341
c906108c 8342 *p = '\0';
6e5abd65
PA
8343 str = escape_buffer (buf2, p - buf2);
8344 old_chain = make_cleanup (xfree, str);
8345 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8346 gdb_flush (gdb_stdlog);
6e5abd65 8347 do_cleanups (old_chain);
c906108c 8348 }
c33e31fd 8349 remote_serial_write (buf2, p - buf2);
c906108c 8350
a6f3e723
SL
8351 /* If this is a no acks version of the remote protocol, send the
8352 packet and move on. */
8353 if (rs->noack_mode)
8354 break;
8355
74531fed
PA
8356 /* Read until either a timeout occurs (-2) or '+' is read.
8357 Handle any notification that arrives in the mean time. */
c906108c
SS
8358 while (1)
8359 {
8360 ch = readchar (remote_timeout);
8361
c5aa993b 8362 if (remote_debug)
c906108c
SS
8363 {
8364 switch (ch)
8365 {
8366 case '+':
1216fa2c 8367 case '-':
c906108c
SS
8368 case SERIAL_TIMEOUT:
8369 case '$':
74531fed 8370 case '%':
c906108c
SS
8371 if (started_error_output)
8372 {
8373 putchar_unfiltered ('\n');
8374 started_error_output = 0;
8375 }
8376 }
8377 }
8378
8379 switch (ch)
8380 {
8381 case '+':
8382 if (remote_debug)
0f71a2f6 8383 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8384 do_cleanups (old_chain);
c906108c 8385 return 1;
1216fa2c
AC
8386 case '-':
8387 if (remote_debug)
8388 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8389 /* FALLTHROUGH */
c906108c 8390 case SERIAL_TIMEOUT:
c5aa993b 8391 tcount++;
c906108c 8392 if (tcount > 3)
a5c0808e
PA
8393 {
8394 do_cleanups (old_chain);
8395 return 0;
8396 }
23860348 8397 break; /* Retransmit buffer. */
c906108c
SS
8398 case '$':
8399 {
40e3f985 8400 if (remote_debug)
2bc416ba 8401 fprintf_unfiltered (gdb_stdlog,
23860348 8402 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8403 /* It's probably an old response sent because an ACK
8404 was lost. Gobble up the packet and ack it so it
8405 doesn't get retransmitted when we resend this
8406 packet. */
6d820c5c 8407 skip_frame ();
c33e31fd 8408 remote_serial_write ("+", 1);
23860348 8409 continue; /* Now, go look for +. */
c906108c 8410 }
74531fed
PA
8411
8412 case '%':
8413 {
8414 int val;
8415
8416 /* If we got a notification, handle it, and go back to looking
8417 for an ack. */
8418 /* We've found the start of a notification. Now
8419 collect the data. */
8420 val = read_frame (&rs->buf, &rs->buf_size);
8421 if (val >= 0)
8422 {
8423 if (remote_debug)
8424 {
6e5abd65
PA
8425 struct cleanup *old_chain;
8426 char *str;
8427
8428 str = escape_buffer (rs->buf, val);
8429 old_chain = make_cleanup (xfree, str);
8430 fprintf_unfiltered (gdb_stdlog,
8431 " Notification received: %s\n",
8432 str);
8433 do_cleanups (old_chain);
74531fed 8434 }
5965e028 8435 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8436 /* We're in sync now, rewait for the ack. */
8437 tcount = 0;
8438 }
8439 else
8440 {
8441 if (remote_debug)
8442 {
8443 if (!started_error_output)
8444 {
8445 started_error_output = 1;
8446 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8447 }
8448 fputc_unfiltered (ch & 0177, gdb_stdlog);
8449 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8450 }
8451 }
8452 continue;
8453 }
8454 /* fall-through */
c906108c
SS
8455 default:
8456 if (remote_debug)
8457 {
8458 if (!started_error_output)
8459 {
8460 started_error_output = 1;
0f71a2f6 8461 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8462 }
0f71a2f6 8463 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8464 }
8465 continue;
8466 }
23860348 8467 break; /* Here to retransmit. */
c906108c
SS
8468 }
8469
8470#if 0
8471 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8472 able to get out next time we call QUIT, without anything as
8473 violent as interrupt_query. If we want to provide a way out of
8474 here without getting to the next QUIT, it should be based on
8475 hitting ^C twice as in remote_wait. */
c906108c
SS
8476 if (quit_flag)
8477 {
8478 quit_flag = 0;
8479 interrupt_query ();
8480 }
8481#endif
8482 }
a5c0808e
PA
8483
8484 do_cleanups (old_chain);
a6f3e723 8485 return 0;
c906108c
SS
8486}
8487
6d820c5c
DJ
8488/* Come here after finding the start of a frame when we expected an
8489 ack. Do our best to discard the rest of this packet. */
8490
8491static void
8492skip_frame (void)
8493{
8494 int c;
8495
8496 while (1)
8497 {
8498 c = readchar (remote_timeout);
8499 switch (c)
8500 {
8501 case SERIAL_TIMEOUT:
8502 /* Nothing we can do. */
8503 return;
8504 case '#':
8505 /* Discard the two bytes of checksum and stop. */
8506 c = readchar (remote_timeout);
8507 if (c >= 0)
8508 c = readchar (remote_timeout);
8509
8510 return;
8511 case '*': /* Run length encoding. */
8512 /* Discard the repeat count. */
8513 c = readchar (remote_timeout);
8514 if (c < 0)
8515 return;
8516 break;
8517 default:
8518 /* A regular character. */
8519 break;
8520 }
8521 }
8522}
8523
c906108c 8524/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8525 into *BUF, verifying the checksum, length, and handling run-length
8526 compression. NUL terminate the buffer. If there is not enough room,
8527 expand *BUF using xrealloc.
c906108c 8528
c2d11a7d
JM
8529 Returns -1 on error, number of characters in buffer (ignoring the
8530 trailing NULL) on success. (could be extended to return one of the
23860348 8531 SERIAL status indications). */
c2d11a7d
JM
8532
8533static long
6d820c5c
DJ
8534read_frame (char **buf_p,
8535 long *sizeof_buf)
c906108c
SS
8536{
8537 unsigned char csum;
c2d11a7d 8538 long bc;
c906108c 8539 int c;
6d820c5c 8540 char *buf = *buf_p;
a6f3e723 8541 struct remote_state *rs = get_remote_state ();
c906108c
SS
8542
8543 csum = 0;
c2d11a7d 8544 bc = 0;
c906108c
SS
8545
8546 while (1)
8547 {
8548 c = readchar (remote_timeout);
c906108c
SS
8549 switch (c)
8550 {
8551 case SERIAL_TIMEOUT:
8552 if (remote_debug)
0f71a2f6 8553 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8554 return -1;
c906108c
SS
8555 case '$':
8556 if (remote_debug)
0f71a2f6
JM
8557 fputs_filtered ("Saw new packet start in middle of old one\n",
8558 gdb_stdlog);
23860348 8559 return -1; /* Start a new packet, count retries. */
c906108c
SS
8560 case '#':
8561 {
8562 unsigned char pktcsum;
e1b09194
AC
8563 int check_0 = 0;
8564 int check_1 = 0;
c906108c 8565
c2d11a7d 8566 buf[bc] = '\0';
c906108c 8567
e1b09194
AC
8568 check_0 = readchar (remote_timeout);
8569 if (check_0 >= 0)
8570 check_1 = readchar (remote_timeout);
802188a7 8571
e1b09194
AC
8572 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8573 {
8574 if (remote_debug)
2bc416ba 8575 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8576 gdb_stdlog);
e1b09194
AC
8577 return -1;
8578 }
8579 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8580 {
8581 if (remote_debug)
2bc416ba 8582 fputs_filtered ("Communication error in checksum\n",
23860348 8583 gdb_stdlog);
40e3f985
FN
8584 return -1;
8585 }
c906108c 8586
a6f3e723
SL
8587 /* Don't recompute the checksum; with no ack packets we
8588 don't have any way to indicate a packet retransmission
8589 is necessary. */
8590 if (rs->noack_mode)
8591 return bc;
8592
e1b09194 8593 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8594 if (csum == pktcsum)
c2d11a7d 8595 return bc;
c906108c 8596
c5aa993b 8597 if (remote_debug)
c906108c 8598 {
6e5abd65
PA
8599 struct cleanup *old_chain;
8600 char *str;
8601
8602 str = escape_buffer (buf, bc);
8603 old_chain = make_cleanup (xfree, str);
8604 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8605 "Bad checksum, sentsum=0x%x, "
8606 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8607 pktcsum, csum, str);
8608 do_cleanups (old_chain);
c906108c 8609 }
c2d11a7d 8610 /* Number of characters in buffer ignoring trailing
23860348 8611 NULL. */
c2d11a7d 8612 return -1;
c906108c 8613 }
23860348 8614 case '*': /* Run length encoding. */
c2c6d25f
JM
8615 {
8616 int repeat;
c906108c 8617
a744cf53 8618 csum += c;
b4501125
AC
8619 c = readchar (remote_timeout);
8620 csum += c;
23860348 8621 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8622
23860348 8623 /* The character before ``*'' is repeated. */
c2d11a7d 8624
6d820c5c 8625 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8626 {
6d820c5c
DJ
8627 if (bc + repeat - 1 >= *sizeof_buf - 1)
8628 {
8629 /* Make some more room in the buffer. */
8630 *sizeof_buf += repeat;
224c3ddb 8631 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
8632 buf = *buf_p;
8633 }
8634
c2d11a7d
JM
8635 memset (&buf[bc], buf[bc - 1], repeat);
8636 bc += repeat;
c2c6d25f
JM
8637 continue;
8638 }
8639
c2d11a7d 8640 buf[bc] = '\0';
6d820c5c 8641 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8642 return -1;
c2c6d25f 8643 }
c906108c 8644 default:
6d820c5c 8645 if (bc >= *sizeof_buf - 1)
c906108c 8646 {
6d820c5c
DJ
8647 /* Make some more room in the buffer. */
8648 *sizeof_buf *= 2;
224c3ddb 8649 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 8650 buf = *buf_p;
c906108c
SS
8651 }
8652
6d820c5c
DJ
8653 buf[bc++] = c;
8654 csum += c;
8655 continue;
c906108c
SS
8656 }
8657 }
8658}
8659
8660/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8661 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8662 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8663 rather than timing out; this is used (in synchronous mode) to wait
8664 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8665/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8666 don't have to change all the calls to getpkt to deal with the
8667 return value, because at the moment I don't know what the right
23860348 8668 thing to do it for those. */
c906108c 8669void
6d820c5c
DJ
8670getpkt (char **buf,
8671 long *sizeof_buf,
c2d11a7d 8672 int forever)
d9fcf2fb
JM
8673{
8674 int timed_out;
8675
8676 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8677}
8678
8679
8680/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8681 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8682 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8683 rather than timing out; this is used (in synchronous mode) to wait
8684 for a target that is is executing user code to stop. If FOREVER ==
8685 0, this function is allowed to time out gracefully and return an
74531fed
PA
8686 indication of this to the caller. Otherwise return the number of
8687 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8688 enough reason to return to the caller. *IS_NOTIF is an output
8689 boolean that indicates whether *BUF holds a notification or not
8690 (a regular packet). */
74531fed 8691
3172dc30 8692static int
74531fed 8693getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8694 int expecting_notif, int *is_notif)
c906108c 8695{
2d717e4f 8696 struct remote_state *rs = get_remote_state ();
c906108c
SS
8697 int c;
8698 int tries;
8699 int timeout;
df4b58fe 8700 int val = -1;
c906108c 8701
2d717e4f
DJ
8702 /* We're reading a new response. Make sure we don't look at a
8703 previously cached response. */
8704 rs->cached_wait_status = 0;
8705
6d820c5c 8706 strcpy (*buf, "timeout");
c906108c
SS
8707
8708 if (forever)
74531fed
PA
8709 timeout = watchdog > 0 ? watchdog : -1;
8710 else if (expecting_notif)
8711 timeout = 0; /* There should already be a char in the buffer. If
8712 not, bail out. */
c906108c
SS
8713 else
8714 timeout = remote_timeout;
8715
8716#define MAX_TRIES 3
8717
74531fed
PA
8718 /* Process any number of notifications, and then return when
8719 we get a packet. */
8720 for (;;)
c906108c 8721 {
d9c43928 8722 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8723 times. */
8724 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8725 {
74531fed
PA
8726 /* This can loop forever if the remote side sends us
8727 characters continuously, but if it pauses, we'll get
8728 SERIAL_TIMEOUT from readchar because of timeout. Then
8729 we'll count that as a retry.
8730
8731 Note that even when forever is set, we will only wait
8732 forever prior to the start of a packet. After that, we
8733 expect characters to arrive at a brisk pace. They should
8734 show up within remote_timeout intervals. */
8735 do
8736 c = readchar (timeout);
8737 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8738
8739 if (c == SERIAL_TIMEOUT)
8740 {
74531fed
PA
8741 if (expecting_notif)
8742 return -1; /* Don't complain, it's normal to not get
8743 anything in this case. */
8744
23860348 8745 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8746 {
2acceee2 8747 QUIT;
78a095c3 8748 remote_unpush_target ();
598d3636
JK
8749 throw_error (TARGET_CLOSE_ERROR,
8750 _("Watchdog timeout has expired. "
8751 "Target detached."));
c906108c 8752 }
c906108c 8753 if (remote_debug)
0f71a2f6 8754 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8755 }
74531fed
PA
8756 else
8757 {
8758 /* We've found the start of a packet or notification.
8759 Now collect the data. */
8760 val = read_frame (buf, sizeof_buf);
8761 if (val >= 0)
8762 break;
8763 }
8764
c33e31fd 8765 remote_serial_write ("-", 1);
c906108c 8766 }
c906108c 8767
74531fed
PA
8768 if (tries > MAX_TRIES)
8769 {
8770 /* We have tried hard enough, and just can't receive the
8771 packet/notification. Give up. */
8772 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8773
74531fed
PA
8774 /* Skip the ack char if we're in no-ack mode. */
8775 if (!rs->noack_mode)
c33e31fd 8776 remote_serial_write ("+", 1);
74531fed
PA
8777 return -1;
8778 }
c906108c 8779
74531fed
PA
8780 /* If we got an ordinary packet, return that to our caller. */
8781 if (c == '$')
c906108c
SS
8782 {
8783 if (remote_debug)
43e526b9 8784 {
6e5abd65
PA
8785 struct cleanup *old_chain;
8786 char *str;
8787
8788 str = escape_buffer (*buf, val);
8789 old_chain = make_cleanup (xfree, str);
8790 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8791 do_cleanups (old_chain);
43e526b9 8792 }
a6f3e723
SL
8793
8794 /* Skip the ack char if we're in no-ack mode. */
8795 if (!rs->noack_mode)
c33e31fd 8796 remote_serial_write ("+", 1);
fee9eda9
YQ
8797 if (is_notif != NULL)
8798 *is_notif = 0;
0876f84a 8799 return val;
c906108c
SS
8800 }
8801
74531fed
PA
8802 /* If we got a notification, handle it, and go back to looking
8803 for a packet. */
8804 else
8805 {
8806 gdb_assert (c == '%');
8807
8808 if (remote_debug)
8809 {
6e5abd65
PA
8810 struct cleanup *old_chain;
8811 char *str;
8812
8813 str = escape_buffer (*buf, val);
8814 old_chain = make_cleanup (xfree, str);
8815 fprintf_unfiltered (gdb_stdlog,
8816 " Notification received: %s\n",
8817 str);
8818 do_cleanups (old_chain);
74531fed 8819 }
fee9eda9
YQ
8820 if (is_notif != NULL)
8821 *is_notif = 1;
c906108c 8822
5965e028 8823 handle_notification (rs->notif_state, *buf);
c906108c 8824
74531fed 8825 /* Notifications require no acknowledgement. */
a6f3e723 8826
74531fed 8827 if (expecting_notif)
fee9eda9 8828 return val;
74531fed
PA
8829 }
8830 }
8831}
8832
8833static int
8834getpkt_sane (char **buf, long *sizeof_buf, int forever)
8835{
fee9eda9 8836 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8837}
8838
8839static int
fee9eda9
YQ
8840getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8841 int *is_notif)
74531fed 8842{
fee9eda9
YQ
8843 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8844 is_notif);
c906108c 8845}
74531fed 8846
cbb8991c
DB
8847/* Check whether EVENT is a fork event for the process specified
8848 by the pid passed in DATA, and if it is, kill the fork child. */
8849
8850static int
8851kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8852 QUEUE_ITER (stop_reply_p) *iter,
8853 stop_reply_p event,
8854 void *data)
8855{
19ba03f4 8856 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
8857 int parent_pid = *(int *) param->input;
8858
8859 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8860 {
8861 struct remote_state *rs = get_remote_state ();
8862 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8863 int res;
8864
8865 res = remote_vkill (child_pid, rs);
8866 if (res != 0)
8867 error (_("Can't kill fork child process %d"), child_pid);
8868 }
8869
8870 return 1;
8871}
8872
8873/* Kill any new fork children of process PID that haven't been
8874 processed by follow_fork. */
8875
8876static void
8877kill_new_fork_children (int pid, struct remote_state *rs)
8878{
8879 struct thread_info *thread;
8880 struct notif_client *notif = &notif_client_stop;
8881 struct queue_iter_param param;
8882
8883 /* Kill the fork child threads of any threads in process PID
8884 that are stopped at a fork event. */
8885 ALL_NON_EXITED_THREADS (thread)
8886 {
8887 struct target_waitstatus *ws = &thread->pending_follow;
8888
8889 if (is_pending_fork_parent (ws, pid, thread->ptid))
8890 {
8891 struct remote_state *rs = get_remote_state ();
8892 int child_pid = ptid_get_pid (ws->value.related_pid);
8893 int res;
8894
8895 res = remote_vkill (child_pid, rs);
8896 if (res != 0)
8897 error (_("Can't kill fork child process %d"), child_pid);
8898 }
8899 }
8900
8901 /* Check for any pending fork events (not reported or processed yet)
8902 in process PID and kill those fork child threads as well. */
8903 remote_notif_get_pending_events (notif);
8904 param.input = &pid;
8905 param.output = NULL;
8906 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8907 kill_child_of_pending_fork, &param);
8908}
8909
c906108c 8910\f
8020350c
DB
8911/* Target hook to kill the current inferior. */
8912
c906108c 8913static void
7d85a9c0 8914remote_kill (struct target_ops *ops)
43ff13b4 8915{
8020350c
DB
8916 int res = -1;
8917 int pid = ptid_get_pid (inferior_ptid);
8918 struct remote_state *rs = get_remote_state ();
0fdf84ca 8919
8020350c 8920 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 8921 {
8020350c
DB
8922 /* If we're stopped while forking and we haven't followed yet,
8923 kill the child task. We need to do this before killing the
8924 parent task because if this is a vfork then the parent will
8925 be sleeping. */
8926 kill_new_fork_children (pid, rs);
8927
8928 res = remote_vkill (pid, rs);
8929 if (res == 0)
0fdf84ca 8930 {
8020350c 8931 target_mourn_inferior ();
0fdf84ca
PA
8932 return;
8933 }
8020350c 8934 }
0fdf84ca 8935
8020350c
DB
8936 /* If we are in 'target remote' mode and we are killing the only
8937 inferior, then we will tell gdbserver to exit and unpush the
8938 target. */
8939 if (res == -1 && !remote_multi_process_p (rs)
8940 && number_of_live_inferiors () == 1)
8941 {
8942 remote_kill_k ();
8943
8944 /* We've killed the remote end, we get to mourn it. If we are
8945 not in extended mode, mourning the inferior also unpushes
8946 remote_ops from the target stack, which closes the remote
8947 connection. */
8948 target_mourn_inferior ();
8949
8950 return;
0fdf84ca 8951 }
43ff13b4 8952
8020350c 8953 error (_("Can't kill process"));
43ff13b4
JM
8954}
8955
8020350c
DB
8956/* Send a kill request to the target using the 'vKill' packet. */
8957
82f73884
PA
8958static int
8959remote_vkill (int pid, struct remote_state *rs)
8960{
4082afcc 8961 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8962 return -1;
8963
8964 /* Tell the remote target to detach. */
bba74b36 8965 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8966 putpkt (rs->buf);
8967 getpkt (&rs->buf, &rs->buf_size, 0);
8968
4082afcc
PA
8969 switch (packet_ok (rs->buf,
8970 &remote_protocol_packets[PACKET_vKill]))
8971 {
8972 case PACKET_OK:
8973 return 0;
8974 case PACKET_ERROR:
8975 return 1;
8976 case PACKET_UNKNOWN:
8977 return -1;
8978 default:
8979 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8980 }
82f73884
PA
8981}
8982
8020350c
DB
8983/* Send a kill request to the target using the 'k' packet. */
8984
82f73884 8985static void
8020350c 8986remote_kill_k (void)
82f73884 8987{
8020350c
DB
8988 /* Catch errors so the user can quit from gdb even when we
8989 aren't on speaking terms with the remote system. */
8990 TRY
82f73884 8991 {
82f73884 8992 putpkt ("k");
82f73884 8993 }
8020350c
DB
8994 CATCH (ex, RETURN_MASK_ERROR)
8995 {
8996 if (ex.error == TARGET_CLOSE_ERROR)
8997 {
8998 /* If we got an (EOF) error that caused the target
8999 to go away, then we're done, that's what we wanted.
9000 "k" is susceptible to cause a premature EOF, given
9001 that the remote server isn't actually required to
9002 reply to "k", and it can happen that it doesn't
9003 even get to reply ACK to the "k". */
9004 return;
9005 }
82f73884 9006
8020350c
DB
9007 /* Otherwise, something went wrong. We didn't actually kill
9008 the target. Just propagate the exception, and let the
9009 user or higher layers decide what to do. */
9010 throw_exception (ex);
9011 }
9012 END_CATCH
82f73884
PA
9013}
9014
c906108c 9015static void
20f796c9 9016remote_mourn (struct target_ops *target)
c906108c 9017{
8020350c 9018 struct remote_state *rs = get_remote_state ();
ce5ce7ed 9019
8020350c
DB
9020 /* In 'target remote' mode with one inferior, we close the connection. */
9021 if (!rs->extended && number_of_live_inferiors () <= 1)
9022 {
9023 unpush_target (target);
c906108c 9024
8020350c
DB
9025 /* remote_close takes care of doing most of the clean up. */
9026 generic_mourn_inferior ();
9027 return;
9028 }
c906108c 9029
e24a49d8
PA
9030 /* In case we got here due to an error, but we're going to stay
9031 connected. */
9032 rs->waiting_for_stop_reply = 0;
9033
dc1981d7
PA
9034 /* If the current general thread belonged to the process we just
9035 detached from or has exited, the remote side current general
9036 thread becomes undefined. Considering a case like this:
9037
9038 - We just got here due to a detach.
9039 - The process that we're detaching from happens to immediately
9040 report a global breakpoint being hit in non-stop mode, in the
9041 same thread we had selected before.
9042 - GDB attaches to this process again.
9043 - This event happens to be the next event we handle.
9044
9045 GDB would consider that the current general thread didn't need to
9046 be set on the stub side (with Hg), since for all it knew,
9047 GENERAL_THREAD hadn't changed.
9048
9049 Notice that although in all-stop mode, the remote server always
9050 sets the current thread to the thread reporting the stop event,
9051 that doesn't happen in non-stop mode; in non-stop, the stub *must
9052 not* change the current thread when reporting a breakpoint hit,
9053 due to the decoupling of event reporting and event handling.
9054
9055 To keep things simple, we always invalidate our notion of the
9056 current thread. */
47f8a51d 9057 record_currthread (rs, minus_one_ptid);
dc1981d7 9058
8020350c 9059 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9060 generic_mourn_inferior ();
9061
d729566a 9062 if (!have_inferiors ())
2d717e4f 9063 {
82f73884
PA
9064 if (!remote_multi_process_p (rs))
9065 {
9066 /* Check whether the target is running now - some remote stubs
9067 automatically restart after kill. */
9068 putpkt ("?");
9069 getpkt (&rs->buf, &rs->buf_size, 0);
9070
9071 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9072 {
3e43a32a
MS
9073 /* Assume that the target has been restarted. Set
9074 inferior_ptid so that bits of core GDB realizes
9075 there's something here, e.g., so that the user can
9076 say "kill" again. */
82f73884
PA
9077 inferior_ptid = magic_null_ptid;
9078 }
82f73884 9079 }
2d717e4f
DJ
9080 }
9081}
c906108c 9082
03583c20 9083static int
2bfc0540 9084extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 9085{
4082afcc 9086 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9087}
9088
9089static void
9090extended_remote_disable_randomization (int val)
9091{
9092 struct remote_state *rs = get_remote_state ();
9093 char *reply;
9094
bba74b36
YQ
9095 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9096 val);
03583c20
UW
9097 putpkt (rs->buf);
9098 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9099 if (*reply == '\0')
9100 error (_("Target does not support QDisableRandomization."));
9101 if (strcmp (reply, "OK") != 0)
9102 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9103}
9104
2d717e4f
DJ
9105static int
9106extended_remote_run (char *args)
9107{
9108 struct remote_state *rs = get_remote_state ();
2d717e4f 9109 int len;
94585166 9110 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9111
2d717e4f
DJ
9112 /* If the user has disabled vRun support, or we have detected that
9113 support is not available, do not try it. */
4082afcc 9114 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9115 return -1;
424163ea 9116
2d717e4f
DJ
9117 strcpy (rs->buf, "vRun;");
9118 len = strlen (rs->buf);
c906108c 9119
2d717e4f
DJ
9120 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9121 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9122 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9123 strlen (remote_exec_file));
2d717e4f 9124
d1a41061 9125 gdb_assert (args != NULL);
2d717e4f
DJ
9126 if (*args)
9127 {
9128 struct cleanup *back_to;
9129 int i;
9130 char **argv;
9131
d1a41061 9132 argv = gdb_buildargv (args);
6e366df1 9133 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
9134 for (i = 0; argv[i] != NULL; i++)
9135 {
9136 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9137 error (_("Argument list too long for run packet"));
9138 rs->buf[len++] = ';';
9f1b45b0
TT
9139 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9140 strlen (argv[i]));
2d717e4f
DJ
9141 }
9142 do_cleanups (back_to);
9143 }
9144
9145 rs->buf[len++] = '\0';
9146
9147 putpkt (rs->buf);
9148 getpkt (&rs->buf, &rs->buf_size, 0);
9149
4082afcc 9150 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9151 {
4082afcc 9152 case PACKET_OK:
3405876a 9153 /* We have a wait response. All is well. */
2d717e4f 9154 return 0;
4082afcc
PA
9155 case PACKET_UNKNOWN:
9156 return -1;
9157 case PACKET_ERROR:
2d717e4f
DJ
9158 if (remote_exec_file[0] == '\0')
9159 error (_("Running the default executable on the remote target failed; "
9160 "try \"set remote exec-file\"?"));
9161 else
9162 error (_("Running \"%s\" on the remote target failed"),
9163 remote_exec_file);
4082afcc
PA
9164 default:
9165 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9166 }
c906108c
SS
9167}
9168
2d717e4f
DJ
9169/* In the extended protocol we want to be able to do things like
9170 "run" and have them basically work as expected. So we need
9171 a special create_inferior function. We support changing the
9172 executable file and the command line arguments, but not the
9173 environment. */
9174
43ff13b4 9175static void
77a19445
TT
9176extended_remote_create_inferior (struct target_ops *ops,
9177 char *exec_file, char *args,
9178 char **env, int from_tty)
43ff13b4 9179{
3405876a
PA
9180 int run_worked;
9181 char *stop_reply;
9182 struct remote_state *rs = get_remote_state ();
94585166 9183 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9184
43ff13b4 9185 /* If running asynchronously, register the target file descriptor
23860348 9186 with the event loop. */
75c99385 9187 if (target_can_async_p ())
6a3753b3 9188 target_async (1);
43ff13b4 9189
03583c20 9190 /* Disable address space randomization if requested (and supported). */
2bfc0540 9191 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9192 extended_remote_disable_randomization (disable_randomization);
9193
43ff13b4 9194 /* Now restart the remote server. */
3405876a
PA
9195 run_worked = extended_remote_run (args) != -1;
9196 if (!run_worked)
2d717e4f
DJ
9197 {
9198 /* vRun was not supported. Fail if we need it to do what the
9199 user requested. */
9200 if (remote_exec_file[0])
9201 error (_("Remote target does not support \"set remote exec-file\""));
9202 if (args[0])
9203 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9204
2d717e4f
DJ
9205 /* Fall back to "R". */
9206 extended_remote_restart ();
9207 }
424163ea 9208
6c95b8df
PA
9209 if (!have_inferiors ())
9210 {
9211 /* Clean up from the last time we ran, before we mark the target
9212 running again. This will mark breakpoints uninserted, and
9213 get_offsets may insert breakpoints. */
9214 init_thread_list ();
9215 init_wait_for_inferior ();
9216 }
45280a52 9217
3405876a
PA
9218 /* vRun's success return is a stop reply. */
9219 stop_reply = run_worked ? rs->buf : NULL;
9220 add_current_inferior_and_thread (stop_reply);
c0a2216e 9221
2d717e4f
DJ
9222 /* Get updated offsets, if the stub uses qOffsets. */
9223 get_offsets ();
2d717e4f 9224}
c906108c 9225\f
c5aa993b 9226
b775012e
LM
9227/* Given a location's target info BP_TGT and the packet buffer BUF, output
9228 the list of conditions (in agent expression bytecode format), if any, the
9229 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9230 started from BUF and ended at BUF_END. */
b775012e
LM
9231
9232static int
9233remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9234 struct bp_target_info *bp_tgt, char *buf,
9235 char *buf_end)
b775012e
LM
9236{
9237 struct agent_expr *aexpr = NULL;
9238 int i, ix;
9239 char *pkt;
9240 char *buf_start = buf;
9241
9242 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9243 return 0;
9244
9245 buf += strlen (buf);
bba74b36 9246 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9247 buf++;
9248
9249 /* Send conditions to the target and free the vector. */
9250 for (ix = 0;
9251 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9252 ix++)
9253 {
bba74b36 9254 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
9255 buf += strlen (buf);
9256 for (i = 0; i < aexpr->len; ++i)
9257 buf = pack_hex_byte (buf, aexpr->buf[i]);
9258 *buf = '\0';
9259 }
b775012e
LM
9260 return 0;
9261}
9262
d3ce09f5
SS
9263static void
9264remote_add_target_side_commands (struct gdbarch *gdbarch,
9265 struct bp_target_info *bp_tgt, char *buf)
9266{
9267 struct agent_expr *aexpr = NULL;
9268 int i, ix;
9269
9270 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9271 return;
9272
9273 buf += strlen (buf);
9274
9275 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9276 buf += strlen (buf);
9277
9278 /* Concatenate all the agent expressions that are commands into the
9279 cmds parameter. */
9280 for (ix = 0;
9281 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9282 ix++)
9283 {
9284 sprintf (buf, "X%x,", aexpr->len);
9285 buf += strlen (buf);
9286 for (i = 0; i < aexpr->len; ++i)
9287 buf = pack_hex_byte (buf, aexpr->buf[i]);
9288 *buf = '\0';
9289 }
d3ce09f5
SS
9290}
9291
8181d85f
DJ
9292/* Insert a breakpoint. On targets that have software breakpoint
9293 support, we ask the remote target to do the work; on targets
9294 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9295
9296static int
3db08215
MM
9297remote_insert_breakpoint (struct target_ops *ops,
9298 struct gdbarch *gdbarch,
a6d9a66e 9299 struct bp_target_info *bp_tgt)
c906108c 9300{
d471ea57
AC
9301 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9302 If it succeeds, then set the support to PACKET_ENABLE. If it
9303 fails, and the user has explicitly requested the Z support then
23860348 9304 report an error, otherwise, mark it disabled and go on. */
802188a7 9305
4082afcc 9306 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9307 {
0d5ed153 9308 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9309 struct remote_state *rs;
bba74b36 9310 char *p, *endbuf;
7c0f6dcc 9311 int bpsize;
b775012e 9312 struct condition_list *cond = NULL;
4fff2411 9313
28439a30
PA
9314 /* Make sure the remote is pointing at the right process, if
9315 necessary. */
9316 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9317 set_general_process ();
9318
a1dcb23a 9319 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
9320
9321 rs = get_remote_state ();
9322 p = rs->buf;
bba74b36 9323 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9324
96baa820
JM
9325 *(p++) = 'Z';
9326 *(p++) = '0';
9327 *(p++) = ',';
7c0f6dcc 9328 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9329 p += hexnumstr (p, addr);
bba74b36 9330 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 9331
efcc2da7 9332 if (remote_supports_cond_breakpoints (ops))
bba74b36 9333 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9334
78eff0ec 9335 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9336 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9337
6d820c5c
DJ
9338 putpkt (rs->buf);
9339 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9340
6d820c5c 9341 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9342 {
d471ea57
AC
9343 case PACKET_ERROR:
9344 return -1;
9345 case PACKET_OK:
7c0f6dcc
JL
9346 bp_tgt->placed_address = addr;
9347 bp_tgt->placed_size = bpsize;
d471ea57
AC
9348 return 0;
9349 case PACKET_UNKNOWN:
9350 break;
96baa820
JM
9351 }
9352 }
c906108c 9353
0000e5cc
PA
9354 /* If this breakpoint has target-side commands but this stub doesn't
9355 support Z0 packets, throw error. */
9356 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9357 throw_error (NOT_SUPPORTED_ERROR, _("\
9358Target doesn't support breakpoints that have target side commands."));
9359
3db08215 9360 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9361}
9362
9363static int
3db08215
MM
9364remote_remove_breakpoint (struct target_ops *ops,
9365 struct gdbarch *gdbarch,
a6d9a66e 9366 struct bp_target_info *bp_tgt)
c906108c 9367{
8181d85f 9368 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9369 struct remote_state *rs = get_remote_state ();
96baa820 9370
4082afcc 9371 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9372 {
6d820c5c 9373 char *p = rs->buf;
bba74b36 9374 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9375
28439a30
PA
9376 /* Make sure the remote is pointing at the right process, if
9377 necessary. */
9378 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9379 set_general_process ();
9380
96baa820
JM
9381 *(p++) = 'z';
9382 *(p++) = '0';
9383 *(p++) = ',';
9384
8181d85f
DJ
9385 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9386 p += hexnumstr (p, addr);
bba74b36 9387 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9388
6d820c5c
DJ
9389 putpkt (rs->buf);
9390 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9391
6d820c5c 9392 return (rs->buf[0] == 'E');
96baa820
JM
9393 }
9394
3db08215 9395 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9396}
9397
f486487f 9398static enum Z_packet_type
d471ea57
AC
9399watchpoint_to_Z_packet (int type)
9400{
9401 switch (type)
9402 {
9403 case hw_write:
bb858e6a 9404 return Z_PACKET_WRITE_WP;
d471ea57
AC
9405 break;
9406 case hw_read:
bb858e6a 9407 return Z_PACKET_READ_WP;
d471ea57
AC
9408 break;
9409 case hw_access:
bb858e6a 9410 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9411 break;
9412 default:
8e65ff28 9413 internal_error (__FILE__, __LINE__,
e2e0b3e5 9414 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9415 }
9416}
9417
3c3bea1c 9418static int
f486487f
SM
9419remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9420 enum target_hw_bp_type type, struct expression *cond)
96baa820 9421{
d01949b6 9422 struct remote_state *rs = get_remote_state ();
bba74b36 9423 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9424 char *p;
d471ea57 9425 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9426
4082afcc 9427 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9428 return 1;
802188a7 9429
28439a30
PA
9430 /* Make sure the remote is pointing at the right process, if
9431 necessary. */
9432 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9433 set_general_process ();
9434
bba74b36 9435 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9436 p = strchr (rs->buf, '\0');
96baa820
JM
9437 addr = remote_address_masked (addr);
9438 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9439 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9440
6d820c5c
DJ
9441 putpkt (rs->buf);
9442 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9443
6d820c5c 9444 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9445 {
9446 case PACKET_ERROR:
d471ea57 9447 return -1;
85d721b8
PA
9448 case PACKET_UNKNOWN:
9449 return 1;
d471ea57
AC
9450 case PACKET_OK:
9451 return 0;
9452 }
8e65ff28 9453 internal_error (__FILE__, __LINE__,
e2e0b3e5 9454 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9455}
9456
283002cf
MR
9457static int
9458remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9459 CORE_ADDR start, int length)
9460{
9461 CORE_ADDR diff = remote_address_masked (addr - start);
9462
9463 return diff < length;
9464}
9465
d471ea57 9466
3c3bea1c 9467static int
f486487f
SM
9468remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9469 enum target_hw_bp_type type, struct expression *cond)
96baa820 9470{
d01949b6 9471 struct remote_state *rs = get_remote_state ();
bba74b36 9472 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9473 char *p;
d471ea57
AC
9474 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9475
4082afcc 9476 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9477 return -1;
802188a7 9478
28439a30
PA
9479 /* Make sure the remote is pointing at the right process, if
9480 necessary. */
9481 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9482 set_general_process ();
9483
bba74b36 9484 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9485 p = strchr (rs->buf, '\0');
96baa820
JM
9486 addr = remote_address_masked (addr);
9487 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9488 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9489 putpkt (rs->buf);
9490 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9491
6d820c5c 9492 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9493 {
9494 case PACKET_ERROR:
9495 case PACKET_UNKNOWN:
9496 return -1;
9497 case PACKET_OK:
9498 return 0;
9499 }
8e65ff28 9500 internal_error (__FILE__, __LINE__,
e2e0b3e5 9501 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9502}
9503
3c3bea1c 9504
501eef12 9505int remote_hw_watchpoint_limit = -1;
480a3f21 9506int remote_hw_watchpoint_length_limit = -1;
501eef12 9507int remote_hw_breakpoint_limit = -1;
d471ea57 9508
480a3f21 9509static int
31568a15
TT
9510remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9511 CORE_ADDR addr, int len)
480a3f21
PW
9512{
9513 if (remote_hw_watchpoint_length_limit == 0)
9514 return 0;
9515 else if (remote_hw_watchpoint_length_limit < 0)
9516 return 1;
9517 else if (len <= remote_hw_watchpoint_length_limit)
9518 return 1;
9519 else
9520 return 0;
9521}
9522
b9362cc7 9523static int
5461485a 9524remote_check_watch_resources (struct target_ops *self,
f486487f 9525 enum bptype type, int cnt, int ot)
96baa820 9526{
3c3bea1c
GS
9527 if (type == bp_hardware_breakpoint)
9528 {
9529 if (remote_hw_breakpoint_limit == 0)
9530 return 0;
501eef12
AC
9531 else if (remote_hw_breakpoint_limit < 0)
9532 return 1;
3c3bea1c
GS
9533 else if (cnt <= remote_hw_breakpoint_limit)
9534 return 1;
9535 }
9536 else
9537 {
9538 if (remote_hw_watchpoint_limit == 0)
9539 return 0;
501eef12
AC
9540 else if (remote_hw_watchpoint_limit < 0)
9541 return 1;
3c3bea1c
GS
9542 else if (ot)
9543 return -1;
9544 else if (cnt <= remote_hw_watchpoint_limit)
9545 return 1;
9546 }
9547 return -1;
9548}
9549
f7e6eed5
PA
9550/* The to_stopped_by_sw_breakpoint method of target remote. */
9551
9552static int
9553remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9554{
799a2abe 9555 struct thread_info *thread = inferior_thread ();
f7e6eed5 9556
799a2abe
PA
9557 return (thread->priv != NULL
9558 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9559}
9560
9561/* The to_supports_stopped_by_sw_breakpoint method of target
9562 remote. */
9563
9564static int
9565remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9566{
9567 struct remote_state *rs = get_remote_state ();
9568
9569 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9570}
9571
9572/* The to_stopped_by_hw_breakpoint method of target remote. */
9573
9574static int
9575remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9576{
799a2abe 9577 struct thread_info *thread = inferior_thread ();
f7e6eed5 9578
799a2abe
PA
9579 return (thread->priv != NULL
9580 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9581}
9582
9583/* The to_supports_stopped_by_hw_breakpoint method of target
9584 remote. */
9585
9586static int
9587remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9588{
9589 struct remote_state *rs = get_remote_state ();
9590
9591 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9592}
9593
b9362cc7 9594static int
6a109b6b 9595remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9596{
799a2abe 9597 struct thread_info *thread = inferior_thread ();
ee154bee 9598
799a2abe
PA
9599 return (thread->priv != NULL
9600 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9601}
9602
4aa7a7f5
JJ
9603static int
9604remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9605{
799a2abe 9606 struct thread_info *thread = inferior_thread ();
a744cf53 9607
799a2abe
PA
9608 if (thread->priv != NULL
9609 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9610 {
799a2abe
PA
9611 *addr_p = thread->priv->watch_data_address;
9612 return 1;
4aa7a7f5
JJ
9613 }
9614
799a2abe 9615 return 0;
3c3bea1c
GS
9616}
9617
9618
9619static int
23a26771 9620remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9621 struct bp_target_info *bp_tgt)
3c3bea1c 9622{
0d5ed153 9623 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9624 struct remote_state *rs;
bba74b36 9625 char *p, *endbuf;
dd61ec5c 9626 char *message;
0d5ed153 9627 int bpsize;
802188a7 9628
c8189ed1 9629 /* The length field should be set to the size of a breakpoint
8181d85f 9630 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9631
0d5ed153 9632 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9633
4082afcc 9634 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9635 return -1;
2bc416ba 9636
28439a30
PA
9637 /* Make sure the remote is pointing at the right process, if
9638 necessary. */
9639 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9640 set_general_process ();
9641
4fff2411
JZ
9642 rs = get_remote_state ();
9643 p = rs->buf;
bba74b36 9644 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9645
96baa820
JM
9646 *(p++) = 'Z';
9647 *(p++) = '1';
9648 *(p++) = ',';
802188a7 9649
0d5ed153 9650 addr = remote_address_masked (addr);
96baa820 9651 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9652 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9653
efcc2da7 9654 if (remote_supports_cond_breakpoints (self))
bba74b36 9655 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9656
78eff0ec 9657 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9658 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9659
6d820c5c
DJ
9660 putpkt (rs->buf);
9661 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9662
6d820c5c 9663 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9664 {
9665 case PACKET_ERROR:
dd61ec5c
MW
9666 if (rs->buf[1] == '.')
9667 {
9668 message = strchr (rs->buf + 2, '.');
9669 if (message)
0316657e 9670 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9671 }
9672 return -1;
d471ea57
AC
9673 case PACKET_UNKNOWN:
9674 return -1;
9675 case PACKET_OK:
0d5ed153
MR
9676 bp_tgt->placed_address = addr;
9677 bp_tgt->placed_size = bpsize;
d471ea57
AC
9678 return 0;
9679 }
8e65ff28 9680 internal_error (__FILE__, __LINE__,
e2e0b3e5 9681 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9682}
9683
d471ea57 9684
802188a7 9685static int
a64dc96c 9686remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9687 struct bp_target_info *bp_tgt)
96baa820 9688{
8181d85f 9689 CORE_ADDR addr;
d01949b6 9690 struct remote_state *rs = get_remote_state ();
6d820c5c 9691 char *p = rs->buf;
bba74b36 9692 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9693
4082afcc 9694 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9695 return -1;
802188a7 9696
28439a30
PA
9697 /* Make sure the remote is pointing at the right process, if
9698 necessary. */
9699 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9700 set_general_process ();
9701
96baa820
JM
9702 *(p++) = 'z';
9703 *(p++) = '1';
9704 *(p++) = ',';
802188a7 9705
8181d85f 9706 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9707 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9708 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9709
6d820c5c
DJ
9710 putpkt (rs->buf);
9711 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9712
6d820c5c 9713 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9714 {
9715 case PACKET_ERROR:
9716 case PACKET_UNKNOWN:
9717 return -1;
9718 case PACKET_OK:
9719 return 0;
9720 }
8e65ff28 9721 internal_error (__FILE__, __LINE__,
e2e0b3e5 9722 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9723}
96baa820 9724
4a5e7a5b
PA
9725/* Verify memory using the "qCRC:" request. */
9726
9727static int
9728remote_verify_memory (struct target_ops *ops,
9729 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9730{
9731 struct remote_state *rs = get_remote_state ();
9732 unsigned long host_crc, target_crc;
9733 char *tmp;
9734
936d2992
PA
9735 /* It doesn't make sense to use qCRC if the remote target is
9736 connected but not running. */
9737 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9738 {
9739 enum packet_result result;
28439a30 9740
936d2992
PA
9741 /* Make sure the remote is pointing at the right process. */
9742 set_general_process ();
4a5e7a5b 9743
936d2992
PA
9744 /* FIXME: assumes lma can fit into long. */
9745 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9746 (long) lma, (long) size);
9747 putpkt (rs->buf);
4a5e7a5b 9748
936d2992
PA
9749 /* Be clever; compute the host_crc before waiting for target
9750 reply. */
9751 host_crc = xcrc32 (data, size, 0xffffffff);
9752
9753 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9754
936d2992
PA
9755 result = packet_ok (rs->buf,
9756 &remote_protocol_packets[PACKET_qCRC]);
9757 if (result == PACKET_ERROR)
9758 return -1;
9759 else if (result == PACKET_OK)
9760 {
9761 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9762 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9763
936d2992
PA
9764 return (host_crc == target_crc);
9765 }
9766 }
4a5e7a5b 9767
936d2992 9768 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9769}
9770
c906108c
SS
9771/* compare-sections command
9772
9773 With no arguments, compares each loadable section in the exec bfd
9774 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9775 Useful for verifying the image on the target against the exec file. */
e514a9d6 9776
c906108c 9777static void
fba45db2 9778compare_sections_command (char *args, int from_tty)
c906108c
SS
9779{
9780 asection *s;
c906108c 9781 struct cleanup *old_chain;
948f8e3d 9782 gdb_byte *sectdata;
ce359b09 9783 const char *sectname;
c906108c
SS
9784 bfd_size_type size;
9785 bfd_vma lma;
9786 int matched = 0;
9787 int mismatched = 0;
4a5e7a5b 9788 int res;
95cf3b38 9789 int read_only = 0;
c906108c
SS
9790
9791 if (!exec_bfd)
8a3fe4f8 9792 error (_("command cannot be used without an exec file"));
c906108c 9793
28439a30
PA
9794 /* Make sure the remote is pointing at the right process. */
9795 set_general_process ();
9796
95cf3b38
DT
9797 if (args != NULL && strcmp (args, "-r") == 0)
9798 {
9799 read_only = 1;
9800 args = NULL;
9801 }
9802
c5aa993b 9803 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9804 {
9805 if (!(s->flags & SEC_LOAD))
0df8b418 9806 continue; /* Skip non-loadable section. */
c906108c 9807
95cf3b38
DT
9808 if (read_only && (s->flags & SEC_READONLY) == 0)
9809 continue; /* Skip writeable sections */
9810
2c500098 9811 size = bfd_get_section_size (s);
c906108c 9812 if (size == 0)
0df8b418 9813 continue; /* Skip zero-length section. */
c906108c 9814
ce359b09 9815 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9816 if (args && strcmp (args, sectname) != 0)
0df8b418 9817 continue; /* Not the section selected by user. */
c906108c 9818
0df8b418 9819 matched = 1; /* Do this section. */
c906108c 9820 lma = s->lma;
c906108c 9821
224c3ddb 9822 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9823 old_chain = make_cleanup (xfree, sectdata);
c906108c 9824 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9825
4a5e7a5b
PA
9826 res = target_verify_memory (sectdata, lma, size);
9827
9828 if (res == -1)
5af949e3 9829 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9830 paddress (target_gdbarch (), lma),
9831 paddress (target_gdbarch (), lma + size));
c906108c 9832
5af949e3 9833 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9834 paddress (target_gdbarch (), lma),
9835 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9836 if (res)
c906108c
SS
9837 printf_filtered ("matched.\n");
9838 else
c5aa993b
JM
9839 {
9840 printf_filtered ("MIS-MATCHED!\n");
9841 mismatched++;
9842 }
c906108c
SS
9843
9844 do_cleanups (old_chain);
9845 }
9846 if (mismatched > 0)
936d2992 9847 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9848the loaded file\n"));
c906108c 9849 if (args && !matched)
a3f17187 9850 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9851}
9852
0e7f50da
UW
9853/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9854 into remote target. The number of bytes written to the remote
9855 target is returned, or -1 for error. */
9856
9b409511 9857static enum target_xfer_status
0e7f50da
UW
9858remote_write_qxfer (struct target_ops *ops, const char *object_name,
9859 const char *annex, const gdb_byte *writebuf,
9b409511 9860 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9861 struct packet_config *packet)
9862{
9863 int i, buf_len;
9864 ULONGEST n;
0e7f50da
UW
9865 struct remote_state *rs = get_remote_state ();
9866 int max_size = get_memory_write_packet_size ();
9867
9868 if (packet->support == PACKET_DISABLE)
2ed4b548 9869 return TARGET_XFER_E_IO;
0e7f50da
UW
9870
9871 /* Insert header. */
9872 i = snprintf (rs->buf, max_size,
9873 "qXfer:%s:write:%s:%s:",
9874 object_name, annex ? annex : "",
9875 phex_nz (offset, sizeof offset));
9876 max_size -= (i + 1);
9877
9878 /* Escape as much data as fits into rs->buf. */
9879 buf_len = remote_escape_output
124e13d9 9880 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9881
9882 if (putpkt_binary (rs->buf, i + buf_len) < 0
9883 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9884 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9885 return TARGET_XFER_E_IO;
0e7f50da
UW
9886
9887 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9888
9889 *xfered_len = n;
9890 return TARGET_XFER_OK;
0e7f50da
UW
9891}
9892
0876f84a
DJ
9893/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9894 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9895 number of bytes read is returned, or 0 for EOF, or -1 for error.
9896 The number of bytes read may be less than LEN without indicating an
9897 EOF. PACKET is checked and updated to indicate whether the remote
9898 target supports this object. */
9899
9b409511 9900static enum target_xfer_status
0876f84a
DJ
9901remote_read_qxfer (struct target_ops *ops, const char *object_name,
9902 const char *annex,
9903 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9904 ULONGEST *xfered_len,
0876f84a
DJ
9905 struct packet_config *packet)
9906{
0876f84a 9907 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9908 LONGEST i, n, packet_len;
9909
9910 if (packet->support == PACKET_DISABLE)
2ed4b548 9911 return TARGET_XFER_E_IO;
0876f84a
DJ
9912
9913 /* Check whether we've cached an end-of-object packet that matches
9914 this request. */
8e88304f 9915 if (rs->finished_object)
0876f84a 9916 {
8e88304f
TT
9917 if (strcmp (object_name, rs->finished_object) == 0
9918 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9919 && offset == rs->finished_offset)
9b409511
YQ
9920 return TARGET_XFER_EOF;
9921
0876f84a
DJ
9922
9923 /* Otherwise, we're now reading something different. Discard
9924 the cache. */
8e88304f
TT
9925 xfree (rs->finished_object);
9926 xfree (rs->finished_annex);
9927 rs->finished_object = NULL;
9928 rs->finished_annex = NULL;
0876f84a
DJ
9929 }
9930
9931 /* Request only enough to fit in a single packet. The actual data
9932 may not, since we don't know how much of it will need to be escaped;
9933 the target is free to respond with slightly less data. We subtract
9934 five to account for the response type and the protocol frame. */
9935 n = min (get_remote_packet_size () - 5, len);
9936 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9937 object_name, annex ? annex : "",
9938 phex_nz (offset, sizeof offset),
9939 phex_nz (n, sizeof n));
9940 i = putpkt (rs->buf);
9941 if (i < 0)
2ed4b548 9942 return TARGET_XFER_E_IO;
0876f84a
DJ
9943
9944 rs->buf[0] = '\0';
9945 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9946 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9947 return TARGET_XFER_E_IO;
0876f84a
DJ
9948
9949 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9950 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9951
9952 /* 'm' means there is (or at least might be) more data after this
9953 batch. That does not make sense unless there's at least one byte
9954 of data in this reply. */
9955 if (rs->buf[0] == 'm' && packet_len == 1)
9956 error (_("Remote qXfer reply contained no data."));
9957
9958 /* Got some data. */
bc20a4af
PA
9959 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9960 packet_len - 1, readbuf, n);
0876f84a
DJ
9961
9962 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9963 or possibly empty. If we have the final block of a non-empty
9964 object, record this fact to bypass a subsequent partial read. */
9965 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9966 {
8e88304f
TT
9967 rs->finished_object = xstrdup (object_name);
9968 rs->finished_annex = xstrdup (annex ? annex : "");
9969 rs->finished_offset = offset + i;
0876f84a
DJ
9970 }
9971
9b409511
YQ
9972 if (i == 0)
9973 return TARGET_XFER_EOF;
9974 else
9975 {
9976 *xfered_len = i;
9977 return TARGET_XFER_OK;
9978 }
0876f84a
DJ
9979}
9980
9b409511 9981static enum target_xfer_status
4b8a223f 9982remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9983 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9984 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9985 ULONGEST *xfered_len)
c906108c 9986{
82f73884 9987 struct remote_state *rs;
c906108c 9988 int i;
6d820c5c 9989 char *p2;
1e3ff5ad 9990 char query_type;
124e13d9 9991 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9992
e6e4e701 9993 set_remote_traceframe ();
82f73884
PA
9994 set_general_thread (inferior_ptid);
9995
9996 rs = get_remote_state ();
9997
b2182ed2 9998 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9999 if (object == TARGET_OBJECT_MEMORY)
10000 {
2d717e4f
DJ
10001 /* If the remote target is connected but not running, we should
10002 pass this request down to a lower stratum (e.g. the executable
10003 file). */
10004 if (!target_has_execution)
9b409511 10005 return TARGET_XFER_EOF;
2d717e4f 10006
21e3b9b9 10007 if (writebuf != NULL)
124e13d9
SM
10008 return remote_write_bytes (offset, writebuf, len, unit_size,
10009 xfered_len);
21e3b9b9 10010 else
124e13d9
SM
10011 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10012 xfered_len);
21e3b9b9
DJ
10013 }
10014
0df8b418 10015 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
10016 if (object == TARGET_OBJECT_SPU)
10017 {
10018 if (readbuf)
10019 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
10020 xfered_len, &remote_protocol_packets
10021 [PACKET_qXfer_spu_read]);
0e7f50da
UW
10022 else
10023 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
10024 xfered_len, &remote_protocol_packets
10025 [PACKET_qXfer_spu_write]);
0e7f50da
UW
10026 }
10027
4aa995e1
PA
10028 /* Handle extra signal info using qxfer packets. */
10029 if (object == TARGET_OBJECT_SIGNAL_INFO)
10030 {
10031 if (readbuf)
10032 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 10033 xfered_len, &remote_protocol_packets
4aa995e1
PA
10034 [PACKET_qXfer_siginfo_read]);
10035 else
3e43a32a 10036 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 10037 writebuf, offset, len, xfered_len,
4aa995e1
PA
10038 &remote_protocol_packets
10039 [PACKET_qXfer_siginfo_write]);
10040 }
10041
0fb4aa4b
PA
10042 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10043 {
10044 if (readbuf)
3e43a32a 10045 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 10046 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
10047 &remote_protocol_packets
10048 [PACKET_qXfer_statictrace_read]);
10049 else
2ed4b548 10050 return TARGET_XFER_E_IO;
0fb4aa4b
PA
10051 }
10052
a76d924d
DJ
10053 /* Only handle flash writes. */
10054 if (writebuf != NULL)
10055 {
10056 LONGEST xfered;
10057
10058 switch (object)
10059 {
10060 case TARGET_OBJECT_FLASH:
9b409511
YQ
10061 return remote_flash_write (ops, offset, len, xfered_len,
10062 writebuf);
a76d924d
DJ
10063
10064 default:
2ed4b548 10065 return TARGET_XFER_E_IO;
a76d924d
DJ
10066 }
10067 }
4b8a223f 10068
1e3ff5ad
AC
10069 /* Map pre-existing objects onto letters. DO NOT do this for new
10070 objects!!! Instead specify new query packets. */
10071 switch (object)
c906108c 10072 {
1e3ff5ad
AC
10073 case TARGET_OBJECT_AVR:
10074 query_type = 'R';
10075 break;
802188a7
RM
10076
10077 case TARGET_OBJECT_AUXV:
0876f84a
DJ
10078 gdb_assert (annex == NULL);
10079 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 10080 xfered_len,
0876f84a 10081 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10082
23181151
DJ
10083 case TARGET_OBJECT_AVAILABLE_FEATURES:
10084 return remote_read_qxfer
9b409511 10085 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10086 &remote_protocol_packets[PACKET_qXfer_features]);
10087
cfa9d6d9
DJ
10088 case TARGET_OBJECT_LIBRARIES:
10089 return remote_read_qxfer
9b409511 10090 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10091 &remote_protocol_packets[PACKET_qXfer_libraries]);
10092
2268b414
JK
10093 case TARGET_OBJECT_LIBRARIES_SVR4:
10094 return remote_read_qxfer
9b409511 10095 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10096 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10097
fd79ecee
DJ
10098 case TARGET_OBJECT_MEMORY_MAP:
10099 gdb_assert (annex == NULL);
10100 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 10101 xfered_len,
fd79ecee
DJ
10102 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10103
07e059b5
VP
10104 case TARGET_OBJECT_OSDATA:
10105 /* Should only get here if we're connected. */
5d93a237 10106 gdb_assert (rs->remote_desc);
07e059b5 10107 return remote_read_qxfer
9b409511 10108 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10109 &remote_protocol_packets[PACKET_qXfer_osdata]);
10110
dc146f7c
VP
10111 case TARGET_OBJECT_THREADS:
10112 gdb_assert (annex == NULL);
10113 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10114 xfered_len,
dc146f7c
VP
10115 &remote_protocol_packets[PACKET_qXfer_threads]);
10116
b3b9301e
PA
10117 case TARGET_OBJECT_TRACEFRAME_INFO:
10118 gdb_assert (annex == NULL);
10119 return remote_read_qxfer
9b409511 10120 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10121 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10122
10123 case TARGET_OBJECT_FDPIC:
10124 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10125 xfered_len,
78d85199 10126 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10127
10128 case TARGET_OBJECT_OPENVMS_UIB:
10129 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10130 xfered_len,
169081d0
TG
10131 &remote_protocol_packets[PACKET_qXfer_uib]);
10132
9accd112
MM
10133 case TARGET_OBJECT_BTRACE:
10134 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10135 xfered_len,
9accd112
MM
10136 &remote_protocol_packets[PACKET_qXfer_btrace]);
10137
f4abbc16
MM
10138 case TARGET_OBJECT_BTRACE_CONF:
10139 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10140 len, xfered_len,
10141 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10142
c78fa86a
GB
10143 case TARGET_OBJECT_EXEC_FILE:
10144 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10145 len, xfered_len,
10146 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10147
1e3ff5ad 10148 default:
2ed4b548 10149 return TARGET_XFER_E_IO;
c906108c
SS
10150 }
10151
0df8b418 10152 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10153 large enough let the caller deal with it. */
ea9c271d 10154 if (len < get_remote_packet_size ())
2ed4b548 10155 return TARGET_XFER_E_IO;
ea9c271d 10156 len = get_remote_packet_size ();
1e3ff5ad 10157
23860348 10158 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10159 if (!rs->remote_desc)
8a3fe4f8 10160 error (_("remote query is only available after target open"));
c906108c 10161
1e3ff5ad 10162 gdb_assert (annex != NULL);
4b8a223f 10163 gdb_assert (readbuf != NULL);
c906108c 10164
6d820c5c 10165 p2 = rs->buf;
c906108c
SS
10166 *p2++ = 'q';
10167 *p2++ = query_type;
10168
23860348
MS
10169 /* We used one buffer char for the remote protocol q command and
10170 another for the query type. As the remote protocol encapsulation
10171 uses 4 chars plus one extra in case we are debugging
10172 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10173 string. */
c906108c 10174 i = 0;
ea9c271d 10175 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10176 {
1e3ff5ad
AC
10177 /* Bad caller may have sent forbidden characters. */
10178 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10179 *p2++ = annex[i];
c906108c
SS
10180 i++;
10181 }
1e3ff5ad
AC
10182 *p2 = '\0';
10183 gdb_assert (annex[i] == '\0');
c906108c 10184
6d820c5c 10185 i = putpkt (rs->buf);
c5aa993b 10186 if (i < 0)
2ed4b548 10187 return TARGET_XFER_E_IO;
c906108c 10188
6d820c5c
DJ
10189 getpkt (&rs->buf, &rs->buf_size, 0);
10190 strcpy ((char *) readbuf, rs->buf);
c906108c 10191
9b409511
YQ
10192 *xfered_len = strlen ((char *) readbuf);
10193 return TARGET_XFER_OK;
c906108c
SS
10194}
10195
08388c79
DE
10196static int
10197remote_search_memory (struct target_ops* ops,
10198 CORE_ADDR start_addr, ULONGEST search_space_len,
10199 const gdb_byte *pattern, ULONGEST pattern_len,
10200 CORE_ADDR *found_addrp)
10201{
f5656ead 10202 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10203 struct remote_state *rs = get_remote_state ();
10204 int max_size = get_memory_write_packet_size ();
10205 struct packet_config *packet =
10206 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10207 /* Number of packet bytes used to encode the pattern;
10208 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10209 int escaped_pattern_len;
0df8b418 10210 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10211 int used_pattern_len;
10212 int i;
10213 int found;
10214 ULONGEST found_addr;
10215
10216 /* Don't go to the target if we don't have to.
10217 This is done before checking packet->support to avoid the possibility that
10218 a success for this edge case means the facility works in general. */
10219 if (pattern_len > search_space_len)
10220 return 0;
10221 if (pattern_len == 0)
10222 {
10223 *found_addrp = start_addr;
10224 return 1;
10225 }
10226
10227 /* If we already know the packet isn't supported, fall back to the simple
10228 way of searching memory. */
10229
4082afcc 10230 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10231 {
10232 /* Target doesn't provided special support, fall back and use the
10233 standard support (copy memory and do the search here). */
10234 return simple_search_memory (ops, start_addr, search_space_len,
10235 pattern, pattern_len, found_addrp);
10236 }
10237
28439a30
PA
10238 /* Make sure the remote is pointing at the right process. */
10239 set_general_process ();
10240
08388c79
DE
10241 /* Insert header. */
10242 i = snprintf (rs->buf, max_size,
10243 "qSearch:memory:%s;%s;",
5af949e3 10244 phex_nz (start_addr, addr_size),
08388c79
DE
10245 phex_nz (search_space_len, sizeof (search_space_len)));
10246 max_size -= (i + 1);
10247
10248 /* Escape as much data as fits into rs->buf. */
10249 escaped_pattern_len =
124e13d9 10250 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10251 &used_pattern_len, max_size);
10252
10253 /* Bail if the pattern is too large. */
10254 if (used_pattern_len != pattern_len)
9b20d036 10255 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10256
10257 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10258 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10259 || packet_ok (rs->buf, packet) != PACKET_OK)
10260 {
10261 /* The request may not have worked because the command is not
10262 supported. If so, fall back to the simple way. */
10263 if (packet->support == PACKET_DISABLE)
10264 {
10265 return simple_search_memory (ops, start_addr, search_space_len,
10266 pattern, pattern_len, found_addrp);
10267 }
10268 return -1;
10269 }
10270
10271 if (rs->buf[0] == '0')
10272 found = 0;
10273 else if (rs->buf[0] == '1')
10274 {
10275 found = 1;
10276 if (rs->buf[1] != ',')
10e0fa18 10277 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10278 unpack_varlen_hex (rs->buf + 2, &found_addr);
10279 *found_addrp = found_addr;
10280 }
10281 else
10e0fa18 10282 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10283
10284 return found;
10285}
10286
96baa820 10287static void
a30bf1f1 10288remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10289 struct ui_file *outbuf)
96baa820 10290{
d01949b6 10291 struct remote_state *rs = get_remote_state ();
2e9f7625 10292 char *p = rs->buf;
96baa820 10293
5d93a237 10294 if (!rs->remote_desc)
8a3fe4f8 10295 error (_("remote rcmd is only available after target open"));
96baa820 10296
23860348 10297 /* Send a NULL command across as an empty command. */
7be570e7
JM
10298 if (command == NULL)
10299 command = "";
10300
23860348 10301 /* The query prefix. */
2e9f7625
DJ
10302 strcpy (rs->buf, "qRcmd,");
10303 p = strchr (rs->buf, '\0');
96baa820 10304
3e43a32a
MS
10305 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10306 > get_remote_packet_size ())
8a3fe4f8 10307 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10308
23860348 10309 /* Encode the actual command. */
a30bf1f1 10310 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10311
6d820c5c 10312 if (putpkt (rs->buf) < 0)
8a3fe4f8 10313 error (_("Communication problem with target."));
96baa820
JM
10314
10315 /* get/display the response */
10316 while (1)
10317 {
2e9f7625
DJ
10318 char *buf;
10319
00bf0b85 10320 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10321 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10322 rs->buf[0] = '\0';
5b37825d
PW
10323 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10324 {
10325 /* Timeout. Continue to (try to) read responses.
10326 This is better than stopping with an error, assuming the stub
10327 is still executing the (long) monitor command.
10328 If needed, the user can interrupt gdb using C-c, obtaining
10329 an effect similar to stop on timeout. */
10330 continue;
10331 }
2e9f7625 10332 buf = rs->buf;
96baa820 10333 if (buf[0] == '\0')
8a3fe4f8 10334 error (_("Target does not support this command."));
96baa820
JM
10335 if (buf[0] == 'O' && buf[1] != 'K')
10336 {
23860348 10337 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10338 continue;
10339 }
10340 if (strcmp (buf, "OK") == 0)
10341 break;
7be570e7
JM
10342 if (strlen (buf) == 3 && buf[0] == 'E'
10343 && isdigit (buf[1]) && isdigit (buf[2]))
10344 {
8a3fe4f8 10345 error (_("Protocol error with Rcmd"));
7be570e7 10346 }
96baa820
JM
10347 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10348 {
10349 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10350
96baa820
JM
10351 fputc_unfiltered (c, outbuf);
10352 }
10353 break;
10354 }
10355}
10356
fd79ecee
DJ
10357static VEC(mem_region_s) *
10358remote_memory_map (struct target_ops *ops)
10359{
10360 VEC(mem_region_s) *result = NULL;
10361 char *text = target_read_stralloc (&current_target,
10362 TARGET_OBJECT_MEMORY_MAP, NULL);
10363
10364 if (text)
10365 {
10366 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10367
fd79ecee
DJ
10368 result = parse_memory_map (text);
10369 do_cleanups (back_to);
10370 }
10371
10372 return result;
10373}
10374
c906108c 10375static void
fba45db2 10376packet_command (char *args, int from_tty)
c906108c 10377{
d01949b6 10378 struct remote_state *rs = get_remote_state ();
c906108c 10379
5d93a237 10380 if (!rs->remote_desc)
8a3fe4f8 10381 error (_("command can only be used with remote target"));
c906108c 10382
c5aa993b 10383 if (!args)
8a3fe4f8 10384 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10385
10386 puts_filtered ("sending: ");
10387 print_packet (args);
10388 puts_filtered ("\n");
10389 putpkt (args);
10390
6d820c5c 10391 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10392 puts_filtered ("received: ");
6d820c5c 10393 print_packet (rs->buf);
c906108c
SS
10394 puts_filtered ("\n");
10395}
10396
10397#if 0
23860348 10398/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10399
a14ed312 10400static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10401
a14ed312 10402static void threadset_test_cmd (char *cmd, int tty);
c906108c 10403
a14ed312 10404static void threadalive_test (char *cmd, int tty);
c906108c 10405
a14ed312 10406static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10407
23860348 10408int get_and_display_threadinfo (threadref *ref);
c906108c 10409
a14ed312 10410static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10411
23860348 10412static int thread_display_step (threadref *ref, void *context);
c906108c 10413
a14ed312 10414static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10415
a14ed312 10416static void init_remote_threadtests (void);
c906108c 10417
23860348 10418#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10419
10420static void
fba45db2 10421threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10422{
10423 int sample_thread = SAMPLE_THREAD;
10424
a3f17187 10425 printf_filtered (_("Remote threadset test\n"));
79d7f229 10426 set_general_thread (sample_thread);
c906108c
SS
10427}
10428
10429
10430static void
fba45db2 10431threadalive_test (char *cmd, int tty)
c906108c
SS
10432{
10433 int sample_thread = SAMPLE_THREAD;
79d7f229 10434 int pid = ptid_get_pid (inferior_ptid);
ba348170 10435 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10436
79d7f229 10437 if (remote_thread_alive (ptid))
c906108c
SS
10438 printf_filtered ("PASS: Thread alive test\n");
10439 else
10440 printf_filtered ("FAIL: Thread alive test\n");
10441}
10442
23860348 10443void output_threadid (char *title, threadref *ref);
c906108c
SS
10444
10445void
fba45db2 10446output_threadid (char *title, threadref *ref)
c906108c
SS
10447{
10448 char hexid[20];
10449
23860348 10450 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10451 hexid[16] = 0;
10452 printf_filtered ("%s %s\n", title, (&hexid[0]));
10453}
10454
10455static void
fba45db2 10456threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10457{
10458 int startflag = 1;
10459 threadref nextthread;
10460 int done, result_count;
10461 threadref threadlist[3];
10462
10463 printf_filtered ("Remote Threadlist test\n");
10464 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10465 &result_count, &threadlist[0]))
10466 printf_filtered ("FAIL: threadlist test\n");
10467 else
10468 {
10469 threadref *scan = threadlist;
10470 threadref *limit = scan + result_count;
10471
10472 while (scan < limit)
10473 output_threadid (" thread ", scan++);
10474 }
10475}
10476
10477void
fba45db2 10478display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10479{
10480 output_threadid ("Threadid: ", &info->threadid);
10481 printf_filtered ("Name: %s\n ", info->shortname);
10482 printf_filtered ("State: %s\n", info->display);
10483 printf_filtered ("other: %s\n\n", info->more_display);
10484}
10485
10486int
fba45db2 10487get_and_display_threadinfo (threadref *ref)
c906108c
SS
10488{
10489 int result;
10490 int set;
10491 struct gdb_ext_thread_info threadinfo;
10492
10493 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10494 | TAG_MOREDISPLAY | TAG_DISPLAY;
10495 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10496 display_thread_info (&threadinfo);
10497 return result;
10498}
10499
10500static void
fba45db2 10501threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10502{
10503 int athread = SAMPLE_THREAD;
10504 threadref thread;
10505 int set;
10506
10507 int_to_threadref (&thread, athread);
10508 printf_filtered ("Remote Threadinfo test\n");
10509 if (!get_and_display_threadinfo (&thread))
10510 printf_filtered ("FAIL cannot get thread info\n");
10511}
10512
10513static int
fba45db2 10514thread_display_step (threadref *ref, void *context)
c906108c
SS
10515{
10516 /* output_threadid(" threadstep ",ref); *//* simple test */
10517 return get_and_display_threadinfo (ref);
10518}
10519
10520static void
fba45db2 10521threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10522{
10523 printf_filtered ("Remote Threadlist update test\n");
10524 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10525}
10526
10527static void
10528init_remote_threadtests (void)
10529{
3e43a32a
MS
10530 add_com ("tlist", class_obscure, threadlist_test_cmd,
10531 _("Fetch and print the remote list of "
10532 "thread identifiers, one pkt only"));
c906108c 10533 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10534 _("Fetch and display info about one thread"));
c906108c 10535 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10536 _("Test setting to a different thread"));
c906108c 10537 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10538 _("Iterate through updating all remote thread info"));
c906108c 10539 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10540 _(" Remote thread alive test "));
c906108c
SS
10541}
10542
10543#endif /* 0 */
10544
f3fb8c85
MS
10545/* Convert a thread ID to a string. Returns the string in a static
10546 buffer. */
10547
10548static char *
117de6a9 10549remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10550{
79d7f229 10551 static char buf[64];
82f73884 10552 struct remote_state *rs = get_remote_state ();
f3fb8c85 10553
7cee1e54
PA
10554 if (ptid_equal (ptid, null_ptid))
10555 return normal_pid_to_str (ptid);
10556 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10557 {
10558 /* Printing an inferior target id. */
10559
10560 /* When multi-process extensions are off, there's no way in the
10561 remote protocol to know the remote process id, if there's any
10562 at all. There's one exception --- when we're connected with
10563 target extended-remote, and we manually attached to a process
10564 with "attach PID". We don't record anywhere a flag that
10565 allows us to distinguish that case from the case of
10566 connecting with extended-remote and the stub already being
10567 attached to a process, and reporting yes to qAttached, hence
10568 no smart special casing here. */
10569 if (!remote_multi_process_p (rs))
10570 {
10571 xsnprintf (buf, sizeof buf, "Remote target");
10572 return buf;
10573 }
10574
10575 return normal_pid_to_str (ptid);
82f73884 10576 }
ecd0ada5 10577 else
79d7f229 10578 {
ecd0ada5
PA
10579 if (ptid_equal (magic_null_ptid, ptid))
10580 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 10581 else if (remote_multi_process_p (rs))
de0d863e
DB
10582 if (ptid_get_lwp (ptid) == 0)
10583 return normal_pid_to_str (ptid);
10584 else
10585 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10586 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10587 else
10588 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10589 ptid_get_lwp (ptid));
79d7f229
PA
10590 return buf;
10591 }
f3fb8c85
MS
10592}
10593
38691318
KB
10594/* Get the address of the thread local variable in OBJFILE which is
10595 stored at OFFSET within the thread local storage for thread PTID. */
10596
10597static CORE_ADDR
117de6a9
PA
10598remote_get_thread_local_address (struct target_ops *ops,
10599 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10600{
4082afcc 10601 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10602 {
10603 struct remote_state *rs = get_remote_state ();
6d820c5c 10604 char *p = rs->buf;
82f73884 10605 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10606 enum packet_result result;
38691318
KB
10607
10608 strcpy (p, "qGetTLSAddr:");
10609 p += strlen (p);
82f73884 10610 p = write_ptid (p, endp, ptid);
38691318
KB
10611 *p++ = ',';
10612 p += hexnumstr (p, offset);
10613 *p++ = ',';
10614 p += hexnumstr (p, lm);
10615 *p++ = '\0';
10616
6d820c5c
DJ
10617 putpkt (rs->buf);
10618 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10619 result = packet_ok (rs->buf,
10620 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10621 if (result == PACKET_OK)
38691318
KB
10622 {
10623 ULONGEST result;
10624
6d820c5c 10625 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10626 return result;
10627 }
571dd617 10628 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10629 throw_error (TLS_GENERIC_ERROR,
10630 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10631 else
109c3e39
AC
10632 throw_error (TLS_GENERIC_ERROR,
10633 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10634 }
10635 else
109c3e39
AC
10636 throw_error (TLS_GENERIC_ERROR,
10637 _("TLS not supported or disabled on this target"));
38691318
KB
10638 /* Not reached. */
10639 return 0;
10640}
10641
711e434b
PM
10642/* Provide thread local base, i.e. Thread Information Block address.
10643 Returns 1 if ptid is found and thread_local_base is non zero. */
10644
70221824 10645static int
bd7ae0f5 10646remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10647{
4082afcc 10648 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10649 {
10650 struct remote_state *rs = get_remote_state ();
10651 char *p = rs->buf;
10652 char *endp = rs->buf + get_remote_packet_size ();
10653 enum packet_result result;
10654
10655 strcpy (p, "qGetTIBAddr:");
10656 p += strlen (p);
10657 p = write_ptid (p, endp, ptid);
10658 *p++ = '\0';
10659
10660 putpkt (rs->buf);
10661 getpkt (&rs->buf, &rs->buf_size, 0);
10662 result = packet_ok (rs->buf,
10663 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10664 if (result == PACKET_OK)
10665 {
10666 ULONGEST result;
10667
10668 unpack_varlen_hex (rs->buf, &result);
10669 if (addr)
10670 *addr = (CORE_ADDR) result;
10671 return 1;
10672 }
10673 else if (result == PACKET_UNKNOWN)
10674 error (_("Remote target doesn't support qGetTIBAddr packet"));
10675 else
10676 error (_("Remote target failed to process qGetTIBAddr request"));
10677 }
10678 else
10679 error (_("qGetTIBAddr not supported or disabled on this target"));
10680 /* Not reached. */
10681 return 0;
10682}
10683
29709017
DJ
10684/* Support for inferring a target description based on the current
10685 architecture and the size of a 'g' packet. While the 'g' packet
10686 can have any size (since optional registers can be left off the
10687 end), some sizes are easily recognizable given knowledge of the
10688 approximate architecture. */
10689
10690struct remote_g_packet_guess
10691{
10692 int bytes;
10693 const struct target_desc *tdesc;
10694};
10695typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10696DEF_VEC_O(remote_g_packet_guess_s);
10697
10698struct remote_g_packet_data
10699{
10700 VEC(remote_g_packet_guess_s) *guesses;
10701};
10702
10703static struct gdbarch_data *remote_g_packet_data_handle;
10704
10705static void *
10706remote_g_packet_data_init (struct obstack *obstack)
10707{
10708 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10709}
10710
10711void
10712register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10713 const struct target_desc *tdesc)
10714{
10715 struct remote_g_packet_data *data
19ba03f4
SM
10716 = ((struct remote_g_packet_data *)
10717 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10718 struct remote_g_packet_guess new_guess, *guess;
10719 int ix;
10720
10721 gdb_assert (tdesc != NULL);
10722
10723 for (ix = 0;
10724 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10725 ix++)
10726 if (guess->bytes == bytes)
10727 internal_error (__FILE__, __LINE__,
9b20d036 10728 _("Duplicate g packet description added for size %d"),
29709017
DJ
10729 bytes);
10730
10731 new_guess.bytes = bytes;
10732 new_guess.tdesc = tdesc;
10733 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10734}
10735
d962ef82
DJ
10736/* Return 1 if remote_read_description would do anything on this target
10737 and architecture, 0 otherwise. */
10738
10739static int
10740remote_read_description_p (struct target_ops *target)
10741{
10742 struct remote_g_packet_data *data
19ba03f4
SM
10743 = ((struct remote_g_packet_data *)
10744 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10745
10746 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10747 return 1;
10748
10749 return 0;
10750}
10751
29709017
DJ
10752static const struct target_desc *
10753remote_read_description (struct target_ops *target)
10754{
10755 struct remote_g_packet_data *data
19ba03f4
SM
10756 = ((struct remote_g_packet_data *)
10757 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10758
d962ef82
DJ
10759 /* Do not try this during initial connection, when we do not know
10760 whether there is a running but stopped thread. */
10761 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10762 return target->beneath->to_read_description (target->beneath);
d962ef82 10763
29709017
DJ
10764 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10765 {
10766 struct remote_g_packet_guess *guess;
10767 int ix;
10768 int bytes = send_g_packet ();
10769
10770 for (ix = 0;
10771 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10772 ix++)
10773 if (guess->bytes == bytes)
10774 return guess->tdesc;
10775
10776 /* We discard the g packet. A minor optimization would be to
10777 hold on to it, and fill the register cache once we have selected
10778 an architecture, but it's too tricky to do safely. */
10779 }
10780
2117c711 10781 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10782}
10783
a6b151f1
DJ
10784/* Remote file transfer support. This is host-initiated I/O, not
10785 target-initiated; for target-initiated, see remote-fileio.c. */
10786
10787/* If *LEFT is at least the length of STRING, copy STRING to
10788 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10789 decrease *LEFT. Otherwise raise an error. */
10790
10791static void
10792remote_buffer_add_string (char **buffer, int *left, char *string)
10793{
10794 int len = strlen (string);
10795
10796 if (len > *left)
10797 error (_("Packet too long for target."));
10798
10799 memcpy (*buffer, string, len);
10800 *buffer += len;
10801 *left -= len;
10802
10803 /* NUL-terminate the buffer as a convenience, if there is
10804 room. */
10805 if (*left)
10806 **buffer = '\0';
10807}
10808
10809/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10810 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10811 decrease *LEFT. Otherwise raise an error. */
10812
10813static void
10814remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10815 int len)
10816{
10817 if (2 * len > *left)
10818 error (_("Packet too long for target."));
10819
10820 bin2hex (bytes, *buffer, len);
10821 *buffer += 2 * len;
10822 *left -= 2 * len;
10823
10824 /* NUL-terminate the buffer as a convenience, if there is
10825 room. */
10826 if (*left)
10827 **buffer = '\0';
10828}
10829
10830/* If *LEFT is large enough, convert VALUE to hex and add it to
10831 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10832 decrease *LEFT. Otherwise raise an error. */
10833
10834static void
10835remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10836{
10837 int len = hexnumlen (value);
10838
10839 if (len > *left)
10840 error (_("Packet too long for target."));
10841
10842 hexnumstr (*buffer, value);
10843 *buffer += len;
10844 *left -= len;
10845
10846 /* NUL-terminate the buffer as a convenience, if there is
10847 room. */
10848 if (*left)
10849 **buffer = '\0';
10850}
10851
10852/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10853 value, *REMOTE_ERRNO to the remote error number or zero if none
10854 was included, and *ATTACHMENT to point to the start of the annex
10855 if any. The length of the packet isn't needed here; there may
10856 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10857
10858 Return 0 if the packet could be parsed, -1 if it could not. If
10859 -1 is returned, the other variables may not be initialized. */
10860
10861static int
10862remote_hostio_parse_result (char *buffer, int *retcode,
10863 int *remote_errno, char **attachment)
10864{
10865 char *p, *p2;
10866
10867 *remote_errno = 0;
10868 *attachment = NULL;
10869
10870 if (buffer[0] != 'F')
10871 return -1;
10872
10873 errno = 0;
10874 *retcode = strtol (&buffer[1], &p, 16);
10875 if (errno != 0 || p == &buffer[1])
10876 return -1;
10877
10878 /* Check for ",errno". */
10879 if (*p == ',')
10880 {
10881 errno = 0;
10882 *remote_errno = strtol (p + 1, &p2, 16);
10883 if (errno != 0 || p + 1 == p2)
10884 return -1;
10885 p = p2;
10886 }
10887
10888 /* Check for ";attachment". If there is no attachment, the
10889 packet should end here. */
10890 if (*p == ';')
10891 {
10892 *attachment = p + 1;
10893 return 0;
10894 }
10895 else if (*p == '\0')
10896 return 0;
10897 else
10898 return -1;
10899}
10900
10901/* Send a prepared I/O packet to the target and read its response.
10902 The prepared packet is in the global RS->BUF before this function
10903 is called, and the answer is there when we return.
10904
10905 COMMAND_BYTES is the length of the request to send, which may include
10906 binary data. WHICH_PACKET is the packet configuration to check
10907 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10908 is set to the error number and -1 is returned. Otherwise the value
10909 returned by the function is returned.
10910
10911 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10912 attachment is expected; an error will be reported if there's a
10913 mismatch. If one is found, *ATTACHMENT will be set to point into
10914 the packet buffer and *ATTACHMENT_LEN will be set to the
10915 attachment's length. */
10916
10917static int
10918remote_hostio_send_command (int command_bytes, int which_packet,
10919 int *remote_errno, char **attachment,
10920 int *attachment_len)
10921{
10922 struct remote_state *rs = get_remote_state ();
10923 int ret, bytes_read;
10924 char *attachment_tmp;
10925
5d93a237 10926 if (!rs->remote_desc
4082afcc 10927 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10928 {
10929 *remote_errno = FILEIO_ENOSYS;
10930 return -1;
10931 }
10932
10933 putpkt_binary (rs->buf, command_bytes);
10934 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10935
10936 /* If it timed out, something is wrong. Don't try to parse the
10937 buffer. */
10938 if (bytes_read < 0)
10939 {
10940 *remote_errno = FILEIO_EINVAL;
10941 return -1;
10942 }
10943
10944 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10945 {
10946 case PACKET_ERROR:
10947 *remote_errno = FILEIO_EINVAL;
10948 return -1;
10949 case PACKET_UNKNOWN:
10950 *remote_errno = FILEIO_ENOSYS;
10951 return -1;
10952 case PACKET_OK:
10953 break;
10954 }
10955
10956 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10957 &attachment_tmp))
10958 {
10959 *remote_errno = FILEIO_EINVAL;
10960 return -1;
10961 }
10962
10963 /* Make sure we saw an attachment if and only if we expected one. */
10964 if ((attachment_tmp == NULL && attachment != NULL)
10965 || (attachment_tmp != NULL && attachment == NULL))
10966 {
10967 *remote_errno = FILEIO_EINVAL;
10968 return -1;
10969 }
10970
10971 /* If an attachment was found, it must point into the packet buffer;
10972 work out how many bytes there were. */
10973 if (attachment_tmp != NULL)
10974 {
10975 *attachment = attachment_tmp;
10976 *attachment_len = bytes_read - (*attachment - rs->buf);
10977 }
10978
10979 return ret;
10980}
10981
80152258
PA
10982/* Invalidate the readahead cache. */
10983
10984static void
10985readahead_cache_invalidate (void)
10986{
10987 struct remote_state *rs = get_remote_state ();
10988
10989 rs->readahead_cache.fd = -1;
10990}
10991
10992/* Invalidate the readahead cache if it is holding data for FD. */
10993
10994static void
10995readahead_cache_invalidate_fd (int fd)
10996{
10997 struct remote_state *rs = get_remote_state ();
10998
10999 if (rs->readahead_cache.fd == fd)
11000 rs->readahead_cache.fd = -1;
11001}
11002
15a201c8
GB
11003/* Set the filesystem remote_hostio functions that take FILENAME
11004 arguments will use. Return 0 on success, or -1 if an error
11005 occurs (and set *REMOTE_ERRNO). */
11006
11007static int
11008remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11009{
11010 struct remote_state *rs = get_remote_state ();
11011 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11012 char *p = rs->buf;
11013 int left = get_remote_packet_size () - 1;
11014 char arg[9];
11015 int ret;
11016
11017 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11018 return 0;
11019
11020 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11021 return 0;
11022
11023 remote_buffer_add_string (&p, &left, "vFile:setfs:");
11024
11025 xsnprintf (arg, sizeof (arg), "%x", required_pid);
11026 remote_buffer_add_string (&p, &left, arg);
11027
11028 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11029 remote_errno, NULL, NULL);
11030
11031 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11032 return 0;
11033
11034 if (ret == 0)
11035 rs->fs_pid = required_pid;
11036
11037 return ret;
11038}
11039
12e2a5fd 11040/* Implementation of to_fileio_open. */
a6b151f1
DJ
11041
11042static int
cd897586 11043remote_hostio_open (struct target_ops *self,
07c138c8 11044 struct inferior *inf, const char *filename,
4313b8c0
GB
11045 int flags, int mode, int warn_if_slow,
11046 int *remote_errno)
a6b151f1
DJ
11047{
11048 struct remote_state *rs = get_remote_state ();
11049 char *p = rs->buf;
11050 int left = get_remote_packet_size () - 1;
11051
4313b8c0
GB
11052 if (warn_if_slow)
11053 {
11054 static int warning_issued = 0;
11055
11056 printf_unfiltered (_("Reading %s from remote target...\n"),
11057 filename);
11058
11059 if (!warning_issued)
11060 {
11061 warning (_("File transfers from remote targets can be slow."
11062 " Use \"set sysroot\" to access files locally"
11063 " instead."));
11064 warning_issued = 1;
11065 }
11066 }
11067
15a201c8
GB
11068 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11069 return -1;
11070
a6b151f1
DJ
11071 remote_buffer_add_string (&p, &left, "vFile:open:");
11072
11073 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11074 strlen (filename));
11075 remote_buffer_add_string (&p, &left, ",");
11076
11077 remote_buffer_add_int (&p, &left, flags);
11078 remote_buffer_add_string (&p, &left, ",");
11079
11080 remote_buffer_add_int (&p, &left, mode);
11081
11082 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11083 remote_errno, NULL, NULL);
11084}
11085
12e2a5fd 11086/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11087
11088static int
0d866f62
TT
11089remote_hostio_pwrite (struct target_ops *self,
11090 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11091 ULONGEST offset, int *remote_errno)
11092{
11093 struct remote_state *rs = get_remote_state ();
11094 char *p = rs->buf;
11095 int left = get_remote_packet_size ();
11096 int out_len;
11097
80152258
PA
11098 readahead_cache_invalidate_fd (fd);
11099
a6b151f1
DJ
11100 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11101
11102 remote_buffer_add_int (&p, &left, fd);
11103 remote_buffer_add_string (&p, &left, ",");
11104
11105 remote_buffer_add_int (&p, &left, offset);
11106 remote_buffer_add_string (&p, &left, ",");
11107
124e13d9 11108 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11109 get_remote_packet_size () - (p - rs->buf));
11110
11111 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11112 remote_errno, NULL, NULL);
11113}
11114
80152258
PA
11115/* Helper for the implementation of to_fileio_pread. Read the file
11116 from the remote side with vFile:pread. */
a6b151f1
DJ
11117
11118static int
80152258
PA
11119remote_hostio_pread_vFile (struct target_ops *self,
11120 int fd, gdb_byte *read_buf, int len,
11121 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11122{
11123 struct remote_state *rs = get_remote_state ();
11124 char *p = rs->buf;
11125 char *attachment;
11126 int left = get_remote_packet_size ();
11127 int ret, attachment_len;
11128 int read_len;
11129
11130 remote_buffer_add_string (&p, &left, "vFile:pread:");
11131
11132 remote_buffer_add_int (&p, &left, fd);
11133 remote_buffer_add_string (&p, &left, ",");
11134
11135 remote_buffer_add_int (&p, &left, len);
11136 remote_buffer_add_string (&p, &left, ",");
11137
11138 remote_buffer_add_int (&p, &left, offset);
11139
11140 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11141 remote_errno, &attachment,
11142 &attachment_len);
11143
11144 if (ret < 0)
11145 return ret;
11146
bc20a4af 11147 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11148 read_buf, len);
11149 if (read_len != ret)
11150 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11151
11152 return ret;
11153}
11154
80152258
PA
11155/* Serve pread from the readahead cache. Returns number of bytes
11156 read, or 0 if the request can't be served from the cache. */
11157
11158static int
11159remote_hostio_pread_from_cache (struct remote_state *rs,
11160 int fd, gdb_byte *read_buf, size_t len,
11161 ULONGEST offset)
11162{
11163 struct readahead_cache *cache = &rs->readahead_cache;
11164
11165 if (cache->fd == fd
11166 && cache->offset <= offset
11167 && offset < cache->offset + cache->bufsize)
11168 {
11169 ULONGEST max = cache->offset + cache->bufsize;
11170
11171 if (offset + len > max)
11172 len = max - offset;
11173
11174 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11175 return len;
11176 }
11177
11178 return 0;
11179}
11180
11181/* Implementation of to_fileio_pread. */
11182
11183static int
11184remote_hostio_pread (struct target_ops *self,
11185 int fd, gdb_byte *read_buf, int len,
11186 ULONGEST offset, int *remote_errno)
11187{
11188 int ret;
11189 struct remote_state *rs = get_remote_state ();
11190 struct readahead_cache *cache = &rs->readahead_cache;
11191
11192 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11193 if (ret > 0)
11194 {
11195 cache->hit_count++;
11196
11197 if (remote_debug)
11198 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11199 pulongest (cache->hit_count));
11200 return ret;
11201 }
11202
11203 cache->miss_count++;
11204 if (remote_debug)
11205 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11206 pulongest (cache->miss_count));
11207
11208 cache->fd = fd;
11209 cache->offset = offset;
11210 cache->bufsize = get_remote_packet_size ();
224c3ddb 11211 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11212
11213 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11214 cache->offset, remote_errno);
11215 if (ret <= 0)
11216 {
11217 readahead_cache_invalidate_fd (fd);
11218 return ret;
11219 }
11220
11221 cache->bufsize = ret;
11222 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11223}
11224
12e2a5fd 11225/* Implementation of to_fileio_close. */
a6b151f1
DJ
11226
11227static int
df39ea25 11228remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11229{
11230 struct remote_state *rs = get_remote_state ();
11231 char *p = rs->buf;
11232 int left = get_remote_packet_size () - 1;
11233
80152258
PA
11234 readahead_cache_invalidate_fd (fd);
11235
a6b151f1
DJ
11236 remote_buffer_add_string (&p, &left, "vFile:close:");
11237
11238 remote_buffer_add_int (&p, &left, fd);
11239
11240 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11241 remote_errno, NULL, NULL);
11242}
11243
12e2a5fd 11244/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11245
11246static int
dbbca37d 11247remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11248 struct inferior *inf, const char *filename,
11249 int *remote_errno)
a6b151f1
DJ
11250{
11251 struct remote_state *rs = get_remote_state ();
11252 char *p = rs->buf;
11253 int left = get_remote_packet_size () - 1;
11254
15a201c8
GB
11255 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11256 return -1;
11257
a6b151f1
DJ
11258 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11259
11260 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11261 strlen (filename));
11262
11263 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11264 remote_errno, NULL, NULL);
11265}
11266
12e2a5fd 11267/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11268
11269static char *
fab5aa7c 11270remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11271 struct inferior *inf, const char *filename,
11272 int *remote_errno)
b9e7b9c3
UW
11273{
11274 struct remote_state *rs = get_remote_state ();
11275 char *p = rs->buf;
11276 char *attachment;
11277 int left = get_remote_packet_size ();
11278 int len, attachment_len;
11279 int read_len;
11280 char *ret;
11281
15a201c8
GB
11282 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11283 return NULL;
11284
b9e7b9c3
UW
11285 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11286
11287 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11288 strlen (filename));
11289
11290 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11291 remote_errno, &attachment,
11292 &attachment_len);
11293
11294 if (len < 0)
11295 return NULL;
11296
224c3ddb 11297 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11298
bc20a4af
PA
11299 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11300 (gdb_byte *) ret, len);
b9e7b9c3
UW
11301 if (read_len != len)
11302 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11303
11304 ret[len] = '\0';
11305 return ret;
11306}
11307
12e2a5fd 11308/* Implementation of to_fileio_fstat. */
0a93529c
GB
11309
11310static int
11311remote_hostio_fstat (struct target_ops *self,
11312 int fd, struct stat *st,
11313 int *remote_errno)
11314{
11315 struct remote_state *rs = get_remote_state ();
11316 char *p = rs->buf;
11317 int left = get_remote_packet_size ();
11318 int attachment_len, ret;
11319 char *attachment;
11320 struct fio_stat fst;
11321 int read_len;
11322
464b0089
GB
11323 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11324
11325 remote_buffer_add_int (&p, &left, fd);
11326
11327 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11328 remote_errno, &attachment,
11329 &attachment_len);
11330 if (ret < 0)
0a93529c 11331 {
464b0089
GB
11332 if (*remote_errno != FILEIO_ENOSYS)
11333 return ret;
11334
0a93529c
GB
11335 /* Strictly we should return -1, ENOSYS here, but when
11336 "set sysroot remote:" was implemented in August 2008
11337 BFD's need for a stat function was sidestepped with
11338 this hack. This was not remedied until March 2015
11339 so we retain the previous behavior to avoid breaking
11340 compatibility.
11341
11342 Note that the memset is a March 2015 addition; older
11343 GDBs set st_size *and nothing else* so the structure
11344 would have garbage in all other fields. This might
11345 break something but retaining the previous behavior
11346 here would be just too wrong. */
11347
11348 memset (st, 0, sizeof (struct stat));
11349 st->st_size = INT_MAX;
11350 return 0;
11351 }
11352
0a93529c
GB
11353 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11354 (gdb_byte *) &fst, sizeof (fst));
11355
11356 if (read_len != ret)
11357 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11358
11359 if (read_len != sizeof (fst))
11360 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11361 read_len, (int) sizeof (fst));
11362
11363 remote_fileio_to_host_stat (&fst, st);
11364
11365 return 0;
11366}
11367
12e2a5fd 11368/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11369
11370static int
11371remote_filesystem_is_local (struct target_ops *self)
11372{
11373 /* Valgrind GDB presents itself as a remote target but works
11374 on the local filesystem: it does not implement remote get
11375 and users are not expected to set a sysroot. To handle
11376 this case we treat the remote filesystem as local if the
11377 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11378 does not support vFile:open. */
a3be80c3 11379 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11380 {
11381 enum packet_support ps = packet_support (PACKET_vFile_open);
11382
11383 if (ps == PACKET_SUPPORT_UNKNOWN)
11384 {
11385 int fd, remote_errno;
11386
11387 /* Try opening a file to probe support. The supplied
11388 filename is irrelevant, we only care about whether
11389 the stub recognizes the packet or not. */
07c138c8 11390 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11391 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11392 &remote_errno);
11393
11394 if (fd >= 0)
11395 remote_hostio_close (self, fd, &remote_errno);
11396
11397 ps = packet_support (PACKET_vFile_open);
11398 }
11399
11400 if (ps == PACKET_DISABLE)
11401 {
11402 static int warning_issued = 0;
11403
11404 if (!warning_issued)
11405 {
11406 warning (_("remote target does not support file"
11407 " transfer, attempting to access files"
11408 " from local filesystem."));
11409 warning_issued = 1;
11410 }
11411
11412 return 1;
11413 }
11414 }
11415
11416 return 0;
11417}
11418
a6b151f1
DJ
11419static int
11420remote_fileio_errno_to_host (int errnum)
11421{
11422 switch (errnum)
11423 {
11424 case FILEIO_EPERM:
11425 return EPERM;
11426 case FILEIO_ENOENT:
11427 return ENOENT;
11428 case FILEIO_EINTR:
11429 return EINTR;
11430 case FILEIO_EIO:
11431 return EIO;
11432 case FILEIO_EBADF:
11433 return EBADF;
11434 case FILEIO_EACCES:
11435 return EACCES;
11436 case FILEIO_EFAULT:
11437 return EFAULT;
11438 case FILEIO_EBUSY:
11439 return EBUSY;
11440 case FILEIO_EEXIST:
11441 return EEXIST;
11442 case FILEIO_ENODEV:
11443 return ENODEV;
11444 case FILEIO_ENOTDIR:
11445 return ENOTDIR;
11446 case FILEIO_EISDIR:
11447 return EISDIR;
11448 case FILEIO_EINVAL:
11449 return EINVAL;
11450 case FILEIO_ENFILE:
11451 return ENFILE;
11452 case FILEIO_EMFILE:
11453 return EMFILE;
11454 case FILEIO_EFBIG:
11455 return EFBIG;
11456 case FILEIO_ENOSPC:
11457 return ENOSPC;
11458 case FILEIO_ESPIPE:
11459 return ESPIPE;
11460 case FILEIO_EROFS:
11461 return EROFS;
11462 case FILEIO_ENOSYS:
11463 return ENOSYS;
11464 case FILEIO_ENAMETOOLONG:
11465 return ENAMETOOLONG;
11466 }
11467 return -1;
11468}
11469
11470static char *
11471remote_hostio_error (int errnum)
11472{
11473 int host_error = remote_fileio_errno_to_host (errnum);
11474
11475 if (host_error == -1)
11476 error (_("Unknown remote I/O error %d"), errnum);
11477 else
11478 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11479}
11480
a6b151f1
DJ
11481static void
11482remote_hostio_close_cleanup (void *opaque)
11483{
11484 int fd = *(int *) opaque;
11485 int remote_errno;
11486
df39ea25 11487 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11488}
11489
11490void
11491remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11492{
11493 struct cleanup *back_to, *close_cleanup;
11494 int retcode, fd, remote_errno, bytes, io_size;
11495 FILE *file;
11496 gdb_byte *buffer;
11497 int bytes_in_buffer;
11498 int saw_eof;
11499 ULONGEST offset;
5d93a237 11500 struct remote_state *rs = get_remote_state ();
a6b151f1 11501
5d93a237 11502 if (!rs->remote_desc)
a6b151f1
DJ
11503 error (_("command can only be used with remote target"));
11504
614c279d 11505 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11506 if (file == NULL)
11507 perror_with_name (local_file);
7c8a8b04 11508 back_to = make_cleanup_fclose (file);
a6b151f1 11509
07c138c8 11510 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11511 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11512 | FILEIO_O_TRUNC),
4313b8c0 11513 0700, 0, &remote_errno);
a6b151f1
DJ
11514 if (fd == -1)
11515 remote_hostio_error (remote_errno);
11516
11517 /* Send up to this many bytes at once. They won't all fit in the
11518 remote packet limit, so we'll transfer slightly fewer. */
11519 io_size = get_remote_packet_size ();
224c3ddb 11520 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11521 make_cleanup (xfree, buffer);
11522
11523 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11524
11525 bytes_in_buffer = 0;
11526 saw_eof = 0;
11527 offset = 0;
11528 while (bytes_in_buffer || !saw_eof)
11529 {
11530 if (!saw_eof)
11531 {
3e43a32a
MS
11532 bytes = fread (buffer + bytes_in_buffer, 1,
11533 io_size - bytes_in_buffer,
a6b151f1
DJ
11534 file);
11535 if (bytes == 0)
11536 {
11537 if (ferror (file))
11538 error (_("Error reading %s."), local_file);
11539 else
11540 {
11541 /* EOF. Unless there is something still in the
11542 buffer from the last iteration, we are done. */
11543 saw_eof = 1;
11544 if (bytes_in_buffer == 0)
11545 break;
11546 }
11547 }
11548 }
11549 else
11550 bytes = 0;
11551
11552 bytes += bytes_in_buffer;
11553 bytes_in_buffer = 0;
11554
0d866f62
TT
11555 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11556 fd, buffer, bytes,
3e43a32a 11557 offset, &remote_errno);
a6b151f1
DJ
11558
11559 if (retcode < 0)
11560 remote_hostio_error (remote_errno);
11561 else if (retcode == 0)
11562 error (_("Remote write of %d bytes returned 0!"), bytes);
11563 else if (retcode < bytes)
11564 {
11565 /* Short write. Save the rest of the read data for the next
11566 write. */
11567 bytes_in_buffer = bytes - retcode;
11568 memmove (buffer, buffer + retcode, bytes_in_buffer);
11569 }
11570
11571 offset += retcode;
11572 }
11573
11574 discard_cleanups (close_cleanup);
df39ea25 11575 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11576 remote_hostio_error (remote_errno);
11577
11578 if (from_tty)
11579 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11580 do_cleanups (back_to);
11581}
11582
11583void
11584remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11585{
11586 struct cleanup *back_to, *close_cleanup;
cea39f65 11587 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11588 FILE *file;
11589 gdb_byte *buffer;
11590 ULONGEST offset;
5d93a237 11591 struct remote_state *rs = get_remote_state ();
a6b151f1 11592
5d93a237 11593 if (!rs->remote_desc)
a6b151f1
DJ
11594 error (_("command can only be used with remote target"));
11595
07c138c8 11596 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11597 remote_file, FILEIO_O_RDONLY, 0, 0,
11598 &remote_errno);
a6b151f1
DJ
11599 if (fd == -1)
11600 remote_hostio_error (remote_errno);
11601
614c279d 11602 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11603 if (file == NULL)
11604 perror_with_name (local_file);
7c8a8b04 11605 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11606
11607 /* Send up to this many bytes at once. They won't all fit in the
11608 remote packet limit, so we'll transfer slightly fewer. */
11609 io_size = get_remote_packet_size ();
224c3ddb 11610 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11611 make_cleanup (xfree, buffer);
11612
11613 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11614
11615 offset = 0;
11616 while (1)
11617 {
a3be983c
TT
11618 bytes = remote_hostio_pread (find_target_at (process_stratum),
11619 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11620 if (bytes == 0)
11621 /* Success, but no bytes, means end-of-file. */
11622 break;
11623 if (bytes == -1)
11624 remote_hostio_error (remote_errno);
11625
11626 offset += bytes;
11627
11628 bytes = fwrite (buffer, 1, bytes, file);
11629 if (bytes == 0)
11630 perror_with_name (local_file);
11631 }
11632
11633 discard_cleanups (close_cleanup);
df39ea25 11634 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11635 remote_hostio_error (remote_errno);
11636
11637 if (from_tty)
11638 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11639 do_cleanups (back_to);
11640}
11641
11642void
11643remote_file_delete (const char *remote_file, int from_tty)
11644{
11645 int retcode, remote_errno;
5d93a237 11646 struct remote_state *rs = get_remote_state ();
a6b151f1 11647
5d93a237 11648 if (!rs->remote_desc)
a6b151f1
DJ
11649 error (_("command can only be used with remote target"));
11650
dbbca37d 11651 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11652 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11653 if (retcode == -1)
11654 remote_hostio_error (remote_errno);
11655
11656 if (from_tty)
11657 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11658}
11659
11660static void
11661remote_put_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 put"));
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 put"));
11673
11674 remote_file_put (argv[0], argv[1], from_tty);
11675
11676 do_cleanups (back_to);
11677}
11678
11679static void
11680remote_get_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 get"));
11687
11688 argv = gdb_buildargv (args);
a6b151f1
DJ
11689 back_to = make_cleanup_freeargv (argv);
11690 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11691 error (_("Invalid parameters to remote get"));
11692
11693 remote_file_get (argv[0], argv[1], from_tty);
11694
11695 do_cleanups (back_to);
11696}
11697
11698static void
11699remote_delete_command (char *args, int from_tty)
11700{
11701 struct cleanup *back_to;
11702 char **argv;
11703
d1a41061
PP
11704 if (args == NULL)
11705 error_no_arg (_("file to delete"));
11706
11707 argv = gdb_buildargv (args);
a6b151f1
DJ
11708 back_to = make_cleanup_freeargv (argv);
11709 if (argv[0] == NULL || argv[1] != NULL)
11710 error (_("Invalid parameters to remote delete"));
11711
11712 remote_file_delete (argv[0], from_tty);
11713
11714 do_cleanups (back_to);
11715}
11716
11717static void
11718remote_command (char *args, int from_tty)
11719{
635c7e8a 11720 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11721}
11722
b2175913 11723static int
19db3e69 11724remote_can_execute_reverse (struct target_ops *self)
b2175913 11725{
4082afcc
PA
11726 if (packet_support (PACKET_bs) == PACKET_ENABLE
11727 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11728 return 1;
11729 else
11730 return 0;
b2175913
MS
11731}
11732
74531fed 11733static int
2a9a2795 11734remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11735{
11736 return 1;
11737}
11738
03583c20 11739static int
2bfc0540 11740remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11741{
11742 /* Only supported in extended mode. */
11743 return 0;
11744}
11745
8a305172 11746static int
86ce2668 11747remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11748{
11749 struct remote_state *rs = get_remote_state ();
a744cf53 11750
8020350c 11751 return remote_multi_process_p (rs);
8a305172
PA
11752}
11753
70221824 11754static int
782b2b07
SS
11755remote_supports_cond_tracepoints (void)
11756{
4082afcc 11757 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11758}
11759
3788aec7 11760static int
efcc2da7 11761remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11762{
4082afcc 11763 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11764}
11765
70221824 11766static int
7a697b8d
SS
11767remote_supports_fast_tracepoints (void)
11768{
4082afcc 11769 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11770}
11771
0fb4aa4b
PA
11772static int
11773remote_supports_static_tracepoints (void)
11774{
4082afcc 11775 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11776}
11777
1e4d1764
YQ
11778static int
11779remote_supports_install_in_trace (void)
11780{
4082afcc 11781 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11782}
11783
d248b706 11784static int
7d178d6a 11785remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11786{
4082afcc
PA
11787 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11788 == PACKET_ENABLE);
d248b706
KY
11789}
11790
3065dfb6 11791static int
6de37a3a 11792remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11793{
4082afcc 11794 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11795}
11796
d3ce09f5 11797static int
78eff0ec 11798remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11799{
4082afcc 11800 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11801}
11802
35b1e5cc 11803static void
ecae04e1 11804remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11805{
11806 putpkt ("QTinit");
11807 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11808 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11809 error (_("Target does not support this command."));
11810}
11811
11812static void free_actions_list (char **actions_list);
11813static void free_actions_list_cleanup_wrapper (void *);
11814static void
11815free_actions_list_cleanup_wrapper (void *al)
11816{
19ba03f4 11817 free_actions_list ((char **) al);
35b1e5cc
SS
11818}
11819
11820static void
11821free_actions_list (char **actions_list)
11822{
11823 int ndx;
11824
11825 if (actions_list == 0)
11826 return;
11827
11828 for (ndx = 0; actions_list[ndx]; ndx++)
11829 xfree (actions_list[ndx]);
11830
11831 xfree (actions_list);
11832}
11833
409873ef
SS
11834/* Recursive routine to walk through command list including loops, and
11835 download packets for each command. */
11836
11837static void
11838remote_download_command_source (int num, ULONGEST addr,
11839 struct command_line *cmds)
11840{
11841 struct remote_state *rs = get_remote_state ();
11842 struct command_line *cmd;
11843
11844 for (cmd = cmds; cmd; cmd = cmd->next)
11845 {
0df8b418 11846 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11847 strcpy (rs->buf, "QTDPsrc:");
11848 encode_source_string (num, addr, "cmd", cmd->line,
11849 rs->buf + strlen (rs->buf),
11850 rs->buf_size - strlen (rs->buf));
11851 putpkt (rs->buf);
11852 remote_get_noisy_reply (&target_buf, &target_buf_size);
11853 if (strcmp (target_buf, "OK"))
11854 warning (_("Target does not support source download."));
11855
11856 if (cmd->control_type == while_control
11857 || cmd->control_type == while_stepping_control)
11858 {
11859 remote_download_command_source (num, addr, *cmd->body_list);
11860
0df8b418 11861 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11862 strcpy (rs->buf, "QTDPsrc:");
11863 encode_source_string (num, addr, "cmd", "end",
11864 rs->buf + strlen (rs->buf),
11865 rs->buf_size - strlen (rs->buf));
11866 putpkt (rs->buf);
11867 remote_get_noisy_reply (&target_buf, &target_buf_size);
11868 if (strcmp (target_buf, "OK"))
11869 warning (_("Target does not support source download."));
11870 }
11871 }
11872}
11873
35b1e5cc 11874static void
548f7808 11875remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11876{
bba74b36 11877#define BUF_SIZE 2048
e8ba3115 11878
35b1e5cc 11879 CORE_ADDR tpaddr;
409873ef 11880 char addrbuf[40];
bba74b36 11881 char buf[BUF_SIZE];
35b1e5cc
SS
11882 char **tdp_actions;
11883 char **stepping_actions;
11884 int ndx;
11885 struct cleanup *old_chain = NULL;
11886 struct agent_expr *aexpr;
11887 struct cleanup *aexpr_chain = NULL;
11888 char *pkt;
e8ba3115 11889 struct breakpoint *b = loc->owner;
d9b3f62e 11890 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11891
dc673c81 11892 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11893 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11894 tdp_actions);
11895 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11896 stepping_actions);
11897
11898 tpaddr = loc->address;
11899 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11900 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11901 addrbuf, /* address */
11902 (b->enable_state == bp_enabled ? 'E' : 'D'),
11903 t->step_count, t->pass_count);
e8ba3115
YQ
11904 /* Fast tracepoints are mostly handled by the target, but we can
11905 tell the target how big of an instruction block should be moved
11906 around. */
11907 if (b->type == bp_fast_tracepoint)
11908 {
11909 /* Only test for support at download time; we may not know
11910 target capabilities at definition time. */
11911 if (remote_supports_fast_tracepoints ())
35b1e5cc 11912 {
6b940e6a
PL
11913 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11914 NULL))
bba74b36 11915 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11916 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11917 else
e8ba3115
YQ
11918 /* If it passed validation at definition but fails now,
11919 something is very wrong. */
11920 internal_error (__FILE__, __LINE__,
11921 _("Fast tracepoint not "
11922 "valid during download"));
35b1e5cc 11923 }
e8ba3115
YQ
11924 else
11925 /* Fast tracepoints are functionally identical to regular
11926 tracepoints, so don't take lack of support as a reason to
11927 give up on the trace run. */
11928 warning (_("Target does not support fast tracepoints, "
11929 "downloading %d as regular tracepoint"), b->number);
11930 }
11931 else if (b->type == bp_static_tracepoint)
11932 {
11933 /* Only test for support at download time; we may not know
11934 target capabilities at definition time. */
11935 if (remote_supports_static_tracepoints ())
0fb4aa4b 11936 {
e8ba3115 11937 struct static_tracepoint_marker marker;
0fb4aa4b 11938
e8ba3115
YQ
11939 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11940 strcat (buf, ":S");
0fb4aa4b 11941 else
e8ba3115 11942 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11943 }
e8ba3115
YQ
11944 else
11945 /* Fast tracepoints are functionally identical to regular
11946 tracepoints, so don't take lack of support as a reason
11947 to give up on the trace run. */
11948 error (_("Target does not support static tracepoints"));
11949 }
11950 /* If the tracepoint has a conditional, make it into an agent
11951 expression and append to the definition. */
11952 if (loc->cond)
11953 {
11954 /* Only test support at download time, we may not know target
11955 capabilities at definition time. */
11956 if (remote_supports_cond_tracepoints ())
35b1e5cc 11957 {
e8ba3115
YQ
11958 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11959 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11960 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11961 aexpr->len);
e8ba3115
YQ
11962 pkt = buf + strlen (buf);
11963 for (ndx = 0; ndx < aexpr->len; ++ndx)
11964 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11965 *pkt = '\0';
11966 do_cleanups (aexpr_chain);
35b1e5cc 11967 }
e8ba3115
YQ
11968 else
11969 warning (_("Target does not support conditional tracepoints, "
11970 "ignoring tp %d cond"), b->number);
11971 }
35b1e5cc 11972
d9b3f62e 11973 if (b->commands || *default_collect)
e8ba3115
YQ
11974 strcat (buf, "-");
11975 putpkt (buf);
11976 remote_get_noisy_reply (&target_buf, &target_buf_size);
11977 if (strcmp (target_buf, "OK"))
11978 error (_("Target does not support tracepoints."));
35b1e5cc 11979
e8ba3115
YQ
11980 /* do_single_steps (t); */
11981 if (tdp_actions)
11982 {
11983 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11984 {
e8ba3115 11985 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11986 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11987 b->number, addrbuf, /* address */
11988 tdp_actions[ndx],
11989 ((tdp_actions[ndx + 1] || stepping_actions)
11990 ? '-' : 0));
e8ba3115
YQ
11991 putpkt (buf);
11992 remote_get_noisy_reply (&target_buf,
11993 &target_buf_size);
11994 if (strcmp (target_buf, "OK"))
11995 error (_("Error on target while setting tracepoints."));
35b1e5cc 11996 }
e8ba3115
YQ
11997 }
11998 if (stepping_actions)
11999 {
12000 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 12001 {
e8ba3115 12002 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
12003 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12004 b->number, addrbuf, /* address */
12005 ((ndx == 0) ? "S" : ""),
12006 stepping_actions[ndx],
12007 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
12008 putpkt (buf);
12009 remote_get_noisy_reply (&target_buf,
12010 &target_buf_size);
12011 if (strcmp (target_buf, "OK"))
12012 error (_("Error on target while setting tracepoints."));
35b1e5cc 12013 }
e8ba3115 12014 }
409873ef 12015
4082afcc 12016 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 12017 {
f00aae0f 12018 if (b->location != NULL)
409873ef 12019 {
e8ba3115 12020 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
12021 encode_source_string (b->number, loc->address, "at",
12022 event_location_to_string (b->location),
12023 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
12024 putpkt (buf);
12025 remote_get_noisy_reply (&target_buf, &target_buf_size);
12026 if (strcmp (target_buf, "OK"))
12027 warning (_("Target does not support source download."));
409873ef 12028 }
e8ba3115
YQ
12029 if (b->cond_string)
12030 {
12031 strcpy (buf, "QTDPsrc:");
12032 encode_source_string (b->number, loc->address,
12033 "cond", b->cond_string, buf + strlen (buf),
12034 2048 - strlen (buf));
12035 putpkt (buf);
12036 remote_get_noisy_reply (&target_buf, &target_buf_size);
12037 if (strcmp (target_buf, "OK"))
12038 warning (_("Target does not support source download."));
12039 }
12040 remote_download_command_source (b->number, loc->address,
12041 breakpoint_commands (b));
35b1e5cc 12042 }
e8ba3115
YQ
12043
12044 do_cleanups (old_chain);
35b1e5cc
SS
12045}
12046
1e4d1764 12047static int
a52a8357 12048remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 12049{
1e51243a
PA
12050 struct remote_state *rs = get_remote_state ();
12051 struct trace_status *ts;
12052 int status;
12053
12054 /* Don't try to install tracepoints until we've relocated our
12055 symbols, and fetched and merged the target's tracepoint list with
12056 ours. */
12057 if (rs->starting_up)
12058 return 0;
12059
12060 ts = current_trace_status ();
8bd200f1 12061 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
12062
12063 if (status == -1 || !ts->running_known || !ts->running)
12064 return 0;
12065
12066 /* If we are in a tracing experiment, but remote stub doesn't support
12067 installing tracepoint in trace, we have to return. */
12068 if (!remote_supports_install_in_trace ())
12069 return 0;
12070
12071 return 1;
12072}
12073
12074
35b1e5cc 12075static void
559d2b81
TT
12076remote_download_trace_state_variable (struct target_ops *self,
12077 struct trace_state_variable *tsv)
35b1e5cc
SS
12078{
12079 struct remote_state *rs = get_remote_state ();
00bf0b85 12080 char *p;
35b1e5cc 12081
bba74b36
YQ
12082 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12083 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12084 tsv->builtin);
00bf0b85
SS
12085 p = rs->buf + strlen (rs->buf);
12086 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12087 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 12088 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 12089 *p++ = '\0';
35b1e5cc
SS
12090 putpkt (rs->buf);
12091 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12092 if (*target_buf == '\0')
12093 error (_("Target does not support this command."));
12094 if (strcmp (target_buf, "OK") != 0)
12095 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12096}
12097
d248b706 12098static void
46670d57
TT
12099remote_enable_tracepoint (struct target_ops *self,
12100 struct bp_location *location)
d248b706
KY
12101{
12102 struct remote_state *rs = get_remote_state ();
12103 char addr_buf[40];
12104
12105 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12106 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12107 location->owner->number, addr_buf);
d248b706
KY
12108 putpkt (rs->buf);
12109 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12110 if (*rs->buf == '\0')
12111 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12112 if (strcmp (rs->buf, "OK") != 0)
12113 error (_("Error on target while enabling tracepoint."));
12114}
12115
12116static void
780b049c
TT
12117remote_disable_tracepoint (struct target_ops *self,
12118 struct bp_location *location)
d248b706
KY
12119{
12120 struct remote_state *rs = get_remote_state ();
12121 char addr_buf[40];
12122
12123 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12124 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12125 location->owner->number, addr_buf);
d248b706
KY
12126 putpkt (rs->buf);
12127 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12128 if (*rs->buf == '\0')
12129 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12130 if (strcmp (rs->buf, "OK") != 0)
12131 error (_("Error on target while disabling tracepoint."));
12132}
12133
35b1e5cc 12134static void
583f9a86 12135remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12136{
12137 asection *s;
81b9b86e 12138 bfd *abfd = NULL;
35b1e5cc 12139 bfd_size_type size;
608bcef2 12140 bfd_vma vma;
35b1e5cc 12141 int anysecs = 0;
c2fa21f1 12142 int offset = 0;
35b1e5cc
SS
12143
12144 if (!exec_bfd)
12145 return; /* No information to give. */
12146
12147 strcpy (target_buf, "QTro");
9779ab84 12148 offset = strlen (target_buf);
35b1e5cc
SS
12149 for (s = exec_bfd->sections; s; s = s->next)
12150 {
12151 char tmp1[40], tmp2[40];
c2fa21f1 12152 int sec_length;
35b1e5cc
SS
12153
12154 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12155 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12156 (s->flags & SEC_READONLY) == 0)
12157 continue;
12158
12159 anysecs = 1;
81b9b86e 12160 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12161 size = bfd_get_section_size (s);
608bcef2
HZ
12162 sprintf_vma (tmp1, vma);
12163 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12164 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12165 if (offset + sec_length + 1 > target_buf_size)
12166 {
4082afcc 12167 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12168 warning (_("\
c2fa21f1
HZ
12169Too many sections for read-only sections definition packet."));
12170 break;
12171 }
bba74b36
YQ
12172 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12173 tmp1, tmp2);
c2fa21f1 12174 offset += sec_length;
35b1e5cc
SS
12175 }
12176 if (anysecs)
12177 {
12178 putpkt (target_buf);
12179 getpkt (&target_buf, &target_buf_size, 0);
12180 }
12181}
12182
12183static void
e2d1aae3 12184remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12185{
12186 putpkt ("QTStart");
12187 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12188 if (*target_buf == '\0')
12189 error (_("Target does not support this command."));
12190 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12191 error (_("Bogus reply from target: %s"), target_buf);
12192}
12193
12194static int
8bd200f1 12195remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12196{
953b98d1 12197 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12198 char *p = NULL;
0df8b418 12199 /* FIXME we need to get register block size some other way. */
00bf0b85 12200 extern int trace_regblock_size;
bd3eecc3
PA
12201 enum packet_result result;
12202
4082afcc 12203 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12204 return -1;
a744cf53 12205
00bf0b85
SS
12206 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12207
049dc89b
JK
12208 putpkt ("qTStatus");
12209
492d29ea 12210 TRY
67f41397
JK
12211 {
12212 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12213 }
492d29ea 12214 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12215 {
598d3636
JK
12216 if (ex.error != TARGET_CLOSE_ERROR)
12217 {
12218 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12219 return -1;
12220 }
12221 throw_exception (ex);
67f41397 12222 }
492d29ea 12223 END_CATCH
00bf0b85 12224
bd3eecc3
PA
12225 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12226
00bf0b85 12227 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12228 if (result == PACKET_UNKNOWN)
00bf0b85 12229 return -1;
35b1e5cc 12230
00bf0b85 12231 /* We're working with a live target. */
f5911ea1 12232 ts->filename = NULL;
00bf0b85 12233
00bf0b85 12234 if (*p++ != 'T')
35b1e5cc
SS
12235 error (_("Bogus trace status reply from target: %s"), target_buf);
12236
84cebc4a
YQ
12237 /* Function 'parse_trace_status' sets default value of each field of
12238 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12239 parse_trace_status (p, ts);
12240
12241 return ts->running;
35b1e5cc
SS
12242}
12243
70221824 12244static void
db90e85c 12245remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12246 struct uploaded_tp *utp)
12247{
12248 struct remote_state *rs = get_remote_state ();
f196051f
SS
12249 char *reply;
12250 struct bp_location *loc;
12251 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12252 size_t size = get_remote_packet_size ();
f196051f
SS
12253
12254 if (tp)
12255 {
12256 tp->base.hit_count = 0;
12257 tp->traceframe_usage = 0;
12258 for (loc = tp->base.loc; loc; loc = loc->next)
12259 {
12260 /* If the tracepoint was never downloaded, don't go asking for
12261 any status. */
12262 if (tp->number_on_target == 0)
12263 continue;
bba74b36
YQ
12264 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12265 phex_nz (loc->address, 0));
f196051f
SS
12266 putpkt (rs->buf);
12267 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12268 if (reply && *reply)
12269 {
12270 if (*reply == 'V')
12271 parse_tracepoint_status (reply + 1, bp, utp);
12272 }
12273 }
12274 }
12275 else if (utp)
12276 {
12277 utp->hit_count = 0;
12278 utp->traceframe_usage = 0;
bba74b36
YQ
12279 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12280 phex_nz (utp->addr, 0));
f196051f
SS
12281 putpkt (rs->buf);
12282 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12283 if (reply && *reply)
12284 {
12285 if (*reply == 'V')
12286 parse_tracepoint_status (reply + 1, bp, utp);
12287 }
12288 }
12289}
12290
35b1e5cc 12291static void
74499f1b 12292remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12293{
12294 putpkt ("QTStop");
12295 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12296 if (*target_buf == '\0')
12297 error (_("Target does not support this command."));
12298 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12299 error (_("Bogus reply from target: %s"), target_buf);
12300}
12301
12302static int
bd4c6793
TT
12303remote_trace_find (struct target_ops *self,
12304 enum trace_find_type type, int num,
cc5925ad 12305 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12306 int *tpp)
12307{
12308 struct remote_state *rs = get_remote_state ();
bba74b36 12309 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12310 char *p, *reply;
12311 int target_frameno = -1, target_tracept = -1;
12312
e6e4e701
PA
12313 /* Lookups other than by absolute frame number depend on the current
12314 trace selected, so make sure it is correct on the remote end
12315 first. */
12316 if (type != tfind_number)
12317 set_remote_traceframe ();
12318
35b1e5cc
SS
12319 p = rs->buf;
12320 strcpy (p, "QTFrame:");
12321 p = strchr (p, '\0');
12322 switch (type)
12323 {
12324 case tfind_number:
bba74b36 12325 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12326 break;
12327 case tfind_pc:
bba74b36 12328 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12329 break;
12330 case tfind_tp:
bba74b36 12331 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12332 break;
12333 case tfind_range:
bba74b36
YQ
12334 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12335 phex_nz (addr2, 0));
35b1e5cc
SS
12336 break;
12337 case tfind_outside:
bba74b36
YQ
12338 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12339 phex_nz (addr2, 0));
35b1e5cc
SS
12340 break;
12341 default:
9b20d036 12342 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12343 }
12344
12345 putpkt (rs->buf);
2f65bcb7 12346 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12347 if (*reply == '\0')
12348 error (_("Target does not support this command."));
35b1e5cc
SS
12349
12350 while (reply && *reply)
12351 switch (*reply)
12352 {
12353 case 'F':
f197e0f1
VP
12354 p = ++reply;
12355 target_frameno = (int) strtol (p, &reply, 16);
12356 if (reply == p)
12357 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12358 /* Don't update our remote traceframe number cache on failure
12359 to select a remote traceframe. */
f197e0f1
VP
12360 if (target_frameno == -1)
12361 return -1;
35b1e5cc
SS
12362 break;
12363 case 'T':
f197e0f1
VP
12364 p = ++reply;
12365 target_tracept = (int) strtol (p, &reply, 16);
12366 if (reply == p)
12367 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12368 break;
12369 case 'O': /* "OK"? */
12370 if (reply[1] == 'K' && reply[2] == '\0')
12371 reply += 2;
12372 else
12373 error (_("Bogus reply from target: %s"), reply);
12374 break;
12375 default:
12376 error (_("Bogus reply from target: %s"), reply);
12377 }
12378 if (tpp)
12379 *tpp = target_tracept;
e6e4e701 12380
262e1174 12381 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12382 return target_frameno;
12383}
12384
12385static int
4011015b
TT
12386remote_get_trace_state_variable_value (struct target_ops *self,
12387 int tsvnum, LONGEST *val)
35b1e5cc
SS
12388{
12389 struct remote_state *rs = get_remote_state ();
12390 char *reply;
12391 ULONGEST uval;
12392
e6e4e701
PA
12393 set_remote_traceframe ();
12394
bba74b36 12395 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12396 putpkt (rs->buf);
12397 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12398 if (reply && *reply)
12399 {
12400 if (*reply == 'V')
12401 {
12402 unpack_varlen_hex (reply + 1, &uval);
12403 *val = (LONGEST) uval;
12404 return 1;
12405 }
12406 }
12407 return 0;
12408}
12409
00bf0b85 12410static int
dc3decaf 12411remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12412{
12413 struct remote_state *rs = get_remote_state ();
12414 char *p, *reply;
12415
12416 p = rs->buf;
12417 strcpy (p, "QTSave:");
12418 p += strlen (p);
12419 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12420 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12421 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12422 *p++ = '\0';
12423 putpkt (rs->buf);
ad91cd99 12424 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12425 if (*reply == '\0')
ad91cd99
PA
12426 error (_("Target does not support this command."));
12427 if (strcmp (reply, "OK") != 0)
12428 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12429 return 0;
12430}
12431
12432/* This is basically a memory transfer, but needs to be its own packet
12433 because we don't know how the target actually organizes its trace
12434 memory, plus we want to be able to ask for as much as possible, but
12435 not be unhappy if we don't get as much as we ask for. */
12436
12437static LONGEST
88ee6f45
TT
12438remote_get_raw_trace_data (struct target_ops *self,
12439 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12440{
12441 struct remote_state *rs = get_remote_state ();
12442 char *reply;
12443 char *p;
12444 int rslt;
12445
12446 p = rs->buf;
12447 strcpy (p, "qTBuffer:");
12448 p += strlen (p);
12449 p += hexnumstr (p, offset);
12450 *p++ = ',';
12451 p += hexnumstr (p, len);
12452 *p++ = '\0';
12453
12454 putpkt (rs->buf);
12455 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12456 if (reply && *reply)
12457 {
12458 /* 'l' by itself means we're at the end of the buffer and
12459 there is nothing more to get. */
12460 if (*reply == 'l')
12461 return 0;
12462
12463 /* Convert the reply into binary. Limit the number of bytes to
12464 convert according to our passed-in buffer size, rather than
12465 what was returned in the packet; if the target is
12466 unexpectedly generous and gives us a bigger reply than we
12467 asked for, we don't want to crash. */
12468 rslt = hex2bin (target_buf, buf, len);
12469 return rslt;
12470 }
12471
12472 /* Something went wrong, flag as an error. */
12473 return -1;
12474}
12475
35b1e5cc 12476static void
37b25738 12477remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12478{
12479 struct remote_state *rs = get_remote_state ();
12480
4082afcc 12481 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12482 {
ad91cd99
PA
12483 char *reply;
12484
bba74b36 12485 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12486 putpkt (rs->buf);
ad91cd99
PA
12487 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12488 if (*reply == '\0')
33da3f1c 12489 error (_("Target does not support this command."));
ad91cd99
PA
12490 if (strcmp (reply, "OK") != 0)
12491 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12492 }
12493 else if (val)
12494 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12495}
12496
dc146f7c
VP
12497static int
12498remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12499{
12500 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12501
fe978cb0
PA
12502 if (info && info->priv)
12503 return info->priv->core;
dc146f7c
VP
12504 return -1;
12505}
12506
4daf5ac0 12507static void
736d5b1f 12508remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12509{
12510 struct remote_state *rs = get_remote_state ();
ad91cd99 12511 char *reply;
4daf5ac0 12512
bba74b36 12513 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12514 putpkt (rs->buf);
ad91cd99
PA
12515 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12516 if (*reply == '\0')
4daf5ac0 12517 error (_("Target does not support this command."));
ad91cd99
PA
12518 if (strcmp (reply, "OK") != 0)
12519 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12520}
12521
b3b9301e 12522static struct traceframe_info *
a893e81f 12523remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12524{
12525 char *text;
12526
12527 text = target_read_stralloc (&current_target,
12528 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12529 if (text != NULL)
12530 {
12531 struct traceframe_info *info;
12532 struct cleanup *back_to = make_cleanup (xfree, text);
12533
12534 info = parse_traceframe_info (text);
12535 do_cleanups (back_to);
12536 return info;
12537 }
12538
12539 return NULL;
12540}
12541
405f8e94
SS
12542/* Handle the qTMinFTPILen packet. Returns the minimum length of
12543 instruction on which a fast tracepoint may be placed. Returns -1
12544 if the packet is not supported, and 0 if the minimum instruction
12545 length is unknown. */
12546
12547static int
0e67620a 12548remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12549{
12550 struct remote_state *rs = get_remote_state ();
12551 char *reply;
12552
e886a173
PA
12553 /* If we're not debugging a process yet, the IPA can't be
12554 loaded. */
12555 if (!target_has_execution)
12556 return 0;
12557
12558 /* Make sure the remote is pointing at the right process. */
12559 set_general_process ();
12560
bba74b36 12561 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12562 putpkt (rs->buf);
12563 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12564 if (*reply == '\0')
12565 return -1;
12566 else
12567 {
12568 ULONGEST min_insn_len;
12569
12570 unpack_varlen_hex (reply, &min_insn_len);
12571
12572 return (int) min_insn_len;
12573 }
12574}
12575
f6f899bf 12576static void
4da384be 12577remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12578{
4082afcc 12579 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12580 {
12581 struct remote_state *rs = get_remote_state ();
12582 char *buf = rs->buf;
12583 char *endbuf = rs->buf + get_remote_packet_size ();
12584 enum packet_result result;
12585
12586 gdb_assert (val >= 0 || val == -1);
12587 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12588 /* Send -1 as literal "-1" to avoid host size dependency. */
12589 if (val < 0)
12590 {
12591 *buf++ = '-';
12592 buf += hexnumstr (buf, (ULONGEST) -val);
12593 }
12594 else
12595 buf += hexnumstr (buf, (ULONGEST) val);
12596
12597 putpkt (rs->buf);
12598 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12599 result = packet_ok (rs->buf,
12600 &remote_protocol_packets[PACKET_QTBuffer_size]);
12601
12602 if (result != PACKET_OK)
12603 warning (_("Bogus reply from target: %s"), rs->buf);
12604 }
12605}
12606
f196051f 12607static int
d9e68a2c
TT
12608remote_set_trace_notes (struct target_ops *self,
12609 const char *user, const char *notes,
ca623f82 12610 const char *stop_notes)
f196051f
SS
12611{
12612 struct remote_state *rs = get_remote_state ();
12613 char *reply;
12614 char *buf = rs->buf;
12615 char *endbuf = rs->buf + get_remote_packet_size ();
12616 int nbytes;
12617
12618 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12619 if (user)
12620 {
12621 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12622 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12623 buf += 2 * nbytes;
12624 *buf++ = ';';
12625 }
12626 if (notes)
12627 {
12628 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12629 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12630 buf += 2 * nbytes;
12631 *buf++ = ';';
12632 }
12633 if (stop_notes)
12634 {
12635 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12636 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12637 buf += 2 * nbytes;
12638 *buf++ = ';';
12639 }
12640 /* Ensure the buffer is terminated. */
12641 *buf = '\0';
12642
12643 putpkt (rs->buf);
12644 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12645 if (*reply == '\0')
12646 return 0;
12647
12648 if (strcmp (reply, "OK") != 0)
12649 error (_("Bogus reply from target: %s"), reply);
12650
12651 return 1;
12652}
12653
d1feda86 12654static int
2c152180 12655remote_use_agent (struct target_ops *self, int use)
d1feda86 12656{
4082afcc 12657 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12658 {
12659 struct remote_state *rs = get_remote_state ();
12660
12661 /* If the stub supports QAgent. */
bba74b36 12662 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12663 putpkt (rs->buf);
12664 getpkt (&rs->buf, &rs->buf_size, 0);
12665
12666 if (strcmp (rs->buf, "OK") == 0)
12667 {
12668 use_agent = use;
12669 return 1;
12670 }
12671 }
12672
12673 return 0;
12674}
12675
12676static int
fe38f897 12677remote_can_use_agent (struct target_ops *self)
d1feda86 12678{
4082afcc 12679 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12680}
12681
9accd112
MM
12682struct btrace_target_info
12683{
12684 /* The ptid of the traced thread. */
12685 ptid_t ptid;
f4abbc16
MM
12686
12687 /* The obtained branch trace configuration. */
12688 struct btrace_config conf;
9accd112
MM
12689};
12690
f4abbc16
MM
12691/* Reset our idea of our target's btrace configuration. */
12692
12693static void
12694remote_btrace_reset (void)
12695{
12696 struct remote_state *rs = get_remote_state ();
12697
12698 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12699}
12700
9accd112
MM
12701/* Check whether the target supports branch tracing. */
12702
12703static int
043c3577 12704remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12705{
4082afcc 12706 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12707 return 0;
4082afcc 12708 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12709 return 0;
12710
043c3577
MM
12711 switch (format)
12712 {
12713 case BTRACE_FORMAT_NONE:
12714 return 0;
12715
12716 case BTRACE_FORMAT_BTS:
12717 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12718
12719 case BTRACE_FORMAT_PT:
12720 /* The trace is decoded on the host. Even if our target supports it,
12721 we still need to have libipt to decode the trace. */
12722#if defined (HAVE_LIBIPT)
12723 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12724#else /* !defined (HAVE_LIBIPT) */
12725 return 0;
12726#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12727 }
12728
12729 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12730}
12731
f4abbc16
MM
12732/* Synchronize the configuration with the target. */
12733
12734static void
12735btrace_sync_conf (const struct btrace_config *conf)
12736{
d33501a5
MM
12737 struct packet_config *packet;
12738 struct remote_state *rs;
12739 char *buf, *pos, *endbuf;
12740
12741 rs = get_remote_state ();
12742 buf = rs->buf;
12743 endbuf = buf + get_remote_packet_size ();
12744
12745 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12746 if (packet_config_support (packet) == PACKET_ENABLE
12747 && conf->bts.size != rs->btrace_config.bts.size)
12748 {
12749 pos = buf;
12750 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12751 conf->bts.size);
12752
12753 putpkt (buf);
12754 getpkt (&buf, &rs->buf_size, 0);
12755
12756 if (packet_ok (buf, packet) == PACKET_ERROR)
12757 {
12758 if (buf[0] == 'E' && buf[1] == '.')
12759 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12760 else
12761 error (_("Failed to configure the BTS buffer size."));
12762 }
12763
12764 rs->btrace_config.bts.size = conf->bts.size;
12765 }
b20a6524
MM
12766
12767 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12768 if (packet_config_support (packet) == PACKET_ENABLE
12769 && conf->pt.size != rs->btrace_config.pt.size)
12770 {
12771 pos = buf;
12772 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12773 conf->pt.size);
12774
12775 putpkt (buf);
12776 getpkt (&buf, &rs->buf_size, 0);
12777
12778 if (packet_ok (buf, packet) == PACKET_ERROR)
12779 {
12780 if (buf[0] == 'E' && buf[1] == '.')
12781 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12782 else
12783 error (_("Failed to configure the trace buffer size."));
12784 }
12785
12786 rs->btrace_config.pt.size = conf->pt.size;
12787 }
f4abbc16
MM
12788}
12789
12790/* Read the current thread's btrace configuration from the target and
12791 store it into CONF. */
12792
12793static void
12794btrace_read_config (struct btrace_config *conf)
12795{
12796 char *xml;
12797
12798 xml = target_read_stralloc (&current_target,
b20a6524 12799 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12800 if (xml != NULL)
12801 {
12802 struct cleanup *cleanup;
12803
12804 cleanup = make_cleanup (xfree, xml);
12805 parse_xml_btrace_conf (conf, xml);
12806 do_cleanups (cleanup);
12807 }
12808}
12809
9accd112
MM
12810/* Enable branch tracing. */
12811
12812static struct btrace_target_info *
f4abbc16
MM
12813remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12814 const struct btrace_config *conf)
9accd112
MM
12815{
12816 struct btrace_target_info *tinfo = NULL;
b20a6524 12817 struct packet_config *packet = NULL;
9accd112
MM
12818 struct remote_state *rs = get_remote_state ();
12819 char *buf = rs->buf;
12820 char *endbuf = rs->buf + get_remote_packet_size ();
12821
b20a6524
MM
12822 switch (conf->format)
12823 {
12824 case BTRACE_FORMAT_BTS:
12825 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12826 break;
12827
12828 case BTRACE_FORMAT_PT:
12829 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12830 break;
12831 }
12832
12833 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12834 error (_("Target does not support branch tracing."));
12835
f4abbc16
MM
12836 btrace_sync_conf (conf);
12837
9accd112
MM
12838 set_general_thread (ptid);
12839
12840 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12841 putpkt (rs->buf);
12842 getpkt (&rs->buf, &rs->buf_size, 0);
12843
12844 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12845 {
12846 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12847 error (_("Could not enable branch tracing for %s: %s"),
12848 target_pid_to_str (ptid), rs->buf + 2);
12849 else
12850 error (_("Could not enable branch tracing for %s."),
12851 target_pid_to_str (ptid));
12852 }
12853
8d749320 12854 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12855 tinfo->ptid = ptid;
12856
f4abbc16
MM
12857 /* If we fail to read the configuration, we lose some information, but the
12858 tracing itself is not impacted. */
492d29ea
PA
12859 TRY
12860 {
12861 btrace_read_config (&tinfo->conf);
12862 }
12863 CATCH (err, RETURN_MASK_ERROR)
12864 {
12865 if (err.message != NULL)
12866 warning ("%s", err.message);
12867 }
12868 END_CATCH
f4abbc16 12869
9accd112
MM
12870 return tinfo;
12871}
12872
12873/* Disable branch tracing. */
12874
12875static void
25e95349
TT
12876remote_disable_btrace (struct target_ops *self,
12877 struct btrace_target_info *tinfo)
9accd112
MM
12878{
12879 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12880 struct remote_state *rs = get_remote_state ();
12881 char *buf = rs->buf;
12882 char *endbuf = rs->buf + get_remote_packet_size ();
12883
4082afcc 12884 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12885 error (_("Target does not support branch tracing."));
12886
12887 set_general_thread (tinfo->ptid);
12888
12889 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12890 putpkt (rs->buf);
12891 getpkt (&rs->buf, &rs->buf_size, 0);
12892
12893 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12894 {
12895 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12896 error (_("Could not disable branch tracing for %s: %s"),
12897 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12898 else
12899 error (_("Could not disable branch tracing for %s."),
12900 target_pid_to_str (tinfo->ptid));
12901 }
12902
12903 xfree (tinfo);
12904}
12905
12906/* Teardown branch tracing. */
12907
12908static void
1777056d
TT
12909remote_teardown_btrace (struct target_ops *self,
12910 struct btrace_target_info *tinfo)
9accd112
MM
12911{
12912 /* We must not talk to the target during teardown. */
12913 xfree (tinfo);
12914}
12915
12916/* Read the branch trace. */
12917
969c39fb 12918static enum btrace_error
39c49f83 12919remote_read_btrace (struct target_ops *self,
734b0e4b 12920 struct btrace_data *btrace,
969c39fb 12921 struct btrace_target_info *tinfo,
9accd112
MM
12922 enum btrace_read_type type)
12923{
12924 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12925 struct remote_state *rs = get_remote_state ();
969c39fb 12926 struct cleanup *cleanup;
9accd112
MM
12927 const char *annex;
12928 char *xml;
12929
4082afcc 12930 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12931 error (_("Target does not support branch tracing."));
12932
12933#if !defined(HAVE_LIBEXPAT)
12934 error (_("Cannot process branch tracing result. XML parsing not supported."));
12935#endif
12936
12937 switch (type)
12938 {
864089d2 12939 case BTRACE_READ_ALL:
9accd112
MM
12940 annex = "all";
12941 break;
864089d2 12942 case BTRACE_READ_NEW:
9accd112
MM
12943 annex = "new";
12944 break;
969c39fb
MM
12945 case BTRACE_READ_DELTA:
12946 annex = "delta";
12947 break;
9accd112
MM
12948 default:
12949 internal_error (__FILE__, __LINE__,
12950 _("Bad branch tracing read type: %u."),
12951 (unsigned int) type);
12952 }
12953
12954 xml = target_read_stralloc (&current_target,
b20a6524 12955 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12956 if (xml == NULL)
12957 return BTRACE_ERR_UNKNOWN;
9accd112 12958
969c39fb 12959 cleanup = make_cleanup (xfree, xml);
734b0e4b 12960 parse_xml_btrace (btrace, xml);
969c39fb 12961 do_cleanups (cleanup);
9accd112 12962
969c39fb 12963 return BTRACE_ERR_NONE;
9accd112
MM
12964}
12965
f4abbc16
MM
12966static const struct btrace_config *
12967remote_btrace_conf (struct target_ops *self,
12968 const struct btrace_target_info *tinfo)
12969{
12970 return &tinfo->conf;
12971}
12972
ced63ec0 12973static int
5436ff03 12974remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12975{
4082afcc
PA
12976 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12977 == PACKET_ENABLE);
ced63ec0
GB
12978}
12979
9dd130a0
TT
12980/* Implementation of to_load. */
12981
12982static void
9cbe5fff 12983remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12984{
12985 generic_load (name, from_tty);
12986}
12987
c78fa86a
GB
12988/* Accepts an integer PID; returns a string representing a file that
12989 can be opened on the remote side to get the symbols for the child
12990 process. Returns NULL if the operation is not supported. */
12991
12992static char *
12993remote_pid_to_exec_file (struct target_ops *self, int pid)
12994{
12995 static char *filename = NULL;
835205d0
GB
12996 struct inferior *inf;
12997 char *annex = NULL;
c78fa86a
GB
12998
12999 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13000 return NULL;
13001
13002 if (filename != NULL)
13003 xfree (filename);
13004
835205d0
GB
13005 inf = find_inferior_pid (pid);
13006 if (inf == NULL)
13007 internal_error (__FILE__, __LINE__,
13008 _("not currently attached to process %d"), pid);
13009
13010 if (!inf->fake_pid_p)
13011 {
13012 const int annex_size = 9;
13013
224c3ddb 13014 annex = (char *) alloca (annex_size);
835205d0
GB
13015 xsnprintf (annex, annex_size, "%x", pid);
13016 }
13017
c78fa86a
GB
13018 filename = target_read_stralloc (&current_target,
13019 TARGET_OBJECT_EXEC_FILE, annex);
13020
13021 return filename;
13022}
13023
750ce8d1
YQ
13024/* Implement the to_can_do_single_step target_ops method. */
13025
13026static int
13027remote_can_do_single_step (struct target_ops *ops)
13028{
13029 /* We can only tell whether target supports single step or not by
13030 supported s and S vCont actions if the stub supports vContSupported
13031 feature. If the stub doesn't support vContSupported feature,
13032 we have conservatively to think target doesn't supports single
13033 step. */
13034 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13035 {
13036 struct remote_state *rs = get_remote_state ();
13037
13038 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13039 remote_vcont_probe (rs);
13040
13041 return rs->supports_vCont.s && rs->supports_vCont.S;
13042 }
13043 else
13044 return 0;
13045}
13046
c906108c 13047static void
fba45db2 13048init_remote_ops (void)
c906108c 13049{
c5aa993b 13050 remote_ops.to_shortname = "remote";
c906108c 13051 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 13052 remote_ops.to_doc =
c906108c 13053 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
13054Specify the serial device it is connected to\n\
13055(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
13056 remote_ops.to_open = remote_open;
13057 remote_ops.to_close = remote_close;
c906108c 13058 remote_ops.to_detach = remote_detach;
6ad8ae5c 13059 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 13060 remote_ops.to_resume = remote_resume;
c906108c
SS
13061 remote_ops.to_wait = remote_wait;
13062 remote_ops.to_fetch_registers = remote_fetch_registers;
13063 remote_ops.to_store_registers = remote_store_registers;
13064 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 13065 remote_ops.to_files_info = remote_files_info;
c906108c
SS
13066 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13067 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
13068 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13069 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13070 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13071 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
13072 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13073 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
13074 remote_ops.to_watchpoint_addr_within_range =
13075 remote_watchpoint_addr_within_range;
3c3bea1c
GS
13076 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13077 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13078 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
13079 remote_ops.to_region_ok_for_hw_watchpoint
13080 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
13081 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13082 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 13083 remote_ops.to_kill = remote_kill;
9dd130a0 13084 remote_ops.to_load = remote_load;
c906108c 13085 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 13086 remote_ops.to_pass_signals = remote_pass_signals;
82075af2 13087 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
9b224c5e 13088 remote_ops.to_program_signals = remote_program_signals;
c906108c 13089 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 13090 remote_ops.to_thread_name = remote_thread_name;
e8032dde 13091 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 13092 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 13093 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 13094 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 13095 remote_ops.to_stop = remote_stop;
bfedc46a 13096 remote_ops.to_interrupt = remote_interrupt;
abc56d60 13097 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
4b8a223f 13098 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 13099 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 13100 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 13101 remote_ops.to_log_command = serial_log_command;
38691318 13102 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 13103 remote_ops.to_stratum = process_stratum;
c35b1492
PA
13104 remote_ops.to_has_all_memory = default_child_has_all_memory;
13105 remote_ops.to_has_memory = default_child_has_memory;
13106 remote_ops.to_has_stack = default_child_has_stack;
13107 remote_ops.to_has_registers = default_child_has_registers;
13108 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 13109 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13110 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13111 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13112 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13113 remote_ops.to_flash_erase = remote_flash_erase;
13114 remote_ops.to_flash_done = remote_flash_done;
29709017 13115 remote_ops.to_read_description = remote_read_description;
08388c79 13116 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13117 remote_ops.to_can_async_p = remote_can_async_p;
13118 remote_ops.to_is_async_p = remote_is_async_p;
13119 remote_ops.to_async = remote_async;
65706a29 13120 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13121 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13122 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13123 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13124 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13125 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13126 remote_ops.to_supports_disable_randomization
13127 = remote_supports_disable_randomization;
4bd7dc42 13128 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13129 remote_ops.to_fileio_open = remote_hostio_open;
13130 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13131 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13132 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13133 remote_ops.to_fileio_close = remote_hostio_close;
13134 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13135 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13136 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13137 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13138 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13139 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13140 remote_ops.to_trace_init = remote_trace_init;
13141 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13142 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13143 remote_ops.to_download_trace_state_variable
13144 = remote_download_trace_state_variable;
d248b706
KY
13145 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13146 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13147 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13148 remote_ops.to_trace_start = remote_trace_start;
13149 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13150 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13151 remote_ops.to_trace_stop = remote_trace_stop;
13152 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13153 remote_ops.to_get_trace_state_variable_value
13154 = remote_get_trace_state_variable_value;
00bf0b85
SS
13155 remote_ops.to_save_trace_data = remote_save_trace_data;
13156 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13157 remote_ops.to_upload_trace_state_variables
13158 = remote_upload_trace_state_variables;
00bf0b85 13159 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13160 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13161 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13162 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13163 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13164 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13165 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13166 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13167 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13168 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13169 remote_ops.to_static_tracepoint_marker_at
13170 = remote_static_tracepoint_marker_at;
13171 remote_ops.to_static_tracepoint_markers_by_strid
13172 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13173 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13174 remote_ops.to_use_agent = remote_use_agent;
13175 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13176 remote_ops.to_supports_btrace = remote_supports_btrace;
13177 remote_ops.to_enable_btrace = remote_enable_btrace;
13178 remote_ops.to_disable_btrace = remote_disable_btrace;
13179 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13180 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13181 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13182 remote_ops.to_augmented_libraries_svr4_read =
13183 remote_augmented_libraries_svr4_read;
8020350c
DB
13184 remote_ops.to_follow_fork = remote_follow_fork;
13185 remote_ops.to_follow_exec = remote_follow_exec;
13186 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13187 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13188 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13189 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13190 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13191 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
c906108c
SS
13192}
13193
13194/* Set up the extended remote vector by making a copy of the standard
13195 remote vector and adding to it. */
13196
13197static void
fba45db2 13198init_extended_remote_ops (void)
c906108c
SS
13199{
13200 extended_remote_ops = remote_ops;
13201
0f71a2f6 13202 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13203 extended_remote_ops.to_longname =
c906108c 13204 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13205 extended_remote_ops.to_doc =
c906108c 13206 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13207Specify the serial device it is connected to (e.g. /dev/ttya).";
13208 extended_remote_ops.to_open = extended_remote_open;
c906108c 13209 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
2d717e4f
DJ
13210 extended_remote_ops.to_detach = extended_remote_detach;
13211 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13212 extended_remote_ops.to_post_attach = extended_remote_post_attach;
03583c20
UW
13213 extended_remote_ops.to_supports_disable_randomization
13214 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
13215}
13216
6426a772 13217static int
6a109b6b 13218remote_can_async_p (struct target_ops *ops)
6426a772 13219{
5d93a237
TT
13220 struct remote_state *rs = get_remote_state ();
13221
c6ebd6cf 13222 if (!target_async_permitted)
75c99385
PA
13223 /* We only enable async when the user specifically asks for it. */
13224 return 0;
13225
23860348 13226 /* We're async whenever the serial device is. */
5d93a237 13227 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13228}
13229
13230static int
6a109b6b 13231remote_is_async_p (struct target_ops *ops)
6426a772 13232{
5d93a237
TT
13233 struct remote_state *rs = get_remote_state ();
13234
c6ebd6cf 13235 if (!target_async_permitted)
75c99385
PA
13236 /* We only enable async when the user specifically asks for it. */
13237 return 0;
13238
23860348 13239 /* We're async whenever the serial device is. */
5d93a237 13240 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13241}
13242
2acceee2
JM
13243/* Pass the SERIAL event on and up to the client. One day this code
13244 will be able to delay notifying the client of an event until the
23860348 13245 point where an entire packet has been received. */
2acceee2 13246
2acceee2
JM
13247static serial_event_ftype remote_async_serial_handler;
13248
6426a772 13249static void
819cc324 13250remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13251{
19ba03f4 13252 struct remote_state *rs = (struct remote_state *) context;
88b496c3 13253
2acceee2
JM
13254 /* Don't propogate error information up to the client. Instead let
13255 the client find out about the error by querying the target. */
6a3753b3 13256 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13257}
13258
74531fed
PA
13259static void
13260remote_async_inferior_event_handler (gdb_client_data data)
13261{
13262 inferior_event_handler (INF_REG_EVENT, NULL);
13263}
13264
2acceee2 13265static void
6a3753b3 13266remote_async (struct target_ops *ops, int enable)
2acceee2 13267{
5d93a237
TT
13268 struct remote_state *rs = get_remote_state ();
13269
6a3753b3 13270 if (enable)
2acceee2 13271 {
88b496c3 13272 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13273
13274 /* If there are pending events in the stop reply queue tell the
13275 event loop to process them. */
13276 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13277 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13278 /* For simplicity, below we clear the pending events token
13279 without remembering whether it is marked, so here we always
13280 mark it. If there's actually no pending notification to
13281 process, this ends up being a no-op (other than a spurious
13282 event-loop wakeup). */
13283 if (target_is_non_stop_p ())
13284 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13285 }
13286 else
b7d2e916
PA
13287 {
13288 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13289 /* If the core is disabling async, it doesn't want to be
13290 disturbed with target events. Clear all async event sources
13291 too. */
b7d2e916 13292 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13293 if (target_is_non_stop_p ())
13294 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13295 }
6426a772
JM
13296}
13297
65706a29
PA
13298/* Implementation of the to_thread_events method. */
13299
13300static void
13301remote_thread_events (struct target_ops *ops, int enable)
13302{
13303 struct remote_state *rs = get_remote_state ();
13304 size_t size = get_remote_packet_size ();
13305 char *p = rs->buf;
13306
13307 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13308 return;
13309
13310 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13311 putpkt (rs->buf);
13312 getpkt (&rs->buf, &rs->buf_size, 0);
13313
13314 switch (packet_ok (rs->buf,
13315 &remote_protocol_packets[PACKET_QThreadEvents]))
13316 {
13317 case PACKET_OK:
13318 if (strcmp (rs->buf, "OK") != 0)
13319 error (_("Remote refused setting thread events: %s"), rs->buf);
13320 break;
13321 case PACKET_ERROR:
13322 warning (_("Remote failure reply: %s"), rs->buf);
13323 break;
13324 case PACKET_UNKNOWN:
13325 break;
13326 }
13327}
13328
5a2468f5 13329static void
c2d11a7d 13330set_remote_cmd (char *args, int from_tty)
5a2468f5 13331{
635c7e8a 13332 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13333}
13334
d471ea57
AC
13335static void
13336show_remote_cmd (char *args, int from_tty)
13337{
37a105a1 13338 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13339 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13340 struct cleanup *showlist_chain;
13341 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13342 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13343
13344 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13345 for (; list != NULL; list = list->next)
13346 if (strcmp (list->name, "Z-packet") == 0)
13347 continue;
427c3a89
DJ
13348 else if (list->type == not_set_cmd)
13349 /* Alias commands are exactly like the original, except they
13350 don't have the normal type. */
13351 continue;
13352 else
37a105a1
DJ
13353 {
13354 struct cleanup *option_chain
13355 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13356
37a105a1
DJ
13357 ui_out_field_string (uiout, "name", list->name);
13358 ui_out_text (uiout, ": ");
427c3a89 13359 if (list->type == show_cmd)
5b9afe8a 13360 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
13361 else
13362 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13363 /* Close the tuple. */
13364 do_cleanups (option_chain);
13365 }
427c3a89
DJ
13366
13367 /* Close the tuple. */
13368 do_cleanups (showlist_chain);
d471ea57 13369}
5a2468f5 13370
0f71a2f6 13371
23860348 13372/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13373static void
13374remote_new_objfile (struct objfile *objfile)
13375{
5d93a237
TT
13376 struct remote_state *rs = get_remote_state ();
13377
13378 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13379 remote_check_symbols ();
dc8acb97
MS
13380}
13381
00bf0b85
SS
13382/* Pull all the tracepoints defined on the target and create local
13383 data structures representing them. We don't want to create real
13384 tracepoints yet, we don't want to mess up the user's existing
13385 collection. */
13386
13387static int
ab6617cc 13388remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13389{
00bf0b85
SS
13390 struct remote_state *rs = get_remote_state ();
13391 char *p;
d5551862 13392
00bf0b85
SS
13393 /* Ask for a first packet of tracepoint definition. */
13394 putpkt ("qTfP");
13395 getpkt (&rs->buf, &rs->buf_size, 0);
13396 p = rs->buf;
13397 while (*p && *p != 'l')
d5551862 13398 {
00bf0b85
SS
13399 parse_tracepoint_definition (p, utpp);
13400 /* Ask for another packet of tracepoint definition. */
13401 putpkt ("qTsP");
13402 getpkt (&rs->buf, &rs->buf_size, 0);
13403 p = rs->buf;
d5551862 13404 }
00bf0b85 13405 return 0;
d5551862
SS
13406}
13407
00bf0b85 13408static int
181e3713
TT
13409remote_upload_trace_state_variables (struct target_ops *self,
13410 struct uploaded_tsv **utsvp)
d5551862 13411{
00bf0b85 13412 struct remote_state *rs = get_remote_state ();
d5551862 13413 char *p;
d5551862 13414
00bf0b85
SS
13415 /* Ask for a first packet of variable definition. */
13416 putpkt ("qTfV");
d5551862
SS
13417 getpkt (&rs->buf, &rs->buf_size, 0);
13418 p = rs->buf;
00bf0b85 13419 while (*p && *p != 'l')
d5551862 13420 {
00bf0b85
SS
13421 parse_tsv_definition (p, utsvp);
13422 /* Ask for another packet of variable definition. */
13423 putpkt ("qTsV");
d5551862
SS
13424 getpkt (&rs->buf, &rs->buf_size, 0);
13425 p = rs->buf;
13426 }
00bf0b85 13427 return 0;
d5551862
SS
13428}
13429
c1e36e3e
PA
13430/* The "set/show range-stepping" show hook. */
13431
13432static void
13433show_range_stepping (struct ui_file *file, int from_tty,
13434 struct cmd_list_element *c,
13435 const char *value)
13436{
13437 fprintf_filtered (file,
13438 _("Debugger's willingness to use range stepping "
13439 "is %s.\n"), value);
13440}
13441
13442/* The "set/show range-stepping" set hook. */
13443
13444static void
13445set_range_stepping (char *ignore_args, int from_tty,
13446 struct cmd_list_element *c)
13447{
5d93a237
TT
13448 struct remote_state *rs = get_remote_state ();
13449
c1e36e3e
PA
13450 /* Whene enabling, check whether range stepping is actually
13451 supported by the target, and warn if not. */
13452 if (use_range_stepping)
13453 {
5d93a237 13454 if (rs->remote_desc != NULL)
c1e36e3e 13455 {
4082afcc 13456 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13457 remote_vcont_probe (rs);
13458
4082afcc 13459 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13460 && rs->supports_vCont.r)
13461 return;
13462 }
13463
13464 warning (_("Range stepping is not supported by the current target"));
13465 }
13466}
13467
c906108c 13468void
fba45db2 13469_initialize_remote (void)
c906108c 13470{
ea9c271d 13471 struct remote_state *rs;
9a7071a8 13472 struct cmd_list_element *cmd;
6f937416 13473 const char *cmd_name;
ea9c271d 13474
0f71a2f6 13475 /* architecture specific data */
2bc416ba 13476 remote_gdbarch_data_handle =
23860348 13477 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13478 remote_g_packet_data_handle =
13479 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13480
94585166
DB
13481 remote_pspace_data
13482 = register_program_space_data_with_cleanup (NULL,
13483 remote_pspace_data_cleanup);
13484
ea9c271d
DJ
13485 /* Initialize the per-target state. At the moment there is only one
13486 of these, not one per target. Only one target is active at a
cf792862
TT
13487 time. */
13488 remote_state = new_remote_state ();
ea9c271d 13489
c906108c
SS
13490 init_remote_ops ();
13491 add_target (&remote_ops);
13492
13493 init_extended_remote_ops ();
13494 add_target (&extended_remote_ops);
cce74817 13495
dc8acb97 13496 /* Hook into new objfile notification. */
06d3b283 13497 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13498 /* We're no longer interested in notification events of an inferior
13499 when it exits. */
13500 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13501
b803fb0f 13502 /* Set up signal handlers. */
934b9bac 13503 async_sigint_remote_token =
b803fb0f 13504 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 13505 async_sigint_remote_twice_token =
6d549500 13506 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 13507
c906108c
SS
13508#if 0
13509 init_remote_threadtests ();
13510#endif
13511
722247f1 13512 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13513 /* set/show remote ... */
d471ea57 13514
1bedd215 13515 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13516Remote protocol specific variables\n\
13517Configure various remote-protocol specific variables such as\n\
1bedd215 13518the packets being used"),
cff3e48b 13519 &remote_set_cmdlist, "set remote ",
23860348 13520 0 /* allow-unknown */, &setlist);
1bedd215 13521 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13522Remote protocol specific variables\n\
13523Configure various remote-protocol specific variables such as\n\
1bedd215 13524the packets being used"),
cff3e48b 13525 &remote_show_cmdlist, "show remote ",
23860348 13526 0 /* allow-unknown */, &showlist);
5a2468f5 13527
1a966eab
AC
13528 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13529Compare section data on target to the exec file.\n\
95cf3b38
DT
13530Argument is a single section name (default: all loaded sections).\n\
13531To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13532 &cmdlist);
13533
1a966eab
AC
13534 add_cmd ("packet", class_maintenance, packet_command, _("\
13535Send an arbitrary packet to a remote target.\n\
c906108c
SS
13536 maintenance packet TEXT\n\
13537If GDB is talking to an inferior via the GDB serial protocol, then\n\
13538this command sends the string TEXT to the inferior, and displays the\n\
13539response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13540terminating `#' character and checksum."),
c906108c
SS
13541 &maintenancelist);
13542
7915a72c
AC
13543 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13544Set whether to send break if interrupted."), _("\
13545Show whether to send break if interrupted."), _("\
13546If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13547 set_remotebreak, show_remotebreak,
e707bbc2 13548 &setlist, &showlist);
9a7071a8
JB
13549 cmd_name = "remotebreak";
13550 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13551 deprecate_cmd (cmd, "set remote interrupt-sequence");
13552 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13553 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13554 deprecate_cmd (cmd, "show remote interrupt-sequence");
13555
13556 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13557 interrupt_sequence_modes, &interrupt_sequence_mode,
13558 _("\
9a7071a8
JB
13559Set interrupt sequence to remote target."), _("\
13560Show interrupt sequence to remote target."), _("\
13561Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13562 NULL, show_interrupt_sequence,
13563 &remote_set_cmdlist,
13564 &remote_show_cmdlist);
13565
13566 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13567 &interrupt_on_connect, _("\
13568Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13569Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13570If set, interrupt sequence is sent to remote target."),
13571 NULL, NULL,
13572 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13573
23860348 13574 /* Install commands for configuring memory read/write packets. */
11cf8741 13575
1a966eab
AC
13576 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13577Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13578 &setlist);
1a966eab
AC
13579 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13580Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13581 &showlist);
13582 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13583 set_memory_write_packet_size, _("\
13584Set the maximum number of bytes per memory-write packet.\n\
13585Specify the number of bytes in a packet or 0 (zero) for the\n\
13586default packet size. The actual limit is further reduced\n\
13587dependent on the target. Specify ``fixed'' to disable the\n\
13588further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13589 &remote_set_cmdlist);
13590 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13591 set_memory_read_packet_size, _("\
13592Set the maximum number of bytes per memory-read packet.\n\
13593Specify the number of bytes in a packet or 0 (zero) for the\n\
13594default packet size. The actual limit is further reduced\n\
13595dependent on the target. Specify ``fixed'' to disable the\n\
13596further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13597 &remote_set_cmdlist);
13598 add_cmd ("memory-write-packet-size", no_class,
13599 show_memory_write_packet_size,
1a966eab 13600 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13601 &remote_show_cmdlist);
13602 add_cmd ("memory-read-packet-size", no_class,
13603 show_memory_read_packet_size,
1a966eab 13604 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13605 &remote_show_cmdlist);
c906108c 13606
b3f42336 13607 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13608 &remote_hw_watchpoint_limit, _("\
13609Set the maximum number of target hardware watchpoints."), _("\
13610Show the maximum number of target hardware watchpoints."), _("\
13611Specify a negative limit for unlimited."),
3e43a32a
MS
13612 NULL, NULL, /* FIXME: i18n: The maximum
13613 number of target hardware
13614 watchpoints is %s. */
b3f42336 13615 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13616 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13617 &remote_hw_watchpoint_length_limit, _("\
13618Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13619Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13620Specify a negative limit for unlimited."),
13621 NULL, NULL, /* FIXME: i18n: The maximum
13622 length (in bytes) of a target
13623 hardware watchpoint is %s. */
13624 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13625 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13626 &remote_hw_breakpoint_limit, _("\
13627Set the maximum number of target hardware breakpoints."), _("\
13628Show the maximum number of target hardware breakpoints."), _("\
13629Specify a negative limit for unlimited."),
3e43a32a
MS
13630 NULL, NULL, /* FIXME: i18n: The maximum
13631 number of target hardware
13632 breakpoints is %s. */
b3f42336 13633 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13634
1b493192
PA
13635 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13636 &remote_address_size, _("\
4d28ad1e
AC
13637Set the maximum size of the address (in bits) in a memory packet."), _("\
13638Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13639 NULL,
13640 NULL, /* FIXME: i18n: */
13641 &setlist, &showlist);
c906108c 13642
ca4f7f8b
PA
13643 init_all_packet_configs ();
13644
444abaca 13645 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13646 "X", "binary-download", 1);
0f71a2f6 13647
444abaca 13648 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13649 "vCont", "verbose-resume", 0);
506fb367 13650
89be2091
DJ
13651 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13652 "QPassSignals", "pass-signals", 0);
13653
82075af2
JS
13654 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13655 "QCatchSyscalls", "catch-syscalls", 0);
13656
9b224c5e
PA
13657 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13658 "QProgramSignals", "program-signals", 0);
13659
444abaca 13660 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13661 "qSymbol", "symbol-lookup", 0);
dc8acb97 13662
444abaca 13663 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13664 "P", "set-register", 1);
d471ea57 13665
444abaca 13666 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13667 "p", "fetch-register", 1);
b96ec7ac 13668
444abaca 13669 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13670 "Z0", "software-breakpoint", 0);
d471ea57 13671
444abaca 13672 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13673 "Z1", "hardware-breakpoint", 0);
d471ea57 13674
444abaca 13675 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13676 "Z2", "write-watchpoint", 0);
d471ea57 13677
444abaca 13678 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13679 "Z3", "read-watchpoint", 0);
d471ea57 13680
444abaca 13681 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13682 "Z4", "access-watchpoint", 0);
d471ea57 13683
0876f84a
DJ
13684 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13685 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13686
c78fa86a
GB
13687 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13688 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13689
23181151
DJ
13690 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13691 "qXfer:features:read", "target-features", 0);
13692
cfa9d6d9
DJ
13693 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13694 "qXfer:libraries:read", "library-info", 0);
13695
2268b414
JK
13696 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13697 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13698
fd79ecee
DJ
13699 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13700 "qXfer:memory-map:read", "memory-map", 0);
13701
0e7f50da
UW
13702 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13703 "qXfer:spu:read", "read-spu-object", 0);
13704
13705 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13706 "qXfer:spu:write", "write-spu-object", 0);
13707
07e059b5
VP
13708 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13709 "qXfer:osdata:read", "osdata", 0);
13710
dc146f7c
VP
13711 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13712 "qXfer:threads:read", "threads", 0);
13713
4aa995e1
PA
13714 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13715 "qXfer:siginfo:read", "read-siginfo-object", 0);
13716
13717 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13718 "qXfer:siginfo:write", "write-siginfo-object", 0);
13719
b3b9301e
PA
13720 add_packet_config_cmd
13721 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13722 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13723
169081d0
TG
13724 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13725 "qXfer:uib:read", "unwind-info-block", 0);
13726
444abaca 13727 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13728 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13729 0);
13730
711e434b
PM
13731 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13732 "qGetTIBAddr", "get-thread-information-block-address",
13733 0);
13734
40ab02ce
MS
13735 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13736 "bc", "reverse-continue", 0);
13737
13738 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13739 "bs", "reverse-step", 0);
13740
be2a5f71
DJ
13741 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13742 "qSupported", "supported-packets", 0);
13743
08388c79
DE
13744 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13745 "qSearch:memory", "search-memory", 0);
13746
bd3eecc3
PA
13747 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13748 "qTStatus", "trace-status", 0);
13749
15a201c8
GB
13750 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13751 "vFile:setfs", "hostio-setfs", 0);
13752
a6b151f1
DJ
13753 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13754 "vFile:open", "hostio-open", 0);
13755
13756 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13757 "vFile:pread", "hostio-pread", 0);
13758
13759 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13760 "vFile:pwrite", "hostio-pwrite", 0);
13761
13762 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13763 "vFile:close", "hostio-close", 0);
13764
13765 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13766 "vFile:unlink", "hostio-unlink", 0);
13767
b9e7b9c3
UW
13768 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13769 "vFile:readlink", "hostio-readlink", 0);
13770
0a93529c
GB
13771 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13772 "vFile:fstat", "hostio-fstat", 0);
13773
2d717e4f
DJ
13774 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13775 "vAttach", "attach", 0);
13776
13777 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13778 "vRun", "run", 0);
13779
a6f3e723
SL
13780 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13781 "QStartNoAckMode", "noack", 0);
13782
82f73884
PA
13783 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13784 "vKill", "kill", 0);
13785
0b16c5cf
PA
13786 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13787 "qAttached", "query-attached", 0);
13788
782b2b07 13789 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13790 "ConditionalTracepoints",
13791 "conditional-tracepoints", 0);
3788aec7
LM
13792
13793 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13794 "ConditionalBreakpoints",
13795 "conditional-breakpoints", 0);
13796
d3ce09f5
SS
13797 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13798 "BreakpointCommands",
13799 "breakpoint-commands", 0);
13800
7a697b8d
SS
13801 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13802 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13803
409873ef
SS
13804 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13805 "TracepointSource", "TracepointSource", 0);
13806
d914c394
SS
13807 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13808 "QAllow", "allow", 0);
13809
0fb4aa4b
PA
13810 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13811 "StaticTracepoints", "static-tracepoints", 0);
13812
1e4d1764
YQ
13813 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13814 "InstallInTrace", "install-in-trace", 0);
13815
0fb4aa4b
PA
13816 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13817 "qXfer:statictrace:read", "read-sdata-object", 0);
13818
78d85199
YQ
13819 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13820 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13821
03583c20
UW
13822 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13823 "QDisableRandomization", "disable-randomization", 0);
13824
d1feda86
YQ
13825 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13826 "QAgent", "agent", 0);
13827
f6f899bf
HAQ
13828 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13829 "QTBuffer:size", "trace-buffer-size", 0);
13830
9accd112
MM
13831 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13832 "Qbtrace:off", "disable-btrace", 0);
13833
13834 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13835 "Qbtrace:bts", "enable-btrace-bts", 0);
13836
13837 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13838 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13839
13840 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13841 "qXfer:btrace", "read-btrace", 0);
13842
f4abbc16
MM
13843 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13844 "qXfer:btrace-conf", "read-btrace-conf", 0);
13845
d33501a5
MM
13846 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13847 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13848
73b8c1fd
PA
13849 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13850 "multiprocess-feature", "multiprocess-feature", 0);
13851
f7e6eed5
PA
13852 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13853 "swbreak-feature", "swbreak-feature", 0);
13854
13855 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13856 "hwbreak-feature", "hwbreak-feature", 0);
13857
89245bc0
DB
13858 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13859 "fork-event-feature", "fork-event-feature", 0);
13860
13861 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13862 "vfork-event-feature", "vfork-event-feature", 0);
13863
b20a6524
MM
13864 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13865 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13866
750ce8d1
YQ
13867 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13868 "vContSupported", "verbose-resume-supported", 0);
13869
94585166
DB
13870 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13871 "exec-event-feature", "exec-event-feature", 0);
13872
de979965
PA
13873 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13874 "vCtrlC", "ctrl-c", 0);
13875
65706a29
PA
13876 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13877 "QThreadEvents", "thread-events", 0);
13878
f2faf941
PA
13879 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13880 "N stop reply", "no-resumed-stop-reply", 0);
13881
0b736949
DB
13882 /* Assert that we've registered "set remote foo-packet" commands
13883 for all packet configs. */
ca4f7f8b
PA
13884 {
13885 int i;
13886
13887 for (i = 0; i < PACKET_MAX; i++)
13888 {
13889 /* Ideally all configs would have a command associated. Some
13890 still don't though. */
13891 int excepted;
13892
13893 switch (i)
13894 {
13895 case PACKET_QNonStop:
ca4f7f8b
PA
13896 case PACKET_EnableDisableTracepoints_feature:
13897 case PACKET_tracenz_feature:
13898 case PACKET_DisconnectedTracing_feature:
13899 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13900 case PACKET_qCRC:
13901 /* Additions to this list need to be well justified:
13902 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13903 excepted = 1;
13904 break;
13905 default:
13906 excepted = 0;
13907 break;
13908 }
13909
13910 /* This catches both forgetting to add a config command, and
13911 forgetting to remove a packet from the exception list. */
13912 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13913 }
13914 }
13915
37a105a1
DJ
13916 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13917 Z sub-packet has its own set and show commands, but users may
13918 have sets to this variable in their .gdbinit files (or in their
13919 documentation). */
e9e68a56 13920 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13921 &remote_Z_packet_detect, _("\
13922Set use of remote protocol `Z' packets"), _("\
13923Show use of remote protocol `Z' packets "), _("\
3b64bf98 13924When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13925packets."),
e9e68a56 13926 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13927 show_remote_protocol_Z_packet_cmd,
13928 /* FIXME: i18n: Use of remote protocol
13929 `Z' packets is %s. */
e9e68a56 13930 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13931
a6b151f1
DJ
13932 add_prefix_cmd ("remote", class_files, remote_command, _("\
13933Manipulate files on the remote system\n\
13934Transfer files to and from the remote target system."),
13935 &remote_cmdlist, "remote ",
13936 0 /* allow-unknown */, &cmdlist);
13937
13938 add_cmd ("put", class_files, remote_put_command,
13939 _("Copy a local file to the remote system."),
13940 &remote_cmdlist);
13941
13942 add_cmd ("get", class_files, remote_get_command,
13943 _("Copy a remote file to the local system."),
13944 &remote_cmdlist);
13945
13946 add_cmd ("delete", class_files, remote_delete_command,
13947 _("Delete a remote file."),
13948 &remote_cmdlist);
13949
2d717e4f 13950 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13951 &remote_exec_file_var, _("\
2d717e4f 13952Set the remote pathname for \"run\""), _("\
94585166
DB
13953Show the remote pathname for \"run\""), NULL,
13954 set_remote_exec_file,
13955 show_remote_exec_file,
13956 &remote_set_cmdlist,
13957 &remote_show_cmdlist);
2d717e4f 13958
c1e36e3e
PA
13959 add_setshow_boolean_cmd ("range-stepping", class_run,
13960 &use_range_stepping, _("\
13961Enable or disable range stepping."), _("\
13962Show whether target-assisted range stepping is enabled."), _("\
13963If on, and the target supports it, when stepping a source line, GDB\n\
13964tells the target to step the corresponding range of addresses itself instead\n\
13965of issuing multiple single-steps. This speeds up source level\n\
13966stepping. If off, GDB always issues single-steps, even if range\n\
13967stepping is supported by the target. The default is on."),
13968 set_range_stepping,
13969 show_range_stepping,
13970 &setlist,
13971 &showlist);
13972
449092f6
CV
13973 /* Eventually initialize fileio. See fileio.c */
13974 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13975
ba348170 13976 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13977 special ptids with it set to != 0. */
ba348170
PA
13978 magic_null_ptid = ptid_build (42000, -1, 1);
13979 not_sent_ptid = ptid_build (42000, -2, 1);
13980 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13981
13982 target_buf_size = 2048;
224c3ddb 13983 target_buf = (char *) xmalloc (target_buf_size);
c906108c 13984}
10760264 13985