]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
Resync files in the binutils repository that are maintained in the gcc repository.
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
32d0add0 3 Copyright (C) 1988-2015 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
136d6dae 122static void remote_mourn (struct target_ops *ops);
c906108c 123
a14ed312 124static void extended_remote_restart (void);
c906108c 125
136d6dae 126static void extended_remote_mourn (struct target_ops *);
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
934b9bac 142static void sync_remote_interrupt_twice (int signo);
7a292a7a 143
a14ed312 144static void interrupt_query (void);
c906108c 145
79d7f229
PA
146static void set_general_thread (struct ptid ptid);
147static void set_continue_thread (struct ptid ptid);
c906108c 148
a14ed312 149static void get_offsets (void);
c906108c 150
6d820c5c
DJ
151static void skip_frame (void);
152
153static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 154
a14ed312 155static int hexnumlen (ULONGEST num);
c906108c 156
a14ed312 157static void init_remote_ops (void);
c906108c 158
a14ed312 159static void init_extended_remote_ops (void);
c906108c 160
1eab8a48 161static void remote_stop (struct target_ops *self, ptid_t);
c906108c 162
a14ed312 163static int stubhex (int ch);
c906108c 164
a14ed312 165static int hexnumstr (char *, ULONGEST);
c906108c 166
a14ed312 167static int hexnumnstr (char *, ULONGEST, int);
2df3850c 168
a14ed312 169static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 170
baa336ce 171static void print_packet (const char *);
c906108c 172
a14ed312 173static void compare_sections_command (char *, int);
c906108c 174
a14ed312 175static void packet_command (char *, int);
c906108c 176
a14ed312 177static int stub_unpack_int (char *buff, int fieldlength);
c906108c 178
39f77062 179static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 180
baa336ce 181static int putpkt_binary (const char *buf, int cnt);
c906108c 182
a14ed312 183static void check_binary_download (CORE_ADDR addr);
c906108c 184
5a2468f5 185struct packet_config;
5a2468f5 186
a14ed312 187static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 188
bb572ddd
DJ
189static void show_remote_protocol_packet_cmd (struct ui_file *file,
190 int from_tty,
191 struct cmd_list_element *c,
192 const char *value);
193
82f73884
PA
194static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
195static ptid_t read_ptid (char *buf, char **obuf);
196
c378d69d 197static void remote_set_permissions (struct target_ops *self);
d914c394 198
8bd200f1
TT
199static int remote_get_trace_status (struct target_ops *self,
200 struct trace_status *ts);
d5551862 201
ab6617cc
TT
202static int remote_upload_tracepoints (struct target_ops *self,
203 struct uploaded_tp **utpp);
00bf0b85 204
181e3713
TT
205static int remote_upload_trace_state_variables (struct target_ops *self,
206 struct uploaded_tsv **utsvp);
00bf0b85 207
c8d104ad
PA
208static void remote_query_supported (void);
209
36d25514 210static void remote_check_symbols (void);
c8d104ad 211
a14ed312 212void _initialize_remote (void);
c906108c 213
74531fed 214struct stop_reply;
74531fed 215static void stop_reply_xfree (struct stop_reply *);
722247f1 216static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 217static void push_stop_reply (struct stop_reply *);
bcc75809 218static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
219static int peek_stop_reply (ptid_t ptid);
220
cbb8991c
DB
221struct threads_listing_context;
222static void remove_new_fork_children (struct threads_listing_context *);
223
74531fed 224static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 225
e3594fd1 226static void remote_terminal_ours (struct target_ops *self);
d3fd5342 227
d962ef82
DJ
228static int remote_read_description_p (struct target_ops *target);
229
176a6961 230static void remote_console_output (char *msg);
dde08ee1 231
efcc2da7 232static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 233
78eff0ec 234static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 235
f4abbc16
MM
236static void remote_btrace_reset (void);
237
221e1a37
PA
238static int stop_reply_queue_length (void);
239
80152258
PA
240static void readahead_cache_invalidate (void);
241
a6b151f1
DJ
242/* For "remote". */
243
244static struct cmd_list_element *remote_cmdlist;
245
bb572ddd
DJ
246/* For "set remote" and "show remote". */
247
248static struct cmd_list_element *remote_set_cmdlist;
249static struct cmd_list_element *remote_show_cmdlist;
250
d458bd84
PA
251/* Stub vCont actions support.
252
253 Each field is a boolean flag indicating whether the stub reports
254 support for the corresponding action. */
255
256struct vCont_action_support
257{
258 /* vCont;t */
259 int t;
c1e36e3e
PA
260
261 /* vCont;r */
262 int r;
750ce8d1
YQ
263
264 /* vCont;s */
265 int s;
266
267 /* vCont;S */
268 int S;
d458bd84
PA
269};
270
c1e36e3e
PA
271/* Controls whether GDB is willing to use range stepping. */
272
273static int use_range_stepping = 1;
274
0d031856
TT
275#define OPAQUETHREADBYTES 8
276
277/* a 64 bit opaque identifier */
278typedef unsigned char threadref[OPAQUETHREADBYTES];
279
280/* About this many threadisds fit in a packet. */
281
282#define MAXTHREADLISTRESULTS 32
283
80152258
PA
284/* Data for the vFile:pread readahead cache. */
285
286struct readahead_cache
287{
288 /* The file descriptor for the file that is being cached. -1 if the
289 cache is invalid. */
290 int fd;
291
292 /* The offset into the file that the cache buffer corresponds
293 to. */
294 ULONGEST offset;
295
296 /* The buffer holding the cache contents. */
297 gdb_byte *buf;
298 /* The buffer's size. We try to read as much as fits into a packet
299 at a time. */
300 size_t bufsize;
301
302 /* Cache hit and miss counters. */
303 ULONGEST hit_count;
304 ULONGEST miss_count;
305};
306
ea9c271d
DJ
307/* Description of the remote protocol state for the currently
308 connected target. This is per-target state, and independent of the
309 selected architecture. */
310
311struct remote_state
312{
313 /* A buffer to use for incoming packets, and its current size. The
314 buffer is grown dynamically for larger incoming packets.
315 Outgoing packets may also be constructed in this buffer.
316 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
317 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
318 packets. */
319 char *buf;
320 long buf_size;
be2a5f71 321
1e51243a
PA
322 /* True if we're going through initial connection setup (finding out
323 about the remote side's threads, relocating symbols, etc.). */
324 int starting_up;
325
be2a5f71
DJ
326 /* If we negotiated packet size explicitly (and thus can bypass
327 heuristics for the largest packet size that will not overflow
328 a buffer in the stub), this will be set to that packet size.
329 Otherwise zero, meaning to use the guessed size. */
330 long explicit_packet_size;
2d717e4f
DJ
331
332 /* remote_wait is normally called when the target is running and
333 waits for a stop reply packet. But sometimes we need to call it
334 when the target is already stopped. We can send a "?" packet
335 and have remote_wait read the response. Or, if we already have
336 the response, we can stash it in BUF and tell remote_wait to
337 skip calling getpkt. This flag is set when BUF contains a
338 stop reply packet and the target is not waiting. */
339 int cached_wait_status;
a6f3e723
SL
340
341 /* True, if in no ack mode. That is, neither GDB nor the stub will
342 expect acks from each other. The connection is assumed to be
343 reliable. */
344 int noack_mode;
82f73884
PA
345
346 /* True if we're connected in extended remote mode. */
347 int extended;
348
e24a49d8
PA
349 /* True if we resumed the target and we're waiting for the target to
350 stop. In the mean time, we can't start another command/query.
351 The remote server wouldn't be ready to process it, so we'd
352 timeout waiting for a reply that would never come and eventually
353 we'd close the connection. This can happen in asynchronous mode
354 because we allow GDB commands while the target is running. */
355 int waiting_for_stop_reply;
74531fed 356
d458bd84
PA
357 /* The status of the stub support for the various vCont actions. */
358 struct vCont_action_support supports_vCont;
782b2b07 359
3a29589a
DJ
360 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
361 responded to that. */
362 int ctrlc_pending_p;
5d93a237
TT
363
364 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
365 remote_open knows that we don't have a file open when the program
366 starts. */
367 struct serial *remote_desc;
47f8a51d
TT
368
369 /* These are the threads which we last sent to the remote system. The
370 TID member will be -1 for all or -2 for not sent yet. */
371 ptid_t general_thread;
372 ptid_t continue_thread;
262e1174
TT
373
374 /* This is the traceframe which we last selected on the remote system.
375 It will be -1 if no traceframe is selected. */
376 int remote_traceframe_number;
747dc59d
TT
377
378 char *last_pass_packet;
5e4a05c4
TT
379
380 /* The last QProgramSignals packet sent to the target. We bypass
381 sending a new program signals list down to the target if the new
382 packet is exactly the same as the last we sent. IOW, we only let
383 the target know about program signals list changes. */
384 char *last_program_signals_packet;
b73be471
TT
385
386 enum gdb_signal last_sent_signal;
280ceea3
TT
387
388 int last_sent_step;
8e88304f
TT
389
390 char *finished_object;
391 char *finished_annex;
392 ULONGEST finished_offset;
b80fafe3
TT
393
394 /* Should we try the 'ThreadInfo' query packet?
395
396 This variable (NOT available to the user: auto-detect only!)
397 determines whether GDB will use the new, simpler "ThreadInfo"
398 query or the older, more complex syntax for thread queries.
399 This is an auto-detect variable (set to true at each connect,
400 and set to false when the target fails to recognize it). */
401 int use_threadinfo_query;
402 int use_threadextra_query;
88b496c3 403
ee154bee
TT
404 /* This is set to the data address of the access causing the target
405 to stop for a watchpoint. */
406 CORE_ADDR remote_watch_data_address;
407
f7e6eed5
PA
408 /* Whether the target stopped for a breakpoint/watchpoint. */
409 enum target_stop_reason stop_reason;
0d031856
TT
410
411 threadref echo_nextthread;
412 threadref nextthread;
413 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
414
415 /* The state of remote notification. */
416 struct remote_notif_state *notif_state;
f4abbc16
MM
417
418 /* The branch trace configuration. */
419 struct btrace_config btrace_config;
15a201c8
GB
420
421 /* The argument to the last "vFile:setfs:" packet we sent, used
422 to avoid sending repeated unnecessary "vFile:setfs:" packets.
423 Initialized to -1 to indicate that no "vFile:setfs:" packet
424 has yet been sent. */
425 int fs_pid;
80152258
PA
426
427 /* A readahead cache for vFile:pread. Often, reading a binary
428 involves a sequence of small reads. E.g., when parsing an ELF
429 file. A readahead cache helps mostly the case of remote
430 debugging on a connection with higher latency, due to the
431 request/reply nature of the RSP. We only cache data for a single
432 file descriptor at a time. */
433 struct readahead_cache readahead_cache;
ea9c271d
DJ
434};
435
dc146f7c
VP
436/* Private data that we'll store in (struct thread_info)->private. */
437struct private_thread_info
438{
439 char *extra;
440 int core;
441};
442
443static void
444free_private_thread_info (struct private_thread_info *info)
445{
446 xfree (info->extra);
447 xfree (info);
448}
449
ea9c271d
DJ
450/* This data could be associated with a target, but we do not always
451 have access to the current target when we need it, so for now it is
452 static. This will be fine for as long as only one target is in use
453 at a time. */
cf792862 454static struct remote_state *remote_state;
ea9c271d
DJ
455
456static struct remote_state *
0b83947e 457get_remote_state_raw (void)
ea9c271d 458{
cf792862
TT
459 return remote_state;
460}
461
462/* Allocate a new struct remote_state with xmalloc, initialize it, and
463 return it. */
464
465static struct remote_state *
466new_remote_state (void)
467{
468 struct remote_state *result = XCNEW (struct remote_state);
469
470 /* The default buffer size is unimportant; it will be expanded
471 whenever a larger buffer is needed. */
472 result->buf_size = 400;
224c3ddb 473 result->buf = (char *) xmalloc (result->buf_size);
262e1174 474 result->remote_traceframe_number = -1;
b73be471 475 result->last_sent_signal = GDB_SIGNAL_0;
15a201c8 476 result->fs_pid = -1;
cf792862
TT
477
478 return result;
ea9c271d
DJ
479}
480
481/* Description of the remote protocol for a given architecture. */
d01949b6 482
ad10f812
AC
483struct packet_reg
484{
485 long offset; /* Offset into G packet. */
486 long regnum; /* GDB's internal register number. */
487 LONGEST pnum; /* Remote protocol register number. */
b323314b 488 int in_g_packet; /* Always part of G packet. */
f5656ead 489 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 490 at present. */
f5656ead 491 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 492 at present. */
ad10f812
AC
493};
494
ea9c271d 495struct remote_arch_state
d01949b6 496{
ad10f812
AC
497 /* Description of the remote protocol registers. */
498 long sizeof_g_packet;
b323314b
AC
499
500 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 501 (making an array gdbarch_num_regs in size). */
b323314b 502 struct packet_reg *regs;
ad10f812 503
d01949b6
AC
504 /* This is the size (in chars) of the first response to the ``g''
505 packet. It is used as a heuristic when determining the maximum
506 size of memory-read and memory-write packets. A target will
507 typically only reserve a buffer large enough to hold the ``g''
508 packet. The size does not include packet overhead (headers and
23860348 509 trailers). */
d01949b6
AC
510 long actual_register_packet_size;
511
512 /* This is the maximum size (in chars) of a non read/write packet.
23860348 513 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
514 long remote_packet_size;
515};
516
35b1e5cc
SS
517/* Utility: generate error from an incoming stub packet. */
518static void
519trace_error (char *buf)
520{
521 if (*buf++ != 'E')
522 return; /* not an error msg */
523 switch (*buf)
524 {
525 case '1': /* malformed packet error */
526 if (*++buf == '0') /* general case: */
527 error (_("remote.c: error in outgoing packet."));
528 else
529 error (_("remote.c: error in outgoing packet at field #%ld."),
530 strtol (buf, NULL, 16));
35b1e5cc
SS
531 default:
532 error (_("Target returns error code '%s'."), buf);
533 }
534}
535
536/* Utility: wait for reply from stub, while accepting "O" packets. */
537static char *
538remote_get_noisy_reply (char **buf_p,
539 long *sizeof_buf)
540{
541 do /* Loop on reply from remote stub. */
542 {
543 char *buf;
a744cf53 544
0df8b418 545 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
546 getpkt (buf_p, sizeof_buf, 0);
547 buf = *buf_p;
ad91cd99 548 if (buf[0] == 'E')
35b1e5cc 549 trace_error (buf);
61012eef 550 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
551 {
552 ULONGEST ul;
553 CORE_ADDR from, to, org_to;
554 char *p, *pp;
555 int adjusted_size = 0;
7556d4a4 556 int relocated = 0;
dde08ee1
PA
557
558 p = buf + strlen ("qRelocInsn:");
559 pp = unpack_varlen_hex (p, &ul);
560 if (*pp != ';')
cb91c06a 561 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
562 from = ul;
563
564 p = pp + 1;
a9cbf802 565 unpack_varlen_hex (p, &ul);
dde08ee1
PA
566 to = ul;
567
568 org_to = to;
569
492d29ea 570 TRY
dde08ee1 571 {
f5656ead 572 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 573 relocated = 1;
dde08ee1 574 }
492d29ea 575 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
576 {
577 if (ex.error == MEMORY_ERROR)
578 {
579 /* Propagate memory errors silently back to the
580 target. The stub may have limited the range of
581 addresses we can write to, for example. */
582 }
583 else
584 {
585 /* Something unexpectedly bad happened. Be verbose
586 so we can tell what, and propagate the error back
587 to the stub, so it doesn't get stuck waiting for
588 a response. */
589 exception_fprintf (gdb_stderr, ex,
590 _("warning: relocating instruction: "));
591 }
592 putpkt ("E01");
593 }
492d29ea 594 END_CATCH
7556d4a4
PA
595
596 if (relocated)
dde08ee1
PA
597 {
598 adjusted_size = to - org_to;
599
bba74b36 600 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
601 putpkt (buf);
602 }
dde08ee1 603 }
ad91cd99 604 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
605 remote_console_output (buf + 1); /* 'O' message from stub */
606 else
0df8b418 607 return buf; /* Here's the actual reply. */
35b1e5cc
SS
608 }
609 while (1);
610}
3c3bea1c 611
d01949b6
AC
612/* Handle for retreving the remote protocol data from gdbarch. */
613static struct gdbarch_data *remote_gdbarch_data_handle;
614
ea9c271d
DJ
615static struct remote_arch_state *
616get_remote_arch_state (void)
d01949b6 617{
17d8546e 618 gdb_assert (target_gdbarch () != NULL);
19ba03f4
SM
619 return ((struct remote_arch_state *)
620 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
d01949b6
AC
621}
622
0b83947e
DJ
623/* Fetch the global remote target state. */
624
625static struct remote_state *
626get_remote_state (void)
627{
628 /* Make sure that the remote architecture state has been
629 initialized, because doing so might reallocate rs->buf. Any
630 function which calls getpkt also needs to be mindful of changes
631 to rs->buf, but this call limits the number of places which run
632 into trouble. */
633 get_remote_arch_state ();
634
635 return get_remote_state_raw ();
636}
637
94585166
DB
638/* Cleanup routine for the remote module's pspace data. */
639
640static void
641remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
642{
19ba03f4 643 char *remote_exec_file = (char *) arg;
94585166
DB
644
645 xfree (remote_exec_file);
646}
647
648/* Fetch the remote exec-file from the current program space. */
649
650static const char *
651get_remote_exec_file (void)
652{
653 char *remote_exec_file;
654
19ba03f4
SM
655 remote_exec_file
656 = (char *) program_space_data (current_program_space,
657 remote_pspace_data);
94585166
DB
658 if (remote_exec_file == NULL)
659 return "";
660
661 return remote_exec_file;
662}
663
664/* Set the remote exec file for PSPACE. */
665
666static void
667set_pspace_remote_exec_file (struct program_space *pspace,
668 char *remote_exec_file)
669{
19ba03f4 670 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
671
672 xfree (old_file);
673 set_program_space_data (pspace, remote_pspace_data,
674 xstrdup (remote_exec_file));
675}
676
677/* The "set/show remote exec-file" set command hook. */
678
679static void
680set_remote_exec_file (char *ignored, int from_tty,
681 struct cmd_list_element *c)
682{
683 gdb_assert (remote_exec_file_var != NULL);
684 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
685}
686
687/* The "set/show remote exec-file" show command hook. */
688
689static void
690show_remote_exec_file (struct ui_file *file, int from_tty,
691 struct cmd_list_element *cmd, const char *value)
692{
693 fprintf_filtered (file, "%s\n", remote_exec_file_var);
694}
695
74ca34ce
DJ
696static int
697compare_pnums (const void *lhs_, const void *rhs_)
698{
19ba03f4
SM
699 const struct packet_reg * const *lhs
700 = (const struct packet_reg * const *) lhs_;
701 const struct packet_reg * const *rhs
702 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
703
704 if ((*lhs)->pnum < (*rhs)->pnum)
705 return -1;
706 else if ((*lhs)->pnum == (*rhs)->pnum)
707 return 0;
708 else
709 return 1;
710}
711
c21236dc
PA
712static int
713map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 714{
74ca34ce 715 int regnum, num_remote_regs, offset;
74ca34ce 716 struct packet_reg **remote_regs;
ea9c271d 717
4a22f64d 718 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 719 {
c21236dc 720 struct packet_reg *r = &regs[regnum];
baef701f 721
4a22f64d 722 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
723 /* Do not try to fetch zero-sized (placeholder) registers. */
724 r->pnum = -1;
725 else
726 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
727
b323314b 728 r->regnum = regnum;
74ca34ce
DJ
729 }
730
731 /* Define the g/G packet format as the contents of each register
732 with a remote protocol number, in order of ascending protocol
733 number. */
734
224c3ddb 735 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 736 for (num_remote_regs = 0, regnum = 0;
4a22f64d 737 regnum < gdbarch_num_regs (gdbarch);
f57d151a 738 regnum++)
c21236dc
PA
739 if (regs[regnum].pnum != -1)
740 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 741
74ca34ce
DJ
742 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
743 compare_pnums);
744
745 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
746 {
747 remote_regs[regnum]->in_g_packet = 1;
748 remote_regs[regnum]->offset = offset;
4a22f64d 749 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
750 }
751
c21236dc
PA
752 return offset;
753}
754
755/* Given the architecture described by GDBARCH, return the remote
756 protocol register's number and the register's offset in the g/G
757 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
758 If the target does not have a mapping for REGNUM, return false,
759 otherwise, return true. */
760
761int
762remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
763 int *pnum, int *poffset)
764{
765 int sizeof_g_packet;
766 struct packet_reg *regs;
767 struct cleanup *old_chain;
768
769 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
770
224c3ddb 771 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
c21236dc
PA
772 old_chain = make_cleanup (xfree, regs);
773
774 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
775
776 *pnum = regs[regnum].pnum;
777 *poffset = regs[regnum].offset;
778
779 do_cleanups (old_chain);
780
781 return *pnum != -1;
782}
783
784static void *
785init_remote_state (struct gdbarch *gdbarch)
786{
787 struct remote_state *rs = get_remote_state_raw ();
788 struct remote_arch_state *rsa;
789
790 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
791
792 /* Use the architecture to build a regnum<->pnum table, which will be
793 1:1 unless a feature set specifies otherwise. */
794 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
795 gdbarch_num_regs (gdbarch),
796 struct packet_reg);
797
74ca34ce
DJ
798 /* Record the maximum possible size of the g packet - it may turn out
799 to be smaller. */
c21236dc 800 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 801
0df8b418 802 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
803 remote stubs have a hardwired buffer size of 400 bytes
804 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
805 as the maximum packet-size to ensure that the packet and an extra
806 NUL character can always fit in the buffer. This stops GDB
807 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
808 already a full buffer (As of 1999-12-04 that was most stubs). */
809 rsa->remote_packet_size = 400 - 1;
d01949b6 810
ea9c271d
DJ
811 /* This one is filled in when a ``g'' packet is received. */
812 rsa->actual_register_packet_size = 0;
813
814 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
815 default, adjust the size accordingly. Remember that each byte is
816 encoded as two characters. 32 is the overhead for the packet
817 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 818 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 819 little. */
ea9c271d
DJ
820 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
821 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 822
ea9c271d
DJ
823 /* Make sure that the packet buffer is plenty big enough for
824 this architecture. */
825 if (rs->buf_size < rsa->remote_packet_size)
826 {
827 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 828 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 829 }
6d820c5c 830
ea9c271d
DJ
831 return rsa;
832}
833
834/* Return the current allowed size of a remote packet. This is
835 inferred from the current architecture, and should be used to
836 limit the length of outgoing packets. */
837static long
838get_remote_packet_size (void)
839{
be2a5f71 840 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
841 struct remote_arch_state *rsa = get_remote_arch_state ();
842
be2a5f71
DJ
843 if (rs->explicit_packet_size)
844 return rs->explicit_packet_size;
845
ea9c271d 846 return rsa->remote_packet_size;
d01949b6
AC
847}
848
ad10f812 849static struct packet_reg *
ea9c271d 850packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 851{
f5656ead 852 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
853 return NULL;
854 else
ad10f812 855 {
ea9c271d 856 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 857
b323314b
AC
858 gdb_assert (r->regnum == regnum);
859 return r;
ad10f812 860 }
ad10f812
AC
861}
862
863static struct packet_reg *
ea9c271d 864packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 865{
b323314b 866 int i;
a744cf53 867
f5656ead 868 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 869 {
ea9c271d 870 struct packet_reg *r = &rsa->regs[i];
a744cf53 871
b323314b
AC
872 if (r->pnum == pnum)
873 return r;
ad10f812
AC
874 }
875 return NULL;
d01949b6
AC
876}
877
c906108c
SS
878static struct target_ops remote_ops;
879
880static struct target_ops extended_remote_ops;
881
6426a772
JM
882/* FIXME: cagney/1999-09-23: Even though getpkt was called with
883 ``forever'' still use the normal timeout mechanism. This is
884 currently used by the ASYNC code to guarentee that target reads
885 during the initial connect always time-out. Once getpkt has been
886 modified to return a timeout indication and, in turn
887 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 888 this can go away. */
6426a772
JM
889static int wait_forever_enabled_p = 1;
890
9a7071a8
JB
891/* Allow the user to specify what sequence to send to the remote
892 when he requests a program interruption: Although ^C is usually
893 what remote systems expect (this is the default, here), it is
894 sometimes preferable to send a break. On other systems such
895 as the Linux kernel, a break followed by g, which is Magic SysRq g
896 is required in order to interrupt the execution. */
897const char interrupt_sequence_control_c[] = "Ctrl-C";
898const char interrupt_sequence_break[] = "BREAK";
899const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 900static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
901 {
902 interrupt_sequence_control_c,
903 interrupt_sequence_break,
904 interrupt_sequence_break_g,
905 NULL
906 };
907static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
908
909static void
910show_interrupt_sequence (struct ui_file *file, int from_tty,
911 struct cmd_list_element *c,
912 const char *value)
913{
914 if (interrupt_sequence_mode == interrupt_sequence_control_c)
915 fprintf_filtered (file,
916 _("Send the ASCII ETX character (Ctrl-c) "
917 "to the remote target to interrupt the "
918 "execution of the program.\n"));
919 else if (interrupt_sequence_mode == interrupt_sequence_break)
920 fprintf_filtered (file,
921 _("send a break signal to the remote target "
922 "to interrupt the execution of the program.\n"));
923 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
924 fprintf_filtered (file,
925 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
926 "the remote target to interrupt the execution "
927 "of Linux kernel.\n"));
928 else
929 internal_error (__FILE__, __LINE__,
930 _("Invalid value for interrupt_sequence_mode: %s."),
931 interrupt_sequence_mode);
932}
6426a772 933
9a7071a8
JB
934/* This boolean variable specifies whether interrupt_sequence is sent
935 to the remote target when gdb connects to it.
936 This is mostly needed when you debug the Linux kernel: The Linux kernel
937 expects BREAK g which is Magic SysRq g for connecting gdb. */
938static int interrupt_on_connect = 0;
c906108c 939
9a7071a8
JB
940/* This variable is used to implement the "set/show remotebreak" commands.
941 Since these commands are now deprecated in favor of "set/show remote
942 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
943static int remote_break;
944
9a7071a8
JB
945static void
946set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
947{
948 if (remote_break)
949 interrupt_sequence_mode = interrupt_sequence_break;
950 else
951 interrupt_sequence_mode = interrupt_sequence_control_c;
952}
953
954static void
955show_remotebreak (struct ui_file *file, int from_tty,
956 struct cmd_list_element *c,
957 const char *value)
958{
959}
960
c906108c
SS
961/* This variable sets the number of bits in an address that are to be
962 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 963 leading zeros, the entire address would be sent. This variable
c906108c
SS
964 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
965 initial implementation of remote.c restricted the address sent in
966 memory packets to ``host::sizeof long'' bytes - (typically 32
967 bits). Consequently, for 64 bit targets, the upper 32 bits of an
968 address was never sent. Since fixing this bug may cause a break in
969 some remote targets this variable is principly provided to
23860348 970 facilitate backward compatibility. */
c906108c 971
883b9c6c 972static unsigned int remote_address_size;
c906108c 973
75c99385
PA
974/* Temporary to track who currently owns the terminal. See
975 remote_terminal_* for more details. */
6426a772
JM
976
977static int remote_async_terminal_ours_p;
978
11cf8741 979\f
11cf8741 980/* User configurable variables for the number of characters in a
ea9c271d
DJ
981 memory read/write packet. MIN (rsa->remote_packet_size,
982 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 983 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
984 (speed up transfers). The variables ``preferred_*'' (the user
985 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 986 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
987
988struct memory_packet_config
989{
990 char *name;
991 long size;
992 int fixed_p;
993};
994
a5c0808e
PA
995/* The default max memory-write-packet-size. The 16k is historical.
996 (It came from older GDB's using alloca for buffers and the
997 knowledge (folklore?) that some hosts don't cope very well with
998 large alloca calls.) */
999#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1000
1001/* The minimum remote packet size for memory transfers. Ensures we
1002 can write at least one byte. */
1003#define MIN_MEMORY_PACKET_SIZE 20
1004
11cf8741
JM
1005/* Compute the current size of a read/write packet. Since this makes
1006 use of ``actual_register_packet_size'' the computation is dynamic. */
1007
1008static long
1009get_memory_packet_size (struct memory_packet_config *config)
1010{
d01949b6 1011 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
1012 struct remote_arch_state *rsa = get_remote_arch_state ();
1013
11cf8741
JM
1014 long what_they_get;
1015 if (config->fixed_p)
1016 {
1017 if (config->size <= 0)
a5c0808e 1018 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1019 else
1020 what_they_get = config->size;
1021 }
1022 else
1023 {
ea9c271d 1024 what_they_get = get_remote_packet_size ();
23860348 1025 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1026 if (config->size > 0
1027 && what_they_get > config->size)
1028 what_they_get = config->size;
be2a5f71
DJ
1029
1030 /* Limit it to the size of the targets ``g'' response unless we have
1031 permission from the stub to use a larger packet size. */
1032 if (rs->explicit_packet_size == 0
1033 && rsa->actual_register_packet_size > 0
1034 && what_they_get > rsa->actual_register_packet_size)
1035 what_they_get = rsa->actual_register_packet_size;
11cf8741 1036 }
a5c0808e
PA
1037 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1038 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1039
1040 /* Make sure there is room in the global buffer for this packet
1041 (including its trailing NUL byte). */
1042 if (rs->buf_size < what_they_get + 1)
1043 {
1044 rs->buf_size = 2 * what_they_get;
224c3ddb 1045 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1046 }
1047
11cf8741
JM
1048 return what_they_get;
1049}
1050
0df8b418 1051/* Update the size of a read/write packet. If they user wants
23860348 1052 something really big then do a sanity check. */
11cf8741
JM
1053
1054static void
1055set_memory_packet_size (char *args, struct memory_packet_config *config)
1056{
1057 int fixed_p = config->fixed_p;
1058 long size = config->size;
a744cf53 1059
11cf8741 1060 if (args == NULL)
8a3fe4f8 1061 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1062 else if (strcmp (args, "hard") == 0
1063 || strcmp (args, "fixed") == 0)
1064 fixed_p = 1;
1065 else if (strcmp (args, "soft") == 0
1066 || strcmp (args, "limit") == 0)
1067 fixed_p = 0;
1068 else
1069 {
1070 char *end;
a744cf53 1071
11cf8741
JM
1072 size = strtoul (args, &end, 0);
1073 if (args == end)
8a3fe4f8 1074 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1075
1076 /* Instead of explicitly capping the size of a packet to or
1077 disallowing it, the user is allowed to set the size to
1078 something arbitrarily large. */
11cf8741 1079 }
a5c0808e
PA
1080
1081 /* So that the query shows the correct value. */
1082 if (size <= 0)
1083 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1084
23860348 1085 /* Extra checks? */
11cf8741
JM
1086 if (fixed_p && !config->fixed_p)
1087 {
e2e0b3e5
AC
1088 if (! query (_("The target may not be able to correctly handle a %s\n"
1089 "of %ld bytes. Change the packet size? "),
11cf8741 1090 config->name, size))
8a3fe4f8 1091 error (_("Packet size not changed."));
11cf8741 1092 }
23860348 1093 /* Update the config. */
11cf8741
JM
1094 config->fixed_p = fixed_p;
1095 config->size = size;
1096}
1097
1098static void
1099show_memory_packet_size (struct memory_packet_config *config)
1100{
a3f17187 1101 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1102 if (config->fixed_p)
a3f17187 1103 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1104 get_memory_packet_size (config));
1105 else
a3f17187 1106 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1107 get_memory_packet_size (config));
1108}
1109
1110static struct memory_packet_config memory_write_packet_config =
1111{
1112 "memory-write-packet-size",
1113};
1114
1115static void
1116set_memory_write_packet_size (char *args, int from_tty)
1117{
1118 set_memory_packet_size (args, &memory_write_packet_config);
1119}
1120
1121static void
1122show_memory_write_packet_size (char *args, int from_tty)
1123{
1124 show_memory_packet_size (&memory_write_packet_config);
1125}
1126
1127static long
1128get_memory_write_packet_size (void)
1129{
1130 return get_memory_packet_size (&memory_write_packet_config);
1131}
1132
1133static struct memory_packet_config memory_read_packet_config =
1134{
1135 "memory-read-packet-size",
1136};
1137
1138static void
1139set_memory_read_packet_size (char *args, int from_tty)
1140{
1141 set_memory_packet_size (args, &memory_read_packet_config);
1142}
1143
1144static void
1145show_memory_read_packet_size (char *args, int from_tty)
1146{
1147 show_memory_packet_size (&memory_read_packet_config);
1148}
1149
1150static long
1151get_memory_read_packet_size (void)
1152{
1153 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1154
11cf8741
JM
1155 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1156 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1157 increased beyond this. */
1158 if (size > get_remote_packet_size ())
1159 size = get_remote_packet_size ();
11cf8741
JM
1160 return size;
1161}
1162
11cf8741 1163\f
5a2468f5 1164/* Generic configuration support for packets the stub optionally
0df8b418 1165 supports. Allows the user to specify the use of the packet as well
23860348 1166 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1167
1168enum packet_support
1169 {
1170 PACKET_SUPPORT_UNKNOWN = 0,
1171 PACKET_ENABLE,
1172 PACKET_DISABLE
1173 };
1174
5a2468f5
JM
1175struct packet_config
1176 {
bb572ddd
DJ
1177 const char *name;
1178 const char *title;
4082afcc
PA
1179
1180 /* If auto, GDB auto-detects support for this packet or feature,
1181 either through qSupported, or by trying the packet and looking
1182 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1183 packet. If false, the packet is disabled. Configs that don't
1184 have an associated command always have this set to auto. */
7f19b9a2 1185 enum auto_boolean detect;
4082afcc
PA
1186
1187 /* Does the target support this packet? */
5a2468f5
JM
1188 enum packet_support support;
1189 };
1190
d471ea57 1191/* Analyze a packet's return value and update the packet config
23860348 1192 accordingly. */
d471ea57
AC
1193
1194enum packet_result
1195{
1196 PACKET_ERROR,
1197 PACKET_OK,
1198 PACKET_UNKNOWN
1199};
1200
4082afcc
PA
1201static enum packet_support packet_config_support (struct packet_config *config);
1202static enum packet_support packet_support (int packet);
5a2468f5
JM
1203
1204static void
fba45db2 1205show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1206{
1207 char *support = "internal-error";
a744cf53 1208
4082afcc 1209 switch (packet_config_support (config))
5a2468f5
JM
1210 {
1211 case PACKET_ENABLE:
1212 support = "enabled";
1213 break;
1214 case PACKET_DISABLE:
1215 support = "disabled";
1216 break;
1217 case PACKET_SUPPORT_UNKNOWN:
1218 support = "unknown";
1219 break;
1220 }
1221 switch (config->detect)
1222 {
7f19b9a2 1223 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1224 printf_filtered (_("Support for the `%s' packet "
1225 "is auto-detected, currently %s.\n"),
37a105a1 1226 config->name, support);
5a2468f5 1227 break;
7f19b9a2
AC
1228 case AUTO_BOOLEAN_TRUE:
1229 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1230 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1231 config->name, support);
8e248173 1232 break;
5a2468f5
JM
1233 }
1234}
1235
1236static void
bb572ddd
DJ
1237add_packet_config_cmd (struct packet_config *config, const char *name,
1238 const char *title, int legacy)
d471ea57 1239{
5a2468f5
JM
1240 char *set_doc;
1241 char *show_doc;
d471ea57 1242 char *cmd_name;
3ed07be4 1243
5a2468f5
JM
1244 config->name = name;
1245 config->title = title;
b435e160
AC
1246 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1247 name, title);
3e43a32a
MS
1248 show_doc = xstrprintf ("Show current use of remote "
1249 "protocol `%s' (%s) packet",
b435e160 1250 name, title);
d471ea57 1251 /* set/show TITLE-packet {auto,on,off} */
b435e160 1252 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1253 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1254 &config->detect, set_doc,
1255 show_doc, NULL, /* help_doc */
4082afcc 1256 NULL,
bb572ddd
DJ
1257 show_remote_protocol_packet_cmd,
1258 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1259 /* The command code copies the documentation strings. */
1260 xfree (set_doc);
1261 xfree (show_doc);
23860348 1262 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1263 if (legacy)
1264 {
1265 char *legacy_name;
a744cf53 1266
b435e160 1267 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1268 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1269 &remote_set_cmdlist);
d471ea57 1270 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1271 &remote_show_cmdlist);
d471ea57 1272 }
5a2468f5
JM
1273}
1274
d471ea57 1275static enum packet_result
a76d924d 1276packet_check_result (const char *buf)
5a2468f5 1277{
d471ea57 1278 if (buf[0] != '\0')
5a2468f5 1279 {
d471ea57 1280 /* The stub recognized the packet request. Check that the
23860348 1281 operation succeeded. */
a76d924d
DJ
1282 if (buf[0] == 'E'
1283 && isxdigit (buf[1]) && isxdigit (buf[2])
1284 && buf[3] == '\0')
1285 /* "Enn" - definitly an error. */
1286 return PACKET_ERROR;
1287
1288 /* Always treat "E." as an error. This will be used for
1289 more verbose error messages, such as E.memtypes. */
1290 if (buf[0] == 'E' && buf[1] == '.')
1291 return PACKET_ERROR;
1292
1293 /* The packet may or may not be OK. Just assume it is. */
1294 return PACKET_OK;
1295 }
1296 else
1297 /* The stub does not support the packet. */
1298 return PACKET_UNKNOWN;
1299}
1300
1301static enum packet_result
1302packet_ok (const char *buf, struct packet_config *config)
1303{
1304 enum packet_result result;
1305
4082afcc
PA
1306 if (config->detect != AUTO_BOOLEAN_TRUE
1307 && config->support == PACKET_DISABLE)
1308 internal_error (__FILE__, __LINE__,
1309 _("packet_ok: attempt to use a disabled packet"));
1310
a76d924d
DJ
1311 result = packet_check_result (buf);
1312 switch (result)
1313 {
1314 case PACKET_OK:
1315 case PACKET_ERROR:
1316 /* The stub recognized the packet request. */
4082afcc 1317 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1318 {
d471ea57
AC
1319 if (remote_debug)
1320 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1321 "Packet %s (%s) is supported\n",
1322 config->name, config->title);
d471ea57 1323 config->support = PACKET_ENABLE;
d471ea57 1324 }
a76d924d
DJ
1325 break;
1326 case PACKET_UNKNOWN:
23860348 1327 /* The stub does not support the packet. */
4082afcc
PA
1328 if (config->detect == AUTO_BOOLEAN_AUTO
1329 && config->support == PACKET_ENABLE)
d471ea57 1330 {
4082afcc
PA
1331 /* If the stub previously indicated that the packet was
1332 supported then there is a protocol error. */
1333 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1334 config->name, config->title);
1335 }
1336 else if (config->detect == AUTO_BOOLEAN_TRUE)
1337 {
1338 /* The user set it wrong. */
1339 error (_("Enabled packet %s (%s) not recognized by stub"),
1340 config->name, config->title);
d471ea57 1341 }
4082afcc
PA
1342
1343 if (remote_debug)
1344 fprintf_unfiltered (gdb_stdlog,
1345 "Packet %s (%s) is NOT supported\n",
1346 config->name, config->title);
1347 config->support = PACKET_DISABLE;
a76d924d 1348 break;
5a2468f5 1349 }
a76d924d
DJ
1350
1351 return result;
5a2468f5
JM
1352}
1353
444abaca
DJ
1354enum {
1355 PACKET_vCont = 0,
1356 PACKET_X,
1357 PACKET_qSymbol,
1358 PACKET_P,
1359 PACKET_p,
1360 PACKET_Z0,
1361 PACKET_Z1,
1362 PACKET_Z2,
1363 PACKET_Z3,
1364 PACKET_Z4,
15a201c8 1365 PACKET_vFile_setfs,
a6b151f1
DJ
1366 PACKET_vFile_open,
1367 PACKET_vFile_pread,
1368 PACKET_vFile_pwrite,
1369 PACKET_vFile_close,
1370 PACKET_vFile_unlink,
b9e7b9c3 1371 PACKET_vFile_readlink,
0a93529c 1372 PACKET_vFile_fstat,
0876f84a 1373 PACKET_qXfer_auxv,
23181151 1374 PACKET_qXfer_features,
c78fa86a 1375 PACKET_qXfer_exec_file,
cfa9d6d9 1376 PACKET_qXfer_libraries,
2268b414 1377 PACKET_qXfer_libraries_svr4,
fd79ecee 1378 PACKET_qXfer_memory_map,
0e7f50da
UW
1379 PACKET_qXfer_spu_read,
1380 PACKET_qXfer_spu_write,
07e059b5 1381 PACKET_qXfer_osdata,
dc146f7c 1382 PACKET_qXfer_threads,
0fb4aa4b 1383 PACKET_qXfer_statictrace_read,
b3b9301e 1384 PACKET_qXfer_traceframe_info,
169081d0 1385 PACKET_qXfer_uib,
711e434b 1386 PACKET_qGetTIBAddr,
444abaca 1387 PACKET_qGetTLSAddr,
be2a5f71 1388 PACKET_qSupported,
bd3eecc3 1389 PACKET_qTStatus,
89be2091 1390 PACKET_QPassSignals,
9b224c5e 1391 PACKET_QProgramSignals,
936d2992 1392 PACKET_qCRC,
08388c79 1393 PACKET_qSearch_memory,
2d717e4f
DJ
1394 PACKET_vAttach,
1395 PACKET_vRun,
a6f3e723 1396 PACKET_QStartNoAckMode,
82f73884 1397 PACKET_vKill,
4aa995e1
PA
1398 PACKET_qXfer_siginfo_read,
1399 PACKET_qXfer_siginfo_write,
0b16c5cf 1400 PACKET_qAttached,
4082afcc
PA
1401
1402 /* Support for conditional tracepoints. */
782b2b07 1403 PACKET_ConditionalTracepoints,
4082afcc
PA
1404
1405 /* Support for target-side breakpoint conditions. */
3788aec7 1406 PACKET_ConditionalBreakpoints,
4082afcc
PA
1407
1408 /* Support for target-side breakpoint commands. */
d3ce09f5 1409 PACKET_BreakpointCommands,
4082afcc
PA
1410
1411 /* Support for fast tracepoints. */
7a697b8d 1412 PACKET_FastTracepoints,
4082afcc
PA
1413
1414 /* Support for static tracepoints. */
0fb4aa4b 1415 PACKET_StaticTracepoints,
4082afcc
PA
1416
1417 /* Support for installing tracepoints while a trace experiment is
1418 running. */
1e4d1764 1419 PACKET_InstallInTrace,
4082afcc 1420
40ab02ce
MS
1421 PACKET_bc,
1422 PACKET_bs,
409873ef 1423 PACKET_TracepointSource,
d914c394 1424 PACKET_QAllow,
78d85199 1425 PACKET_qXfer_fdpic,
03583c20 1426 PACKET_QDisableRandomization,
d1feda86 1427 PACKET_QAgent,
f6f899bf 1428 PACKET_QTBuffer_size,
9accd112
MM
1429 PACKET_Qbtrace_off,
1430 PACKET_Qbtrace_bts,
b20a6524 1431 PACKET_Qbtrace_pt,
9accd112 1432 PACKET_qXfer_btrace,
4082afcc
PA
1433
1434 /* Support for the QNonStop packet. */
1435 PACKET_QNonStop,
1436
1437 /* Support for multi-process extensions. */
1438 PACKET_multiprocess_feature,
1439
1440 /* Support for enabling and disabling tracepoints while a trace
1441 experiment is running. */
1442 PACKET_EnableDisableTracepoints_feature,
1443
1444 /* Support for collecting strings using the tracenz bytecode. */
1445 PACKET_tracenz_feature,
1446
1447 /* Support for continuing to run a trace experiment while GDB is
1448 disconnected. */
1449 PACKET_DisconnectedTracing_feature,
1450
1451 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1452 PACKET_augmented_libraries_svr4_read_feature,
1453
f4abbc16
MM
1454 /* Support for the qXfer:btrace-conf:read packet. */
1455 PACKET_qXfer_btrace_conf,
1456
d33501a5
MM
1457 /* Support for the Qbtrace-conf:bts:size packet. */
1458 PACKET_Qbtrace_conf_bts_size,
1459
f7e6eed5
PA
1460 /* Support for swbreak+ feature. */
1461 PACKET_swbreak_feature,
1462
1463 /* Support for hwbreak+ feature. */
1464 PACKET_hwbreak_feature,
1465
89245bc0
DB
1466 /* Support for fork events. */
1467 PACKET_fork_event_feature,
1468
1469 /* Support for vfork events. */
1470 PACKET_vfork_event_feature,
1471
b20a6524
MM
1472 /* Support for the Qbtrace-conf:pt:size packet. */
1473 PACKET_Qbtrace_conf_pt_size,
1474
94585166
DB
1475 /* Support for exec events. */
1476 PACKET_exec_event_feature,
1477
750ce8d1
YQ
1478 /* Support for query supported vCont actions. */
1479 PACKET_vContSupported,
1480
444abaca
DJ
1481 PACKET_MAX
1482};
506fb367 1483
444abaca 1484static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1485
f7e6eed5
PA
1486/* Returns the packet's corresponding "set remote foo-packet" command
1487 state. See struct packet_config for more details. */
1488
1489static enum auto_boolean
1490packet_set_cmd_state (int packet)
1491{
1492 return remote_protocol_packets[packet].detect;
1493}
1494
4082afcc
PA
1495/* Returns whether a given packet or feature is supported. This takes
1496 into account the state of the corresponding "set remote foo-packet"
1497 command, which may be used to bypass auto-detection. */
dc8acb97 1498
4082afcc
PA
1499static enum packet_support
1500packet_config_support (struct packet_config *config)
1501{
1502 switch (config->detect)
444abaca 1503 {
4082afcc
PA
1504 case AUTO_BOOLEAN_TRUE:
1505 return PACKET_ENABLE;
1506 case AUTO_BOOLEAN_FALSE:
1507 return PACKET_DISABLE;
1508 case AUTO_BOOLEAN_AUTO:
1509 return config->support;
1510 default:
1511 gdb_assert_not_reached (_("bad switch"));
444abaca 1512 }
4082afcc
PA
1513}
1514
1515/* Same as packet_config_support, but takes the packet's enum value as
1516 argument. */
1517
1518static enum packet_support
1519packet_support (int packet)
1520{
1521 struct packet_config *config = &remote_protocol_packets[packet];
1522
1523 return packet_config_support (config);
dc8acb97
MS
1524}
1525
5a2468f5 1526static void
444abaca
DJ
1527show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1528 struct cmd_list_element *c,
1529 const char *value)
5a2468f5 1530{
444abaca 1531 struct packet_config *packet;
5a2468f5 1532
444abaca
DJ
1533 for (packet = remote_protocol_packets;
1534 packet < &remote_protocol_packets[PACKET_MAX];
1535 packet++)
1536 {
1537 if (&packet->detect == c->var)
1538 {
1539 show_packet_config_cmd (packet);
1540 return;
1541 }
1542 }
9b20d036 1543 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1544 c->name);
5a2468f5
JM
1545}
1546
d471ea57
AC
1547/* Should we try one of the 'Z' requests? */
1548
1549enum Z_packet_type
1550{
1551 Z_PACKET_SOFTWARE_BP,
1552 Z_PACKET_HARDWARE_BP,
1553 Z_PACKET_WRITE_WP,
1554 Z_PACKET_READ_WP,
1555 Z_PACKET_ACCESS_WP,
1556 NR_Z_PACKET_TYPES
1557};
96baa820 1558
d471ea57 1559/* For compatibility with older distributions. Provide a ``set remote
23860348 1560 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1561
7f19b9a2 1562static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1563
1564static void
fba45db2
KB
1565set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1566 struct cmd_list_element *c)
96baa820 1567{
d471ea57 1568 int i;
a744cf53 1569
d471ea57 1570 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1571 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1572}
1573
1574static void
08546159
AC
1575show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1576 struct cmd_list_element *c,
1577 const char *value)
96baa820 1578{
d471ea57 1579 int i;
a744cf53 1580
d471ea57
AC
1581 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1582 {
444abaca 1583 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1584 }
96baa820
JM
1585}
1586
4082afcc
PA
1587/* Returns true if the multi-process extensions are in effect. */
1588
1589static int
1590remote_multi_process_p (struct remote_state *rs)
1591{
1592 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1593}
1594
de0d863e
DB
1595/* Returns true if fork events are supported. */
1596
1597static int
1598remote_fork_event_p (struct remote_state *rs)
1599{
1600 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1601}
1602
c269dbdb
DB
1603/* Returns true if vfork events are supported. */
1604
1605static int
1606remote_vfork_event_p (struct remote_state *rs)
1607{
1608 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1609}
1610
d46addbb
DB
1611/* Returns true if exec events are supported. */
1612
1613static int
1614remote_exec_event_p (struct remote_state *rs)
1615{
1616 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1617}
1618
cbb8991c
DB
1619/* Insert fork catchpoint target routine. If fork events are enabled
1620 then return success, nothing more to do. */
1621
1622static int
1623remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1624{
1625 struct remote_state *rs = get_remote_state ();
1626
1627 return !remote_fork_event_p (rs);
1628}
1629
1630/* Remove fork catchpoint target routine. Nothing to do, just
1631 return success. */
1632
1633static int
1634remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1635{
1636 return 0;
1637}
1638
1639/* Insert vfork catchpoint target routine. If vfork events are enabled
1640 then return success, nothing more to do. */
1641
1642static int
1643remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1644{
1645 struct remote_state *rs = get_remote_state ();
1646
1647 return !remote_vfork_event_p (rs);
1648}
1649
1650/* Remove vfork catchpoint target routine. Nothing to do, just
1651 return success. */
1652
1653static int
1654remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1655{
1656 return 0;
1657}
1658
d46addbb
DB
1659/* Insert exec catchpoint target routine. If exec events are
1660 enabled, just return success. */
1661
1662static int
1663remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1664{
1665 struct remote_state *rs = get_remote_state ();
1666
1667 return !remote_exec_event_p (rs);
1668}
1669
1670/* Remove exec catchpoint target routine. Nothing to do, just
1671 return success. */
1672
1673static int
1674remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1675{
1676 return 0;
1677}
1678
23860348 1679/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1680static struct async_signal_handler *async_sigint_remote_twice_token;
1681static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1682
74531fed
PA
1683\f
1684/* Asynchronous signal handle registered as event loop source for
1685 when we have pending events ready to be passed to the core. */
1686
1687static struct async_event_handler *remote_async_inferior_event_token;
1688
c906108c
SS
1689\f
1690
79d7f229
PA
1691static ptid_t magic_null_ptid;
1692static ptid_t not_sent_ptid;
1693static ptid_t any_thread_ptid;
1694
0b16c5cf
PA
1695/* Find out if the stub attached to PID (and hence GDB should offer to
1696 detach instead of killing it when bailing out). */
1697
1698static int
1699remote_query_attached (int pid)
1700{
1701 struct remote_state *rs = get_remote_state ();
bba74b36 1702 size_t size = get_remote_packet_size ();
0b16c5cf 1703
4082afcc 1704 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1705 return 0;
1706
1707 if (remote_multi_process_p (rs))
bba74b36 1708 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1709 else
bba74b36 1710 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1711
1712 putpkt (rs->buf);
1713 getpkt (&rs->buf, &rs->buf_size, 0);
1714
1715 switch (packet_ok (rs->buf,
1554e9be 1716 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1717 {
1718 case PACKET_OK:
1719 if (strcmp (rs->buf, "1") == 0)
1720 return 1;
1721 break;
1722 case PACKET_ERROR:
1723 warning (_("Remote failure reply: %s"), rs->buf);
1724 break;
1725 case PACKET_UNKNOWN:
1726 break;
1727 }
1728
1729 return 0;
1730}
1731
49c62f2e
PA
1732/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1733 has been invented by GDB, instead of reported by the target. Since
1734 we can be connected to a remote system before before knowing about
1735 any inferior, mark the target with execution when we find the first
1736 inferior. If ATTACHED is 1, then we had just attached to this
1737 inferior. If it is 0, then we just created this inferior. If it
1738 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1739 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1740 attempt to open this inferior's executable as the main executable
1741 if no main executable is open already. */
1941c569
PA
1742
1743static struct inferior *
1b6e6f5c
GB
1744remote_add_inferior (int fake_pid_p, int pid, int attached,
1745 int try_open_exec)
1941c569 1746{
1941c569
PA
1747 struct inferior *inf;
1748
0b16c5cf
PA
1749 /* Check whether this process we're learning about is to be
1750 considered attached, or if is to be considered to have been
1751 spawned by the stub. */
1752 if (attached == -1)
1753 attached = remote_query_attached (pid);
1754
f5656ead 1755 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1756 {
1757 /* If the target shares code across all inferiors, then every
1758 attach adds a new inferior. */
1759 inf = add_inferior (pid);
1760
1761 /* ... and every inferior is bound to the same program space.
1762 However, each inferior may still have its own address
1763 space. */
1764 inf->aspace = maybe_new_address_space ();
1765 inf->pspace = current_program_space;
1766 }
1767 else
1768 {
1769 /* In the traditional debugging scenario, there's a 1-1 match
1770 between program/address spaces. We simply bind the inferior
1771 to the program space's address space. */
1772 inf = current_inferior ();
1773 inferior_appeared (inf, pid);
1774 }
1941c569 1775
0b16c5cf 1776 inf->attach_flag = attached;
49c62f2e 1777 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1778
1b6e6f5c
GB
1779 /* If no main executable is currently open then attempt to
1780 open the file that was executed to create this inferior. */
835205d0 1781 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1782 exec_file_locate_attach (pid, 1);
1783
1941c569
PA
1784 return inf;
1785}
1786
1787/* Add thread PTID to GDB's thread list. Tag it as executing/running
1788 according to RUNNING. */
1789
c906108c 1790static void
1941c569 1791remote_add_thread (ptid_t ptid, int running)
c906108c 1792{
b7ea362b
PA
1793 struct remote_state *rs = get_remote_state ();
1794
1795 /* GDB historically didn't pull threads in the initial connection
1796 setup. If the remote target doesn't even have a concept of
1797 threads (e.g., a bare-metal target), even if internally we
1798 consider that a single-threaded target, mentioning a new thread
1799 might be confusing to the user. Be silent then, preserving the
1800 age old behavior. */
1801 if (rs->starting_up)
1802 add_thread_silent (ptid);
1803 else
1804 add_thread (ptid);
1941c569
PA
1805
1806 set_executing (ptid, running);
1807 set_running (ptid, running);
1808}
1809
1810/* Come here when we learn about a thread id from the remote target.
1811 It may be the first time we hear about such thread, so take the
1812 opportunity to add it to GDB's thread list. In case this is the
1813 first time we're noticing its corresponding inferior, add it to
1814 GDB's inferior list as well. */
1815
1816static void
1817remote_notice_new_inferior (ptid_t currthread, int running)
1818{
c906108c
SS
1819 /* If this is a new thread, add it to GDB's thread list.
1820 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1821
1822 if (in_thread_list (currthread) && is_exited (currthread))
1823 {
1824 /* We're seeing an event on a thread id we knew had exited.
1825 This has to be a new thread reusing the old id. Add it. */
1941c569 1826 remote_add_thread (currthread, running);
82f73884
PA
1827 return;
1828 }
1829
79d7f229 1830 if (!in_thread_list (currthread))
c0a2216e 1831 {
1941c569 1832 struct inferior *inf = NULL;
bad34192 1833 int pid = ptid_get_pid (currthread);
1941c569 1834
bad34192
PA
1835 if (ptid_is_pid (inferior_ptid)
1836 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1837 {
1838 /* inferior_ptid has no thread member yet. This can happen
1839 with the vAttach -> remote_wait,"TAAthread:" path if the
1840 stub doesn't support qC. This is the first stop reported
1841 after an attach, so this is the main thread. Update the
1842 ptid in the thread list. */
bad34192
PA
1843 if (in_thread_list (pid_to_ptid (pid)))
1844 thread_change_ptid (inferior_ptid, currthread);
1845 else
1846 {
1847 remote_add_thread (currthread, running);
1848 inferior_ptid = currthread;
1849 }
dc146f7c 1850 return;
c0a2216e 1851 }
82f73884
PA
1852
1853 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1854 {
1855 /* inferior_ptid is not set yet. This can happen with the
1856 vRun -> remote_wait,"TAAthread:" path if the stub
1857 doesn't support qC. This is the first stop reported
1858 after an attach, so this is the main thread. Update the
1859 ptid in the thread list. */
dc146f7c 1860 thread_change_ptid (inferior_ptid, currthread);
82f73884 1861 return;
c0a2216e 1862 }
82f73884 1863
29c87f7f
PA
1864 /* When connecting to a target remote, or to a target
1865 extended-remote which already was debugging an inferior, we
1866 may not know about it yet. Add it before adding its child
1867 thread, so notifications are emitted in a sensible order. */
1868 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1869 {
1870 struct remote_state *rs = get_remote_state ();
1871 int fake_pid_p = !remote_multi_process_p (rs);
1872
1873 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1874 ptid_get_pid (currthread), -1, 1);
49c62f2e 1875 }
29c87f7f 1876
82f73884 1877 /* This is really a new thread. Add it. */
1941c569
PA
1878 remote_add_thread (currthread, running);
1879
1880 /* If we found a new inferior, let the common code do whatever
1881 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1882 breakpoints), unless we're just setting up an all-stop
1883 connection. */
1941c569 1884 if (inf != NULL)
b7ea362b
PA
1885 {
1886 struct remote_state *rs = get_remote_state ();
1887
1888 if (non_stop || !rs->starting_up)
1889 notice_new_inferior (currthread, running, 0);
1890 }
c0a2216e 1891 }
c906108c
SS
1892}
1893
dc146f7c
VP
1894/* Return the private thread data, creating it if necessary. */
1895
70221824 1896static struct private_thread_info *
dc146f7c
VP
1897demand_private_info (ptid_t ptid)
1898{
1899 struct thread_info *info = find_thread_ptid (ptid);
1900
1901 gdb_assert (info);
1902
fe978cb0 1903 if (!info->priv)
dc146f7c 1904 {
8d749320 1905 info->priv = XNEW (struct private_thread_info);
dc146f7c 1906 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1907 info->priv->core = -1;
1908 info->priv->extra = 0;
dc146f7c
VP
1909 }
1910
fe978cb0 1911 return info->priv;
dc146f7c
VP
1912}
1913
74531fed
PA
1914/* Call this function as a result of
1915 1) A halt indication (T packet) containing a thread id
1916 2) A direct query of currthread
0df8b418 1917 3) Successful execution of set thread */
74531fed
PA
1918
1919static void
47f8a51d 1920record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1921{
47f8a51d 1922 rs->general_thread = currthread;
74531fed
PA
1923}
1924
89be2091
DJ
1925/* If 'QPassSignals' is supported, tell the remote stub what signals
1926 it can simply pass through to the inferior without reporting. */
1927
1928static void
94bedb42
TT
1929remote_pass_signals (struct target_ops *self,
1930 int numsigs, unsigned char *pass_signals)
89be2091 1931{
4082afcc 1932 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1933 {
1934 char *pass_packet, *p;
89be2091 1935 int count = 0, i;
747dc59d 1936 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1937
1938 gdb_assert (numsigs < 256);
1939 for (i = 0; i < numsigs; i++)
1940 {
2455069d 1941 if (pass_signals[i])
89be2091
DJ
1942 count++;
1943 }
224c3ddb 1944 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
1945 strcpy (pass_packet, "QPassSignals:");
1946 p = pass_packet + strlen (pass_packet);
1947 for (i = 0; i < numsigs; i++)
1948 {
2455069d 1949 if (pass_signals[i])
89be2091
DJ
1950 {
1951 if (i >= 16)
1952 *p++ = tohex (i >> 4);
1953 *p++ = tohex (i & 15);
1954 if (count)
1955 *p++ = ';';
1956 else
1957 break;
1958 count--;
1959 }
1960 }
1961 *p = 0;
747dc59d 1962 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1963 {
89be2091
DJ
1964 putpkt (pass_packet);
1965 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1966 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1967 if (rs->last_pass_packet)
1968 xfree (rs->last_pass_packet);
1969 rs->last_pass_packet = pass_packet;
89be2091
DJ
1970 }
1971 else
1972 xfree (pass_packet);
1973 }
1974}
1975
9b224c5e
PA
1976/* If 'QProgramSignals' is supported, tell the remote stub what
1977 signals it should pass through to the inferior when detaching. */
1978
1979static void
daf5e9b6
TT
1980remote_program_signals (struct target_ops *self,
1981 int numsigs, unsigned char *signals)
9b224c5e 1982{
4082afcc 1983 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1984 {
1985 char *packet, *p;
1986 int count = 0, i;
5e4a05c4 1987 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1988
1989 gdb_assert (numsigs < 256);
1990 for (i = 0; i < numsigs; i++)
1991 {
1992 if (signals[i])
1993 count++;
1994 }
224c3ddb 1995 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
1996 strcpy (packet, "QProgramSignals:");
1997 p = packet + strlen (packet);
1998 for (i = 0; i < numsigs; i++)
1999 {
2000 if (signal_pass_state (i))
2001 {
2002 if (i >= 16)
2003 *p++ = tohex (i >> 4);
2004 *p++ = tohex (i & 15);
2005 if (count)
2006 *p++ = ';';
2007 else
2008 break;
2009 count--;
2010 }
2011 }
2012 *p = 0;
5e4a05c4
TT
2013 if (!rs->last_program_signals_packet
2014 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2015 {
9b224c5e
PA
2016 putpkt (packet);
2017 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2018 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2019 xfree (rs->last_program_signals_packet);
2020 rs->last_program_signals_packet = packet;
9b224c5e
PA
2021 }
2022 else
2023 xfree (packet);
2024 }
2025}
2026
79d7f229
PA
2027/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2028 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2029 thread. If GEN is set, set the general thread, if not, then set
2030 the step/continue thread. */
c906108c 2031static void
79d7f229 2032set_thread (struct ptid ptid, int gen)
c906108c 2033{
d01949b6 2034 struct remote_state *rs = get_remote_state ();
47f8a51d 2035 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2036 char *buf = rs->buf;
79d7f229 2037 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2038
79d7f229 2039 if (ptid_equal (state, ptid))
c906108c
SS
2040 return;
2041
79d7f229
PA
2042 *buf++ = 'H';
2043 *buf++ = gen ? 'g' : 'c';
2044 if (ptid_equal (ptid, magic_null_ptid))
2045 xsnprintf (buf, endbuf - buf, "0");
2046 else if (ptid_equal (ptid, any_thread_ptid))
2047 xsnprintf (buf, endbuf - buf, "0");
2048 else if (ptid_equal (ptid, minus_one_ptid))
2049 xsnprintf (buf, endbuf - buf, "-1");
2050 else
82f73884 2051 write_ptid (buf, endbuf, ptid);
79d7f229 2052 putpkt (rs->buf);
6d820c5c 2053 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2054 if (gen)
47f8a51d 2055 rs->general_thread = ptid;
c906108c 2056 else
47f8a51d 2057 rs->continue_thread = ptid;
c906108c 2058}
79d7f229
PA
2059
2060static void
2061set_general_thread (struct ptid ptid)
2062{
2063 set_thread (ptid, 1);
2064}
2065
2066static void
2067set_continue_thread (struct ptid ptid)
2068{
2069 set_thread (ptid, 0);
2070}
2071
3c9c4b83
PA
2072/* Change the remote current process. Which thread within the process
2073 ends up selected isn't important, as long as it is the same process
2074 as what INFERIOR_PTID points to.
2075
2076 This comes from that fact that there is no explicit notion of
2077 "selected process" in the protocol. The selected process for
2078 general operations is the process the selected general thread
2079 belongs to. */
2080
2081static void
2082set_general_process (void)
2083{
2084 struct remote_state *rs = get_remote_state ();
2085
2086 /* If the remote can't handle multiple processes, don't bother. */
901f9912 2087 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
2088 return;
2089
2090 /* We only need to change the remote current thread if it's pointing
2091 at some other process. */
47f8a51d 2092 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2093 set_general_thread (inferior_ptid);
2094}
2095
c906108c 2096\f
7d1a114c
PA
2097/* Return nonzero if this is the main thread that we made up ourselves
2098 to model non-threaded targets as single-threaded. */
c906108c
SS
2099
2100static int
7d1a114c 2101remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2102{
6d820c5c 2103 struct remote_state *rs = get_remote_state ();
82f73884 2104 char *p, *endp;
c906108c 2105
c0a2216e
PA
2106 if (ptid_equal (ptid, magic_null_ptid))
2107 /* The main thread is always alive. */
2108 return 1;
2109
ba348170 2110 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2111 /* The main thread is always alive. This can happen after a
2112 vAttach, if the remote side doesn't support
2113 multi-threading. */
2114 return 1;
2115
7d1a114c
PA
2116 return 0;
2117}
2118
2119/* Return nonzero if the thread PTID is still alive on the remote
2120 system. */
2121
2122static int
2123remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2124{
2125 struct remote_state *rs = get_remote_state ();
2126 char *p, *endp;
2127
2128 /* Check if this is a thread that we made up ourselves to model
2129 non-threaded targets as single-threaded. */
2130 if (remote_thread_always_alive (ops, ptid))
2131 return 1;
2132
82f73884
PA
2133 p = rs->buf;
2134 endp = rs->buf + get_remote_packet_size ();
2135
2136 *p++ = 'T';
2137 write_ptid (p, endp, ptid);
2138
2e9f7625 2139 putpkt (rs->buf);
6d820c5c 2140 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2141 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2142}
2143
2144/* About these extended threadlist and threadinfo packets. They are
2145 variable length packets but, the fields within them are often fixed
2146 length. They are redundent enough to send over UDP as is the
2147 remote protocol in general. There is a matching unit test module
2148 in libstub. */
2149
23860348 2150/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2151 libstub protocol encoding, and remote.c. It is not particularly
23860348 2152 changable. */
cce74817
JM
2153
2154/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2155 Plan to fix this. */
cce74817 2156
23860348 2157typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2158
9d1f7ab2 2159/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2160 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2161
2162struct gdb_ext_thread_info
c5aa993b 2163 {
23860348 2164 threadref threadid; /* External form of thread reference. */
2bc416ba 2165 int active; /* Has state interesting to GDB?
23860348 2166 regs, stack. */
2bc416ba 2167 char display[256]; /* Brief state display, name,
cedea757 2168 blocked/suspended. */
23860348 2169 char shortname[32]; /* To be used to name threads. */
2bc416ba 2170 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2171 whatever. */
c5aa993b 2172 };
cce74817
JM
2173
2174/* The volume of remote transfers can be limited by submitting
2175 a mask containing bits specifying the desired information.
2176 Use a union of these values as the 'selection' parameter to
0df8b418 2177 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2178
2179#define TAG_THREADID 1
2180#define TAG_EXISTS 2
2181#define TAG_DISPLAY 4
2182#define TAG_THREADNAME 8
c5aa993b 2183#define TAG_MOREDISPLAY 16
cce74817 2184
23860348 2185#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2186
a14ed312 2187static char *unpack_nibble (char *buf, int *val);
cce74817 2188
a14ed312 2189static char *unpack_byte (char *buf, int *value);
cce74817 2190
a14ed312 2191static char *pack_int (char *buf, int value);
cce74817 2192
a14ed312 2193static char *unpack_int (char *buf, int *value);
cce74817 2194
a14ed312 2195static char *unpack_string (char *src, char *dest, int length);
cce74817 2196
23860348 2197static char *pack_threadid (char *pkt, threadref *id);
cce74817 2198
23860348 2199static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2200
23860348 2201void int_to_threadref (threadref *id, int value);
cce74817 2202
23860348 2203static int threadref_to_int (threadref *ref);
cce74817 2204
23860348 2205static void copy_threadref (threadref *dest, threadref *src);
cce74817 2206
23860348 2207static int threadmatch (threadref *dest, threadref *src);
cce74817 2208
2bc416ba 2209static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2210 threadref *id);
cce74817 2211
a14ed312 2212static int remote_unpack_thread_info_response (char *pkt,
23860348 2213 threadref *expectedref,
a14ed312
KB
2214 struct gdb_ext_thread_info
2215 *info);
cce74817
JM
2216
2217
2bc416ba 2218static int remote_get_threadinfo (threadref *threadid,
23860348 2219 int fieldset, /*TAG mask */
a14ed312 2220 struct gdb_ext_thread_info *info);
cce74817 2221
a14ed312
KB
2222static char *pack_threadlist_request (char *pkt, int startflag,
2223 int threadcount,
23860348 2224 threadref *nextthread);
cce74817 2225
a14ed312
KB
2226static int parse_threadlist_response (char *pkt,
2227 int result_limit,
23860348 2228 threadref *original_echo,
2bc416ba 2229 threadref *resultlist,
23860348 2230 int *doneflag);
cce74817 2231
a14ed312 2232static int remote_get_threadlist (int startflag,
23860348 2233 threadref *nextthread,
a14ed312
KB
2234 int result_limit,
2235 int *done,
2bc416ba 2236 int *result_count,
23860348 2237 threadref *threadlist);
cce74817 2238
23860348 2239typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2240
a14ed312
KB
2241static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2242 void *context, int looplimit);
cce74817 2243
23860348 2244static int remote_newthread_step (threadref *ref, void *context);
cce74817 2245
82f73884
PA
2246
2247/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2248 buffer we're allowed to write to. Returns
2249 BUF+CHARACTERS_WRITTEN. */
2250
2251static char *
2252write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2253{
2254 int pid, tid;
2255 struct remote_state *rs = get_remote_state ();
2256
2257 if (remote_multi_process_p (rs))
2258 {
2259 pid = ptid_get_pid (ptid);
2260 if (pid < 0)
2261 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2262 else
2263 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2264 }
ba348170 2265 tid = ptid_get_lwp (ptid);
82f73884
PA
2266 if (tid < 0)
2267 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2268 else
2269 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2270
2271 return buf;
2272}
2273
2274/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2275 passed the last parsed char. Returns null_ptid on error. */
2276
2277static ptid_t
2278read_ptid (char *buf, char **obuf)
2279{
2280 char *p = buf;
2281 char *pp;
2282 ULONGEST pid = 0, tid = 0;
82f73884
PA
2283
2284 if (*p == 'p')
2285 {
2286 /* Multi-process ptid. */
2287 pp = unpack_varlen_hex (p + 1, &pid);
2288 if (*pp != '.')
b37520b6 2289 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2290
2291 p = pp;
2292 pp = unpack_varlen_hex (p + 1, &tid);
2293 if (obuf)
2294 *obuf = pp;
ba348170 2295 return ptid_build (pid, tid, 0);
82f73884
PA
2296 }
2297
2298 /* No multi-process. Just a tid. */
2299 pp = unpack_varlen_hex (p, &tid);
2300
c9f35b34
KB
2301 /* Return null_ptid when no thread id is found. */
2302 if (p == pp)
2303 {
2304 if (obuf)
2305 *obuf = pp;
2306 return null_ptid;
2307 }
2308
82f73884 2309 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2310 what's in inferior_ptid, unless it's null at this point. If so,
2311 then since there's no way to know the pid of the reported
2312 threads, use the magic number. */
2313 if (ptid_equal (inferior_ptid, null_ptid))
2314 pid = ptid_get_pid (magic_null_ptid);
2315 else
2316 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2317
2318 if (obuf)
2319 *obuf = pp;
ba348170 2320 return ptid_build (pid, tid, 0);
82f73884
PA
2321}
2322
c906108c 2323static int
fba45db2 2324stubhex (int ch)
c906108c
SS
2325{
2326 if (ch >= 'a' && ch <= 'f')
2327 return ch - 'a' + 10;
2328 if (ch >= '0' && ch <= '9')
2329 return ch - '0';
2330 if (ch >= 'A' && ch <= 'F')
2331 return ch - 'A' + 10;
2332 return -1;
2333}
2334
2335static int
fba45db2 2336stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2337{
2338 int nibble;
2339 int retval = 0;
2340
2341 while (fieldlength)
2342 {
2343 nibble = stubhex (*buff++);
2344 retval |= nibble;
2345 fieldlength--;
2346 if (fieldlength)
2347 retval = retval << 4;
2348 }
2349 return retval;
2350}
2351
c906108c 2352static char *
fba45db2 2353unpack_nibble (char *buf, int *val)
c906108c 2354{
b7589f7d 2355 *val = fromhex (*buf++);
c906108c
SS
2356 return buf;
2357}
2358
c906108c 2359static char *
fba45db2 2360unpack_byte (char *buf, int *value)
c906108c
SS
2361{
2362 *value = stub_unpack_int (buf, 2);
2363 return buf + 2;
2364}
2365
2366static char *
fba45db2 2367pack_int (char *buf, int value)
c906108c
SS
2368{
2369 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2370 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2371 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2372 buf = pack_hex_byte (buf, (value & 0xff));
2373 return buf;
2374}
2375
2376static char *
fba45db2 2377unpack_int (char *buf, int *value)
c906108c
SS
2378{
2379 *value = stub_unpack_int (buf, 8);
2380 return buf + 8;
2381}
2382
23860348 2383#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2384static char *pack_string (char *pkt, char *string);
c906108c
SS
2385
2386static char *
fba45db2 2387pack_string (char *pkt, char *string)
c906108c
SS
2388{
2389 char ch;
2390 int len;
2391
2392 len = strlen (string);
2393 if (len > 200)
23860348 2394 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2395 pkt = pack_hex_byte (pkt, len);
2396 while (len-- > 0)
2397 {
2398 ch = *string++;
2399 if ((ch == '\0') || (ch == '#'))
23860348 2400 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2401 *pkt++ = ch;
2402 }
2403 return pkt;
2404}
2405#endif /* 0 (unused) */
2406
2407static char *
fba45db2 2408unpack_string (char *src, char *dest, int length)
c906108c
SS
2409{
2410 while (length--)
2411 *dest++ = *src++;
2412 *dest = '\0';
2413 return src;
2414}
2415
2416static char *
fba45db2 2417pack_threadid (char *pkt, threadref *id)
c906108c
SS
2418{
2419 char *limit;
2420 unsigned char *altid;
2421
2422 altid = (unsigned char *) id;
2423 limit = pkt + BUF_THREAD_ID_SIZE;
2424 while (pkt < limit)
2425 pkt = pack_hex_byte (pkt, *altid++);
2426 return pkt;
2427}
2428
2429
2430static char *
fba45db2 2431unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2432{
2433 char *altref;
2434 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2435 int x, y;
2436
2437 altref = (char *) id;
2438
2439 while (inbuf < limit)
2440 {
2441 x = stubhex (*inbuf++);
2442 y = stubhex (*inbuf++);
2443 *altref++ = (x << 4) | y;
2444 }
2445 return inbuf;
2446}
2447
2448/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2449 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2450 to use 64bit thread references internally. This is an adapter
2451 function. */
2452
2453void
fba45db2 2454int_to_threadref (threadref *id, int value)
c906108c
SS
2455{
2456 unsigned char *scan;
2457
2458 scan = (unsigned char *) id;
2459 {
2460 int i = 4;
2461 while (i--)
2462 *scan++ = 0;
2463 }
2464 *scan++ = (value >> 24) & 0xff;
2465 *scan++ = (value >> 16) & 0xff;
2466 *scan++ = (value >> 8) & 0xff;
2467 *scan++ = (value & 0xff);
2468}
2469
2470static int
fba45db2 2471threadref_to_int (threadref *ref)
c906108c
SS
2472{
2473 int i, value = 0;
2474 unsigned char *scan;
2475
cfd77fa1 2476 scan = *ref;
c906108c
SS
2477 scan += 4;
2478 i = 4;
2479 while (i-- > 0)
2480 value = (value << 8) | ((*scan++) & 0xff);
2481 return value;
2482}
2483
2484static void
fba45db2 2485copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2486{
2487 int i;
2488 unsigned char *csrc, *cdest;
2489
2490 csrc = (unsigned char *) src;
2491 cdest = (unsigned char *) dest;
2492 i = 8;
2493 while (i--)
2494 *cdest++ = *csrc++;
2495}
2496
2497static int
fba45db2 2498threadmatch (threadref *dest, threadref *src)
c906108c 2499{
23860348 2500 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2501#if 0
2502 unsigned char *srcp, *destp;
2503 int i, result;
2504 srcp = (char *) src;
2505 destp = (char *) dest;
2506
2507 result = 1;
2508 while (i-- > 0)
2509 result &= (*srcp++ == *destp++) ? 1 : 0;
2510 return result;
2511#endif
2512 return 1;
2513}
2514
2515/*
c5aa993b
JM
2516 threadid:1, # always request threadid
2517 context_exists:2,
2518 display:4,
2519 unique_name:8,
2520 more_display:16
2521 */
c906108c
SS
2522
2523/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2524
2525static char *
fba45db2 2526pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2527{
23860348
MS
2528 *pkt++ = 'q'; /* Info Query */
2529 *pkt++ = 'P'; /* process or thread info */
2530 pkt = pack_int (pkt, mode); /* mode */
c906108c 2531 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2532 *pkt = '\0'; /* terminate */
c906108c
SS
2533 return pkt;
2534}
2535
23860348 2536/* These values tag the fields in a thread info response packet. */
c906108c 2537/* Tagging the fields allows us to request specific fields and to
23860348 2538 add more fields as time goes by. */
c906108c 2539
23860348 2540#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2541#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2542 fetch registers and its stack? */
c5aa993b 2543#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2544#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2545#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2546 the process. */
c906108c
SS
2547
2548static int
fba45db2
KB
2549remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2550 struct gdb_ext_thread_info *info)
c906108c 2551{
d01949b6 2552 struct remote_state *rs = get_remote_state ();
c906108c 2553 int mask, length;
cfd77fa1 2554 int tag;
c906108c 2555 threadref ref;
6d820c5c 2556 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2557 int retval = 1;
2558
23860348 2559 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2560 info->active = 0;
2561 info->display[0] = '\0';
2562 info->shortname[0] = '\0';
2563 info->more_display[0] = '\0';
2564
23860348
MS
2565 /* Assume the characters indicating the packet type have been
2566 stripped. */
c906108c
SS
2567 pkt = unpack_int (pkt, &mask); /* arg mask */
2568 pkt = unpack_threadid (pkt, &ref);
2569
2570 if (mask == 0)
8a3fe4f8 2571 warning (_("Incomplete response to threadinfo request."));
c906108c 2572 if (!threadmatch (&ref, expectedref))
23860348 2573 { /* This is an answer to a different request. */
8a3fe4f8 2574 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2575 return 0;
2576 }
2577 copy_threadref (&info->threadid, &ref);
2578
23860348 2579 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2580
23860348
MS
2581 /* Packets are terminated with nulls. */
2582 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2583 {
2584 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2585 pkt = unpack_byte (pkt, &length); /* length */
2586 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2587 {
8a3fe4f8 2588 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2589 retval = 0;
2590 break;
2591 }
2592 if (tag == TAG_THREADID)
2593 {
2594 if (length != 16)
2595 {
8a3fe4f8 2596 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2597 retval = 0;
2598 break;
2599 }
2600 pkt = unpack_threadid (pkt, &ref);
2601 mask = mask & ~TAG_THREADID;
2602 continue;
2603 }
2604 if (tag == TAG_EXISTS)
2605 {
2606 info->active = stub_unpack_int (pkt, length);
2607 pkt += length;
2608 mask = mask & ~(TAG_EXISTS);
2609 if (length > 8)
2610 {
8a3fe4f8 2611 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2612 retval = 0;
2613 break;
2614 }
2615 continue;
2616 }
2617 if (tag == TAG_THREADNAME)
2618 {
2619 pkt = unpack_string (pkt, &info->shortname[0], length);
2620 mask = mask & ~TAG_THREADNAME;
2621 continue;
2622 }
2623 if (tag == TAG_DISPLAY)
2624 {
2625 pkt = unpack_string (pkt, &info->display[0], length);
2626 mask = mask & ~TAG_DISPLAY;
2627 continue;
2628 }
2629 if (tag == TAG_MOREDISPLAY)
2630 {
2631 pkt = unpack_string (pkt, &info->more_display[0], length);
2632 mask = mask & ~TAG_MOREDISPLAY;
2633 continue;
2634 }
8a3fe4f8 2635 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2636 break; /* Not a tag we know about. */
c906108c
SS
2637 }
2638 return retval;
2639}
2640
2641static int
fba45db2
KB
2642remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2643 struct gdb_ext_thread_info *info)
c906108c 2644{
d01949b6 2645 struct remote_state *rs = get_remote_state ();
c906108c 2646 int result;
c906108c 2647
2e9f7625
DJ
2648 pack_threadinfo_request (rs->buf, fieldset, threadid);
2649 putpkt (rs->buf);
6d820c5c 2650 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2651
2652 if (rs->buf[0] == '\0')
2653 return 0;
2654
2e9f7625 2655 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2656 threadid, info);
c906108c
SS
2657 return result;
2658}
2659
c906108c
SS
2660/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2661
2662static char *
fba45db2
KB
2663pack_threadlist_request (char *pkt, int startflag, int threadcount,
2664 threadref *nextthread)
c906108c
SS
2665{
2666 *pkt++ = 'q'; /* info query packet */
2667 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2668 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2669 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2670 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2671 *pkt = '\0';
2672 return pkt;
2673}
2674
2675/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2676
2677static int
fba45db2
KB
2678parse_threadlist_response (char *pkt, int result_limit,
2679 threadref *original_echo, threadref *resultlist,
2680 int *doneflag)
c906108c 2681{
d01949b6 2682 struct remote_state *rs = get_remote_state ();
c906108c
SS
2683 char *limit;
2684 int count, resultcount, done;
2685
2686 resultcount = 0;
2687 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2688 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2689 /* done parse past here */
c906108c
SS
2690 pkt = unpack_byte (pkt, &count); /* count field */
2691 pkt = unpack_nibble (pkt, &done);
2692 /* The first threadid is the argument threadid. */
2693 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2694 while ((count-- > 0) && (pkt < limit))
2695 {
2696 pkt = unpack_threadid (pkt, resultlist++);
2697 if (resultcount++ >= result_limit)
2698 break;
2699 }
2700 if (doneflag)
2701 *doneflag = done;
2702 return resultcount;
2703}
2704
6dc54d91
PA
2705/* Fetch the next batch of threads from the remote. Returns -1 if the
2706 qL packet is not supported, 0 on error and 1 on success. */
2707
c906108c 2708static int
fba45db2
KB
2709remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2710 int *done, int *result_count, threadref *threadlist)
c906108c 2711{
d01949b6 2712 struct remote_state *rs = get_remote_state ();
c906108c
SS
2713 int result = 1;
2714
23860348 2715 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2716 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2717 >= get_remote_packet_size ())
ea9c271d 2718 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2719
6d820c5c
DJ
2720 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2721 putpkt (rs->buf);
2722 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2723 if (*rs->buf == '\0')
6dc54d91
PA
2724 {
2725 /* Packet not supported. */
2726 return -1;
2727 }
2728
2729 *result_count =
2730 parse_threadlist_response (rs->buf + 2, result_limit,
2731 &rs->echo_nextthread, threadlist, done);
c906108c 2732
0d031856 2733 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2734 {
23860348
MS
2735 /* FIXME: This is a good reason to drop the packet. */
2736 /* Possably, there is a duplicate response. */
c906108c
SS
2737 /* Possabilities :
2738 retransmit immediatly - race conditions
2739 retransmit after timeout - yes
2740 exit
2741 wait for packet, then exit
2742 */
8a3fe4f8 2743 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2744 return 0; /* I choose simply exiting. */
c906108c
SS
2745 }
2746 if (*result_count <= 0)
2747 {
2748 if (*done != 1)
2749 {
8a3fe4f8 2750 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2751 result = 0;
2752 }
2753 return result; /* break; */
2754 }
2755 if (*result_count > result_limit)
2756 {
2757 *result_count = 0;
8a3fe4f8 2758 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2759 return 0;
2760 }
2761 return result;
2762}
2763
6dc54d91
PA
2764/* Fetch the list of remote threads, with the qL packet, and call
2765 STEPFUNCTION for each thread found. Stops iterating and returns 1
2766 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2767 STEPFUNCTION returns false. If the packet is not supported,
2768 returns -1. */
c906108c 2769
c906108c 2770static int
fba45db2
KB
2771remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2772 int looplimit)
c906108c 2773{
0d031856 2774 struct remote_state *rs = get_remote_state ();
c906108c
SS
2775 int done, i, result_count;
2776 int startflag = 1;
2777 int result = 1;
2778 int loopcount = 0;
c906108c
SS
2779
2780 done = 0;
2781 while (!done)
2782 {
2783 if (loopcount++ > looplimit)
2784 {
2785 result = 0;
8a3fe4f8 2786 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2787 break;
2788 }
6dc54d91
PA
2789 result = remote_get_threadlist (startflag, &rs->nextthread,
2790 MAXTHREADLISTRESULTS,
2791 &done, &result_count,
2792 rs->resultthreadlist);
2793 if (result <= 0)
2794 break;
23860348 2795 /* Clear for later iterations. */
c906108c
SS
2796 startflag = 0;
2797 /* Setup to resume next batch of thread references, set nextthread. */
2798 if (result_count >= 1)
0d031856
TT
2799 copy_threadref (&rs->nextthread,
2800 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2801 i = 0;
2802 while (result_count--)
6dc54d91
PA
2803 {
2804 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2805 {
2806 result = 0;
2807 break;
2808 }
2809 }
c906108c
SS
2810 }
2811 return result;
2812}
2813
6dc54d91
PA
2814/* A thread found on the remote target. */
2815
2816typedef struct thread_item
2817{
2818 /* The thread's PTID. */
2819 ptid_t ptid;
2820
2821 /* The thread's extra info. May be NULL. */
2822 char *extra;
2823
2824 /* The core the thread was running on. -1 if not known. */
2825 int core;
2826} thread_item_t;
2827DEF_VEC_O(thread_item_t);
2828
2829/* Context passed around to the various methods listing remote
2830 threads. As new threads are found, they're added to the ITEMS
2831 vector. */
2832
2833struct threads_listing_context
2834{
2835 /* The threads found on the remote target. */
2836 VEC (thread_item_t) *items;
2837};
2838
80134cf5
PA
2839/* Discard the contents of the constructed thread listing context. */
2840
2841static void
2842clear_threads_listing_context (void *p)
2843{
19ba03f4
SM
2844 struct threads_listing_context *context
2845 = (struct threads_listing_context *) p;
80134cf5
PA
2846 int i;
2847 struct thread_item *item;
2848
2849 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2850 xfree (item->extra);
2851
2852 VEC_free (thread_item_t, context->items);
2853}
2854
cbb8991c
DB
2855/* Remove the thread specified as the related_pid field of WS
2856 from the CONTEXT list. */
2857
2858static void
2859threads_listing_context_remove (struct target_waitstatus *ws,
2860 struct threads_listing_context *context)
2861{
2862 struct thread_item *item;
2863 int i;
2864 ptid_t child_ptid = ws->value.related_pid;
2865
2866 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2867 {
2868 if (ptid_equal (item->ptid, child_ptid))
2869 {
2870 VEC_ordered_remove (thread_item_t, context->items, i);
2871 break;
2872 }
2873 }
2874}
2875
c906108c 2876static int
6dc54d91 2877remote_newthread_step (threadref *ref, void *data)
c906108c 2878{
19ba03f4
SM
2879 struct threads_listing_context *context
2880 = (struct threads_listing_context *) data;
6dc54d91 2881 struct thread_item item;
79d7f229 2882 int pid = ptid_get_pid (inferior_ptid);
39f77062 2883
6dc54d91
PA
2884 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2885 item.core = -1;
2886 item.extra = NULL;
2887
2888 VEC_safe_push (thread_item_t, context->items, &item);
2889
c906108c
SS
2890 return 1; /* continue iterator */
2891}
2892
2893#define CRAZY_MAX_THREADS 1000
2894
39f77062
KB
2895static ptid_t
2896remote_current_thread (ptid_t oldpid)
c906108c 2897{
d01949b6 2898 struct remote_state *rs = get_remote_state ();
c906108c
SS
2899
2900 putpkt ("qC");
6d820c5c 2901 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2902 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
2903 {
2904 char *obuf;
2905 ptid_t result;
2906
2907 result = read_ptid (&rs->buf[2], &obuf);
2908 if (*obuf != '\0' && remote_debug)
2909 fprintf_unfiltered (gdb_stdlog,
2910 "warning: garbage in qC reply\n");
2911
2912 return result;
2913 }
c906108c
SS
2914 else
2915 return oldpid;
2916}
2917
6dc54d91 2918/* List remote threads using the deprecated qL packet. */
cce74817 2919
6dc54d91
PA
2920static int
2921remote_get_threads_with_ql (struct target_ops *ops,
2922 struct threads_listing_context *context)
c906108c 2923{
6dc54d91
PA
2924 if (remote_threadlist_iterator (remote_newthread_step, context,
2925 CRAZY_MAX_THREADS) >= 0)
2926 return 1;
2927
2928 return 0;
c906108c
SS
2929}
2930
dc146f7c
VP
2931#if defined(HAVE_LIBEXPAT)
2932
dc146f7c
VP
2933static void
2934start_thread (struct gdb_xml_parser *parser,
2935 const struct gdb_xml_element *element,
2936 void *user_data, VEC(gdb_xml_value_s) *attributes)
2937{
19ba03f4
SM
2938 struct threads_listing_context *data
2939 = (struct threads_listing_context *) user_data;
dc146f7c
VP
2940
2941 struct thread_item item;
2942 char *id;
3d2c1d41 2943 struct gdb_xml_value *attr;
dc146f7c 2944
19ba03f4 2945 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2946 item.ptid = read_ptid (id, NULL);
2947
3d2c1d41
PA
2948 attr = xml_find_attribute (attributes, "core");
2949 if (attr != NULL)
2950 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2951 else
2952 item.core = -1;
2953
2954 item.extra = 0;
2955
2956 VEC_safe_push (thread_item_t, data->items, &item);
2957}
2958
2959static void
2960end_thread (struct gdb_xml_parser *parser,
2961 const struct gdb_xml_element *element,
2962 void *user_data, const char *body_text)
2963{
19ba03f4
SM
2964 struct threads_listing_context *data
2965 = (struct threads_listing_context *) user_data;
dc146f7c
VP
2966
2967 if (body_text && *body_text)
2ae2a0b7 2968 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2969}
2970
2971const struct gdb_xml_attribute thread_attributes[] = {
2972 { "id", GDB_XML_AF_NONE, NULL, NULL },
2973 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2974 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2975};
2976
2977const struct gdb_xml_element thread_children[] = {
2978 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2979};
2980
2981const struct gdb_xml_element threads_children[] = {
2982 { "thread", thread_attributes, thread_children,
2983 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2984 start_thread, end_thread },
2985 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2986};
2987
2988const struct gdb_xml_element threads_elements[] = {
2989 { "threads", NULL, threads_children,
2990 GDB_XML_EF_NONE, NULL, NULL },
2991 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2992};
2993
2994#endif
2995
6dc54d91 2996/* List remote threads using qXfer:threads:read. */
9d1f7ab2 2997
6dc54d91
PA
2998static int
2999remote_get_threads_with_qxfer (struct target_ops *ops,
3000 struct threads_listing_context *context)
0f71a2f6 3001{
dc146f7c 3002#if defined(HAVE_LIBEXPAT)
4082afcc 3003 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3004 {
6dc54d91 3005 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3006 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3007
6dc54d91 3008 if (xml != NULL && *xml != '\0')
dc146f7c 3009 {
6dc54d91
PA
3010 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3011 threads_elements, xml, context);
dc146f7c
VP
3012 }
3013
3014 do_cleanups (back_to);
6dc54d91 3015 return 1;
dc146f7c
VP
3016 }
3017#endif
3018
6dc54d91
PA
3019 return 0;
3020}
3021
3022/* List remote threads using qfThreadInfo/qsThreadInfo. */
3023
3024static int
3025remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3026 struct threads_listing_context *context)
3027{
3028 struct remote_state *rs = get_remote_state ();
3029
b80fafe3 3030 if (rs->use_threadinfo_query)
9d1f7ab2 3031 {
6dc54d91
PA
3032 char *bufp;
3033
9d1f7ab2 3034 putpkt ("qfThreadInfo");
6d820c5c 3035 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3036 bufp = rs->buf;
9d1f7ab2 3037 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3038 {
9d1f7ab2
MS
3039 while (*bufp++ == 'm') /* reply contains one or more TID */
3040 {
3041 do
3042 {
6dc54d91
PA
3043 struct thread_item item;
3044
3045 item.ptid = read_ptid (bufp, &bufp);
3046 item.core = -1;
3047 item.extra = NULL;
3048
3049 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3050 }
3051 while (*bufp++ == ','); /* comma-separated list */
3052 putpkt ("qsThreadInfo");
6d820c5c 3053 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3054 bufp = rs->buf;
9d1f7ab2 3055 }
6dc54d91
PA
3056 return 1;
3057 }
3058 else
3059 {
3060 /* Packet not recognized. */
3061 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3062 }
3063 }
3064
6dc54d91
PA
3065 return 0;
3066}
3067
e8032dde 3068/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3069 targets. */
3070
3071static void
e8032dde 3072remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
3073{
3074 struct remote_state *rs = get_remote_state ();
3075 struct threads_listing_context context;
3076 struct cleanup *old_chain;
ab970af1 3077 int got_list = 0;
e8032dde 3078
6dc54d91
PA
3079 context.items = NULL;
3080 old_chain = make_cleanup (clear_threads_listing_context, &context);
3081
3082 /* We have a few different mechanisms to fetch the thread list. Try
3083 them all, starting with the most preferred one first, falling
3084 back to older methods. */
3085 if (remote_get_threads_with_qxfer (ops, &context)
3086 || remote_get_threads_with_qthreadinfo (ops, &context)
3087 || remote_get_threads_with_ql (ops, &context))
3088 {
3089 int i;
3090 struct thread_item *item;
ab970af1
PA
3091 struct thread_info *tp, *tmp;
3092
3093 got_list = 1;
3094
7d1a114c
PA
3095 if (VEC_empty (thread_item_t, context.items)
3096 && remote_thread_always_alive (ops, inferior_ptid))
3097 {
3098 /* Some targets don't really support threads, but still
3099 reply an (empty) thread list in response to the thread
3100 listing packets, instead of replying "packet not
3101 supported". Exit early so we don't delete the main
3102 thread. */
3103 do_cleanups (old_chain);
3104 return;
3105 }
3106
ab970af1
PA
3107 /* CONTEXT now holds the current thread list on the remote
3108 target end. Delete GDB-side threads no longer found on the
3109 target. */
8a06aea7 3110 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3111 {
ab970af1
PA
3112 for (i = 0;
3113 VEC_iterate (thread_item_t, context.items, i, item);
3114 ++i)
3115 {
3116 if (ptid_equal (item->ptid, tp->ptid))
3117 break;
3118 }
3119
3120 if (i == VEC_length (thread_item_t, context.items))
3121 {
3122 /* Not found. */
3123 delete_thread (tp->ptid);
3124 }
cbb8991c
DB
3125 }
3126
3127 /* Remove any unreported fork child threads from CONTEXT so
3128 that we don't interfere with follow fork, which is where
3129 creation of such threads is handled. */
3130 remove_new_fork_children (&context);
74531fed 3131
ab970af1 3132 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3133 for (i = 0;
3134 VEC_iterate (thread_item_t, context.items, i, item);
3135 ++i)
3136 {
3137 if (!ptid_equal (item->ptid, null_ptid))
3138 {
3139 struct private_thread_info *info;
3140 /* In non-stop mode, we assume new found threads are
3141 running until proven otherwise with a stop reply. In
3142 all-stop, we can only get here if all threads are
3143 stopped. */
3144 int running = non_stop ? 1 : 0;
3145
3146 remote_notice_new_inferior (item->ptid, running);
3147
3148 info = demand_private_info (item->ptid);
3149 info->core = item->core;
3150 info->extra = item->extra;
3151 item->extra = NULL;
3152 }
3153 }
3154 }
3155
ab970af1
PA
3156 if (!got_list)
3157 {
3158 /* If no thread listing method is supported, then query whether
3159 each known thread is alive, one by one, with the T packet.
3160 If the target doesn't support threads at all, then this is a
3161 no-op. See remote_thread_alive. */
3162 prune_threads ();
3163 }
3164
6dc54d91 3165 do_cleanups (old_chain);
9d1f7ab2
MS
3166}
3167
802188a7 3168/*
9d1f7ab2
MS
3169 * Collect a descriptive string about the given thread.
3170 * The target may say anything it wants to about the thread
3171 * (typically info about its blocked / runnable state, name, etc.).
3172 * This string will appear in the info threads display.
802188a7 3173 *
9d1f7ab2
MS
3174 * Optional: targets are not required to implement this function.
3175 */
3176
3177static char *
c15906d8 3178remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3179{
d01949b6 3180 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3181 int result;
3182 int set;
3183 threadref id;
3184 struct gdb_ext_thread_info threadinfo;
23860348 3185 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3186 int n = 0; /* position in display_buf */
3187
5d93a237 3188 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3189 internal_error (__FILE__, __LINE__,
e2e0b3e5 3190 _("remote_threads_extra_info"));
9d1f7ab2 3191
60e569b9 3192 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3193 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3194 /* This is the main thread which was added by GDB. The remote
3195 server doesn't know about it. */
3196 return NULL;
3197
4082afcc 3198 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3199 {
3200 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3201
fe978cb0
PA
3202 if (info && info->priv)
3203 return info->priv->extra;
dc146f7c
VP
3204 else
3205 return NULL;
3206 }
3207
b80fafe3 3208 if (rs->use_threadextra_query)
9d1f7ab2 3209 {
82f73884
PA
3210 char *b = rs->buf;
3211 char *endb = rs->buf + get_remote_packet_size ();
3212
3213 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3214 b += strlen (b);
3215 write_ptid (b, endb, tp->ptid);
3216
2e9f7625 3217 putpkt (rs->buf);
6d820c5c 3218 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3219 if (rs->buf[0] != 0)
9d1f7ab2 3220 {
2e9f7625
DJ
3221 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3222 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3223 display_buf [result] = '\0';
9d1f7ab2
MS
3224 return display_buf;
3225 }
0f71a2f6 3226 }
9d1f7ab2
MS
3227
3228 /* If the above query fails, fall back to the old method. */
b80fafe3 3229 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3230 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3231 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3232 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3233 if (remote_get_threadinfo (&id, set, &threadinfo))
3234 if (threadinfo.active)
0f71a2f6 3235 {
9d1f7ab2 3236 if (*threadinfo.shortname)
2bc416ba 3237 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3238 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3239 if (*threadinfo.display)
2bc416ba 3240 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3241 " State: %s,", threadinfo.display);
9d1f7ab2 3242 if (*threadinfo.more_display)
2bc416ba 3243 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3244 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3245
3246 if (n > 0)
c5aa993b 3247 {
23860348 3248 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3249 if (',' == display_buf[n-1])
3250 display_buf[n-1] = ' ';
3251 return display_buf;
c5aa993b 3252 }
0f71a2f6 3253 }
9d1f7ab2 3254 return NULL;
0f71a2f6 3255}
c906108c 3256\f
c5aa993b 3257
0fb4aa4b 3258static int
61fc905d 3259remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3260 struct static_tracepoint_marker *marker)
3261{
3262 struct remote_state *rs = get_remote_state ();
3263 char *p = rs->buf;
3264
bba74b36 3265 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3266 p += strlen (p);
3267 p += hexnumstr (p, addr);
3268 putpkt (rs->buf);
3269 getpkt (&rs->buf, &rs->buf_size, 0);
3270 p = rs->buf;
3271
3272 if (*p == 'E')
3273 error (_("Remote failure reply: %s"), p);
3274
3275 if (*p++ == 'm')
3276 {
3277 parse_static_tracepoint_marker_definition (p, &p, marker);
3278 return 1;
3279 }
3280
3281 return 0;
3282}
3283
0fb4aa4b 3284static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3285remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3286 const char *strid)
0fb4aa4b
PA
3287{
3288 struct remote_state *rs = get_remote_state ();
3289 VEC(static_tracepoint_marker_p) *markers = NULL;
3290 struct static_tracepoint_marker *marker = NULL;
3291 struct cleanup *old_chain;
3292 char *p;
3293
3294 /* Ask for a first packet of static tracepoint marker
3295 definition. */
3296 putpkt ("qTfSTM");
3297 getpkt (&rs->buf, &rs->buf_size, 0);
3298 p = rs->buf;
3299 if (*p == 'E')
3300 error (_("Remote failure reply: %s"), p);
3301
3302 old_chain = make_cleanup (free_current_marker, &marker);
3303
3304 while (*p++ == 'm')
3305 {
3306 if (marker == NULL)
3307 marker = XCNEW (struct static_tracepoint_marker);
3308
3309 do
3310 {
3311 parse_static_tracepoint_marker_definition (p, &p, marker);
3312
3313 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3314 {
3315 VEC_safe_push (static_tracepoint_marker_p,
3316 markers, marker);
3317 marker = NULL;
3318 }
3319 else
3320 {
3321 release_static_tracepoint_marker (marker);
3322 memset (marker, 0, sizeof (*marker));
3323 }
3324 }
3325 while (*p++ == ','); /* comma-separated list */
3326 /* Ask for another packet of static tracepoint definition. */
3327 putpkt ("qTsSTM");
3328 getpkt (&rs->buf, &rs->buf_size, 0);
3329 p = rs->buf;
3330 }
3331
3332 do_cleanups (old_chain);
3333 return markers;
3334}
3335
3336\f
10760264
JB
3337/* Implement the to_get_ada_task_ptid function for the remote targets. */
3338
3339static ptid_t
1e6b91a4 3340remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3341{
ba348170 3342 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3343}
3344\f
3345
24b06219 3346/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3347
3348static void
fba45db2 3349extended_remote_restart (void)
c906108c 3350{
d01949b6 3351 struct remote_state *rs = get_remote_state ();
c906108c
SS
3352
3353 /* Send the restart command; for reasons I don't understand the
3354 remote side really expects a number after the "R". */
ea9c271d 3355 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3356 putpkt (rs->buf);
c906108c 3357
ad9a8f3f 3358 remote_fileio_reset ();
c906108c
SS
3359}
3360\f
3361/* Clean up connection to a remote debugger. */
3362
c906108c 3363static void
de90e03d 3364remote_close (struct target_ops *self)
c906108c 3365{
5d93a237
TT
3366 struct remote_state *rs = get_remote_state ();
3367
3368 if (rs->remote_desc == NULL)
d3fd5342
PA
3369 return; /* already closed */
3370
3371 /* Make sure we leave stdin registered in the event loop, and we
3372 don't leave the async SIGINT signal handler installed. */
e3594fd1 3373 remote_terminal_ours (self);
ce5ce7ed 3374
5d93a237
TT
3375 serial_close (rs->remote_desc);
3376 rs->remote_desc = NULL;
ce5ce7ed
PA
3377
3378 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3379 of all the inferiors and their threads we were controlling.
3380 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3381 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3382 inferior_ptid = null_ptid;
f67fd822 3383 discard_all_inferiors ();
ce5ce7ed 3384
f48ff2a7
YQ
3385 /* We are closing the remote target, so we should discard
3386 everything of this target. */
bcc75809 3387 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3388
3389 if (remote_async_inferior_event_token)
3390 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3391
5965e028 3392 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3393
3394 trace_reset_local_state ();
c906108c
SS
3395}
3396
23860348 3397/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3398
3399static void
fba45db2 3400get_offsets (void)
c906108c 3401{
d01949b6 3402 struct remote_state *rs = get_remote_state ();
2e9f7625 3403 char *buf;
085dd6e6 3404 char *ptr;
31d99776
DJ
3405 int lose, num_segments = 0, do_sections, do_segments;
3406 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3407 struct section_offsets *offs;
31d99776
DJ
3408 struct symfile_segment_data *data;
3409
3410 if (symfile_objfile == NULL)
3411 return;
c906108c
SS
3412
3413 putpkt ("qOffsets");
6d820c5c 3414 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3415 buf = rs->buf;
c906108c
SS
3416
3417 if (buf[0] == '\000')
3418 return; /* Return silently. Stub doesn't support
23860348 3419 this command. */
c906108c
SS
3420 if (buf[0] == 'E')
3421 {
8a3fe4f8 3422 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3423 return;
3424 }
3425
3426 /* Pick up each field in turn. This used to be done with scanf, but
3427 scanf will make trouble if CORE_ADDR size doesn't match
3428 conversion directives correctly. The following code will work
3429 with any size of CORE_ADDR. */
3430 text_addr = data_addr = bss_addr = 0;
3431 ptr = buf;
3432 lose = 0;
3433
61012eef 3434 if (startswith (ptr, "Text="))
c906108c
SS
3435 {
3436 ptr += 5;
3437 /* Don't use strtol, could lose on big values. */
3438 while (*ptr && *ptr != ';')
3439 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3440
61012eef 3441 if (startswith (ptr, ";Data="))
31d99776
DJ
3442 {
3443 ptr += 6;
3444 while (*ptr && *ptr != ';')
3445 data_addr = (data_addr << 4) + fromhex (*ptr++);
3446 }
3447 else
3448 lose = 1;
3449
61012eef 3450 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3451 {
3452 ptr += 5;
3453 while (*ptr && *ptr != ';')
3454 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3455
31d99776
DJ
3456 if (bss_addr != data_addr)
3457 warning (_("Target reported unsupported offsets: %s"), buf);
3458 }
3459 else
3460 lose = 1;
3461 }
61012eef 3462 else if (startswith (ptr, "TextSeg="))
c906108c 3463 {
31d99776
DJ
3464 ptr += 8;
3465 /* Don't use strtol, could lose on big values. */
c906108c 3466 while (*ptr && *ptr != ';')
31d99776
DJ
3467 text_addr = (text_addr << 4) + fromhex (*ptr++);
3468 num_segments = 1;
3469
61012eef 3470 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3471 {
3472 ptr += 9;
3473 while (*ptr && *ptr != ';')
3474 data_addr = (data_addr << 4) + fromhex (*ptr++);
3475 num_segments++;
3476 }
c906108c
SS
3477 }
3478 else
3479 lose = 1;
3480
3481 if (lose)
8a3fe4f8 3482 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3483 else if (*ptr != '\0')
3484 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3485
802188a7 3486 offs = ((struct section_offsets *)
a39a16c4 3487 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3488 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3489 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3490
31d99776
DJ
3491 data = get_symfile_segment_data (symfile_objfile->obfd);
3492 do_segments = (data != NULL);
3493 do_sections = num_segments == 0;
c906108c 3494
28c32713 3495 if (num_segments > 0)
31d99776 3496 {
31d99776
DJ
3497 segments[0] = text_addr;
3498 segments[1] = data_addr;
3499 }
28c32713
JB
3500 /* If we have two segments, we can still try to relocate everything
3501 by assuming that the .text and .data offsets apply to the whole
3502 text and data segments. Convert the offsets given in the packet
3503 to base addresses for symfile_map_offsets_to_segments. */
3504 else if (data && data->num_segments == 2)
3505 {
3506 segments[0] = data->segment_bases[0] + text_addr;
3507 segments[1] = data->segment_bases[1] + data_addr;
3508 num_segments = 2;
3509 }
8d385431
DJ
3510 /* If the object file has only one segment, assume that it is text
3511 rather than data; main programs with no writable data are rare,
3512 but programs with no code are useless. Of course the code might
3513 have ended up in the data segment... to detect that we would need
3514 the permissions here. */
3515 else if (data && data->num_segments == 1)
3516 {
3517 segments[0] = data->segment_bases[0] + text_addr;
3518 num_segments = 1;
3519 }
28c32713
JB
3520 /* There's no way to relocate by segment. */
3521 else
3522 do_segments = 0;
31d99776
DJ
3523
3524 if (do_segments)
3525 {
3526 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3527 offs, num_segments, segments);
3528
3529 if (ret == 0 && !do_sections)
3e43a32a
MS
3530 error (_("Can not handle qOffsets TextSeg "
3531 "response with this symbol file"));
31d99776
DJ
3532
3533 if (ret > 0)
3534 do_sections = 0;
3535 }
c906108c 3536
9ef895d6
DJ
3537 if (data)
3538 free_symfile_segment_data (data);
31d99776
DJ
3539
3540 if (do_sections)
3541 {
3542 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3543
3e43a32a
MS
3544 /* This is a temporary kludge to force data and bss to use the
3545 same offsets because that's what nlmconv does now. The real
3546 solution requires changes to the stub and remote.c that I
3547 don't have time to do right now. */
31d99776
DJ
3548
3549 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3550 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3551 }
c906108c
SS
3552
3553 objfile_relocate (symfile_objfile, offs);
3554}
3555
9a7071a8
JB
3556/* Send interrupt_sequence to remote target. */
3557static void
eeae04df 3558send_interrupt_sequence (void)
9a7071a8 3559{
5d93a237
TT
3560 struct remote_state *rs = get_remote_state ();
3561
9a7071a8 3562 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3563 remote_serial_write ("\x03", 1);
9a7071a8 3564 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3565 serial_send_break (rs->remote_desc);
9a7071a8
JB
3566 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3567 {
5d93a237 3568 serial_send_break (rs->remote_desc);
c33e31fd 3569 remote_serial_write ("g", 1);
9a7071a8
JB
3570 }
3571 else
3572 internal_error (__FILE__, __LINE__,
3573 _("Invalid value for interrupt_sequence_mode: %s."),
3574 interrupt_sequence_mode);
3575}
3576
3405876a
PA
3577
3578/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3579 and extract the PTID. Returns NULL_PTID if not found. */
3580
3581static ptid_t
3582stop_reply_extract_thread (char *stop_reply)
3583{
3584 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3585 {
3586 char *p;
3587
3588 /* Txx r:val ; r:val (...) */
3589 p = &stop_reply[3];
3590
3591 /* Look for "register" named "thread". */
3592 while (*p != '\0')
3593 {
3594 char *p1;
3595
3596 p1 = strchr (p, ':');
3597 if (p1 == NULL)
3598 return null_ptid;
3599
3600 if (strncmp (p, "thread", p1 - p) == 0)
3601 return read_ptid (++p1, &p);
3602
3603 p1 = strchr (p, ';');
3604 if (p1 == NULL)
3605 return null_ptid;
3606 p1++;
3607
3608 p = p1;
3609 }
3610 }
3611
3612 return null_ptid;
3613}
3614
b7ea362b
PA
3615/* Determine the remote side's current thread. If we have a stop
3616 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3617 "thread" register we can extract the current thread from. If not,
3618 ask the remote which is the current thread with qC. The former
3619 method avoids a roundtrip. */
3620
3621static ptid_t
3622get_current_thread (char *wait_status)
3623{
6a49a997 3624 ptid_t ptid = null_ptid;
b7ea362b
PA
3625
3626 /* Note we don't use remote_parse_stop_reply as that makes use of
3627 the target architecture, which we haven't yet fully determined at
3628 this point. */
3629 if (wait_status != NULL)
3630 ptid = stop_reply_extract_thread (wait_status);
3631 if (ptid_equal (ptid, null_ptid))
3632 ptid = remote_current_thread (inferior_ptid);
3633
3634 return ptid;
3635}
3636
49c62f2e
PA
3637/* Query the remote target for which is the current thread/process,
3638 add it to our tables, and update INFERIOR_PTID. The caller is
3639 responsible for setting the state such that the remote end is ready
3405876a
PA
3640 to return the current thread.
3641
3642 This function is called after handling the '?' or 'vRun' packets,
3643 whose response is a stop reply from which we can also try
3644 extracting the thread. If the target doesn't support the explicit
3645 qC query, we infer the current thread from that stop reply, passed
3646 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3647
3648static void
3405876a 3649add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3650{
3651 struct remote_state *rs = get_remote_state ();
3652 int fake_pid_p = 0;
6a49a997 3653 ptid_t ptid;
49c62f2e
PA
3654
3655 inferior_ptid = null_ptid;
3656
b7ea362b
PA
3657 /* Now, if we have thread information, update inferior_ptid. */
3658 ptid = get_current_thread (wait_status);
3405876a 3659
49c62f2e
PA
3660 if (!ptid_equal (ptid, null_ptid))
3661 {
3662 if (!remote_multi_process_p (rs))
3663 fake_pid_p = 1;
3664
3665 inferior_ptid = ptid;
3666 }
3667 else
3668 {
3669 /* Without this, some commands which require an active target
3670 (such as kill) won't work. This variable serves (at least)
3671 double duty as both the pid of the target process (if it has
3672 such), and as a flag indicating that a target is active. */
3673 inferior_ptid = magic_null_ptid;
3674 fake_pid_p = 1;
3675 }
3676
1b6e6f5c 3677 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3678
3679 /* Add the main thread. */
3680 add_thread_silent (inferior_ptid);
3681}
3682
221e1a37
PA
3683/* Process all initial stop replies the remote side sent in response
3684 to the ? packet. These indicate threads that were already stopped
3685 on initial connection. We mark these threads as stopped and print
3686 their current frame before giving the user the prompt. */
3687
3688static void
3689process_initial_stop_replies (void)
3690{
3691 int pending_stop_replies = stop_reply_queue_length ();
3692
3693 /* Consume the initial pending events. */
3694 while (pending_stop_replies-- > 0)
3695 {
3696 ptid_t waiton_ptid = minus_one_ptid;
3697 ptid_t event_ptid;
3698 struct target_waitstatus ws;
3699 int ignore_event = 0;
3700
3701 memset (&ws, 0, sizeof (ws));
3702 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3703 if (remote_debug)
3704 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3705
3706 switch (ws.kind)
3707 {
3708 case TARGET_WAITKIND_IGNORE:
3709 case TARGET_WAITKIND_NO_RESUMED:
3710 case TARGET_WAITKIND_SIGNALLED:
3711 case TARGET_WAITKIND_EXITED:
3712 /* We shouldn't see these, but if we do, just ignore. */
3713 if (remote_debug)
3714 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3715 ignore_event = 1;
3716 break;
3717
3718 case TARGET_WAITKIND_EXECD:
3719 xfree (ws.value.execd_pathname);
3720 break;
3721 default:
3722 break;
3723 }
3724
3725 if (ignore_event)
3726 continue;
3727
3728 switch_to_thread (event_ptid);
3729 set_executing (event_ptid, 0);
3730 set_running (event_ptid, 0);
3731
3732 stop_pc = get_frame_pc (get_current_frame ());
3733 set_current_sal_from_frame (get_current_frame ());
3734
3735 if (ws.kind == TARGET_WAITKIND_STOPPED)
3736 {
3737 enum gdb_signal sig = ws.value.sig;
3738
3739 /* Stubs traditionally report SIGTRAP as initial signal,
3740 instead of signal 0. Suppress it. */
3741 if (sig == GDB_SIGNAL_TRAP)
3742 sig = GDB_SIGNAL_0;
3743 inferior_thread ()->suspend.stop_signal = sig;
3744
3745 if (signal_print_state (sig))
3746 observer_notify_signal_received (sig);
3747 }
3748
243a9253 3749 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
221e1a37
PA
3750 observer_notify_normal_stop (NULL, 1);
3751 }
3752}
3753
9cbc821d 3754static void
04bd08de 3755remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3756{
c8d104ad
PA
3757 struct remote_state *rs = get_remote_state ();
3758 struct packet_config *noack_config;
2d717e4f 3759 char *wait_status = NULL;
8621d6a9 3760
23860348 3761 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3762 QUIT;
c906108c 3763
9a7071a8
JB
3764 if (interrupt_on_connect)
3765 send_interrupt_sequence ();
3766
57e12211 3767 /* Ack any packet which the remote side has already sent. */
5d93a237 3768 serial_write (rs->remote_desc, "+", 1);
57e12211 3769
1e51243a
PA
3770 /* Signal other parts that we're going through the initial setup,
3771 and so things may not be stable yet. */
3772 rs->starting_up = 1;
3773
c8d104ad
PA
3774 /* The first packet we send to the target is the optional "supported
3775 packets" request. If the target can answer this, it will tell us
3776 which later probes to skip. */
3777 remote_query_supported ();
3778
d914c394 3779 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3780 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3781 remote_set_permissions (target);
d914c394 3782
c8d104ad
PA
3783 /* Next, we possibly activate noack mode.
3784
3785 If the QStartNoAckMode packet configuration is set to AUTO,
3786 enable noack mode if the stub reported a wish for it with
3787 qSupported.
3788
3789 If set to TRUE, then enable noack mode even if the stub didn't
3790 report it in qSupported. If the stub doesn't reply OK, the
3791 session ends with an error.
3792
3793 If FALSE, then don't activate noack mode, regardless of what the
3794 stub claimed should be the default with qSupported. */
3795
3796 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3797 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3798 {
3799 putpkt ("QStartNoAckMode");
3800 getpkt (&rs->buf, &rs->buf_size, 0);
3801 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3802 rs->noack_mode = 1;
3803 }
3804
04bd08de 3805 if (extended_p)
5fe04517
PA
3806 {
3807 /* Tell the remote that we are using the extended protocol. */
3808 putpkt ("!");
3809 getpkt (&rs->buf, &rs->buf_size, 0);
3810 }
3811
9b224c5e
PA
3812 /* Let the target know which signals it is allowed to pass down to
3813 the program. */
3814 update_signals_program_target ();
3815
d962ef82
DJ
3816 /* Next, if the target can specify a description, read it. We do
3817 this before anything involving memory or registers. */
3818 target_find_description ();
3819
6c95b8df
PA
3820 /* Next, now that we know something about the target, update the
3821 address spaces in the program spaces. */
3822 update_address_spaces ();
3823
50c71eaf
PA
3824 /* On OSs where the list of libraries is global to all
3825 processes, we fetch them early. */
f5656ead 3826 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3827 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3828
74531fed
PA
3829 if (non_stop)
3830 {
4082afcc 3831 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3832 error (_("Non-stop mode requested, but remote "
3833 "does not support non-stop"));
74531fed
PA
3834
3835 putpkt ("QNonStop:1");
3836 getpkt (&rs->buf, &rs->buf_size, 0);
3837
3838 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3839 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3840
3841 /* Find about threads and processes the stub is already
3842 controlling. We default to adding them in the running state.
3843 The '?' query below will then tell us about which threads are
3844 stopped. */
e8032dde 3845 remote_update_thread_list (target);
74531fed 3846 }
4082afcc 3847 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3848 {
3849 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3850 Request it explicitly. */
74531fed
PA
3851 putpkt ("QNonStop:0");
3852 getpkt (&rs->buf, &rs->buf_size, 0);
3853
3854 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3855 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3856 }
3857
a0743c90
YQ
3858 /* Upload TSVs regardless of whether the target is running or not. The
3859 remote stub, such as GDBserver, may have some predefined or builtin
3860 TSVs, even if the target is not running. */
8bd200f1 3861 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
3862 {
3863 struct uploaded_tsv *uploaded_tsvs = NULL;
3864
181e3713 3865 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
3866 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3867 }
3868
2d717e4f
DJ
3869 /* Check whether the target is running now. */
3870 putpkt ("?");
3871 getpkt (&rs->buf, &rs->buf_size, 0);
3872
74531fed 3873 if (!non_stop)
2d717e4f 3874 {
e714e1bf
UW
3875 ptid_t ptid;
3876 int fake_pid_p = 0;
3877 struct inferior *inf;
3878
74531fed 3879 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3880 {
04bd08de 3881 if (!extended_p)
74531fed 3882 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3883
3884 /* We're connected, but not running. Drop out before we
3885 call start_remote. */
e278ad5b 3886 rs->starting_up = 0;
c35b1492 3887 return;
2d717e4f
DJ
3888 }
3889 else
74531fed 3890 {
74531fed 3891 /* Save the reply for later. */
224c3ddb 3892 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
3893 strcpy (wait_status, rs->buf);
3894 }
3895
b7ea362b 3896 /* Fetch thread list. */
e8032dde 3897 target_update_thread_list ();
b7ea362b 3898
74531fed
PA
3899 /* Let the stub know that we want it to return the thread. */
3900 set_continue_thread (minus_one_ptid);
3901
b7ea362b
PA
3902 if (thread_count () == 0)
3903 {
3904 /* Target has no concept of threads at all. GDB treats
3905 non-threaded target as single-threaded; add a main
3906 thread. */
3907 add_current_inferior_and_thread (wait_status);
3908 }
3909 else
3910 {
3911 /* We have thread information; select the thread the target
3912 says should be current. If we're reconnecting to a
3913 multi-threaded program, this will ideally be the thread
3914 that last reported an event before GDB disconnected. */
3915 inferior_ptid = get_current_thread (wait_status);
3916 if (ptid_equal (inferior_ptid, null_ptid))
3917 {
3918 /* Odd... The target was able to list threads, but not
3919 tell us which thread was current (no "thread"
3920 register in T stop reply?). Just pick the first
3921 thread in the thread list then. */
c9f35b34
KB
3922
3923 if (remote_debug)
3924 fprintf_unfiltered (gdb_stdlog,
3925 "warning: couldn't determine remote "
3926 "current thread; picking first in list.\n");
3927
b7ea362b
PA
3928 inferior_ptid = thread_list->ptid;
3929 }
3930 }
74531fed 3931
6e586cc5
YQ
3932 /* init_wait_for_inferior should be called before get_offsets in order
3933 to manage `inserted' flag in bp loc in a correct state.
3934 breakpoint_init_inferior, called from init_wait_for_inferior, set
3935 `inserted' flag to 0, while before breakpoint_re_set, called from
3936 start_remote, set `inserted' flag to 1. In the initialization of
3937 inferior, breakpoint_init_inferior should be called first, and then
3938 breakpoint_re_set can be called. If this order is broken, state of
3939 `inserted' flag is wrong, and cause some problems on breakpoint
3940 manipulation. */
3941 init_wait_for_inferior ();
3942
74531fed
PA
3943 get_offsets (); /* Get text, data & bss offsets. */
3944
d962ef82
DJ
3945 /* If we could not find a description using qXfer, and we know
3946 how to do it some other way, try again. This is not
3947 supported for non-stop; it could be, but it is tricky if
3948 there are no stopped threads when we connect. */
04bd08de 3949 if (remote_read_description_p (target)
f5656ead 3950 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
3951 {
3952 target_clear_description ();
3953 target_find_description ();
3954 }
3955
74531fed
PA
3956 /* Use the previously fetched status. */
3957 gdb_assert (wait_status != NULL);
3958 strcpy (rs->buf, wait_status);
3959 rs->cached_wait_status = 1;
3960
3961 immediate_quit--;
04bd08de 3962 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3963 }
3964 else
3965 {
221e1a37
PA
3966 ptid_t current_ptid;
3967
68c97600
PA
3968 /* Clear WFI global state. Do this before finding about new
3969 threads and inferiors, and setting the current inferior.
3970 Otherwise we would clear the proceed status of the current
3971 inferior when we want its stop_soon state to be preserved
3972 (see notice_new_inferior). */
3973 init_wait_for_inferior ();
3974
74531fed
PA
3975 /* In non-stop, we will either get an "OK", meaning that there
3976 are no stopped threads at this time; or, a regular stop
3977 reply. In the latter case, there may be more than one thread
3978 stopped --- we pull them all out using the vStopped
3979 mechanism. */
3980 if (strcmp (rs->buf, "OK") != 0)
3981 {
722247f1 3982 struct notif_client *notif = &notif_client_stop;
2d717e4f 3983
722247f1
YQ
3984 /* remote_notif_get_pending_replies acks this one, and gets
3985 the rest out. */
f48ff2a7 3986 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
3987 = remote_notif_parse (notif, rs->buf);
3988 remote_notif_get_pending_events (notif);
74531fed 3989 }
2d717e4f 3990
74531fed
PA
3991 if (thread_count () == 0)
3992 {
04bd08de 3993 if (!extended_p)
74531fed 3994 error (_("The target is not running (try extended-remote?)"));
82f73884 3995
c35b1492
PA
3996 /* We're connected, but not running. Drop out before we
3997 call start_remote. */
e278ad5b 3998 rs->starting_up = 0;
c35b1492
PA
3999 return;
4000 }
74531fed
PA
4001
4002 /* Let the stub know that we want it to return the thread. */
c0a2216e 4003
74531fed
PA
4004 /* Force the stub to choose a thread. */
4005 set_general_thread (null_ptid);
c906108c 4006
74531fed 4007 /* Query it. */
221e1a37 4008 current_ptid = remote_current_thread (minus_one_ptid);
74531fed
PA
4009 if (ptid_equal (inferior_ptid, minus_one_ptid))
4010 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 4011
221e1a37 4012 inferior_ptid = current_ptid;
74531fed
PA
4013 get_offsets (); /* Get text, data & bss offsets. */
4014
4015 /* In non-stop mode, any cached wait status will be stored in
4016 the stop reply queue. */
4017 gdb_assert (wait_status == NULL);
f0223081 4018
2455069d 4019 /* Report all signals during attach/startup. */
94bedb42 4020 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4021
4022 /* If there are already stopped threads, mark them stopped and
4023 report their stops before giving the prompt to the user. */
4024 process_initial_stop_replies ();
4025
4026 switch_to_thread (current_ptid);
4027
4028 if (target_can_async_p ())
4029 target_async (1);
74531fed 4030 }
c8d104ad 4031
c8d104ad
PA
4032 /* If we connected to a live target, do some additional setup. */
4033 if (target_has_execution)
4034 {
f4ccffad 4035 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4036 remote_check_symbols ();
c8d104ad 4037 }
50c71eaf 4038
d5551862
SS
4039 /* Possibly the target has been engaged in a trace run started
4040 previously; find out where things are at. */
8bd200f1 4041 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4042 {
00bf0b85 4043 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4044
00bf0b85
SS
4045 if (current_trace_status ()->running)
4046 printf_filtered (_("Trace is already running on the target.\n"));
4047
ab6617cc 4048 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4049
4050 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4051 }
4052
1e51243a
PA
4053 /* The thread and inferior lists are now synchronized with the
4054 target, our symbols have been relocated, and we're merged the
4055 target's tracepoints with ours. We're done with basic start
4056 up. */
4057 rs->starting_up = 0;
4058
a25a5a45
PA
4059 /* Maybe breakpoints are global and need to be inserted now. */
4060 if (breakpoints_should_be_inserted_now ())
50c71eaf 4061 insert_breakpoints ();
c906108c
SS
4062}
4063
4064/* Open a connection to a remote debugger.
4065 NAME is the filename used for communication. */
4066
4067static void
014f9477 4068remote_open (const char *name, int from_tty)
c906108c 4069{
75c99385 4070 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4071}
4072
c906108c
SS
4073/* Open a connection to a remote debugger using the extended
4074 remote gdb protocol. NAME is the filename used for communication. */
4075
4076static void
014f9477 4077extended_remote_open (const char *name, int from_tty)
c906108c 4078{
75c99385 4079 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4080}
4081
ca4f7f8b
PA
4082/* Reset all packets back to "unknown support". Called when opening a
4083 new connection to a remote target. */
c906108c 4084
d471ea57 4085static void
ca4f7f8b 4086reset_all_packet_configs_support (void)
d471ea57
AC
4087{
4088 int i;
a744cf53 4089
444abaca 4090 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4091 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4092}
4093
ca4f7f8b
PA
4094/* Initialize all packet configs. */
4095
4096static void
4097init_all_packet_configs (void)
4098{
4099 int i;
4100
4101 for (i = 0; i < PACKET_MAX; i++)
4102 {
4103 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4104 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4105 }
4106}
4107
23860348 4108/* Symbol look-up. */
dc8acb97
MS
4109
4110static void
36d25514 4111remote_check_symbols (void)
dc8acb97 4112{
d01949b6 4113 struct remote_state *rs = get_remote_state ();
dc8acb97 4114 char *msg, *reply, *tmp;
3b7344d5 4115 struct bound_minimal_symbol sym;
dc8acb97 4116 int end;
a5c0808e 4117 struct cleanup *old_chain;
dc8acb97 4118
63154eca
PA
4119 /* The remote side has no concept of inferiors that aren't running
4120 yet, it only knows about running processes. If we're connected
4121 but our current inferior is not running, we should not invite the
4122 remote target to request symbol lookups related to its
4123 (unrelated) current process. */
4124 if (!target_has_execution)
4125 return;
4126
4082afcc 4127 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4128 return;
4129
63154eca
PA
4130 /* Make sure the remote is pointing at the right process. Note
4131 there's no way to select "no process". */
3c9c4b83
PA
4132 set_general_process ();
4133
6d820c5c
DJ
4134 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4135 because we need both at the same time. */
224c3ddb 4136 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4137 old_chain = make_cleanup (xfree, msg);
6d820c5c 4138
23860348 4139 /* Invite target to request symbol lookups. */
dc8acb97
MS
4140
4141 putpkt ("qSymbol::");
6d820c5c
DJ
4142 getpkt (&rs->buf, &rs->buf_size, 0);
4143 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 4144 reply = rs->buf;
dc8acb97 4145
61012eef 4146 while (startswith (reply, "qSymbol:"))
dc8acb97 4147 {
77e371c0
TT
4148 struct bound_minimal_symbol sym;
4149
dc8acb97 4150 tmp = &reply[8];
cfd77fa1 4151 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4152 msg[end] = '\0';
4153 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4154 if (sym.minsym == NULL)
ea9c271d 4155 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4156 else
2bbe3cc1 4157 {
f5656ead 4158 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4159 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4160
4161 /* If this is a function address, return the start of code
4162 instead of any data function descriptor. */
f5656ead 4163 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4164 sym_addr,
4165 &current_target);
4166
4167 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4168 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4169 }
4170
dc8acb97 4171 putpkt (msg);
6d820c5c 4172 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4173 reply = rs->buf;
dc8acb97 4174 }
a5c0808e
PA
4175
4176 do_cleanups (old_chain);
dc8acb97
MS
4177}
4178
9db8d71f 4179static struct serial *
baa336ce 4180remote_serial_open (const char *name)
9db8d71f
DJ
4181{
4182 static int udp_warning = 0;
4183
4184 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4185 of in ser-tcp.c, because it is the remote protocol assuming that the
4186 serial connection is reliable and not the serial connection promising
4187 to be. */
61012eef 4188 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4189 {
3e43a32a
MS
4190 warning (_("The remote protocol may be unreliable over UDP.\n"
4191 "Some events may be lost, rendering further debugging "
4192 "impossible."));
9db8d71f
DJ
4193 udp_warning = 1;
4194 }
4195
4196 return serial_open (name);
4197}
4198
d914c394
SS
4199/* Inform the target of our permission settings. The permission flags
4200 work without this, but if the target knows the settings, it can do
4201 a couple things. First, it can add its own check, to catch cases
4202 that somehow manage to get by the permissions checks in target
4203 methods. Second, if the target is wired to disallow particular
4204 settings (for instance, a system in the field that is not set up to
4205 be able to stop at a breakpoint), it can object to any unavailable
4206 permissions. */
4207
4208void
c378d69d 4209remote_set_permissions (struct target_ops *self)
d914c394
SS
4210{
4211 struct remote_state *rs = get_remote_state ();
4212
bba74b36
YQ
4213 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4214 "WriteReg:%x;WriteMem:%x;"
4215 "InsertBreak:%x;InsertTrace:%x;"
4216 "InsertFastTrace:%x;Stop:%x",
4217 may_write_registers, may_write_memory,
4218 may_insert_breakpoints, may_insert_tracepoints,
4219 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4220 putpkt (rs->buf);
4221 getpkt (&rs->buf, &rs->buf_size, 0);
4222
4223 /* If the target didn't like the packet, warn the user. Do not try
4224 to undo the user's settings, that would just be maddening. */
4225 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4226 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4227}
4228
be2a5f71
DJ
4229/* This type describes each known response to the qSupported
4230 packet. */
4231struct protocol_feature
4232{
4233 /* The name of this protocol feature. */
4234 const char *name;
4235
4236 /* The default for this protocol feature. */
4237 enum packet_support default_support;
4238
4239 /* The function to call when this feature is reported, or after
4240 qSupported processing if the feature is not supported.
4241 The first argument points to this structure. The second
4242 argument indicates whether the packet requested support be
4243 enabled, disabled, or probed (or the default, if this function
4244 is being called at the end of processing and this feature was
4245 not reported). The third argument may be NULL; if not NULL, it
4246 is a NUL-terminated string taken from the packet following
4247 this feature's name and an equals sign. */
4248 void (*func) (const struct protocol_feature *, enum packet_support,
4249 const char *);
4250
4251 /* The corresponding packet for this feature. Only used if
4252 FUNC is remote_supported_packet. */
4253 int packet;
4254};
4255
be2a5f71
DJ
4256static void
4257remote_supported_packet (const struct protocol_feature *feature,
4258 enum packet_support support,
4259 const char *argument)
4260{
4261 if (argument)
4262 {
4263 warning (_("Remote qSupported response supplied an unexpected value for"
4264 " \"%s\"."), feature->name);
4265 return;
4266 }
4267
4082afcc 4268 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4269}
be2a5f71
DJ
4270
4271static void
4272remote_packet_size (const struct protocol_feature *feature,
4273 enum packet_support support, const char *value)
4274{
4275 struct remote_state *rs = get_remote_state ();
4276
4277 int packet_size;
4278 char *value_end;
4279
4280 if (support != PACKET_ENABLE)
4281 return;
4282
4283 if (value == NULL || *value == '\0')
4284 {
4285 warning (_("Remote target reported \"%s\" without a size."),
4286 feature->name);
4287 return;
4288 }
4289
4290 errno = 0;
4291 packet_size = strtol (value, &value_end, 16);
4292 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4293 {
4294 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4295 feature->name, value);
4296 return;
4297 }
4298
be2a5f71
DJ
4299 /* Record the new maximum packet size. */
4300 rs->explicit_packet_size = packet_size;
4301}
4302
dc473cfb 4303static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4304 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4305 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4306 PACKET_qXfer_auxv },
c78fa86a
GB
4307 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4308 PACKET_qXfer_exec_file },
23181151
DJ
4309 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4310 PACKET_qXfer_features },
cfa9d6d9
DJ
4311 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4312 PACKET_qXfer_libraries },
2268b414
JK
4313 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4314 PACKET_qXfer_libraries_svr4 },
ced63ec0 4315 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4316 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4317 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4318 PACKET_qXfer_memory_map },
4de6483e
UW
4319 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4320 PACKET_qXfer_spu_read },
4321 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4322 PACKET_qXfer_spu_write },
07e059b5
VP
4323 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4324 PACKET_qXfer_osdata },
dc146f7c
VP
4325 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4326 PACKET_qXfer_threads },
b3b9301e
PA
4327 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4328 PACKET_qXfer_traceframe_info },
89be2091
DJ
4329 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4330 PACKET_QPassSignals },
9b224c5e
PA
4331 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4332 PACKET_QProgramSignals },
a6f3e723
SL
4333 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4334 PACKET_QStartNoAckMode },
4082afcc
PA
4335 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4336 PACKET_multiprocess_feature },
4337 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4338 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4339 PACKET_qXfer_siginfo_read },
4340 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4341 PACKET_qXfer_siginfo_write },
4082afcc 4342 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4343 PACKET_ConditionalTracepoints },
4082afcc 4344 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4345 PACKET_ConditionalBreakpoints },
4082afcc 4346 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4347 PACKET_BreakpointCommands },
4082afcc 4348 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4349 PACKET_FastTracepoints },
4082afcc 4350 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4351 PACKET_StaticTracepoints },
4082afcc 4352 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4353 PACKET_InstallInTrace},
4082afcc
PA
4354 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4355 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4356 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4357 PACKET_bc },
4358 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4359 PACKET_bs },
409873ef
SS
4360 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4361 PACKET_TracepointSource },
d914c394
SS
4362 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4363 PACKET_QAllow },
4082afcc
PA
4364 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4365 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4366 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4367 PACKET_qXfer_fdpic },
169081d0
TG
4368 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4369 PACKET_qXfer_uib },
03583c20
UW
4370 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4371 PACKET_QDisableRandomization },
d1feda86 4372 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4373 { "QTBuffer:size", PACKET_DISABLE,
4374 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4375 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4376 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4377 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4378 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4379 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4380 PACKET_qXfer_btrace },
4381 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4382 PACKET_qXfer_btrace_conf },
4383 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4384 PACKET_Qbtrace_conf_bts_size },
4385 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4386 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4387 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4388 PACKET_fork_event_feature },
4389 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4390 PACKET_vfork_event_feature },
94585166
DB
4391 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4392 PACKET_exec_event_feature },
b20a6524 4393 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1
YQ
4394 PACKET_Qbtrace_conf_pt_size },
4395 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported }
be2a5f71
DJ
4396};
4397
c8d5aac9
L
4398static char *remote_support_xml;
4399
4400/* Register string appended to "xmlRegisters=" in qSupported query. */
4401
4402void
6e39997a 4403register_remote_support_xml (const char *xml)
c8d5aac9
L
4404{
4405#if defined(HAVE_LIBEXPAT)
4406 if (remote_support_xml == NULL)
c4f7c687 4407 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4408 else
4409 {
4410 char *copy = xstrdup (remote_support_xml + 13);
4411 char *p = strtok (copy, ",");
4412
4413 do
4414 {
4415 if (strcmp (p, xml) == 0)
4416 {
4417 /* already there */
4418 xfree (copy);
4419 return;
4420 }
4421 }
4422 while ((p = strtok (NULL, ",")) != NULL);
4423 xfree (copy);
4424
94b0dee1
PA
4425 remote_support_xml = reconcat (remote_support_xml,
4426 remote_support_xml, ",", xml,
4427 (char *) NULL);
c8d5aac9
L
4428 }
4429#endif
4430}
4431
4432static char *
4433remote_query_supported_append (char *msg, const char *append)
4434{
4435 if (msg)
94b0dee1 4436 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4437 else
4438 return xstrdup (append);
4439}
4440
be2a5f71
DJ
4441static void
4442remote_query_supported (void)
4443{
4444 struct remote_state *rs = get_remote_state ();
4445 char *next;
4446 int i;
4447 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4448
4449 /* The packet support flags are handled differently for this packet
4450 than for most others. We treat an error, a disabled packet, and
4451 an empty response identically: any features which must be reported
4452 to be used will be automatically disabled. An empty buffer
4453 accomplishes this, since that is also the representation for a list
4454 containing no features. */
4455
4456 rs->buf[0] = 0;
4082afcc 4457 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4458 {
c8d5aac9 4459 char *q = NULL;
94b0dee1 4460 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4461
73b8c1fd
PA
4462 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4463 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4464
f7e6eed5
PA
4465 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4466 q = remote_query_supported_append (q, "swbreak+");
4467 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4468 q = remote_query_supported_append (q, "hwbreak+");
4469
c8d5aac9
L
4470 if (remote_support_xml)
4471 q = remote_query_supported_append (q, remote_support_xml);
4472
dde08ee1
PA
4473 q = remote_query_supported_append (q, "qRelocInsn+");
4474
89245bc0
DB
4475 if (rs->extended)
4476 {
4477 if (packet_set_cmd_state (PACKET_fork_event_feature)
4478 != AUTO_BOOLEAN_FALSE)
4479 q = remote_query_supported_append (q, "fork-events+");
4480 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4481 != AUTO_BOOLEAN_FALSE)
4482 q = remote_query_supported_append (q, "vfork-events+");
94585166
DB
4483 if (packet_set_cmd_state (PACKET_exec_event_feature)
4484 != AUTO_BOOLEAN_FALSE)
4485 q = remote_query_supported_append (q, "exec-events+");
89245bc0
DB
4486 }
4487
750ce8d1
YQ
4488 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4489 q = remote_query_supported_append (q, "vContSupported+");
4490
dde08ee1
PA
4491 q = reconcat (q, "qSupported:", q, (char *) NULL);
4492 putpkt (q);
82f73884 4493
94b0dee1
PA
4494 do_cleanups (old_chain);
4495
be2a5f71
DJ
4496 getpkt (&rs->buf, &rs->buf_size, 0);
4497
4498 /* If an error occured, warn, but do not return - just reset the
4499 buffer to empty and go on to disable features. */
4500 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4501 == PACKET_ERROR)
4502 {
4503 warning (_("Remote failure reply: %s"), rs->buf);
4504 rs->buf[0] = 0;
4505 }
4506 }
4507
4508 memset (seen, 0, sizeof (seen));
4509
4510 next = rs->buf;
4511 while (*next)
4512 {
4513 enum packet_support is_supported;
4514 char *p, *end, *name_end, *value;
4515
4516 /* First separate out this item from the rest of the packet. If
4517 there's another item after this, we overwrite the separator
4518 (terminated strings are much easier to work with). */
4519 p = next;
4520 end = strchr (p, ';');
4521 if (end == NULL)
4522 {
4523 end = p + strlen (p);
4524 next = end;
4525 }
4526 else
4527 {
89be2091
DJ
4528 *end = '\0';
4529 next = end + 1;
4530
be2a5f71
DJ
4531 if (end == p)
4532 {
4533 warning (_("empty item in \"qSupported\" response"));
4534 continue;
4535 }
be2a5f71
DJ
4536 }
4537
4538 name_end = strchr (p, '=');
4539 if (name_end)
4540 {
4541 /* This is a name=value entry. */
4542 is_supported = PACKET_ENABLE;
4543 value = name_end + 1;
4544 *name_end = '\0';
4545 }
4546 else
4547 {
4548 value = NULL;
4549 switch (end[-1])
4550 {
4551 case '+':
4552 is_supported = PACKET_ENABLE;
4553 break;
4554
4555 case '-':
4556 is_supported = PACKET_DISABLE;
4557 break;
4558
4559 case '?':
4560 is_supported = PACKET_SUPPORT_UNKNOWN;
4561 break;
4562
4563 default:
3e43a32a
MS
4564 warning (_("unrecognized item \"%s\" "
4565 "in \"qSupported\" response"), p);
be2a5f71
DJ
4566 continue;
4567 }
4568 end[-1] = '\0';
4569 }
4570
4571 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4572 if (strcmp (remote_protocol_features[i].name, p) == 0)
4573 {
4574 const struct protocol_feature *feature;
4575
4576 seen[i] = 1;
4577 feature = &remote_protocol_features[i];
4578 feature->func (feature, is_supported, value);
4579 break;
4580 }
4581 }
4582
4583 /* If we increased the packet size, make sure to increase the global
4584 buffer size also. We delay this until after parsing the entire
4585 qSupported packet, because this is the same buffer we were
4586 parsing. */
4587 if (rs->buf_size < rs->explicit_packet_size)
4588 {
4589 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4590 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4591 }
4592
4593 /* Handle the defaults for unmentioned features. */
4594 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4595 if (!seen[i])
4596 {
4597 const struct protocol_feature *feature;
4598
4599 feature = &remote_protocol_features[i];
4600 feature->func (feature, feature->default_support, NULL);
4601 }
4602}
4603
78a095c3
JK
4604/* Remove any of the remote.c targets from target stack. Upper targets depend
4605 on it so remove them first. */
4606
4607static void
4608remote_unpush_target (void)
4609{
4610 pop_all_targets_above (process_stratum - 1);
4611}
be2a5f71 4612
c906108c 4613static void
014f9477 4614remote_open_1 (const char *name, int from_tty,
3e43a32a 4615 struct target_ops *target, int extended_p)
c906108c 4616{
d01949b6 4617 struct remote_state *rs = get_remote_state ();
a6f3e723 4618
c906108c 4619 if (name == 0)
8a3fe4f8 4620 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4621 "serial device is attached to the remote system\n"
8a3fe4f8 4622 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4623
23860348 4624 /* See FIXME above. */
c6ebd6cf 4625 if (!target_async_permitted)
92d1e331 4626 wait_forever_enabled_p = 1;
6426a772 4627
2d717e4f 4628 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4629 Ask this question first, before target_preopen has a chance to kill
4630 anything. */
5d93a237 4631 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4632 {
78a095c3
JK
4633 if (from_tty
4634 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4635 error (_("Still connected."));
4636 }
4637
78a095c3 4638 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4639 target_preopen (from_tty);
4640
89be2091 4641 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4642 xfree (rs->last_pass_packet);
4643 rs->last_pass_packet = NULL;
89be2091 4644
9b224c5e
PA
4645 /* Make sure we send the program signals list the next time we
4646 resume. */
5e4a05c4
TT
4647 xfree (rs->last_program_signals_packet);
4648 rs->last_program_signals_packet = NULL;
9b224c5e 4649
ad9a8f3f 4650 remote_fileio_reset ();
1dd41f16
NS
4651 reopen_exec_file ();
4652 reread_symbols ();
4653
5d93a237
TT
4654 rs->remote_desc = remote_serial_open (name);
4655 if (!rs->remote_desc)
c906108c
SS
4656 perror_with_name (name);
4657
4658 if (baud_rate != -1)
4659 {
5d93a237 4660 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4661 {
9b74d5d3
KB
4662 /* The requested speed could not be set. Error out to
4663 top level after closing remote_desc. Take care to
4664 set remote_desc to NULL to avoid closing remote_desc
4665 more than once. */
5d93a237
TT
4666 serial_close (rs->remote_desc);
4667 rs->remote_desc = NULL;
c906108c
SS
4668 perror_with_name (name);
4669 }
4670 }
4671
236af5e3 4672 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4673 serial_raw (rs->remote_desc);
c906108c
SS
4674
4675 /* If there is something sitting in the buffer we might take it as a
4676 response to a command, which would be bad. */
5d93a237 4677 serial_flush_input (rs->remote_desc);
c906108c
SS
4678
4679 if (from_tty)
4680 {
4681 puts_filtered ("Remote debugging using ");
4682 puts_filtered (name);
4683 puts_filtered ("\n");
4684 }
23860348 4685 push_target (target); /* Switch to using remote target now. */
c906108c 4686
74531fed
PA
4687 /* Register extra event sources in the event loop. */
4688 remote_async_inferior_event_token
4689 = create_async_event_handler (remote_async_inferior_event_handler,
4690 NULL);
5965e028 4691 rs->notif_state = remote_notif_state_allocate ();
74531fed 4692
be2a5f71
DJ
4693 /* Reset the target state; these things will be queried either by
4694 remote_query_supported or as they are needed. */
ca4f7f8b 4695 reset_all_packet_configs_support ();
74531fed 4696 rs->cached_wait_status = 0;
be2a5f71 4697 rs->explicit_packet_size = 0;
a6f3e723 4698 rs->noack_mode = 0;
82f73884 4699 rs->extended = extended_p;
e24a49d8 4700 rs->waiting_for_stop_reply = 0;
3a29589a 4701 rs->ctrlc_pending_p = 0;
802188a7 4702
47f8a51d
TT
4703 rs->general_thread = not_sent_ptid;
4704 rs->continue_thread = not_sent_ptid;
262e1174 4705 rs->remote_traceframe_number = -1;
c906108c 4706
9d1f7ab2 4707 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4708 rs->use_threadinfo_query = 1;
4709 rs->use_threadextra_query = 1;
9d1f7ab2 4710
80152258
PA
4711 readahead_cache_invalidate ();
4712
c6ebd6cf 4713 if (target_async_permitted)
92d1e331 4714 {
23860348 4715 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4716 remote_async_terminal_ours_p = 1;
4717
4718 /* FIXME: cagney/1999-09-23: During the initial connection it is
4719 assumed that the target is already ready and able to respond to
0df8b418 4720 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4721 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4722 around this. Eventually a mechanism that allows
92d1e331 4723 wait_for_inferior() to expect/get timeouts will be
23860348 4724 implemented. */
92d1e331
DJ
4725 wait_forever_enabled_p = 0;
4726 }
4727
23860348 4728 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4729 no_shared_libraries (NULL, 0);
f78f6cf1 4730
74531fed
PA
4731 /* Start afresh. */
4732 init_thread_list ();
4733
36918e70 4734 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4735 target (we'd otherwise be in an inconsistent state) and then
4736 propogate the error on up the exception chain. This ensures that
4737 the caller doesn't stumble along blindly assuming that the
4738 function succeeded. The CLI doesn't have this problem but other
4739 UI's, such as MI do.
36918e70
AC
4740
4741 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4742 this function should return an error indication letting the
ce2826aa 4743 caller restore the previous state. Unfortunately the command
36918e70
AC
4744 ``target remote'' is directly wired to this function making that
4745 impossible. On a positive note, the CLI side of this problem has
4746 been fixed - the function set_cmd_context() makes it possible for
4747 all the ``target ....'' commands to share a common callback
4748 function. See cli-dump.c. */
109c3e39 4749 {
2d717e4f 4750
492d29ea 4751 TRY
04bd08de
TT
4752 {
4753 remote_start_remote (from_tty, target, extended_p);
4754 }
492d29ea 4755 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4756 {
c8d104ad
PA
4757 /* Pop the partially set up target - unless something else did
4758 already before throwing the exception. */
5d93a237 4759 if (rs->remote_desc != NULL)
78a095c3 4760 remote_unpush_target ();
c6ebd6cf 4761 if (target_async_permitted)
109c3e39
AC
4762 wait_forever_enabled_p = 1;
4763 throw_exception (ex);
4764 }
492d29ea 4765 END_CATCH
109c3e39 4766 }
c906108c 4767
f4abbc16
MM
4768 remote_btrace_reset ();
4769
c6ebd6cf 4770 if (target_async_permitted)
92d1e331 4771 wait_forever_enabled_p = 1;
43ff13b4
JM
4772}
4773
de0d863e
DB
4774/* Detach the specified process. */
4775
4776static void
4777remote_detach_pid (int pid)
4778{
4779 struct remote_state *rs = get_remote_state ();
4780
4781 if (remote_multi_process_p (rs))
4782 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4783 else
4784 strcpy (rs->buf, "D");
4785
4786 putpkt (rs->buf);
4787 getpkt (&rs->buf, &rs->buf_size, 0);
4788
4789 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4790 ;
4791 else if (rs->buf[0] == '\0')
4792 error (_("Remote doesn't know how to detach"));
4793 else
4794 error (_("Can't detach process."));
4795}
4796
4797/* This detaches a program to which we previously attached, using
4798 inferior_ptid to identify the process. After this is done, GDB
4799 can be used to debug some other program. We better not have left
4800 any breakpoints in the target program or it'll die when it hits
4801 one. */
c906108c
SS
4802
4803static void
de0d863e 4804remote_detach_1 (const char *args, int from_tty)
c906108c 4805{
82f73884 4806 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4807 struct remote_state *rs = get_remote_state ();
de0d863e
DB
4808 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4809 int is_fork_parent;
c906108c
SS
4810
4811 if (args)
8a3fe4f8 4812 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4813
2d717e4f
DJ
4814 if (!target_has_execution)
4815 error (_("No process to detach from."));
4816
7cee1e54
PA
4817 if (from_tty)
4818 {
4819 char *exec_file = get_exec_file (0);
4820 if (exec_file == NULL)
4821 exec_file = "";
4822 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4823 target_pid_to_str (pid_to_ptid (pid)));
4824 gdb_flush (gdb_stdout);
4825 }
4826
c906108c 4827 /* Tell the remote target to detach. */
de0d863e 4828 remote_detach_pid (pid);
82f73884 4829
de0d863e 4830 if (from_tty && !rs->extended)
7cee1e54 4831 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4832
de0d863e
DB
4833 /* Check to see if we are detaching a fork parent. Note that if we
4834 are detaching a fork child, tp == NULL. */
4835 is_fork_parent = (tp != NULL
4836 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4837
4838 /* If doing detach-on-fork, we don't mourn, because that will delete
4839 breakpoints that should be available for the followed inferior. */
4840 if (!is_fork_parent)
4841 target_mourn_inferior ();
4842 else
4843 {
4844 inferior_ptid = null_ptid;
4845 detach_inferior (pid);
4846 }
2d717e4f
DJ
4847}
4848
4849static void
52554a0e 4850remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4851{
de0d863e 4852 remote_detach_1 (args, from_tty);
2d717e4f
DJ
4853}
4854
4855static void
52554a0e 4856extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4857{
de0d863e
DB
4858 remote_detach_1 (args, from_tty);
4859}
4860
4861/* Target follow-fork function for remote targets. On entry, and
4862 at return, the current inferior is the fork parent.
4863
4864 Note that although this is currently only used for extended-remote,
4865 it is named remote_follow_fork in anticipation of using it for the
4866 remote target as well. */
4867
4868static int
4869remote_follow_fork (struct target_ops *ops, int follow_child,
4870 int detach_fork)
4871{
4872 struct remote_state *rs = get_remote_state ();
c269dbdb 4873 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 4874
c269dbdb
DB
4875 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4876 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
4877 {
4878 /* When following the parent and detaching the child, we detach
4879 the child here. For the case of following the child and
4880 detaching the parent, the detach is done in the target-
4881 independent follow fork code in infrun.c. We can't use
4882 target_detach when detaching an unfollowed child because
4883 the client side doesn't know anything about the child. */
4884 if (detach_fork && !follow_child)
4885 {
4886 /* Detach the fork child. */
4887 ptid_t child_ptid;
4888 pid_t child_pid;
4889
4890 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4891 child_pid = ptid_get_pid (child_ptid);
4892
4893 remote_detach_pid (child_pid);
4894 detach_inferior (child_pid);
4895 }
4896 }
4897 return 0;
c906108c
SS
4898}
4899
94585166
DB
4900/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
4901 in the program space of the new inferior. On entry and at return the
4902 current inferior is the exec'ing inferior. INF is the new exec'd
4903 inferior, which may be the same as the exec'ing inferior unless
4904 follow-exec-mode is "new". */
4905
4906static void
4907remote_follow_exec (struct target_ops *ops,
4908 struct inferior *inf, char *execd_pathname)
4909{
4910 /* We know that this is a target file name, so if it has the "target:"
4911 prefix we strip it off before saving it in the program space. */
4912 if (is_target_filename (execd_pathname))
4913 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
4914
4915 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
4916}
4917
6ad8ae5c
DJ
4918/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4919
43ff13b4 4920static void
fee354ee 4921remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 4922{
43ff13b4 4923 if (args)
2d717e4f 4924 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4925
2d717e4f 4926 /* Make sure we unpush even the extended remote targets; mourn
20f796c9 4927 won't do it. So call remote_mourn directly instead of
2d717e4f 4928 target_mourn_inferior. */
20f796c9 4929 remote_mourn (target);
2d717e4f 4930
43ff13b4
JM
4931 if (from_tty)
4932 puts_filtered ("Ending remote debugging.\n");
4933}
4934
2d717e4f
DJ
4935/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4936 be chatty about it. */
4937
4938static void
20f796c9
GB
4939extended_remote_attach (struct target_ops *target, const char *args,
4940 int from_tty)
2d717e4f
DJ
4941{
4942 struct remote_state *rs = get_remote_state ();
be86555c 4943 int pid;
96ef3384 4944 char *wait_status = NULL;
2d717e4f 4945
74164c56 4946 pid = parse_pid_to_attach (args);
2d717e4f 4947
74164c56
JK
4948 /* Remote PID can be freely equal to getpid, do not check it here the same
4949 way as in other targets. */
2d717e4f 4950
4082afcc 4951 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
4952 error (_("This target does not support attaching to a process"));
4953
7cee1e54
PA
4954 if (from_tty)
4955 {
4956 char *exec_file = get_exec_file (0);
4957
4958 if (exec_file)
4959 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4960 target_pid_to_str (pid_to_ptid (pid)));
4961 else
4962 printf_unfiltered (_("Attaching to %s\n"),
4963 target_pid_to_str (pid_to_ptid (pid)));
4964
4965 gdb_flush (gdb_stdout);
4966 }
4967
bba74b36 4968 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4969 putpkt (rs->buf);
4970 getpkt (&rs->buf, &rs->buf_size, 0);
4971
4082afcc
PA
4972 switch (packet_ok (rs->buf,
4973 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 4974 {
4082afcc 4975 case PACKET_OK:
74531fed
PA
4976 if (!non_stop)
4977 {
4978 /* Save the reply for later. */
224c3ddb 4979 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4980 strcpy (wait_status, rs->buf);
4981 }
4982 else if (strcmp (rs->buf, "OK") != 0)
4983 error (_("Attaching to %s failed with: %s"),
4984 target_pid_to_str (pid_to_ptid (pid)),
4985 rs->buf);
4082afcc
PA
4986 break;
4987 case PACKET_UNKNOWN:
4988 error (_("This target does not support attaching to a process"));
4989 default:
4990 error (_("Attaching to %s failed"),
4991 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4992 }
2d717e4f 4993
1b6e6f5c 4994 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 4995
2d717e4f 4996 inferior_ptid = pid_to_ptid (pid);
79d7f229 4997
bad34192
PA
4998 if (non_stop)
4999 {
5000 struct thread_info *thread;
79d7f229 5001
bad34192 5002 /* Get list of threads. */
e8032dde 5003 remote_update_thread_list (target);
82f73884 5004
bad34192
PA
5005 thread = first_thread_of_process (pid);
5006 if (thread)
5007 inferior_ptid = thread->ptid;
5008 else
5009 inferior_ptid = pid_to_ptid (pid);
5010
5011 /* Invalidate our notion of the remote current thread. */
47f8a51d 5012 record_currthread (rs, minus_one_ptid);
bad34192 5013 }
74531fed 5014 else
bad34192
PA
5015 {
5016 /* Now, if we have thread information, update inferior_ptid. */
5017 inferior_ptid = remote_current_thread (inferior_ptid);
5018
5019 /* Add the main thread to the thread list. */
5020 add_thread_silent (inferior_ptid);
5021 }
c0a2216e 5022
96ef3384
UW
5023 /* Next, if the target can specify a description, read it. We do
5024 this before anything involving memory or registers. */
5025 target_find_description ();
5026
74531fed
PA
5027 if (!non_stop)
5028 {
5029 /* Use the previously fetched status. */
5030 gdb_assert (wait_status != NULL);
5031
5032 if (target_can_async_p ())
5033 {
722247f1
YQ
5034 struct notif_event *reply
5035 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5036
722247f1 5037 push_stop_reply ((struct stop_reply *) reply);
74531fed 5038
6a3753b3 5039 target_async (1);
74531fed
PA
5040 }
5041 else
5042 {
5043 gdb_assert (wait_status != NULL);
5044 strcpy (rs->buf, wait_status);
5045 rs->cached_wait_status = 1;
5046 }
5047 }
5048 else
5049 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5050}
5051
b9c1d481
AS
5052/* Implementation of the to_post_attach method. */
5053
5054static void
5055extended_remote_post_attach (struct target_ops *ops, int pid)
5056{
5057 /* In certain cases GDB might not have had the chance to start
5058 symbol lookup up until now. This could happen if the debugged
5059 binary is not using shared libraries, the vsyscall page is not
5060 present (on Linux) and the binary itself hadn't changed since the
5061 debugging process was started. */
5062 if (symfile_objfile != NULL)
5063 remote_check_symbols();
5064}
5065
c906108c 5066\f
506fb367
DJ
5067/* Check for the availability of vCont. This function should also check
5068 the response. */
c906108c
SS
5069
5070static void
6d820c5c 5071remote_vcont_probe (struct remote_state *rs)
c906108c 5072{
2e9f7625 5073 char *buf;
6d820c5c 5074
2e9f7625
DJ
5075 strcpy (rs->buf, "vCont?");
5076 putpkt (rs->buf);
6d820c5c 5077 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5078 buf = rs->buf;
c906108c 5079
506fb367 5080 /* Make sure that the features we assume are supported. */
61012eef 5081 if (startswith (buf, "vCont"))
506fb367
DJ
5082 {
5083 char *p = &buf[5];
750ce8d1 5084 int support_c, support_C;
506fb367 5085
750ce8d1
YQ
5086 rs->supports_vCont.s = 0;
5087 rs->supports_vCont.S = 0;
506fb367
DJ
5088 support_c = 0;
5089 support_C = 0;
d458bd84 5090 rs->supports_vCont.t = 0;
c1e36e3e 5091 rs->supports_vCont.r = 0;
506fb367
DJ
5092 while (p && *p == ';')
5093 {
5094 p++;
5095 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5096 rs->supports_vCont.s = 1;
506fb367 5097 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5098 rs->supports_vCont.S = 1;
506fb367
DJ
5099 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5100 support_c = 1;
5101 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5102 support_C = 1;
74531fed 5103 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5104 rs->supports_vCont.t = 1;
c1e36e3e
PA
5105 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5106 rs->supports_vCont.r = 1;
506fb367
DJ
5107
5108 p = strchr (p, ';');
5109 }
c906108c 5110
750ce8d1
YQ
5111 /* If c, and C are not all supported, we can't use vCont. Clearing
5112 BUF will make packet_ok disable the packet. */
5113 if (!support_c || !support_C)
506fb367
DJ
5114 buf[0] = 0;
5115 }
c906108c 5116
444abaca 5117 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5118}
c906108c 5119
0d8f58ca
PA
5120/* Helper function for building "vCont" resumptions. Write a
5121 resumption to P. ENDP points to one-passed-the-end of the buffer
5122 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5123 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5124 resumed thread should be single-stepped and/or signalled. If PTID
5125 equals minus_one_ptid, then all threads are resumed; if PTID
5126 represents a process, then all threads of the process are resumed;
5127 the thread to be stepped and/or signalled is given in the global
5128 INFERIOR_PTID. */
5129
5130static char *
5131append_resumption (char *p, char *endp,
2ea28649 5132 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5133{
5134 struct remote_state *rs = get_remote_state ();
5135
a493e3e2 5136 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5137 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5138 else if (step
5139 /* GDB is willing to range step. */
5140 && use_range_stepping
5141 /* Target supports range stepping. */
5142 && rs->supports_vCont.r
5143 /* We don't currently support range stepping multiple
5144 threads with a wildcard (though the protocol allows it,
5145 so stubs shouldn't make an active effort to forbid
5146 it). */
5147 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5148 {
5149 struct thread_info *tp;
5150
5151 if (ptid_equal (ptid, minus_one_ptid))
5152 {
5153 /* If we don't know about the target thread's tid, then
5154 we're resuming magic_null_ptid (see caller). */
5155 tp = find_thread_ptid (magic_null_ptid);
5156 }
5157 else
5158 tp = find_thread_ptid (ptid);
5159 gdb_assert (tp != NULL);
5160
5161 if (tp->control.may_range_step)
5162 {
5163 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5164
5165 p += xsnprintf (p, endp - p, ";r%s,%s",
5166 phex_nz (tp->control.step_range_start,
5167 addr_size),
5168 phex_nz (tp->control.step_range_end,
5169 addr_size));
5170 }
5171 else
5172 p += xsnprintf (p, endp - p, ";s");
5173 }
0d8f58ca
PA
5174 else if (step)
5175 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5176 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5177 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5178 else
5179 p += xsnprintf (p, endp - p, ";c");
5180
5181 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5182 {
5183 ptid_t nptid;
5184
5185 /* All (-1) threads of process. */
ba348170 5186 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5187
5188 p += xsnprintf (p, endp - p, ":");
5189 p = write_ptid (p, endp, nptid);
5190 }
5191 else if (!ptid_equal (ptid, minus_one_ptid))
5192 {
5193 p += xsnprintf (p, endp - p, ":");
5194 p = write_ptid (p, endp, ptid);
5195 }
5196
5197 return p;
5198}
5199
e5ef252a
PA
5200/* Append a vCont continue-with-signal action for threads that have a
5201 non-zero stop signal. */
5202
5203static char *
5204append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5205{
5206 struct thread_info *thread;
5207
034f788c 5208 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5209 if (ptid_match (thread->ptid, ptid)
5210 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5211 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5212 {
5213 p = append_resumption (p, endp, thread->ptid,
5214 0, thread->suspend.stop_signal);
5215 thread->suspend.stop_signal = GDB_SIGNAL_0;
5216 }
5217
5218 return p;
5219}
5220
506fb367
DJ
5221/* Resume the remote inferior by using a "vCont" packet. The thread
5222 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5223 resumed thread should be single-stepped and/or signalled. If PTID
5224 equals minus_one_ptid, then all threads are resumed; the thread to
5225 be stepped and/or signalled is given in the global INFERIOR_PTID.
5226 This function returns non-zero iff it resumes the inferior.
44eaed12 5227
506fb367
DJ
5228 This function issues a strict subset of all possible vCont commands at the
5229 moment. */
44eaed12 5230
506fb367 5231static int
2ea28649 5232remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5233{
5234 struct remote_state *rs = get_remote_state ();
82f73884
PA
5235 char *p;
5236 char *endp;
44eaed12 5237
4082afcc 5238 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5239 remote_vcont_probe (rs);
44eaed12 5240
4082afcc 5241 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5242 return 0;
44eaed12 5243
82f73884
PA
5244 p = rs->buf;
5245 endp = rs->buf + get_remote_packet_size ();
5246
506fb367
DJ
5247 /* If we could generate a wider range of packets, we'd have to worry
5248 about overflowing BUF. Should there be a generic
5249 "multi-part-packet" packet? */
5250
0d8f58ca
PA
5251 p += xsnprintf (p, endp - p, "vCont");
5252
79d7f229 5253 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5254 {
79d7f229
PA
5255 /* MAGIC_NULL_PTID means that we don't have any active threads,
5256 so we don't have any TID numbers the inferior will
5257 understand. Make sure to only send forms that do not specify
5258 a TID. */
a9cbf802 5259 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5260 }
0d8f58ca 5261 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5262 {
0d8f58ca
PA
5263 /* Resume all threads (of all processes, or of a single
5264 process), with preference for INFERIOR_PTID. This assumes
5265 inferior_ptid belongs to the set of all threads we are about
5266 to resume. */
a493e3e2 5267 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5268 {
0d8f58ca
PA
5269 /* Step inferior_ptid, with or without signal. */
5270 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5271 }
0d8f58ca 5272
e5ef252a
PA
5273 /* Also pass down any pending signaled resumption for other
5274 threads not the current. */
5275 p = append_pending_thread_resumptions (p, endp, ptid);
5276
0d8f58ca 5277 /* And continue others without a signal. */
a493e3e2 5278 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5279 }
5280 else
506fb367
DJ
5281 {
5282 /* Scheduler locking; resume only PTID. */
a9cbf802 5283 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5284 }
c906108c 5285
82f73884
PA
5286 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5287 putpkt (rs->buf);
506fb367 5288
74531fed
PA
5289 if (non_stop)
5290 {
5291 /* In non-stop, the stub replies to vCont with "OK". The stop
5292 reply will be reported asynchronously by means of a `%Stop'
5293 notification. */
5294 getpkt (&rs->buf, &rs->buf_size, 0);
5295 if (strcmp (rs->buf, "OK") != 0)
5296 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5297 }
5298
506fb367 5299 return 1;
c906108c 5300}
43ff13b4 5301
506fb367
DJ
5302/* Tell the remote machine to resume. */
5303
43ff13b4 5304static void
28439f5e 5305remote_resume (struct target_ops *ops,
2ea28649 5306 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5307{
d01949b6 5308 struct remote_state *rs = get_remote_state ();
2e9f7625 5309 char *buf;
43ff13b4 5310
722247f1
YQ
5311 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5312 (explained in remote-notif.c:handle_notification) so
5313 remote_notif_process is not called. We need find a place where
5314 it is safe to start a 'vNotif' sequence. It is good to do it
5315 before resuming inferior, because inferior was stopped and no RSP
5316 traffic at that moment. */
5317 if (!non_stop)
5965e028 5318 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5319
b73be471 5320 rs->last_sent_signal = siggnal;
280ceea3 5321 rs->last_sent_step = step;
43ff13b4 5322
506fb367 5323 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5324 /* No reverse support (yet) for vCont. */
5325 if (execution_direction != EXEC_REVERSE)
5326 if (remote_vcont_resume (ptid, step, siggnal))
5327 goto done;
506fb367 5328
79d7f229
PA
5329 /* All other supported resume packets do use Hc, so set the continue
5330 thread. */
5331 if (ptid_equal (ptid, minus_one_ptid))
5332 set_continue_thread (any_thread_ptid);
506fb367 5333 else
79d7f229 5334 set_continue_thread (ptid);
506fb367 5335
2e9f7625 5336 buf = rs->buf;
b2175913
MS
5337 if (execution_direction == EXEC_REVERSE)
5338 {
5339 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5340 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5341 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5342 siggnal);
40ab02ce 5343
4082afcc 5344 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5345 error (_("Remote reverse-step not supported."));
4082afcc 5346 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5347 error (_("Remote reverse-continue not supported."));
40ab02ce 5348
b2175913
MS
5349 strcpy (buf, step ? "bs" : "bc");
5350 }
a493e3e2 5351 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5352 {
5353 buf[0] = step ? 'S' : 'C';
c5aa993b 5354 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5355 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5356 buf[3] = '\0';
5357 }
5358 else
c5aa993b 5359 strcpy (buf, step ? "s" : "c");
506fb367 5360
44eaed12 5361 putpkt (buf);
43ff13b4 5362
75c99385 5363 done:
2acceee2 5364 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5365 with the event loop. NOTE: this is the one place where all the
5366 execution commands end up. We could alternatively do this in each
23860348 5367 of the execution commands in infcmd.c. */
2acceee2
JM
5368 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5369 into infcmd.c in order to allow inferior function calls to work
23860348 5370 NOT asynchronously. */
362646f5 5371 if (target_can_async_p ())
6a3753b3 5372 target_async (1);
e24a49d8
PA
5373
5374 /* We've just told the target to resume. The remote server will
5375 wait for the inferior to stop, and then send a stop reply. In
5376 the mean time, we can't start another command/query ourselves
74531fed
PA
5377 because the stub wouldn't be ready to process it. This applies
5378 only to the base all-stop protocol, however. In non-stop (which
5379 only supports vCont), the stub replies with an "OK", and is
5380 immediate able to process further serial input. */
5381 if (!non_stop)
5382 rs->waiting_for_stop_reply = 1;
43ff13b4 5383}
c906108c 5384\f
43ff13b4
JM
5385
5386/* Set up the signal handler for SIGINT, while the target is
23860348 5387 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5388static void
934b9bac 5389async_initialize_sigint_signal_handler (void)
43ff13b4 5390{
934b9bac 5391 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5392}
5393
23860348 5394/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5395static void
934b9bac 5396async_handle_remote_sigint (int sig)
43ff13b4 5397{
934b9bac 5398 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5399 /* Note we need to go through gdb_call_async_signal_handler in order
5400 to wake up the event loop on Windows. */
5401 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5402}
5403
5404/* Signal handler for SIGINT, installed after SIGINT has already been
5405 sent once. It will take effect the second time that the user sends
23860348 5406 a ^C. */
43ff13b4 5407static void
934b9bac 5408async_handle_remote_sigint_twice (int sig)
43ff13b4 5409{
934b9bac 5410 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5411 /* See note in async_handle_remote_sigint. */
5412 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5413}
5414
abc56d60
PA
5415/* Implementation of to_check_pending_interrupt. */
5416
5417static void
5418remote_check_pending_interrupt (struct target_ops *self)
5419{
5420 struct async_signal_handler *token = async_sigint_remote_twice_token;
5421
5422 if (async_signal_handler_is_marked (token))
5423 {
5424 clear_async_signal_handler (token);
5425 call_async_signal_handler (token);
5426 }
5427}
5428
6426a772 5429/* Perform the real interruption of the target execution, in response
23860348 5430 to a ^C. */
c5aa993b 5431static void
fba45db2 5432async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5433{
5434 if (remote_debug)
248fd3bf 5435 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5436
94cc34af 5437 target_stop (inferior_ptid);
43ff13b4
JM
5438}
5439
0df8b418 5440/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5441 up on the target alltogether. */
47e1ce27 5442static void
fba45db2 5443async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5444{
2df3850c 5445 if (remote_debug)
248fd3bf 5446 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5447
5448 interrupt_query ();
43ff13b4
JM
5449}
5450
5451/* Reinstall the usual SIGINT handlers, after the target has
23860348 5452 stopped. */
6426a772 5453static void
934b9bac 5454async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5455{
5456 signal (SIGINT, handle_sigint);
43ff13b4
JM
5457}
5458
c906108c
SS
5459/* Send ^C to target to halt it. Target will respond, and send us a
5460 packet. */
507f3c78 5461static void (*ofunc) (int);
c906108c 5462
bfedc46a
PA
5463/* The command line interface's interrupt routine. This function is installed
5464 as a signal handler for SIGINT. The first time a user requests an
5465 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5466 response from the target (it didn't stop when the user requested it),
23860348 5467 we ask the user if he'd like to detach from the target. */
bfedc46a 5468
c906108c 5469static void
934b9bac 5470sync_remote_interrupt (int signo)
c906108c 5471{
23860348 5472 /* If this doesn't work, try more severe steps. */
934b9bac 5473 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5474
934b9bac 5475 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5476}
5477
5478/* The user typed ^C twice. */
5479
5480static void
934b9bac 5481sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5482{
5483 signal (signo, ofunc);
934b9bac
JK
5484 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5485 signal (signo, sync_remote_interrupt);
c906108c 5486}
7a292a7a 5487
74531fed
PA
5488/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5489 thread, all threads of a remote process, or all threads of all
5490 processes. */
5491
5492static void
5493remote_stop_ns (ptid_t ptid)
5494{
5495 struct remote_state *rs = get_remote_state ();
5496 char *p = rs->buf;
5497 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5498
4082afcc 5499 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5500 remote_vcont_probe (rs);
5501
d458bd84 5502 if (!rs->supports_vCont.t)
74531fed
PA
5503 error (_("Remote server does not support stopping threads"));
5504
f91d3df5
PA
5505 if (ptid_equal (ptid, minus_one_ptid)
5506 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5507 p += xsnprintf (p, endp - p, "vCont;t");
5508 else
5509 {
5510 ptid_t nptid;
5511
74531fed
PA
5512 p += xsnprintf (p, endp - p, "vCont;t:");
5513
5514 if (ptid_is_pid (ptid))
5515 /* All (-1) threads of process. */
ba348170 5516 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5517 else
5518 {
5519 /* Small optimization: if we already have a stop reply for
5520 this thread, no use in telling the stub we want this
5521 stopped. */
5522 if (peek_stop_reply (ptid))
5523 return;
5524
5525 nptid = ptid;
5526 }
5527
a9cbf802 5528 write_ptid (p, endp, nptid);
74531fed
PA
5529 }
5530
5531 /* In non-stop, we get an immediate OK reply. The stop reply will
5532 come in asynchronously by notification. */
5533 putpkt (rs->buf);
5534 getpkt (&rs->buf, &rs->buf_size, 0);
5535 if (strcmp (rs->buf, "OK") != 0)
5536 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5537}
5538
bfedc46a
PA
5539/* All-stop version of target_interrupt. Sends a break or a ^C to
5540 interrupt the remote target. It is undefined which thread of which
5541 process reports the interrupt. */
74531fed
PA
5542
5543static void
bfedc46a 5544remote_interrupt_as (ptid_t ptid)
74531fed
PA
5545{
5546 struct remote_state *rs = get_remote_state ();
5547
3a29589a
DJ
5548 rs->ctrlc_pending_p = 1;
5549
74531fed
PA
5550 /* If the inferior is stopped already, but the core didn't know
5551 about it yet, just ignore the request. The cached wait status
5552 will be collected in remote_wait. */
5553 if (rs->cached_wait_status)
5554 return;
5555
9a7071a8
JB
5556 /* Send interrupt_sequence to remote target. */
5557 send_interrupt_sequence ();
74531fed
PA
5558}
5559
bfedc46a 5560/* Implement the to_stop function for the remote targets. */
74531fed 5561
c906108c 5562static void
1eab8a48 5563remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5564{
7a292a7a 5565 if (remote_debug)
0f71a2f6 5566 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5567
74531fed
PA
5568 if (non_stop)
5569 remote_stop_ns (ptid);
c906108c 5570 else
bfedc46a
PA
5571 {
5572 /* We don't currently have a way to transparently pause the
5573 remote target in all-stop mode. Interrupt it instead. */
5574 remote_interrupt_as (ptid);
5575 }
5576}
5577
5578/* Implement the to_interrupt function for the remote targets. */
5579
5580static void
5581remote_interrupt (struct target_ops *self, ptid_t ptid)
5582{
5583 if (remote_debug)
5584 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5585
5586 if (non_stop)
5587 {
5588 /* We don't currently have a way to ^C the remote target in
5589 non-stop mode. Stop it (with no signal) instead. */
5590 remote_stop_ns (ptid);
5591 }
5592 else
5593 remote_interrupt_as (ptid);
c906108c
SS
5594}
5595
5596/* Ask the user what to do when an interrupt is received. */
5597
5598static void
fba45db2 5599interrupt_query (void)
c906108c 5600{
abc56d60
PA
5601 struct remote_state *rs = get_remote_state ();
5602 struct cleanup *old_chain;
5603
5604 old_chain = make_cleanup_restore_target_terminal ();
c906108c
SS
5605 target_terminal_ours ();
5606
abc56d60 5607 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5608 {
abc56d60
PA
5609 if (query (_("The target is not responding to interrupt requests.\n"
5610 "Stop debugging it? ")))
74531fed 5611 {
78a095c3 5612 remote_unpush_target ();
abc56d60 5613 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5614 }
5615 }
abc56d60
PA
5616 else
5617 {
5618 if (query (_("Interrupted while waiting for the program.\n"
5619 "Give up waiting? ")))
5620 quit ();
5621 }
c906108c 5622
abc56d60 5623 do_cleanups (old_chain);
c906108c
SS
5624}
5625
6426a772
JM
5626/* Enable/disable target terminal ownership. Most targets can use
5627 terminal groups to control terminal ownership. Remote targets are
5628 different in that explicit transfer of ownership to/from GDB/target
23860348 5629 is required. */
6426a772
JM
5630
5631static void
d2f640d4 5632remote_terminal_inferior (struct target_ops *self)
6426a772 5633{
c6ebd6cf 5634 if (!target_async_permitted)
75c99385
PA
5635 /* Nothing to do. */
5636 return;
5637
d9d2d8b6
PA
5638 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5639 idempotent. The event-loop GDB talking to an asynchronous target
5640 with a synchronous command calls this function from both
5641 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5642 transfer the terminal to the target when it shouldn't this guard
5643 can go away. */
6426a772
JM
5644 if (!remote_async_terminal_ours_p)
5645 return;
5646 delete_file_handler (input_fd);
5647 remote_async_terminal_ours_p = 0;
934b9bac 5648 async_initialize_sigint_signal_handler ();
6426a772
JM
5649 /* NOTE: At this point we could also register our selves as the
5650 recipient of all input. Any characters typed could then be
23860348 5651 passed on down to the target. */
6426a772
JM
5652}
5653
5654static void
e3594fd1 5655remote_terminal_ours (struct target_ops *self)
6426a772 5656{
c6ebd6cf 5657 if (!target_async_permitted)
75c99385
PA
5658 /* Nothing to do. */
5659 return;
5660
5661 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5662 if (remote_async_terminal_ours_p)
5663 return;
934b9bac 5664 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5665 add_file_handler (input_fd, stdin_event_handler, 0);
5666 remote_async_terminal_ours_p = 1;
5667}
5668
176a6961 5669static void
917317f4 5670remote_console_output (char *msg)
c906108c
SS
5671{
5672 char *p;
5673
c5aa993b 5674 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5675 {
5676 char tb[2];
5677 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5678
c906108c
SS
5679 tb[0] = c;
5680 tb[1] = 0;
43ff13b4 5681 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5682 }
00db5b94
PA
5683 gdb_flush (gdb_stdtarg);
5684}
74531fed
PA
5685
5686typedef struct cached_reg
5687{
5688 int num;
5689 gdb_byte data[MAX_REGISTER_SIZE];
5690} cached_reg_t;
5691
5692DEF_VEC_O(cached_reg_t);
5693
722247f1 5694typedef struct stop_reply
74531fed 5695{
722247f1 5696 struct notif_event base;
74531fed 5697
722247f1 5698 /* The identifier of the thread about this event */
74531fed
PA
5699 ptid_t ptid;
5700
340e3c99 5701 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5702 connection, represented by a remote_state object, is closed,
5703 all the associated stop_reply events should be released. */
5704 struct remote_state *rs;
5705
74531fed
PA
5706 struct target_waitstatus ws;
5707
15148d6a
PA
5708 /* Expedited registers. This makes remote debugging a bit more
5709 efficient for those targets that provide critical registers as
5710 part of their normal status mechanism (as another roundtrip to
5711 fetch them is avoided). */
74531fed
PA
5712 VEC(cached_reg_t) *regcache;
5713
f7e6eed5
PA
5714 enum target_stop_reason stop_reason;
5715
74531fed
PA
5716 CORE_ADDR watch_data_address;
5717
dc146f7c 5718 int core;
722247f1 5719} *stop_reply_p;
a744cf53 5720
722247f1
YQ
5721DECLARE_QUEUE_P (stop_reply_p);
5722DEFINE_QUEUE_P (stop_reply_p);
5723/* The list of already fetched and acknowledged stop events. This
5724 queue is used for notification Stop, and other notifications
5725 don't need queue for their events, because the notification events
5726 of Stop can't be consumed immediately, so that events should be
5727 queued first, and be consumed by remote_wait_{ns,as} one per
5728 time. Other notifications can consume their events immediately,
5729 so queue is not needed for them. */
5730static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5731
5732static void
5733stop_reply_xfree (struct stop_reply *r)
5734{
f48ff2a7 5735 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5736}
5737
221e1a37
PA
5738/* Return the length of the stop reply queue. */
5739
5740static int
5741stop_reply_queue_length (void)
5742{
5743 return QUEUE_length (stop_reply_p, stop_reply_queue);
5744}
5745
722247f1
YQ
5746static void
5747remote_notif_stop_parse (struct notif_client *self, char *buf,
5748 struct notif_event *event)
5749{
5750 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5751}
5752
5753static void
5754remote_notif_stop_ack (struct notif_client *self, char *buf,
5755 struct notif_event *event)
5756{
5757 struct stop_reply *stop_reply = (struct stop_reply *) event;
5758
5759 /* acknowledge */
5760 putpkt ((char *) self->ack_command);
5761
5762 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5763 /* We got an unknown stop reply. */
5764 error (_("Unknown stop reply"));
5765
5766 push_stop_reply (stop_reply);
5767}
5768
5769static int
5770remote_notif_stop_can_get_pending_events (struct notif_client *self)
5771{
5772 /* We can't get pending events in remote_notif_process for
5773 notification stop, and we have to do this in remote_wait_ns
5774 instead. If we fetch all queued events from stub, remote stub
5775 may exit and we have no chance to process them back in
5776 remote_wait_ns. */
5777 mark_async_event_handler (remote_async_inferior_event_token);
5778 return 0;
5779}
5780
5781static void
5782stop_reply_dtr (struct notif_event *event)
5783{
5784 struct stop_reply *r = (struct stop_reply *) event;
5785
5786 VEC_free (cached_reg_t, r->regcache);
5787}
5788
5789static struct notif_event *
5790remote_notif_stop_alloc_reply (void)
5791{
8d749320
SM
5792 /* We cast to a pointer to the "base class". */
5793 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5794
5795 r->dtr = stop_reply_dtr;
5796
5797 return r;
5798}
5799
5800/* A client of notification Stop. */
5801
5802struct notif_client notif_client_stop =
5803{
5804 "Stop",
5805 "vStopped",
5806 remote_notif_stop_parse,
5807 remote_notif_stop_ack,
5808 remote_notif_stop_can_get_pending_events,
5809 remote_notif_stop_alloc_reply,
f48ff2a7 5810 REMOTE_NOTIF_STOP,
722247f1
YQ
5811};
5812
5813/* A parameter to pass data in and out. */
5814
5815struct queue_iter_param
5816{
5817 void *input;
5818 struct stop_reply *output;
5819};
5820
cbb8991c
DB
5821/* Determine if THREAD is a pending fork parent thread. ARG contains
5822 the pid of the process that owns the threads we want to check, or
5823 -1 if we want to check all threads. */
5824
5825static int
5826is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5827 ptid_t thread_ptid)
5828{
5829 if (ws->kind == TARGET_WAITKIND_FORKED
5830 || ws->kind == TARGET_WAITKIND_VFORKED)
5831 {
5832 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5833 return 1;
5834 }
5835
5836 return 0;
5837}
5838
5839/* Check whether EVENT is a fork event, and if it is, remove the
5840 fork child from the context list passed in DATA. */
5841
5842static int
5843remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5844 QUEUE_ITER (stop_reply_p) *iter,
5845 stop_reply_p event,
5846 void *data)
5847{
19ba03f4
SM
5848 struct queue_iter_param *param = (struct queue_iter_param *) data;
5849 struct threads_listing_context *context
5850 = (struct threads_listing_context *) param->input;
cbb8991c
DB
5851
5852 if (event->ws.kind == TARGET_WAITKIND_FORKED
5853 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5854 {
5855 threads_listing_context_remove (&event->ws, context);
5856 }
5857
5858 return 1;
5859}
5860
5861/* If CONTEXT contains any fork child threads that have not been
5862 reported yet, remove them from the CONTEXT list. If such a
5863 thread exists it is because we are stopped at a fork catchpoint
5864 and have not yet called follow_fork, which will set up the
5865 host-side data structures for the new process. */
5866
5867static void
5868remove_new_fork_children (struct threads_listing_context *context)
5869{
5870 struct thread_info * thread;
5871 int pid = -1;
5872 struct notif_client *notif = &notif_client_stop;
5873 struct queue_iter_param param;
5874
5875 /* For any threads stopped at a fork event, remove the corresponding
5876 fork child threads from the CONTEXT list. */
5877 ALL_NON_EXITED_THREADS (thread)
5878 {
5879 struct target_waitstatus *ws = &thread->pending_follow;
5880
5881 if (is_pending_fork_parent (ws, pid, thread->ptid))
5882 {
5883 threads_listing_context_remove (ws, context);
5884 }
5885 }
5886
5887 /* Check for any pending fork events (not reported or processed yet)
5888 in process PID and remove those fork child threads from the
5889 CONTEXT list as well. */
5890 remote_notif_get_pending_events (notif);
5891 param.input = context;
5892 param.output = NULL;
5893 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5894 remove_child_of_pending_fork, &param);
5895}
5896
f48ff2a7
YQ
5897/* Remove stop replies in the queue if its pid is equal to the given
5898 inferior's pid. */
722247f1
YQ
5899
5900static int
f48ff2a7
YQ
5901remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5902 QUEUE_ITER (stop_reply_p) *iter,
5903 stop_reply_p event,
5904 void *data)
722247f1 5905{
19ba03f4
SM
5906 struct queue_iter_param *param = (struct queue_iter_param *) data;
5907 struct inferior *inf = (struct inferior *) param->input;
722247f1 5908
f48ff2a7 5909 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5910 {
5911 stop_reply_xfree (event);
5912 QUEUE_remove_elem (stop_reply_p, q, iter);
5913 }
5914
5915 return 1;
5916}
5917
f48ff2a7 5918/* Discard all pending stop replies of inferior INF. */
c906108c 5919
74531fed 5920static void
5f4cf0bb 5921discard_pending_stop_replies (struct inferior *inf)
c906108c 5922{
722247f1
YQ
5923 int i;
5924 struct queue_iter_param param;
f48ff2a7
YQ
5925 struct stop_reply *reply;
5926 struct remote_state *rs = get_remote_state ();
5927 struct remote_notif_state *rns = rs->notif_state;
5928
5929 /* This function can be notified when an inferior exists. When the
5930 target is not remote, the notification state is NULL. */
5931 if (rs->remote_desc == NULL)
5932 return;
5933
5934 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5935
74531fed 5936 /* Discard the in-flight notification. */
f48ff2a7 5937 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5938 {
722247f1 5939 stop_reply_xfree (reply);
f48ff2a7 5940 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5941 }
c906108c 5942
722247f1
YQ
5943 param.input = inf;
5944 param.output = NULL;
74531fed
PA
5945 /* Discard the stop replies we have already pulled with
5946 vStopped. */
722247f1 5947 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5948 remove_stop_reply_for_inferior, &param);
5949}
5950
bcc75809
YQ
5951/* If its remote state is equal to the given remote state,
5952 remove EVENT from the stop reply queue. */
5953
5954static int
5955remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5956 QUEUE_ITER (stop_reply_p) *iter,
5957 stop_reply_p event,
5958 void *data)
5959{
19ba03f4
SM
5960 struct queue_iter_param *param = (struct queue_iter_param *) data;
5961 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
5962
5963 if (event->rs == rs)
5964 {
5965 stop_reply_xfree (event);
5966 QUEUE_remove_elem (stop_reply_p, q, iter);
5967 }
5968
5969 return 1;
5970}
5971
5972/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5973
5974static void
bcc75809 5975discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5976{
5977 struct queue_iter_param param;
5978
bcc75809 5979 param.input = rs;
f48ff2a7
YQ
5980 param.output = NULL;
5981 /* Discard the stop replies we have already pulled with
5982 vStopped. */
5983 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5984 remove_stop_reply_of_remote_state, &param);
722247f1 5985}
74531fed 5986
722247f1
YQ
5987/* A parameter to pass data in and out. */
5988
5989static int
5990remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5991 QUEUE_ITER (stop_reply_p) *iter,
5992 stop_reply_p event,
5993 void *data)
5994{
19ba03f4
SM
5995 struct queue_iter_param *param = (struct queue_iter_param *) data;
5996 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
5997
5998 if (ptid_match (event->ptid, *ptid))
5999 {
6000 param->output = event;
6001 QUEUE_remove_elem (stop_reply_p, q, iter);
6002 return 0;
c8e38a49 6003 }
722247f1
YQ
6004
6005 return 1;
74531fed 6006}
43ff13b4 6007
722247f1
YQ
6008/* Remove the first reply in 'stop_reply_queue' which matches
6009 PTID. */
2e9f7625 6010
722247f1
YQ
6011static struct stop_reply *
6012remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6013{
722247f1
YQ
6014 struct queue_iter_param param;
6015
6016 param.input = &ptid;
6017 param.output = NULL;
6018
6019 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6020 remote_notif_remove_once_on_match, &param);
6021 if (notif_debug)
6022 fprintf_unfiltered (gdb_stdlog,
6023 "notif: discard queued event: 'Stop' in %s\n",
6024 target_pid_to_str (ptid));
a744cf53 6025
722247f1 6026 return param.output;
74531fed 6027}
75c99385 6028
74531fed
PA
6029/* Look for a queued stop reply belonging to PTID. If one is found,
6030 remove it from the queue, and return it. Returns NULL if none is
6031 found. If there are still queued events left to process, tell the
6032 event loop to get back to target_wait soon. */
e24a49d8 6033
74531fed
PA
6034static struct stop_reply *
6035queued_stop_reply (ptid_t ptid)
6036{
722247f1 6037 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6038
722247f1 6039 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6040 /* There's still at least an event left. */
6041 mark_async_event_handler (remote_async_inferior_event_token);
6042
722247f1 6043 return r;
74531fed
PA
6044}
6045
6046/* Push a fully parsed stop reply in the stop reply queue. Since we
6047 know that we now have at least one queued event left to pass to the
6048 core side, tell the event loop to get back to target_wait soon. */
6049
6050static void
6051push_stop_reply (struct stop_reply *new_event)
6052{
722247f1 6053 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6054
722247f1
YQ
6055 if (notif_debug)
6056 fprintf_unfiltered (gdb_stdlog,
6057 "notif: push 'Stop' %s to queue %d\n",
6058 target_pid_to_str (new_event->ptid),
6059 QUEUE_length (stop_reply_p,
6060 stop_reply_queue));
74531fed
PA
6061
6062 mark_async_event_handler (remote_async_inferior_event_token);
6063}
6064
722247f1
YQ
6065static int
6066stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6067 QUEUE_ITER (stop_reply_p) *iter,
6068 struct stop_reply *event,
6069 void *data)
6070{
19ba03f4 6071 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6072
6073 return !(ptid_equal (*ptid, event->ptid)
6074 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6075}
6076
74531fed
PA
6077/* Returns true if we have a stop reply for PTID. */
6078
6079static int
6080peek_stop_reply (ptid_t ptid)
6081{
722247f1
YQ
6082 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6083 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6084}
6085
1f10ba14
PA
6086/* Skip PACKET until the next semi-colon (or end of string). */
6087
6088static char *
6089skip_to_semicolon (char *p)
6090{
6091 while (*p != '\0' && *p != ';')
6092 p++;
6093 return p;
6094}
6095
26d56a93
SL
6096/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6097 starting with P and ending with PEND matches PREFIX. */
6098
6099static int
6100strprefix (const char *p, const char *pend, const char *prefix)
6101{
6102 for ( ; p < pend; p++, prefix++)
6103 if (*p != *prefix)
6104 return 0;
6105 return *prefix == '\0';
6106}
6107
74531fed
PA
6108/* Parse the stop reply in BUF. Either the function succeeds, and the
6109 result is stored in EVENT, or throws an error. */
6110
6111static void
6112remote_parse_stop_reply (char *buf, struct stop_reply *event)
6113{
6114 struct remote_arch_state *rsa = get_remote_arch_state ();
6115 ULONGEST addr;
6116 char *p;
94585166 6117 int skipregs = 0;
74531fed
PA
6118
6119 event->ptid = null_ptid;
bcc75809 6120 event->rs = get_remote_state ();
74531fed
PA
6121 event->ws.kind = TARGET_WAITKIND_IGNORE;
6122 event->ws.value.integer = 0;
f7e6eed5 6123 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6124 event->regcache = NULL;
dc146f7c 6125 event->core = -1;
74531fed
PA
6126
6127 switch (buf[0])
6128 {
6129 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6130 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6131 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6132 ss = signal number
6133 n... = register number
6134 r... = register contents
6135 */
6136
6137 p = &buf[3]; /* after Txx */
6138 while (*p)
6139 {
6140 char *p1;
cea39f65 6141 int fieldsize;
43ff13b4 6142
1f10ba14
PA
6143 p1 = strchr (p, ':');
6144 if (p1 == NULL)
6145 error (_("Malformed packet(a) (missing colon): %s\n\
6146Packet: '%s'\n"),
6147 p, buf);
6148 if (p == p1)
6149 error (_("Malformed packet(a) (missing register number): %s\n\
6150Packet: '%s'\n"),
6151 p, buf);
3c3bea1c 6152
1f10ba14
PA
6153 /* Some "registers" are actually extended stop information.
6154 Note if you're adding a new entry here: GDB 7.9 and
6155 earlier assume that all register "numbers" that start
6156 with an hex digit are real register numbers. Make sure
6157 the server only sends such a packet if it knows the
6158 client understands it. */
c8e38a49 6159
26d56a93 6160 if (strprefix (p, p1, "thread"))
1f10ba14 6161 event->ptid = read_ptid (++p1, &p);
26d56a93
SL
6162 else if (strprefix (p, p1, "watch")
6163 || strprefix (p, p1, "rwatch")
6164 || strprefix (p, p1, "awatch"))
cea39f65 6165 {
f7e6eed5 6166 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6167 p = unpack_varlen_hex (++p1, &addr);
6168 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6169 }
26d56a93 6170 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6171 {
6172 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6173
6174 /* Make sure the stub doesn't forget to indicate support
6175 with qSupported. */
6176 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6177 error (_("Unexpected swbreak stop reason"));
6178
6179 /* The value part is documented as "must be empty",
6180 though we ignore it, in case we ever decide to make
6181 use of it in a backward compatible way. */
6182 p = skip_to_semicolon (p1 + 1);
6183 }
26d56a93 6184 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6185 {
6186 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6187
6188 /* Make sure the stub doesn't forget to indicate support
6189 with qSupported. */
6190 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6191 error (_("Unexpected hwbreak stop reason"));
6192
6193 /* See above. */
6194 p = skip_to_semicolon (p1 + 1);
6195 }
26d56a93 6196 else if (strprefix (p, p1, "library"))
cea39f65 6197 {
1f10ba14
PA
6198 event->ws.kind = TARGET_WAITKIND_LOADED;
6199 p = skip_to_semicolon (p1 + 1);
6200 }
26d56a93 6201 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6202 {
6203 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6204 /* p1 will indicate "begin" or "end", but it makes
6205 no difference for now, so ignore it. */
6206 p = skip_to_semicolon (p1 + 1);
6207 }
26d56a93 6208 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6209 {
6210 ULONGEST c;
a744cf53 6211
1f10ba14
PA
6212 p = unpack_varlen_hex (++p1, &c);
6213 event->core = c;
cea39f65 6214 }
26d56a93 6215 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6216 {
6217 event->ws.value.related_pid = read_ptid (++p1, &p);
6218 event->ws.kind = TARGET_WAITKIND_FORKED;
6219 }
26d56a93 6220 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6221 {
6222 event->ws.value.related_pid = read_ptid (++p1, &p);
6223 event->ws.kind = TARGET_WAITKIND_VFORKED;
6224 }
26d56a93 6225 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6226 {
6227 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6228 p = skip_to_semicolon (p1 + 1);
6229 }
94585166
DB
6230 else if (strncmp (p, "exec", p1 - p) == 0)
6231 {
6232 ULONGEST ignored;
6233 char pathname[PATH_MAX];
6234 int pathlen;
6235
6236 /* Determine the length of the execd pathname. */
6237 p = unpack_varlen_hex (++p1, &ignored);
6238 pathlen = (p - p1) / 2;
6239
6240 /* Save the pathname for event reporting and for
6241 the next run command. */
6242 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6243 pathname[pathlen] = '\0';
6244
6245 /* This is freed during event handling. */
6246 event->ws.value.execd_pathname = xstrdup (pathname);
6247 event->ws.kind = TARGET_WAITKIND_EXECD;
6248
6249 /* Skip the registers included in this packet, since
6250 they may be for an architecture different from the
6251 one used by the original program. */
6252 skipregs = 1;
6253 }
cea39f65
MS
6254 else
6255 {
1f10ba14
PA
6256 ULONGEST pnum;
6257 char *p_temp;
6258
94585166
DB
6259 if (skipregs)
6260 {
6261 p = skip_to_semicolon (p1 + 1);
6262 p++;
6263 continue;
6264 }
6265
1f10ba14
PA
6266 /* Maybe a real ``P'' register number. */
6267 p_temp = unpack_varlen_hex (p, &pnum);
6268 /* If the first invalid character is the colon, we got a
6269 register number. Otherwise, it's an unknown stop
6270 reason. */
6271 if (p_temp == p1)
6272 {
6273 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6274 cached_reg_t cached_reg;
43ff13b4 6275
1f10ba14
PA
6276 if (reg == NULL)
6277 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6278Packet: '%s'\n"),
1f10ba14 6279 hex_string (pnum), p, buf);
c8e38a49 6280
1f10ba14 6281 cached_reg.num = reg->regnum;
4100683b 6282
1f10ba14
PA
6283 p = p1 + 1;
6284 fieldsize = hex2bin (p, cached_reg.data,
6285 register_size (target_gdbarch (),
6286 reg->regnum));
6287 p += 2 * fieldsize;
6288 if (fieldsize < register_size (target_gdbarch (),
6289 reg->regnum))
6290 warning (_("Remote reply is too short: %s"), buf);
74531fed 6291
1f10ba14
PA
6292 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6293 }
6294 else
6295 {
6296 /* Not a number. Silently skip unknown optional
6297 info. */
6298 p = skip_to_semicolon (p1 + 1);
6299 }
cea39f65 6300 }
c8e38a49 6301
cea39f65
MS
6302 if (*p != ';')
6303 error (_("Remote register badly formatted: %s\nhere: %s"),
6304 buf, p);
6305 ++p;
6306 }
5b5596ff
PA
6307
6308 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6309 break;
6310
c8e38a49
PA
6311 /* fall through */
6312 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6313 {
6314 int sig;
6315
6316 event->ws.kind = TARGET_WAITKIND_STOPPED;
6317 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6318 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6319 event->ws.value.sig = (enum gdb_signal) sig;
6320 else
6321 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6322 }
c8e38a49
PA
6323 break;
6324 case 'W': /* Target exited. */
6325 case 'X':
6326 {
6327 char *p;
6328 int pid;
6329 ULONGEST value;
82f73884 6330
c8e38a49
PA
6331 /* GDB used to accept only 2 hex chars here. Stubs should
6332 only send more if they detect GDB supports multi-process
6333 support. */
6334 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6335
c8e38a49
PA
6336 if (buf[0] == 'W')
6337 {
6338 /* The remote process exited. */
74531fed
PA
6339 event->ws.kind = TARGET_WAITKIND_EXITED;
6340 event->ws.value.integer = value;
c8e38a49
PA
6341 }
6342 else
6343 {
6344 /* The remote process exited with a signal. */
74531fed 6345 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6346 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6347 event->ws.value.sig = (enum gdb_signal) value;
6348 else
6349 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6350 }
82f73884 6351
c8e38a49
PA
6352 /* If no process is specified, assume inferior_ptid. */
6353 pid = ptid_get_pid (inferior_ptid);
6354 if (*p == '\0')
6355 ;
6356 else if (*p == ';')
6357 {
6358 p++;
6359
0b24eb2d 6360 if (*p == '\0')
82f73884 6361 ;
61012eef 6362 else if (startswith (p, "process:"))
82f73884 6363 {
c8e38a49 6364 ULONGEST upid;
a744cf53 6365
c8e38a49
PA
6366 p += sizeof ("process:") - 1;
6367 unpack_varlen_hex (p, &upid);
6368 pid = upid;
82f73884
PA
6369 }
6370 else
6371 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6372 }
c8e38a49
PA
6373 else
6374 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6375 event->ptid = pid_to_ptid (pid);
6376 }
6377 break;
6378 }
6379
6380 if (non_stop && ptid_equal (event->ptid, null_ptid))
6381 error (_("No process or thread specified in stop reply: %s"), buf);
6382}
6383
722247f1
YQ
6384/* When the stub wants to tell GDB about a new notification reply, it
6385 sends a notification (%Stop, for example). Those can come it at
6386 any time, hence, we have to make sure that any pending
6387 putpkt/getpkt sequence we're making is finished, before querying
6388 the stub for more events with the corresponding ack command
6389 (vStopped, for example). E.g., if we started a vStopped sequence
6390 immediately upon receiving the notification, something like this
6391 could happen:
74531fed
PA
6392
6393 1.1) --> Hg 1
6394 1.2) <-- OK
6395 1.3) --> g
6396 1.4) <-- %Stop
6397 1.5) --> vStopped
6398 1.6) <-- (registers reply to step #1.3)
6399
6400 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6401 query.
6402
796cb314 6403 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6404 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6405 doing whatever we were doing:
6406
6407 2.1) --> Hg 1
6408 2.2) <-- OK
6409 2.3) --> g
6410 2.4) <-- %Stop
6411 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6412 2.5) <-- (registers reply to step #2.3)
6413
6414 Eventualy after step #2.5, we return to the event loop, which
6415 notices there's an event on the
6416 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6417 associated callback --- the function below. At this point, we're
6418 always safe to start a vStopped sequence. :
6419
6420 2.6) --> vStopped
6421 2.7) <-- T05 thread:2
6422 2.8) --> vStopped
6423 2.9) --> OK
6424*/
6425
722247f1
YQ
6426void
6427remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6428{
6429 struct remote_state *rs = get_remote_state ();
74531fed 6430
f48ff2a7 6431 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6432 {
722247f1
YQ
6433 if (notif_debug)
6434 fprintf_unfiltered (gdb_stdlog,
6435 "notif: process: '%s' ack pending event\n",
6436 nc->name);
74531fed 6437
722247f1 6438 /* acknowledge */
f48ff2a7
YQ
6439 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6440 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6441
6442 while (1)
6443 {
6444 getpkt (&rs->buf, &rs->buf_size, 0);
6445 if (strcmp (rs->buf, "OK") == 0)
6446 break;
6447 else
722247f1 6448 remote_notif_ack (nc, rs->buf);
74531fed
PA
6449 }
6450 }
722247f1
YQ
6451 else
6452 {
6453 if (notif_debug)
6454 fprintf_unfiltered (gdb_stdlog,
6455 "notif: process: '%s' no pending reply\n",
6456 nc->name);
6457 }
74531fed
PA
6458}
6459
74531fed
PA
6460/* Called when it is decided that STOP_REPLY holds the info of the
6461 event that is to be returned to the core. This function always
6462 destroys STOP_REPLY. */
6463
6464static ptid_t
6465process_stop_reply (struct stop_reply *stop_reply,
6466 struct target_waitstatus *status)
6467{
6468 ptid_t ptid;
6469
6470 *status = stop_reply->ws;
6471 ptid = stop_reply->ptid;
6472
6473 /* If no thread/process was reported by the stub, assume the current
6474 inferior. */
6475 if (ptid_equal (ptid, null_ptid))
6476 ptid = inferior_ptid;
6477
5f3563ea
PA
6478 if (status->kind != TARGET_WAITKIND_EXITED
6479 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 6480 {
ee154bee
TT
6481 struct remote_state *rs = get_remote_state ();
6482
5f3563ea
PA
6483 /* Expedited registers. */
6484 if (stop_reply->regcache)
6485 {
217f1f79 6486 struct regcache *regcache
f5656ead 6487 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6488 cached_reg_t *reg;
6489 int ix;
6490
6491 for (ix = 0;
6492 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6493 ix++)
217f1f79 6494 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6495 VEC_free (cached_reg_t, stop_reply->regcache);
6496 }
74531fed 6497
f7e6eed5 6498 rs->stop_reason = stop_reply->stop_reason;
ee154bee 6499 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
6500
6501 remote_notice_new_inferior (ptid, 0);
dc146f7c 6502 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
6503 }
6504
74531fed
PA
6505 stop_reply_xfree (stop_reply);
6506 return ptid;
6507}
6508
6509/* The non-stop mode version of target_wait. */
6510
6511static ptid_t
47608cb1 6512remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6513{
6514 struct remote_state *rs = get_remote_state ();
74531fed
PA
6515 struct stop_reply *stop_reply;
6516 int ret;
fee9eda9 6517 int is_notif = 0;
74531fed
PA
6518
6519 /* If in non-stop mode, get out of getpkt even if a
6520 notification is received. */
6521
6522 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6523 0 /* forever */, &is_notif);
74531fed
PA
6524 while (1)
6525 {
fee9eda9 6526 if (ret != -1 && !is_notif)
74531fed
PA
6527 switch (rs->buf[0])
6528 {
6529 case 'E': /* Error of some sort. */
6530 /* We're out of sync with the target now. Did it continue
6531 or not? We can't tell which thread it was in non-stop,
6532 so just ignore this. */
6533 warning (_("Remote failure reply: %s"), rs->buf);
6534 break;
6535 case 'O': /* Console output. */
6536 remote_console_output (rs->buf + 1);
6537 break;
6538 default:
6539 warning (_("Invalid remote reply: %s"), rs->buf);
6540 break;
6541 }
6542
6543 /* Acknowledge a pending stop reply that may have arrived in the
6544 mean time. */
f48ff2a7 6545 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6546 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6547
6548 /* If indeed we noticed a stop reply, we're done. */
6549 stop_reply = queued_stop_reply (ptid);
6550 if (stop_reply != NULL)
6551 return process_stop_reply (stop_reply, status);
6552
47608cb1 6553 /* Still no event. If we're just polling for an event, then
74531fed 6554 return to the event loop. */
47608cb1 6555 if (options & TARGET_WNOHANG)
74531fed
PA
6556 {
6557 status->kind = TARGET_WAITKIND_IGNORE;
6558 return minus_one_ptid;
6559 }
6560
47608cb1 6561 /* Otherwise do a blocking wait. */
74531fed 6562 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6563 1 /* forever */, &is_notif);
74531fed
PA
6564 }
6565}
6566
6567/* Wait until the remote machine stops, then return, storing status in
6568 STATUS just as `wait' would. */
6569
6570static ptid_t
47608cb1 6571remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6572{
6573 struct remote_state *rs = get_remote_state ();
74531fed 6574 ptid_t event_ptid = null_ptid;
cea39f65 6575 char *buf;
74531fed
PA
6576 struct stop_reply *stop_reply;
6577
47608cb1
PA
6578 again:
6579
74531fed
PA
6580 status->kind = TARGET_WAITKIND_IGNORE;
6581 status->value.integer = 0;
6582
6583 stop_reply = queued_stop_reply (ptid);
6584 if (stop_reply != NULL)
6585 return process_stop_reply (stop_reply, status);
6586
6587 if (rs->cached_wait_status)
6588 /* Use the cached wait status, but only once. */
6589 rs->cached_wait_status = 0;
6590 else
6591 {
6592 int ret;
722247f1 6593 int is_notif;
567420d1
PA
6594 int forever = ((options & TARGET_WNOHANG) == 0
6595 && wait_forever_enabled_p);
6596
6597 if (!rs->waiting_for_stop_reply)
6598 {
6599 status->kind = TARGET_WAITKIND_NO_RESUMED;
6600 return minus_one_ptid;
6601 }
74531fed
PA
6602
6603 if (!target_is_async_p ())
6604 {
934b9bac 6605 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6606 /* If the user hit C-c before this packet, or between packets,
6607 pretend that it was hit right here. */
522002f9 6608 if (check_quit_flag ())
74531fed 6609 {
522002f9 6610 clear_quit_flag ();
934b9bac 6611 sync_remote_interrupt (SIGINT);
74531fed
PA
6612 }
6613 }
6614
6615 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6616 _never_ wait for ever -> test on target_is_async_p().
6617 However, before we do that we need to ensure that the caller
6618 knows how to take the target into/out of async mode. */
722247f1 6619 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6620 forever, &is_notif);
722247f1 6621
5e1b953b
SDJ
6622 if (!target_is_async_p ())
6623 signal (SIGINT, ofunc);
6624
722247f1
YQ
6625 /* GDB gets a notification. Return to core as this event is
6626 not interesting. */
6627 if (ret != -1 && is_notif)
6628 return minus_one_ptid;
567420d1
PA
6629
6630 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6631 return minus_one_ptid;
74531fed
PA
6632 }
6633
6634 buf = rs->buf;
6635
f7e6eed5 6636 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed
PA
6637
6638 /* We got something. */
6639 rs->waiting_for_stop_reply = 0;
6640
3a29589a
DJ
6641 /* Assume that the target has acknowledged Ctrl-C unless we receive
6642 an 'F' or 'O' packet. */
6643 if (buf[0] != 'F' && buf[0] != 'O')
6644 rs->ctrlc_pending_p = 0;
6645
74531fed
PA
6646 switch (buf[0])
6647 {
6648 case 'E': /* Error of some sort. */
6649 /* We're out of sync with the target now. Did it continue or
6650 not? Not is more likely, so report a stop. */
6651 warning (_("Remote failure reply: %s"), buf);
6652 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6653 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6654 break;
6655 case 'F': /* File-I/O request. */
3a29589a
DJ
6656 remote_fileio_request (buf, rs->ctrlc_pending_p);
6657 rs->ctrlc_pending_p = 0;
74531fed
PA
6658 break;
6659 case 'T': case 'S': case 'X': case 'W':
6660 {
722247f1
YQ
6661 struct stop_reply *stop_reply
6662 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6663 rs->buf);
74531fed 6664
74531fed 6665 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6666 break;
6667 }
6668 case 'O': /* Console output. */
6669 remote_console_output (buf + 1);
e24a49d8 6670
c8e38a49
PA
6671 /* The target didn't really stop; keep waiting. */
6672 rs->waiting_for_stop_reply = 1;
e24a49d8 6673
c8e38a49
PA
6674 break;
6675 case '\0':
b73be471 6676 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6677 {
6678 /* Zero length reply means that we tried 'S' or 'C' and the
6679 remote system doesn't support it. */
6680 target_terminal_ours_for_output ();
6681 printf_filtered
6682 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6683 gdb_signal_to_name (rs->last_sent_signal));
6684 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6685 target_terminal_inferior ();
6686
280ceea3 6687 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6688 putpkt ((char *) buf);
6689
6690 /* We just told the target to resume, so a stop reply is in
6691 order. */
e24a49d8 6692 rs->waiting_for_stop_reply = 1;
c8e38a49 6693 break;
43ff13b4 6694 }
c8e38a49
PA
6695 /* else fallthrough */
6696 default:
6697 warning (_("Invalid remote reply: %s"), buf);
6698 /* Keep waiting. */
6699 rs->waiting_for_stop_reply = 1;
6700 break;
43ff13b4 6701 }
c8e38a49 6702
c8e38a49 6703 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6704 {
6705 /* Nothing interesting happened. If we're doing a non-blocking
6706 poll, we're done. Otherwise, go back to waiting. */
6707 if (options & TARGET_WNOHANG)
6708 return minus_one_ptid;
6709 else
6710 goto again;
6711 }
74531fed
PA
6712 else if (status->kind != TARGET_WAITKIND_EXITED
6713 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6714 {
6715 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6716 record_currthread (rs, event_ptid);
82f73884
PA
6717 else
6718 event_ptid = inferior_ptid;
43ff13b4 6719 }
74531fed
PA
6720 else
6721 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6722 record_currthread (rs, minus_one_ptid);
79d7f229 6723
82f73884 6724 return event_ptid;
43ff13b4
JM
6725}
6726
74531fed
PA
6727/* Wait until the remote machine stops, then return, storing status in
6728 STATUS just as `wait' would. */
6729
c8e38a49 6730static ptid_t
117de6a9 6731remote_wait (struct target_ops *ops,
47608cb1 6732 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6733{
6734 ptid_t event_ptid;
6735
74531fed 6736 if (non_stop)
47608cb1 6737 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6738 else
47608cb1 6739 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6740
d9d41e78 6741 if (target_is_async_p ())
c8e38a49 6742 {
74531fed
PA
6743 /* If there are are events left in the queue tell the event loop
6744 to return here. */
722247f1 6745 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6746 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6747 }
c8e38a49
PA
6748
6749 return event_ptid;
6750}
6751
74ca34ce 6752/* Fetch a single register using a 'p' packet. */
c906108c 6753
b96ec7ac 6754static int
56be3814 6755fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6756{
6757 struct remote_state *rs = get_remote_state ();
2e9f7625 6758 char *buf, *p;
b96ec7ac
AC
6759 char regp[MAX_REGISTER_SIZE];
6760 int i;
6761
4082afcc 6762 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6763 return 0;
6764
6765 if (reg->pnum == -1)
6766 return 0;
6767
2e9f7625 6768 p = rs->buf;
fcad0fa4 6769 *p++ = 'p';
74ca34ce 6770 p += hexnumstr (p, reg->pnum);
fcad0fa4 6771 *p++ = '\0';
1f4437a4
MS
6772 putpkt (rs->buf);
6773 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6774
2e9f7625
DJ
6775 buf = rs->buf;
6776
74ca34ce
DJ
6777 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6778 {
6779 case PACKET_OK:
6780 break;
6781 case PACKET_UNKNOWN:
6782 return 0;
6783 case PACKET_ERROR:
27a9c0bf
MS
6784 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6785 gdbarch_register_name (get_regcache_arch (regcache),
6786 reg->regnum),
6787 buf);
74ca34ce 6788 }
3f9a994c
JB
6789
6790 /* If this register is unfetchable, tell the regcache. */
6791 if (buf[0] == 'x')
8480adf2 6792 {
56be3814 6793 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6794 return 1;
b96ec7ac 6795 }
b96ec7ac 6796
3f9a994c
JB
6797 /* Otherwise, parse and supply the value. */
6798 p = buf;
6799 i = 0;
6800 while (p[0] != 0)
6801 {
6802 if (p[1] == 0)
74ca34ce 6803 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6804
6805 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6806 p += 2;
6807 }
56be3814 6808 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6809 return 1;
b96ec7ac
AC
6810}
6811
74ca34ce
DJ
6812/* Fetch the registers included in the target's 'g' packet. */
6813
29709017
DJ
6814static int
6815send_g_packet (void)
c906108c 6816{
d01949b6 6817 struct remote_state *rs = get_remote_state ();
cea39f65 6818 int buf_len;
c906108c 6819
bba74b36 6820 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6821 remote_send (&rs->buf, &rs->buf_size);
c906108c 6822
29709017
DJ
6823 /* We can get out of synch in various cases. If the first character
6824 in the buffer is not a hex character, assume that has happened
6825 and try to fetch another packet to read. */
6826 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6827 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6828 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6829 && rs->buf[0] != 'x') /* New: unavailable register value. */
6830 {
6831 if (remote_debug)
6832 fprintf_unfiltered (gdb_stdlog,
6833 "Bad register packet; fetching a new packet\n");
6834 getpkt (&rs->buf, &rs->buf_size, 0);
6835 }
6836
74ca34ce
DJ
6837 buf_len = strlen (rs->buf);
6838
6839 /* Sanity check the received packet. */
6840 if (buf_len % 2 != 0)
6841 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6842
6843 return buf_len / 2;
6844}
6845
6846static void
56be3814 6847process_g_packet (struct regcache *regcache)
29709017 6848{
4a22f64d 6849 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6850 struct remote_state *rs = get_remote_state ();
6851 struct remote_arch_state *rsa = get_remote_arch_state ();
6852 int i, buf_len;
6853 char *p;
6854 char *regs;
6855
6856 buf_len = strlen (rs->buf);
6857
6858 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6859 if (buf_len > 2 * rsa->sizeof_g_packet)
6860 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6861
6862 /* Save the size of the packet sent to us by the target. It is used
6863 as a heuristic when determining the max size of packets that the
6864 target can safely receive. */
6865 if (rsa->actual_register_packet_size == 0)
6866 rsa->actual_register_packet_size = buf_len;
6867
6868 /* If this is smaller than we guessed the 'g' packet would be,
6869 update our records. A 'g' reply that doesn't include a register's
6870 value implies either that the register is not available, or that
6871 the 'p' packet must be used. */
6872 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6873 {
74ca34ce
DJ
6874 rsa->sizeof_g_packet = buf_len / 2;
6875
4a22f64d 6876 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6877 {
74ca34ce
DJ
6878 if (rsa->regs[i].pnum == -1)
6879 continue;
6880
6881 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6882 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6883 else
74ca34ce 6884 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6885 }
74ca34ce 6886 }
b323314b 6887
224c3ddb 6888 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
6889
6890 /* Unimplemented registers read as all bits zero. */
ea9c271d 6891 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6892
c906108c
SS
6893 /* Reply describes registers byte by byte, each byte encoded as two
6894 hex characters. Suck them all up, then supply them to the
6895 register cacheing/storage mechanism. */
6896
74ca34ce 6897 p = rs->buf;
ea9c271d 6898 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6899 {
74ca34ce
DJ
6900 if (p[0] == 0 || p[1] == 0)
6901 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6902 internal_error (__FILE__, __LINE__,
9b20d036 6903 _("unexpected end of 'g' packet reply"));
74ca34ce 6904
c906108c 6905 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6906 regs[i] = 0; /* 'x' */
c906108c
SS
6907 else
6908 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6909 p += 2;
6910 }
6911
a744cf53
MS
6912 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6913 {
6914 struct packet_reg *r = &rsa->regs[i];
6915
6916 if (r->in_g_packet)
6917 {
6918 if (r->offset * 2 >= strlen (rs->buf))
6919 /* This shouldn't happen - we adjusted in_g_packet above. */
6920 internal_error (__FILE__, __LINE__,
9b20d036 6921 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6922 else if (rs->buf[r->offset * 2] == 'x')
6923 {
6924 gdb_assert (r->offset * 2 < strlen (rs->buf));
6925 /* The register isn't available, mark it as such (at
6926 the same time setting the value to zero). */
6927 regcache_raw_supply (regcache, r->regnum, NULL);
6928 }
6929 else
6930 regcache_raw_supply (regcache, r->regnum,
6931 regs + r->offset);
6932 }
6933 }
c906108c
SS
6934}
6935
29709017 6936static void
56be3814 6937fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6938{
6939 send_g_packet ();
56be3814 6940 process_g_packet (regcache);
29709017
DJ
6941}
6942
e6e4e701
PA
6943/* Make the remote selected traceframe match GDB's selected
6944 traceframe. */
6945
6946static void
6947set_remote_traceframe (void)
6948{
6949 int newnum;
262e1174 6950 struct remote_state *rs = get_remote_state ();
e6e4e701 6951
262e1174 6952 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6953 return;
6954
6955 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6956 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6957
6958 newnum = target_trace_find (tfind_number,
6959 get_traceframe_number (), 0, 0, NULL);
6960
6961 /* Should not happen. If it does, all bets are off. */
6962 if (newnum != get_traceframe_number ())
6963 warning (_("could not set remote traceframe"));
6964}
6965
74ca34ce 6966static void
28439f5e
PA
6967remote_fetch_registers (struct target_ops *ops,
6968 struct regcache *regcache, int regnum)
74ca34ce 6969{
74ca34ce
DJ
6970 struct remote_arch_state *rsa = get_remote_arch_state ();
6971 int i;
6972
e6e4e701 6973 set_remote_traceframe ();
79d7f229 6974 set_general_thread (inferior_ptid);
74ca34ce
DJ
6975
6976 if (regnum >= 0)
6977 {
6978 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6979
74ca34ce
DJ
6980 gdb_assert (reg != NULL);
6981
6982 /* If this register might be in the 'g' packet, try that first -
6983 we are likely to read more than one register. If this is the
6984 first 'g' packet, we might be overly optimistic about its
6985 contents, so fall back to 'p'. */
6986 if (reg->in_g_packet)
6987 {
56be3814 6988 fetch_registers_using_g (regcache);
74ca34ce
DJ
6989 if (reg->in_g_packet)
6990 return;
6991 }
6992
56be3814 6993 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6994 return;
6995
6996 /* This register is not available. */
56be3814 6997 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6998
6999 return;
7000 }
7001
56be3814 7002 fetch_registers_using_g (regcache);
74ca34ce 7003
4a22f64d 7004 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7005 if (!rsa->regs[i].in_g_packet)
56be3814 7006 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7007 {
7008 /* This register is not available. */
56be3814 7009 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7010 }
7011}
7012
c906108c
SS
7013/* Prepare to store registers. Since we may send them all (using a
7014 'G' request), we have to read out the ones we don't want to change
7015 first. */
7016
c5aa993b 7017static void
f32dbf8c 7018remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7019{
ea9c271d 7020 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7021 int i;
cfd77fa1 7022 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7023
c906108c 7024 /* Make sure the entire registers array is valid. */
4082afcc 7025 switch (packet_support (PACKET_P))
5a2468f5
JM
7026 {
7027 case PACKET_DISABLE:
7028 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7029 /* Make sure all the necessary registers are cached. */
4a22f64d 7030 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7031 if (rsa->regs[i].in_g_packet)
316f2060 7032 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7033 break;
7034 case PACKET_ENABLE:
7035 break;
7036 }
7037}
7038
ad10f812 7039/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7040 packet was not recognized. */
5a2468f5
JM
7041
7042static int
1f4437a4
MS
7043store_register_using_P (const struct regcache *regcache,
7044 struct packet_reg *reg)
5a2468f5 7045{
4a22f64d 7046 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7047 struct remote_state *rs = get_remote_state ();
5a2468f5 7048 /* Try storing a single register. */
6d820c5c 7049 char *buf = rs->buf;
cfd77fa1 7050 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7051 char *p;
5a2468f5 7052
4082afcc 7053 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7054 return 0;
7055
7056 if (reg->pnum == -1)
7057 return 0;
7058
ea9c271d 7059 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7060 p = buf + strlen (buf);
56be3814 7061 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7062 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7063 putpkt (rs->buf);
7064 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7065
74ca34ce
DJ
7066 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7067 {
7068 case PACKET_OK:
7069 return 1;
7070 case PACKET_ERROR:
27a9c0bf
MS
7071 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7072 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7073 case PACKET_UNKNOWN:
7074 return 0;
7075 default:
7076 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7077 }
c906108c
SS
7078}
7079
23860348
MS
7080/* Store register REGNUM, or all registers if REGNUM == -1, from the
7081 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7082
7083static void
56be3814 7084store_registers_using_G (const struct regcache *regcache)
c906108c 7085{
d01949b6 7086 struct remote_state *rs = get_remote_state ();
ea9c271d 7087 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7088 gdb_byte *regs;
c906108c
SS
7089 char *p;
7090
193cb69f
AC
7091 /* Extract all the registers in the regcache copying them into a
7092 local buffer. */
7093 {
b323314b 7094 int i;
a744cf53 7095
224c3ddb 7096 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7097 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7098 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7099 {
ea9c271d 7100 struct packet_reg *r = &rsa->regs[i];
a744cf53 7101
b323314b 7102 if (r->in_g_packet)
56be3814 7103 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7104 }
7105 }
c906108c
SS
7106
7107 /* Command describes registers byte by byte,
7108 each byte encoded as two hex characters. */
6d820c5c 7109 p = rs->buf;
193cb69f 7110 *p++ = 'G';
74ca34ce
DJ
7111 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7112 updated. */
7113 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7114 putpkt (rs->buf);
7115 getpkt (&rs->buf, &rs->buf_size, 0);
7116 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7117 error (_("Could not write registers; remote failure reply '%s'"),
7118 rs->buf);
c906108c 7119}
74ca34ce
DJ
7120
7121/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7122 of the register cache buffer. FIXME: ignores errors. */
7123
7124static void
28439f5e
PA
7125remote_store_registers (struct target_ops *ops,
7126 struct regcache *regcache, int regnum)
74ca34ce 7127{
74ca34ce
DJ
7128 struct remote_arch_state *rsa = get_remote_arch_state ();
7129 int i;
7130
e6e4e701 7131 set_remote_traceframe ();
79d7f229 7132 set_general_thread (inferior_ptid);
74ca34ce
DJ
7133
7134 if (regnum >= 0)
7135 {
7136 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7137
74ca34ce
DJ
7138 gdb_assert (reg != NULL);
7139
7140 /* Always prefer to store registers using the 'P' packet if
7141 possible; we often change only a small number of registers.
7142 Sometimes we change a larger number; we'd need help from a
7143 higher layer to know to use 'G'. */
56be3814 7144 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7145 return;
7146
7147 /* For now, don't complain if we have no way to write the
7148 register. GDB loses track of unavailable registers too
7149 easily. Some day, this may be an error. We don't have
0df8b418 7150 any way to read the register, either... */
74ca34ce
DJ
7151 if (!reg->in_g_packet)
7152 return;
7153
56be3814 7154 store_registers_using_G (regcache);
74ca34ce
DJ
7155 return;
7156 }
7157
56be3814 7158 store_registers_using_G (regcache);
74ca34ce 7159
4a22f64d 7160 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7161 if (!rsa->regs[i].in_g_packet)
56be3814 7162 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7163 /* See above for why we do not issue an error here. */
7164 continue;
7165}
c906108c
SS
7166\f
7167
7168/* Return the number of hex digits in num. */
7169
7170static int
fba45db2 7171hexnumlen (ULONGEST num)
c906108c
SS
7172{
7173 int i;
7174
7175 for (i = 0; num != 0; i++)
7176 num >>= 4;
7177
7178 return max (i, 1);
7179}
7180
2df3850c 7181/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7182
7183static int
fba45db2 7184hexnumstr (char *buf, ULONGEST num)
c906108c 7185{
c906108c 7186 int len = hexnumlen (num);
a744cf53 7187
2df3850c
JM
7188 return hexnumnstr (buf, num, len);
7189}
7190
c906108c 7191
2df3850c 7192/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7193
2df3850c 7194static int
fba45db2 7195hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7196{
7197 int i;
7198
7199 buf[width] = '\0';
7200
7201 for (i = width - 1; i >= 0; i--)
c906108c 7202 {
c5aa993b 7203 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7204 num >>= 4;
7205 }
7206
2df3850c 7207 return width;
c906108c
SS
7208}
7209
23860348 7210/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7211
7212static CORE_ADDR
fba45db2 7213remote_address_masked (CORE_ADDR addr)
c906108c 7214{
883b9c6c 7215 unsigned int address_size = remote_address_size;
a744cf53 7216
911c95a5
UW
7217 /* If "remoteaddresssize" was not set, default to target address size. */
7218 if (!address_size)
f5656ead 7219 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7220
7221 if (address_size > 0
7222 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7223 {
7224 /* Only create a mask when that mask can safely be constructed
23860348 7225 in a ULONGEST variable. */
c906108c 7226 ULONGEST mask = 1;
a744cf53 7227
911c95a5 7228 mask = (mask << address_size) - 1;
c906108c
SS
7229 addr &= mask;
7230 }
7231 return addr;
7232}
7233
7234/* Determine whether the remote target supports binary downloading.
7235 This is accomplished by sending a no-op memory write of zero length
7236 to the target at the specified address. It does not suffice to send
23860348
MS
7237 the whole packet, since many stubs strip the eighth bit and
7238 subsequently compute a wrong checksum, which causes real havoc with
7239 remote_write_bytes.
7a292a7a 7240
96baa820 7241 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7242 clean. In cases like this, the user should clear "remote
23860348 7243 X-packet". */
96baa820 7244
c906108c 7245static void
fba45db2 7246check_binary_download (CORE_ADDR addr)
c906108c 7247{
d01949b6 7248 struct remote_state *rs = get_remote_state ();
24b06219 7249
4082afcc 7250 switch (packet_support (PACKET_X))
c906108c 7251 {
96baa820
JM
7252 case PACKET_DISABLE:
7253 break;
7254 case PACKET_ENABLE:
7255 break;
7256 case PACKET_SUPPORT_UNKNOWN:
7257 {
96baa820 7258 char *p;
802188a7 7259
2e9f7625 7260 p = rs->buf;
96baa820
JM
7261 *p++ = 'X';
7262 p += hexnumstr (p, (ULONGEST) addr);
7263 *p++ = ',';
7264 p += hexnumstr (p, (ULONGEST) 0);
7265 *p++ = ':';
7266 *p = '\0';
802188a7 7267
2e9f7625 7268 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7269 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7270
2e9f7625 7271 if (rs->buf[0] == '\0')
96baa820
JM
7272 {
7273 if (remote_debug)
7274 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7275 "binary downloading NOT "
7276 "supported by target\n");
444abaca 7277 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7278 }
7279 else
7280 {
7281 if (remote_debug)
7282 fprintf_unfiltered (gdb_stdlog,
64b9b334 7283 "binary downloading supported by target\n");
444abaca 7284 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7285 }
7286 break;
7287 }
c906108c
SS
7288 }
7289}
7290
124e13d9
SM
7291/* Helper function to resize the payload in order to try to get a good
7292 alignment. We try to write an amount of data such that the next write will
7293 start on an address aligned on REMOTE_ALIGN_WRITES. */
7294
7295static int
7296align_for_efficient_write (int todo, CORE_ADDR memaddr)
7297{
7298 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7299}
7300
c906108c
SS
7301/* Write memory data directly to the remote machine.
7302 This does not inform the data cache; the data cache uses this.
a76d924d 7303 HEADER is the starting part of the packet.
c906108c
SS
7304 MEMADDR is the address in the remote memory space.
7305 MYADDR is the address of the buffer in our space.
124e13d9
SM
7306 LEN_UNITS is the number of addressable units to write.
7307 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7308 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7309 should send data as binary ('X'), or hex-encoded ('M').
7310
7311 The function creates packet of the form
7312 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7313
124e13d9 7314 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7315
7316 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7317 are omitted.
7318
9b409511 7319 Return the transferred status, error or OK (an
124e13d9
SM
7320 'enum target_xfer_status' value). Save the number of addressable units
7321 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7322
7323 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7324 exchange between gdb and the stub could look like (?? in place of the
7325 checksum):
7326
7327 -> $m1000,4#??
7328 <- aaaabbbbccccdddd
7329
7330 -> $M1000,3:eeeeffffeeee#??
7331 <- OK
7332
7333 -> $m1000,4#??
7334 <- eeeeffffeeeedddd */
c906108c 7335
9b409511 7336static enum target_xfer_status
a76d924d 7337remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7338 const gdb_byte *myaddr, ULONGEST len_units,
7339 int unit_size, ULONGEST *xfered_len_units,
7340 char packet_format, int use_length)
c906108c 7341{
6d820c5c 7342 struct remote_state *rs = get_remote_state ();
cfd77fa1 7343 char *p;
a76d924d
DJ
7344 char *plen = NULL;
7345 int plenlen = 0;
124e13d9
SM
7346 int todo_units;
7347 int units_written;
7348 int payload_capacity_bytes;
7349 int payload_length_bytes;
a76d924d
DJ
7350
7351 if (packet_format != 'X' && packet_format != 'M')
7352 internal_error (__FILE__, __LINE__,
9b20d036 7353 _("remote_write_bytes_aux: bad packet format"));
c906108c 7354
124e13d9 7355 if (len_units == 0)
9b409511 7356 return TARGET_XFER_EOF;
b2182ed2 7357
124e13d9 7358 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7359
6d820c5c
DJ
7360 /* The packet buffer will be large enough for the payload;
7361 get_memory_packet_size ensures this. */
a76d924d 7362 rs->buf[0] = '\0';
c906108c 7363
a257b5bb 7364 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7365 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7366
124e13d9 7367 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7368 if (!use_length)
0df8b418 7369 /* The comma won't be used. */
124e13d9
SM
7370 payload_capacity_bytes += 1;
7371 payload_capacity_bytes -= strlen (header);
7372 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7373
a76d924d 7374 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7375
a76d924d
DJ
7376 strcat (rs->buf, header);
7377 p = rs->buf + strlen (header);
7378
7379 /* Compute a best guess of the number of bytes actually transfered. */
7380 if (packet_format == 'X')
c906108c 7381 {
23860348 7382 /* Best guess at number of bytes that will fit. */
124e13d9 7383 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7384 if (use_length)
124e13d9
SM
7385 payload_capacity_bytes -= hexnumlen (todo_units);
7386 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7387 }
7388 else
7389 {
124e13d9
SM
7390 /* Number of bytes that will fit. */
7391 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7392 if (use_length)
124e13d9
SM
7393 payload_capacity_bytes -= hexnumlen (todo_units);
7394 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7395 }
a76d924d 7396
124e13d9 7397 if (todo_units <= 0)
3de11b2e 7398 internal_error (__FILE__, __LINE__,
405f8e94 7399 _("minimum packet size too small to write data"));
802188a7 7400
6765f3e5
DJ
7401 /* If we already need another packet, then try to align the end
7402 of this packet to a useful boundary. */
124e13d9
SM
7403 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7404 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7405
a257b5bb 7406 /* Append "<memaddr>". */
917317f4
JM
7407 memaddr = remote_address_masked (memaddr);
7408 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7409
a76d924d
DJ
7410 if (use_length)
7411 {
7412 /* Append ",". */
7413 *p++ = ',';
802188a7 7414
124e13d9
SM
7415 /* Append the length and retain its location and size. It may need to be
7416 adjusted once the packet body has been created. */
a76d924d 7417 plen = p;
124e13d9 7418 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7419 p += plenlen;
7420 }
a257b5bb
AC
7421
7422 /* Append ":". */
917317f4
JM
7423 *p++ = ':';
7424 *p = '\0';
802188a7 7425
a257b5bb 7426 /* Append the packet body. */
a76d924d 7427 if (packet_format == 'X')
917317f4 7428 {
917317f4
JM
7429 /* Binary mode. Send target system values byte by byte, in
7430 increasing byte addresses. Only escape certain critical
7431 characters. */
124e13d9
SM
7432 payload_length_bytes =
7433 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7434 &units_written, payload_capacity_bytes);
6765f3e5 7435
124e13d9 7436 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7437 a second try to keep the end of the packet aligned. Don't do
7438 this if the packet is tiny. */
124e13d9 7439 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7440 {
124e13d9
SM
7441 int new_todo_units;
7442
7443 new_todo_units = align_for_efficient_write (units_written, memaddr);
7444
7445 if (new_todo_units != units_written)
7446 payload_length_bytes =
7447 remote_escape_output (myaddr, new_todo_units, unit_size,
7448 (gdb_byte *) p, &units_written,
7449 payload_capacity_bytes);
6765f3e5
DJ
7450 }
7451
124e13d9
SM
7452 p += payload_length_bytes;
7453 if (use_length && units_written < todo_units)
c906108c 7454 {
802188a7 7455 /* Escape chars have filled up the buffer prematurely,
124e13d9 7456 and we have actually sent fewer units than planned.
917317f4
JM
7457 Fix-up the length field of the packet. Use the same
7458 number of characters as before. */
124e13d9
SM
7459 plen += hexnumnstr (plen, (ULONGEST) units_written,
7460 plenlen);
917317f4 7461 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7462 }
a76d924d
DJ
7463 }
7464 else
7465 {
917317f4
JM
7466 /* Normal mode: Send target system values byte by byte, in
7467 increasing byte addresses. Each byte is encoded as a two hex
7468 value. */
124e13d9
SM
7469 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7470 units_written = todo_units;
c906108c 7471 }
802188a7 7472
2e9f7625 7473 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7474 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7475
2e9f7625 7476 if (rs->buf[0] == 'E')
00d84524 7477 return TARGET_XFER_E_IO;
802188a7 7478
124e13d9
SM
7479 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7480 send fewer units than we'd planned. */
7481 *xfered_len_units = (ULONGEST) units_written;
9b409511 7482 return TARGET_XFER_OK;
c906108c
SS
7483}
7484
a76d924d
DJ
7485/* Write memory data directly to the remote machine.
7486 This does not inform the data cache; the data cache uses this.
7487 MEMADDR is the address in the remote memory space.
7488 MYADDR is the address of the buffer in our space.
7489 LEN is the number of bytes.
7490
9b409511
YQ
7491 Return the transferred status, error or OK (an
7492 'enum target_xfer_status' value). Save the number of bytes
7493 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7494
9b409511
YQ
7495static enum target_xfer_status
7496remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7497 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7498{
7499 char *packet_format = 0;
7500
7501 /* Check whether the target supports binary download. */
7502 check_binary_download (memaddr);
7503
4082afcc 7504 switch (packet_support (PACKET_X))
a76d924d
DJ
7505 {
7506 case PACKET_ENABLE:
7507 packet_format = "X";
7508 break;
7509 case PACKET_DISABLE:
7510 packet_format = "M";
7511 break;
7512 case PACKET_SUPPORT_UNKNOWN:
7513 internal_error (__FILE__, __LINE__,
7514 _("remote_write_bytes: bad internal state"));
7515 default:
7516 internal_error (__FILE__, __LINE__, _("bad switch"));
7517 }
7518
7519 return remote_write_bytes_aux (packet_format,
124e13d9 7520 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7521 packet_format[0], 1);
a76d924d
DJ
7522}
7523
9217e74e
YQ
7524/* Read memory data directly from the remote machine.
7525 This does not use the data cache; the data cache uses this.
7526 MEMADDR is the address in the remote memory space.
7527 MYADDR is the address of the buffer in our space.
124e13d9
SM
7528 LEN_UNITS is the number of addressable memory units to read..
7529 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7530
7531 Return the transferred status, error or OK (an
7532 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7533 transferred in *XFERED_LEN_UNITS.
7534
7535 See the comment of remote_write_bytes_aux for an example of
7536 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7537
7538static enum target_xfer_status
124e13d9
SM
7539remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7540 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7541{
7542 struct remote_state *rs = get_remote_state ();
124e13d9 7543 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7544 char *p;
124e13d9
SM
7545 int todo_units;
7546 int decoded_bytes;
9217e74e 7547
124e13d9 7548 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7549 /* The packet buffer will be large enough for the payload;
7550 get_memory_packet_size ensures this. */
7551
124e13d9
SM
7552 /* Number of units that will fit. */
7553 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7554
7555 /* Construct "m"<memaddr>","<len>". */
7556 memaddr = remote_address_masked (memaddr);
7557 p = rs->buf;
7558 *p++ = 'm';
7559 p += hexnumstr (p, (ULONGEST) memaddr);
7560 *p++ = ',';
124e13d9 7561 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7562 *p = '\0';
7563 putpkt (rs->buf);
7564 getpkt (&rs->buf, &rs->buf_size, 0);
7565 if (rs->buf[0] == 'E'
7566 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7567 && rs->buf[3] == '\0')
7568 return TARGET_XFER_E_IO;
7569 /* Reply describes memory byte by byte, each byte encoded as two hex
7570 characters. */
7571 p = rs->buf;
124e13d9 7572 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7573 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7574 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7575 return TARGET_XFER_OK;
7576}
7577
b55fbac4
YQ
7578/* Using the set of read-only target sections of remote, read live
7579 read-only memory.
8acf9577
YQ
7580
7581 For interface/parameters/return description see target.h,
7582 to_xfer_partial. */
7583
7584static enum target_xfer_status
b55fbac4
YQ
7585remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7586 ULONGEST memaddr, ULONGEST len,
124e13d9 7587 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7588{
7589 struct target_section *secp;
7590 struct target_section_table *table;
7591
7592 secp = target_section_by_addr (ops, memaddr);
7593 if (secp != NULL
7594 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7595 secp->the_bfd_section)
7596 & SEC_READONLY))
7597 {
7598 struct target_section *p;
7599 ULONGEST memend = memaddr + len;
7600
7601 table = target_get_section_table (ops);
7602
7603 for (p = table->sections; p < table->sections_end; p++)
7604 {
7605 if (memaddr >= p->addr)
7606 {
7607 if (memend <= p->endaddr)
7608 {
7609 /* Entire transfer is within this section. */
124e13d9 7610 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7611 xfered_len);
8acf9577
YQ
7612 }
7613 else if (memaddr >= p->endaddr)
7614 {
7615 /* This section ends before the transfer starts. */
7616 continue;
7617 }
7618 else
7619 {
7620 /* This section overlaps the transfer. Just do half. */
7621 len = p->endaddr - memaddr;
124e13d9 7622 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7623 xfered_len);
8acf9577
YQ
7624 }
7625 }
7626 }
7627 }
7628
7629 return TARGET_XFER_EOF;
7630}
7631
9217e74e
YQ
7632/* Similar to remote_read_bytes_1, but it reads from the remote stub
7633 first if the requested memory is unavailable in traceframe.
7634 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7635
9b409511 7636static enum target_xfer_status
8acf9577 7637remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7638 gdb_byte *myaddr, ULONGEST len, int unit_size,
7639 ULONGEST *xfered_len)
c906108c 7640{
6b6aa828 7641 if (len == 0)
96c4f946 7642 return TARGET_XFER_EOF;
b2182ed2 7643
8acf9577
YQ
7644 if (get_traceframe_number () != -1)
7645 {
7646 VEC(mem_range_s) *available;
7647
7648 /* If we fail to get the set of available memory, then the
7649 target does not support querying traceframe info, and so we
7650 attempt reading from the traceframe anyway (assuming the
7651 target implements the old QTro packet then). */
7652 if (traceframe_available_memory (&available, memaddr, len))
7653 {
7654 struct cleanup *old_chain;
7655
7656 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7657
7658 if (VEC_empty (mem_range_s, available)
7659 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7660 {
7661 enum target_xfer_status res;
7662
7663 /* Don't read into the traceframe's available
7664 memory. */
7665 if (!VEC_empty (mem_range_s, available))
7666 {
7667 LONGEST oldlen = len;
7668
7669 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7670 gdb_assert (len <= oldlen);
7671 }
7672
7673 do_cleanups (old_chain);
7674
7675 /* This goes through the topmost target again. */
b55fbac4 7676 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7677 len, unit_size, xfered_len);
8acf9577
YQ
7678 if (res == TARGET_XFER_OK)
7679 return TARGET_XFER_OK;
7680 else
7681 {
7682 /* No use trying further, we know some memory starting
7683 at MEMADDR isn't available. */
7684 *xfered_len = len;
7685 return TARGET_XFER_UNAVAILABLE;
7686 }
7687 }
7688
7689 /* Don't try to read more than how much is available, in
7690 case the target implements the deprecated QTro packet to
7691 cater for older GDBs (the target's knowledge of read-only
7692 sections may be outdated by now). */
7693 len = VEC_index (mem_range_s, available, 0)->length;
7694
7695 do_cleanups (old_chain);
7696 }
7697 }
7698
124e13d9 7699 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7700}
74531fed 7701
c906108c 7702\f
c906108c 7703
a76d924d
DJ
7704/* Sends a packet with content determined by the printf format string
7705 FORMAT and the remaining arguments, then gets the reply. Returns
7706 whether the packet was a success, a failure, or unknown. */
7707
77b64a49
PA
7708static enum packet_result remote_send_printf (const char *format, ...)
7709 ATTRIBUTE_PRINTF (1, 2);
7710
2c0b251b 7711static enum packet_result
a76d924d
DJ
7712remote_send_printf (const char *format, ...)
7713{
7714 struct remote_state *rs = get_remote_state ();
7715 int max_size = get_remote_packet_size ();
a76d924d 7716 va_list ap;
a744cf53 7717
a76d924d
DJ
7718 va_start (ap, format);
7719
7720 rs->buf[0] = '\0';
7721 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7722 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7723
7724 if (putpkt (rs->buf) < 0)
7725 error (_("Communication problem with target."));
7726
7727 rs->buf[0] = '\0';
7728 getpkt (&rs->buf, &rs->buf_size, 0);
7729
7730 return packet_check_result (rs->buf);
7731}
7732
7733static void
7734restore_remote_timeout (void *p)
7735{
7736 int value = *(int *)p;
a744cf53 7737
a76d924d
DJ
7738 remote_timeout = value;
7739}
7740
7741/* Flash writing can take quite some time. We'll set
7742 effectively infinite timeout for flash operations.
7743 In future, we'll need to decide on a better approach. */
7744static const int remote_flash_timeout = 1000;
7745
7746static void
7747remote_flash_erase (struct target_ops *ops,
7748 ULONGEST address, LONGEST length)
7749{
f5656ead 7750 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7751 int saved_remote_timeout = remote_timeout;
7752 enum packet_result ret;
a76d924d
DJ
7753 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7754 &saved_remote_timeout);
a744cf53 7755
a76d924d
DJ
7756 remote_timeout = remote_flash_timeout;
7757
7758 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7759 phex (address, addr_size),
a76d924d
DJ
7760 phex (length, 4));
7761 switch (ret)
7762 {
7763 case PACKET_UNKNOWN:
7764 error (_("Remote target does not support flash erase"));
7765 case PACKET_ERROR:
7766 error (_("Error erasing flash with vFlashErase packet"));
7767 default:
7768 break;
7769 }
7770
7771 do_cleanups (back_to);
7772}
7773
9b409511
YQ
7774static enum target_xfer_status
7775remote_flash_write (struct target_ops *ops, ULONGEST address,
7776 ULONGEST length, ULONGEST *xfered_len,
7777 const gdb_byte *data)
a76d924d
DJ
7778{
7779 int saved_remote_timeout = remote_timeout;
9b409511 7780 enum target_xfer_status ret;
a76d924d 7781 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7782 &saved_remote_timeout);
a76d924d
DJ
7783
7784 remote_timeout = remote_flash_timeout;
124e13d9 7785 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 7786 xfered_len,'X', 0);
a76d924d
DJ
7787 do_cleanups (back_to);
7788
7789 return ret;
7790}
7791
7792static void
7793remote_flash_done (struct target_ops *ops)
7794{
7795 int saved_remote_timeout = remote_timeout;
7796 int ret;
7797 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7798 &saved_remote_timeout);
7799
7800 remote_timeout = remote_flash_timeout;
7801 ret = remote_send_printf ("vFlashDone");
7802 do_cleanups (back_to);
7803
7804 switch (ret)
7805 {
7806 case PACKET_UNKNOWN:
7807 error (_("Remote target does not support vFlashDone"));
7808 case PACKET_ERROR:
7809 error (_("Error finishing flash operation"));
7810 default:
7811 break;
7812 }
7813}
7814
c906108c 7815static void
fba45db2 7816remote_files_info (struct target_ops *ignore)
c906108c
SS
7817{
7818 puts_filtered ("Debugging a target over a serial line.\n");
7819}
7820\f
7821/* Stuff for dealing with the packets which are part of this protocol.
7822 See comment at top of file for details. */
7823
1927e618
PA
7824/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7825 error to higher layers. Called when a serial error is detected.
7826 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7827 the system error message for errno at function entry and final dot
7828 for output compatibility with throw_perror_with_name. */
1927e618
PA
7829
7830static void
7831unpush_and_perror (const char *string)
7832{
d6cb50a2 7833 int saved_errno = errno;
1927e618
PA
7834
7835 remote_unpush_target ();
d6cb50a2
JK
7836 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7837 safe_strerror (saved_errno));
1927e618
PA
7838}
7839
0876f84a 7840/* Read a single character from the remote end. */
c906108c
SS
7841
7842static int
fba45db2 7843readchar (int timeout)
c906108c
SS
7844{
7845 int ch;
5d93a237 7846 struct remote_state *rs = get_remote_state ();
c906108c 7847
5d93a237 7848 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7849
2acceee2 7850 if (ch >= 0)
0876f84a 7851 return ch;
2acceee2
JM
7852
7853 switch ((enum serial_rc) ch)
c906108c
SS
7854 {
7855 case SERIAL_EOF:
78a095c3 7856 remote_unpush_target ();
598d3636 7857 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7858 /* no return */
c906108c 7859 case SERIAL_ERROR:
1927e618
PA
7860 unpush_and_perror (_("Remote communication error. "
7861 "Target disconnected."));
2acceee2 7862 /* no return */
c906108c 7863 case SERIAL_TIMEOUT:
2acceee2 7864 break;
c906108c 7865 }
2acceee2 7866 return ch;
c906108c
SS
7867}
7868
c33e31fd
PA
7869/* Wrapper for serial_write that closes the target and throws if
7870 writing fails. */
7871
7872static void
7873remote_serial_write (const char *str, int len)
7874{
5d93a237
TT
7875 struct remote_state *rs = get_remote_state ();
7876
7877 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7878 {
1927e618
PA
7879 unpush_and_perror (_("Remote communication error. "
7880 "Target disconnected."));
c33e31fd
PA
7881 }
7882}
7883
6d820c5c
DJ
7884/* Send the command in *BUF to the remote machine, and read the reply
7885 into *BUF. Report an error if we get an error reply. Resize
7886 *BUF using xrealloc if necessary to hold the result, and update
7887 *SIZEOF_BUF. */
c906108c
SS
7888
7889static void
6d820c5c
DJ
7890remote_send (char **buf,
7891 long *sizeof_buf)
c906108c 7892{
6d820c5c 7893 putpkt (*buf);
c2d11a7d 7894 getpkt (buf, sizeof_buf, 0);
c906108c 7895
6d820c5c
DJ
7896 if ((*buf)[0] == 'E')
7897 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7898}
7899
6e5abd65
PA
7900/* Return a pointer to an xmalloc'ed string representing an escaped
7901 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7902 etc. The caller is responsible for releasing the returned
7903 memory. */
7904
7905static char *
7906escape_buffer (const char *buf, int n)
7907{
7908 struct cleanup *old_chain;
7909 struct ui_file *stb;
7910 char *str;
6e5abd65
PA
7911
7912 stb = mem_fileopen ();
7913 old_chain = make_cleanup_ui_file_delete (stb);
7914
6ef284bd 7915 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 7916 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7917 do_cleanups (old_chain);
7918 return str;
7919}
7920
c906108c
SS
7921/* Display a null-terminated packet on stdout, for debugging, using C
7922 string notation. */
7923
7924static void
baa336ce 7925print_packet (const char *buf)
c906108c
SS
7926{
7927 puts_filtered ("\"");
43e526b9 7928 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7929 puts_filtered ("\"");
7930}
7931
7932int
baa336ce 7933putpkt (const char *buf)
c906108c
SS
7934{
7935 return putpkt_binary (buf, strlen (buf));
7936}
7937
7938/* Send a packet to the remote machine, with error checking. The data
23860348 7939 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7940 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7941 and for a possible /0 if we are debugging (remote_debug) and want
7942 to print the sent packet as a string. */
c906108c
SS
7943
7944static int
baa336ce 7945putpkt_binary (const char *buf, int cnt)
c906108c 7946{
2d717e4f 7947 struct remote_state *rs = get_remote_state ();
c906108c
SS
7948 int i;
7949 unsigned char csum = 0;
224c3ddb 7950 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 7951 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 7952
c906108c
SS
7953 int ch;
7954 int tcount = 0;
7955 char *p;
dd61ec5c 7956 char *message;
c906108c 7957
e24a49d8
PA
7958 /* Catch cases like trying to read memory or listing threads while
7959 we're waiting for a stop reply. The remote server wouldn't be
7960 ready to handle this request, so we'd hang and timeout. We don't
7961 have to worry about this in synchronous mode, because in that
7962 case it's not possible to issue a command while the target is
74531fed
PA
7963 running. This is not a problem in non-stop mode, because in that
7964 case, the stub is always ready to process serial input. */
d9d41e78 7965 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
9597b22a
DE
7966 {
7967 error (_("Cannot execute this command while the target is running.\n"
7968 "Use the \"interrupt\" command to stop the target\n"
7969 "and then try again."));
7970 }
e24a49d8 7971
2d717e4f
DJ
7972 /* We're sending out a new packet. Make sure we don't look at a
7973 stale cached response. */
7974 rs->cached_wait_status = 0;
7975
c906108c
SS
7976 /* Copy the packet into buffer BUF2, encapsulating it
7977 and giving it a checksum. */
7978
c906108c
SS
7979 p = buf2;
7980 *p++ = '$';
7981
7982 for (i = 0; i < cnt; i++)
7983 {
7984 csum += buf[i];
7985 *p++ = buf[i];
7986 }
7987 *p++ = '#';
7988 *p++ = tohex ((csum >> 4) & 0xf);
7989 *p++ = tohex (csum & 0xf);
7990
7991 /* Send it over and over until we get a positive ack. */
7992
7993 while (1)
7994 {
7995 int started_error_output = 0;
7996
7997 if (remote_debug)
7998 {
6e5abd65
PA
7999 struct cleanup *old_chain;
8000 char *str;
8001
c906108c 8002 *p = '\0';
6e5abd65
PA
8003 str = escape_buffer (buf2, p - buf2);
8004 old_chain = make_cleanup (xfree, str);
8005 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8006 gdb_flush (gdb_stdlog);
6e5abd65 8007 do_cleanups (old_chain);
c906108c 8008 }
c33e31fd 8009 remote_serial_write (buf2, p - buf2);
c906108c 8010
a6f3e723
SL
8011 /* If this is a no acks version of the remote protocol, send the
8012 packet and move on. */
8013 if (rs->noack_mode)
8014 break;
8015
74531fed
PA
8016 /* Read until either a timeout occurs (-2) or '+' is read.
8017 Handle any notification that arrives in the mean time. */
c906108c
SS
8018 while (1)
8019 {
8020 ch = readchar (remote_timeout);
8021
c5aa993b 8022 if (remote_debug)
c906108c
SS
8023 {
8024 switch (ch)
8025 {
8026 case '+':
1216fa2c 8027 case '-':
c906108c
SS
8028 case SERIAL_TIMEOUT:
8029 case '$':
74531fed 8030 case '%':
c906108c
SS
8031 if (started_error_output)
8032 {
8033 putchar_unfiltered ('\n');
8034 started_error_output = 0;
8035 }
8036 }
8037 }
8038
8039 switch (ch)
8040 {
8041 case '+':
8042 if (remote_debug)
0f71a2f6 8043 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8044 do_cleanups (old_chain);
c906108c 8045 return 1;
1216fa2c
AC
8046 case '-':
8047 if (remote_debug)
8048 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8049 /* FALLTHROUGH */
c906108c 8050 case SERIAL_TIMEOUT:
c5aa993b 8051 tcount++;
c906108c 8052 if (tcount > 3)
a5c0808e
PA
8053 {
8054 do_cleanups (old_chain);
8055 return 0;
8056 }
23860348 8057 break; /* Retransmit buffer. */
c906108c
SS
8058 case '$':
8059 {
40e3f985 8060 if (remote_debug)
2bc416ba 8061 fprintf_unfiltered (gdb_stdlog,
23860348 8062 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8063 /* It's probably an old response sent because an ACK
8064 was lost. Gobble up the packet and ack it so it
8065 doesn't get retransmitted when we resend this
8066 packet. */
6d820c5c 8067 skip_frame ();
c33e31fd 8068 remote_serial_write ("+", 1);
23860348 8069 continue; /* Now, go look for +. */
c906108c 8070 }
74531fed
PA
8071
8072 case '%':
8073 {
8074 int val;
8075
8076 /* If we got a notification, handle it, and go back to looking
8077 for an ack. */
8078 /* We've found the start of a notification. Now
8079 collect the data. */
8080 val = read_frame (&rs->buf, &rs->buf_size);
8081 if (val >= 0)
8082 {
8083 if (remote_debug)
8084 {
6e5abd65
PA
8085 struct cleanup *old_chain;
8086 char *str;
8087
8088 str = escape_buffer (rs->buf, val);
8089 old_chain = make_cleanup (xfree, str);
8090 fprintf_unfiltered (gdb_stdlog,
8091 " Notification received: %s\n",
8092 str);
8093 do_cleanups (old_chain);
74531fed 8094 }
5965e028 8095 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8096 /* We're in sync now, rewait for the ack. */
8097 tcount = 0;
8098 }
8099 else
8100 {
8101 if (remote_debug)
8102 {
8103 if (!started_error_output)
8104 {
8105 started_error_output = 1;
8106 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8107 }
8108 fputc_unfiltered (ch & 0177, gdb_stdlog);
8109 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8110 }
8111 }
8112 continue;
8113 }
8114 /* fall-through */
c906108c
SS
8115 default:
8116 if (remote_debug)
8117 {
8118 if (!started_error_output)
8119 {
8120 started_error_output = 1;
0f71a2f6 8121 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8122 }
0f71a2f6 8123 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8124 }
8125 continue;
8126 }
23860348 8127 break; /* Here to retransmit. */
c906108c
SS
8128 }
8129
8130#if 0
8131 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8132 able to get out next time we call QUIT, without anything as
8133 violent as interrupt_query. If we want to provide a way out of
8134 here without getting to the next QUIT, it should be based on
8135 hitting ^C twice as in remote_wait. */
c906108c
SS
8136 if (quit_flag)
8137 {
8138 quit_flag = 0;
8139 interrupt_query ();
8140 }
8141#endif
8142 }
a5c0808e
PA
8143
8144 do_cleanups (old_chain);
a6f3e723 8145 return 0;
c906108c
SS
8146}
8147
6d820c5c
DJ
8148/* Come here after finding the start of a frame when we expected an
8149 ack. Do our best to discard the rest of this packet. */
8150
8151static void
8152skip_frame (void)
8153{
8154 int c;
8155
8156 while (1)
8157 {
8158 c = readchar (remote_timeout);
8159 switch (c)
8160 {
8161 case SERIAL_TIMEOUT:
8162 /* Nothing we can do. */
8163 return;
8164 case '#':
8165 /* Discard the two bytes of checksum and stop. */
8166 c = readchar (remote_timeout);
8167 if (c >= 0)
8168 c = readchar (remote_timeout);
8169
8170 return;
8171 case '*': /* Run length encoding. */
8172 /* Discard the repeat count. */
8173 c = readchar (remote_timeout);
8174 if (c < 0)
8175 return;
8176 break;
8177 default:
8178 /* A regular character. */
8179 break;
8180 }
8181 }
8182}
8183
c906108c 8184/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8185 into *BUF, verifying the checksum, length, and handling run-length
8186 compression. NUL terminate the buffer. If there is not enough room,
8187 expand *BUF using xrealloc.
c906108c 8188
c2d11a7d
JM
8189 Returns -1 on error, number of characters in buffer (ignoring the
8190 trailing NULL) on success. (could be extended to return one of the
23860348 8191 SERIAL status indications). */
c2d11a7d
JM
8192
8193static long
6d820c5c
DJ
8194read_frame (char **buf_p,
8195 long *sizeof_buf)
c906108c
SS
8196{
8197 unsigned char csum;
c2d11a7d 8198 long bc;
c906108c 8199 int c;
6d820c5c 8200 char *buf = *buf_p;
a6f3e723 8201 struct remote_state *rs = get_remote_state ();
c906108c
SS
8202
8203 csum = 0;
c2d11a7d 8204 bc = 0;
c906108c
SS
8205
8206 while (1)
8207 {
8208 c = readchar (remote_timeout);
c906108c
SS
8209 switch (c)
8210 {
8211 case SERIAL_TIMEOUT:
8212 if (remote_debug)
0f71a2f6 8213 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8214 return -1;
c906108c
SS
8215 case '$':
8216 if (remote_debug)
0f71a2f6
JM
8217 fputs_filtered ("Saw new packet start in middle of old one\n",
8218 gdb_stdlog);
23860348 8219 return -1; /* Start a new packet, count retries. */
c906108c
SS
8220 case '#':
8221 {
8222 unsigned char pktcsum;
e1b09194
AC
8223 int check_0 = 0;
8224 int check_1 = 0;
c906108c 8225
c2d11a7d 8226 buf[bc] = '\0';
c906108c 8227
e1b09194
AC
8228 check_0 = readchar (remote_timeout);
8229 if (check_0 >= 0)
8230 check_1 = readchar (remote_timeout);
802188a7 8231
e1b09194
AC
8232 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8233 {
8234 if (remote_debug)
2bc416ba 8235 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8236 gdb_stdlog);
e1b09194
AC
8237 return -1;
8238 }
8239 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8240 {
8241 if (remote_debug)
2bc416ba 8242 fputs_filtered ("Communication error in checksum\n",
23860348 8243 gdb_stdlog);
40e3f985
FN
8244 return -1;
8245 }
c906108c 8246
a6f3e723
SL
8247 /* Don't recompute the checksum; with no ack packets we
8248 don't have any way to indicate a packet retransmission
8249 is necessary. */
8250 if (rs->noack_mode)
8251 return bc;
8252
e1b09194 8253 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8254 if (csum == pktcsum)
c2d11a7d 8255 return bc;
c906108c 8256
c5aa993b 8257 if (remote_debug)
c906108c 8258 {
6e5abd65
PA
8259 struct cleanup *old_chain;
8260 char *str;
8261
8262 str = escape_buffer (buf, bc);
8263 old_chain = make_cleanup (xfree, str);
8264 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8265 "Bad checksum, sentsum=0x%x, "
8266 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8267 pktcsum, csum, str);
8268 do_cleanups (old_chain);
c906108c 8269 }
c2d11a7d 8270 /* Number of characters in buffer ignoring trailing
23860348 8271 NULL. */
c2d11a7d 8272 return -1;
c906108c 8273 }
23860348 8274 case '*': /* Run length encoding. */
c2c6d25f
JM
8275 {
8276 int repeat;
c906108c 8277
a744cf53 8278 csum += c;
b4501125
AC
8279 c = readchar (remote_timeout);
8280 csum += c;
23860348 8281 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8282
23860348 8283 /* The character before ``*'' is repeated. */
c2d11a7d 8284
6d820c5c 8285 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8286 {
6d820c5c
DJ
8287 if (bc + repeat - 1 >= *sizeof_buf - 1)
8288 {
8289 /* Make some more room in the buffer. */
8290 *sizeof_buf += repeat;
224c3ddb 8291 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
8292 buf = *buf_p;
8293 }
8294
c2d11a7d
JM
8295 memset (&buf[bc], buf[bc - 1], repeat);
8296 bc += repeat;
c2c6d25f
JM
8297 continue;
8298 }
8299
c2d11a7d 8300 buf[bc] = '\0';
6d820c5c 8301 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8302 return -1;
c2c6d25f 8303 }
c906108c 8304 default:
6d820c5c 8305 if (bc >= *sizeof_buf - 1)
c906108c 8306 {
6d820c5c
DJ
8307 /* Make some more room in the buffer. */
8308 *sizeof_buf *= 2;
224c3ddb 8309 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 8310 buf = *buf_p;
c906108c
SS
8311 }
8312
6d820c5c
DJ
8313 buf[bc++] = c;
8314 csum += c;
8315 continue;
c906108c
SS
8316 }
8317 }
8318}
8319
8320/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8321 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8322 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8323 rather than timing out; this is used (in synchronous mode) to wait
8324 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8325/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8326 don't have to change all the calls to getpkt to deal with the
8327 return value, because at the moment I don't know what the right
23860348 8328 thing to do it for those. */
c906108c 8329void
6d820c5c
DJ
8330getpkt (char **buf,
8331 long *sizeof_buf,
c2d11a7d 8332 int forever)
d9fcf2fb
JM
8333{
8334 int timed_out;
8335
8336 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8337}
8338
8339
8340/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8341 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8342 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8343 rather than timing out; this is used (in synchronous mode) to wait
8344 for a target that is is executing user code to stop. If FOREVER ==
8345 0, this function is allowed to time out gracefully and return an
74531fed
PA
8346 indication of this to the caller. Otherwise return the number of
8347 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8348 enough reason to return to the caller. *IS_NOTIF is an output
8349 boolean that indicates whether *BUF holds a notification or not
8350 (a regular packet). */
74531fed 8351
3172dc30 8352static int
74531fed 8353getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8354 int expecting_notif, int *is_notif)
c906108c 8355{
2d717e4f 8356 struct remote_state *rs = get_remote_state ();
c906108c
SS
8357 int c;
8358 int tries;
8359 int timeout;
df4b58fe 8360 int val = -1;
c906108c 8361
2d717e4f
DJ
8362 /* We're reading a new response. Make sure we don't look at a
8363 previously cached response. */
8364 rs->cached_wait_status = 0;
8365
6d820c5c 8366 strcpy (*buf, "timeout");
c906108c
SS
8367
8368 if (forever)
74531fed
PA
8369 timeout = watchdog > 0 ? watchdog : -1;
8370 else if (expecting_notif)
8371 timeout = 0; /* There should already be a char in the buffer. If
8372 not, bail out. */
c906108c
SS
8373 else
8374 timeout = remote_timeout;
8375
8376#define MAX_TRIES 3
8377
74531fed
PA
8378 /* Process any number of notifications, and then return when
8379 we get a packet. */
8380 for (;;)
c906108c 8381 {
d9c43928 8382 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8383 times. */
8384 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8385 {
74531fed
PA
8386 /* This can loop forever if the remote side sends us
8387 characters continuously, but if it pauses, we'll get
8388 SERIAL_TIMEOUT from readchar because of timeout. Then
8389 we'll count that as a retry.
8390
8391 Note that even when forever is set, we will only wait
8392 forever prior to the start of a packet. After that, we
8393 expect characters to arrive at a brisk pace. They should
8394 show up within remote_timeout intervals. */
8395 do
8396 c = readchar (timeout);
8397 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8398
8399 if (c == SERIAL_TIMEOUT)
8400 {
74531fed
PA
8401 if (expecting_notif)
8402 return -1; /* Don't complain, it's normal to not get
8403 anything in this case. */
8404
23860348 8405 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8406 {
2acceee2 8407 QUIT;
78a095c3 8408 remote_unpush_target ();
598d3636
JK
8409 throw_error (TARGET_CLOSE_ERROR,
8410 _("Watchdog timeout has expired. "
8411 "Target detached."));
c906108c 8412 }
c906108c 8413 if (remote_debug)
0f71a2f6 8414 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8415 }
74531fed
PA
8416 else
8417 {
8418 /* We've found the start of a packet or notification.
8419 Now collect the data. */
8420 val = read_frame (buf, sizeof_buf);
8421 if (val >= 0)
8422 break;
8423 }
8424
c33e31fd 8425 remote_serial_write ("-", 1);
c906108c 8426 }
c906108c 8427
74531fed
PA
8428 if (tries > MAX_TRIES)
8429 {
8430 /* We have tried hard enough, and just can't receive the
8431 packet/notification. Give up. */
8432 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8433
74531fed
PA
8434 /* Skip the ack char if we're in no-ack mode. */
8435 if (!rs->noack_mode)
c33e31fd 8436 remote_serial_write ("+", 1);
74531fed
PA
8437 return -1;
8438 }
c906108c 8439
74531fed
PA
8440 /* If we got an ordinary packet, return that to our caller. */
8441 if (c == '$')
c906108c
SS
8442 {
8443 if (remote_debug)
43e526b9 8444 {
6e5abd65
PA
8445 struct cleanup *old_chain;
8446 char *str;
8447
8448 str = escape_buffer (*buf, val);
8449 old_chain = make_cleanup (xfree, str);
8450 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8451 do_cleanups (old_chain);
43e526b9 8452 }
a6f3e723
SL
8453
8454 /* Skip the ack char if we're in no-ack mode. */
8455 if (!rs->noack_mode)
c33e31fd 8456 remote_serial_write ("+", 1);
fee9eda9
YQ
8457 if (is_notif != NULL)
8458 *is_notif = 0;
0876f84a 8459 return val;
c906108c
SS
8460 }
8461
74531fed
PA
8462 /* If we got a notification, handle it, and go back to looking
8463 for a packet. */
8464 else
8465 {
8466 gdb_assert (c == '%');
8467
8468 if (remote_debug)
8469 {
6e5abd65
PA
8470 struct cleanup *old_chain;
8471 char *str;
8472
8473 str = escape_buffer (*buf, val);
8474 old_chain = make_cleanup (xfree, str);
8475 fprintf_unfiltered (gdb_stdlog,
8476 " Notification received: %s\n",
8477 str);
8478 do_cleanups (old_chain);
74531fed 8479 }
fee9eda9
YQ
8480 if (is_notif != NULL)
8481 *is_notif = 1;
c906108c 8482
5965e028 8483 handle_notification (rs->notif_state, *buf);
c906108c 8484
74531fed 8485 /* Notifications require no acknowledgement. */
a6f3e723 8486
74531fed 8487 if (expecting_notif)
fee9eda9 8488 return val;
74531fed
PA
8489 }
8490 }
8491}
8492
8493static int
8494getpkt_sane (char **buf, long *sizeof_buf, int forever)
8495{
fee9eda9 8496 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8497}
8498
8499static int
fee9eda9
YQ
8500getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8501 int *is_notif)
74531fed 8502{
fee9eda9
YQ
8503 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8504 is_notif);
c906108c 8505}
74531fed 8506
cbb8991c
DB
8507/* Check whether EVENT is a fork event for the process specified
8508 by the pid passed in DATA, and if it is, kill the fork child. */
8509
8510static int
8511kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8512 QUEUE_ITER (stop_reply_p) *iter,
8513 stop_reply_p event,
8514 void *data)
8515{
19ba03f4 8516 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
8517 int parent_pid = *(int *) param->input;
8518
8519 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8520 {
8521 struct remote_state *rs = get_remote_state ();
8522 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8523 int res;
8524
8525 res = remote_vkill (child_pid, rs);
8526 if (res != 0)
8527 error (_("Can't kill fork child process %d"), child_pid);
8528 }
8529
8530 return 1;
8531}
8532
8533/* Kill any new fork children of process PID that haven't been
8534 processed by follow_fork. */
8535
8536static void
8537kill_new_fork_children (int pid, struct remote_state *rs)
8538{
8539 struct thread_info *thread;
8540 struct notif_client *notif = &notif_client_stop;
8541 struct queue_iter_param param;
8542
8543 /* Kill the fork child threads of any threads in process PID
8544 that are stopped at a fork event. */
8545 ALL_NON_EXITED_THREADS (thread)
8546 {
8547 struct target_waitstatus *ws = &thread->pending_follow;
8548
8549 if (is_pending_fork_parent (ws, pid, thread->ptid))
8550 {
8551 struct remote_state *rs = get_remote_state ();
8552 int child_pid = ptid_get_pid (ws->value.related_pid);
8553 int res;
8554
8555 res = remote_vkill (child_pid, rs);
8556 if (res != 0)
8557 error (_("Can't kill fork child process %d"), child_pid);
8558 }
8559 }
8560
8561 /* Check for any pending fork events (not reported or processed yet)
8562 in process PID and kill those fork child threads as well. */
8563 remote_notif_get_pending_events (notif);
8564 param.input = &pid;
8565 param.output = NULL;
8566 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8567 kill_child_of_pending_fork, &param);
8568}
8569
c906108c
SS
8570\f
8571static void
7d85a9c0 8572remote_kill (struct target_ops *ops)
43ff13b4 8573{
0fdf84ca
PA
8574
8575 /* Catch errors so the user can quit from gdb even when we
23860348 8576 aren't on speaking terms with the remote system. */
492d29ea 8577 TRY
0fdf84ca
PA
8578 {
8579 putpkt ("k");
8580 }
492d29ea 8581 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
8582 {
8583 if (ex.error == TARGET_CLOSE_ERROR)
8584 {
8585 /* If we got an (EOF) error that caused the target
8586 to go away, then we're done, that's what we wanted.
8587 "k" is susceptible to cause a premature EOF, given
8588 that the remote server isn't actually required to
8589 reply to "k", and it can happen that it doesn't
8590 even get to reply ACK to the "k". */
8591 return;
8592 }
8593
8594 /* Otherwise, something went wrong. We didn't actually kill
8595 the target. Just propagate the exception, and let the
8596 user or higher layers decide what to do. */
8597 throw_exception (ex);
8598 }
492d29ea 8599 END_CATCH
43ff13b4 8600
0fdf84ca
PA
8601 /* We've killed the remote end, we get to mourn it. Since this is
8602 target remote, single-process, mourning the inferior also
8603 unpushes remote_ops. */
43ff13b4
JM
8604 target_mourn_inferior ();
8605}
8606
82f73884
PA
8607static int
8608remote_vkill (int pid, struct remote_state *rs)
8609{
4082afcc 8610 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8611 return -1;
8612
8613 /* Tell the remote target to detach. */
bba74b36 8614 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8615 putpkt (rs->buf);
8616 getpkt (&rs->buf, &rs->buf_size, 0);
8617
4082afcc
PA
8618 switch (packet_ok (rs->buf,
8619 &remote_protocol_packets[PACKET_vKill]))
8620 {
8621 case PACKET_OK:
8622 return 0;
8623 case PACKET_ERROR:
8624 return 1;
8625 case PACKET_UNKNOWN:
8626 return -1;
8627 default:
8628 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8629 }
82f73884
PA
8630}
8631
8632static void
7d85a9c0 8633extended_remote_kill (struct target_ops *ops)
82f73884
PA
8634{
8635 int res;
8636 int pid = ptid_get_pid (inferior_ptid);
8637 struct remote_state *rs = get_remote_state ();
8638
cbb8991c
DB
8639 /* If we're stopped while forking and we haven't followed yet, kill the
8640 child task. We need to do this before killing the parent task
8641 because if this is a vfork then the parent will be sleeping. */
8642 kill_new_fork_children (pid, rs);
8643
82f73884 8644 res = remote_vkill (pid, rs);
901f9912 8645 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
8646 {
8647 /* Don't try 'k' on a multi-process aware stub -- it has no way
8648 to specify the pid. */
8649
8650 putpkt ("k");
8651#if 0
8652 getpkt (&rs->buf, &rs->buf_size, 0);
8653 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8654 res = 1;
8655#else
8656 /* Don't wait for it to die. I'm not really sure it matters whether
8657 we do or not. For the existing stubs, kill is a noop. */
8658 res = 0;
8659#endif
8660 }
8661
8662 if (res != 0)
8663 error (_("Can't kill process"));
8664
82f73884
PA
8665 target_mourn_inferior ();
8666}
8667
c906108c 8668static void
20f796c9 8669remote_mourn (struct target_ops *target)
c906108c
SS
8670{
8671 unpush_target (target);
ce5ce7ed 8672
8a2492ee
PA
8673 /* remote_close takes care of doing most of the clean up. */
8674 generic_mourn_inferior ();
c906108c
SS
8675}
8676
2d717e4f 8677static void
20f796c9 8678extended_remote_mourn (struct target_ops *target)
2d717e4f
DJ
8679{
8680 struct remote_state *rs = get_remote_state ();
c906108c 8681
e24a49d8
PA
8682 /* In case we got here due to an error, but we're going to stay
8683 connected. */
8684 rs->waiting_for_stop_reply = 0;
8685
dc1981d7
PA
8686 /* If the current general thread belonged to the process we just
8687 detached from or has exited, the remote side current general
8688 thread becomes undefined. Considering a case like this:
8689
8690 - We just got here due to a detach.
8691 - The process that we're detaching from happens to immediately
8692 report a global breakpoint being hit in non-stop mode, in the
8693 same thread we had selected before.
8694 - GDB attaches to this process again.
8695 - This event happens to be the next event we handle.
8696
8697 GDB would consider that the current general thread didn't need to
8698 be set on the stub side (with Hg), since for all it knew,
8699 GENERAL_THREAD hadn't changed.
8700
8701 Notice that although in all-stop mode, the remote server always
8702 sets the current thread to the thread reporting the stop event,
8703 that doesn't happen in non-stop mode; in non-stop, the stub *must
8704 not* change the current thread when reporting a breakpoint hit,
8705 due to the decoupling of event reporting and event handling.
8706
8707 To keep things simple, we always invalidate our notion of the
8708 current thread. */
47f8a51d 8709 record_currthread (rs, minus_one_ptid);
dc1981d7 8710
2d717e4f
DJ
8711 /* Unlike "target remote", we do not want to unpush the target; then
8712 the next time the user says "run", we won't be connected. */
8713
48aa3c27
PA
8714 /* Call common code to mark the inferior as not running. */
8715 generic_mourn_inferior ();
8716
d729566a 8717 if (!have_inferiors ())
2d717e4f 8718 {
82f73884
PA
8719 if (!remote_multi_process_p (rs))
8720 {
8721 /* Check whether the target is running now - some remote stubs
8722 automatically restart after kill. */
8723 putpkt ("?");
8724 getpkt (&rs->buf, &rs->buf_size, 0);
8725
8726 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8727 {
3e43a32a
MS
8728 /* Assume that the target has been restarted. Set
8729 inferior_ptid so that bits of core GDB realizes
8730 there's something here, e.g., so that the user can
8731 say "kill" again. */
82f73884
PA
8732 inferior_ptid = magic_null_ptid;
8733 }
82f73884 8734 }
2d717e4f
DJ
8735 }
8736}
c906108c 8737
03583c20 8738static int
2bfc0540 8739extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8740{
4082afcc 8741 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8742}
8743
8744static void
8745extended_remote_disable_randomization (int val)
8746{
8747 struct remote_state *rs = get_remote_state ();
8748 char *reply;
8749
bba74b36
YQ
8750 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8751 val);
03583c20
UW
8752 putpkt (rs->buf);
8753 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8754 if (*reply == '\0')
8755 error (_("Target does not support QDisableRandomization."));
8756 if (strcmp (reply, "OK") != 0)
8757 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8758}
8759
2d717e4f
DJ
8760static int
8761extended_remote_run (char *args)
8762{
8763 struct remote_state *rs = get_remote_state ();
2d717e4f 8764 int len;
94585166 8765 const char *remote_exec_file = get_remote_exec_file ();
c906108c 8766
2d717e4f
DJ
8767 /* If the user has disabled vRun support, or we have detected that
8768 support is not available, do not try it. */
4082afcc 8769 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8770 return -1;
424163ea 8771
2d717e4f
DJ
8772 strcpy (rs->buf, "vRun;");
8773 len = strlen (rs->buf);
c906108c 8774
2d717e4f
DJ
8775 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8776 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8777 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8778 strlen (remote_exec_file));
2d717e4f 8779
d1a41061 8780 gdb_assert (args != NULL);
2d717e4f
DJ
8781 if (*args)
8782 {
8783 struct cleanup *back_to;
8784 int i;
8785 char **argv;
8786
d1a41061 8787 argv = gdb_buildargv (args);
6e366df1 8788 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
8789 for (i = 0; argv[i] != NULL; i++)
8790 {
8791 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8792 error (_("Argument list too long for run packet"));
8793 rs->buf[len++] = ';';
9f1b45b0
TT
8794 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8795 strlen (argv[i]));
2d717e4f
DJ
8796 }
8797 do_cleanups (back_to);
8798 }
8799
8800 rs->buf[len++] = '\0';
8801
8802 putpkt (rs->buf);
8803 getpkt (&rs->buf, &rs->buf_size, 0);
8804
4082afcc 8805 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 8806 {
4082afcc 8807 case PACKET_OK:
3405876a 8808 /* We have a wait response. All is well. */
2d717e4f 8809 return 0;
4082afcc
PA
8810 case PACKET_UNKNOWN:
8811 return -1;
8812 case PACKET_ERROR:
2d717e4f
DJ
8813 if (remote_exec_file[0] == '\0')
8814 error (_("Running the default executable on the remote target failed; "
8815 "try \"set remote exec-file\"?"));
8816 else
8817 error (_("Running \"%s\" on the remote target failed"),
8818 remote_exec_file);
4082afcc
PA
8819 default:
8820 gdb_assert_not_reached (_("bad switch"));
2d717e4f 8821 }
c906108c
SS
8822}
8823
2d717e4f
DJ
8824/* In the extended protocol we want to be able to do things like
8825 "run" and have them basically work as expected. So we need
8826 a special create_inferior function. We support changing the
8827 executable file and the command line arguments, but not the
8828 environment. */
8829
43ff13b4 8830static void
77a19445
TT
8831extended_remote_create_inferior (struct target_ops *ops,
8832 char *exec_file, char *args,
8833 char **env, int from_tty)
43ff13b4 8834{
3405876a
PA
8835 int run_worked;
8836 char *stop_reply;
8837 struct remote_state *rs = get_remote_state ();
94585166 8838 const char *remote_exec_file = get_remote_exec_file ();
3405876a 8839
43ff13b4 8840 /* If running asynchronously, register the target file descriptor
23860348 8841 with the event loop. */
75c99385 8842 if (target_can_async_p ())
6a3753b3 8843 target_async (1);
43ff13b4 8844
03583c20 8845 /* Disable address space randomization if requested (and supported). */
2bfc0540 8846 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
8847 extended_remote_disable_randomization (disable_randomization);
8848
43ff13b4 8849 /* Now restart the remote server. */
3405876a
PA
8850 run_worked = extended_remote_run (args) != -1;
8851 if (!run_worked)
2d717e4f
DJ
8852 {
8853 /* vRun was not supported. Fail if we need it to do what the
8854 user requested. */
8855 if (remote_exec_file[0])
8856 error (_("Remote target does not support \"set remote exec-file\""));
8857 if (args[0])
8858 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 8859
2d717e4f
DJ
8860 /* Fall back to "R". */
8861 extended_remote_restart ();
8862 }
424163ea 8863
6c95b8df
PA
8864 if (!have_inferiors ())
8865 {
8866 /* Clean up from the last time we ran, before we mark the target
8867 running again. This will mark breakpoints uninserted, and
8868 get_offsets may insert breakpoints. */
8869 init_thread_list ();
8870 init_wait_for_inferior ();
8871 }
45280a52 8872
3405876a
PA
8873 /* vRun's success return is a stop reply. */
8874 stop_reply = run_worked ? rs->buf : NULL;
8875 add_current_inferior_and_thread (stop_reply);
c0a2216e 8876
2d717e4f
DJ
8877 /* Get updated offsets, if the stub uses qOffsets. */
8878 get_offsets ();
2d717e4f 8879}
c906108c 8880\f
c5aa993b 8881
b775012e
LM
8882/* Given a location's target info BP_TGT and the packet buffer BUF, output
8883 the list of conditions (in agent expression bytecode format), if any, the
8884 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8885 started from BUF and ended at BUF_END. */
b775012e
LM
8886
8887static int
8888remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8889 struct bp_target_info *bp_tgt, char *buf,
8890 char *buf_end)
b775012e
LM
8891{
8892 struct agent_expr *aexpr = NULL;
8893 int i, ix;
8894 char *pkt;
8895 char *buf_start = buf;
8896
8897 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8898 return 0;
8899
8900 buf += strlen (buf);
bba74b36 8901 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8902 buf++;
8903
8904 /* Send conditions to the target and free the vector. */
8905 for (ix = 0;
8906 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8907 ix++)
8908 {
bba74b36 8909 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8910 buf += strlen (buf);
8911 for (i = 0; i < aexpr->len; ++i)
8912 buf = pack_hex_byte (buf, aexpr->buf[i]);
8913 *buf = '\0';
8914 }
b775012e
LM
8915 return 0;
8916}
8917
d3ce09f5
SS
8918static void
8919remote_add_target_side_commands (struct gdbarch *gdbarch,
8920 struct bp_target_info *bp_tgt, char *buf)
8921{
8922 struct agent_expr *aexpr = NULL;
8923 int i, ix;
8924
8925 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8926 return;
8927
8928 buf += strlen (buf);
8929
8930 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8931 buf += strlen (buf);
8932
8933 /* Concatenate all the agent expressions that are commands into the
8934 cmds parameter. */
8935 for (ix = 0;
8936 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8937 ix++)
8938 {
8939 sprintf (buf, "X%x,", aexpr->len);
8940 buf += strlen (buf);
8941 for (i = 0; i < aexpr->len; ++i)
8942 buf = pack_hex_byte (buf, aexpr->buf[i]);
8943 *buf = '\0';
8944 }
d3ce09f5
SS
8945}
8946
8181d85f
DJ
8947/* Insert a breakpoint. On targets that have software breakpoint
8948 support, we ask the remote target to do the work; on targets
8949 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8950
8951static int
3db08215
MM
8952remote_insert_breakpoint (struct target_ops *ops,
8953 struct gdbarch *gdbarch,
a6d9a66e 8954 struct bp_target_info *bp_tgt)
c906108c 8955{
d471ea57
AC
8956 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8957 If it succeeds, then set the support to PACKET_ENABLE. If it
8958 fails, and the user has explicitly requested the Z support then
23860348 8959 report an error, otherwise, mark it disabled and go on. */
802188a7 8960
4082afcc 8961 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8962 {
0d5ed153 8963 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8964 struct remote_state *rs;
bba74b36 8965 char *p, *endbuf;
7c0f6dcc 8966 int bpsize;
b775012e 8967 struct condition_list *cond = NULL;
4fff2411 8968
28439a30
PA
8969 /* Make sure the remote is pointing at the right process, if
8970 necessary. */
8971 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8972 set_general_process ();
8973
a1dcb23a 8974 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8975
8976 rs = get_remote_state ();
8977 p = rs->buf;
bba74b36 8978 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8979
96baa820
JM
8980 *(p++) = 'Z';
8981 *(p++) = '0';
8982 *(p++) = ',';
7c0f6dcc 8983 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8984 p += hexnumstr (p, addr);
bba74b36 8985 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8986
efcc2da7 8987 if (remote_supports_cond_breakpoints (ops))
bba74b36 8988 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8989
78eff0ec 8990 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8991 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8992
6d820c5c
DJ
8993 putpkt (rs->buf);
8994 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8995
6d820c5c 8996 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8997 {
d471ea57
AC
8998 case PACKET_ERROR:
8999 return -1;
9000 case PACKET_OK:
7c0f6dcc
JL
9001 bp_tgt->placed_address = addr;
9002 bp_tgt->placed_size = bpsize;
d471ea57
AC
9003 return 0;
9004 case PACKET_UNKNOWN:
9005 break;
96baa820
JM
9006 }
9007 }
c906108c 9008
0000e5cc
PA
9009 /* If this breakpoint has target-side commands but this stub doesn't
9010 support Z0 packets, throw error. */
9011 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9012 throw_error (NOT_SUPPORTED_ERROR, _("\
9013Target doesn't support breakpoints that have target side commands."));
9014
3db08215 9015 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9016}
9017
9018static int
3db08215
MM
9019remote_remove_breakpoint (struct target_ops *ops,
9020 struct gdbarch *gdbarch,
a6d9a66e 9021 struct bp_target_info *bp_tgt)
c906108c 9022{
8181d85f 9023 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9024 struct remote_state *rs = get_remote_state ();
96baa820 9025
4082afcc 9026 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9027 {
6d820c5c 9028 char *p = rs->buf;
bba74b36 9029 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9030
28439a30
PA
9031 /* Make sure the remote is pointing at the right process, if
9032 necessary. */
9033 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9034 set_general_process ();
9035
96baa820
JM
9036 *(p++) = 'z';
9037 *(p++) = '0';
9038 *(p++) = ',';
9039
8181d85f
DJ
9040 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9041 p += hexnumstr (p, addr);
bba74b36 9042 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9043
6d820c5c
DJ
9044 putpkt (rs->buf);
9045 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9046
6d820c5c 9047 return (rs->buf[0] == 'E');
96baa820
JM
9048 }
9049
3db08215 9050 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9051}
9052
f486487f 9053static enum Z_packet_type
d471ea57
AC
9054watchpoint_to_Z_packet (int type)
9055{
9056 switch (type)
9057 {
9058 case hw_write:
bb858e6a 9059 return Z_PACKET_WRITE_WP;
d471ea57
AC
9060 break;
9061 case hw_read:
bb858e6a 9062 return Z_PACKET_READ_WP;
d471ea57
AC
9063 break;
9064 case hw_access:
bb858e6a 9065 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9066 break;
9067 default:
8e65ff28 9068 internal_error (__FILE__, __LINE__,
e2e0b3e5 9069 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9070 }
9071}
9072
3c3bea1c 9073static int
f486487f
SM
9074remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9075 enum target_hw_bp_type type, struct expression *cond)
96baa820 9076{
d01949b6 9077 struct remote_state *rs = get_remote_state ();
bba74b36 9078 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9079 char *p;
d471ea57 9080 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9081
4082afcc 9082 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9083 return 1;
802188a7 9084
28439a30
PA
9085 /* Make sure the remote is pointing at the right process, if
9086 necessary. */
9087 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9088 set_general_process ();
9089
bba74b36 9090 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9091 p = strchr (rs->buf, '\0');
96baa820
JM
9092 addr = remote_address_masked (addr);
9093 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9094 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9095
6d820c5c
DJ
9096 putpkt (rs->buf);
9097 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9098
6d820c5c 9099 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9100 {
9101 case PACKET_ERROR:
d471ea57 9102 return -1;
85d721b8
PA
9103 case PACKET_UNKNOWN:
9104 return 1;
d471ea57
AC
9105 case PACKET_OK:
9106 return 0;
9107 }
8e65ff28 9108 internal_error (__FILE__, __LINE__,
e2e0b3e5 9109 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9110}
9111
283002cf
MR
9112static int
9113remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9114 CORE_ADDR start, int length)
9115{
9116 CORE_ADDR diff = remote_address_masked (addr - start);
9117
9118 return diff < length;
9119}
9120
d471ea57 9121
3c3bea1c 9122static int
f486487f
SM
9123remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9124 enum target_hw_bp_type type, struct expression *cond)
96baa820 9125{
d01949b6 9126 struct remote_state *rs = get_remote_state ();
bba74b36 9127 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9128 char *p;
d471ea57
AC
9129 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9130
4082afcc 9131 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9132 return -1;
802188a7 9133
28439a30
PA
9134 /* Make sure the remote is pointing at the right process, if
9135 necessary. */
9136 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9137 set_general_process ();
9138
bba74b36 9139 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9140 p = strchr (rs->buf, '\0');
96baa820
JM
9141 addr = remote_address_masked (addr);
9142 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9143 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9144 putpkt (rs->buf);
9145 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9146
6d820c5c 9147 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9148 {
9149 case PACKET_ERROR:
9150 case PACKET_UNKNOWN:
9151 return -1;
9152 case PACKET_OK:
9153 return 0;
9154 }
8e65ff28 9155 internal_error (__FILE__, __LINE__,
e2e0b3e5 9156 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9157}
9158
3c3bea1c 9159
501eef12 9160int remote_hw_watchpoint_limit = -1;
480a3f21 9161int remote_hw_watchpoint_length_limit = -1;
501eef12 9162int remote_hw_breakpoint_limit = -1;
d471ea57 9163
480a3f21 9164static int
31568a15
TT
9165remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9166 CORE_ADDR addr, int len)
480a3f21
PW
9167{
9168 if (remote_hw_watchpoint_length_limit == 0)
9169 return 0;
9170 else if (remote_hw_watchpoint_length_limit < 0)
9171 return 1;
9172 else if (len <= remote_hw_watchpoint_length_limit)
9173 return 1;
9174 else
9175 return 0;
9176}
9177
b9362cc7 9178static int
5461485a 9179remote_check_watch_resources (struct target_ops *self,
f486487f 9180 enum bptype type, int cnt, int ot)
96baa820 9181{
3c3bea1c
GS
9182 if (type == bp_hardware_breakpoint)
9183 {
9184 if (remote_hw_breakpoint_limit == 0)
9185 return 0;
501eef12
AC
9186 else if (remote_hw_breakpoint_limit < 0)
9187 return 1;
3c3bea1c
GS
9188 else if (cnt <= remote_hw_breakpoint_limit)
9189 return 1;
9190 }
9191 else
9192 {
9193 if (remote_hw_watchpoint_limit == 0)
9194 return 0;
501eef12
AC
9195 else if (remote_hw_watchpoint_limit < 0)
9196 return 1;
3c3bea1c
GS
9197 else if (ot)
9198 return -1;
9199 else if (cnt <= remote_hw_watchpoint_limit)
9200 return 1;
9201 }
9202 return -1;
9203}
9204
f7e6eed5
PA
9205/* The to_stopped_by_sw_breakpoint method of target remote. */
9206
9207static int
9208remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9209{
9210 struct remote_state *rs = get_remote_state ();
9211
9212 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
9213}
9214
9215/* The to_supports_stopped_by_sw_breakpoint method of target
9216 remote. */
9217
9218static int
9219remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9220{
9221 struct remote_state *rs = get_remote_state ();
9222
9223 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9224}
9225
9226/* The to_stopped_by_hw_breakpoint method of target remote. */
9227
9228static int
9229remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9230{
9231 struct remote_state *rs = get_remote_state ();
9232
9233 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9234}
9235
9236/* The to_supports_stopped_by_hw_breakpoint method of target
9237 remote. */
9238
9239static int
9240remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9241{
9242 struct remote_state *rs = get_remote_state ();
9243
9244 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9245}
9246
b9362cc7 9247static int
6a109b6b 9248remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9249{
ee154bee
TT
9250 struct remote_state *rs = get_remote_state ();
9251
f7e6eed5 9252 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
3c3bea1c
GS
9253}
9254
4aa7a7f5
JJ
9255static int
9256remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9257{
ee154bee 9258 struct remote_state *rs = get_remote_state ();
4aa7a7f5 9259 int rc = 0;
a744cf53 9260
6a109b6b 9261 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 9262 {
ee154bee 9263 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
9264 rc = 1;
9265 }
9266
9267 return rc;
3c3bea1c
GS
9268}
9269
9270
9271static int
23a26771 9272remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9273 struct bp_target_info *bp_tgt)
3c3bea1c 9274{
0d5ed153 9275 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9276 struct remote_state *rs;
bba74b36 9277 char *p, *endbuf;
dd61ec5c 9278 char *message;
0d5ed153 9279 int bpsize;
802188a7 9280
c8189ed1 9281 /* The length field should be set to the size of a breakpoint
8181d85f 9282 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9283
0d5ed153 9284 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9285
4082afcc 9286 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9287 return -1;
2bc416ba 9288
28439a30
PA
9289 /* Make sure the remote is pointing at the right process, if
9290 necessary. */
9291 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9292 set_general_process ();
9293
4fff2411
JZ
9294 rs = get_remote_state ();
9295 p = rs->buf;
bba74b36 9296 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9297
96baa820
JM
9298 *(p++) = 'Z';
9299 *(p++) = '1';
9300 *(p++) = ',';
802188a7 9301
0d5ed153 9302 addr = remote_address_masked (addr);
96baa820 9303 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9304 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9305
efcc2da7 9306 if (remote_supports_cond_breakpoints (self))
bba74b36 9307 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9308
78eff0ec 9309 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9310 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9311
6d820c5c
DJ
9312 putpkt (rs->buf);
9313 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9314
6d820c5c 9315 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9316 {
9317 case PACKET_ERROR:
dd61ec5c
MW
9318 if (rs->buf[1] == '.')
9319 {
9320 message = strchr (rs->buf + 2, '.');
9321 if (message)
0316657e 9322 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9323 }
9324 return -1;
d471ea57
AC
9325 case PACKET_UNKNOWN:
9326 return -1;
9327 case PACKET_OK:
0d5ed153
MR
9328 bp_tgt->placed_address = addr;
9329 bp_tgt->placed_size = bpsize;
d471ea57
AC
9330 return 0;
9331 }
8e65ff28 9332 internal_error (__FILE__, __LINE__,
e2e0b3e5 9333 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9334}
9335
d471ea57 9336
802188a7 9337static int
a64dc96c 9338remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9339 struct bp_target_info *bp_tgt)
96baa820 9340{
8181d85f 9341 CORE_ADDR addr;
d01949b6 9342 struct remote_state *rs = get_remote_state ();
6d820c5c 9343 char *p = rs->buf;
bba74b36 9344 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9345
4082afcc 9346 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9347 return -1;
802188a7 9348
28439a30
PA
9349 /* Make sure the remote is pointing at the right process, if
9350 necessary. */
9351 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9352 set_general_process ();
9353
96baa820
JM
9354 *(p++) = 'z';
9355 *(p++) = '1';
9356 *(p++) = ',';
802188a7 9357
8181d85f 9358 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9359 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9360 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9361
6d820c5c
DJ
9362 putpkt (rs->buf);
9363 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9364
6d820c5c 9365 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9366 {
9367 case PACKET_ERROR:
9368 case PACKET_UNKNOWN:
9369 return -1;
9370 case PACKET_OK:
9371 return 0;
9372 }
8e65ff28 9373 internal_error (__FILE__, __LINE__,
e2e0b3e5 9374 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9375}
96baa820 9376
4a5e7a5b
PA
9377/* Verify memory using the "qCRC:" request. */
9378
9379static int
9380remote_verify_memory (struct target_ops *ops,
9381 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9382{
9383 struct remote_state *rs = get_remote_state ();
9384 unsigned long host_crc, target_crc;
9385 char *tmp;
9386
936d2992
PA
9387 /* It doesn't make sense to use qCRC if the remote target is
9388 connected but not running. */
9389 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9390 {
9391 enum packet_result result;
28439a30 9392
936d2992
PA
9393 /* Make sure the remote is pointing at the right process. */
9394 set_general_process ();
4a5e7a5b 9395
936d2992
PA
9396 /* FIXME: assumes lma can fit into long. */
9397 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9398 (long) lma, (long) size);
9399 putpkt (rs->buf);
4a5e7a5b 9400
936d2992
PA
9401 /* Be clever; compute the host_crc before waiting for target
9402 reply. */
9403 host_crc = xcrc32 (data, size, 0xffffffff);
9404
9405 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9406
936d2992
PA
9407 result = packet_ok (rs->buf,
9408 &remote_protocol_packets[PACKET_qCRC]);
9409 if (result == PACKET_ERROR)
9410 return -1;
9411 else if (result == PACKET_OK)
9412 {
9413 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9414 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9415
936d2992
PA
9416 return (host_crc == target_crc);
9417 }
9418 }
4a5e7a5b 9419
936d2992 9420 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9421}
9422
c906108c
SS
9423/* compare-sections command
9424
9425 With no arguments, compares each loadable section in the exec bfd
9426 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9427 Useful for verifying the image on the target against the exec file. */
e514a9d6 9428
c906108c 9429static void
fba45db2 9430compare_sections_command (char *args, int from_tty)
c906108c
SS
9431{
9432 asection *s;
c906108c 9433 struct cleanup *old_chain;
948f8e3d 9434 gdb_byte *sectdata;
ce359b09 9435 const char *sectname;
c906108c
SS
9436 bfd_size_type size;
9437 bfd_vma lma;
9438 int matched = 0;
9439 int mismatched = 0;
4a5e7a5b 9440 int res;
95cf3b38 9441 int read_only = 0;
c906108c
SS
9442
9443 if (!exec_bfd)
8a3fe4f8 9444 error (_("command cannot be used without an exec file"));
c906108c 9445
28439a30
PA
9446 /* Make sure the remote is pointing at the right process. */
9447 set_general_process ();
9448
95cf3b38
DT
9449 if (args != NULL && strcmp (args, "-r") == 0)
9450 {
9451 read_only = 1;
9452 args = NULL;
9453 }
9454
c5aa993b 9455 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9456 {
9457 if (!(s->flags & SEC_LOAD))
0df8b418 9458 continue; /* Skip non-loadable section. */
c906108c 9459
95cf3b38
DT
9460 if (read_only && (s->flags & SEC_READONLY) == 0)
9461 continue; /* Skip writeable sections */
9462
2c500098 9463 size = bfd_get_section_size (s);
c906108c 9464 if (size == 0)
0df8b418 9465 continue; /* Skip zero-length section. */
c906108c 9466
ce359b09 9467 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9468 if (args && strcmp (args, sectname) != 0)
0df8b418 9469 continue; /* Not the section selected by user. */
c906108c 9470
0df8b418 9471 matched = 1; /* Do this section. */
c906108c 9472 lma = s->lma;
c906108c 9473
224c3ddb 9474 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9475 old_chain = make_cleanup (xfree, sectdata);
c906108c 9476 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9477
4a5e7a5b
PA
9478 res = target_verify_memory (sectdata, lma, size);
9479
9480 if (res == -1)
5af949e3 9481 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9482 paddress (target_gdbarch (), lma),
9483 paddress (target_gdbarch (), lma + size));
c906108c 9484
5af949e3 9485 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9486 paddress (target_gdbarch (), lma),
9487 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9488 if (res)
c906108c
SS
9489 printf_filtered ("matched.\n");
9490 else
c5aa993b
JM
9491 {
9492 printf_filtered ("MIS-MATCHED!\n");
9493 mismatched++;
9494 }
c906108c
SS
9495
9496 do_cleanups (old_chain);
9497 }
9498 if (mismatched > 0)
936d2992 9499 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9500the loaded file\n"));
c906108c 9501 if (args && !matched)
a3f17187 9502 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9503}
9504
0e7f50da
UW
9505/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9506 into remote target. The number of bytes written to the remote
9507 target is returned, or -1 for error. */
9508
9b409511 9509static enum target_xfer_status
0e7f50da
UW
9510remote_write_qxfer (struct target_ops *ops, const char *object_name,
9511 const char *annex, const gdb_byte *writebuf,
9b409511 9512 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9513 struct packet_config *packet)
9514{
9515 int i, buf_len;
9516 ULONGEST n;
0e7f50da
UW
9517 struct remote_state *rs = get_remote_state ();
9518 int max_size = get_memory_write_packet_size ();
9519
9520 if (packet->support == PACKET_DISABLE)
2ed4b548 9521 return TARGET_XFER_E_IO;
0e7f50da
UW
9522
9523 /* Insert header. */
9524 i = snprintf (rs->buf, max_size,
9525 "qXfer:%s:write:%s:%s:",
9526 object_name, annex ? annex : "",
9527 phex_nz (offset, sizeof offset));
9528 max_size -= (i + 1);
9529
9530 /* Escape as much data as fits into rs->buf. */
9531 buf_len = remote_escape_output
124e13d9 9532 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9533
9534 if (putpkt_binary (rs->buf, i + buf_len) < 0
9535 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9536 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9537 return TARGET_XFER_E_IO;
0e7f50da
UW
9538
9539 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9540
9541 *xfered_len = n;
9542 return TARGET_XFER_OK;
0e7f50da
UW
9543}
9544
0876f84a
DJ
9545/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9546 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9547 number of bytes read is returned, or 0 for EOF, or -1 for error.
9548 The number of bytes read may be less than LEN without indicating an
9549 EOF. PACKET is checked and updated to indicate whether the remote
9550 target supports this object. */
9551
9b409511 9552static enum target_xfer_status
0876f84a
DJ
9553remote_read_qxfer (struct target_ops *ops, const char *object_name,
9554 const char *annex,
9555 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9556 ULONGEST *xfered_len,
0876f84a
DJ
9557 struct packet_config *packet)
9558{
0876f84a 9559 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9560 LONGEST i, n, packet_len;
9561
9562 if (packet->support == PACKET_DISABLE)
2ed4b548 9563 return TARGET_XFER_E_IO;
0876f84a
DJ
9564
9565 /* Check whether we've cached an end-of-object packet that matches
9566 this request. */
8e88304f 9567 if (rs->finished_object)
0876f84a 9568 {
8e88304f
TT
9569 if (strcmp (object_name, rs->finished_object) == 0
9570 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9571 && offset == rs->finished_offset)
9b409511
YQ
9572 return TARGET_XFER_EOF;
9573
0876f84a
DJ
9574
9575 /* Otherwise, we're now reading something different. Discard
9576 the cache. */
8e88304f
TT
9577 xfree (rs->finished_object);
9578 xfree (rs->finished_annex);
9579 rs->finished_object = NULL;
9580 rs->finished_annex = NULL;
0876f84a
DJ
9581 }
9582
9583 /* Request only enough to fit in a single packet. The actual data
9584 may not, since we don't know how much of it will need to be escaped;
9585 the target is free to respond with slightly less data. We subtract
9586 five to account for the response type and the protocol frame. */
9587 n = min (get_remote_packet_size () - 5, len);
9588 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9589 object_name, annex ? annex : "",
9590 phex_nz (offset, sizeof offset),
9591 phex_nz (n, sizeof n));
9592 i = putpkt (rs->buf);
9593 if (i < 0)
2ed4b548 9594 return TARGET_XFER_E_IO;
0876f84a
DJ
9595
9596 rs->buf[0] = '\0';
9597 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9598 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9599 return TARGET_XFER_E_IO;
0876f84a
DJ
9600
9601 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9602 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9603
9604 /* 'm' means there is (or at least might be) more data after this
9605 batch. That does not make sense unless there's at least one byte
9606 of data in this reply. */
9607 if (rs->buf[0] == 'm' && packet_len == 1)
9608 error (_("Remote qXfer reply contained no data."));
9609
9610 /* Got some data. */
bc20a4af
PA
9611 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9612 packet_len - 1, readbuf, n);
0876f84a
DJ
9613
9614 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9615 or possibly empty. If we have the final block of a non-empty
9616 object, record this fact to bypass a subsequent partial read. */
9617 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9618 {
8e88304f
TT
9619 rs->finished_object = xstrdup (object_name);
9620 rs->finished_annex = xstrdup (annex ? annex : "");
9621 rs->finished_offset = offset + i;
0876f84a
DJ
9622 }
9623
9b409511
YQ
9624 if (i == 0)
9625 return TARGET_XFER_EOF;
9626 else
9627 {
9628 *xfered_len = i;
9629 return TARGET_XFER_OK;
9630 }
0876f84a
DJ
9631}
9632
9b409511 9633static enum target_xfer_status
4b8a223f 9634remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9635 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9636 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9637 ULONGEST *xfered_len)
c906108c 9638{
82f73884 9639 struct remote_state *rs;
c906108c 9640 int i;
6d820c5c 9641 char *p2;
1e3ff5ad 9642 char query_type;
124e13d9 9643 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9644
e6e4e701 9645 set_remote_traceframe ();
82f73884
PA
9646 set_general_thread (inferior_ptid);
9647
9648 rs = get_remote_state ();
9649
b2182ed2 9650 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9651 if (object == TARGET_OBJECT_MEMORY)
9652 {
2d717e4f
DJ
9653 /* If the remote target is connected but not running, we should
9654 pass this request down to a lower stratum (e.g. the executable
9655 file). */
9656 if (!target_has_execution)
9b409511 9657 return TARGET_XFER_EOF;
2d717e4f 9658
21e3b9b9 9659 if (writebuf != NULL)
124e13d9
SM
9660 return remote_write_bytes (offset, writebuf, len, unit_size,
9661 xfered_len);
21e3b9b9 9662 else
124e13d9
SM
9663 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9664 xfered_len);
21e3b9b9
DJ
9665 }
9666
0df8b418 9667 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9668 if (object == TARGET_OBJECT_SPU)
9669 {
9670 if (readbuf)
9671 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9672 xfered_len, &remote_protocol_packets
9673 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9674 else
9675 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9676 xfered_len, &remote_protocol_packets
9677 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9678 }
9679
4aa995e1
PA
9680 /* Handle extra signal info using qxfer packets. */
9681 if (object == TARGET_OBJECT_SIGNAL_INFO)
9682 {
9683 if (readbuf)
9684 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 9685 xfered_len, &remote_protocol_packets
4aa995e1
PA
9686 [PACKET_qXfer_siginfo_read]);
9687 else
3e43a32a 9688 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 9689 writebuf, offset, len, xfered_len,
4aa995e1
PA
9690 &remote_protocol_packets
9691 [PACKET_qXfer_siginfo_write]);
9692 }
9693
0fb4aa4b
PA
9694 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9695 {
9696 if (readbuf)
3e43a32a 9697 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 9698 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
9699 &remote_protocol_packets
9700 [PACKET_qXfer_statictrace_read]);
9701 else
2ed4b548 9702 return TARGET_XFER_E_IO;
0fb4aa4b
PA
9703 }
9704
a76d924d
DJ
9705 /* Only handle flash writes. */
9706 if (writebuf != NULL)
9707 {
9708 LONGEST xfered;
9709
9710 switch (object)
9711 {
9712 case TARGET_OBJECT_FLASH:
9b409511
YQ
9713 return remote_flash_write (ops, offset, len, xfered_len,
9714 writebuf);
a76d924d
DJ
9715
9716 default:
2ed4b548 9717 return TARGET_XFER_E_IO;
a76d924d
DJ
9718 }
9719 }
4b8a223f 9720
1e3ff5ad
AC
9721 /* Map pre-existing objects onto letters. DO NOT do this for new
9722 objects!!! Instead specify new query packets. */
9723 switch (object)
c906108c 9724 {
1e3ff5ad
AC
9725 case TARGET_OBJECT_AVR:
9726 query_type = 'R';
9727 break;
802188a7
RM
9728
9729 case TARGET_OBJECT_AUXV:
0876f84a
DJ
9730 gdb_assert (annex == NULL);
9731 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9732 xfered_len,
0876f84a 9733 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9734
23181151
DJ
9735 case TARGET_OBJECT_AVAILABLE_FEATURES:
9736 return remote_read_qxfer
9b409511 9737 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9738 &remote_protocol_packets[PACKET_qXfer_features]);
9739
cfa9d6d9
DJ
9740 case TARGET_OBJECT_LIBRARIES:
9741 return remote_read_qxfer
9b409511 9742 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9743 &remote_protocol_packets[PACKET_qXfer_libraries]);
9744
2268b414
JK
9745 case TARGET_OBJECT_LIBRARIES_SVR4:
9746 return remote_read_qxfer
9b409511 9747 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9748 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9749
fd79ecee
DJ
9750 case TARGET_OBJECT_MEMORY_MAP:
9751 gdb_assert (annex == NULL);
9752 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9753 xfered_len,
fd79ecee
DJ
9754 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9755
07e059b5
VP
9756 case TARGET_OBJECT_OSDATA:
9757 /* Should only get here if we're connected. */
5d93a237 9758 gdb_assert (rs->remote_desc);
07e059b5 9759 return remote_read_qxfer
9b409511 9760 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9761 &remote_protocol_packets[PACKET_qXfer_osdata]);
9762
dc146f7c
VP
9763 case TARGET_OBJECT_THREADS:
9764 gdb_assert (annex == NULL);
9765 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9766 xfered_len,
dc146f7c
VP
9767 &remote_protocol_packets[PACKET_qXfer_threads]);
9768
b3b9301e
PA
9769 case TARGET_OBJECT_TRACEFRAME_INFO:
9770 gdb_assert (annex == NULL);
9771 return remote_read_qxfer
9b409511 9772 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9773 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9774
9775 case TARGET_OBJECT_FDPIC:
9776 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9777 xfered_len,
78d85199 9778 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9779
9780 case TARGET_OBJECT_OPENVMS_UIB:
9781 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 9782 xfered_len,
169081d0
TG
9783 &remote_protocol_packets[PACKET_qXfer_uib]);
9784
9accd112
MM
9785 case TARGET_OBJECT_BTRACE:
9786 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 9787 xfered_len,
9accd112
MM
9788 &remote_protocol_packets[PACKET_qXfer_btrace]);
9789
f4abbc16
MM
9790 case TARGET_OBJECT_BTRACE_CONF:
9791 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9792 len, xfered_len,
9793 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9794
c78fa86a
GB
9795 case TARGET_OBJECT_EXEC_FILE:
9796 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9797 len, xfered_len,
9798 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9799
1e3ff5ad 9800 default:
2ed4b548 9801 return TARGET_XFER_E_IO;
c906108c
SS
9802 }
9803
0df8b418 9804 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 9805 large enough let the caller deal with it. */
ea9c271d 9806 if (len < get_remote_packet_size ())
2ed4b548 9807 return TARGET_XFER_E_IO;
ea9c271d 9808 len = get_remote_packet_size ();
1e3ff5ad 9809
23860348 9810 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 9811 if (!rs->remote_desc)
8a3fe4f8 9812 error (_("remote query is only available after target open"));
c906108c 9813
1e3ff5ad 9814 gdb_assert (annex != NULL);
4b8a223f 9815 gdb_assert (readbuf != NULL);
c906108c 9816
6d820c5c 9817 p2 = rs->buf;
c906108c
SS
9818 *p2++ = 'q';
9819 *p2++ = query_type;
9820
23860348
MS
9821 /* We used one buffer char for the remote protocol q command and
9822 another for the query type. As the remote protocol encapsulation
9823 uses 4 chars plus one extra in case we are debugging
9824 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9825 string. */
c906108c 9826 i = 0;
ea9c271d 9827 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 9828 {
1e3ff5ad
AC
9829 /* Bad caller may have sent forbidden characters. */
9830 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9831 *p2++ = annex[i];
c906108c
SS
9832 i++;
9833 }
1e3ff5ad
AC
9834 *p2 = '\0';
9835 gdb_assert (annex[i] == '\0');
c906108c 9836
6d820c5c 9837 i = putpkt (rs->buf);
c5aa993b 9838 if (i < 0)
2ed4b548 9839 return TARGET_XFER_E_IO;
c906108c 9840
6d820c5c
DJ
9841 getpkt (&rs->buf, &rs->buf_size, 0);
9842 strcpy ((char *) readbuf, rs->buf);
c906108c 9843
9b409511
YQ
9844 *xfered_len = strlen ((char *) readbuf);
9845 return TARGET_XFER_OK;
c906108c
SS
9846}
9847
08388c79
DE
9848static int
9849remote_search_memory (struct target_ops* ops,
9850 CORE_ADDR start_addr, ULONGEST search_space_len,
9851 const gdb_byte *pattern, ULONGEST pattern_len,
9852 CORE_ADDR *found_addrp)
9853{
f5656ead 9854 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
9855 struct remote_state *rs = get_remote_state ();
9856 int max_size = get_memory_write_packet_size ();
9857 struct packet_config *packet =
9858 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
9859 /* Number of packet bytes used to encode the pattern;
9860 this could be more than PATTERN_LEN due to escape characters. */
08388c79 9861 int escaped_pattern_len;
0df8b418 9862 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
9863 int used_pattern_len;
9864 int i;
9865 int found;
9866 ULONGEST found_addr;
9867
9868 /* Don't go to the target if we don't have to.
9869 This is done before checking packet->support to avoid the possibility that
9870 a success for this edge case means the facility works in general. */
9871 if (pattern_len > search_space_len)
9872 return 0;
9873 if (pattern_len == 0)
9874 {
9875 *found_addrp = start_addr;
9876 return 1;
9877 }
9878
9879 /* If we already know the packet isn't supported, fall back to the simple
9880 way of searching memory. */
9881
4082afcc 9882 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
9883 {
9884 /* Target doesn't provided special support, fall back and use the
9885 standard support (copy memory and do the search here). */
9886 return simple_search_memory (ops, start_addr, search_space_len,
9887 pattern, pattern_len, found_addrp);
9888 }
9889
28439a30
PA
9890 /* Make sure the remote is pointing at the right process. */
9891 set_general_process ();
9892
08388c79
DE
9893 /* Insert header. */
9894 i = snprintf (rs->buf, max_size,
9895 "qSearch:memory:%s;%s;",
5af949e3 9896 phex_nz (start_addr, addr_size),
08388c79
DE
9897 phex_nz (search_space_len, sizeof (search_space_len)));
9898 max_size -= (i + 1);
9899
9900 /* Escape as much data as fits into rs->buf. */
9901 escaped_pattern_len =
124e13d9 9902 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
9903 &used_pattern_len, max_size);
9904
9905 /* Bail if the pattern is too large. */
9906 if (used_pattern_len != pattern_len)
9b20d036 9907 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
9908
9909 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9910 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9911 || packet_ok (rs->buf, packet) != PACKET_OK)
9912 {
9913 /* The request may not have worked because the command is not
9914 supported. If so, fall back to the simple way. */
9915 if (packet->support == PACKET_DISABLE)
9916 {
9917 return simple_search_memory (ops, start_addr, search_space_len,
9918 pattern, pattern_len, found_addrp);
9919 }
9920 return -1;
9921 }
9922
9923 if (rs->buf[0] == '0')
9924 found = 0;
9925 else if (rs->buf[0] == '1')
9926 {
9927 found = 1;
9928 if (rs->buf[1] != ',')
10e0fa18 9929 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9930 unpack_varlen_hex (rs->buf + 2, &found_addr);
9931 *found_addrp = found_addr;
9932 }
9933 else
10e0fa18 9934 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9935
9936 return found;
9937}
9938
96baa820 9939static void
a30bf1f1 9940remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 9941 struct ui_file *outbuf)
96baa820 9942{
d01949b6 9943 struct remote_state *rs = get_remote_state ();
2e9f7625 9944 char *p = rs->buf;
96baa820 9945
5d93a237 9946 if (!rs->remote_desc)
8a3fe4f8 9947 error (_("remote rcmd is only available after target open"));
96baa820 9948
23860348 9949 /* Send a NULL command across as an empty command. */
7be570e7
JM
9950 if (command == NULL)
9951 command = "";
9952
23860348 9953 /* The query prefix. */
2e9f7625
DJ
9954 strcpy (rs->buf, "qRcmd,");
9955 p = strchr (rs->buf, '\0');
96baa820 9956
3e43a32a
MS
9957 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9958 > get_remote_packet_size ())
8a3fe4f8 9959 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9960
23860348 9961 /* Encode the actual command. */
a30bf1f1 9962 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 9963
6d820c5c 9964 if (putpkt (rs->buf) < 0)
8a3fe4f8 9965 error (_("Communication problem with target."));
96baa820
JM
9966
9967 /* get/display the response */
9968 while (1)
9969 {
2e9f7625
DJ
9970 char *buf;
9971
00bf0b85 9972 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9973 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9974 rs->buf[0] = '\0';
5b37825d
PW
9975 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9976 {
9977 /* Timeout. Continue to (try to) read responses.
9978 This is better than stopping with an error, assuming the stub
9979 is still executing the (long) monitor command.
9980 If needed, the user can interrupt gdb using C-c, obtaining
9981 an effect similar to stop on timeout. */
9982 continue;
9983 }
2e9f7625 9984 buf = rs->buf;
96baa820 9985 if (buf[0] == '\0')
8a3fe4f8 9986 error (_("Target does not support this command."));
96baa820
JM
9987 if (buf[0] == 'O' && buf[1] != 'K')
9988 {
23860348 9989 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9990 continue;
9991 }
9992 if (strcmp (buf, "OK") == 0)
9993 break;
7be570e7
JM
9994 if (strlen (buf) == 3 && buf[0] == 'E'
9995 && isdigit (buf[1]) && isdigit (buf[2]))
9996 {
8a3fe4f8 9997 error (_("Protocol error with Rcmd"));
7be570e7 9998 }
96baa820
JM
9999 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10000 {
10001 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10002
96baa820
JM
10003 fputc_unfiltered (c, outbuf);
10004 }
10005 break;
10006 }
10007}
10008
fd79ecee
DJ
10009static VEC(mem_region_s) *
10010remote_memory_map (struct target_ops *ops)
10011{
10012 VEC(mem_region_s) *result = NULL;
10013 char *text = target_read_stralloc (&current_target,
10014 TARGET_OBJECT_MEMORY_MAP, NULL);
10015
10016 if (text)
10017 {
10018 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10019
fd79ecee
DJ
10020 result = parse_memory_map (text);
10021 do_cleanups (back_to);
10022 }
10023
10024 return result;
10025}
10026
c906108c 10027static void
fba45db2 10028packet_command (char *args, int from_tty)
c906108c 10029{
d01949b6 10030 struct remote_state *rs = get_remote_state ();
c906108c 10031
5d93a237 10032 if (!rs->remote_desc)
8a3fe4f8 10033 error (_("command can only be used with remote target"));
c906108c 10034
c5aa993b 10035 if (!args)
8a3fe4f8 10036 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10037
10038 puts_filtered ("sending: ");
10039 print_packet (args);
10040 puts_filtered ("\n");
10041 putpkt (args);
10042
6d820c5c 10043 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10044 puts_filtered ("received: ");
6d820c5c 10045 print_packet (rs->buf);
c906108c
SS
10046 puts_filtered ("\n");
10047}
10048
10049#if 0
23860348 10050/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10051
a14ed312 10052static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10053
a14ed312 10054static void threadset_test_cmd (char *cmd, int tty);
c906108c 10055
a14ed312 10056static void threadalive_test (char *cmd, int tty);
c906108c 10057
a14ed312 10058static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10059
23860348 10060int get_and_display_threadinfo (threadref *ref);
c906108c 10061
a14ed312 10062static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10063
23860348 10064static int thread_display_step (threadref *ref, void *context);
c906108c 10065
a14ed312 10066static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10067
a14ed312 10068static void init_remote_threadtests (void);
c906108c 10069
23860348 10070#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10071
10072static void
fba45db2 10073threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10074{
10075 int sample_thread = SAMPLE_THREAD;
10076
a3f17187 10077 printf_filtered (_("Remote threadset test\n"));
79d7f229 10078 set_general_thread (sample_thread);
c906108c
SS
10079}
10080
10081
10082static void
fba45db2 10083threadalive_test (char *cmd, int tty)
c906108c
SS
10084{
10085 int sample_thread = SAMPLE_THREAD;
79d7f229 10086 int pid = ptid_get_pid (inferior_ptid);
ba348170 10087 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10088
79d7f229 10089 if (remote_thread_alive (ptid))
c906108c
SS
10090 printf_filtered ("PASS: Thread alive test\n");
10091 else
10092 printf_filtered ("FAIL: Thread alive test\n");
10093}
10094
23860348 10095void output_threadid (char *title, threadref *ref);
c906108c
SS
10096
10097void
fba45db2 10098output_threadid (char *title, threadref *ref)
c906108c
SS
10099{
10100 char hexid[20];
10101
23860348 10102 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10103 hexid[16] = 0;
10104 printf_filtered ("%s %s\n", title, (&hexid[0]));
10105}
10106
10107static void
fba45db2 10108threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10109{
10110 int startflag = 1;
10111 threadref nextthread;
10112 int done, result_count;
10113 threadref threadlist[3];
10114
10115 printf_filtered ("Remote Threadlist test\n");
10116 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10117 &result_count, &threadlist[0]))
10118 printf_filtered ("FAIL: threadlist test\n");
10119 else
10120 {
10121 threadref *scan = threadlist;
10122 threadref *limit = scan + result_count;
10123
10124 while (scan < limit)
10125 output_threadid (" thread ", scan++);
10126 }
10127}
10128
10129void
fba45db2 10130display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10131{
10132 output_threadid ("Threadid: ", &info->threadid);
10133 printf_filtered ("Name: %s\n ", info->shortname);
10134 printf_filtered ("State: %s\n", info->display);
10135 printf_filtered ("other: %s\n\n", info->more_display);
10136}
10137
10138int
fba45db2 10139get_and_display_threadinfo (threadref *ref)
c906108c
SS
10140{
10141 int result;
10142 int set;
10143 struct gdb_ext_thread_info threadinfo;
10144
10145 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10146 | TAG_MOREDISPLAY | TAG_DISPLAY;
10147 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10148 display_thread_info (&threadinfo);
10149 return result;
10150}
10151
10152static void
fba45db2 10153threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10154{
10155 int athread = SAMPLE_THREAD;
10156 threadref thread;
10157 int set;
10158
10159 int_to_threadref (&thread, athread);
10160 printf_filtered ("Remote Threadinfo test\n");
10161 if (!get_and_display_threadinfo (&thread))
10162 printf_filtered ("FAIL cannot get thread info\n");
10163}
10164
10165static int
fba45db2 10166thread_display_step (threadref *ref, void *context)
c906108c
SS
10167{
10168 /* output_threadid(" threadstep ",ref); *//* simple test */
10169 return get_and_display_threadinfo (ref);
10170}
10171
10172static void
fba45db2 10173threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10174{
10175 printf_filtered ("Remote Threadlist update test\n");
10176 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10177}
10178
10179static void
10180init_remote_threadtests (void)
10181{
3e43a32a
MS
10182 add_com ("tlist", class_obscure, threadlist_test_cmd,
10183 _("Fetch and print the remote list of "
10184 "thread identifiers, one pkt only"));
c906108c 10185 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10186 _("Fetch and display info about one thread"));
c906108c 10187 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10188 _("Test setting to a different thread"));
c906108c 10189 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10190 _("Iterate through updating all remote thread info"));
c906108c 10191 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10192 _(" Remote thread alive test "));
c906108c
SS
10193}
10194
10195#endif /* 0 */
10196
f3fb8c85
MS
10197/* Convert a thread ID to a string. Returns the string in a static
10198 buffer. */
10199
10200static char *
117de6a9 10201remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10202{
79d7f229 10203 static char buf[64];
82f73884 10204 struct remote_state *rs = get_remote_state ();
f3fb8c85 10205
7cee1e54
PA
10206 if (ptid_equal (ptid, null_ptid))
10207 return normal_pid_to_str (ptid);
10208 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10209 {
10210 /* Printing an inferior target id. */
10211
10212 /* When multi-process extensions are off, there's no way in the
10213 remote protocol to know the remote process id, if there's any
10214 at all. There's one exception --- when we're connected with
10215 target extended-remote, and we manually attached to a process
10216 with "attach PID". We don't record anywhere a flag that
10217 allows us to distinguish that case from the case of
10218 connecting with extended-remote and the stub already being
10219 attached to a process, and reporting yes to qAttached, hence
10220 no smart special casing here. */
10221 if (!remote_multi_process_p (rs))
10222 {
10223 xsnprintf (buf, sizeof buf, "Remote target");
10224 return buf;
10225 }
10226
10227 return normal_pid_to_str (ptid);
82f73884 10228 }
ecd0ada5 10229 else
79d7f229 10230 {
ecd0ada5
PA
10231 if (ptid_equal (magic_null_ptid, ptid))
10232 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 10233 else if (rs->extended && remote_multi_process_p (rs))
de0d863e
DB
10234 if (ptid_get_lwp (ptid) == 0)
10235 return normal_pid_to_str (ptid);
10236 else
10237 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10238 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10239 else
10240 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10241 ptid_get_lwp (ptid));
79d7f229
PA
10242 return buf;
10243 }
f3fb8c85
MS
10244}
10245
38691318
KB
10246/* Get the address of the thread local variable in OBJFILE which is
10247 stored at OFFSET within the thread local storage for thread PTID. */
10248
10249static CORE_ADDR
117de6a9
PA
10250remote_get_thread_local_address (struct target_ops *ops,
10251 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10252{
4082afcc 10253 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10254 {
10255 struct remote_state *rs = get_remote_state ();
6d820c5c 10256 char *p = rs->buf;
82f73884 10257 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10258 enum packet_result result;
38691318
KB
10259
10260 strcpy (p, "qGetTLSAddr:");
10261 p += strlen (p);
82f73884 10262 p = write_ptid (p, endp, ptid);
38691318
KB
10263 *p++ = ',';
10264 p += hexnumstr (p, offset);
10265 *p++ = ',';
10266 p += hexnumstr (p, lm);
10267 *p++ = '\0';
10268
6d820c5c
DJ
10269 putpkt (rs->buf);
10270 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10271 result = packet_ok (rs->buf,
10272 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10273 if (result == PACKET_OK)
38691318
KB
10274 {
10275 ULONGEST result;
10276
6d820c5c 10277 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10278 return result;
10279 }
571dd617 10280 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10281 throw_error (TLS_GENERIC_ERROR,
10282 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10283 else
109c3e39
AC
10284 throw_error (TLS_GENERIC_ERROR,
10285 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10286 }
10287 else
109c3e39
AC
10288 throw_error (TLS_GENERIC_ERROR,
10289 _("TLS not supported or disabled on this target"));
38691318
KB
10290 /* Not reached. */
10291 return 0;
10292}
10293
711e434b
PM
10294/* Provide thread local base, i.e. Thread Information Block address.
10295 Returns 1 if ptid is found and thread_local_base is non zero. */
10296
70221824 10297static int
bd7ae0f5 10298remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10299{
4082afcc 10300 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10301 {
10302 struct remote_state *rs = get_remote_state ();
10303 char *p = rs->buf;
10304 char *endp = rs->buf + get_remote_packet_size ();
10305 enum packet_result result;
10306
10307 strcpy (p, "qGetTIBAddr:");
10308 p += strlen (p);
10309 p = write_ptid (p, endp, ptid);
10310 *p++ = '\0';
10311
10312 putpkt (rs->buf);
10313 getpkt (&rs->buf, &rs->buf_size, 0);
10314 result = packet_ok (rs->buf,
10315 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10316 if (result == PACKET_OK)
10317 {
10318 ULONGEST result;
10319
10320 unpack_varlen_hex (rs->buf, &result);
10321 if (addr)
10322 *addr = (CORE_ADDR) result;
10323 return 1;
10324 }
10325 else if (result == PACKET_UNKNOWN)
10326 error (_("Remote target doesn't support qGetTIBAddr packet"));
10327 else
10328 error (_("Remote target failed to process qGetTIBAddr request"));
10329 }
10330 else
10331 error (_("qGetTIBAddr not supported or disabled on this target"));
10332 /* Not reached. */
10333 return 0;
10334}
10335
29709017
DJ
10336/* Support for inferring a target description based on the current
10337 architecture and the size of a 'g' packet. While the 'g' packet
10338 can have any size (since optional registers can be left off the
10339 end), some sizes are easily recognizable given knowledge of the
10340 approximate architecture. */
10341
10342struct remote_g_packet_guess
10343{
10344 int bytes;
10345 const struct target_desc *tdesc;
10346};
10347typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10348DEF_VEC_O(remote_g_packet_guess_s);
10349
10350struct remote_g_packet_data
10351{
10352 VEC(remote_g_packet_guess_s) *guesses;
10353};
10354
10355static struct gdbarch_data *remote_g_packet_data_handle;
10356
10357static void *
10358remote_g_packet_data_init (struct obstack *obstack)
10359{
10360 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10361}
10362
10363void
10364register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10365 const struct target_desc *tdesc)
10366{
10367 struct remote_g_packet_data *data
19ba03f4
SM
10368 = ((struct remote_g_packet_data *)
10369 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10370 struct remote_g_packet_guess new_guess, *guess;
10371 int ix;
10372
10373 gdb_assert (tdesc != NULL);
10374
10375 for (ix = 0;
10376 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10377 ix++)
10378 if (guess->bytes == bytes)
10379 internal_error (__FILE__, __LINE__,
9b20d036 10380 _("Duplicate g packet description added for size %d"),
29709017
DJ
10381 bytes);
10382
10383 new_guess.bytes = bytes;
10384 new_guess.tdesc = tdesc;
10385 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10386}
10387
d962ef82
DJ
10388/* Return 1 if remote_read_description would do anything on this target
10389 and architecture, 0 otherwise. */
10390
10391static int
10392remote_read_description_p (struct target_ops *target)
10393{
10394 struct remote_g_packet_data *data
19ba03f4
SM
10395 = ((struct remote_g_packet_data *)
10396 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10397
10398 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10399 return 1;
10400
10401 return 0;
10402}
10403
29709017
DJ
10404static const struct target_desc *
10405remote_read_description (struct target_ops *target)
10406{
10407 struct remote_g_packet_data *data
19ba03f4
SM
10408 = ((struct remote_g_packet_data *)
10409 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10410
d962ef82
DJ
10411 /* Do not try this during initial connection, when we do not know
10412 whether there is a running but stopped thread. */
10413 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10414 return target->beneath->to_read_description (target->beneath);
d962ef82 10415
29709017
DJ
10416 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10417 {
10418 struct remote_g_packet_guess *guess;
10419 int ix;
10420 int bytes = send_g_packet ();
10421
10422 for (ix = 0;
10423 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10424 ix++)
10425 if (guess->bytes == bytes)
10426 return guess->tdesc;
10427
10428 /* We discard the g packet. A minor optimization would be to
10429 hold on to it, and fill the register cache once we have selected
10430 an architecture, but it's too tricky to do safely. */
10431 }
10432
2117c711 10433 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10434}
10435
a6b151f1
DJ
10436/* Remote file transfer support. This is host-initiated I/O, not
10437 target-initiated; for target-initiated, see remote-fileio.c. */
10438
10439/* If *LEFT is at least the length of STRING, copy STRING to
10440 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10441 decrease *LEFT. Otherwise raise an error. */
10442
10443static void
10444remote_buffer_add_string (char **buffer, int *left, char *string)
10445{
10446 int len = strlen (string);
10447
10448 if (len > *left)
10449 error (_("Packet too long for target."));
10450
10451 memcpy (*buffer, string, len);
10452 *buffer += len;
10453 *left -= len;
10454
10455 /* NUL-terminate the buffer as a convenience, if there is
10456 room. */
10457 if (*left)
10458 **buffer = '\0';
10459}
10460
10461/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10462 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10463 decrease *LEFT. Otherwise raise an error. */
10464
10465static void
10466remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10467 int len)
10468{
10469 if (2 * len > *left)
10470 error (_("Packet too long for target."));
10471
10472 bin2hex (bytes, *buffer, len);
10473 *buffer += 2 * len;
10474 *left -= 2 * len;
10475
10476 /* NUL-terminate the buffer as a convenience, if there is
10477 room. */
10478 if (*left)
10479 **buffer = '\0';
10480}
10481
10482/* If *LEFT is large enough, convert VALUE to hex and add it to
10483 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10484 decrease *LEFT. Otherwise raise an error. */
10485
10486static void
10487remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10488{
10489 int len = hexnumlen (value);
10490
10491 if (len > *left)
10492 error (_("Packet too long for target."));
10493
10494 hexnumstr (*buffer, value);
10495 *buffer += len;
10496 *left -= len;
10497
10498 /* NUL-terminate the buffer as a convenience, if there is
10499 room. */
10500 if (*left)
10501 **buffer = '\0';
10502}
10503
10504/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10505 value, *REMOTE_ERRNO to the remote error number or zero if none
10506 was included, and *ATTACHMENT to point to the start of the annex
10507 if any. The length of the packet isn't needed here; there may
10508 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10509
10510 Return 0 if the packet could be parsed, -1 if it could not. If
10511 -1 is returned, the other variables may not be initialized. */
10512
10513static int
10514remote_hostio_parse_result (char *buffer, int *retcode,
10515 int *remote_errno, char **attachment)
10516{
10517 char *p, *p2;
10518
10519 *remote_errno = 0;
10520 *attachment = NULL;
10521
10522 if (buffer[0] != 'F')
10523 return -1;
10524
10525 errno = 0;
10526 *retcode = strtol (&buffer[1], &p, 16);
10527 if (errno != 0 || p == &buffer[1])
10528 return -1;
10529
10530 /* Check for ",errno". */
10531 if (*p == ',')
10532 {
10533 errno = 0;
10534 *remote_errno = strtol (p + 1, &p2, 16);
10535 if (errno != 0 || p + 1 == p2)
10536 return -1;
10537 p = p2;
10538 }
10539
10540 /* Check for ";attachment". If there is no attachment, the
10541 packet should end here. */
10542 if (*p == ';')
10543 {
10544 *attachment = p + 1;
10545 return 0;
10546 }
10547 else if (*p == '\0')
10548 return 0;
10549 else
10550 return -1;
10551}
10552
10553/* Send a prepared I/O packet to the target and read its response.
10554 The prepared packet is in the global RS->BUF before this function
10555 is called, and the answer is there when we return.
10556
10557 COMMAND_BYTES is the length of the request to send, which may include
10558 binary data. WHICH_PACKET is the packet configuration to check
10559 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10560 is set to the error number and -1 is returned. Otherwise the value
10561 returned by the function is returned.
10562
10563 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10564 attachment is expected; an error will be reported if there's a
10565 mismatch. If one is found, *ATTACHMENT will be set to point into
10566 the packet buffer and *ATTACHMENT_LEN will be set to the
10567 attachment's length. */
10568
10569static int
10570remote_hostio_send_command (int command_bytes, int which_packet,
10571 int *remote_errno, char **attachment,
10572 int *attachment_len)
10573{
10574 struct remote_state *rs = get_remote_state ();
10575 int ret, bytes_read;
10576 char *attachment_tmp;
10577
5d93a237 10578 if (!rs->remote_desc
4082afcc 10579 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10580 {
10581 *remote_errno = FILEIO_ENOSYS;
10582 return -1;
10583 }
10584
10585 putpkt_binary (rs->buf, command_bytes);
10586 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10587
10588 /* If it timed out, something is wrong. Don't try to parse the
10589 buffer. */
10590 if (bytes_read < 0)
10591 {
10592 *remote_errno = FILEIO_EINVAL;
10593 return -1;
10594 }
10595
10596 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10597 {
10598 case PACKET_ERROR:
10599 *remote_errno = FILEIO_EINVAL;
10600 return -1;
10601 case PACKET_UNKNOWN:
10602 *remote_errno = FILEIO_ENOSYS;
10603 return -1;
10604 case PACKET_OK:
10605 break;
10606 }
10607
10608 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10609 &attachment_tmp))
10610 {
10611 *remote_errno = FILEIO_EINVAL;
10612 return -1;
10613 }
10614
10615 /* Make sure we saw an attachment if and only if we expected one. */
10616 if ((attachment_tmp == NULL && attachment != NULL)
10617 || (attachment_tmp != NULL && attachment == NULL))
10618 {
10619 *remote_errno = FILEIO_EINVAL;
10620 return -1;
10621 }
10622
10623 /* If an attachment was found, it must point into the packet buffer;
10624 work out how many bytes there were. */
10625 if (attachment_tmp != NULL)
10626 {
10627 *attachment = attachment_tmp;
10628 *attachment_len = bytes_read - (*attachment - rs->buf);
10629 }
10630
10631 return ret;
10632}
10633
80152258
PA
10634/* Invalidate the readahead cache. */
10635
10636static void
10637readahead_cache_invalidate (void)
10638{
10639 struct remote_state *rs = get_remote_state ();
10640
10641 rs->readahead_cache.fd = -1;
10642}
10643
10644/* Invalidate the readahead cache if it is holding data for FD. */
10645
10646static void
10647readahead_cache_invalidate_fd (int fd)
10648{
10649 struct remote_state *rs = get_remote_state ();
10650
10651 if (rs->readahead_cache.fd == fd)
10652 rs->readahead_cache.fd = -1;
10653}
10654
15a201c8
GB
10655/* Set the filesystem remote_hostio functions that take FILENAME
10656 arguments will use. Return 0 on success, or -1 if an error
10657 occurs (and set *REMOTE_ERRNO). */
10658
10659static int
10660remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10661{
10662 struct remote_state *rs = get_remote_state ();
10663 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10664 char *p = rs->buf;
10665 int left = get_remote_packet_size () - 1;
10666 char arg[9];
10667 int ret;
10668
10669 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10670 return 0;
10671
10672 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10673 return 0;
10674
10675 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10676
10677 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10678 remote_buffer_add_string (&p, &left, arg);
10679
10680 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10681 remote_errno, NULL, NULL);
10682
10683 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10684 return 0;
10685
10686 if (ret == 0)
10687 rs->fs_pid = required_pid;
10688
10689 return ret;
10690}
10691
12e2a5fd 10692/* Implementation of to_fileio_open. */
a6b151f1
DJ
10693
10694static int
cd897586 10695remote_hostio_open (struct target_ops *self,
07c138c8 10696 struct inferior *inf, const char *filename,
4313b8c0
GB
10697 int flags, int mode, int warn_if_slow,
10698 int *remote_errno)
a6b151f1
DJ
10699{
10700 struct remote_state *rs = get_remote_state ();
10701 char *p = rs->buf;
10702 int left = get_remote_packet_size () - 1;
10703
4313b8c0
GB
10704 if (warn_if_slow)
10705 {
10706 static int warning_issued = 0;
10707
10708 printf_unfiltered (_("Reading %s from remote target...\n"),
10709 filename);
10710
10711 if (!warning_issued)
10712 {
10713 warning (_("File transfers from remote targets can be slow."
10714 " Use \"set sysroot\" to access files locally"
10715 " instead."));
10716 warning_issued = 1;
10717 }
10718 }
10719
15a201c8
GB
10720 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10721 return -1;
10722
a6b151f1
DJ
10723 remote_buffer_add_string (&p, &left, "vFile:open:");
10724
10725 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10726 strlen (filename));
10727 remote_buffer_add_string (&p, &left, ",");
10728
10729 remote_buffer_add_int (&p, &left, flags);
10730 remote_buffer_add_string (&p, &left, ",");
10731
10732 remote_buffer_add_int (&p, &left, mode);
10733
10734 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10735 remote_errno, NULL, NULL);
10736}
10737
12e2a5fd 10738/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
10739
10740static int
0d866f62
TT
10741remote_hostio_pwrite (struct target_ops *self,
10742 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
10743 ULONGEST offset, int *remote_errno)
10744{
10745 struct remote_state *rs = get_remote_state ();
10746 char *p = rs->buf;
10747 int left = get_remote_packet_size ();
10748 int out_len;
10749
80152258
PA
10750 readahead_cache_invalidate_fd (fd);
10751
a6b151f1
DJ
10752 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10753
10754 remote_buffer_add_int (&p, &left, fd);
10755 remote_buffer_add_string (&p, &left, ",");
10756
10757 remote_buffer_add_int (&p, &left, offset);
10758 remote_buffer_add_string (&p, &left, ",");
10759
124e13d9 10760 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
10761 get_remote_packet_size () - (p - rs->buf));
10762
10763 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10764 remote_errno, NULL, NULL);
10765}
10766
80152258
PA
10767/* Helper for the implementation of to_fileio_pread. Read the file
10768 from the remote side with vFile:pread. */
a6b151f1
DJ
10769
10770static int
80152258
PA
10771remote_hostio_pread_vFile (struct target_ops *self,
10772 int fd, gdb_byte *read_buf, int len,
10773 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
10774{
10775 struct remote_state *rs = get_remote_state ();
10776 char *p = rs->buf;
10777 char *attachment;
10778 int left = get_remote_packet_size ();
10779 int ret, attachment_len;
10780 int read_len;
10781
10782 remote_buffer_add_string (&p, &left, "vFile:pread:");
10783
10784 remote_buffer_add_int (&p, &left, fd);
10785 remote_buffer_add_string (&p, &left, ",");
10786
10787 remote_buffer_add_int (&p, &left, len);
10788 remote_buffer_add_string (&p, &left, ",");
10789
10790 remote_buffer_add_int (&p, &left, offset);
10791
10792 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10793 remote_errno, &attachment,
10794 &attachment_len);
10795
10796 if (ret < 0)
10797 return ret;
10798
bc20a4af 10799 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
10800 read_buf, len);
10801 if (read_len != ret)
10802 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10803
10804 return ret;
10805}
10806
80152258
PA
10807/* Serve pread from the readahead cache. Returns number of bytes
10808 read, or 0 if the request can't be served from the cache. */
10809
10810static int
10811remote_hostio_pread_from_cache (struct remote_state *rs,
10812 int fd, gdb_byte *read_buf, size_t len,
10813 ULONGEST offset)
10814{
10815 struct readahead_cache *cache = &rs->readahead_cache;
10816
10817 if (cache->fd == fd
10818 && cache->offset <= offset
10819 && offset < cache->offset + cache->bufsize)
10820 {
10821 ULONGEST max = cache->offset + cache->bufsize;
10822
10823 if (offset + len > max)
10824 len = max - offset;
10825
10826 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10827 return len;
10828 }
10829
10830 return 0;
10831}
10832
10833/* Implementation of to_fileio_pread. */
10834
10835static int
10836remote_hostio_pread (struct target_ops *self,
10837 int fd, gdb_byte *read_buf, int len,
10838 ULONGEST offset, int *remote_errno)
10839{
10840 int ret;
10841 struct remote_state *rs = get_remote_state ();
10842 struct readahead_cache *cache = &rs->readahead_cache;
10843
10844 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10845 if (ret > 0)
10846 {
10847 cache->hit_count++;
10848
10849 if (remote_debug)
10850 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10851 pulongest (cache->hit_count));
10852 return ret;
10853 }
10854
10855 cache->miss_count++;
10856 if (remote_debug)
10857 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10858 pulongest (cache->miss_count));
10859
10860 cache->fd = fd;
10861 cache->offset = offset;
10862 cache->bufsize = get_remote_packet_size ();
224c3ddb 10863 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
10864
10865 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10866 cache->offset, remote_errno);
10867 if (ret <= 0)
10868 {
10869 readahead_cache_invalidate_fd (fd);
10870 return ret;
10871 }
10872
10873 cache->bufsize = ret;
10874 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10875}
10876
12e2a5fd 10877/* Implementation of to_fileio_close. */
a6b151f1
DJ
10878
10879static int
df39ea25 10880remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
10881{
10882 struct remote_state *rs = get_remote_state ();
10883 char *p = rs->buf;
10884 int left = get_remote_packet_size () - 1;
10885
80152258
PA
10886 readahead_cache_invalidate_fd (fd);
10887
a6b151f1
DJ
10888 remote_buffer_add_string (&p, &left, "vFile:close:");
10889
10890 remote_buffer_add_int (&p, &left, fd);
10891
10892 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10893 remote_errno, NULL, NULL);
10894}
10895
12e2a5fd 10896/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
10897
10898static int
dbbca37d 10899remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
10900 struct inferior *inf, const char *filename,
10901 int *remote_errno)
a6b151f1
DJ
10902{
10903 struct remote_state *rs = get_remote_state ();
10904 char *p = rs->buf;
10905 int left = get_remote_packet_size () - 1;
10906
15a201c8
GB
10907 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10908 return -1;
10909
a6b151f1
DJ
10910 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10911
10912 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10913 strlen (filename));
10914
10915 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10916 remote_errno, NULL, NULL);
10917}
10918
12e2a5fd 10919/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
10920
10921static char *
fab5aa7c 10922remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
10923 struct inferior *inf, const char *filename,
10924 int *remote_errno)
b9e7b9c3
UW
10925{
10926 struct remote_state *rs = get_remote_state ();
10927 char *p = rs->buf;
10928 char *attachment;
10929 int left = get_remote_packet_size ();
10930 int len, attachment_len;
10931 int read_len;
10932 char *ret;
10933
15a201c8
GB
10934 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10935 return NULL;
10936
b9e7b9c3
UW
10937 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10938
10939 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10940 strlen (filename));
10941
10942 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10943 remote_errno, &attachment,
10944 &attachment_len);
10945
10946 if (len < 0)
10947 return NULL;
10948
224c3ddb 10949 ret = (char *) xmalloc (len + 1);
b9e7b9c3 10950
bc20a4af
PA
10951 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10952 (gdb_byte *) ret, len);
b9e7b9c3
UW
10953 if (read_len != len)
10954 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10955
10956 ret[len] = '\0';
10957 return ret;
10958}
10959
12e2a5fd 10960/* Implementation of to_fileio_fstat. */
0a93529c
GB
10961
10962static int
10963remote_hostio_fstat (struct target_ops *self,
10964 int fd, struct stat *st,
10965 int *remote_errno)
10966{
10967 struct remote_state *rs = get_remote_state ();
10968 char *p = rs->buf;
10969 int left = get_remote_packet_size ();
10970 int attachment_len, ret;
10971 char *attachment;
10972 struct fio_stat fst;
10973 int read_len;
10974
464b0089
GB
10975 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10976
10977 remote_buffer_add_int (&p, &left, fd);
10978
10979 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10980 remote_errno, &attachment,
10981 &attachment_len);
10982 if (ret < 0)
0a93529c 10983 {
464b0089
GB
10984 if (*remote_errno != FILEIO_ENOSYS)
10985 return ret;
10986
0a93529c
GB
10987 /* Strictly we should return -1, ENOSYS here, but when
10988 "set sysroot remote:" was implemented in August 2008
10989 BFD's need for a stat function was sidestepped with
10990 this hack. This was not remedied until March 2015
10991 so we retain the previous behavior to avoid breaking
10992 compatibility.
10993
10994 Note that the memset is a March 2015 addition; older
10995 GDBs set st_size *and nothing else* so the structure
10996 would have garbage in all other fields. This might
10997 break something but retaining the previous behavior
10998 here would be just too wrong. */
10999
11000 memset (st, 0, sizeof (struct stat));
11001 st->st_size = INT_MAX;
11002 return 0;
11003 }
11004
0a93529c
GB
11005 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11006 (gdb_byte *) &fst, sizeof (fst));
11007
11008 if (read_len != ret)
11009 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11010
11011 if (read_len != sizeof (fst))
11012 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11013 read_len, (int) sizeof (fst));
11014
11015 remote_fileio_to_host_stat (&fst, st);
11016
11017 return 0;
11018}
11019
12e2a5fd 11020/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11021
11022static int
11023remote_filesystem_is_local (struct target_ops *self)
11024{
11025 /* Valgrind GDB presents itself as a remote target but works
11026 on the local filesystem: it does not implement remote get
11027 and users are not expected to set a sysroot. To handle
11028 this case we treat the remote filesystem as local if the
11029 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11030 does not support vFile:open. */
a3be80c3 11031 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11032 {
11033 enum packet_support ps = packet_support (PACKET_vFile_open);
11034
11035 if (ps == PACKET_SUPPORT_UNKNOWN)
11036 {
11037 int fd, remote_errno;
11038
11039 /* Try opening a file to probe support. The supplied
11040 filename is irrelevant, we only care about whether
11041 the stub recognizes the packet or not. */
07c138c8 11042 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11043 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11044 &remote_errno);
11045
11046 if (fd >= 0)
11047 remote_hostio_close (self, fd, &remote_errno);
11048
11049 ps = packet_support (PACKET_vFile_open);
11050 }
11051
11052 if (ps == PACKET_DISABLE)
11053 {
11054 static int warning_issued = 0;
11055
11056 if (!warning_issued)
11057 {
11058 warning (_("remote target does not support file"
11059 " transfer, attempting to access files"
11060 " from local filesystem."));
11061 warning_issued = 1;
11062 }
11063
11064 return 1;
11065 }
11066 }
11067
11068 return 0;
11069}
11070
a6b151f1
DJ
11071static int
11072remote_fileio_errno_to_host (int errnum)
11073{
11074 switch (errnum)
11075 {
11076 case FILEIO_EPERM:
11077 return EPERM;
11078 case FILEIO_ENOENT:
11079 return ENOENT;
11080 case FILEIO_EINTR:
11081 return EINTR;
11082 case FILEIO_EIO:
11083 return EIO;
11084 case FILEIO_EBADF:
11085 return EBADF;
11086 case FILEIO_EACCES:
11087 return EACCES;
11088 case FILEIO_EFAULT:
11089 return EFAULT;
11090 case FILEIO_EBUSY:
11091 return EBUSY;
11092 case FILEIO_EEXIST:
11093 return EEXIST;
11094 case FILEIO_ENODEV:
11095 return ENODEV;
11096 case FILEIO_ENOTDIR:
11097 return ENOTDIR;
11098 case FILEIO_EISDIR:
11099 return EISDIR;
11100 case FILEIO_EINVAL:
11101 return EINVAL;
11102 case FILEIO_ENFILE:
11103 return ENFILE;
11104 case FILEIO_EMFILE:
11105 return EMFILE;
11106 case FILEIO_EFBIG:
11107 return EFBIG;
11108 case FILEIO_ENOSPC:
11109 return ENOSPC;
11110 case FILEIO_ESPIPE:
11111 return ESPIPE;
11112 case FILEIO_EROFS:
11113 return EROFS;
11114 case FILEIO_ENOSYS:
11115 return ENOSYS;
11116 case FILEIO_ENAMETOOLONG:
11117 return ENAMETOOLONG;
11118 }
11119 return -1;
11120}
11121
11122static char *
11123remote_hostio_error (int errnum)
11124{
11125 int host_error = remote_fileio_errno_to_host (errnum);
11126
11127 if (host_error == -1)
11128 error (_("Unknown remote I/O error %d"), errnum);
11129 else
11130 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11131}
11132
a6b151f1
DJ
11133static void
11134remote_hostio_close_cleanup (void *opaque)
11135{
11136 int fd = *(int *) opaque;
11137 int remote_errno;
11138
df39ea25 11139 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11140}
11141
11142void
11143remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11144{
11145 struct cleanup *back_to, *close_cleanup;
11146 int retcode, fd, remote_errno, bytes, io_size;
11147 FILE *file;
11148 gdb_byte *buffer;
11149 int bytes_in_buffer;
11150 int saw_eof;
11151 ULONGEST offset;
5d93a237 11152 struct remote_state *rs = get_remote_state ();
a6b151f1 11153
5d93a237 11154 if (!rs->remote_desc)
a6b151f1
DJ
11155 error (_("command can only be used with remote target"));
11156
614c279d 11157 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11158 if (file == NULL)
11159 perror_with_name (local_file);
7c8a8b04 11160 back_to = make_cleanup_fclose (file);
a6b151f1 11161
07c138c8 11162 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11163 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11164 | FILEIO_O_TRUNC),
4313b8c0 11165 0700, 0, &remote_errno);
a6b151f1
DJ
11166 if (fd == -1)
11167 remote_hostio_error (remote_errno);
11168
11169 /* Send up to this many bytes at once. They won't all fit in the
11170 remote packet limit, so we'll transfer slightly fewer. */
11171 io_size = get_remote_packet_size ();
224c3ddb 11172 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11173 make_cleanup (xfree, buffer);
11174
11175 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11176
11177 bytes_in_buffer = 0;
11178 saw_eof = 0;
11179 offset = 0;
11180 while (bytes_in_buffer || !saw_eof)
11181 {
11182 if (!saw_eof)
11183 {
3e43a32a
MS
11184 bytes = fread (buffer + bytes_in_buffer, 1,
11185 io_size - bytes_in_buffer,
a6b151f1
DJ
11186 file);
11187 if (bytes == 0)
11188 {
11189 if (ferror (file))
11190 error (_("Error reading %s."), local_file);
11191 else
11192 {
11193 /* EOF. Unless there is something still in the
11194 buffer from the last iteration, we are done. */
11195 saw_eof = 1;
11196 if (bytes_in_buffer == 0)
11197 break;
11198 }
11199 }
11200 }
11201 else
11202 bytes = 0;
11203
11204 bytes += bytes_in_buffer;
11205 bytes_in_buffer = 0;
11206
0d866f62
TT
11207 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11208 fd, buffer, bytes,
3e43a32a 11209 offset, &remote_errno);
a6b151f1
DJ
11210
11211 if (retcode < 0)
11212 remote_hostio_error (remote_errno);
11213 else if (retcode == 0)
11214 error (_("Remote write of %d bytes returned 0!"), bytes);
11215 else if (retcode < bytes)
11216 {
11217 /* Short write. Save the rest of the read data for the next
11218 write. */
11219 bytes_in_buffer = bytes - retcode;
11220 memmove (buffer, buffer + retcode, bytes_in_buffer);
11221 }
11222
11223 offset += retcode;
11224 }
11225
11226 discard_cleanups (close_cleanup);
df39ea25 11227 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11228 remote_hostio_error (remote_errno);
11229
11230 if (from_tty)
11231 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11232 do_cleanups (back_to);
11233}
11234
11235void
11236remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11237{
11238 struct cleanup *back_to, *close_cleanup;
cea39f65 11239 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11240 FILE *file;
11241 gdb_byte *buffer;
11242 ULONGEST offset;
5d93a237 11243 struct remote_state *rs = get_remote_state ();
a6b151f1 11244
5d93a237 11245 if (!rs->remote_desc)
a6b151f1
DJ
11246 error (_("command can only be used with remote target"));
11247
07c138c8 11248 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11249 remote_file, FILEIO_O_RDONLY, 0, 0,
11250 &remote_errno);
a6b151f1
DJ
11251 if (fd == -1)
11252 remote_hostio_error (remote_errno);
11253
614c279d 11254 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11255 if (file == NULL)
11256 perror_with_name (local_file);
7c8a8b04 11257 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11258
11259 /* Send up to this many bytes at once. They won't all fit in the
11260 remote packet limit, so we'll transfer slightly fewer. */
11261 io_size = get_remote_packet_size ();
224c3ddb 11262 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11263 make_cleanup (xfree, buffer);
11264
11265 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11266
11267 offset = 0;
11268 while (1)
11269 {
a3be983c
TT
11270 bytes = remote_hostio_pread (find_target_at (process_stratum),
11271 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11272 if (bytes == 0)
11273 /* Success, but no bytes, means end-of-file. */
11274 break;
11275 if (bytes == -1)
11276 remote_hostio_error (remote_errno);
11277
11278 offset += bytes;
11279
11280 bytes = fwrite (buffer, 1, bytes, file);
11281 if (bytes == 0)
11282 perror_with_name (local_file);
11283 }
11284
11285 discard_cleanups (close_cleanup);
df39ea25 11286 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11287 remote_hostio_error (remote_errno);
11288
11289 if (from_tty)
11290 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11291 do_cleanups (back_to);
11292}
11293
11294void
11295remote_file_delete (const char *remote_file, int from_tty)
11296{
11297 int retcode, remote_errno;
5d93a237 11298 struct remote_state *rs = get_remote_state ();
a6b151f1 11299
5d93a237 11300 if (!rs->remote_desc)
a6b151f1
DJ
11301 error (_("command can only be used with remote target"));
11302
dbbca37d 11303 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11304 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11305 if (retcode == -1)
11306 remote_hostio_error (remote_errno);
11307
11308 if (from_tty)
11309 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11310}
11311
11312static void
11313remote_put_command (char *args, int from_tty)
11314{
11315 struct cleanup *back_to;
11316 char **argv;
11317
d1a41061
PP
11318 if (args == NULL)
11319 error_no_arg (_("file to put"));
11320
11321 argv = gdb_buildargv (args);
a6b151f1
DJ
11322 back_to = make_cleanup_freeargv (argv);
11323 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11324 error (_("Invalid parameters to remote put"));
11325
11326 remote_file_put (argv[0], argv[1], from_tty);
11327
11328 do_cleanups (back_to);
11329}
11330
11331static void
11332remote_get_command (char *args, int from_tty)
11333{
11334 struct cleanup *back_to;
11335 char **argv;
11336
d1a41061
PP
11337 if (args == NULL)
11338 error_no_arg (_("file to get"));
11339
11340 argv = gdb_buildargv (args);
a6b151f1
DJ
11341 back_to = make_cleanup_freeargv (argv);
11342 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11343 error (_("Invalid parameters to remote get"));
11344
11345 remote_file_get (argv[0], argv[1], from_tty);
11346
11347 do_cleanups (back_to);
11348}
11349
11350static void
11351remote_delete_command (char *args, int from_tty)
11352{
11353 struct cleanup *back_to;
11354 char **argv;
11355
d1a41061
PP
11356 if (args == NULL)
11357 error_no_arg (_("file to delete"));
11358
11359 argv = gdb_buildargv (args);
a6b151f1
DJ
11360 back_to = make_cleanup_freeargv (argv);
11361 if (argv[0] == NULL || argv[1] != NULL)
11362 error (_("Invalid parameters to remote delete"));
11363
11364 remote_file_delete (argv[0], from_tty);
11365
11366 do_cleanups (back_to);
11367}
11368
11369static void
11370remote_command (char *args, int from_tty)
11371{
635c7e8a 11372 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11373}
11374
b2175913 11375static int
19db3e69 11376remote_can_execute_reverse (struct target_ops *self)
b2175913 11377{
4082afcc
PA
11378 if (packet_support (PACKET_bs) == PACKET_ENABLE
11379 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11380 return 1;
11381 else
11382 return 0;
b2175913
MS
11383}
11384
74531fed 11385static int
2a9a2795 11386remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11387{
11388 return 1;
11389}
11390
03583c20 11391static int
2bfc0540 11392remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11393{
11394 /* Only supported in extended mode. */
11395 return 0;
11396}
11397
8a305172 11398static int
86ce2668 11399remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11400{
11401 struct remote_state *rs = get_remote_state ();
a744cf53 11402
901f9912
UW
11403 /* Only extended-remote handles being attached to multiple
11404 processes, even though plain remote can use the multi-process
11405 thread id extensions, so that GDB knows the target process's
11406 PID. */
11407 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
11408}
11409
70221824 11410static int
782b2b07
SS
11411remote_supports_cond_tracepoints (void)
11412{
4082afcc 11413 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11414}
11415
3788aec7 11416static int
efcc2da7 11417remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11418{
4082afcc 11419 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11420}
11421
70221824 11422static int
7a697b8d
SS
11423remote_supports_fast_tracepoints (void)
11424{
4082afcc 11425 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11426}
11427
0fb4aa4b
PA
11428static int
11429remote_supports_static_tracepoints (void)
11430{
4082afcc 11431 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11432}
11433
1e4d1764
YQ
11434static int
11435remote_supports_install_in_trace (void)
11436{
4082afcc 11437 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11438}
11439
d248b706 11440static int
7d178d6a 11441remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11442{
4082afcc
PA
11443 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11444 == PACKET_ENABLE);
d248b706
KY
11445}
11446
3065dfb6 11447static int
6de37a3a 11448remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11449{
4082afcc 11450 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11451}
11452
d3ce09f5 11453static int
78eff0ec 11454remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11455{
4082afcc 11456 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11457}
11458
35b1e5cc 11459static void
ecae04e1 11460remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11461{
11462 putpkt ("QTinit");
11463 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11464 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11465 error (_("Target does not support this command."));
11466}
11467
11468static void free_actions_list (char **actions_list);
11469static void free_actions_list_cleanup_wrapper (void *);
11470static void
11471free_actions_list_cleanup_wrapper (void *al)
11472{
19ba03f4 11473 free_actions_list ((char **) al);
35b1e5cc
SS
11474}
11475
11476static void
11477free_actions_list (char **actions_list)
11478{
11479 int ndx;
11480
11481 if (actions_list == 0)
11482 return;
11483
11484 for (ndx = 0; actions_list[ndx]; ndx++)
11485 xfree (actions_list[ndx]);
11486
11487 xfree (actions_list);
11488}
11489
409873ef
SS
11490/* Recursive routine to walk through command list including loops, and
11491 download packets for each command. */
11492
11493static void
11494remote_download_command_source (int num, ULONGEST addr,
11495 struct command_line *cmds)
11496{
11497 struct remote_state *rs = get_remote_state ();
11498 struct command_line *cmd;
11499
11500 for (cmd = cmds; cmd; cmd = cmd->next)
11501 {
0df8b418 11502 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11503 strcpy (rs->buf, "QTDPsrc:");
11504 encode_source_string (num, addr, "cmd", cmd->line,
11505 rs->buf + strlen (rs->buf),
11506 rs->buf_size - strlen (rs->buf));
11507 putpkt (rs->buf);
11508 remote_get_noisy_reply (&target_buf, &target_buf_size);
11509 if (strcmp (target_buf, "OK"))
11510 warning (_("Target does not support source download."));
11511
11512 if (cmd->control_type == while_control
11513 || cmd->control_type == while_stepping_control)
11514 {
11515 remote_download_command_source (num, addr, *cmd->body_list);
11516
0df8b418 11517 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11518 strcpy (rs->buf, "QTDPsrc:");
11519 encode_source_string (num, addr, "cmd", "end",
11520 rs->buf + strlen (rs->buf),
11521 rs->buf_size - strlen (rs->buf));
11522 putpkt (rs->buf);
11523 remote_get_noisy_reply (&target_buf, &target_buf_size);
11524 if (strcmp (target_buf, "OK"))
11525 warning (_("Target does not support source download."));
11526 }
11527 }
11528}
11529
35b1e5cc 11530static void
548f7808 11531remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11532{
bba74b36 11533#define BUF_SIZE 2048
e8ba3115 11534
35b1e5cc 11535 CORE_ADDR tpaddr;
409873ef 11536 char addrbuf[40];
bba74b36 11537 char buf[BUF_SIZE];
35b1e5cc
SS
11538 char **tdp_actions;
11539 char **stepping_actions;
11540 int ndx;
11541 struct cleanup *old_chain = NULL;
11542 struct agent_expr *aexpr;
11543 struct cleanup *aexpr_chain = NULL;
11544 char *pkt;
e8ba3115 11545 struct breakpoint *b = loc->owner;
d9b3f62e 11546 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11547
dc673c81 11548 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11549 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11550 tdp_actions);
11551 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11552 stepping_actions);
11553
11554 tpaddr = loc->address;
11555 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11556 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11557 addrbuf, /* address */
11558 (b->enable_state == bp_enabled ? 'E' : 'D'),
11559 t->step_count, t->pass_count);
e8ba3115
YQ
11560 /* Fast tracepoints are mostly handled by the target, but we can
11561 tell the target how big of an instruction block should be moved
11562 around. */
11563 if (b->type == bp_fast_tracepoint)
11564 {
11565 /* Only test for support at download time; we may not know
11566 target capabilities at definition time. */
11567 if (remote_supports_fast_tracepoints ())
35b1e5cc 11568 {
6b940e6a
PL
11569 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11570 NULL))
bba74b36 11571 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11572 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11573 else
e8ba3115
YQ
11574 /* If it passed validation at definition but fails now,
11575 something is very wrong. */
11576 internal_error (__FILE__, __LINE__,
11577 _("Fast tracepoint not "
11578 "valid during download"));
35b1e5cc 11579 }
e8ba3115
YQ
11580 else
11581 /* Fast tracepoints are functionally identical to regular
11582 tracepoints, so don't take lack of support as a reason to
11583 give up on the trace run. */
11584 warning (_("Target does not support fast tracepoints, "
11585 "downloading %d as regular tracepoint"), b->number);
11586 }
11587 else if (b->type == bp_static_tracepoint)
11588 {
11589 /* Only test for support at download time; we may not know
11590 target capabilities at definition time. */
11591 if (remote_supports_static_tracepoints ())
0fb4aa4b 11592 {
e8ba3115 11593 struct static_tracepoint_marker marker;
0fb4aa4b 11594
e8ba3115
YQ
11595 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11596 strcat (buf, ":S");
0fb4aa4b 11597 else
e8ba3115 11598 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11599 }
e8ba3115
YQ
11600 else
11601 /* Fast tracepoints are functionally identical to regular
11602 tracepoints, so don't take lack of support as a reason
11603 to give up on the trace run. */
11604 error (_("Target does not support static tracepoints"));
11605 }
11606 /* If the tracepoint has a conditional, make it into an agent
11607 expression and append to the definition. */
11608 if (loc->cond)
11609 {
11610 /* Only test support at download time, we may not know target
11611 capabilities at definition time. */
11612 if (remote_supports_cond_tracepoints ())
35b1e5cc 11613 {
e8ba3115
YQ
11614 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11615 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11616 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11617 aexpr->len);
e8ba3115
YQ
11618 pkt = buf + strlen (buf);
11619 for (ndx = 0; ndx < aexpr->len; ++ndx)
11620 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11621 *pkt = '\0';
11622 do_cleanups (aexpr_chain);
35b1e5cc 11623 }
e8ba3115
YQ
11624 else
11625 warning (_("Target does not support conditional tracepoints, "
11626 "ignoring tp %d cond"), b->number);
11627 }
35b1e5cc 11628
d9b3f62e 11629 if (b->commands || *default_collect)
e8ba3115
YQ
11630 strcat (buf, "-");
11631 putpkt (buf);
11632 remote_get_noisy_reply (&target_buf, &target_buf_size);
11633 if (strcmp (target_buf, "OK"))
11634 error (_("Target does not support tracepoints."));
35b1e5cc 11635
e8ba3115
YQ
11636 /* do_single_steps (t); */
11637 if (tdp_actions)
11638 {
11639 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11640 {
e8ba3115 11641 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11642 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11643 b->number, addrbuf, /* address */
11644 tdp_actions[ndx],
11645 ((tdp_actions[ndx + 1] || stepping_actions)
11646 ? '-' : 0));
e8ba3115
YQ
11647 putpkt (buf);
11648 remote_get_noisy_reply (&target_buf,
11649 &target_buf_size);
11650 if (strcmp (target_buf, "OK"))
11651 error (_("Error on target while setting tracepoints."));
35b1e5cc 11652 }
e8ba3115
YQ
11653 }
11654 if (stepping_actions)
11655 {
11656 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11657 {
e8ba3115 11658 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11659 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11660 b->number, addrbuf, /* address */
11661 ((ndx == 0) ? "S" : ""),
11662 stepping_actions[ndx],
11663 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11664 putpkt (buf);
11665 remote_get_noisy_reply (&target_buf,
11666 &target_buf_size);
11667 if (strcmp (target_buf, "OK"))
11668 error (_("Error on target while setting tracepoints."));
35b1e5cc 11669 }
e8ba3115 11670 }
409873ef 11671
4082afcc 11672 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11673 {
f00aae0f 11674 if (b->location != NULL)
409873ef 11675 {
e8ba3115 11676 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11677 encode_source_string (b->number, loc->address, "at",
11678 event_location_to_string (b->location),
11679 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11680 putpkt (buf);
11681 remote_get_noisy_reply (&target_buf, &target_buf_size);
11682 if (strcmp (target_buf, "OK"))
11683 warning (_("Target does not support source download."));
409873ef 11684 }
e8ba3115
YQ
11685 if (b->cond_string)
11686 {
11687 strcpy (buf, "QTDPsrc:");
11688 encode_source_string (b->number, loc->address,
11689 "cond", b->cond_string, buf + strlen (buf),
11690 2048 - strlen (buf));
11691 putpkt (buf);
11692 remote_get_noisy_reply (&target_buf, &target_buf_size);
11693 if (strcmp (target_buf, "OK"))
11694 warning (_("Target does not support source download."));
11695 }
11696 remote_download_command_source (b->number, loc->address,
11697 breakpoint_commands (b));
35b1e5cc 11698 }
e8ba3115
YQ
11699
11700 do_cleanups (old_chain);
35b1e5cc
SS
11701}
11702
1e4d1764 11703static int
a52a8357 11704remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 11705{
1e51243a
PA
11706 struct remote_state *rs = get_remote_state ();
11707 struct trace_status *ts;
11708 int status;
11709
11710 /* Don't try to install tracepoints until we've relocated our
11711 symbols, and fetched and merged the target's tracepoint list with
11712 ours. */
11713 if (rs->starting_up)
11714 return 0;
11715
11716 ts = current_trace_status ();
8bd200f1 11717 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
11718
11719 if (status == -1 || !ts->running_known || !ts->running)
11720 return 0;
11721
11722 /* If we are in a tracing experiment, but remote stub doesn't support
11723 installing tracepoint in trace, we have to return. */
11724 if (!remote_supports_install_in_trace ())
11725 return 0;
11726
11727 return 1;
11728}
11729
11730
35b1e5cc 11731static void
559d2b81
TT
11732remote_download_trace_state_variable (struct target_ops *self,
11733 struct trace_state_variable *tsv)
35b1e5cc
SS
11734{
11735 struct remote_state *rs = get_remote_state ();
00bf0b85 11736 char *p;
35b1e5cc 11737
bba74b36
YQ
11738 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11739 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11740 tsv->builtin);
00bf0b85
SS
11741 p = rs->buf + strlen (rs->buf);
11742 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11743 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 11744 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 11745 *p++ = '\0';
35b1e5cc
SS
11746 putpkt (rs->buf);
11747 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11748 if (*target_buf == '\0')
11749 error (_("Target does not support this command."));
11750 if (strcmp (target_buf, "OK") != 0)
11751 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
11752}
11753
d248b706 11754static void
46670d57
TT
11755remote_enable_tracepoint (struct target_ops *self,
11756 struct bp_location *location)
d248b706
KY
11757{
11758 struct remote_state *rs = get_remote_state ();
11759 char addr_buf[40];
11760
11761 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11762 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11763 location->owner->number, addr_buf);
d248b706
KY
11764 putpkt (rs->buf);
11765 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11766 if (*rs->buf == '\0')
11767 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11768 if (strcmp (rs->buf, "OK") != 0)
11769 error (_("Error on target while enabling tracepoint."));
11770}
11771
11772static void
780b049c
TT
11773remote_disable_tracepoint (struct target_ops *self,
11774 struct bp_location *location)
d248b706
KY
11775{
11776 struct remote_state *rs = get_remote_state ();
11777 char addr_buf[40];
11778
11779 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11780 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11781 location->owner->number, addr_buf);
d248b706
KY
11782 putpkt (rs->buf);
11783 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11784 if (*rs->buf == '\0')
11785 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11786 if (strcmp (rs->buf, "OK") != 0)
11787 error (_("Error on target while disabling tracepoint."));
11788}
11789
35b1e5cc 11790static void
583f9a86 11791remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
11792{
11793 asection *s;
81b9b86e 11794 bfd *abfd = NULL;
35b1e5cc 11795 bfd_size_type size;
608bcef2 11796 bfd_vma vma;
35b1e5cc 11797 int anysecs = 0;
c2fa21f1 11798 int offset = 0;
35b1e5cc
SS
11799
11800 if (!exec_bfd)
11801 return; /* No information to give. */
11802
11803 strcpy (target_buf, "QTro");
9779ab84 11804 offset = strlen (target_buf);
35b1e5cc
SS
11805 for (s = exec_bfd->sections; s; s = s->next)
11806 {
11807 char tmp1[40], tmp2[40];
c2fa21f1 11808 int sec_length;
35b1e5cc
SS
11809
11810 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 11811 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
11812 (s->flags & SEC_READONLY) == 0)
11813 continue;
11814
11815 anysecs = 1;
81b9b86e 11816 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 11817 size = bfd_get_section_size (s);
608bcef2
HZ
11818 sprintf_vma (tmp1, vma);
11819 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
11820 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11821 if (offset + sec_length + 1 > target_buf_size)
11822 {
4082afcc 11823 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 11824 warning (_("\
c2fa21f1
HZ
11825Too many sections for read-only sections definition packet."));
11826 break;
11827 }
bba74b36
YQ
11828 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11829 tmp1, tmp2);
c2fa21f1 11830 offset += sec_length;
35b1e5cc
SS
11831 }
11832 if (anysecs)
11833 {
11834 putpkt (target_buf);
11835 getpkt (&target_buf, &target_buf_size, 0);
11836 }
11837}
11838
11839static void
e2d1aae3 11840remote_trace_start (struct target_ops *self)
35b1e5cc
SS
11841{
11842 putpkt ("QTStart");
11843 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11844 if (*target_buf == '\0')
11845 error (_("Target does not support this command."));
11846 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11847 error (_("Bogus reply from target: %s"), target_buf);
11848}
11849
11850static int
8bd200f1 11851remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 11852{
953b98d1 11853 /* Initialize it just to avoid a GCC false warning. */
f652de6f 11854 char *p = NULL;
0df8b418 11855 /* FIXME we need to get register block size some other way. */
00bf0b85 11856 extern int trace_regblock_size;
bd3eecc3
PA
11857 enum packet_result result;
11858
4082afcc 11859 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 11860 return -1;
a744cf53 11861
00bf0b85
SS
11862 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11863
049dc89b
JK
11864 putpkt ("qTStatus");
11865
492d29ea 11866 TRY
67f41397
JK
11867 {
11868 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11869 }
492d29ea 11870 CATCH (ex, RETURN_MASK_ERROR)
67f41397 11871 {
598d3636
JK
11872 if (ex.error != TARGET_CLOSE_ERROR)
11873 {
11874 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11875 return -1;
11876 }
11877 throw_exception (ex);
67f41397 11878 }
492d29ea 11879 END_CATCH
00bf0b85 11880
bd3eecc3
PA
11881 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11882
00bf0b85 11883 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 11884 if (result == PACKET_UNKNOWN)
00bf0b85 11885 return -1;
35b1e5cc 11886
00bf0b85 11887 /* We're working with a live target. */
f5911ea1 11888 ts->filename = NULL;
00bf0b85 11889
00bf0b85 11890 if (*p++ != 'T')
35b1e5cc
SS
11891 error (_("Bogus trace status reply from target: %s"), target_buf);
11892
84cebc4a
YQ
11893 /* Function 'parse_trace_status' sets default value of each field of
11894 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
11895 parse_trace_status (p, ts);
11896
11897 return ts->running;
35b1e5cc
SS
11898}
11899
70221824 11900static void
db90e85c 11901remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
11902 struct uploaded_tp *utp)
11903{
11904 struct remote_state *rs = get_remote_state ();
f196051f
SS
11905 char *reply;
11906 struct bp_location *loc;
11907 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 11908 size_t size = get_remote_packet_size ();
f196051f
SS
11909
11910 if (tp)
11911 {
11912 tp->base.hit_count = 0;
11913 tp->traceframe_usage = 0;
11914 for (loc = tp->base.loc; loc; loc = loc->next)
11915 {
11916 /* If the tracepoint was never downloaded, don't go asking for
11917 any status. */
11918 if (tp->number_on_target == 0)
11919 continue;
bba74b36
YQ
11920 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11921 phex_nz (loc->address, 0));
f196051f
SS
11922 putpkt (rs->buf);
11923 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11924 if (reply && *reply)
11925 {
11926 if (*reply == 'V')
11927 parse_tracepoint_status (reply + 1, bp, utp);
11928 }
11929 }
11930 }
11931 else if (utp)
11932 {
11933 utp->hit_count = 0;
11934 utp->traceframe_usage = 0;
bba74b36
YQ
11935 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11936 phex_nz (utp->addr, 0));
f196051f
SS
11937 putpkt (rs->buf);
11938 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11939 if (reply && *reply)
11940 {
11941 if (*reply == 'V')
11942 parse_tracepoint_status (reply + 1, bp, utp);
11943 }
11944 }
11945}
11946
35b1e5cc 11947static void
74499f1b 11948remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
11949{
11950 putpkt ("QTStop");
11951 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11952 if (*target_buf == '\0')
11953 error (_("Target does not support this command."));
11954 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11955 error (_("Bogus reply from target: %s"), target_buf);
11956}
11957
11958static int
bd4c6793
TT
11959remote_trace_find (struct target_ops *self,
11960 enum trace_find_type type, int num,
cc5925ad 11961 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
11962 int *tpp)
11963{
11964 struct remote_state *rs = get_remote_state ();
bba74b36 11965 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
11966 char *p, *reply;
11967 int target_frameno = -1, target_tracept = -1;
11968
e6e4e701
PA
11969 /* Lookups other than by absolute frame number depend on the current
11970 trace selected, so make sure it is correct on the remote end
11971 first. */
11972 if (type != tfind_number)
11973 set_remote_traceframe ();
11974
35b1e5cc
SS
11975 p = rs->buf;
11976 strcpy (p, "QTFrame:");
11977 p = strchr (p, '\0');
11978 switch (type)
11979 {
11980 case tfind_number:
bba74b36 11981 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
11982 break;
11983 case tfind_pc:
bba74b36 11984 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
11985 break;
11986 case tfind_tp:
bba74b36 11987 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
11988 break;
11989 case tfind_range:
bba74b36
YQ
11990 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11991 phex_nz (addr2, 0));
35b1e5cc
SS
11992 break;
11993 case tfind_outside:
bba74b36
YQ
11994 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11995 phex_nz (addr2, 0));
35b1e5cc
SS
11996 break;
11997 default:
9b20d036 11998 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
11999 }
12000
12001 putpkt (rs->buf);
2f65bcb7 12002 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12003 if (*reply == '\0')
12004 error (_("Target does not support this command."));
35b1e5cc
SS
12005
12006 while (reply && *reply)
12007 switch (*reply)
12008 {
12009 case 'F':
f197e0f1
VP
12010 p = ++reply;
12011 target_frameno = (int) strtol (p, &reply, 16);
12012 if (reply == p)
12013 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12014 /* Don't update our remote traceframe number cache on failure
12015 to select a remote traceframe. */
f197e0f1
VP
12016 if (target_frameno == -1)
12017 return -1;
35b1e5cc
SS
12018 break;
12019 case 'T':
f197e0f1
VP
12020 p = ++reply;
12021 target_tracept = (int) strtol (p, &reply, 16);
12022 if (reply == p)
12023 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12024 break;
12025 case 'O': /* "OK"? */
12026 if (reply[1] == 'K' && reply[2] == '\0')
12027 reply += 2;
12028 else
12029 error (_("Bogus reply from target: %s"), reply);
12030 break;
12031 default:
12032 error (_("Bogus reply from target: %s"), reply);
12033 }
12034 if (tpp)
12035 *tpp = target_tracept;
e6e4e701 12036
262e1174 12037 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12038 return target_frameno;
12039}
12040
12041static int
4011015b
TT
12042remote_get_trace_state_variable_value (struct target_ops *self,
12043 int tsvnum, LONGEST *val)
35b1e5cc
SS
12044{
12045 struct remote_state *rs = get_remote_state ();
12046 char *reply;
12047 ULONGEST uval;
12048
e6e4e701
PA
12049 set_remote_traceframe ();
12050
bba74b36 12051 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12052 putpkt (rs->buf);
12053 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12054 if (reply && *reply)
12055 {
12056 if (*reply == 'V')
12057 {
12058 unpack_varlen_hex (reply + 1, &uval);
12059 *val = (LONGEST) uval;
12060 return 1;
12061 }
12062 }
12063 return 0;
12064}
12065
00bf0b85 12066static int
dc3decaf 12067remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12068{
12069 struct remote_state *rs = get_remote_state ();
12070 char *p, *reply;
12071
12072 p = rs->buf;
12073 strcpy (p, "QTSave:");
12074 p += strlen (p);
12075 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12076 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12077 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12078 *p++ = '\0';
12079 putpkt (rs->buf);
ad91cd99 12080 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12081 if (*reply == '\0')
ad91cd99
PA
12082 error (_("Target does not support this command."));
12083 if (strcmp (reply, "OK") != 0)
12084 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12085 return 0;
12086}
12087
12088/* This is basically a memory transfer, but needs to be its own packet
12089 because we don't know how the target actually organizes its trace
12090 memory, plus we want to be able to ask for as much as possible, but
12091 not be unhappy if we don't get as much as we ask for. */
12092
12093static LONGEST
88ee6f45
TT
12094remote_get_raw_trace_data (struct target_ops *self,
12095 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12096{
12097 struct remote_state *rs = get_remote_state ();
12098 char *reply;
12099 char *p;
12100 int rslt;
12101
12102 p = rs->buf;
12103 strcpy (p, "qTBuffer:");
12104 p += strlen (p);
12105 p += hexnumstr (p, offset);
12106 *p++ = ',';
12107 p += hexnumstr (p, len);
12108 *p++ = '\0';
12109
12110 putpkt (rs->buf);
12111 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12112 if (reply && *reply)
12113 {
12114 /* 'l' by itself means we're at the end of the buffer and
12115 there is nothing more to get. */
12116 if (*reply == 'l')
12117 return 0;
12118
12119 /* Convert the reply into binary. Limit the number of bytes to
12120 convert according to our passed-in buffer size, rather than
12121 what was returned in the packet; if the target is
12122 unexpectedly generous and gives us a bigger reply than we
12123 asked for, we don't want to crash. */
12124 rslt = hex2bin (target_buf, buf, len);
12125 return rslt;
12126 }
12127
12128 /* Something went wrong, flag as an error. */
12129 return -1;
12130}
12131
35b1e5cc 12132static void
37b25738 12133remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12134{
12135 struct remote_state *rs = get_remote_state ();
12136
4082afcc 12137 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12138 {
ad91cd99
PA
12139 char *reply;
12140
bba74b36 12141 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12142 putpkt (rs->buf);
ad91cd99
PA
12143 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12144 if (*reply == '\0')
33da3f1c 12145 error (_("Target does not support this command."));
ad91cd99
PA
12146 if (strcmp (reply, "OK") != 0)
12147 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12148 }
12149 else if (val)
12150 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12151}
12152
dc146f7c
VP
12153static int
12154remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12155{
12156 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12157
fe978cb0
PA
12158 if (info && info->priv)
12159 return info->priv->core;
dc146f7c
VP
12160 return -1;
12161}
12162
4daf5ac0 12163static void
736d5b1f 12164remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12165{
12166 struct remote_state *rs = get_remote_state ();
ad91cd99 12167 char *reply;
4daf5ac0 12168
bba74b36 12169 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12170 putpkt (rs->buf);
ad91cd99
PA
12171 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12172 if (*reply == '\0')
4daf5ac0 12173 error (_("Target does not support this command."));
ad91cd99
PA
12174 if (strcmp (reply, "OK") != 0)
12175 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12176}
12177
b3b9301e 12178static struct traceframe_info *
a893e81f 12179remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12180{
12181 char *text;
12182
12183 text = target_read_stralloc (&current_target,
12184 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12185 if (text != NULL)
12186 {
12187 struct traceframe_info *info;
12188 struct cleanup *back_to = make_cleanup (xfree, text);
12189
12190 info = parse_traceframe_info (text);
12191 do_cleanups (back_to);
12192 return info;
12193 }
12194
12195 return NULL;
12196}
12197
405f8e94
SS
12198/* Handle the qTMinFTPILen packet. Returns the minimum length of
12199 instruction on which a fast tracepoint may be placed. Returns -1
12200 if the packet is not supported, and 0 if the minimum instruction
12201 length is unknown. */
12202
12203static int
0e67620a 12204remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12205{
12206 struct remote_state *rs = get_remote_state ();
12207 char *reply;
12208
e886a173
PA
12209 /* If we're not debugging a process yet, the IPA can't be
12210 loaded. */
12211 if (!target_has_execution)
12212 return 0;
12213
12214 /* Make sure the remote is pointing at the right process. */
12215 set_general_process ();
12216
bba74b36 12217 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12218 putpkt (rs->buf);
12219 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12220 if (*reply == '\0')
12221 return -1;
12222 else
12223 {
12224 ULONGEST min_insn_len;
12225
12226 unpack_varlen_hex (reply, &min_insn_len);
12227
12228 return (int) min_insn_len;
12229 }
12230}
12231
f6f899bf 12232static void
4da384be 12233remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12234{
4082afcc 12235 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12236 {
12237 struct remote_state *rs = get_remote_state ();
12238 char *buf = rs->buf;
12239 char *endbuf = rs->buf + get_remote_packet_size ();
12240 enum packet_result result;
12241
12242 gdb_assert (val >= 0 || val == -1);
12243 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12244 /* Send -1 as literal "-1" to avoid host size dependency. */
12245 if (val < 0)
12246 {
12247 *buf++ = '-';
12248 buf += hexnumstr (buf, (ULONGEST) -val);
12249 }
12250 else
12251 buf += hexnumstr (buf, (ULONGEST) val);
12252
12253 putpkt (rs->buf);
12254 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12255 result = packet_ok (rs->buf,
12256 &remote_protocol_packets[PACKET_QTBuffer_size]);
12257
12258 if (result != PACKET_OK)
12259 warning (_("Bogus reply from target: %s"), rs->buf);
12260 }
12261}
12262
f196051f 12263static int
d9e68a2c
TT
12264remote_set_trace_notes (struct target_ops *self,
12265 const char *user, const char *notes,
ca623f82 12266 const char *stop_notes)
f196051f
SS
12267{
12268 struct remote_state *rs = get_remote_state ();
12269 char *reply;
12270 char *buf = rs->buf;
12271 char *endbuf = rs->buf + get_remote_packet_size ();
12272 int nbytes;
12273
12274 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12275 if (user)
12276 {
12277 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12278 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12279 buf += 2 * nbytes;
12280 *buf++ = ';';
12281 }
12282 if (notes)
12283 {
12284 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12285 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12286 buf += 2 * nbytes;
12287 *buf++ = ';';
12288 }
12289 if (stop_notes)
12290 {
12291 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12292 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12293 buf += 2 * nbytes;
12294 *buf++ = ';';
12295 }
12296 /* Ensure the buffer is terminated. */
12297 *buf = '\0';
12298
12299 putpkt (rs->buf);
12300 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12301 if (*reply == '\0')
12302 return 0;
12303
12304 if (strcmp (reply, "OK") != 0)
12305 error (_("Bogus reply from target: %s"), reply);
12306
12307 return 1;
12308}
12309
d1feda86 12310static int
2c152180 12311remote_use_agent (struct target_ops *self, int use)
d1feda86 12312{
4082afcc 12313 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12314 {
12315 struct remote_state *rs = get_remote_state ();
12316
12317 /* If the stub supports QAgent. */
bba74b36 12318 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12319 putpkt (rs->buf);
12320 getpkt (&rs->buf, &rs->buf_size, 0);
12321
12322 if (strcmp (rs->buf, "OK") == 0)
12323 {
12324 use_agent = use;
12325 return 1;
12326 }
12327 }
12328
12329 return 0;
12330}
12331
12332static int
fe38f897 12333remote_can_use_agent (struct target_ops *self)
d1feda86 12334{
4082afcc 12335 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12336}
12337
9accd112
MM
12338struct btrace_target_info
12339{
12340 /* The ptid of the traced thread. */
12341 ptid_t ptid;
f4abbc16
MM
12342
12343 /* The obtained branch trace configuration. */
12344 struct btrace_config conf;
9accd112
MM
12345};
12346
f4abbc16
MM
12347/* Reset our idea of our target's btrace configuration. */
12348
12349static void
12350remote_btrace_reset (void)
12351{
12352 struct remote_state *rs = get_remote_state ();
12353
12354 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12355}
12356
9accd112
MM
12357/* Check whether the target supports branch tracing. */
12358
12359static int
043c3577 12360remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12361{
4082afcc 12362 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12363 return 0;
4082afcc 12364 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12365 return 0;
12366
043c3577
MM
12367 switch (format)
12368 {
12369 case BTRACE_FORMAT_NONE:
12370 return 0;
12371
12372 case BTRACE_FORMAT_BTS:
12373 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12374
12375 case BTRACE_FORMAT_PT:
12376 /* The trace is decoded on the host. Even if our target supports it,
12377 we still need to have libipt to decode the trace. */
12378#if defined (HAVE_LIBIPT)
12379 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12380#else /* !defined (HAVE_LIBIPT) */
12381 return 0;
12382#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12383 }
12384
12385 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12386}
12387
f4abbc16
MM
12388/* Synchronize the configuration with the target. */
12389
12390static void
12391btrace_sync_conf (const struct btrace_config *conf)
12392{
d33501a5
MM
12393 struct packet_config *packet;
12394 struct remote_state *rs;
12395 char *buf, *pos, *endbuf;
12396
12397 rs = get_remote_state ();
12398 buf = rs->buf;
12399 endbuf = buf + get_remote_packet_size ();
12400
12401 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12402 if (packet_config_support (packet) == PACKET_ENABLE
12403 && conf->bts.size != rs->btrace_config.bts.size)
12404 {
12405 pos = buf;
12406 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12407 conf->bts.size);
12408
12409 putpkt (buf);
12410 getpkt (&buf, &rs->buf_size, 0);
12411
12412 if (packet_ok (buf, packet) == PACKET_ERROR)
12413 {
12414 if (buf[0] == 'E' && buf[1] == '.')
12415 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12416 else
12417 error (_("Failed to configure the BTS buffer size."));
12418 }
12419
12420 rs->btrace_config.bts.size = conf->bts.size;
12421 }
b20a6524
MM
12422
12423 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12424 if (packet_config_support (packet) == PACKET_ENABLE
12425 && conf->pt.size != rs->btrace_config.pt.size)
12426 {
12427 pos = buf;
12428 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12429 conf->pt.size);
12430
12431 putpkt (buf);
12432 getpkt (&buf, &rs->buf_size, 0);
12433
12434 if (packet_ok (buf, packet) == PACKET_ERROR)
12435 {
12436 if (buf[0] == 'E' && buf[1] == '.')
12437 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12438 else
12439 error (_("Failed to configure the trace buffer size."));
12440 }
12441
12442 rs->btrace_config.pt.size = conf->pt.size;
12443 }
f4abbc16
MM
12444}
12445
12446/* Read the current thread's btrace configuration from the target and
12447 store it into CONF. */
12448
12449static void
12450btrace_read_config (struct btrace_config *conf)
12451{
12452 char *xml;
12453
12454 xml = target_read_stralloc (&current_target,
b20a6524 12455 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12456 if (xml != NULL)
12457 {
12458 struct cleanup *cleanup;
12459
12460 cleanup = make_cleanup (xfree, xml);
12461 parse_xml_btrace_conf (conf, xml);
12462 do_cleanups (cleanup);
12463 }
12464}
12465
9accd112
MM
12466/* Enable branch tracing. */
12467
12468static struct btrace_target_info *
f4abbc16
MM
12469remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12470 const struct btrace_config *conf)
9accd112
MM
12471{
12472 struct btrace_target_info *tinfo = NULL;
b20a6524 12473 struct packet_config *packet = NULL;
9accd112
MM
12474 struct remote_state *rs = get_remote_state ();
12475 char *buf = rs->buf;
12476 char *endbuf = rs->buf + get_remote_packet_size ();
12477
b20a6524
MM
12478 switch (conf->format)
12479 {
12480 case BTRACE_FORMAT_BTS:
12481 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12482 break;
12483
12484 case BTRACE_FORMAT_PT:
12485 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12486 break;
12487 }
12488
12489 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12490 error (_("Target does not support branch tracing."));
12491
f4abbc16
MM
12492 btrace_sync_conf (conf);
12493
9accd112
MM
12494 set_general_thread (ptid);
12495
12496 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12497 putpkt (rs->buf);
12498 getpkt (&rs->buf, &rs->buf_size, 0);
12499
12500 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12501 {
12502 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12503 error (_("Could not enable branch tracing for %s: %s"),
12504 target_pid_to_str (ptid), rs->buf + 2);
12505 else
12506 error (_("Could not enable branch tracing for %s."),
12507 target_pid_to_str (ptid));
12508 }
12509
8d749320 12510 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12511 tinfo->ptid = ptid;
12512
f4abbc16
MM
12513 /* If we fail to read the configuration, we lose some information, but the
12514 tracing itself is not impacted. */
492d29ea
PA
12515 TRY
12516 {
12517 btrace_read_config (&tinfo->conf);
12518 }
12519 CATCH (err, RETURN_MASK_ERROR)
12520 {
12521 if (err.message != NULL)
12522 warning ("%s", err.message);
12523 }
12524 END_CATCH
f4abbc16 12525
9accd112
MM
12526 return tinfo;
12527}
12528
12529/* Disable branch tracing. */
12530
12531static void
25e95349
TT
12532remote_disable_btrace (struct target_ops *self,
12533 struct btrace_target_info *tinfo)
9accd112
MM
12534{
12535 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12536 struct remote_state *rs = get_remote_state ();
12537 char *buf = rs->buf;
12538 char *endbuf = rs->buf + get_remote_packet_size ();
12539
4082afcc 12540 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12541 error (_("Target does not support branch tracing."));
12542
12543 set_general_thread (tinfo->ptid);
12544
12545 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12546 putpkt (rs->buf);
12547 getpkt (&rs->buf, &rs->buf_size, 0);
12548
12549 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12550 {
12551 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12552 error (_("Could not disable branch tracing for %s: %s"),
12553 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12554 else
12555 error (_("Could not disable branch tracing for %s."),
12556 target_pid_to_str (tinfo->ptid));
12557 }
12558
12559 xfree (tinfo);
12560}
12561
12562/* Teardown branch tracing. */
12563
12564static void
1777056d
TT
12565remote_teardown_btrace (struct target_ops *self,
12566 struct btrace_target_info *tinfo)
9accd112
MM
12567{
12568 /* We must not talk to the target during teardown. */
12569 xfree (tinfo);
12570}
12571
12572/* Read the branch trace. */
12573
969c39fb 12574static enum btrace_error
39c49f83 12575remote_read_btrace (struct target_ops *self,
734b0e4b 12576 struct btrace_data *btrace,
969c39fb 12577 struct btrace_target_info *tinfo,
9accd112
MM
12578 enum btrace_read_type type)
12579{
12580 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12581 struct remote_state *rs = get_remote_state ();
969c39fb 12582 struct cleanup *cleanup;
9accd112
MM
12583 const char *annex;
12584 char *xml;
12585
4082afcc 12586 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12587 error (_("Target does not support branch tracing."));
12588
12589#if !defined(HAVE_LIBEXPAT)
12590 error (_("Cannot process branch tracing result. XML parsing not supported."));
12591#endif
12592
12593 switch (type)
12594 {
864089d2 12595 case BTRACE_READ_ALL:
9accd112
MM
12596 annex = "all";
12597 break;
864089d2 12598 case BTRACE_READ_NEW:
9accd112
MM
12599 annex = "new";
12600 break;
969c39fb
MM
12601 case BTRACE_READ_DELTA:
12602 annex = "delta";
12603 break;
9accd112
MM
12604 default:
12605 internal_error (__FILE__, __LINE__,
12606 _("Bad branch tracing read type: %u."),
12607 (unsigned int) type);
12608 }
12609
12610 xml = target_read_stralloc (&current_target,
b20a6524 12611 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12612 if (xml == NULL)
12613 return BTRACE_ERR_UNKNOWN;
9accd112 12614
969c39fb 12615 cleanup = make_cleanup (xfree, xml);
734b0e4b 12616 parse_xml_btrace (btrace, xml);
969c39fb 12617 do_cleanups (cleanup);
9accd112 12618
969c39fb 12619 return BTRACE_ERR_NONE;
9accd112
MM
12620}
12621
f4abbc16
MM
12622static const struct btrace_config *
12623remote_btrace_conf (struct target_ops *self,
12624 const struct btrace_target_info *tinfo)
12625{
12626 return &tinfo->conf;
12627}
12628
ced63ec0 12629static int
5436ff03 12630remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12631{
4082afcc
PA
12632 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12633 == PACKET_ENABLE);
ced63ec0
GB
12634}
12635
9dd130a0
TT
12636/* Implementation of to_load. */
12637
12638static void
9cbe5fff 12639remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12640{
12641 generic_load (name, from_tty);
12642}
12643
c78fa86a
GB
12644/* Accepts an integer PID; returns a string representing a file that
12645 can be opened on the remote side to get the symbols for the child
12646 process. Returns NULL if the operation is not supported. */
12647
12648static char *
12649remote_pid_to_exec_file (struct target_ops *self, int pid)
12650{
12651 static char *filename = NULL;
835205d0
GB
12652 struct inferior *inf;
12653 char *annex = NULL;
c78fa86a
GB
12654
12655 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12656 return NULL;
12657
12658 if (filename != NULL)
12659 xfree (filename);
12660
835205d0
GB
12661 inf = find_inferior_pid (pid);
12662 if (inf == NULL)
12663 internal_error (__FILE__, __LINE__,
12664 _("not currently attached to process %d"), pid);
12665
12666 if (!inf->fake_pid_p)
12667 {
12668 const int annex_size = 9;
12669
224c3ddb 12670 annex = (char *) alloca (annex_size);
835205d0
GB
12671 xsnprintf (annex, annex_size, "%x", pid);
12672 }
12673
c78fa86a
GB
12674 filename = target_read_stralloc (&current_target,
12675 TARGET_OBJECT_EXEC_FILE, annex);
12676
12677 return filename;
12678}
12679
750ce8d1
YQ
12680/* Implement the to_can_do_single_step target_ops method. */
12681
12682static int
12683remote_can_do_single_step (struct target_ops *ops)
12684{
12685 /* We can only tell whether target supports single step or not by
12686 supported s and S vCont actions if the stub supports vContSupported
12687 feature. If the stub doesn't support vContSupported feature,
12688 we have conservatively to think target doesn't supports single
12689 step. */
12690 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12691 {
12692 struct remote_state *rs = get_remote_state ();
12693
12694 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12695 remote_vcont_probe (rs);
12696
12697 return rs->supports_vCont.s && rs->supports_vCont.S;
12698 }
12699 else
12700 return 0;
12701}
12702
c906108c 12703static void
fba45db2 12704init_remote_ops (void)
c906108c 12705{
c5aa993b 12706 remote_ops.to_shortname = "remote";
c906108c 12707 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 12708 remote_ops.to_doc =
c906108c 12709 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
12710Specify the serial device it is connected to\n\
12711(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
12712 remote_ops.to_open = remote_open;
12713 remote_ops.to_close = remote_close;
c906108c 12714 remote_ops.to_detach = remote_detach;
6ad8ae5c 12715 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 12716 remote_ops.to_resume = remote_resume;
c906108c
SS
12717 remote_ops.to_wait = remote_wait;
12718 remote_ops.to_fetch_registers = remote_fetch_registers;
12719 remote_ops.to_store_registers = remote_store_registers;
12720 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 12721 remote_ops.to_files_info = remote_files_info;
c906108c
SS
12722 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12723 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
12724 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12725 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12726 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12727 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
12728 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12729 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
12730 remote_ops.to_watchpoint_addr_within_range =
12731 remote_watchpoint_addr_within_range;
3c3bea1c
GS
12732 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12733 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12734 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
12735 remote_ops.to_region_ok_for_hw_watchpoint
12736 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
12737 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12738 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 12739 remote_ops.to_kill = remote_kill;
9dd130a0 12740 remote_ops.to_load = remote_load;
c906108c 12741 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 12742 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 12743 remote_ops.to_program_signals = remote_program_signals;
c906108c 12744 remote_ops.to_thread_alive = remote_thread_alive;
e8032dde 12745 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 12746 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 12747 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 12748 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 12749 remote_ops.to_stop = remote_stop;
bfedc46a 12750 remote_ops.to_interrupt = remote_interrupt;
abc56d60 12751 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
4b8a223f 12752 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 12753 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 12754 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 12755 remote_ops.to_log_command = serial_log_command;
38691318 12756 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 12757 remote_ops.to_stratum = process_stratum;
c35b1492
PA
12758 remote_ops.to_has_all_memory = default_child_has_all_memory;
12759 remote_ops.to_has_memory = default_child_has_memory;
12760 remote_ops.to_has_stack = default_child_has_stack;
12761 remote_ops.to_has_registers = default_child_has_registers;
12762 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 12763 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 12764 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 12765 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 12766 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
12767 remote_ops.to_flash_erase = remote_flash_erase;
12768 remote_ops.to_flash_done = remote_flash_done;
29709017 12769 remote_ops.to_read_description = remote_read_description;
08388c79 12770 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
12771 remote_ops.to_can_async_p = remote_can_async_p;
12772 remote_ops.to_is_async_p = remote_is_async_p;
12773 remote_ops.to_async = remote_async;
750ce8d1 12774 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
12775 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12776 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 12777 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 12778 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
12779 remote_ops.to_supports_disable_randomization
12780 = remote_supports_disable_randomization;
4bd7dc42 12781 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
12782 remote_ops.to_fileio_open = remote_hostio_open;
12783 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12784 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 12785 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
12786 remote_ops.to_fileio_close = remote_hostio_close;
12787 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 12788 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 12789 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 12790 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 12791 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 12792 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
12793 remote_ops.to_trace_init = remote_trace_init;
12794 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 12795 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
12796 remote_ops.to_download_trace_state_variable
12797 = remote_download_trace_state_variable;
d248b706
KY
12798 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12799 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
12800 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12801 remote_ops.to_trace_start = remote_trace_start;
12802 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 12803 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
12804 remote_ops.to_trace_stop = remote_trace_stop;
12805 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
12806 remote_ops.to_get_trace_state_variable_value
12807 = remote_get_trace_state_variable_value;
00bf0b85
SS
12808 remote_ops.to_save_trace_data = remote_save_trace_data;
12809 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
12810 remote_ops.to_upload_trace_state_variables
12811 = remote_upload_trace_state_variables;
00bf0b85 12812 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 12813 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 12814 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 12815 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 12816 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 12817 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 12818 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 12819 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 12820 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 12821 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
12822 remote_ops.to_static_tracepoint_marker_at
12823 = remote_static_tracepoint_marker_at;
12824 remote_ops.to_static_tracepoint_markers_by_strid
12825 = remote_static_tracepoint_markers_by_strid;
b3b9301e 12826 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
12827 remote_ops.to_use_agent = remote_use_agent;
12828 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
12829 remote_ops.to_supports_btrace = remote_supports_btrace;
12830 remote_ops.to_enable_btrace = remote_enable_btrace;
12831 remote_ops.to_disable_btrace = remote_disable_btrace;
12832 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12833 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 12834 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
12835 remote_ops.to_augmented_libraries_svr4_read =
12836 remote_augmented_libraries_svr4_read;
c906108c
SS
12837}
12838
12839/* Set up the extended remote vector by making a copy of the standard
12840 remote vector and adding to it. */
12841
12842static void
fba45db2 12843init_extended_remote_ops (void)
c906108c
SS
12844{
12845 extended_remote_ops = remote_ops;
12846
0f71a2f6 12847 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 12848 extended_remote_ops.to_longname =
c906108c 12849 "Extended remote serial target in gdb-specific protocol";
c5aa993b 12850 extended_remote_ops.to_doc =
c906108c 12851 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
12852Specify the serial device it is connected to (e.g. /dev/ttya).";
12853 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
12854 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12855 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
12856 extended_remote_ops.to_detach = extended_remote_detach;
12857 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 12858 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 12859 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
12860 extended_remote_ops.to_supports_disable_randomization
12861 = extended_remote_supports_disable_randomization;
de0d863e 12862 extended_remote_ops.to_follow_fork = remote_follow_fork;
94585166 12863 extended_remote_ops.to_follow_exec = remote_follow_exec;
cbb8991c
DB
12864 extended_remote_ops.to_insert_fork_catchpoint
12865 = remote_insert_fork_catchpoint;
12866 extended_remote_ops.to_remove_fork_catchpoint
12867 = remote_remove_fork_catchpoint;
12868 extended_remote_ops.to_insert_vfork_catchpoint
12869 = remote_insert_vfork_catchpoint;
12870 extended_remote_ops.to_remove_vfork_catchpoint
12871 = remote_remove_vfork_catchpoint;
d46addbb
DB
12872 extended_remote_ops.to_insert_exec_catchpoint
12873 = remote_insert_exec_catchpoint;
12874 extended_remote_ops.to_remove_exec_catchpoint
12875 = remote_remove_exec_catchpoint;
0f71a2f6
JM
12876}
12877
6426a772 12878static int
6a109b6b 12879remote_can_async_p (struct target_ops *ops)
6426a772 12880{
5d93a237
TT
12881 struct remote_state *rs = get_remote_state ();
12882
c6ebd6cf 12883 if (!target_async_permitted)
75c99385
PA
12884 /* We only enable async when the user specifically asks for it. */
12885 return 0;
12886
23860348 12887 /* We're async whenever the serial device is. */
5d93a237 12888 return serial_can_async_p (rs->remote_desc);
6426a772
JM
12889}
12890
12891static int
6a109b6b 12892remote_is_async_p (struct target_ops *ops)
6426a772 12893{
5d93a237
TT
12894 struct remote_state *rs = get_remote_state ();
12895
c6ebd6cf 12896 if (!target_async_permitted)
75c99385
PA
12897 /* We only enable async when the user specifically asks for it. */
12898 return 0;
12899
23860348 12900 /* We're async whenever the serial device is. */
5d93a237 12901 return serial_is_async_p (rs->remote_desc);
6426a772
JM
12902}
12903
2acceee2
JM
12904/* Pass the SERIAL event on and up to the client. One day this code
12905 will be able to delay notifying the client of an event until the
23860348 12906 point where an entire packet has been received. */
2acceee2 12907
2acceee2
JM
12908static serial_event_ftype remote_async_serial_handler;
12909
6426a772 12910static void
819cc324 12911remote_async_serial_handler (struct serial *scb, void *context)
6426a772 12912{
19ba03f4 12913 struct remote_state *rs = (struct remote_state *) context;
88b496c3 12914
2acceee2
JM
12915 /* Don't propogate error information up to the client. Instead let
12916 the client find out about the error by querying the target. */
6a3753b3 12917 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
12918}
12919
74531fed
PA
12920static void
12921remote_async_inferior_event_handler (gdb_client_data data)
12922{
12923 inferior_event_handler (INF_REG_EVENT, NULL);
12924}
12925
2acceee2 12926static void
6a3753b3 12927remote_async (struct target_ops *ops, int enable)
2acceee2 12928{
5d93a237
TT
12929 struct remote_state *rs = get_remote_state ();
12930
6a3753b3 12931 if (enable)
2acceee2 12932 {
88b496c3 12933 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
12934
12935 /* If there are pending events in the stop reply queue tell the
12936 event loop to process them. */
12937 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12938 mark_async_event_handler (remote_async_inferior_event_token);
2acceee2
JM
12939 }
12940 else
b7d2e916
PA
12941 {
12942 serial_async (rs->remote_desc, NULL, NULL);
12943 clear_async_event_handler (remote_async_inferior_event_token);
12944 }
6426a772
JM
12945}
12946
5a2468f5 12947static void
c2d11a7d 12948set_remote_cmd (char *args, int from_tty)
5a2468f5 12949{
635c7e8a 12950 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
12951}
12952
d471ea57
AC
12953static void
12954show_remote_cmd (char *args, int from_tty)
12955{
37a105a1 12956 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 12957 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
12958 struct cleanup *showlist_chain;
12959 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 12960 struct ui_out *uiout = current_uiout;
37a105a1
DJ
12961
12962 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12963 for (; list != NULL; list = list->next)
12964 if (strcmp (list->name, "Z-packet") == 0)
12965 continue;
427c3a89
DJ
12966 else if (list->type == not_set_cmd)
12967 /* Alias commands are exactly like the original, except they
12968 don't have the normal type. */
12969 continue;
12970 else
37a105a1
DJ
12971 {
12972 struct cleanup *option_chain
12973 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 12974
37a105a1
DJ
12975 ui_out_field_string (uiout, "name", list->name);
12976 ui_out_text (uiout, ": ");
427c3a89 12977 if (list->type == show_cmd)
5b9afe8a 12978 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
12979 else
12980 cmd_func (list, NULL, from_tty);
37a105a1
DJ
12981 /* Close the tuple. */
12982 do_cleanups (option_chain);
12983 }
427c3a89
DJ
12984
12985 /* Close the tuple. */
12986 do_cleanups (showlist_chain);
d471ea57 12987}
5a2468f5 12988
0f71a2f6 12989
23860348 12990/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
12991static void
12992remote_new_objfile (struct objfile *objfile)
12993{
5d93a237
TT
12994 struct remote_state *rs = get_remote_state ();
12995
12996 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 12997 remote_check_symbols ();
dc8acb97
MS
12998}
12999
00bf0b85
SS
13000/* Pull all the tracepoints defined on the target and create local
13001 data structures representing them. We don't want to create real
13002 tracepoints yet, we don't want to mess up the user's existing
13003 collection. */
13004
13005static int
ab6617cc 13006remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13007{
00bf0b85
SS
13008 struct remote_state *rs = get_remote_state ();
13009 char *p;
d5551862 13010
00bf0b85
SS
13011 /* Ask for a first packet of tracepoint definition. */
13012 putpkt ("qTfP");
13013 getpkt (&rs->buf, &rs->buf_size, 0);
13014 p = rs->buf;
13015 while (*p && *p != 'l')
d5551862 13016 {
00bf0b85
SS
13017 parse_tracepoint_definition (p, utpp);
13018 /* Ask for another packet of tracepoint definition. */
13019 putpkt ("qTsP");
13020 getpkt (&rs->buf, &rs->buf_size, 0);
13021 p = rs->buf;
d5551862 13022 }
00bf0b85 13023 return 0;
d5551862
SS
13024}
13025
00bf0b85 13026static int
181e3713
TT
13027remote_upload_trace_state_variables (struct target_ops *self,
13028 struct uploaded_tsv **utsvp)
d5551862 13029{
00bf0b85 13030 struct remote_state *rs = get_remote_state ();
d5551862 13031 char *p;
d5551862 13032
00bf0b85
SS
13033 /* Ask for a first packet of variable definition. */
13034 putpkt ("qTfV");
d5551862
SS
13035 getpkt (&rs->buf, &rs->buf_size, 0);
13036 p = rs->buf;
00bf0b85 13037 while (*p && *p != 'l')
d5551862 13038 {
00bf0b85
SS
13039 parse_tsv_definition (p, utsvp);
13040 /* Ask for another packet of variable definition. */
13041 putpkt ("qTsV");
d5551862
SS
13042 getpkt (&rs->buf, &rs->buf_size, 0);
13043 p = rs->buf;
13044 }
00bf0b85 13045 return 0;
d5551862
SS
13046}
13047
c1e36e3e
PA
13048/* The "set/show range-stepping" show hook. */
13049
13050static void
13051show_range_stepping (struct ui_file *file, int from_tty,
13052 struct cmd_list_element *c,
13053 const char *value)
13054{
13055 fprintf_filtered (file,
13056 _("Debugger's willingness to use range stepping "
13057 "is %s.\n"), value);
13058}
13059
13060/* The "set/show range-stepping" set hook. */
13061
13062static void
13063set_range_stepping (char *ignore_args, int from_tty,
13064 struct cmd_list_element *c)
13065{
5d93a237
TT
13066 struct remote_state *rs = get_remote_state ();
13067
c1e36e3e
PA
13068 /* Whene enabling, check whether range stepping is actually
13069 supported by the target, and warn if not. */
13070 if (use_range_stepping)
13071 {
5d93a237 13072 if (rs->remote_desc != NULL)
c1e36e3e 13073 {
4082afcc 13074 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13075 remote_vcont_probe (rs);
13076
4082afcc 13077 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13078 && rs->supports_vCont.r)
13079 return;
13080 }
13081
13082 warning (_("Range stepping is not supported by the current target"));
13083 }
13084}
13085
c906108c 13086void
fba45db2 13087_initialize_remote (void)
c906108c 13088{
ea9c271d 13089 struct remote_state *rs;
9a7071a8 13090 struct cmd_list_element *cmd;
6f937416 13091 const char *cmd_name;
ea9c271d 13092
0f71a2f6 13093 /* architecture specific data */
2bc416ba 13094 remote_gdbarch_data_handle =
23860348 13095 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13096 remote_g_packet_data_handle =
13097 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13098
94585166
DB
13099 remote_pspace_data
13100 = register_program_space_data_with_cleanup (NULL,
13101 remote_pspace_data_cleanup);
13102
ea9c271d
DJ
13103 /* Initialize the per-target state. At the moment there is only one
13104 of these, not one per target. Only one target is active at a
cf792862
TT
13105 time. */
13106 remote_state = new_remote_state ();
ea9c271d 13107
c906108c
SS
13108 init_remote_ops ();
13109 add_target (&remote_ops);
13110
13111 init_extended_remote_ops ();
13112 add_target (&extended_remote_ops);
cce74817 13113
dc8acb97 13114 /* Hook into new objfile notification. */
06d3b283 13115 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13116 /* We're no longer interested in notification events of an inferior
13117 when it exits. */
13118 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13119
b803fb0f 13120 /* Set up signal handlers. */
934b9bac 13121 async_sigint_remote_token =
b803fb0f 13122 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 13123 async_sigint_remote_twice_token =
6d549500 13124 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 13125
c906108c
SS
13126#if 0
13127 init_remote_threadtests ();
13128#endif
13129
722247f1 13130 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13131 /* set/show remote ... */
d471ea57 13132
1bedd215 13133 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13134Remote protocol specific variables\n\
13135Configure various remote-protocol specific variables such as\n\
1bedd215 13136the packets being used"),
cff3e48b 13137 &remote_set_cmdlist, "set remote ",
23860348 13138 0 /* allow-unknown */, &setlist);
1bedd215 13139 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13140Remote protocol specific variables\n\
13141Configure various remote-protocol specific variables such as\n\
1bedd215 13142the packets being used"),
cff3e48b 13143 &remote_show_cmdlist, "show remote ",
23860348 13144 0 /* allow-unknown */, &showlist);
5a2468f5 13145
1a966eab
AC
13146 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13147Compare section data on target to the exec file.\n\
95cf3b38
DT
13148Argument is a single section name (default: all loaded sections).\n\
13149To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13150 &cmdlist);
13151
1a966eab
AC
13152 add_cmd ("packet", class_maintenance, packet_command, _("\
13153Send an arbitrary packet to a remote target.\n\
c906108c
SS
13154 maintenance packet TEXT\n\
13155If GDB is talking to an inferior via the GDB serial protocol, then\n\
13156this command sends the string TEXT to the inferior, and displays the\n\
13157response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13158terminating `#' character and checksum."),
c906108c
SS
13159 &maintenancelist);
13160
7915a72c
AC
13161 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13162Set whether to send break if interrupted."), _("\
13163Show whether to send break if interrupted."), _("\
13164If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13165 set_remotebreak, show_remotebreak,
e707bbc2 13166 &setlist, &showlist);
9a7071a8
JB
13167 cmd_name = "remotebreak";
13168 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13169 deprecate_cmd (cmd, "set remote interrupt-sequence");
13170 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13171 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13172 deprecate_cmd (cmd, "show remote interrupt-sequence");
13173
13174 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13175 interrupt_sequence_modes, &interrupt_sequence_mode,
13176 _("\
9a7071a8
JB
13177Set interrupt sequence to remote target."), _("\
13178Show interrupt sequence to remote target."), _("\
13179Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13180 NULL, show_interrupt_sequence,
13181 &remote_set_cmdlist,
13182 &remote_show_cmdlist);
13183
13184 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13185 &interrupt_on_connect, _("\
13186Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13187Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13188If set, interrupt sequence is sent to remote target."),
13189 NULL, NULL,
13190 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13191
23860348 13192 /* Install commands for configuring memory read/write packets. */
11cf8741 13193
1a966eab
AC
13194 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13195Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13196 &setlist);
1a966eab
AC
13197 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13198Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13199 &showlist);
13200 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13201 set_memory_write_packet_size, _("\
13202Set the maximum number of bytes per memory-write packet.\n\
13203Specify the number of bytes in a packet or 0 (zero) for the\n\
13204default packet size. The actual limit is further reduced\n\
13205dependent on the target. Specify ``fixed'' to disable the\n\
13206further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13207 &remote_set_cmdlist);
13208 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13209 set_memory_read_packet_size, _("\
13210Set the maximum number of bytes per memory-read packet.\n\
13211Specify the number of bytes in a packet or 0 (zero) for the\n\
13212default packet size. The actual limit is further reduced\n\
13213dependent on the target. Specify ``fixed'' to disable the\n\
13214further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13215 &remote_set_cmdlist);
13216 add_cmd ("memory-write-packet-size", no_class,
13217 show_memory_write_packet_size,
1a966eab 13218 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13219 &remote_show_cmdlist);
13220 add_cmd ("memory-read-packet-size", no_class,
13221 show_memory_read_packet_size,
1a966eab 13222 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13223 &remote_show_cmdlist);
c906108c 13224
b3f42336 13225 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13226 &remote_hw_watchpoint_limit, _("\
13227Set the maximum number of target hardware watchpoints."), _("\
13228Show the maximum number of target hardware watchpoints."), _("\
13229Specify a negative limit for unlimited."),
3e43a32a
MS
13230 NULL, NULL, /* FIXME: i18n: The maximum
13231 number of target hardware
13232 watchpoints is %s. */
b3f42336 13233 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13234 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13235 &remote_hw_watchpoint_length_limit, _("\
13236Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13237Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13238Specify a negative limit for unlimited."),
13239 NULL, NULL, /* FIXME: i18n: The maximum
13240 length (in bytes) of a target
13241 hardware watchpoint is %s. */
13242 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13243 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13244 &remote_hw_breakpoint_limit, _("\
13245Set the maximum number of target hardware breakpoints."), _("\
13246Show the maximum number of target hardware breakpoints."), _("\
13247Specify a negative limit for unlimited."),
3e43a32a
MS
13248 NULL, NULL, /* FIXME: i18n: The maximum
13249 number of target hardware
13250 breakpoints is %s. */
b3f42336 13251 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13252
1b493192
PA
13253 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13254 &remote_address_size, _("\
4d28ad1e
AC
13255Set the maximum size of the address (in bits) in a memory packet."), _("\
13256Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13257 NULL,
13258 NULL, /* FIXME: i18n: */
13259 &setlist, &showlist);
c906108c 13260
ca4f7f8b
PA
13261 init_all_packet_configs ();
13262
444abaca 13263 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13264 "X", "binary-download", 1);
0f71a2f6 13265
444abaca 13266 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13267 "vCont", "verbose-resume", 0);
506fb367 13268
89be2091
DJ
13269 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13270 "QPassSignals", "pass-signals", 0);
13271
9b224c5e
PA
13272 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13273 "QProgramSignals", "program-signals", 0);
13274
444abaca 13275 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13276 "qSymbol", "symbol-lookup", 0);
dc8acb97 13277
444abaca 13278 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13279 "P", "set-register", 1);
d471ea57 13280
444abaca 13281 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13282 "p", "fetch-register", 1);
b96ec7ac 13283
444abaca 13284 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13285 "Z0", "software-breakpoint", 0);
d471ea57 13286
444abaca 13287 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13288 "Z1", "hardware-breakpoint", 0);
d471ea57 13289
444abaca 13290 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13291 "Z2", "write-watchpoint", 0);
d471ea57 13292
444abaca 13293 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13294 "Z3", "read-watchpoint", 0);
d471ea57 13295
444abaca 13296 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13297 "Z4", "access-watchpoint", 0);
d471ea57 13298
0876f84a
DJ
13299 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13300 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13301
c78fa86a
GB
13302 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13303 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13304
23181151
DJ
13305 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13306 "qXfer:features:read", "target-features", 0);
13307
cfa9d6d9
DJ
13308 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13309 "qXfer:libraries:read", "library-info", 0);
13310
2268b414
JK
13311 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13312 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13313
fd79ecee
DJ
13314 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13315 "qXfer:memory-map:read", "memory-map", 0);
13316
0e7f50da
UW
13317 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13318 "qXfer:spu:read", "read-spu-object", 0);
13319
13320 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13321 "qXfer:spu:write", "write-spu-object", 0);
13322
07e059b5
VP
13323 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13324 "qXfer:osdata:read", "osdata", 0);
13325
dc146f7c
VP
13326 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13327 "qXfer:threads:read", "threads", 0);
13328
4aa995e1
PA
13329 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13330 "qXfer:siginfo:read", "read-siginfo-object", 0);
13331
13332 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13333 "qXfer:siginfo:write", "write-siginfo-object", 0);
13334
b3b9301e
PA
13335 add_packet_config_cmd
13336 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13337 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13338
169081d0
TG
13339 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13340 "qXfer:uib:read", "unwind-info-block", 0);
13341
444abaca 13342 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13343 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13344 0);
13345
711e434b
PM
13346 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13347 "qGetTIBAddr", "get-thread-information-block-address",
13348 0);
13349
40ab02ce
MS
13350 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13351 "bc", "reverse-continue", 0);
13352
13353 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13354 "bs", "reverse-step", 0);
13355
be2a5f71
DJ
13356 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13357 "qSupported", "supported-packets", 0);
13358
08388c79
DE
13359 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13360 "qSearch:memory", "search-memory", 0);
13361
bd3eecc3
PA
13362 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13363 "qTStatus", "trace-status", 0);
13364
15a201c8
GB
13365 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13366 "vFile:setfs", "hostio-setfs", 0);
13367
a6b151f1
DJ
13368 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13369 "vFile:open", "hostio-open", 0);
13370
13371 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13372 "vFile:pread", "hostio-pread", 0);
13373
13374 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13375 "vFile:pwrite", "hostio-pwrite", 0);
13376
13377 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13378 "vFile:close", "hostio-close", 0);
13379
13380 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13381 "vFile:unlink", "hostio-unlink", 0);
13382
b9e7b9c3
UW
13383 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13384 "vFile:readlink", "hostio-readlink", 0);
13385
0a93529c
GB
13386 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13387 "vFile:fstat", "hostio-fstat", 0);
13388
2d717e4f
DJ
13389 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13390 "vAttach", "attach", 0);
13391
13392 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13393 "vRun", "run", 0);
13394
a6f3e723
SL
13395 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13396 "QStartNoAckMode", "noack", 0);
13397
82f73884
PA
13398 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13399 "vKill", "kill", 0);
13400
0b16c5cf
PA
13401 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13402 "qAttached", "query-attached", 0);
13403
782b2b07 13404 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13405 "ConditionalTracepoints",
13406 "conditional-tracepoints", 0);
3788aec7
LM
13407
13408 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13409 "ConditionalBreakpoints",
13410 "conditional-breakpoints", 0);
13411
d3ce09f5
SS
13412 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13413 "BreakpointCommands",
13414 "breakpoint-commands", 0);
13415
7a697b8d
SS
13416 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13417 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13418
409873ef
SS
13419 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13420 "TracepointSource", "TracepointSource", 0);
13421
d914c394
SS
13422 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13423 "QAllow", "allow", 0);
13424
0fb4aa4b
PA
13425 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13426 "StaticTracepoints", "static-tracepoints", 0);
13427
1e4d1764
YQ
13428 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13429 "InstallInTrace", "install-in-trace", 0);
13430
0fb4aa4b
PA
13431 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13432 "qXfer:statictrace:read", "read-sdata-object", 0);
13433
78d85199
YQ
13434 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13435 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13436
03583c20
UW
13437 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13438 "QDisableRandomization", "disable-randomization", 0);
13439
d1feda86
YQ
13440 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13441 "QAgent", "agent", 0);
13442
f6f899bf
HAQ
13443 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13444 "QTBuffer:size", "trace-buffer-size", 0);
13445
9accd112
MM
13446 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13447 "Qbtrace:off", "disable-btrace", 0);
13448
13449 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13450 "Qbtrace:bts", "enable-btrace-bts", 0);
13451
13452 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13453 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13454
13455 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13456 "qXfer:btrace", "read-btrace", 0);
13457
f4abbc16
MM
13458 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13459 "qXfer:btrace-conf", "read-btrace-conf", 0);
13460
d33501a5
MM
13461 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13462 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13463
73b8c1fd
PA
13464 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13465 "multiprocess-feature", "multiprocess-feature", 0);
13466
f7e6eed5
PA
13467 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13468 "swbreak-feature", "swbreak-feature", 0);
13469
13470 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13471 "hwbreak-feature", "hwbreak-feature", 0);
13472
89245bc0
DB
13473 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13474 "fork-event-feature", "fork-event-feature", 0);
13475
13476 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13477 "vfork-event-feature", "vfork-event-feature", 0);
13478
b20a6524
MM
13479 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13480 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13481
750ce8d1
YQ
13482 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13483 "vContSupported", "verbose-resume-supported", 0);
13484
94585166
DB
13485 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13486 "exec-event-feature", "exec-event-feature", 0);
13487
0b736949
DB
13488 /* Assert that we've registered "set remote foo-packet" commands
13489 for all packet configs. */
ca4f7f8b
PA
13490 {
13491 int i;
13492
13493 for (i = 0; i < PACKET_MAX; i++)
13494 {
13495 /* Ideally all configs would have a command associated. Some
13496 still don't though. */
13497 int excepted;
13498
13499 switch (i)
13500 {
13501 case PACKET_QNonStop:
ca4f7f8b
PA
13502 case PACKET_EnableDisableTracepoints_feature:
13503 case PACKET_tracenz_feature:
13504 case PACKET_DisconnectedTracing_feature:
13505 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13506 case PACKET_qCRC:
13507 /* Additions to this list need to be well justified:
13508 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13509 excepted = 1;
13510 break;
13511 default:
13512 excepted = 0;
13513 break;
13514 }
13515
13516 /* This catches both forgetting to add a config command, and
13517 forgetting to remove a packet from the exception list. */
13518 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13519 }
13520 }
13521
37a105a1
DJ
13522 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13523 Z sub-packet has its own set and show commands, but users may
13524 have sets to this variable in their .gdbinit files (or in their
13525 documentation). */
e9e68a56 13526 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13527 &remote_Z_packet_detect, _("\
13528Set use of remote protocol `Z' packets"), _("\
13529Show use of remote protocol `Z' packets "), _("\
3b64bf98 13530When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13531packets."),
e9e68a56 13532 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13533 show_remote_protocol_Z_packet_cmd,
13534 /* FIXME: i18n: Use of remote protocol
13535 `Z' packets is %s. */
e9e68a56 13536 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13537
a6b151f1
DJ
13538 add_prefix_cmd ("remote", class_files, remote_command, _("\
13539Manipulate files on the remote system\n\
13540Transfer files to and from the remote target system."),
13541 &remote_cmdlist, "remote ",
13542 0 /* allow-unknown */, &cmdlist);
13543
13544 add_cmd ("put", class_files, remote_put_command,
13545 _("Copy a local file to the remote system."),
13546 &remote_cmdlist);
13547
13548 add_cmd ("get", class_files, remote_get_command,
13549 _("Copy a remote file to the local system."),
13550 &remote_cmdlist);
13551
13552 add_cmd ("delete", class_files, remote_delete_command,
13553 _("Delete a remote file."),
13554 &remote_cmdlist);
13555
2d717e4f 13556 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13557 &remote_exec_file_var, _("\
2d717e4f 13558Set the remote pathname for \"run\""), _("\
94585166
DB
13559Show the remote pathname for \"run\""), NULL,
13560 set_remote_exec_file,
13561 show_remote_exec_file,
13562 &remote_set_cmdlist,
13563 &remote_show_cmdlist);
2d717e4f 13564
c1e36e3e
PA
13565 add_setshow_boolean_cmd ("range-stepping", class_run,
13566 &use_range_stepping, _("\
13567Enable or disable range stepping."), _("\
13568Show whether target-assisted range stepping is enabled."), _("\
13569If on, and the target supports it, when stepping a source line, GDB\n\
13570tells the target to step the corresponding range of addresses itself instead\n\
13571of issuing multiple single-steps. This speeds up source level\n\
13572stepping. If off, GDB always issues single-steps, even if range\n\
13573stepping is supported by the target. The default is on."),
13574 set_range_stepping,
13575 show_range_stepping,
13576 &setlist,
13577 &showlist);
13578
449092f6
CV
13579 /* Eventually initialize fileio. See fileio.c */
13580 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13581
ba348170 13582 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13583 special ptids with it set to != 0. */
ba348170
PA
13584 magic_null_ptid = ptid_build (42000, -1, 1);
13585 not_sent_ptid = ptid_build (42000, -2, 1);
13586 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13587
13588 target_buf_size = 2048;
224c3ddb 13589 target_buf = (char *) xmalloc (target_buf_size);
c906108c 13590}
10760264 13591