New vCtrlC packet, non-stop mode equivalent of \003
[deliverable/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
0d031856
TT
404 threadref echo_nextthread;
405 threadref nextthread;
406 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
407
408 /* The state of remote notification. */
409 struct remote_notif_state *notif_state;
f4abbc16
MM
410
411 /* The branch trace configuration. */
412 struct btrace_config btrace_config;
15a201c8
GB
413
414 /* The argument to the last "vFile:setfs:" packet we sent, used
415 to avoid sending repeated unnecessary "vFile:setfs:" packets.
416 Initialized to -1 to indicate that no "vFile:setfs:" packet
417 has yet been sent. */
418 int fs_pid;
80152258
PA
419
420 /* A readahead cache for vFile:pread. Often, reading a binary
421 involves a sequence of small reads. E.g., when parsing an ELF
422 file. A readahead cache helps mostly the case of remote
423 debugging on a connection with higher latency, due to the
424 request/reply nature of the RSP. We only cache data for a single
425 file descriptor at a time. */
426 struct readahead_cache readahead_cache;
ea9c271d
DJ
427};
428
dc146f7c
VP
429/* Private data that we'll store in (struct thread_info)->private. */
430struct private_thread_info
431{
432 char *extra;
79efa585 433 char *name;
dc146f7c 434 int core;
799a2abe
PA
435
436 /* Whether the target stopped for a breakpoint/watchpoint. */
437 enum target_stop_reason stop_reason;
438
439 /* This is set to the data address of the access causing the target
440 to stop for a watchpoint. */
441 CORE_ADDR watch_data_address;
dc146f7c
VP
442};
443
444static void
445free_private_thread_info (struct private_thread_info *info)
446{
447 xfree (info->extra);
79efa585 448 xfree (info->name);
dc146f7c
VP
449 xfree (info);
450}
451
ea9c271d
DJ
452/* This data could be associated with a target, but we do not always
453 have access to the current target when we need it, so for now it is
454 static. This will be fine for as long as only one target is in use
455 at a time. */
cf792862 456static struct remote_state *remote_state;
ea9c271d
DJ
457
458static struct remote_state *
0b83947e 459get_remote_state_raw (void)
ea9c271d 460{
cf792862
TT
461 return remote_state;
462}
463
464/* Allocate a new struct remote_state with xmalloc, initialize it, and
465 return it. */
466
467static struct remote_state *
468new_remote_state (void)
469{
470 struct remote_state *result = XCNEW (struct remote_state);
471
472 /* The default buffer size is unimportant; it will be expanded
473 whenever a larger buffer is needed. */
474 result->buf_size = 400;
224c3ddb 475 result->buf = (char *) xmalloc (result->buf_size);
262e1174 476 result->remote_traceframe_number = -1;
b73be471 477 result->last_sent_signal = GDB_SIGNAL_0;
15a201c8 478 result->fs_pid = -1;
cf792862
TT
479
480 return result;
ea9c271d
DJ
481}
482
483/* Description of the remote protocol for a given architecture. */
d01949b6 484
ad10f812
AC
485struct packet_reg
486{
487 long offset; /* Offset into G packet. */
488 long regnum; /* GDB's internal register number. */
489 LONGEST pnum; /* Remote protocol register number. */
b323314b 490 int in_g_packet; /* Always part of G packet. */
f5656ead 491 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 492 at present. */
f5656ead 493 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 494 at present. */
ad10f812
AC
495};
496
ea9c271d 497struct remote_arch_state
d01949b6 498{
ad10f812
AC
499 /* Description of the remote protocol registers. */
500 long sizeof_g_packet;
b323314b
AC
501
502 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 503 (making an array gdbarch_num_regs in size). */
b323314b 504 struct packet_reg *regs;
ad10f812 505
d01949b6
AC
506 /* This is the size (in chars) of the first response to the ``g''
507 packet. It is used as a heuristic when determining the maximum
508 size of memory-read and memory-write packets. A target will
509 typically only reserve a buffer large enough to hold the ``g''
510 packet. The size does not include packet overhead (headers and
23860348 511 trailers). */
d01949b6
AC
512 long actual_register_packet_size;
513
514 /* This is the maximum size (in chars) of a non read/write packet.
23860348 515 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
516 long remote_packet_size;
517};
518
35b1e5cc
SS
519/* Utility: generate error from an incoming stub packet. */
520static void
521trace_error (char *buf)
522{
523 if (*buf++ != 'E')
524 return; /* not an error msg */
525 switch (*buf)
526 {
527 case '1': /* malformed packet error */
528 if (*++buf == '0') /* general case: */
529 error (_("remote.c: error in outgoing packet."));
530 else
531 error (_("remote.c: error in outgoing packet at field #%ld."),
532 strtol (buf, NULL, 16));
35b1e5cc
SS
533 default:
534 error (_("Target returns error code '%s'."), buf);
535 }
536}
537
538/* Utility: wait for reply from stub, while accepting "O" packets. */
539static char *
540remote_get_noisy_reply (char **buf_p,
541 long *sizeof_buf)
542{
543 do /* Loop on reply from remote stub. */
544 {
545 char *buf;
a744cf53 546
0df8b418 547 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
548 getpkt (buf_p, sizeof_buf, 0);
549 buf = *buf_p;
ad91cd99 550 if (buf[0] == 'E')
35b1e5cc 551 trace_error (buf);
61012eef 552 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
553 {
554 ULONGEST ul;
555 CORE_ADDR from, to, org_to;
556 char *p, *pp;
557 int adjusted_size = 0;
7556d4a4 558 int relocated = 0;
dde08ee1
PA
559
560 p = buf + strlen ("qRelocInsn:");
561 pp = unpack_varlen_hex (p, &ul);
562 if (*pp != ';')
cb91c06a 563 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
564 from = ul;
565
566 p = pp + 1;
a9cbf802 567 unpack_varlen_hex (p, &ul);
dde08ee1
PA
568 to = ul;
569
570 org_to = to;
571
492d29ea 572 TRY
dde08ee1 573 {
f5656ead 574 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 575 relocated = 1;
dde08ee1 576 }
492d29ea 577 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
578 {
579 if (ex.error == MEMORY_ERROR)
580 {
581 /* Propagate memory errors silently back to the
582 target. The stub may have limited the range of
583 addresses we can write to, for example. */
584 }
585 else
586 {
587 /* Something unexpectedly bad happened. Be verbose
588 so we can tell what, and propagate the error back
589 to the stub, so it doesn't get stuck waiting for
590 a response. */
591 exception_fprintf (gdb_stderr, ex,
592 _("warning: relocating instruction: "));
593 }
594 putpkt ("E01");
595 }
492d29ea 596 END_CATCH
7556d4a4
PA
597
598 if (relocated)
dde08ee1
PA
599 {
600 adjusted_size = to - org_to;
601
bba74b36 602 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
603 putpkt (buf);
604 }
dde08ee1 605 }
ad91cd99 606 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
607 remote_console_output (buf + 1); /* 'O' message from stub */
608 else
0df8b418 609 return buf; /* Here's the actual reply. */
35b1e5cc
SS
610 }
611 while (1);
612}
3c3bea1c 613
d01949b6
AC
614/* Handle for retreving the remote protocol data from gdbarch. */
615static struct gdbarch_data *remote_gdbarch_data_handle;
616
ea9c271d
DJ
617static struct remote_arch_state *
618get_remote_arch_state (void)
d01949b6 619{
17d8546e 620 gdb_assert (target_gdbarch () != NULL);
19ba03f4
SM
621 return ((struct remote_arch_state *)
622 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
d01949b6
AC
623}
624
0b83947e
DJ
625/* Fetch the global remote target state. */
626
627static struct remote_state *
628get_remote_state (void)
629{
630 /* Make sure that the remote architecture state has been
631 initialized, because doing so might reallocate rs->buf. Any
632 function which calls getpkt also needs to be mindful of changes
633 to rs->buf, but this call limits the number of places which run
634 into trouble. */
635 get_remote_arch_state ();
636
637 return get_remote_state_raw ();
638}
639
94585166
DB
640/* Cleanup routine for the remote module's pspace data. */
641
642static void
643remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
644{
19ba03f4 645 char *remote_exec_file = (char *) arg;
94585166
DB
646
647 xfree (remote_exec_file);
648}
649
650/* Fetch the remote exec-file from the current program space. */
651
652static const char *
653get_remote_exec_file (void)
654{
655 char *remote_exec_file;
656
19ba03f4
SM
657 remote_exec_file
658 = (char *) program_space_data (current_program_space,
659 remote_pspace_data);
94585166
DB
660 if (remote_exec_file == NULL)
661 return "";
662
663 return remote_exec_file;
664}
665
666/* Set the remote exec file for PSPACE. */
667
668static void
669set_pspace_remote_exec_file (struct program_space *pspace,
670 char *remote_exec_file)
671{
19ba03f4 672 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
673
674 xfree (old_file);
675 set_program_space_data (pspace, remote_pspace_data,
676 xstrdup (remote_exec_file));
677}
678
679/* The "set/show remote exec-file" set command hook. */
680
681static void
682set_remote_exec_file (char *ignored, int from_tty,
683 struct cmd_list_element *c)
684{
685 gdb_assert (remote_exec_file_var != NULL);
686 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
687}
688
689/* The "set/show remote exec-file" show command hook. */
690
691static void
692show_remote_exec_file (struct ui_file *file, int from_tty,
693 struct cmd_list_element *cmd, const char *value)
694{
695 fprintf_filtered (file, "%s\n", remote_exec_file_var);
696}
697
74ca34ce
DJ
698static int
699compare_pnums (const void *lhs_, const void *rhs_)
700{
19ba03f4
SM
701 const struct packet_reg * const *lhs
702 = (const struct packet_reg * const *) lhs_;
703 const struct packet_reg * const *rhs
704 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
705
706 if ((*lhs)->pnum < (*rhs)->pnum)
707 return -1;
708 else if ((*lhs)->pnum == (*rhs)->pnum)
709 return 0;
710 else
711 return 1;
712}
713
c21236dc
PA
714static int
715map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 716{
74ca34ce 717 int regnum, num_remote_regs, offset;
74ca34ce 718 struct packet_reg **remote_regs;
ea9c271d 719
4a22f64d 720 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 721 {
c21236dc 722 struct packet_reg *r = &regs[regnum];
baef701f 723
4a22f64d 724 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
725 /* Do not try to fetch zero-sized (placeholder) registers. */
726 r->pnum = -1;
727 else
728 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
729
b323314b 730 r->regnum = regnum;
74ca34ce
DJ
731 }
732
733 /* Define the g/G packet format as the contents of each register
734 with a remote protocol number, in order of ascending protocol
735 number. */
736
224c3ddb 737 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 738 for (num_remote_regs = 0, regnum = 0;
4a22f64d 739 regnum < gdbarch_num_regs (gdbarch);
f57d151a 740 regnum++)
c21236dc
PA
741 if (regs[regnum].pnum != -1)
742 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 743
74ca34ce
DJ
744 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
745 compare_pnums);
746
747 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
748 {
749 remote_regs[regnum]->in_g_packet = 1;
750 remote_regs[regnum]->offset = offset;
4a22f64d 751 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
752 }
753
c21236dc
PA
754 return offset;
755}
756
757/* Given the architecture described by GDBARCH, return the remote
758 protocol register's number and the register's offset in the g/G
759 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
760 If the target does not have a mapping for REGNUM, return false,
761 otherwise, return true. */
762
763int
764remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
765 int *pnum, int *poffset)
766{
767 int sizeof_g_packet;
768 struct packet_reg *regs;
769 struct cleanup *old_chain;
770
771 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
772
224c3ddb 773 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
c21236dc
PA
774 old_chain = make_cleanup (xfree, regs);
775
776 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
777
778 *pnum = regs[regnum].pnum;
779 *poffset = regs[regnum].offset;
780
781 do_cleanups (old_chain);
782
783 return *pnum != -1;
784}
785
786static void *
787init_remote_state (struct gdbarch *gdbarch)
788{
789 struct remote_state *rs = get_remote_state_raw ();
790 struct remote_arch_state *rsa;
791
792 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
793
794 /* Use the architecture to build a regnum<->pnum table, which will be
795 1:1 unless a feature set specifies otherwise. */
796 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
797 gdbarch_num_regs (gdbarch),
798 struct packet_reg);
799
74ca34ce
DJ
800 /* Record the maximum possible size of the g packet - it may turn out
801 to be smaller. */
c21236dc 802 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 803
0df8b418 804 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
805 remote stubs have a hardwired buffer size of 400 bytes
806 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
807 as the maximum packet-size to ensure that the packet and an extra
808 NUL character can always fit in the buffer. This stops GDB
809 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
810 already a full buffer (As of 1999-12-04 that was most stubs). */
811 rsa->remote_packet_size = 400 - 1;
d01949b6 812
ea9c271d
DJ
813 /* This one is filled in when a ``g'' packet is received. */
814 rsa->actual_register_packet_size = 0;
815
816 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
817 default, adjust the size accordingly. Remember that each byte is
818 encoded as two characters. 32 is the overhead for the packet
819 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 820 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 821 little. */
ea9c271d
DJ
822 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
823 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 824
ea9c271d
DJ
825 /* Make sure that the packet buffer is plenty big enough for
826 this architecture. */
827 if (rs->buf_size < rsa->remote_packet_size)
828 {
829 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 830 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 831 }
6d820c5c 832
ea9c271d
DJ
833 return rsa;
834}
835
836/* Return the current allowed size of a remote packet. This is
837 inferred from the current architecture, and should be used to
838 limit the length of outgoing packets. */
839static long
840get_remote_packet_size (void)
841{
be2a5f71 842 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
843 struct remote_arch_state *rsa = get_remote_arch_state ();
844
be2a5f71
DJ
845 if (rs->explicit_packet_size)
846 return rs->explicit_packet_size;
847
ea9c271d 848 return rsa->remote_packet_size;
d01949b6
AC
849}
850
ad10f812 851static struct packet_reg *
ea9c271d 852packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 853{
f5656ead 854 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
855 return NULL;
856 else
ad10f812 857 {
ea9c271d 858 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 859
b323314b
AC
860 gdb_assert (r->regnum == regnum);
861 return r;
ad10f812 862 }
ad10f812
AC
863}
864
865static struct packet_reg *
ea9c271d 866packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 867{
b323314b 868 int i;
a744cf53 869
f5656ead 870 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 871 {
ea9c271d 872 struct packet_reg *r = &rsa->regs[i];
a744cf53 873
b323314b
AC
874 if (r->pnum == pnum)
875 return r;
ad10f812
AC
876 }
877 return NULL;
d01949b6
AC
878}
879
c906108c
SS
880static struct target_ops remote_ops;
881
882static struct target_ops extended_remote_ops;
883
6426a772
JM
884/* FIXME: cagney/1999-09-23: Even though getpkt was called with
885 ``forever'' still use the normal timeout mechanism. This is
886 currently used by the ASYNC code to guarentee that target reads
887 during the initial connect always time-out. Once getpkt has been
888 modified to return a timeout indication and, in turn
889 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 890 this can go away. */
6426a772
JM
891static int wait_forever_enabled_p = 1;
892
9a7071a8
JB
893/* Allow the user to specify what sequence to send to the remote
894 when he requests a program interruption: Although ^C is usually
895 what remote systems expect (this is the default, here), it is
896 sometimes preferable to send a break. On other systems such
897 as the Linux kernel, a break followed by g, which is Magic SysRq g
898 is required in order to interrupt the execution. */
899const char interrupt_sequence_control_c[] = "Ctrl-C";
900const char interrupt_sequence_break[] = "BREAK";
901const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 902static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
903 {
904 interrupt_sequence_control_c,
905 interrupt_sequence_break,
906 interrupt_sequence_break_g,
907 NULL
908 };
909static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
910
911static void
912show_interrupt_sequence (struct ui_file *file, int from_tty,
913 struct cmd_list_element *c,
914 const char *value)
915{
916 if (interrupt_sequence_mode == interrupt_sequence_control_c)
917 fprintf_filtered (file,
918 _("Send the ASCII ETX character (Ctrl-c) "
919 "to the remote target to interrupt the "
920 "execution of the program.\n"));
921 else if (interrupt_sequence_mode == interrupt_sequence_break)
922 fprintf_filtered (file,
923 _("send a break signal to the remote target "
924 "to interrupt the execution of the program.\n"));
925 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
926 fprintf_filtered (file,
927 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
928 "the remote target to interrupt the execution "
929 "of Linux kernel.\n"));
930 else
931 internal_error (__FILE__, __LINE__,
932 _("Invalid value for interrupt_sequence_mode: %s."),
933 interrupt_sequence_mode);
934}
6426a772 935
9a7071a8
JB
936/* This boolean variable specifies whether interrupt_sequence is sent
937 to the remote target when gdb connects to it.
938 This is mostly needed when you debug the Linux kernel: The Linux kernel
939 expects BREAK g which is Magic SysRq g for connecting gdb. */
940static int interrupt_on_connect = 0;
c906108c 941
9a7071a8
JB
942/* This variable is used to implement the "set/show remotebreak" commands.
943 Since these commands are now deprecated in favor of "set/show remote
944 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
945static int remote_break;
946
9a7071a8
JB
947static void
948set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
949{
950 if (remote_break)
951 interrupt_sequence_mode = interrupt_sequence_break;
952 else
953 interrupt_sequence_mode = interrupt_sequence_control_c;
954}
955
956static void
957show_remotebreak (struct ui_file *file, int from_tty,
958 struct cmd_list_element *c,
959 const char *value)
960{
961}
962
c906108c
SS
963/* This variable sets the number of bits in an address that are to be
964 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 965 leading zeros, the entire address would be sent. This variable
c906108c
SS
966 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
967 initial implementation of remote.c restricted the address sent in
968 memory packets to ``host::sizeof long'' bytes - (typically 32
969 bits). Consequently, for 64 bit targets, the upper 32 bits of an
970 address was never sent. Since fixing this bug may cause a break in
971 some remote targets this variable is principly provided to
23860348 972 facilitate backward compatibility. */
c906108c 973
883b9c6c 974static unsigned int remote_address_size;
c906108c 975
75c99385
PA
976/* Temporary to track who currently owns the terminal. See
977 remote_terminal_* for more details. */
6426a772
JM
978
979static int remote_async_terminal_ours_p;
980
11cf8741 981\f
11cf8741 982/* User configurable variables for the number of characters in a
ea9c271d
DJ
983 memory read/write packet. MIN (rsa->remote_packet_size,
984 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 985 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
986 (speed up transfers). The variables ``preferred_*'' (the user
987 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 988 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
989
990struct memory_packet_config
991{
992 char *name;
993 long size;
994 int fixed_p;
995};
996
a5c0808e
PA
997/* The default max memory-write-packet-size. The 16k is historical.
998 (It came from older GDB's using alloca for buffers and the
999 knowledge (folklore?) that some hosts don't cope very well with
1000 large alloca calls.) */
1001#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1002
1003/* The minimum remote packet size for memory transfers. Ensures we
1004 can write at least one byte. */
1005#define MIN_MEMORY_PACKET_SIZE 20
1006
11cf8741
JM
1007/* Compute the current size of a read/write packet. Since this makes
1008 use of ``actual_register_packet_size'' the computation is dynamic. */
1009
1010static long
1011get_memory_packet_size (struct memory_packet_config *config)
1012{
d01949b6 1013 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
1014 struct remote_arch_state *rsa = get_remote_arch_state ();
1015
11cf8741
JM
1016 long what_they_get;
1017 if (config->fixed_p)
1018 {
1019 if (config->size <= 0)
a5c0808e 1020 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1021 else
1022 what_they_get = config->size;
1023 }
1024 else
1025 {
ea9c271d 1026 what_they_get = get_remote_packet_size ();
23860348 1027 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1028 if (config->size > 0
1029 && what_they_get > config->size)
1030 what_they_get = config->size;
be2a5f71
DJ
1031
1032 /* Limit it to the size of the targets ``g'' response unless we have
1033 permission from the stub to use a larger packet size. */
1034 if (rs->explicit_packet_size == 0
1035 && rsa->actual_register_packet_size > 0
1036 && what_they_get > rsa->actual_register_packet_size)
1037 what_they_get = rsa->actual_register_packet_size;
11cf8741 1038 }
a5c0808e
PA
1039 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1040 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1041
1042 /* Make sure there is room in the global buffer for this packet
1043 (including its trailing NUL byte). */
1044 if (rs->buf_size < what_they_get + 1)
1045 {
1046 rs->buf_size = 2 * what_they_get;
224c3ddb 1047 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1048 }
1049
11cf8741
JM
1050 return what_they_get;
1051}
1052
0df8b418 1053/* Update the size of a read/write packet. If they user wants
23860348 1054 something really big then do a sanity check. */
11cf8741
JM
1055
1056static void
1057set_memory_packet_size (char *args, struct memory_packet_config *config)
1058{
1059 int fixed_p = config->fixed_p;
1060 long size = config->size;
a744cf53 1061
11cf8741 1062 if (args == NULL)
8a3fe4f8 1063 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1064 else if (strcmp (args, "hard") == 0
1065 || strcmp (args, "fixed") == 0)
1066 fixed_p = 1;
1067 else if (strcmp (args, "soft") == 0
1068 || strcmp (args, "limit") == 0)
1069 fixed_p = 0;
1070 else
1071 {
1072 char *end;
a744cf53 1073
11cf8741
JM
1074 size = strtoul (args, &end, 0);
1075 if (args == end)
8a3fe4f8 1076 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1077
1078 /* Instead of explicitly capping the size of a packet to or
1079 disallowing it, the user is allowed to set the size to
1080 something arbitrarily large. */
11cf8741 1081 }
a5c0808e
PA
1082
1083 /* So that the query shows the correct value. */
1084 if (size <= 0)
1085 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1086
23860348 1087 /* Extra checks? */
11cf8741
JM
1088 if (fixed_p && !config->fixed_p)
1089 {
e2e0b3e5
AC
1090 if (! query (_("The target may not be able to correctly handle a %s\n"
1091 "of %ld bytes. Change the packet size? "),
11cf8741 1092 config->name, size))
8a3fe4f8 1093 error (_("Packet size not changed."));
11cf8741 1094 }
23860348 1095 /* Update the config. */
11cf8741
JM
1096 config->fixed_p = fixed_p;
1097 config->size = size;
1098}
1099
1100static void
1101show_memory_packet_size (struct memory_packet_config *config)
1102{
a3f17187 1103 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1104 if (config->fixed_p)
a3f17187 1105 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1106 get_memory_packet_size (config));
1107 else
a3f17187 1108 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1109 get_memory_packet_size (config));
1110}
1111
1112static struct memory_packet_config memory_write_packet_config =
1113{
1114 "memory-write-packet-size",
1115};
1116
1117static void
1118set_memory_write_packet_size (char *args, int from_tty)
1119{
1120 set_memory_packet_size (args, &memory_write_packet_config);
1121}
1122
1123static void
1124show_memory_write_packet_size (char *args, int from_tty)
1125{
1126 show_memory_packet_size (&memory_write_packet_config);
1127}
1128
1129static long
1130get_memory_write_packet_size (void)
1131{
1132 return get_memory_packet_size (&memory_write_packet_config);
1133}
1134
1135static struct memory_packet_config memory_read_packet_config =
1136{
1137 "memory-read-packet-size",
1138};
1139
1140static void
1141set_memory_read_packet_size (char *args, int from_tty)
1142{
1143 set_memory_packet_size (args, &memory_read_packet_config);
1144}
1145
1146static void
1147show_memory_read_packet_size (char *args, int from_tty)
1148{
1149 show_memory_packet_size (&memory_read_packet_config);
1150}
1151
1152static long
1153get_memory_read_packet_size (void)
1154{
1155 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1156
11cf8741
JM
1157 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1158 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1159 increased beyond this. */
1160 if (size > get_remote_packet_size ())
1161 size = get_remote_packet_size ();
11cf8741
JM
1162 return size;
1163}
1164
11cf8741 1165\f
5a2468f5 1166/* Generic configuration support for packets the stub optionally
0df8b418 1167 supports. Allows the user to specify the use of the packet as well
23860348 1168 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1169
1170enum packet_support
1171 {
1172 PACKET_SUPPORT_UNKNOWN = 0,
1173 PACKET_ENABLE,
1174 PACKET_DISABLE
1175 };
1176
5a2468f5
JM
1177struct packet_config
1178 {
bb572ddd
DJ
1179 const char *name;
1180 const char *title;
4082afcc
PA
1181
1182 /* If auto, GDB auto-detects support for this packet or feature,
1183 either through qSupported, or by trying the packet and looking
1184 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1185 packet. If false, the packet is disabled. Configs that don't
1186 have an associated command always have this set to auto. */
7f19b9a2 1187 enum auto_boolean detect;
4082afcc
PA
1188
1189 /* Does the target support this packet? */
5a2468f5
JM
1190 enum packet_support support;
1191 };
1192
d471ea57 1193/* Analyze a packet's return value and update the packet config
23860348 1194 accordingly. */
d471ea57
AC
1195
1196enum packet_result
1197{
1198 PACKET_ERROR,
1199 PACKET_OK,
1200 PACKET_UNKNOWN
1201};
1202
4082afcc
PA
1203static enum packet_support packet_config_support (struct packet_config *config);
1204static enum packet_support packet_support (int packet);
5a2468f5
JM
1205
1206static void
fba45db2 1207show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1208{
1209 char *support = "internal-error";
a744cf53 1210
4082afcc 1211 switch (packet_config_support (config))
5a2468f5
JM
1212 {
1213 case PACKET_ENABLE:
1214 support = "enabled";
1215 break;
1216 case PACKET_DISABLE:
1217 support = "disabled";
1218 break;
1219 case PACKET_SUPPORT_UNKNOWN:
1220 support = "unknown";
1221 break;
1222 }
1223 switch (config->detect)
1224 {
7f19b9a2 1225 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1226 printf_filtered (_("Support for the `%s' packet "
1227 "is auto-detected, currently %s.\n"),
37a105a1 1228 config->name, support);
5a2468f5 1229 break;
7f19b9a2
AC
1230 case AUTO_BOOLEAN_TRUE:
1231 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1232 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1233 config->name, support);
8e248173 1234 break;
5a2468f5
JM
1235 }
1236}
1237
1238static void
bb572ddd
DJ
1239add_packet_config_cmd (struct packet_config *config, const char *name,
1240 const char *title, int legacy)
d471ea57 1241{
5a2468f5
JM
1242 char *set_doc;
1243 char *show_doc;
d471ea57 1244 char *cmd_name;
3ed07be4 1245
5a2468f5
JM
1246 config->name = name;
1247 config->title = title;
b435e160
AC
1248 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1249 name, title);
3e43a32a
MS
1250 show_doc = xstrprintf ("Show current use of remote "
1251 "protocol `%s' (%s) packet",
b435e160 1252 name, title);
d471ea57 1253 /* set/show TITLE-packet {auto,on,off} */
b435e160 1254 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1255 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1256 &config->detect, set_doc,
1257 show_doc, NULL, /* help_doc */
4082afcc 1258 NULL,
bb572ddd
DJ
1259 show_remote_protocol_packet_cmd,
1260 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1261 /* The command code copies the documentation strings. */
1262 xfree (set_doc);
1263 xfree (show_doc);
23860348 1264 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1265 if (legacy)
1266 {
1267 char *legacy_name;
a744cf53 1268
b435e160 1269 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1270 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1271 &remote_set_cmdlist);
d471ea57 1272 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1273 &remote_show_cmdlist);
d471ea57 1274 }
5a2468f5
JM
1275}
1276
d471ea57 1277static enum packet_result
a76d924d 1278packet_check_result (const char *buf)
5a2468f5 1279{
d471ea57 1280 if (buf[0] != '\0')
5a2468f5 1281 {
d471ea57 1282 /* The stub recognized the packet request. Check that the
23860348 1283 operation succeeded. */
a76d924d
DJ
1284 if (buf[0] == 'E'
1285 && isxdigit (buf[1]) && isxdigit (buf[2])
1286 && buf[3] == '\0')
1287 /* "Enn" - definitly an error. */
1288 return PACKET_ERROR;
1289
1290 /* Always treat "E." as an error. This will be used for
1291 more verbose error messages, such as E.memtypes. */
1292 if (buf[0] == 'E' && buf[1] == '.')
1293 return PACKET_ERROR;
1294
1295 /* The packet may or may not be OK. Just assume it is. */
1296 return PACKET_OK;
1297 }
1298 else
1299 /* The stub does not support the packet. */
1300 return PACKET_UNKNOWN;
1301}
1302
1303static enum packet_result
1304packet_ok (const char *buf, struct packet_config *config)
1305{
1306 enum packet_result result;
1307
4082afcc
PA
1308 if (config->detect != AUTO_BOOLEAN_TRUE
1309 && config->support == PACKET_DISABLE)
1310 internal_error (__FILE__, __LINE__,
1311 _("packet_ok: attempt to use a disabled packet"));
1312
a76d924d
DJ
1313 result = packet_check_result (buf);
1314 switch (result)
1315 {
1316 case PACKET_OK:
1317 case PACKET_ERROR:
1318 /* The stub recognized the packet request. */
4082afcc 1319 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1320 {
d471ea57
AC
1321 if (remote_debug)
1322 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1323 "Packet %s (%s) is supported\n",
1324 config->name, config->title);
d471ea57 1325 config->support = PACKET_ENABLE;
d471ea57 1326 }
a76d924d
DJ
1327 break;
1328 case PACKET_UNKNOWN:
23860348 1329 /* The stub does not support the packet. */
4082afcc
PA
1330 if (config->detect == AUTO_BOOLEAN_AUTO
1331 && config->support == PACKET_ENABLE)
d471ea57 1332 {
4082afcc
PA
1333 /* If the stub previously indicated that the packet was
1334 supported then there is a protocol error. */
1335 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1336 config->name, config->title);
1337 }
1338 else if (config->detect == AUTO_BOOLEAN_TRUE)
1339 {
1340 /* The user set it wrong. */
1341 error (_("Enabled packet %s (%s) not recognized by stub"),
1342 config->name, config->title);
d471ea57 1343 }
4082afcc
PA
1344
1345 if (remote_debug)
1346 fprintf_unfiltered (gdb_stdlog,
1347 "Packet %s (%s) is NOT supported\n",
1348 config->name, config->title);
1349 config->support = PACKET_DISABLE;
a76d924d 1350 break;
5a2468f5 1351 }
a76d924d
DJ
1352
1353 return result;
5a2468f5
JM
1354}
1355
444abaca
DJ
1356enum {
1357 PACKET_vCont = 0,
1358 PACKET_X,
1359 PACKET_qSymbol,
1360 PACKET_P,
1361 PACKET_p,
1362 PACKET_Z0,
1363 PACKET_Z1,
1364 PACKET_Z2,
1365 PACKET_Z3,
1366 PACKET_Z4,
15a201c8 1367 PACKET_vFile_setfs,
a6b151f1
DJ
1368 PACKET_vFile_open,
1369 PACKET_vFile_pread,
1370 PACKET_vFile_pwrite,
1371 PACKET_vFile_close,
1372 PACKET_vFile_unlink,
b9e7b9c3 1373 PACKET_vFile_readlink,
0a93529c 1374 PACKET_vFile_fstat,
0876f84a 1375 PACKET_qXfer_auxv,
23181151 1376 PACKET_qXfer_features,
c78fa86a 1377 PACKET_qXfer_exec_file,
cfa9d6d9 1378 PACKET_qXfer_libraries,
2268b414 1379 PACKET_qXfer_libraries_svr4,
fd79ecee 1380 PACKET_qXfer_memory_map,
0e7f50da
UW
1381 PACKET_qXfer_spu_read,
1382 PACKET_qXfer_spu_write,
07e059b5 1383 PACKET_qXfer_osdata,
dc146f7c 1384 PACKET_qXfer_threads,
0fb4aa4b 1385 PACKET_qXfer_statictrace_read,
b3b9301e 1386 PACKET_qXfer_traceframe_info,
169081d0 1387 PACKET_qXfer_uib,
711e434b 1388 PACKET_qGetTIBAddr,
444abaca 1389 PACKET_qGetTLSAddr,
be2a5f71 1390 PACKET_qSupported,
bd3eecc3 1391 PACKET_qTStatus,
89be2091 1392 PACKET_QPassSignals,
9b224c5e 1393 PACKET_QProgramSignals,
936d2992 1394 PACKET_qCRC,
08388c79 1395 PACKET_qSearch_memory,
2d717e4f
DJ
1396 PACKET_vAttach,
1397 PACKET_vRun,
a6f3e723 1398 PACKET_QStartNoAckMode,
82f73884 1399 PACKET_vKill,
4aa995e1
PA
1400 PACKET_qXfer_siginfo_read,
1401 PACKET_qXfer_siginfo_write,
0b16c5cf 1402 PACKET_qAttached,
4082afcc
PA
1403
1404 /* Support for conditional tracepoints. */
782b2b07 1405 PACKET_ConditionalTracepoints,
4082afcc
PA
1406
1407 /* Support for target-side breakpoint conditions. */
3788aec7 1408 PACKET_ConditionalBreakpoints,
4082afcc
PA
1409
1410 /* Support for target-side breakpoint commands. */
d3ce09f5 1411 PACKET_BreakpointCommands,
4082afcc
PA
1412
1413 /* Support for fast tracepoints. */
7a697b8d 1414 PACKET_FastTracepoints,
4082afcc
PA
1415
1416 /* Support for static tracepoints. */
0fb4aa4b 1417 PACKET_StaticTracepoints,
4082afcc
PA
1418
1419 /* Support for installing tracepoints while a trace experiment is
1420 running. */
1e4d1764 1421 PACKET_InstallInTrace,
4082afcc 1422
40ab02ce
MS
1423 PACKET_bc,
1424 PACKET_bs,
409873ef 1425 PACKET_TracepointSource,
d914c394 1426 PACKET_QAllow,
78d85199 1427 PACKET_qXfer_fdpic,
03583c20 1428 PACKET_QDisableRandomization,
d1feda86 1429 PACKET_QAgent,
f6f899bf 1430 PACKET_QTBuffer_size,
9accd112
MM
1431 PACKET_Qbtrace_off,
1432 PACKET_Qbtrace_bts,
b20a6524 1433 PACKET_Qbtrace_pt,
9accd112 1434 PACKET_qXfer_btrace,
4082afcc
PA
1435
1436 /* Support for the QNonStop packet. */
1437 PACKET_QNonStop,
1438
1439 /* Support for multi-process extensions. */
1440 PACKET_multiprocess_feature,
1441
1442 /* Support for enabling and disabling tracepoints while a trace
1443 experiment is running. */
1444 PACKET_EnableDisableTracepoints_feature,
1445
1446 /* Support for collecting strings using the tracenz bytecode. */
1447 PACKET_tracenz_feature,
1448
1449 /* Support for continuing to run a trace experiment while GDB is
1450 disconnected. */
1451 PACKET_DisconnectedTracing_feature,
1452
1453 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1454 PACKET_augmented_libraries_svr4_read_feature,
1455
f4abbc16
MM
1456 /* Support for the qXfer:btrace-conf:read packet. */
1457 PACKET_qXfer_btrace_conf,
1458
d33501a5
MM
1459 /* Support for the Qbtrace-conf:bts:size packet. */
1460 PACKET_Qbtrace_conf_bts_size,
1461
f7e6eed5
PA
1462 /* Support for swbreak+ feature. */
1463 PACKET_swbreak_feature,
1464
1465 /* Support for hwbreak+ feature. */
1466 PACKET_hwbreak_feature,
1467
89245bc0
DB
1468 /* Support for fork events. */
1469 PACKET_fork_event_feature,
1470
1471 /* Support for vfork events. */
1472 PACKET_vfork_event_feature,
1473
b20a6524
MM
1474 /* Support for the Qbtrace-conf:pt:size packet. */
1475 PACKET_Qbtrace_conf_pt_size,
1476
94585166
DB
1477 /* Support for exec events. */
1478 PACKET_exec_event_feature,
1479
750ce8d1
YQ
1480 /* Support for query supported vCont actions. */
1481 PACKET_vContSupported,
1482
de979965
PA
1483 /* Support remote CTRL-C. */
1484 PACKET_vCtrlC,
1485
444abaca
DJ
1486 PACKET_MAX
1487};
506fb367 1488
444abaca 1489static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1490
f7e6eed5
PA
1491/* Returns the packet's corresponding "set remote foo-packet" command
1492 state. See struct packet_config for more details. */
1493
1494static enum auto_boolean
1495packet_set_cmd_state (int packet)
1496{
1497 return remote_protocol_packets[packet].detect;
1498}
1499
4082afcc
PA
1500/* Returns whether a given packet or feature is supported. This takes
1501 into account the state of the corresponding "set remote foo-packet"
1502 command, which may be used to bypass auto-detection. */
dc8acb97 1503
4082afcc
PA
1504static enum packet_support
1505packet_config_support (struct packet_config *config)
1506{
1507 switch (config->detect)
444abaca 1508 {
4082afcc
PA
1509 case AUTO_BOOLEAN_TRUE:
1510 return PACKET_ENABLE;
1511 case AUTO_BOOLEAN_FALSE:
1512 return PACKET_DISABLE;
1513 case AUTO_BOOLEAN_AUTO:
1514 return config->support;
1515 default:
1516 gdb_assert_not_reached (_("bad switch"));
444abaca 1517 }
4082afcc
PA
1518}
1519
1520/* Same as packet_config_support, but takes the packet's enum value as
1521 argument. */
1522
1523static enum packet_support
1524packet_support (int packet)
1525{
1526 struct packet_config *config = &remote_protocol_packets[packet];
1527
1528 return packet_config_support (config);
dc8acb97
MS
1529}
1530
5a2468f5 1531static void
444abaca
DJ
1532show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1533 struct cmd_list_element *c,
1534 const char *value)
5a2468f5 1535{
444abaca 1536 struct packet_config *packet;
5a2468f5 1537
444abaca
DJ
1538 for (packet = remote_protocol_packets;
1539 packet < &remote_protocol_packets[PACKET_MAX];
1540 packet++)
1541 {
1542 if (&packet->detect == c->var)
1543 {
1544 show_packet_config_cmd (packet);
1545 return;
1546 }
1547 }
9b20d036 1548 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1549 c->name);
5a2468f5
JM
1550}
1551
d471ea57
AC
1552/* Should we try one of the 'Z' requests? */
1553
1554enum Z_packet_type
1555{
1556 Z_PACKET_SOFTWARE_BP,
1557 Z_PACKET_HARDWARE_BP,
1558 Z_PACKET_WRITE_WP,
1559 Z_PACKET_READ_WP,
1560 Z_PACKET_ACCESS_WP,
1561 NR_Z_PACKET_TYPES
1562};
96baa820 1563
d471ea57 1564/* For compatibility with older distributions. Provide a ``set remote
23860348 1565 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1566
7f19b9a2 1567static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1568
1569static void
fba45db2
KB
1570set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1571 struct cmd_list_element *c)
96baa820 1572{
d471ea57 1573 int i;
a744cf53 1574
d471ea57 1575 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1576 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1577}
1578
1579static void
08546159
AC
1580show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1581 struct cmd_list_element *c,
1582 const char *value)
96baa820 1583{
d471ea57 1584 int i;
a744cf53 1585
d471ea57
AC
1586 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1587 {
444abaca 1588 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1589 }
96baa820
JM
1590}
1591
4082afcc
PA
1592/* Returns true if the multi-process extensions are in effect. */
1593
1594static int
1595remote_multi_process_p (struct remote_state *rs)
1596{
1597 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1598}
1599
de0d863e
DB
1600/* Returns true if fork events are supported. */
1601
1602static int
1603remote_fork_event_p (struct remote_state *rs)
1604{
1605 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1606}
1607
c269dbdb
DB
1608/* Returns true if vfork events are supported. */
1609
1610static int
1611remote_vfork_event_p (struct remote_state *rs)
1612{
1613 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1614}
1615
d46addbb
DB
1616/* Returns true if exec events are supported. */
1617
1618static int
1619remote_exec_event_p (struct remote_state *rs)
1620{
1621 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1622}
1623
cbb8991c
DB
1624/* Insert fork catchpoint target routine. If fork events are enabled
1625 then return success, nothing more to do. */
1626
1627static int
1628remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1629{
1630 struct remote_state *rs = get_remote_state ();
1631
1632 return !remote_fork_event_p (rs);
1633}
1634
1635/* Remove fork catchpoint target routine. Nothing to do, just
1636 return success. */
1637
1638static int
1639remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1640{
1641 return 0;
1642}
1643
1644/* Insert vfork catchpoint target routine. If vfork events are enabled
1645 then return success, nothing more to do. */
1646
1647static int
1648remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1649{
1650 struct remote_state *rs = get_remote_state ();
1651
1652 return !remote_vfork_event_p (rs);
1653}
1654
1655/* Remove vfork catchpoint target routine. Nothing to do, just
1656 return success. */
1657
1658static int
1659remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1660{
1661 return 0;
1662}
1663
d46addbb
DB
1664/* Insert exec catchpoint target routine. If exec events are
1665 enabled, just return success. */
1666
1667static int
1668remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1669{
1670 struct remote_state *rs = get_remote_state ();
1671
1672 return !remote_exec_event_p (rs);
1673}
1674
1675/* Remove exec catchpoint target routine. Nothing to do, just
1676 return success. */
1677
1678static int
1679remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1680{
1681 return 0;
1682}
1683
23860348 1684/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1685static struct async_signal_handler *async_sigint_remote_twice_token;
1686static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1687
74531fed
PA
1688\f
1689/* Asynchronous signal handle registered as event loop source for
1690 when we have pending events ready to be passed to the core. */
1691
1692static struct async_event_handler *remote_async_inferior_event_token;
1693
c906108c
SS
1694\f
1695
79d7f229
PA
1696static ptid_t magic_null_ptid;
1697static ptid_t not_sent_ptid;
1698static ptid_t any_thread_ptid;
1699
0b16c5cf
PA
1700/* Find out if the stub attached to PID (and hence GDB should offer to
1701 detach instead of killing it when bailing out). */
1702
1703static int
1704remote_query_attached (int pid)
1705{
1706 struct remote_state *rs = get_remote_state ();
bba74b36 1707 size_t size = get_remote_packet_size ();
0b16c5cf 1708
4082afcc 1709 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1710 return 0;
1711
1712 if (remote_multi_process_p (rs))
bba74b36 1713 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1714 else
bba74b36 1715 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1716
1717 putpkt (rs->buf);
1718 getpkt (&rs->buf, &rs->buf_size, 0);
1719
1720 switch (packet_ok (rs->buf,
1554e9be 1721 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1722 {
1723 case PACKET_OK:
1724 if (strcmp (rs->buf, "1") == 0)
1725 return 1;
1726 break;
1727 case PACKET_ERROR:
1728 warning (_("Remote failure reply: %s"), rs->buf);
1729 break;
1730 case PACKET_UNKNOWN:
1731 break;
1732 }
1733
1734 return 0;
1735}
1736
49c62f2e
PA
1737/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1738 has been invented by GDB, instead of reported by the target. Since
1739 we can be connected to a remote system before before knowing about
1740 any inferior, mark the target with execution when we find the first
1741 inferior. If ATTACHED is 1, then we had just attached to this
1742 inferior. If it is 0, then we just created this inferior. If it
1743 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1744 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1745 attempt to open this inferior's executable as the main executable
1746 if no main executable is open already. */
1941c569
PA
1747
1748static struct inferior *
1b6e6f5c
GB
1749remote_add_inferior (int fake_pid_p, int pid, int attached,
1750 int try_open_exec)
1941c569 1751{
1941c569
PA
1752 struct inferior *inf;
1753
0b16c5cf
PA
1754 /* Check whether this process we're learning about is to be
1755 considered attached, or if is to be considered to have been
1756 spawned by the stub. */
1757 if (attached == -1)
1758 attached = remote_query_attached (pid);
1759
f5656ead 1760 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1761 {
1762 /* If the target shares code across all inferiors, then every
1763 attach adds a new inferior. */
1764 inf = add_inferior (pid);
1765
1766 /* ... and every inferior is bound to the same program space.
1767 However, each inferior may still have its own address
1768 space. */
1769 inf->aspace = maybe_new_address_space ();
1770 inf->pspace = current_program_space;
1771 }
1772 else
1773 {
1774 /* In the traditional debugging scenario, there's a 1-1 match
1775 between program/address spaces. We simply bind the inferior
1776 to the program space's address space. */
1777 inf = current_inferior ();
1778 inferior_appeared (inf, pid);
1779 }
1941c569 1780
0b16c5cf 1781 inf->attach_flag = attached;
49c62f2e 1782 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1783
1b6e6f5c
GB
1784 /* If no main executable is currently open then attempt to
1785 open the file that was executed to create this inferior. */
835205d0 1786 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1787 exec_file_locate_attach (pid, 1);
1788
1941c569
PA
1789 return inf;
1790}
1791
1792/* Add thread PTID to GDB's thread list. Tag it as executing/running
1793 according to RUNNING. */
1794
c906108c 1795static void
1941c569 1796remote_add_thread (ptid_t ptid, int running)
c906108c 1797{
b7ea362b
PA
1798 struct remote_state *rs = get_remote_state ();
1799
1800 /* GDB historically didn't pull threads in the initial connection
1801 setup. If the remote target doesn't even have a concept of
1802 threads (e.g., a bare-metal target), even if internally we
1803 consider that a single-threaded target, mentioning a new thread
1804 might be confusing to the user. Be silent then, preserving the
1805 age old behavior. */
1806 if (rs->starting_up)
1807 add_thread_silent (ptid);
1808 else
1809 add_thread (ptid);
1941c569
PA
1810
1811 set_executing (ptid, running);
1812 set_running (ptid, running);
1813}
1814
1815/* Come here when we learn about a thread id from the remote target.
1816 It may be the first time we hear about such thread, so take the
1817 opportunity to add it to GDB's thread list. In case this is the
1818 first time we're noticing its corresponding inferior, add it to
1819 GDB's inferior list as well. */
1820
1821static void
1822remote_notice_new_inferior (ptid_t currthread, int running)
1823{
c906108c
SS
1824 /* If this is a new thread, add it to GDB's thread list.
1825 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1826
1827 if (in_thread_list (currthread) && is_exited (currthread))
1828 {
1829 /* We're seeing an event on a thread id we knew had exited.
1830 This has to be a new thread reusing the old id. Add it. */
1941c569 1831 remote_add_thread (currthread, running);
82f73884
PA
1832 return;
1833 }
1834
79d7f229 1835 if (!in_thread_list (currthread))
c0a2216e 1836 {
1941c569 1837 struct inferior *inf = NULL;
bad34192 1838 int pid = ptid_get_pid (currthread);
1941c569 1839
bad34192
PA
1840 if (ptid_is_pid (inferior_ptid)
1841 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1842 {
1843 /* inferior_ptid has no thread member yet. This can happen
1844 with the vAttach -> remote_wait,"TAAthread:" path if the
1845 stub doesn't support qC. This is the first stop reported
1846 after an attach, so this is the main thread. Update the
1847 ptid in the thread list. */
bad34192
PA
1848 if (in_thread_list (pid_to_ptid (pid)))
1849 thread_change_ptid (inferior_ptid, currthread);
1850 else
1851 {
1852 remote_add_thread (currthread, running);
1853 inferior_ptid = currthread;
1854 }
dc146f7c 1855 return;
c0a2216e 1856 }
82f73884
PA
1857
1858 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1859 {
1860 /* inferior_ptid is not set yet. This can happen with the
1861 vRun -> remote_wait,"TAAthread:" path if the stub
1862 doesn't support qC. This is the first stop reported
1863 after an attach, so this is the main thread. Update the
1864 ptid in the thread list. */
dc146f7c 1865 thread_change_ptid (inferior_ptid, currthread);
82f73884 1866 return;
c0a2216e 1867 }
82f73884 1868
29c87f7f
PA
1869 /* When connecting to a target remote, or to a target
1870 extended-remote which already was debugging an inferior, we
1871 may not know about it yet. Add it before adding its child
1872 thread, so notifications are emitted in a sensible order. */
1873 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1874 {
1875 struct remote_state *rs = get_remote_state ();
1876 int fake_pid_p = !remote_multi_process_p (rs);
1877
1878 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1879 ptid_get_pid (currthread), -1, 1);
49c62f2e 1880 }
29c87f7f 1881
82f73884 1882 /* This is really a new thread. Add it. */
1941c569
PA
1883 remote_add_thread (currthread, running);
1884
1885 /* If we found a new inferior, let the common code do whatever
1886 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1887 breakpoints), unless we're just setting up an all-stop
1888 connection. */
1941c569 1889 if (inf != NULL)
b7ea362b
PA
1890 {
1891 struct remote_state *rs = get_remote_state ();
1892
6efcd9a8 1893 if (!rs->starting_up)
b7ea362b
PA
1894 notice_new_inferior (currthread, running, 0);
1895 }
c0a2216e 1896 }
c906108c
SS
1897}
1898
dc146f7c
VP
1899/* Return the private thread data, creating it if necessary. */
1900
70221824 1901static struct private_thread_info *
dc146f7c
VP
1902demand_private_info (ptid_t ptid)
1903{
1904 struct thread_info *info = find_thread_ptid (ptid);
1905
1906 gdb_assert (info);
1907
fe978cb0 1908 if (!info->priv)
dc146f7c 1909 {
8d749320 1910 info->priv = XNEW (struct private_thread_info);
dc146f7c 1911 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1912 info->priv->core = -1;
1913 info->priv->extra = 0;
dc146f7c
VP
1914 }
1915
fe978cb0 1916 return info->priv;
dc146f7c
VP
1917}
1918
74531fed
PA
1919/* Call this function as a result of
1920 1) A halt indication (T packet) containing a thread id
1921 2) A direct query of currthread
0df8b418 1922 3) Successful execution of set thread */
74531fed
PA
1923
1924static void
47f8a51d 1925record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1926{
47f8a51d 1927 rs->general_thread = currthread;
74531fed
PA
1928}
1929
89be2091
DJ
1930/* If 'QPassSignals' is supported, tell the remote stub what signals
1931 it can simply pass through to the inferior without reporting. */
1932
1933static void
94bedb42
TT
1934remote_pass_signals (struct target_ops *self,
1935 int numsigs, unsigned char *pass_signals)
89be2091 1936{
4082afcc 1937 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1938 {
1939 char *pass_packet, *p;
89be2091 1940 int count = 0, i;
747dc59d 1941 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1942
1943 gdb_assert (numsigs < 256);
1944 for (i = 0; i < numsigs; i++)
1945 {
2455069d 1946 if (pass_signals[i])
89be2091
DJ
1947 count++;
1948 }
224c3ddb 1949 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
1950 strcpy (pass_packet, "QPassSignals:");
1951 p = pass_packet + strlen (pass_packet);
1952 for (i = 0; i < numsigs; i++)
1953 {
2455069d 1954 if (pass_signals[i])
89be2091
DJ
1955 {
1956 if (i >= 16)
1957 *p++ = tohex (i >> 4);
1958 *p++ = tohex (i & 15);
1959 if (count)
1960 *p++ = ';';
1961 else
1962 break;
1963 count--;
1964 }
1965 }
1966 *p = 0;
747dc59d 1967 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1968 {
89be2091
DJ
1969 putpkt (pass_packet);
1970 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1971 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1972 if (rs->last_pass_packet)
1973 xfree (rs->last_pass_packet);
1974 rs->last_pass_packet = pass_packet;
89be2091
DJ
1975 }
1976 else
1977 xfree (pass_packet);
1978 }
1979}
1980
9b224c5e
PA
1981/* If 'QProgramSignals' is supported, tell the remote stub what
1982 signals it should pass through to the inferior when detaching. */
1983
1984static void
daf5e9b6
TT
1985remote_program_signals (struct target_ops *self,
1986 int numsigs, unsigned char *signals)
9b224c5e 1987{
4082afcc 1988 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1989 {
1990 char *packet, *p;
1991 int count = 0, i;
5e4a05c4 1992 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1993
1994 gdb_assert (numsigs < 256);
1995 for (i = 0; i < numsigs; i++)
1996 {
1997 if (signals[i])
1998 count++;
1999 }
224c3ddb 2000 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2001 strcpy (packet, "QProgramSignals:");
2002 p = packet + strlen (packet);
2003 for (i = 0; i < numsigs; i++)
2004 {
2005 if (signal_pass_state (i))
2006 {
2007 if (i >= 16)
2008 *p++ = tohex (i >> 4);
2009 *p++ = tohex (i & 15);
2010 if (count)
2011 *p++ = ';';
2012 else
2013 break;
2014 count--;
2015 }
2016 }
2017 *p = 0;
5e4a05c4
TT
2018 if (!rs->last_program_signals_packet
2019 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2020 {
9b224c5e
PA
2021 putpkt (packet);
2022 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2023 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2024 xfree (rs->last_program_signals_packet);
2025 rs->last_program_signals_packet = packet;
9b224c5e
PA
2026 }
2027 else
2028 xfree (packet);
2029 }
2030}
2031
79d7f229
PA
2032/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2033 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2034 thread. If GEN is set, set the general thread, if not, then set
2035 the step/continue thread. */
c906108c 2036static void
79d7f229 2037set_thread (struct ptid ptid, int gen)
c906108c 2038{
d01949b6 2039 struct remote_state *rs = get_remote_state ();
47f8a51d 2040 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2041 char *buf = rs->buf;
79d7f229 2042 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2043
79d7f229 2044 if (ptid_equal (state, ptid))
c906108c
SS
2045 return;
2046
79d7f229
PA
2047 *buf++ = 'H';
2048 *buf++ = gen ? 'g' : 'c';
2049 if (ptid_equal (ptid, magic_null_ptid))
2050 xsnprintf (buf, endbuf - buf, "0");
2051 else if (ptid_equal (ptid, any_thread_ptid))
2052 xsnprintf (buf, endbuf - buf, "0");
2053 else if (ptid_equal (ptid, minus_one_ptid))
2054 xsnprintf (buf, endbuf - buf, "-1");
2055 else
82f73884 2056 write_ptid (buf, endbuf, ptid);
79d7f229 2057 putpkt (rs->buf);
6d820c5c 2058 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2059 if (gen)
47f8a51d 2060 rs->general_thread = ptid;
c906108c 2061 else
47f8a51d 2062 rs->continue_thread = ptid;
c906108c 2063}
79d7f229
PA
2064
2065static void
2066set_general_thread (struct ptid ptid)
2067{
2068 set_thread (ptid, 1);
2069}
2070
2071static void
2072set_continue_thread (struct ptid ptid)
2073{
2074 set_thread (ptid, 0);
2075}
2076
3c9c4b83
PA
2077/* Change the remote current process. Which thread within the process
2078 ends up selected isn't important, as long as it is the same process
2079 as what INFERIOR_PTID points to.
2080
2081 This comes from that fact that there is no explicit notion of
2082 "selected process" in the protocol. The selected process for
2083 general operations is the process the selected general thread
2084 belongs to. */
2085
2086static void
2087set_general_process (void)
2088{
2089 struct remote_state *rs = get_remote_state ();
2090
2091 /* If the remote can't handle multiple processes, don't bother. */
901f9912 2092 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
2093 return;
2094
2095 /* We only need to change the remote current thread if it's pointing
2096 at some other process. */
47f8a51d 2097 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2098 set_general_thread (inferior_ptid);
2099}
2100
c906108c 2101\f
7d1a114c
PA
2102/* Return nonzero if this is the main thread that we made up ourselves
2103 to model non-threaded targets as single-threaded. */
c906108c
SS
2104
2105static int
7d1a114c 2106remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2107{
6d820c5c 2108 struct remote_state *rs = get_remote_state ();
82f73884 2109 char *p, *endp;
c906108c 2110
c0a2216e
PA
2111 if (ptid_equal (ptid, magic_null_ptid))
2112 /* The main thread is always alive. */
2113 return 1;
2114
ba348170 2115 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2116 /* The main thread is always alive. This can happen after a
2117 vAttach, if the remote side doesn't support
2118 multi-threading. */
2119 return 1;
2120
7d1a114c
PA
2121 return 0;
2122}
2123
2124/* Return nonzero if the thread PTID is still alive on the remote
2125 system. */
2126
2127static int
2128remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2129{
2130 struct remote_state *rs = get_remote_state ();
2131 char *p, *endp;
2132
2133 /* Check if this is a thread that we made up ourselves to model
2134 non-threaded targets as single-threaded. */
2135 if (remote_thread_always_alive (ops, ptid))
2136 return 1;
2137
82f73884
PA
2138 p = rs->buf;
2139 endp = rs->buf + get_remote_packet_size ();
2140
2141 *p++ = 'T';
2142 write_ptid (p, endp, ptid);
2143
2e9f7625 2144 putpkt (rs->buf);
6d820c5c 2145 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2146 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2147}
2148
79efa585
SM
2149/* Return a pointer to a thread name if we know it and NULL otherwise.
2150 The thread_info object owns the memory for the name. */
2151
2152static const char *
2153remote_thread_name (struct target_ops *ops, struct thread_info *info)
2154{
2155 if (info->priv != NULL)
2156 return info->priv->name;
2157
2158 return NULL;
2159}
2160
c906108c
SS
2161/* About these extended threadlist and threadinfo packets. They are
2162 variable length packets but, the fields within them are often fixed
2163 length. They are redundent enough to send over UDP as is the
2164 remote protocol in general. There is a matching unit test module
2165 in libstub. */
2166
23860348 2167/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2168 libstub protocol encoding, and remote.c. It is not particularly
23860348 2169 changable. */
cce74817
JM
2170
2171/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2172 Plan to fix this. */
cce74817 2173
23860348 2174typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2175
9d1f7ab2 2176/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2177 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2178
2179struct gdb_ext_thread_info
c5aa993b 2180 {
23860348 2181 threadref threadid; /* External form of thread reference. */
2bc416ba 2182 int active; /* Has state interesting to GDB?
23860348 2183 regs, stack. */
2bc416ba 2184 char display[256]; /* Brief state display, name,
cedea757 2185 blocked/suspended. */
23860348 2186 char shortname[32]; /* To be used to name threads. */
2bc416ba 2187 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2188 whatever. */
c5aa993b 2189 };
cce74817
JM
2190
2191/* The volume of remote transfers can be limited by submitting
2192 a mask containing bits specifying the desired information.
2193 Use a union of these values as the 'selection' parameter to
0df8b418 2194 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2195
2196#define TAG_THREADID 1
2197#define TAG_EXISTS 2
2198#define TAG_DISPLAY 4
2199#define TAG_THREADNAME 8
c5aa993b 2200#define TAG_MOREDISPLAY 16
cce74817 2201
23860348 2202#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2203
a14ed312 2204static char *unpack_nibble (char *buf, int *val);
cce74817 2205
a14ed312 2206static char *unpack_byte (char *buf, int *value);
cce74817 2207
a14ed312 2208static char *pack_int (char *buf, int value);
cce74817 2209
a14ed312 2210static char *unpack_int (char *buf, int *value);
cce74817 2211
a14ed312 2212static char *unpack_string (char *src, char *dest, int length);
cce74817 2213
23860348 2214static char *pack_threadid (char *pkt, threadref *id);
cce74817 2215
23860348 2216static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2217
23860348 2218void int_to_threadref (threadref *id, int value);
cce74817 2219
23860348 2220static int threadref_to_int (threadref *ref);
cce74817 2221
23860348 2222static void copy_threadref (threadref *dest, threadref *src);
cce74817 2223
23860348 2224static int threadmatch (threadref *dest, threadref *src);
cce74817 2225
2bc416ba 2226static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2227 threadref *id);
cce74817 2228
a14ed312 2229static int remote_unpack_thread_info_response (char *pkt,
23860348 2230 threadref *expectedref,
a14ed312
KB
2231 struct gdb_ext_thread_info
2232 *info);
cce74817
JM
2233
2234
2bc416ba 2235static int remote_get_threadinfo (threadref *threadid,
23860348 2236 int fieldset, /*TAG mask */
a14ed312 2237 struct gdb_ext_thread_info *info);
cce74817 2238
a14ed312
KB
2239static char *pack_threadlist_request (char *pkt, int startflag,
2240 int threadcount,
23860348 2241 threadref *nextthread);
cce74817 2242
a14ed312
KB
2243static int parse_threadlist_response (char *pkt,
2244 int result_limit,
23860348 2245 threadref *original_echo,
2bc416ba 2246 threadref *resultlist,
23860348 2247 int *doneflag);
cce74817 2248
a14ed312 2249static int remote_get_threadlist (int startflag,
23860348 2250 threadref *nextthread,
a14ed312
KB
2251 int result_limit,
2252 int *done,
2bc416ba 2253 int *result_count,
23860348 2254 threadref *threadlist);
cce74817 2255
23860348 2256typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2257
a14ed312
KB
2258static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2259 void *context, int looplimit);
cce74817 2260
23860348 2261static int remote_newthread_step (threadref *ref, void *context);
cce74817 2262
82f73884
PA
2263
2264/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2265 buffer we're allowed to write to. Returns
2266 BUF+CHARACTERS_WRITTEN. */
2267
2268static char *
2269write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2270{
2271 int pid, tid;
2272 struct remote_state *rs = get_remote_state ();
2273
2274 if (remote_multi_process_p (rs))
2275 {
2276 pid = ptid_get_pid (ptid);
2277 if (pid < 0)
2278 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2279 else
2280 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2281 }
ba348170 2282 tid = ptid_get_lwp (ptid);
82f73884
PA
2283 if (tid < 0)
2284 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2285 else
2286 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2287
2288 return buf;
2289}
2290
2291/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2292 passed the last parsed char. Returns null_ptid on error. */
2293
2294static ptid_t
2295read_ptid (char *buf, char **obuf)
2296{
2297 char *p = buf;
2298 char *pp;
2299 ULONGEST pid = 0, tid = 0;
82f73884
PA
2300
2301 if (*p == 'p')
2302 {
2303 /* Multi-process ptid. */
2304 pp = unpack_varlen_hex (p + 1, &pid);
2305 if (*pp != '.')
b37520b6 2306 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2307
2308 p = pp;
2309 pp = unpack_varlen_hex (p + 1, &tid);
2310 if (obuf)
2311 *obuf = pp;
ba348170 2312 return ptid_build (pid, tid, 0);
82f73884
PA
2313 }
2314
2315 /* No multi-process. Just a tid. */
2316 pp = unpack_varlen_hex (p, &tid);
2317
c9f35b34
KB
2318 /* Return null_ptid when no thread id is found. */
2319 if (p == pp)
2320 {
2321 if (obuf)
2322 *obuf = pp;
2323 return null_ptid;
2324 }
2325
82f73884 2326 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2327 what's in inferior_ptid, unless it's null at this point. If so,
2328 then since there's no way to know the pid of the reported
2329 threads, use the magic number. */
2330 if (ptid_equal (inferior_ptid, null_ptid))
2331 pid = ptid_get_pid (magic_null_ptid);
2332 else
2333 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2334
2335 if (obuf)
2336 *obuf = pp;
ba348170 2337 return ptid_build (pid, tid, 0);
82f73884
PA
2338}
2339
c906108c 2340static int
fba45db2 2341stubhex (int ch)
c906108c
SS
2342{
2343 if (ch >= 'a' && ch <= 'f')
2344 return ch - 'a' + 10;
2345 if (ch >= '0' && ch <= '9')
2346 return ch - '0';
2347 if (ch >= 'A' && ch <= 'F')
2348 return ch - 'A' + 10;
2349 return -1;
2350}
2351
2352static int
fba45db2 2353stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2354{
2355 int nibble;
2356 int retval = 0;
2357
2358 while (fieldlength)
2359 {
2360 nibble = stubhex (*buff++);
2361 retval |= nibble;
2362 fieldlength--;
2363 if (fieldlength)
2364 retval = retval << 4;
2365 }
2366 return retval;
2367}
2368
c906108c 2369static char *
fba45db2 2370unpack_nibble (char *buf, int *val)
c906108c 2371{
b7589f7d 2372 *val = fromhex (*buf++);
c906108c
SS
2373 return buf;
2374}
2375
c906108c 2376static char *
fba45db2 2377unpack_byte (char *buf, int *value)
c906108c
SS
2378{
2379 *value = stub_unpack_int (buf, 2);
2380 return buf + 2;
2381}
2382
2383static char *
fba45db2 2384pack_int (char *buf, int value)
c906108c
SS
2385{
2386 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2387 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2388 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2389 buf = pack_hex_byte (buf, (value & 0xff));
2390 return buf;
2391}
2392
2393static char *
fba45db2 2394unpack_int (char *buf, int *value)
c906108c
SS
2395{
2396 *value = stub_unpack_int (buf, 8);
2397 return buf + 8;
2398}
2399
23860348 2400#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2401static char *pack_string (char *pkt, char *string);
c906108c
SS
2402
2403static char *
fba45db2 2404pack_string (char *pkt, char *string)
c906108c
SS
2405{
2406 char ch;
2407 int len;
2408
2409 len = strlen (string);
2410 if (len > 200)
23860348 2411 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2412 pkt = pack_hex_byte (pkt, len);
2413 while (len-- > 0)
2414 {
2415 ch = *string++;
2416 if ((ch == '\0') || (ch == '#'))
23860348 2417 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2418 *pkt++ = ch;
2419 }
2420 return pkt;
2421}
2422#endif /* 0 (unused) */
2423
2424static char *
fba45db2 2425unpack_string (char *src, char *dest, int length)
c906108c
SS
2426{
2427 while (length--)
2428 *dest++ = *src++;
2429 *dest = '\0';
2430 return src;
2431}
2432
2433static char *
fba45db2 2434pack_threadid (char *pkt, threadref *id)
c906108c
SS
2435{
2436 char *limit;
2437 unsigned char *altid;
2438
2439 altid = (unsigned char *) id;
2440 limit = pkt + BUF_THREAD_ID_SIZE;
2441 while (pkt < limit)
2442 pkt = pack_hex_byte (pkt, *altid++);
2443 return pkt;
2444}
2445
2446
2447static char *
fba45db2 2448unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2449{
2450 char *altref;
2451 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2452 int x, y;
2453
2454 altref = (char *) id;
2455
2456 while (inbuf < limit)
2457 {
2458 x = stubhex (*inbuf++);
2459 y = stubhex (*inbuf++);
2460 *altref++ = (x << 4) | y;
2461 }
2462 return inbuf;
2463}
2464
2465/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2466 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2467 to use 64bit thread references internally. This is an adapter
2468 function. */
2469
2470void
fba45db2 2471int_to_threadref (threadref *id, int value)
c906108c
SS
2472{
2473 unsigned char *scan;
2474
2475 scan = (unsigned char *) id;
2476 {
2477 int i = 4;
2478 while (i--)
2479 *scan++ = 0;
2480 }
2481 *scan++ = (value >> 24) & 0xff;
2482 *scan++ = (value >> 16) & 0xff;
2483 *scan++ = (value >> 8) & 0xff;
2484 *scan++ = (value & 0xff);
2485}
2486
2487static int
fba45db2 2488threadref_to_int (threadref *ref)
c906108c
SS
2489{
2490 int i, value = 0;
2491 unsigned char *scan;
2492
cfd77fa1 2493 scan = *ref;
c906108c
SS
2494 scan += 4;
2495 i = 4;
2496 while (i-- > 0)
2497 value = (value << 8) | ((*scan++) & 0xff);
2498 return value;
2499}
2500
2501static void
fba45db2 2502copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2503{
2504 int i;
2505 unsigned char *csrc, *cdest;
2506
2507 csrc = (unsigned char *) src;
2508 cdest = (unsigned char *) dest;
2509 i = 8;
2510 while (i--)
2511 *cdest++ = *csrc++;
2512}
2513
2514static int
fba45db2 2515threadmatch (threadref *dest, threadref *src)
c906108c 2516{
23860348 2517 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2518#if 0
2519 unsigned char *srcp, *destp;
2520 int i, result;
2521 srcp = (char *) src;
2522 destp = (char *) dest;
2523
2524 result = 1;
2525 while (i-- > 0)
2526 result &= (*srcp++ == *destp++) ? 1 : 0;
2527 return result;
2528#endif
2529 return 1;
2530}
2531
2532/*
c5aa993b
JM
2533 threadid:1, # always request threadid
2534 context_exists:2,
2535 display:4,
2536 unique_name:8,
2537 more_display:16
2538 */
c906108c
SS
2539
2540/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2541
2542static char *
fba45db2 2543pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2544{
23860348
MS
2545 *pkt++ = 'q'; /* Info Query */
2546 *pkt++ = 'P'; /* process or thread info */
2547 pkt = pack_int (pkt, mode); /* mode */
c906108c 2548 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2549 *pkt = '\0'; /* terminate */
c906108c
SS
2550 return pkt;
2551}
2552
23860348 2553/* These values tag the fields in a thread info response packet. */
c906108c 2554/* Tagging the fields allows us to request specific fields and to
23860348 2555 add more fields as time goes by. */
c906108c 2556
23860348 2557#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2558#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2559 fetch registers and its stack? */
c5aa993b 2560#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2561#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2562#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2563 the process. */
c906108c
SS
2564
2565static int
fba45db2
KB
2566remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2567 struct gdb_ext_thread_info *info)
c906108c 2568{
d01949b6 2569 struct remote_state *rs = get_remote_state ();
c906108c 2570 int mask, length;
cfd77fa1 2571 int tag;
c906108c 2572 threadref ref;
6d820c5c 2573 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2574 int retval = 1;
2575
23860348 2576 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2577 info->active = 0;
2578 info->display[0] = '\0';
2579 info->shortname[0] = '\0';
2580 info->more_display[0] = '\0';
2581
23860348
MS
2582 /* Assume the characters indicating the packet type have been
2583 stripped. */
c906108c
SS
2584 pkt = unpack_int (pkt, &mask); /* arg mask */
2585 pkt = unpack_threadid (pkt, &ref);
2586
2587 if (mask == 0)
8a3fe4f8 2588 warning (_("Incomplete response to threadinfo request."));
c906108c 2589 if (!threadmatch (&ref, expectedref))
23860348 2590 { /* This is an answer to a different request. */
8a3fe4f8 2591 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2592 return 0;
2593 }
2594 copy_threadref (&info->threadid, &ref);
2595
23860348 2596 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2597
23860348
MS
2598 /* Packets are terminated with nulls. */
2599 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2600 {
2601 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2602 pkt = unpack_byte (pkt, &length); /* length */
2603 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2604 {
8a3fe4f8 2605 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2606 retval = 0;
2607 break;
2608 }
2609 if (tag == TAG_THREADID)
2610 {
2611 if (length != 16)
2612 {
8a3fe4f8 2613 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2614 retval = 0;
2615 break;
2616 }
2617 pkt = unpack_threadid (pkt, &ref);
2618 mask = mask & ~TAG_THREADID;
2619 continue;
2620 }
2621 if (tag == TAG_EXISTS)
2622 {
2623 info->active = stub_unpack_int (pkt, length);
2624 pkt += length;
2625 mask = mask & ~(TAG_EXISTS);
2626 if (length > 8)
2627 {
8a3fe4f8 2628 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2629 retval = 0;
2630 break;
2631 }
2632 continue;
2633 }
2634 if (tag == TAG_THREADNAME)
2635 {
2636 pkt = unpack_string (pkt, &info->shortname[0], length);
2637 mask = mask & ~TAG_THREADNAME;
2638 continue;
2639 }
2640 if (tag == TAG_DISPLAY)
2641 {
2642 pkt = unpack_string (pkt, &info->display[0], length);
2643 mask = mask & ~TAG_DISPLAY;
2644 continue;
2645 }
2646 if (tag == TAG_MOREDISPLAY)
2647 {
2648 pkt = unpack_string (pkt, &info->more_display[0], length);
2649 mask = mask & ~TAG_MOREDISPLAY;
2650 continue;
2651 }
8a3fe4f8 2652 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2653 break; /* Not a tag we know about. */
c906108c
SS
2654 }
2655 return retval;
2656}
2657
2658static int
fba45db2
KB
2659remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2660 struct gdb_ext_thread_info *info)
c906108c 2661{
d01949b6 2662 struct remote_state *rs = get_remote_state ();
c906108c 2663 int result;
c906108c 2664
2e9f7625
DJ
2665 pack_threadinfo_request (rs->buf, fieldset, threadid);
2666 putpkt (rs->buf);
6d820c5c 2667 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2668
2669 if (rs->buf[0] == '\0')
2670 return 0;
2671
2e9f7625 2672 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2673 threadid, info);
c906108c
SS
2674 return result;
2675}
2676
c906108c
SS
2677/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2678
2679static char *
fba45db2
KB
2680pack_threadlist_request (char *pkt, int startflag, int threadcount,
2681 threadref *nextthread)
c906108c
SS
2682{
2683 *pkt++ = 'q'; /* info query packet */
2684 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2685 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2686 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2687 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2688 *pkt = '\0';
2689 return pkt;
2690}
2691
2692/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2693
2694static int
fba45db2
KB
2695parse_threadlist_response (char *pkt, int result_limit,
2696 threadref *original_echo, threadref *resultlist,
2697 int *doneflag)
c906108c 2698{
d01949b6 2699 struct remote_state *rs = get_remote_state ();
c906108c
SS
2700 char *limit;
2701 int count, resultcount, done;
2702
2703 resultcount = 0;
2704 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2705 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2706 /* done parse past here */
c906108c
SS
2707 pkt = unpack_byte (pkt, &count); /* count field */
2708 pkt = unpack_nibble (pkt, &done);
2709 /* The first threadid is the argument threadid. */
2710 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2711 while ((count-- > 0) && (pkt < limit))
2712 {
2713 pkt = unpack_threadid (pkt, resultlist++);
2714 if (resultcount++ >= result_limit)
2715 break;
2716 }
2717 if (doneflag)
2718 *doneflag = done;
2719 return resultcount;
2720}
2721
6dc54d91
PA
2722/* Fetch the next batch of threads from the remote. Returns -1 if the
2723 qL packet is not supported, 0 on error and 1 on success. */
2724
c906108c 2725static int
fba45db2
KB
2726remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2727 int *done, int *result_count, threadref *threadlist)
c906108c 2728{
d01949b6 2729 struct remote_state *rs = get_remote_state ();
c906108c
SS
2730 int result = 1;
2731
23860348 2732 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2733 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2734 >= get_remote_packet_size ())
ea9c271d 2735 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2736
6d820c5c
DJ
2737 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2738 putpkt (rs->buf);
2739 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2740 if (*rs->buf == '\0')
6dc54d91
PA
2741 {
2742 /* Packet not supported. */
2743 return -1;
2744 }
2745
2746 *result_count =
2747 parse_threadlist_response (rs->buf + 2, result_limit,
2748 &rs->echo_nextthread, threadlist, done);
c906108c 2749
0d031856 2750 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2751 {
23860348
MS
2752 /* FIXME: This is a good reason to drop the packet. */
2753 /* Possably, there is a duplicate response. */
c906108c
SS
2754 /* Possabilities :
2755 retransmit immediatly - race conditions
2756 retransmit after timeout - yes
2757 exit
2758 wait for packet, then exit
2759 */
8a3fe4f8 2760 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2761 return 0; /* I choose simply exiting. */
c906108c
SS
2762 }
2763 if (*result_count <= 0)
2764 {
2765 if (*done != 1)
2766 {
8a3fe4f8 2767 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2768 result = 0;
2769 }
2770 return result; /* break; */
2771 }
2772 if (*result_count > result_limit)
2773 {
2774 *result_count = 0;
8a3fe4f8 2775 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2776 return 0;
2777 }
2778 return result;
2779}
2780
6dc54d91
PA
2781/* Fetch the list of remote threads, with the qL packet, and call
2782 STEPFUNCTION for each thread found. Stops iterating and returns 1
2783 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2784 STEPFUNCTION returns false. If the packet is not supported,
2785 returns -1. */
c906108c 2786
c906108c 2787static int
fba45db2
KB
2788remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2789 int looplimit)
c906108c 2790{
0d031856 2791 struct remote_state *rs = get_remote_state ();
c906108c
SS
2792 int done, i, result_count;
2793 int startflag = 1;
2794 int result = 1;
2795 int loopcount = 0;
c906108c
SS
2796
2797 done = 0;
2798 while (!done)
2799 {
2800 if (loopcount++ > looplimit)
2801 {
2802 result = 0;
8a3fe4f8 2803 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2804 break;
2805 }
6dc54d91
PA
2806 result = remote_get_threadlist (startflag, &rs->nextthread,
2807 MAXTHREADLISTRESULTS,
2808 &done, &result_count,
2809 rs->resultthreadlist);
2810 if (result <= 0)
2811 break;
23860348 2812 /* Clear for later iterations. */
c906108c
SS
2813 startflag = 0;
2814 /* Setup to resume next batch of thread references, set nextthread. */
2815 if (result_count >= 1)
0d031856
TT
2816 copy_threadref (&rs->nextthread,
2817 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2818 i = 0;
2819 while (result_count--)
6dc54d91
PA
2820 {
2821 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2822 {
2823 result = 0;
2824 break;
2825 }
2826 }
c906108c
SS
2827 }
2828 return result;
2829}
2830
6dc54d91
PA
2831/* A thread found on the remote target. */
2832
2833typedef struct thread_item
2834{
2835 /* The thread's PTID. */
2836 ptid_t ptid;
2837
2838 /* The thread's extra info. May be NULL. */
2839 char *extra;
2840
79efa585
SM
2841 /* The thread's name. May be NULL. */
2842 char *name;
2843
6dc54d91
PA
2844 /* The core the thread was running on. -1 if not known. */
2845 int core;
2846} thread_item_t;
2847DEF_VEC_O(thread_item_t);
2848
2849/* Context passed around to the various methods listing remote
2850 threads. As new threads are found, they're added to the ITEMS
2851 vector. */
2852
2853struct threads_listing_context
2854{
2855 /* The threads found on the remote target. */
2856 VEC (thread_item_t) *items;
2857};
2858
80134cf5
PA
2859/* Discard the contents of the constructed thread listing context. */
2860
2861static void
2862clear_threads_listing_context (void *p)
2863{
19ba03f4
SM
2864 struct threads_listing_context *context
2865 = (struct threads_listing_context *) p;
80134cf5
PA
2866 int i;
2867 struct thread_item *item;
2868
2869 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
2870 {
2871 xfree (item->extra);
2872 xfree (item->name);
2873 }
80134cf5
PA
2874
2875 VEC_free (thread_item_t, context->items);
2876}
2877
cbb8991c
DB
2878/* Remove the thread specified as the related_pid field of WS
2879 from the CONTEXT list. */
2880
2881static void
2882threads_listing_context_remove (struct target_waitstatus *ws,
2883 struct threads_listing_context *context)
2884{
2885 struct thread_item *item;
2886 int i;
2887 ptid_t child_ptid = ws->value.related_pid;
2888
2889 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2890 {
2891 if (ptid_equal (item->ptid, child_ptid))
2892 {
2893 VEC_ordered_remove (thread_item_t, context->items, i);
2894 break;
2895 }
2896 }
2897}
2898
c906108c 2899static int
6dc54d91 2900remote_newthread_step (threadref *ref, void *data)
c906108c 2901{
19ba03f4
SM
2902 struct threads_listing_context *context
2903 = (struct threads_listing_context *) data;
6dc54d91 2904 struct thread_item item;
79d7f229 2905 int pid = ptid_get_pid (inferior_ptid);
39f77062 2906
6dc54d91
PA
2907 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2908 item.core = -1;
2909 item.extra = NULL;
2910
2911 VEC_safe_push (thread_item_t, context->items, &item);
2912
c906108c
SS
2913 return 1; /* continue iterator */
2914}
2915
2916#define CRAZY_MAX_THREADS 1000
2917
39f77062
KB
2918static ptid_t
2919remote_current_thread (ptid_t oldpid)
c906108c 2920{
d01949b6 2921 struct remote_state *rs = get_remote_state ();
c906108c
SS
2922
2923 putpkt ("qC");
6d820c5c 2924 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2925 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
2926 {
2927 char *obuf;
2928 ptid_t result;
2929
2930 result = read_ptid (&rs->buf[2], &obuf);
2931 if (*obuf != '\0' && remote_debug)
2932 fprintf_unfiltered (gdb_stdlog,
2933 "warning: garbage in qC reply\n");
2934
2935 return result;
2936 }
c906108c
SS
2937 else
2938 return oldpid;
2939}
2940
6dc54d91 2941/* List remote threads using the deprecated qL packet. */
cce74817 2942
6dc54d91
PA
2943static int
2944remote_get_threads_with_ql (struct target_ops *ops,
2945 struct threads_listing_context *context)
c906108c 2946{
6dc54d91
PA
2947 if (remote_threadlist_iterator (remote_newthread_step, context,
2948 CRAZY_MAX_THREADS) >= 0)
2949 return 1;
2950
2951 return 0;
c906108c
SS
2952}
2953
dc146f7c
VP
2954#if defined(HAVE_LIBEXPAT)
2955
dc146f7c
VP
2956static void
2957start_thread (struct gdb_xml_parser *parser,
2958 const struct gdb_xml_element *element,
2959 void *user_data, VEC(gdb_xml_value_s) *attributes)
2960{
19ba03f4
SM
2961 struct threads_listing_context *data
2962 = (struct threads_listing_context *) user_data;
dc146f7c
VP
2963
2964 struct thread_item item;
2965 char *id;
3d2c1d41 2966 struct gdb_xml_value *attr;
dc146f7c 2967
19ba03f4 2968 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2969 item.ptid = read_ptid (id, NULL);
2970
3d2c1d41
PA
2971 attr = xml_find_attribute (attributes, "core");
2972 if (attr != NULL)
2973 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2974 else
2975 item.core = -1;
2976
79efa585 2977 attr = xml_find_attribute (attributes, "name");
e1961661 2978 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 2979
dc146f7c
VP
2980 item.extra = 0;
2981
2982 VEC_safe_push (thread_item_t, data->items, &item);
2983}
2984
2985static void
2986end_thread (struct gdb_xml_parser *parser,
2987 const struct gdb_xml_element *element,
2988 void *user_data, const char *body_text)
2989{
19ba03f4
SM
2990 struct threads_listing_context *data
2991 = (struct threads_listing_context *) user_data;
dc146f7c
VP
2992
2993 if (body_text && *body_text)
2ae2a0b7 2994 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2995}
2996
2997const struct gdb_xml_attribute thread_attributes[] = {
2998 { "id", GDB_XML_AF_NONE, NULL, NULL },
2999 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3000 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3001 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3002};
3003
3004const struct gdb_xml_element thread_children[] = {
3005 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3006};
3007
3008const struct gdb_xml_element threads_children[] = {
3009 { "thread", thread_attributes, thread_children,
3010 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3011 start_thread, end_thread },
3012 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3013};
3014
3015const struct gdb_xml_element threads_elements[] = {
3016 { "threads", NULL, threads_children,
3017 GDB_XML_EF_NONE, NULL, NULL },
3018 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3019};
3020
3021#endif
3022
6dc54d91 3023/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3024
6dc54d91
PA
3025static int
3026remote_get_threads_with_qxfer (struct target_ops *ops,
3027 struct threads_listing_context *context)
0f71a2f6 3028{
dc146f7c 3029#if defined(HAVE_LIBEXPAT)
4082afcc 3030 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3031 {
6dc54d91 3032 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3033 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3034
6dc54d91 3035 if (xml != NULL && *xml != '\0')
dc146f7c 3036 {
6dc54d91
PA
3037 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3038 threads_elements, xml, context);
dc146f7c
VP
3039 }
3040
3041 do_cleanups (back_to);
6dc54d91 3042 return 1;
dc146f7c
VP
3043 }
3044#endif
3045
6dc54d91
PA
3046 return 0;
3047}
3048
3049/* List remote threads using qfThreadInfo/qsThreadInfo. */
3050
3051static int
3052remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3053 struct threads_listing_context *context)
3054{
3055 struct remote_state *rs = get_remote_state ();
3056
b80fafe3 3057 if (rs->use_threadinfo_query)
9d1f7ab2 3058 {
6dc54d91
PA
3059 char *bufp;
3060
9d1f7ab2 3061 putpkt ("qfThreadInfo");
6d820c5c 3062 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3063 bufp = rs->buf;
9d1f7ab2 3064 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3065 {
9d1f7ab2
MS
3066 while (*bufp++ == 'm') /* reply contains one or more TID */
3067 {
3068 do
3069 {
6dc54d91
PA
3070 struct thread_item item;
3071
3072 item.ptid = read_ptid (bufp, &bufp);
3073 item.core = -1;
3074 item.extra = NULL;
3075
3076 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3077 }
3078 while (*bufp++ == ','); /* comma-separated list */
3079 putpkt ("qsThreadInfo");
6d820c5c 3080 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3081 bufp = rs->buf;
9d1f7ab2 3082 }
6dc54d91
PA
3083 return 1;
3084 }
3085 else
3086 {
3087 /* Packet not recognized. */
3088 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3089 }
3090 }
3091
6dc54d91
PA
3092 return 0;
3093}
3094
e8032dde 3095/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3096 targets. */
3097
3098static void
e8032dde 3099remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
3100{
3101 struct remote_state *rs = get_remote_state ();
3102 struct threads_listing_context context;
3103 struct cleanup *old_chain;
ab970af1 3104 int got_list = 0;
e8032dde 3105
6dc54d91
PA
3106 context.items = NULL;
3107 old_chain = make_cleanup (clear_threads_listing_context, &context);
3108
3109 /* We have a few different mechanisms to fetch the thread list. Try
3110 them all, starting with the most preferred one first, falling
3111 back to older methods. */
3112 if (remote_get_threads_with_qxfer (ops, &context)
3113 || remote_get_threads_with_qthreadinfo (ops, &context)
3114 || remote_get_threads_with_ql (ops, &context))
3115 {
3116 int i;
3117 struct thread_item *item;
ab970af1
PA
3118 struct thread_info *tp, *tmp;
3119
3120 got_list = 1;
3121
7d1a114c
PA
3122 if (VEC_empty (thread_item_t, context.items)
3123 && remote_thread_always_alive (ops, inferior_ptid))
3124 {
3125 /* Some targets don't really support threads, but still
3126 reply an (empty) thread list in response to the thread
3127 listing packets, instead of replying "packet not
3128 supported". Exit early so we don't delete the main
3129 thread. */
3130 do_cleanups (old_chain);
3131 return;
3132 }
3133
ab970af1
PA
3134 /* CONTEXT now holds the current thread list on the remote
3135 target end. Delete GDB-side threads no longer found on the
3136 target. */
8a06aea7 3137 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3138 {
ab970af1
PA
3139 for (i = 0;
3140 VEC_iterate (thread_item_t, context.items, i, item);
3141 ++i)
3142 {
3143 if (ptid_equal (item->ptid, tp->ptid))
3144 break;
3145 }
3146
3147 if (i == VEC_length (thread_item_t, context.items))
3148 {
3149 /* Not found. */
3150 delete_thread (tp->ptid);
3151 }
cbb8991c
DB
3152 }
3153
3154 /* Remove any unreported fork child threads from CONTEXT so
3155 that we don't interfere with follow fork, which is where
3156 creation of such threads is handled. */
3157 remove_new_fork_children (&context);
74531fed 3158
ab970af1 3159 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3160 for (i = 0;
3161 VEC_iterate (thread_item_t, context.items, i, item);
3162 ++i)
3163 {
3164 if (!ptid_equal (item->ptid, null_ptid))
3165 {
3166 struct private_thread_info *info;
3167 /* In non-stop mode, we assume new found threads are
3168 running until proven otherwise with a stop reply. In
3169 all-stop, we can only get here if all threads are
3170 stopped. */
6efcd9a8 3171 int running = target_is_non_stop_p () ? 1 : 0;
6dc54d91
PA
3172
3173 remote_notice_new_inferior (item->ptid, running);
3174
3175 info = demand_private_info (item->ptid);
3176 info->core = item->core;
3177 info->extra = item->extra;
3178 item->extra = NULL;
79efa585
SM
3179 info->name = item->name;
3180 item->name = NULL;
6dc54d91
PA
3181 }
3182 }
3183 }
3184
ab970af1
PA
3185 if (!got_list)
3186 {
3187 /* If no thread listing method is supported, then query whether
3188 each known thread is alive, one by one, with the T packet.
3189 If the target doesn't support threads at all, then this is a
3190 no-op. See remote_thread_alive. */
3191 prune_threads ();
3192 }
3193
6dc54d91 3194 do_cleanups (old_chain);
9d1f7ab2
MS
3195}
3196
802188a7 3197/*
9d1f7ab2
MS
3198 * Collect a descriptive string about the given thread.
3199 * The target may say anything it wants to about the thread
3200 * (typically info about its blocked / runnable state, name, etc.).
3201 * This string will appear in the info threads display.
802188a7 3202 *
9d1f7ab2
MS
3203 * Optional: targets are not required to implement this function.
3204 */
3205
3206static char *
c15906d8 3207remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3208{
d01949b6 3209 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3210 int result;
3211 int set;
3212 threadref id;
3213 struct gdb_ext_thread_info threadinfo;
23860348 3214 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3215 int n = 0; /* position in display_buf */
3216
5d93a237 3217 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3218 internal_error (__FILE__, __LINE__,
e2e0b3e5 3219 _("remote_threads_extra_info"));
9d1f7ab2 3220
60e569b9 3221 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3222 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3223 /* This is the main thread which was added by GDB. The remote
3224 server doesn't know about it. */
3225 return NULL;
3226
4082afcc 3227 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3228 {
3229 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3230
fe978cb0
PA
3231 if (info && info->priv)
3232 return info->priv->extra;
dc146f7c
VP
3233 else
3234 return NULL;
3235 }
3236
b80fafe3 3237 if (rs->use_threadextra_query)
9d1f7ab2 3238 {
82f73884
PA
3239 char *b = rs->buf;
3240 char *endb = rs->buf + get_remote_packet_size ();
3241
3242 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3243 b += strlen (b);
3244 write_ptid (b, endb, tp->ptid);
3245
2e9f7625 3246 putpkt (rs->buf);
6d820c5c 3247 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3248 if (rs->buf[0] != 0)
9d1f7ab2 3249 {
2e9f7625
DJ
3250 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3251 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3252 display_buf [result] = '\0';
9d1f7ab2
MS
3253 return display_buf;
3254 }
0f71a2f6 3255 }
9d1f7ab2
MS
3256
3257 /* If the above query fails, fall back to the old method. */
b80fafe3 3258 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3259 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3260 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3261 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3262 if (remote_get_threadinfo (&id, set, &threadinfo))
3263 if (threadinfo.active)
0f71a2f6 3264 {
9d1f7ab2 3265 if (*threadinfo.shortname)
2bc416ba 3266 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3267 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3268 if (*threadinfo.display)
2bc416ba 3269 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3270 " State: %s,", threadinfo.display);
9d1f7ab2 3271 if (*threadinfo.more_display)
2bc416ba 3272 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3273 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3274
3275 if (n > 0)
c5aa993b 3276 {
23860348 3277 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3278 if (',' == display_buf[n-1])
3279 display_buf[n-1] = ' ';
3280 return display_buf;
c5aa993b 3281 }
0f71a2f6 3282 }
9d1f7ab2 3283 return NULL;
0f71a2f6 3284}
c906108c 3285\f
c5aa993b 3286
0fb4aa4b 3287static int
61fc905d 3288remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3289 struct static_tracepoint_marker *marker)
3290{
3291 struct remote_state *rs = get_remote_state ();
3292 char *p = rs->buf;
3293
bba74b36 3294 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3295 p += strlen (p);
3296 p += hexnumstr (p, addr);
3297 putpkt (rs->buf);
3298 getpkt (&rs->buf, &rs->buf_size, 0);
3299 p = rs->buf;
3300
3301 if (*p == 'E')
3302 error (_("Remote failure reply: %s"), p);
3303
3304 if (*p++ == 'm')
3305 {
3306 parse_static_tracepoint_marker_definition (p, &p, marker);
3307 return 1;
3308 }
3309
3310 return 0;
3311}
3312
0fb4aa4b 3313static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3314remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3315 const char *strid)
0fb4aa4b
PA
3316{
3317 struct remote_state *rs = get_remote_state ();
3318 VEC(static_tracepoint_marker_p) *markers = NULL;
3319 struct static_tracepoint_marker *marker = NULL;
3320 struct cleanup *old_chain;
3321 char *p;
3322
3323 /* Ask for a first packet of static tracepoint marker
3324 definition. */
3325 putpkt ("qTfSTM");
3326 getpkt (&rs->buf, &rs->buf_size, 0);
3327 p = rs->buf;
3328 if (*p == 'E')
3329 error (_("Remote failure reply: %s"), p);
3330
3331 old_chain = make_cleanup (free_current_marker, &marker);
3332
3333 while (*p++ == 'm')
3334 {
3335 if (marker == NULL)
3336 marker = XCNEW (struct static_tracepoint_marker);
3337
3338 do
3339 {
3340 parse_static_tracepoint_marker_definition (p, &p, marker);
3341
3342 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3343 {
3344 VEC_safe_push (static_tracepoint_marker_p,
3345 markers, marker);
3346 marker = NULL;
3347 }
3348 else
3349 {
3350 release_static_tracepoint_marker (marker);
3351 memset (marker, 0, sizeof (*marker));
3352 }
3353 }
3354 while (*p++ == ','); /* comma-separated list */
3355 /* Ask for another packet of static tracepoint definition. */
3356 putpkt ("qTsSTM");
3357 getpkt (&rs->buf, &rs->buf_size, 0);
3358 p = rs->buf;
3359 }
3360
3361 do_cleanups (old_chain);
3362 return markers;
3363}
3364
3365\f
10760264
JB
3366/* Implement the to_get_ada_task_ptid function for the remote targets. */
3367
3368static ptid_t
1e6b91a4 3369remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3370{
ba348170 3371 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3372}
3373\f
3374
24b06219 3375/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3376
3377static void
fba45db2 3378extended_remote_restart (void)
c906108c 3379{
d01949b6 3380 struct remote_state *rs = get_remote_state ();
c906108c
SS
3381
3382 /* Send the restart command; for reasons I don't understand the
3383 remote side really expects a number after the "R". */
ea9c271d 3384 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3385 putpkt (rs->buf);
c906108c 3386
ad9a8f3f 3387 remote_fileio_reset ();
c906108c
SS
3388}
3389\f
3390/* Clean up connection to a remote debugger. */
3391
c906108c 3392static void
de90e03d 3393remote_close (struct target_ops *self)
c906108c 3394{
5d93a237
TT
3395 struct remote_state *rs = get_remote_state ();
3396
3397 if (rs->remote_desc == NULL)
d3fd5342
PA
3398 return; /* already closed */
3399
3400 /* Make sure we leave stdin registered in the event loop, and we
3401 don't leave the async SIGINT signal handler installed. */
e3594fd1 3402 remote_terminal_ours (self);
ce5ce7ed 3403
5d93a237
TT
3404 serial_close (rs->remote_desc);
3405 rs->remote_desc = NULL;
ce5ce7ed
PA
3406
3407 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3408 of all the inferiors and their threads we were controlling.
3409 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3410 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3411 inferior_ptid = null_ptid;
f67fd822 3412 discard_all_inferiors ();
ce5ce7ed 3413
f48ff2a7
YQ
3414 /* We are closing the remote target, so we should discard
3415 everything of this target. */
bcc75809 3416 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3417
3418 if (remote_async_inferior_event_token)
3419 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3420
5965e028 3421 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3422
3423 trace_reset_local_state ();
c906108c
SS
3424}
3425
23860348 3426/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3427
3428static void
fba45db2 3429get_offsets (void)
c906108c 3430{
d01949b6 3431 struct remote_state *rs = get_remote_state ();
2e9f7625 3432 char *buf;
085dd6e6 3433 char *ptr;
31d99776
DJ
3434 int lose, num_segments = 0, do_sections, do_segments;
3435 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3436 struct section_offsets *offs;
31d99776
DJ
3437 struct symfile_segment_data *data;
3438
3439 if (symfile_objfile == NULL)
3440 return;
c906108c
SS
3441
3442 putpkt ("qOffsets");
6d820c5c 3443 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3444 buf = rs->buf;
c906108c
SS
3445
3446 if (buf[0] == '\000')
3447 return; /* Return silently. Stub doesn't support
23860348 3448 this command. */
c906108c
SS
3449 if (buf[0] == 'E')
3450 {
8a3fe4f8 3451 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3452 return;
3453 }
3454
3455 /* Pick up each field in turn. This used to be done with scanf, but
3456 scanf will make trouble if CORE_ADDR size doesn't match
3457 conversion directives correctly. The following code will work
3458 with any size of CORE_ADDR. */
3459 text_addr = data_addr = bss_addr = 0;
3460 ptr = buf;
3461 lose = 0;
3462
61012eef 3463 if (startswith (ptr, "Text="))
c906108c
SS
3464 {
3465 ptr += 5;
3466 /* Don't use strtol, could lose on big values. */
3467 while (*ptr && *ptr != ';')
3468 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3469
61012eef 3470 if (startswith (ptr, ";Data="))
31d99776
DJ
3471 {
3472 ptr += 6;
3473 while (*ptr && *ptr != ';')
3474 data_addr = (data_addr << 4) + fromhex (*ptr++);
3475 }
3476 else
3477 lose = 1;
3478
61012eef 3479 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3480 {
3481 ptr += 5;
3482 while (*ptr && *ptr != ';')
3483 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3484
31d99776
DJ
3485 if (bss_addr != data_addr)
3486 warning (_("Target reported unsupported offsets: %s"), buf);
3487 }
3488 else
3489 lose = 1;
3490 }
61012eef 3491 else if (startswith (ptr, "TextSeg="))
c906108c 3492 {
31d99776
DJ
3493 ptr += 8;
3494 /* Don't use strtol, could lose on big values. */
c906108c 3495 while (*ptr && *ptr != ';')
31d99776
DJ
3496 text_addr = (text_addr << 4) + fromhex (*ptr++);
3497 num_segments = 1;
3498
61012eef 3499 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3500 {
3501 ptr += 9;
3502 while (*ptr && *ptr != ';')
3503 data_addr = (data_addr << 4) + fromhex (*ptr++);
3504 num_segments++;
3505 }
c906108c
SS
3506 }
3507 else
3508 lose = 1;
3509
3510 if (lose)
8a3fe4f8 3511 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3512 else if (*ptr != '\0')
3513 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3514
802188a7 3515 offs = ((struct section_offsets *)
a39a16c4 3516 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3517 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3518 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3519
31d99776
DJ
3520 data = get_symfile_segment_data (symfile_objfile->obfd);
3521 do_segments = (data != NULL);
3522 do_sections = num_segments == 0;
c906108c 3523
28c32713 3524 if (num_segments > 0)
31d99776 3525 {
31d99776
DJ
3526 segments[0] = text_addr;
3527 segments[1] = data_addr;
3528 }
28c32713
JB
3529 /* If we have two segments, we can still try to relocate everything
3530 by assuming that the .text and .data offsets apply to the whole
3531 text and data segments. Convert the offsets given in the packet
3532 to base addresses for symfile_map_offsets_to_segments. */
3533 else if (data && data->num_segments == 2)
3534 {
3535 segments[0] = data->segment_bases[0] + text_addr;
3536 segments[1] = data->segment_bases[1] + data_addr;
3537 num_segments = 2;
3538 }
8d385431
DJ
3539 /* If the object file has only one segment, assume that it is text
3540 rather than data; main programs with no writable data are rare,
3541 but programs with no code are useless. Of course the code might
3542 have ended up in the data segment... to detect that we would need
3543 the permissions here. */
3544 else if (data && data->num_segments == 1)
3545 {
3546 segments[0] = data->segment_bases[0] + text_addr;
3547 num_segments = 1;
3548 }
28c32713
JB
3549 /* There's no way to relocate by segment. */
3550 else
3551 do_segments = 0;
31d99776
DJ
3552
3553 if (do_segments)
3554 {
3555 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3556 offs, num_segments, segments);
3557
3558 if (ret == 0 && !do_sections)
3e43a32a
MS
3559 error (_("Can not handle qOffsets TextSeg "
3560 "response with this symbol file"));
31d99776
DJ
3561
3562 if (ret > 0)
3563 do_sections = 0;
3564 }
c906108c 3565
9ef895d6
DJ
3566 if (data)
3567 free_symfile_segment_data (data);
31d99776
DJ
3568
3569 if (do_sections)
3570 {
3571 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3572
3e43a32a
MS
3573 /* This is a temporary kludge to force data and bss to use the
3574 same offsets because that's what nlmconv does now. The real
3575 solution requires changes to the stub and remote.c that I
3576 don't have time to do right now. */
31d99776
DJ
3577
3578 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3579 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3580 }
c906108c
SS
3581
3582 objfile_relocate (symfile_objfile, offs);
3583}
3584
9a7071a8
JB
3585/* Send interrupt_sequence to remote target. */
3586static void
eeae04df 3587send_interrupt_sequence (void)
9a7071a8 3588{
5d93a237
TT
3589 struct remote_state *rs = get_remote_state ();
3590
9a7071a8 3591 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3592 remote_serial_write ("\x03", 1);
9a7071a8 3593 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3594 serial_send_break (rs->remote_desc);
9a7071a8
JB
3595 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3596 {
5d93a237 3597 serial_send_break (rs->remote_desc);
c33e31fd 3598 remote_serial_write ("g", 1);
9a7071a8
JB
3599 }
3600 else
3601 internal_error (__FILE__, __LINE__,
3602 _("Invalid value for interrupt_sequence_mode: %s."),
3603 interrupt_sequence_mode);
3604}
3605
3405876a
PA
3606
3607/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3608 and extract the PTID. Returns NULL_PTID if not found. */
3609
3610static ptid_t
3611stop_reply_extract_thread (char *stop_reply)
3612{
3613 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3614 {
3615 char *p;
3616
3617 /* Txx r:val ; r:val (...) */
3618 p = &stop_reply[3];
3619
3620 /* Look for "register" named "thread". */
3621 while (*p != '\0')
3622 {
3623 char *p1;
3624
3625 p1 = strchr (p, ':');
3626 if (p1 == NULL)
3627 return null_ptid;
3628
3629 if (strncmp (p, "thread", p1 - p) == 0)
3630 return read_ptid (++p1, &p);
3631
3632 p1 = strchr (p, ';');
3633 if (p1 == NULL)
3634 return null_ptid;
3635 p1++;
3636
3637 p = p1;
3638 }
3639 }
3640
3641 return null_ptid;
3642}
3643
b7ea362b
PA
3644/* Determine the remote side's current thread. If we have a stop
3645 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3646 "thread" register we can extract the current thread from. If not,
3647 ask the remote which is the current thread with qC. The former
3648 method avoids a roundtrip. */
3649
3650static ptid_t
3651get_current_thread (char *wait_status)
3652{
6a49a997 3653 ptid_t ptid = null_ptid;
b7ea362b
PA
3654
3655 /* Note we don't use remote_parse_stop_reply as that makes use of
3656 the target architecture, which we haven't yet fully determined at
3657 this point. */
3658 if (wait_status != NULL)
3659 ptid = stop_reply_extract_thread (wait_status);
3660 if (ptid_equal (ptid, null_ptid))
3661 ptid = remote_current_thread (inferior_ptid);
3662
3663 return ptid;
3664}
3665
49c62f2e
PA
3666/* Query the remote target for which is the current thread/process,
3667 add it to our tables, and update INFERIOR_PTID. The caller is
3668 responsible for setting the state such that the remote end is ready
3405876a
PA
3669 to return the current thread.
3670
3671 This function is called after handling the '?' or 'vRun' packets,
3672 whose response is a stop reply from which we can also try
3673 extracting the thread. If the target doesn't support the explicit
3674 qC query, we infer the current thread from that stop reply, passed
3675 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3676
3677static void
3405876a 3678add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3679{
3680 struct remote_state *rs = get_remote_state ();
3681 int fake_pid_p = 0;
6a49a997 3682 ptid_t ptid;
49c62f2e
PA
3683
3684 inferior_ptid = null_ptid;
3685
b7ea362b
PA
3686 /* Now, if we have thread information, update inferior_ptid. */
3687 ptid = get_current_thread (wait_status);
3405876a 3688
49c62f2e
PA
3689 if (!ptid_equal (ptid, null_ptid))
3690 {
3691 if (!remote_multi_process_p (rs))
3692 fake_pid_p = 1;
3693
3694 inferior_ptid = ptid;
3695 }
3696 else
3697 {
3698 /* Without this, some commands which require an active target
3699 (such as kill) won't work. This variable serves (at least)
3700 double duty as both the pid of the target process (if it has
3701 such), and as a flag indicating that a target is active. */
3702 inferior_ptid = magic_null_ptid;
3703 fake_pid_p = 1;
3704 }
3705
1b6e6f5c 3706 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3707
3708 /* Add the main thread. */
3709 add_thread_silent (inferior_ptid);
3710}
3711
6efcd9a8
PA
3712/* Print info about a thread that was found already stopped on
3713 connection. */
3714
3715static void
3716print_one_stopped_thread (struct thread_info *thread)
3717{
3718 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3719
3720 switch_to_thread (thread->ptid);
3721 stop_pc = get_frame_pc (get_current_frame ());
3722 set_current_sal_from_frame (get_current_frame ());
3723
3724 thread->suspend.waitstatus_pending_p = 0;
3725
3726 if (ws->kind == TARGET_WAITKIND_STOPPED)
3727 {
3728 enum gdb_signal sig = ws->value.sig;
3729
3730 if (signal_print_state (sig))
3731 observer_notify_signal_received (sig);
3732 }
3733 observer_notify_normal_stop (NULL, 1);
3734}
3735
221e1a37
PA
3736/* Process all initial stop replies the remote side sent in response
3737 to the ? packet. These indicate threads that were already stopped
3738 on initial connection. We mark these threads as stopped and print
3739 their current frame before giving the user the prompt. */
3740
3741static void
6efcd9a8 3742process_initial_stop_replies (int from_tty)
221e1a37
PA
3743{
3744 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3745 struct inferior *inf;
3746 struct thread_info *thread;
3747 struct thread_info *selected = NULL;
3748 struct thread_info *lowest_stopped = NULL;
3749 struct thread_info *first = NULL;
221e1a37
PA
3750
3751 /* Consume the initial pending events. */
3752 while (pending_stop_replies-- > 0)
3753 {
3754 ptid_t waiton_ptid = minus_one_ptid;
3755 ptid_t event_ptid;
3756 struct target_waitstatus ws;
3757 int ignore_event = 0;
6efcd9a8 3758 struct thread_info *thread;
221e1a37
PA
3759
3760 memset (&ws, 0, sizeof (ws));
3761 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3762 if (remote_debug)
3763 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3764
3765 switch (ws.kind)
3766 {
3767 case TARGET_WAITKIND_IGNORE:
3768 case TARGET_WAITKIND_NO_RESUMED:
3769 case TARGET_WAITKIND_SIGNALLED:
3770 case TARGET_WAITKIND_EXITED:
3771 /* We shouldn't see these, but if we do, just ignore. */
3772 if (remote_debug)
3773 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3774 ignore_event = 1;
3775 break;
3776
3777 case TARGET_WAITKIND_EXECD:
3778 xfree (ws.value.execd_pathname);
3779 break;
3780 default:
3781 break;
3782 }
3783
3784 if (ignore_event)
3785 continue;
3786
6efcd9a8 3787 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3788
3789 if (ws.kind == TARGET_WAITKIND_STOPPED)
3790 {
3791 enum gdb_signal sig = ws.value.sig;
3792
3793 /* Stubs traditionally report SIGTRAP as initial signal,
3794 instead of signal 0. Suppress it. */
3795 if (sig == GDB_SIGNAL_TRAP)
3796 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3797 thread->suspend.stop_signal = sig;
3798 ws.value.sig = sig;
3799 }
221e1a37 3800
6efcd9a8
PA
3801 thread->suspend.waitstatus = ws;
3802
3803 if (ws.kind != TARGET_WAITKIND_STOPPED
3804 || ws.value.sig != GDB_SIGNAL_0)
3805 thread->suspend.waitstatus_pending_p = 1;
3806
3807 set_executing (event_ptid, 0);
3808 set_running (event_ptid, 0);
3809 }
3810
3811 /* "Notice" the new inferiors before anything related to
3812 registers/memory. */
3813 ALL_INFERIORS (inf)
3814 {
3815 if (inf->pid == 0)
3816 continue;
3817
3818 inf->needs_setup = 1;
3819
3820 if (non_stop)
3821 {
3822 thread = any_live_thread_of_process (inf->pid);
3823 notice_new_inferior (thread->ptid,
3824 thread->state == THREAD_RUNNING,
3825 from_tty);
3826 }
3827 }
3828
3829 /* If all-stop on top of non-stop, pause all threads. Note this
3830 records the threads' stop pc, so must be done after "noticing"
3831 the inferiors. */
3832 if (!non_stop)
3833 {
3834 stop_all_threads ();
3835
3836 /* If all threads of an inferior were already stopped, we
3837 haven't setup the inferior yet. */
3838 ALL_INFERIORS (inf)
3839 {
3840 if (inf->pid == 0)
3841 continue;
221e1a37 3842
6efcd9a8
PA
3843 if (inf->needs_setup)
3844 {
3845 thread = any_live_thread_of_process (inf->pid);
3846 switch_to_thread_no_regs (thread);
3847 setup_inferior (0);
3848 }
3849 }
221e1a37 3850 }
6efcd9a8
PA
3851
3852 /* Now go over all threads that are stopped, and print their current
3853 frame. If all-stop, then if there's a signalled thread, pick
3854 that as current. */
3855 ALL_NON_EXITED_THREADS (thread)
3856 {
3857 struct target_waitstatus *ws;
3858
3859 if (first == NULL)
3860 first = thread;
3861
3862 if (!non_stop)
3863 set_running (thread->ptid, 0);
3864 else if (thread->state != THREAD_STOPPED)
3865 continue;
3866
3867 ws = &thread->suspend.waitstatus;
3868
3869 if (selected == NULL
3870 && thread->suspend.waitstatus_pending_p)
3871 selected = thread;
3872
3873 if (lowest_stopped == NULL || thread->num < lowest_stopped->num)
3874 lowest_stopped = thread;
3875
3876 if (non_stop)
3877 print_one_stopped_thread (thread);
3878 }
3879
3880 /* In all-stop, we only print the status of one thread, and leave
3881 others with their status pending. */
3882 if (!non_stop)
3883 {
3884 thread = selected;
3885 if (thread == NULL)
3886 thread = lowest_stopped;
3887 if (thread == NULL)
3888 thread = first;
3889
3890 print_one_stopped_thread (thread);
3891 }
3892
3893 /* For "info program". */
3894 thread = inferior_thread ();
3895 if (thread->state == THREAD_STOPPED)
3896 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
3897}
3898
9cbc821d 3899static void
04bd08de 3900remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3901{
c8d104ad
PA
3902 struct remote_state *rs = get_remote_state ();
3903 struct packet_config *noack_config;
2d717e4f 3904 char *wait_status = NULL;
8621d6a9 3905
23860348 3906 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3907 QUIT;
c906108c 3908
9a7071a8
JB
3909 if (interrupt_on_connect)
3910 send_interrupt_sequence ();
3911
57e12211 3912 /* Ack any packet which the remote side has already sent. */
5d93a237 3913 serial_write (rs->remote_desc, "+", 1);
57e12211 3914
1e51243a
PA
3915 /* Signal other parts that we're going through the initial setup,
3916 and so things may not be stable yet. */
3917 rs->starting_up = 1;
3918
c8d104ad
PA
3919 /* The first packet we send to the target is the optional "supported
3920 packets" request. If the target can answer this, it will tell us
3921 which later probes to skip. */
3922 remote_query_supported ();
3923
d914c394 3924 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3925 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3926 remote_set_permissions (target);
d914c394 3927
c8d104ad
PA
3928 /* Next, we possibly activate noack mode.
3929
3930 If the QStartNoAckMode packet configuration is set to AUTO,
3931 enable noack mode if the stub reported a wish for it with
3932 qSupported.
3933
3934 If set to TRUE, then enable noack mode even if the stub didn't
3935 report it in qSupported. If the stub doesn't reply OK, the
3936 session ends with an error.
3937
3938 If FALSE, then don't activate noack mode, regardless of what the
3939 stub claimed should be the default with qSupported. */
3940
3941 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3942 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3943 {
3944 putpkt ("QStartNoAckMode");
3945 getpkt (&rs->buf, &rs->buf_size, 0);
3946 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3947 rs->noack_mode = 1;
3948 }
3949
04bd08de 3950 if (extended_p)
5fe04517
PA
3951 {
3952 /* Tell the remote that we are using the extended protocol. */
3953 putpkt ("!");
3954 getpkt (&rs->buf, &rs->buf_size, 0);
3955 }
3956
9b224c5e
PA
3957 /* Let the target know which signals it is allowed to pass down to
3958 the program. */
3959 update_signals_program_target ();
3960
d962ef82
DJ
3961 /* Next, if the target can specify a description, read it. We do
3962 this before anything involving memory or registers. */
3963 target_find_description ();
3964
6c95b8df
PA
3965 /* Next, now that we know something about the target, update the
3966 address spaces in the program spaces. */
3967 update_address_spaces ();
3968
50c71eaf
PA
3969 /* On OSs where the list of libraries is global to all
3970 processes, we fetch them early. */
f5656ead 3971 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3972 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3973
6efcd9a8 3974 if (target_is_non_stop_p ())
74531fed 3975 {
4082afcc 3976 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3977 error (_("Non-stop mode requested, but remote "
3978 "does not support non-stop"));
74531fed
PA
3979
3980 putpkt ("QNonStop:1");
3981 getpkt (&rs->buf, &rs->buf_size, 0);
3982
3983 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3984 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3985
3986 /* Find about threads and processes the stub is already
3987 controlling. We default to adding them in the running state.
3988 The '?' query below will then tell us about which threads are
3989 stopped. */
e8032dde 3990 remote_update_thread_list (target);
74531fed 3991 }
4082afcc 3992 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3993 {
3994 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3995 Request it explicitly. */
74531fed
PA
3996 putpkt ("QNonStop:0");
3997 getpkt (&rs->buf, &rs->buf_size, 0);
3998
3999 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4000 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4001 }
4002
a0743c90
YQ
4003 /* Upload TSVs regardless of whether the target is running or not. The
4004 remote stub, such as GDBserver, may have some predefined or builtin
4005 TSVs, even if the target is not running. */
8bd200f1 4006 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4007 {
4008 struct uploaded_tsv *uploaded_tsvs = NULL;
4009
181e3713 4010 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4011 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4012 }
4013
2d717e4f
DJ
4014 /* Check whether the target is running now. */
4015 putpkt ("?");
4016 getpkt (&rs->buf, &rs->buf_size, 0);
4017
6efcd9a8 4018 if (!target_is_non_stop_p ())
2d717e4f 4019 {
e714e1bf
UW
4020 ptid_t ptid;
4021 int fake_pid_p = 0;
4022 struct inferior *inf;
4023
74531fed 4024 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4025 {
04bd08de 4026 if (!extended_p)
74531fed 4027 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4028
4029 /* We're connected, but not running. Drop out before we
4030 call start_remote. */
e278ad5b 4031 rs->starting_up = 0;
c35b1492 4032 return;
2d717e4f
DJ
4033 }
4034 else
74531fed 4035 {
74531fed 4036 /* Save the reply for later. */
224c3ddb 4037 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4038 strcpy (wait_status, rs->buf);
4039 }
4040
b7ea362b 4041 /* Fetch thread list. */
e8032dde 4042 target_update_thread_list ();
b7ea362b 4043
74531fed
PA
4044 /* Let the stub know that we want it to return the thread. */
4045 set_continue_thread (minus_one_ptid);
4046
b7ea362b
PA
4047 if (thread_count () == 0)
4048 {
4049 /* Target has no concept of threads at all. GDB treats
4050 non-threaded target as single-threaded; add a main
4051 thread. */
4052 add_current_inferior_and_thread (wait_status);
4053 }
4054 else
4055 {
4056 /* We have thread information; select the thread the target
4057 says should be current. If we're reconnecting to a
4058 multi-threaded program, this will ideally be the thread
4059 that last reported an event before GDB disconnected. */
4060 inferior_ptid = get_current_thread (wait_status);
4061 if (ptid_equal (inferior_ptid, null_ptid))
4062 {
4063 /* Odd... The target was able to list threads, but not
4064 tell us which thread was current (no "thread"
4065 register in T stop reply?). Just pick the first
4066 thread in the thread list then. */
c9f35b34
KB
4067
4068 if (remote_debug)
4069 fprintf_unfiltered (gdb_stdlog,
4070 "warning: couldn't determine remote "
4071 "current thread; picking first in list.\n");
4072
b7ea362b
PA
4073 inferior_ptid = thread_list->ptid;
4074 }
4075 }
74531fed 4076
6e586cc5
YQ
4077 /* init_wait_for_inferior should be called before get_offsets in order
4078 to manage `inserted' flag in bp loc in a correct state.
4079 breakpoint_init_inferior, called from init_wait_for_inferior, set
4080 `inserted' flag to 0, while before breakpoint_re_set, called from
4081 start_remote, set `inserted' flag to 1. In the initialization of
4082 inferior, breakpoint_init_inferior should be called first, and then
4083 breakpoint_re_set can be called. If this order is broken, state of
4084 `inserted' flag is wrong, and cause some problems on breakpoint
4085 manipulation. */
4086 init_wait_for_inferior ();
4087
74531fed
PA
4088 get_offsets (); /* Get text, data & bss offsets. */
4089
d962ef82
DJ
4090 /* If we could not find a description using qXfer, and we know
4091 how to do it some other way, try again. This is not
4092 supported for non-stop; it could be, but it is tricky if
4093 there are no stopped threads when we connect. */
04bd08de 4094 if (remote_read_description_p (target)
f5656ead 4095 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4096 {
4097 target_clear_description ();
4098 target_find_description ();
4099 }
4100
74531fed
PA
4101 /* Use the previously fetched status. */
4102 gdb_assert (wait_status != NULL);
4103 strcpy (rs->buf, wait_status);
4104 rs->cached_wait_status = 1;
4105
4106 immediate_quit--;
04bd08de 4107 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4108 }
4109 else
4110 {
68c97600
PA
4111 /* Clear WFI global state. Do this before finding about new
4112 threads and inferiors, and setting the current inferior.
4113 Otherwise we would clear the proceed status of the current
4114 inferior when we want its stop_soon state to be preserved
4115 (see notice_new_inferior). */
4116 init_wait_for_inferior ();
4117
74531fed
PA
4118 /* In non-stop, we will either get an "OK", meaning that there
4119 are no stopped threads at this time; or, a regular stop
4120 reply. In the latter case, there may be more than one thread
4121 stopped --- we pull them all out using the vStopped
4122 mechanism. */
4123 if (strcmp (rs->buf, "OK") != 0)
4124 {
722247f1 4125 struct notif_client *notif = &notif_client_stop;
2d717e4f 4126
722247f1
YQ
4127 /* remote_notif_get_pending_replies acks this one, and gets
4128 the rest out. */
f48ff2a7 4129 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4130 = remote_notif_parse (notif, rs->buf);
4131 remote_notif_get_pending_events (notif);
74531fed 4132 }
2d717e4f 4133
74531fed
PA
4134 if (thread_count () == 0)
4135 {
04bd08de 4136 if (!extended_p)
74531fed 4137 error (_("The target is not running (try extended-remote?)"));
82f73884 4138
c35b1492
PA
4139 /* We're connected, but not running. Drop out before we
4140 call start_remote. */
e278ad5b 4141 rs->starting_up = 0;
c35b1492
PA
4142 return;
4143 }
74531fed 4144
74531fed
PA
4145 /* In non-stop mode, any cached wait status will be stored in
4146 the stop reply queue. */
4147 gdb_assert (wait_status == NULL);
f0223081 4148
2455069d 4149 /* Report all signals during attach/startup. */
94bedb42 4150 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4151
4152 /* If there are already stopped threads, mark them stopped and
4153 report their stops before giving the prompt to the user. */
6efcd9a8 4154 process_initial_stop_replies (from_tty);
221e1a37
PA
4155
4156 if (target_can_async_p ())
4157 target_async (1);
74531fed 4158 }
c8d104ad 4159
c8d104ad
PA
4160 /* If we connected to a live target, do some additional setup. */
4161 if (target_has_execution)
4162 {
f4ccffad 4163 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4164 remote_check_symbols ();
c8d104ad 4165 }
50c71eaf 4166
d5551862
SS
4167 /* Possibly the target has been engaged in a trace run started
4168 previously; find out where things are at. */
8bd200f1 4169 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4170 {
00bf0b85 4171 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4172
00bf0b85
SS
4173 if (current_trace_status ()->running)
4174 printf_filtered (_("Trace is already running on the target.\n"));
4175
ab6617cc 4176 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4177
4178 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4179 }
4180
1e51243a
PA
4181 /* The thread and inferior lists are now synchronized with the
4182 target, our symbols have been relocated, and we're merged the
4183 target's tracepoints with ours. We're done with basic start
4184 up. */
4185 rs->starting_up = 0;
4186
a25a5a45
PA
4187 /* Maybe breakpoints are global and need to be inserted now. */
4188 if (breakpoints_should_be_inserted_now ())
50c71eaf 4189 insert_breakpoints ();
c906108c
SS
4190}
4191
4192/* Open a connection to a remote debugger.
4193 NAME is the filename used for communication. */
4194
4195static void
014f9477 4196remote_open (const char *name, int from_tty)
c906108c 4197{
75c99385 4198 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4199}
4200
c906108c
SS
4201/* Open a connection to a remote debugger using the extended
4202 remote gdb protocol. NAME is the filename used for communication. */
4203
4204static void
014f9477 4205extended_remote_open (const char *name, int from_tty)
c906108c 4206{
75c99385 4207 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4208}
4209
ca4f7f8b
PA
4210/* Reset all packets back to "unknown support". Called when opening a
4211 new connection to a remote target. */
c906108c 4212
d471ea57 4213static void
ca4f7f8b 4214reset_all_packet_configs_support (void)
d471ea57
AC
4215{
4216 int i;
a744cf53 4217
444abaca 4218 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4219 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4220}
4221
ca4f7f8b
PA
4222/* Initialize all packet configs. */
4223
4224static void
4225init_all_packet_configs (void)
4226{
4227 int i;
4228
4229 for (i = 0; i < PACKET_MAX; i++)
4230 {
4231 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4232 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4233 }
4234}
4235
23860348 4236/* Symbol look-up. */
dc8acb97
MS
4237
4238static void
36d25514 4239remote_check_symbols (void)
dc8acb97 4240{
d01949b6 4241 struct remote_state *rs = get_remote_state ();
dc8acb97 4242 char *msg, *reply, *tmp;
3b7344d5 4243 struct bound_minimal_symbol sym;
dc8acb97 4244 int end;
a5c0808e 4245 struct cleanup *old_chain;
dc8acb97 4246
63154eca
PA
4247 /* The remote side has no concept of inferiors that aren't running
4248 yet, it only knows about running processes. If we're connected
4249 but our current inferior is not running, we should not invite the
4250 remote target to request symbol lookups related to its
4251 (unrelated) current process. */
4252 if (!target_has_execution)
4253 return;
4254
4082afcc 4255 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4256 return;
4257
63154eca
PA
4258 /* Make sure the remote is pointing at the right process. Note
4259 there's no way to select "no process". */
3c9c4b83
PA
4260 set_general_process ();
4261
6d820c5c
DJ
4262 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4263 because we need both at the same time. */
224c3ddb 4264 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4265 old_chain = make_cleanup (xfree, msg);
6d820c5c 4266
23860348 4267 /* Invite target to request symbol lookups. */
dc8acb97
MS
4268
4269 putpkt ("qSymbol::");
6d820c5c
DJ
4270 getpkt (&rs->buf, &rs->buf_size, 0);
4271 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 4272 reply = rs->buf;
dc8acb97 4273
61012eef 4274 while (startswith (reply, "qSymbol:"))
dc8acb97 4275 {
77e371c0
TT
4276 struct bound_minimal_symbol sym;
4277
dc8acb97 4278 tmp = &reply[8];
cfd77fa1 4279 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4280 msg[end] = '\0';
4281 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4282 if (sym.minsym == NULL)
ea9c271d 4283 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4284 else
2bbe3cc1 4285 {
f5656ead 4286 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4287 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4288
4289 /* If this is a function address, return the start of code
4290 instead of any data function descriptor. */
f5656ead 4291 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4292 sym_addr,
4293 &current_target);
4294
4295 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4296 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4297 }
4298
dc8acb97 4299 putpkt (msg);
6d820c5c 4300 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4301 reply = rs->buf;
dc8acb97 4302 }
a5c0808e
PA
4303
4304 do_cleanups (old_chain);
dc8acb97
MS
4305}
4306
9db8d71f 4307static struct serial *
baa336ce 4308remote_serial_open (const char *name)
9db8d71f
DJ
4309{
4310 static int udp_warning = 0;
4311
4312 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4313 of in ser-tcp.c, because it is the remote protocol assuming that the
4314 serial connection is reliable and not the serial connection promising
4315 to be. */
61012eef 4316 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4317 {
3e43a32a
MS
4318 warning (_("The remote protocol may be unreliable over UDP.\n"
4319 "Some events may be lost, rendering further debugging "
4320 "impossible."));
9db8d71f
DJ
4321 udp_warning = 1;
4322 }
4323
4324 return serial_open (name);
4325}
4326
d914c394
SS
4327/* Inform the target of our permission settings. The permission flags
4328 work without this, but if the target knows the settings, it can do
4329 a couple things. First, it can add its own check, to catch cases
4330 that somehow manage to get by the permissions checks in target
4331 methods. Second, if the target is wired to disallow particular
4332 settings (for instance, a system in the field that is not set up to
4333 be able to stop at a breakpoint), it can object to any unavailable
4334 permissions. */
4335
4336void
c378d69d 4337remote_set_permissions (struct target_ops *self)
d914c394
SS
4338{
4339 struct remote_state *rs = get_remote_state ();
4340
bba74b36
YQ
4341 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4342 "WriteReg:%x;WriteMem:%x;"
4343 "InsertBreak:%x;InsertTrace:%x;"
4344 "InsertFastTrace:%x;Stop:%x",
4345 may_write_registers, may_write_memory,
4346 may_insert_breakpoints, may_insert_tracepoints,
4347 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4348 putpkt (rs->buf);
4349 getpkt (&rs->buf, &rs->buf_size, 0);
4350
4351 /* If the target didn't like the packet, warn the user. Do not try
4352 to undo the user's settings, that would just be maddening. */
4353 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4354 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4355}
4356
be2a5f71
DJ
4357/* This type describes each known response to the qSupported
4358 packet. */
4359struct protocol_feature
4360{
4361 /* The name of this protocol feature. */
4362 const char *name;
4363
4364 /* The default for this protocol feature. */
4365 enum packet_support default_support;
4366
4367 /* The function to call when this feature is reported, or after
4368 qSupported processing if the feature is not supported.
4369 The first argument points to this structure. The second
4370 argument indicates whether the packet requested support be
4371 enabled, disabled, or probed (or the default, if this function
4372 is being called at the end of processing and this feature was
4373 not reported). The third argument may be NULL; if not NULL, it
4374 is a NUL-terminated string taken from the packet following
4375 this feature's name and an equals sign. */
4376 void (*func) (const struct protocol_feature *, enum packet_support,
4377 const char *);
4378
4379 /* The corresponding packet for this feature. Only used if
4380 FUNC is remote_supported_packet. */
4381 int packet;
4382};
4383
be2a5f71
DJ
4384static void
4385remote_supported_packet (const struct protocol_feature *feature,
4386 enum packet_support support,
4387 const char *argument)
4388{
4389 if (argument)
4390 {
4391 warning (_("Remote qSupported response supplied an unexpected value for"
4392 " \"%s\"."), feature->name);
4393 return;
4394 }
4395
4082afcc 4396 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4397}
be2a5f71
DJ
4398
4399static void
4400remote_packet_size (const struct protocol_feature *feature,
4401 enum packet_support support, const char *value)
4402{
4403 struct remote_state *rs = get_remote_state ();
4404
4405 int packet_size;
4406 char *value_end;
4407
4408 if (support != PACKET_ENABLE)
4409 return;
4410
4411 if (value == NULL || *value == '\0')
4412 {
4413 warning (_("Remote target reported \"%s\" without a size."),
4414 feature->name);
4415 return;
4416 }
4417
4418 errno = 0;
4419 packet_size = strtol (value, &value_end, 16);
4420 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4421 {
4422 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4423 feature->name, value);
4424 return;
4425 }
4426
be2a5f71
DJ
4427 /* Record the new maximum packet size. */
4428 rs->explicit_packet_size = packet_size;
4429}
4430
dc473cfb 4431static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4432 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4433 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4434 PACKET_qXfer_auxv },
c78fa86a
GB
4435 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4436 PACKET_qXfer_exec_file },
23181151
DJ
4437 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4438 PACKET_qXfer_features },
cfa9d6d9
DJ
4439 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4440 PACKET_qXfer_libraries },
2268b414
JK
4441 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4442 PACKET_qXfer_libraries_svr4 },
ced63ec0 4443 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4444 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4445 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4446 PACKET_qXfer_memory_map },
4de6483e
UW
4447 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4448 PACKET_qXfer_spu_read },
4449 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4450 PACKET_qXfer_spu_write },
07e059b5
VP
4451 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4452 PACKET_qXfer_osdata },
dc146f7c
VP
4453 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4454 PACKET_qXfer_threads },
b3b9301e
PA
4455 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4456 PACKET_qXfer_traceframe_info },
89be2091
DJ
4457 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4458 PACKET_QPassSignals },
9b224c5e
PA
4459 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4460 PACKET_QProgramSignals },
a6f3e723
SL
4461 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4462 PACKET_QStartNoAckMode },
4082afcc
PA
4463 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4464 PACKET_multiprocess_feature },
4465 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4466 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4467 PACKET_qXfer_siginfo_read },
4468 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4469 PACKET_qXfer_siginfo_write },
4082afcc 4470 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4471 PACKET_ConditionalTracepoints },
4082afcc 4472 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4473 PACKET_ConditionalBreakpoints },
4082afcc 4474 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4475 PACKET_BreakpointCommands },
4082afcc 4476 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4477 PACKET_FastTracepoints },
4082afcc 4478 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4479 PACKET_StaticTracepoints },
4082afcc 4480 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4481 PACKET_InstallInTrace},
4082afcc
PA
4482 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4483 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4484 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4485 PACKET_bc },
4486 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4487 PACKET_bs },
409873ef
SS
4488 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4489 PACKET_TracepointSource },
d914c394
SS
4490 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4491 PACKET_QAllow },
4082afcc
PA
4492 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4493 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4494 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4495 PACKET_qXfer_fdpic },
169081d0
TG
4496 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4497 PACKET_qXfer_uib },
03583c20
UW
4498 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4499 PACKET_QDisableRandomization },
d1feda86 4500 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4501 { "QTBuffer:size", PACKET_DISABLE,
4502 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4503 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4504 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4505 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4506 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4507 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4508 PACKET_qXfer_btrace },
4509 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4510 PACKET_qXfer_btrace_conf },
4511 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4512 PACKET_Qbtrace_conf_bts_size },
4513 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4514 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4515 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4516 PACKET_fork_event_feature },
4517 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4518 PACKET_vfork_event_feature },
94585166
DB
4519 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4520 PACKET_exec_event_feature },
b20a6524 4521 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1
YQ
4522 PACKET_Qbtrace_conf_pt_size },
4523 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported }
be2a5f71
DJ
4524};
4525
c8d5aac9
L
4526static char *remote_support_xml;
4527
4528/* Register string appended to "xmlRegisters=" in qSupported query. */
4529
4530void
6e39997a 4531register_remote_support_xml (const char *xml)
c8d5aac9
L
4532{
4533#if defined(HAVE_LIBEXPAT)
4534 if (remote_support_xml == NULL)
c4f7c687 4535 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4536 else
4537 {
4538 char *copy = xstrdup (remote_support_xml + 13);
4539 char *p = strtok (copy, ",");
4540
4541 do
4542 {
4543 if (strcmp (p, xml) == 0)
4544 {
4545 /* already there */
4546 xfree (copy);
4547 return;
4548 }
4549 }
4550 while ((p = strtok (NULL, ",")) != NULL);
4551 xfree (copy);
4552
94b0dee1
PA
4553 remote_support_xml = reconcat (remote_support_xml,
4554 remote_support_xml, ",", xml,
4555 (char *) NULL);
c8d5aac9
L
4556 }
4557#endif
4558}
4559
4560static char *
4561remote_query_supported_append (char *msg, const char *append)
4562{
4563 if (msg)
94b0dee1 4564 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4565 else
4566 return xstrdup (append);
4567}
4568
be2a5f71
DJ
4569static void
4570remote_query_supported (void)
4571{
4572 struct remote_state *rs = get_remote_state ();
4573 char *next;
4574 int i;
4575 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4576
4577 /* The packet support flags are handled differently for this packet
4578 than for most others. We treat an error, a disabled packet, and
4579 an empty response identically: any features which must be reported
4580 to be used will be automatically disabled. An empty buffer
4581 accomplishes this, since that is also the representation for a list
4582 containing no features. */
4583
4584 rs->buf[0] = 0;
4082afcc 4585 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4586 {
c8d5aac9 4587 char *q = NULL;
94b0dee1 4588 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4589
73b8c1fd
PA
4590 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4591 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4592
f7e6eed5
PA
4593 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4594 q = remote_query_supported_append (q, "swbreak+");
4595 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4596 q = remote_query_supported_append (q, "hwbreak+");
4597
dde08ee1
PA
4598 q = remote_query_supported_append (q, "qRelocInsn+");
4599
89245bc0
DB
4600 if (rs->extended)
4601 {
4602 if (packet_set_cmd_state (PACKET_fork_event_feature)
4603 != AUTO_BOOLEAN_FALSE)
4604 q = remote_query_supported_append (q, "fork-events+");
4605 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4606 != AUTO_BOOLEAN_FALSE)
4607 q = remote_query_supported_append (q, "vfork-events+");
94585166
DB
4608 if (packet_set_cmd_state (PACKET_exec_event_feature)
4609 != AUTO_BOOLEAN_FALSE)
4610 q = remote_query_supported_append (q, "exec-events+");
89245bc0
DB
4611 }
4612
750ce8d1
YQ
4613 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4614 q = remote_query_supported_append (q, "vContSupported+");
4615
b35d5edb
PA
4616 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4617 the qSupported:xmlRegisters=i386 handling. */
4618 if (remote_support_xml != NULL)
4619 q = remote_query_supported_append (q, remote_support_xml);
4620
dde08ee1
PA
4621 q = reconcat (q, "qSupported:", q, (char *) NULL);
4622 putpkt (q);
82f73884 4623
94b0dee1
PA
4624 do_cleanups (old_chain);
4625
be2a5f71
DJ
4626 getpkt (&rs->buf, &rs->buf_size, 0);
4627
4628 /* If an error occured, warn, but do not return - just reset the
4629 buffer to empty and go on to disable features. */
4630 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4631 == PACKET_ERROR)
4632 {
4633 warning (_("Remote failure reply: %s"), rs->buf);
4634 rs->buf[0] = 0;
4635 }
4636 }
4637
4638 memset (seen, 0, sizeof (seen));
4639
4640 next = rs->buf;
4641 while (*next)
4642 {
4643 enum packet_support is_supported;
4644 char *p, *end, *name_end, *value;
4645
4646 /* First separate out this item from the rest of the packet. If
4647 there's another item after this, we overwrite the separator
4648 (terminated strings are much easier to work with). */
4649 p = next;
4650 end = strchr (p, ';');
4651 if (end == NULL)
4652 {
4653 end = p + strlen (p);
4654 next = end;
4655 }
4656 else
4657 {
89be2091
DJ
4658 *end = '\0';
4659 next = end + 1;
4660
be2a5f71
DJ
4661 if (end == p)
4662 {
4663 warning (_("empty item in \"qSupported\" response"));
4664 continue;
4665 }
be2a5f71
DJ
4666 }
4667
4668 name_end = strchr (p, '=');
4669 if (name_end)
4670 {
4671 /* This is a name=value entry. */
4672 is_supported = PACKET_ENABLE;
4673 value = name_end + 1;
4674 *name_end = '\0';
4675 }
4676 else
4677 {
4678 value = NULL;
4679 switch (end[-1])
4680 {
4681 case '+':
4682 is_supported = PACKET_ENABLE;
4683 break;
4684
4685 case '-':
4686 is_supported = PACKET_DISABLE;
4687 break;
4688
4689 case '?':
4690 is_supported = PACKET_SUPPORT_UNKNOWN;
4691 break;
4692
4693 default:
3e43a32a
MS
4694 warning (_("unrecognized item \"%s\" "
4695 "in \"qSupported\" response"), p);
be2a5f71
DJ
4696 continue;
4697 }
4698 end[-1] = '\0';
4699 }
4700
4701 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4702 if (strcmp (remote_protocol_features[i].name, p) == 0)
4703 {
4704 const struct protocol_feature *feature;
4705
4706 seen[i] = 1;
4707 feature = &remote_protocol_features[i];
4708 feature->func (feature, is_supported, value);
4709 break;
4710 }
4711 }
4712
4713 /* If we increased the packet size, make sure to increase the global
4714 buffer size also. We delay this until after parsing the entire
4715 qSupported packet, because this is the same buffer we were
4716 parsing. */
4717 if (rs->buf_size < rs->explicit_packet_size)
4718 {
4719 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4720 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4721 }
4722
4723 /* Handle the defaults for unmentioned features. */
4724 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4725 if (!seen[i])
4726 {
4727 const struct protocol_feature *feature;
4728
4729 feature = &remote_protocol_features[i];
4730 feature->func (feature, feature->default_support, NULL);
4731 }
4732}
4733
78a095c3
JK
4734/* Remove any of the remote.c targets from target stack. Upper targets depend
4735 on it so remove them first. */
4736
4737static void
4738remote_unpush_target (void)
4739{
915ef8b1 4740 pop_all_targets_at_and_above (process_stratum);
78a095c3 4741}
be2a5f71 4742
c906108c 4743static void
014f9477 4744remote_open_1 (const char *name, int from_tty,
3e43a32a 4745 struct target_ops *target, int extended_p)
c906108c 4746{
d01949b6 4747 struct remote_state *rs = get_remote_state ();
a6f3e723 4748
c906108c 4749 if (name == 0)
8a3fe4f8 4750 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4751 "serial device is attached to the remote system\n"
8a3fe4f8 4752 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4753
23860348 4754 /* See FIXME above. */
c6ebd6cf 4755 if (!target_async_permitted)
92d1e331 4756 wait_forever_enabled_p = 1;
6426a772 4757
2d717e4f 4758 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4759 Ask this question first, before target_preopen has a chance to kill
4760 anything. */
5d93a237 4761 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4762 {
78a095c3
JK
4763 if (from_tty
4764 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4765 error (_("Still connected."));
4766 }
4767
78a095c3 4768 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4769 target_preopen (from_tty);
4770
89be2091 4771 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4772 xfree (rs->last_pass_packet);
4773 rs->last_pass_packet = NULL;
89be2091 4774
9b224c5e
PA
4775 /* Make sure we send the program signals list the next time we
4776 resume. */
5e4a05c4
TT
4777 xfree (rs->last_program_signals_packet);
4778 rs->last_program_signals_packet = NULL;
9b224c5e 4779
ad9a8f3f 4780 remote_fileio_reset ();
1dd41f16
NS
4781 reopen_exec_file ();
4782 reread_symbols ();
4783
5d93a237
TT
4784 rs->remote_desc = remote_serial_open (name);
4785 if (!rs->remote_desc)
c906108c
SS
4786 perror_with_name (name);
4787
4788 if (baud_rate != -1)
4789 {
5d93a237 4790 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4791 {
9b74d5d3
KB
4792 /* The requested speed could not be set. Error out to
4793 top level after closing remote_desc. Take care to
4794 set remote_desc to NULL to avoid closing remote_desc
4795 more than once. */
5d93a237
TT
4796 serial_close (rs->remote_desc);
4797 rs->remote_desc = NULL;
c906108c
SS
4798 perror_with_name (name);
4799 }
4800 }
4801
236af5e3 4802 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4803 serial_raw (rs->remote_desc);
c906108c
SS
4804
4805 /* If there is something sitting in the buffer we might take it as a
4806 response to a command, which would be bad. */
5d93a237 4807 serial_flush_input (rs->remote_desc);
c906108c
SS
4808
4809 if (from_tty)
4810 {
4811 puts_filtered ("Remote debugging using ");
4812 puts_filtered (name);
4813 puts_filtered ("\n");
4814 }
23860348 4815 push_target (target); /* Switch to using remote target now. */
c906108c 4816
74531fed
PA
4817 /* Register extra event sources in the event loop. */
4818 remote_async_inferior_event_token
4819 = create_async_event_handler (remote_async_inferior_event_handler,
4820 NULL);
5965e028 4821 rs->notif_state = remote_notif_state_allocate ();
74531fed 4822
be2a5f71
DJ
4823 /* Reset the target state; these things will be queried either by
4824 remote_query_supported or as they are needed. */
ca4f7f8b 4825 reset_all_packet_configs_support ();
74531fed 4826 rs->cached_wait_status = 0;
be2a5f71 4827 rs->explicit_packet_size = 0;
a6f3e723 4828 rs->noack_mode = 0;
82f73884 4829 rs->extended = extended_p;
e24a49d8 4830 rs->waiting_for_stop_reply = 0;
3a29589a 4831 rs->ctrlc_pending_p = 0;
802188a7 4832
47f8a51d
TT
4833 rs->general_thread = not_sent_ptid;
4834 rs->continue_thread = not_sent_ptid;
262e1174 4835 rs->remote_traceframe_number = -1;
c906108c 4836
9d1f7ab2 4837 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4838 rs->use_threadinfo_query = 1;
4839 rs->use_threadextra_query = 1;
9d1f7ab2 4840
80152258
PA
4841 readahead_cache_invalidate ();
4842
c6ebd6cf 4843 if (target_async_permitted)
92d1e331 4844 {
23860348 4845 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4846 remote_async_terminal_ours_p = 1;
4847
4848 /* FIXME: cagney/1999-09-23: During the initial connection it is
4849 assumed that the target is already ready and able to respond to
0df8b418 4850 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4851 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4852 around this. Eventually a mechanism that allows
92d1e331 4853 wait_for_inferior() to expect/get timeouts will be
23860348 4854 implemented. */
92d1e331
DJ
4855 wait_forever_enabled_p = 0;
4856 }
4857
23860348 4858 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4859 no_shared_libraries (NULL, 0);
f78f6cf1 4860
74531fed
PA
4861 /* Start afresh. */
4862 init_thread_list ();
4863
36918e70 4864 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4865 target (we'd otherwise be in an inconsistent state) and then
4866 propogate the error on up the exception chain. This ensures that
4867 the caller doesn't stumble along blindly assuming that the
4868 function succeeded. The CLI doesn't have this problem but other
4869 UI's, such as MI do.
36918e70
AC
4870
4871 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4872 this function should return an error indication letting the
ce2826aa 4873 caller restore the previous state. Unfortunately the command
36918e70
AC
4874 ``target remote'' is directly wired to this function making that
4875 impossible. On a positive note, the CLI side of this problem has
4876 been fixed - the function set_cmd_context() makes it possible for
4877 all the ``target ....'' commands to share a common callback
4878 function. See cli-dump.c. */
109c3e39 4879 {
2d717e4f 4880
492d29ea 4881 TRY
04bd08de
TT
4882 {
4883 remote_start_remote (from_tty, target, extended_p);
4884 }
492d29ea 4885 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4886 {
c8d104ad
PA
4887 /* Pop the partially set up target - unless something else did
4888 already before throwing the exception. */
5d93a237 4889 if (rs->remote_desc != NULL)
78a095c3 4890 remote_unpush_target ();
c6ebd6cf 4891 if (target_async_permitted)
109c3e39
AC
4892 wait_forever_enabled_p = 1;
4893 throw_exception (ex);
4894 }
492d29ea 4895 END_CATCH
109c3e39 4896 }
c906108c 4897
f4abbc16
MM
4898 remote_btrace_reset ();
4899
c6ebd6cf 4900 if (target_async_permitted)
92d1e331 4901 wait_forever_enabled_p = 1;
43ff13b4
JM
4902}
4903
de0d863e
DB
4904/* Detach the specified process. */
4905
4906static void
4907remote_detach_pid (int pid)
4908{
4909 struct remote_state *rs = get_remote_state ();
4910
4911 if (remote_multi_process_p (rs))
4912 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4913 else
4914 strcpy (rs->buf, "D");
4915
4916 putpkt (rs->buf);
4917 getpkt (&rs->buf, &rs->buf_size, 0);
4918
4919 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4920 ;
4921 else if (rs->buf[0] == '\0')
4922 error (_("Remote doesn't know how to detach"));
4923 else
4924 error (_("Can't detach process."));
4925}
4926
4927/* This detaches a program to which we previously attached, using
4928 inferior_ptid to identify the process. After this is done, GDB
4929 can be used to debug some other program. We better not have left
4930 any breakpoints in the target program or it'll die when it hits
4931 one. */
c906108c
SS
4932
4933static void
de0d863e 4934remote_detach_1 (const char *args, int from_tty)
c906108c 4935{
82f73884 4936 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4937 struct remote_state *rs = get_remote_state ();
de0d863e
DB
4938 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4939 int is_fork_parent;
c906108c
SS
4940
4941 if (args)
8a3fe4f8 4942 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4943
2d717e4f
DJ
4944 if (!target_has_execution)
4945 error (_("No process to detach from."));
4946
7cee1e54
PA
4947 if (from_tty)
4948 {
4949 char *exec_file = get_exec_file (0);
4950 if (exec_file == NULL)
4951 exec_file = "";
4952 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4953 target_pid_to_str (pid_to_ptid (pid)));
4954 gdb_flush (gdb_stdout);
4955 }
4956
c906108c 4957 /* Tell the remote target to detach. */
de0d863e 4958 remote_detach_pid (pid);
82f73884 4959
de0d863e 4960 if (from_tty && !rs->extended)
7cee1e54 4961 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4962
de0d863e
DB
4963 /* Check to see if we are detaching a fork parent. Note that if we
4964 are detaching a fork child, tp == NULL. */
4965 is_fork_parent = (tp != NULL
4966 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4967
4968 /* If doing detach-on-fork, we don't mourn, because that will delete
4969 breakpoints that should be available for the followed inferior. */
4970 if (!is_fork_parent)
4971 target_mourn_inferior ();
4972 else
4973 {
4974 inferior_ptid = null_ptid;
4975 detach_inferior (pid);
4976 }
2d717e4f
DJ
4977}
4978
4979static void
52554a0e 4980remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4981{
de0d863e 4982 remote_detach_1 (args, from_tty);
2d717e4f
DJ
4983}
4984
4985static void
52554a0e 4986extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4987{
de0d863e
DB
4988 remote_detach_1 (args, from_tty);
4989}
4990
4991/* Target follow-fork function for remote targets. On entry, and
4992 at return, the current inferior is the fork parent.
4993
4994 Note that although this is currently only used for extended-remote,
4995 it is named remote_follow_fork in anticipation of using it for the
4996 remote target as well. */
4997
4998static int
4999remote_follow_fork (struct target_ops *ops, int follow_child,
5000 int detach_fork)
5001{
5002 struct remote_state *rs = get_remote_state ();
c269dbdb 5003 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5004
c269dbdb
DB
5005 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5006 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5007 {
5008 /* When following the parent and detaching the child, we detach
5009 the child here. For the case of following the child and
5010 detaching the parent, the detach is done in the target-
5011 independent follow fork code in infrun.c. We can't use
5012 target_detach when detaching an unfollowed child because
5013 the client side doesn't know anything about the child. */
5014 if (detach_fork && !follow_child)
5015 {
5016 /* Detach the fork child. */
5017 ptid_t child_ptid;
5018 pid_t child_pid;
5019
5020 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5021 child_pid = ptid_get_pid (child_ptid);
5022
5023 remote_detach_pid (child_pid);
5024 detach_inferior (child_pid);
5025 }
5026 }
5027 return 0;
c906108c
SS
5028}
5029
94585166
DB
5030/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5031 in the program space of the new inferior. On entry and at return the
5032 current inferior is the exec'ing inferior. INF is the new exec'd
5033 inferior, which may be the same as the exec'ing inferior unless
5034 follow-exec-mode is "new". */
5035
5036static void
5037remote_follow_exec (struct target_ops *ops,
5038 struct inferior *inf, char *execd_pathname)
5039{
5040 /* We know that this is a target file name, so if it has the "target:"
5041 prefix we strip it off before saving it in the program space. */
5042 if (is_target_filename (execd_pathname))
5043 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5044
5045 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5046}
5047
6ad8ae5c
DJ
5048/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5049
43ff13b4 5050static void
fee354ee 5051remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5052{
43ff13b4 5053 if (args)
2d717e4f 5054 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5055
2d717e4f 5056 /* Make sure we unpush even the extended remote targets; mourn
20f796c9 5057 won't do it. So call remote_mourn directly instead of
2d717e4f 5058 target_mourn_inferior. */
20f796c9 5059 remote_mourn (target);
2d717e4f 5060
43ff13b4
JM
5061 if (from_tty)
5062 puts_filtered ("Ending remote debugging.\n");
5063}
5064
2d717e4f
DJ
5065/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5066 be chatty about it. */
5067
5068static void
20f796c9
GB
5069extended_remote_attach (struct target_ops *target, const char *args,
5070 int from_tty)
2d717e4f
DJ
5071{
5072 struct remote_state *rs = get_remote_state ();
be86555c 5073 int pid;
96ef3384 5074 char *wait_status = NULL;
2d717e4f 5075
74164c56 5076 pid = parse_pid_to_attach (args);
2d717e4f 5077
74164c56
JK
5078 /* Remote PID can be freely equal to getpid, do not check it here the same
5079 way as in other targets. */
2d717e4f 5080
4082afcc 5081 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5082 error (_("This target does not support attaching to a process"));
5083
7cee1e54
PA
5084 if (from_tty)
5085 {
5086 char *exec_file = get_exec_file (0);
5087
5088 if (exec_file)
5089 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5090 target_pid_to_str (pid_to_ptid (pid)));
5091 else
5092 printf_unfiltered (_("Attaching to %s\n"),
5093 target_pid_to_str (pid_to_ptid (pid)));
5094
5095 gdb_flush (gdb_stdout);
5096 }
5097
bba74b36 5098 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5099 putpkt (rs->buf);
5100 getpkt (&rs->buf, &rs->buf_size, 0);
5101
4082afcc
PA
5102 switch (packet_ok (rs->buf,
5103 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5104 {
4082afcc 5105 case PACKET_OK:
6efcd9a8 5106 if (!target_is_non_stop_p ())
74531fed
PA
5107 {
5108 /* Save the reply for later. */
224c3ddb 5109 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5110 strcpy (wait_status, rs->buf);
5111 }
5112 else if (strcmp (rs->buf, "OK") != 0)
5113 error (_("Attaching to %s failed with: %s"),
5114 target_pid_to_str (pid_to_ptid (pid)),
5115 rs->buf);
4082afcc
PA
5116 break;
5117 case PACKET_UNKNOWN:
5118 error (_("This target does not support attaching to a process"));
5119 default:
5120 error (_("Attaching to %s failed"),
5121 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5122 }
2d717e4f 5123
1b6e6f5c 5124 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5125
2d717e4f 5126 inferior_ptid = pid_to_ptid (pid);
79d7f229 5127
6efcd9a8 5128 if (target_is_non_stop_p ())
bad34192
PA
5129 {
5130 struct thread_info *thread;
79d7f229 5131
bad34192 5132 /* Get list of threads. */
e8032dde 5133 remote_update_thread_list (target);
82f73884 5134
bad34192
PA
5135 thread = first_thread_of_process (pid);
5136 if (thread)
5137 inferior_ptid = thread->ptid;
5138 else
5139 inferior_ptid = pid_to_ptid (pid);
5140
5141 /* Invalidate our notion of the remote current thread. */
47f8a51d 5142 record_currthread (rs, minus_one_ptid);
bad34192 5143 }
74531fed 5144 else
bad34192
PA
5145 {
5146 /* Now, if we have thread information, update inferior_ptid. */
5147 inferior_ptid = remote_current_thread (inferior_ptid);
5148
5149 /* Add the main thread to the thread list. */
5150 add_thread_silent (inferior_ptid);
5151 }
c0a2216e 5152
96ef3384
UW
5153 /* Next, if the target can specify a description, read it. We do
5154 this before anything involving memory or registers. */
5155 target_find_description ();
5156
6efcd9a8 5157 if (!target_is_non_stop_p ())
74531fed
PA
5158 {
5159 /* Use the previously fetched status. */
5160 gdb_assert (wait_status != NULL);
5161
5162 if (target_can_async_p ())
5163 {
722247f1
YQ
5164 struct notif_event *reply
5165 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5166
722247f1 5167 push_stop_reply ((struct stop_reply *) reply);
74531fed 5168
6a3753b3 5169 target_async (1);
74531fed
PA
5170 }
5171 else
5172 {
5173 gdb_assert (wait_status != NULL);
5174 strcpy (rs->buf, wait_status);
5175 rs->cached_wait_status = 1;
5176 }
5177 }
5178 else
5179 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5180}
5181
b9c1d481
AS
5182/* Implementation of the to_post_attach method. */
5183
5184static void
5185extended_remote_post_attach (struct target_ops *ops, int pid)
5186{
6efcd9a8
PA
5187 /* Get text, data & bss offsets. */
5188 get_offsets ();
5189
b9c1d481
AS
5190 /* In certain cases GDB might not have had the chance to start
5191 symbol lookup up until now. This could happen if the debugged
5192 binary is not using shared libraries, the vsyscall page is not
5193 present (on Linux) and the binary itself hadn't changed since the
5194 debugging process was started. */
5195 if (symfile_objfile != NULL)
5196 remote_check_symbols();
5197}
5198
c906108c 5199\f
506fb367
DJ
5200/* Check for the availability of vCont. This function should also check
5201 the response. */
c906108c
SS
5202
5203static void
6d820c5c 5204remote_vcont_probe (struct remote_state *rs)
c906108c 5205{
2e9f7625 5206 char *buf;
6d820c5c 5207
2e9f7625
DJ
5208 strcpy (rs->buf, "vCont?");
5209 putpkt (rs->buf);
6d820c5c 5210 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5211 buf = rs->buf;
c906108c 5212
506fb367 5213 /* Make sure that the features we assume are supported. */
61012eef 5214 if (startswith (buf, "vCont"))
506fb367
DJ
5215 {
5216 char *p = &buf[5];
750ce8d1 5217 int support_c, support_C;
506fb367 5218
750ce8d1
YQ
5219 rs->supports_vCont.s = 0;
5220 rs->supports_vCont.S = 0;
506fb367
DJ
5221 support_c = 0;
5222 support_C = 0;
d458bd84 5223 rs->supports_vCont.t = 0;
c1e36e3e 5224 rs->supports_vCont.r = 0;
506fb367
DJ
5225 while (p && *p == ';')
5226 {
5227 p++;
5228 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5229 rs->supports_vCont.s = 1;
506fb367 5230 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5231 rs->supports_vCont.S = 1;
506fb367
DJ
5232 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5233 support_c = 1;
5234 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5235 support_C = 1;
74531fed 5236 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5237 rs->supports_vCont.t = 1;
c1e36e3e
PA
5238 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5239 rs->supports_vCont.r = 1;
506fb367
DJ
5240
5241 p = strchr (p, ';');
5242 }
c906108c 5243
750ce8d1
YQ
5244 /* If c, and C are not all supported, we can't use vCont. Clearing
5245 BUF will make packet_ok disable the packet. */
5246 if (!support_c || !support_C)
506fb367
DJ
5247 buf[0] = 0;
5248 }
c906108c 5249
444abaca 5250 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5251}
c906108c 5252
0d8f58ca
PA
5253/* Helper function for building "vCont" resumptions. Write a
5254 resumption to P. ENDP points to one-passed-the-end of the buffer
5255 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5256 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5257 resumed thread should be single-stepped and/or signalled. If PTID
5258 equals minus_one_ptid, then all threads are resumed; if PTID
5259 represents a process, then all threads of the process are resumed;
5260 the thread to be stepped and/or signalled is given in the global
5261 INFERIOR_PTID. */
5262
5263static char *
5264append_resumption (char *p, char *endp,
2ea28649 5265 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5266{
5267 struct remote_state *rs = get_remote_state ();
5268
a493e3e2 5269 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5270 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5271 else if (step
5272 /* GDB is willing to range step. */
5273 && use_range_stepping
5274 /* Target supports range stepping. */
5275 && rs->supports_vCont.r
5276 /* We don't currently support range stepping multiple
5277 threads with a wildcard (though the protocol allows it,
5278 so stubs shouldn't make an active effort to forbid
5279 it). */
5280 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5281 {
5282 struct thread_info *tp;
5283
5284 if (ptid_equal (ptid, minus_one_ptid))
5285 {
5286 /* If we don't know about the target thread's tid, then
5287 we're resuming magic_null_ptid (see caller). */
5288 tp = find_thread_ptid (magic_null_ptid);
5289 }
5290 else
5291 tp = find_thread_ptid (ptid);
5292 gdb_assert (tp != NULL);
5293
5294 if (tp->control.may_range_step)
5295 {
5296 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5297
5298 p += xsnprintf (p, endp - p, ";r%s,%s",
5299 phex_nz (tp->control.step_range_start,
5300 addr_size),
5301 phex_nz (tp->control.step_range_end,
5302 addr_size));
5303 }
5304 else
5305 p += xsnprintf (p, endp - p, ";s");
5306 }
0d8f58ca
PA
5307 else if (step)
5308 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5309 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5310 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5311 else
5312 p += xsnprintf (p, endp - p, ";c");
5313
5314 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5315 {
5316 ptid_t nptid;
5317
5318 /* All (-1) threads of process. */
ba348170 5319 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5320
5321 p += xsnprintf (p, endp - p, ":");
5322 p = write_ptid (p, endp, nptid);
5323 }
5324 else if (!ptid_equal (ptid, minus_one_ptid))
5325 {
5326 p += xsnprintf (p, endp - p, ":");
5327 p = write_ptid (p, endp, ptid);
5328 }
5329
5330 return p;
5331}
5332
799a2abe
PA
5333/* Clear the thread's private info on resume. */
5334
5335static void
5336resume_clear_thread_private_info (struct thread_info *thread)
5337{
5338 if (thread->priv != NULL)
5339 {
5340 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5341 thread->priv->watch_data_address = 0;
5342 }
5343}
5344
e5ef252a
PA
5345/* Append a vCont continue-with-signal action for threads that have a
5346 non-zero stop signal. */
5347
5348static char *
5349append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5350{
5351 struct thread_info *thread;
5352
034f788c 5353 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5354 if (ptid_match (thread->ptid, ptid)
5355 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5356 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5357 {
5358 p = append_resumption (p, endp, thread->ptid,
5359 0, thread->suspend.stop_signal);
5360 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5361 resume_clear_thread_private_info (thread);
e5ef252a
PA
5362 }
5363
5364 return p;
5365}
5366
506fb367
DJ
5367/* Resume the remote inferior by using a "vCont" packet. The thread
5368 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5369 resumed thread should be single-stepped and/or signalled. If PTID
5370 equals minus_one_ptid, then all threads are resumed; the thread to
5371 be stepped and/or signalled is given in the global INFERIOR_PTID.
5372 This function returns non-zero iff it resumes the inferior.
44eaed12 5373
506fb367
DJ
5374 This function issues a strict subset of all possible vCont commands at the
5375 moment. */
44eaed12 5376
506fb367 5377static int
2ea28649 5378remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5379{
5380 struct remote_state *rs = get_remote_state ();
82f73884
PA
5381 char *p;
5382 char *endp;
44eaed12 5383
4082afcc 5384 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5385 remote_vcont_probe (rs);
44eaed12 5386
4082afcc 5387 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5388 return 0;
44eaed12 5389
82f73884
PA
5390 p = rs->buf;
5391 endp = rs->buf + get_remote_packet_size ();
5392
506fb367
DJ
5393 /* If we could generate a wider range of packets, we'd have to worry
5394 about overflowing BUF. Should there be a generic
5395 "multi-part-packet" packet? */
5396
0d8f58ca
PA
5397 p += xsnprintf (p, endp - p, "vCont");
5398
79d7f229 5399 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5400 {
79d7f229
PA
5401 /* MAGIC_NULL_PTID means that we don't have any active threads,
5402 so we don't have any TID numbers the inferior will
5403 understand. Make sure to only send forms that do not specify
5404 a TID. */
a9cbf802 5405 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5406 }
0d8f58ca 5407 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5408 {
0d8f58ca
PA
5409 /* Resume all threads (of all processes, or of a single
5410 process), with preference for INFERIOR_PTID. This assumes
5411 inferior_ptid belongs to the set of all threads we are about
5412 to resume. */
a493e3e2 5413 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5414 {
0d8f58ca
PA
5415 /* Step inferior_ptid, with or without signal. */
5416 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5417 }
0d8f58ca 5418
e5ef252a
PA
5419 /* Also pass down any pending signaled resumption for other
5420 threads not the current. */
5421 p = append_pending_thread_resumptions (p, endp, ptid);
5422
0d8f58ca 5423 /* And continue others without a signal. */
a493e3e2 5424 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5425 }
5426 else
506fb367
DJ
5427 {
5428 /* Scheduler locking; resume only PTID. */
a9cbf802 5429 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5430 }
c906108c 5431
82f73884
PA
5432 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5433 putpkt (rs->buf);
506fb367 5434
6efcd9a8 5435 if (target_is_non_stop_p ())
74531fed
PA
5436 {
5437 /* In non-stop, the stub replies to vCont with "OK". The stop
5438 reply will be reported asynchronously by means of a `%Stop'
5439 notification. */
5440 getpkt (&rs->buf, &rs->buf_size, 0);
5441 if (strcmp (rs->buf, "OK") != 0)
5442 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5443 }
5444
506fb367 5445 return 1;
c906108c 5446}
43ff13b4 5447
506fb367
DJ
5448/* Tell the remote machine to resume. */
5449
43ff13b4 5450static void
28439f5e 5451remote_resume (struct target_ops *ops,
2ea28649 5452 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5453{
d01949b6 5454 struct remote_state *rs = get_remote_state ();
2e9f7625 5455 char *buf;
799a2abe 5456 struct thread_info *thread;
43ff13b4 5457
722247f1
YQ
5458 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5459 (explained in remote-notif.c:handle_notification) so
5460 remote_notif_process is not called. We need find a place where
5461 it is safe to start a 'vNotif' sequence. It is good to do it
5462 before resuming inferior, because inferior was stopped and no RSP
5463 traffic at that moment. */
6efcd9a8 5464 if (!target_is_non_stop_p ())
5965e028 5465 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5466
b73be471 5467 rs->last_sent_signal = siggnal;
280ceea3 5468 rs->last_sent_step = step;
43ff13b4 5469
506fb367 5470 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5471 /* No reverse support (yet) for vCont. */
5472 if (execution_direction != EXEC_REVERSE)
5473 if (remote_vcont_resume (ptid, step, siggnal))
5474 goto done;
506fb367 5475
79d7f229
PA
5476 /* All other supported resume packets do use Hc, so set the continue
5477 thread. */
5478 if (ptid_equal (ptid, minus_one_ptid))
5479 set_continue_thread (any_thread_ptid);
506fb367 5480 else
79d7f229 5481 set_continue_thread (ptid);
506fb367 5482
799a2abe
PA
5483 ALL_NON_EXITED_THREADS (thread)
5484 resume_clear_thread_private_info (thread);
5485
2e9f7625 5486 buf = rs->buf;
b2175913
MS
5487 if (execution_direction == EXEC_REVERSE)
5488 {
5489 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5490 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5491 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5492 siggnal);
40ab02ce 5493
4082afcc 5494 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5495 error (_("Remote reverse-step not supported."));
4082afcc 5496 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5497 error (_("Remote reverse-continue not supported."));
40ab02ce 5498
b2175913
MS
5499 strcpy (buf, step ? "bs" : "bc");
5500 }
a493e3e2 5501 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5502 {
5503 buf[0] = step ? 'S' : 'C';
c5aa993b 5504 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5505 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5506 buf[3] = '\0';
5507 }
5508 else
c5aa993b 5509 strcpy (buf, step ? "s" : "c");
506fb367 5510
44eaed12 5511 putpkt (buf);
43ff13b4 5512
75c99385 5513 done:
2acceee2 5514 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5515 with the event loop. NOTE: this is the one place where all the
5516 execution commands end up. We could alternatively do this in each
23860348 5517 of the execution commands in infcmd.c. */
2acceee2
JM
5518 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5519 into infcmd.c in order to allow inferior function calls to work
23860348 5520 NOT asynchronously. */
362646f5 5521 if (target_can_async_p ())
6a3753b3 5522 target_async (1);
e24a49d8
PA
5523
5524 /* We've just told the target to resume. The remote server will
5525 wait for the inferior to stop, and then send a stop reply. In
5526 the mean time, we can't start another command/query ourselves
74531fed
PA
5527 because the stub wouldn't be ready to process it. This applies
5528 only to the base all-stop protocol, however. In non-stop (which
5529 only supports vCont), the stub replies with an "OK", and is
5530 immediate able to process further serial input. */
6efcd9a8 5531 if (!target_is_non_stop_p ())
74531fed 5532 rs->waiting_for_stop_reply = 1;
43ff13b4 5533}
c906108c 5534\f
43ff13b4
JM
5535
5536/* Set up the signal handler for SIGINT, while the target is
23860348 5537 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5538static void
934b9bac 5539async_initialize_sigint_signal_handler (void)
43ff13b4 5540{
934b9bac 5541 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5542}
5543
23860348 5544/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5545static void
934b9bac 5546async_handle_remote_sigint (int sig)
43ff13b4 5547{
934b9bac 5548 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5549 /* Note we need to go through gdb_call_async_signal_handler in order
5550 to wake up the event loop on Windows. */
5551 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5552}
5553
5554/* Signal handler for SIGINT, installed after SIGINT has already been
5555 sent once. It will take effect the second time that the user sends
23860348 5556 a ^C. */
43ff13b4 5557static void
934b9bac 5558async_handle_remote_sigint_twice (int sig)
43ff13b4 5559{
934b9bac 5560 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5561 /* See note in async_handle_remote_sigint. */
5562 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5563}
5564
abc56d60
PA
5565/* Implementation of to_check_pending_interrupt. */
5566
5567static void
5568remote_check_pending_interrupt (struct target_ops *self)
5569{
5570 struct async_signal_handler *token = async_sigint_remote_twice_token;
5571
5572 if (async_signal_handler_is_marked (token))
5573 {
5574 clear_async_signal_handler (token);
5575 call_async_signal_handler (token);
5576 }
5577}
5578
6426a772 5579/* Perform the real interruption of the target execution, in response
23860348 5580 to a ^C. */
c5aa993b 5581static void
fba45db2 5582async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5583{
5584 if (remote_debug)
248fd3bf 5585 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5586
de979965 5587 target_interrupt (inferior_ptid);
43ff13b4
JM
5588}
5589
0df8b418 5590/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5591 up on the target alltogether. */
47e1ce27 5592static void
fba45db2 5593async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5594{
2df3850c 5595 if (remote_debug)
248fd3bf 5596 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5597
5598 interrupt_query ();
43ff13b4
JM
5599}
5600
5601/* Reinstall the usual SIGINT handlers, after the target has
23860348 5602 stopped. */
6426a772 5603static void
934b9bac 5604async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5605{
5606 signal (SIGINT, handle_sigint);
43ff13b4
JM
5607}
5608
c906108c
SS
5609/* Send ^C to target to halt it. Target will respond, and send us a
5610 packet. */
507f3c78 5611static void (*ofunc) (int);
c906108c 5612
bfedc46a
PA
5613/* The command line interface's interrupt routine. This function is installed
5614 as a signal handler for SIGINT. The first time a user requests an
5615 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5616 response from the target (it didn't stop when the user requested it),
23860348 5617 we ask the user if he'd like to detach from the target. */
bfedc46a 5618
c906108c 5619static void
934b9bac 5620sync_remote_interrupt (int signo)
c906108c 5621{
23860348 5622 /* If this doesn't work, try more severe steps. */
934b9bac 5623 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5624
934b9bac 5625 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5626}
5627
5628/* The user typed ^C twice. */
5629
5630static void
934b9bac 5631sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5632{
5633 signal (signo, ofunc);
934b9bac
JK
5634 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5635 signal (signo, sync_remote_interrupt);
c906108c 5636}
7a292a7a 5637
74531fed
PA
5638/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5639 thread, all threads of a remote process, or all threads of all
5640 processes. */
5641
5642static void
5643remote_stop_ns (ptid_t ptid)
5644{
5645 struct remote_state *rs = get_remote_state ();
5646 char *p = rs->buf;
5647 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5648
4082afcc 5649 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5650 remote_vcont_probe (rs);
5651
d458bd84 5652 if (!rs->supports_vCont.t)
74531fed
PA
5653 error (_("Remote server does not support stopping threads"));
5654
f91d3df5
PA
5655 if (ptid_equal (ptid, minus_one_ptid)
5656 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5657 p += xsnprintf (p, endp - p, "vCont;t");
5658 else
5659 {
5660 ptid_t nptid;
5661
74531fed
PA
5662 p += xsnprintf (p, endp - p, "vCont;t:");
5663
5664 if (ptid_is_pid (ptid))
5665 /* All (-1) threads of process. */
ba348170 5666 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5667 else
5668 {
5669 /* Small optimization: if we already have a stop reply for
5670 this thread, no use in telling the stub we want this
5671 stopped. */
5672 if (peek_stop_reply (ptid))
5673 return;
5674
5675 nptid = ptid;
5676 }
5677
a9cbf802 5678 write_ptid (p, endp, nptid);
74531fed
PA
5679 }
5680
5681 /* In non-stop, we get an immediate OK reply. The stop reply will
5682 come in asynchronously by notification. */
5683 putpkt (rs->buf);
5684 getpkt (&rs->buf, &rs->buf_size, 0);
5685 if (strcmp (rs->buf, "OK") != 0)
5686 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5687}
5688
bfedc46a
PA
5689/* All-stop version of target_interrupt. Sends a break or a ^C to
5690 interrupt the remote target. It is undefined which thread of which
5691 process reports the interrupt. */
74531fed
PA
5692
5693static void
de979965 5694remote_interrupt_as (void)
74531fed
PA
5695{
5696 struct remote_state *rs = get_remote_state ();
5697
3a29589a
DJ
5698 rs->ctrlc_pending_p = 1;
5699
74531fed
PA
5700 /* If the inferior is stopped already, but the core didn't know
5701 about it yet, just ignore the request. The cached wait status
5702 will be collected in remote_wait. */
5703 if (rs->cached_wait_status)
5704 return;
5705
9a7071a8
JB
5706 /* Send interrupt_sequence to remote target. */
5707 send_interrupt_sequence ();
74531fed
PA
5708}
5709
de979965
PA
5710/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5711 the remote target. It is undefined which thread of which process
5712 reports the interrupt. Returns true if the packet is supported by
5713 the server, false otherwise. */
5714
5715static int
5716remote_interrupt_ns (void)
5717{
5718 struct remote_state *rs = get_remote_state ();
5719 char *p = rs->buf;
5720 char *endp = rs->buf + get_remote_packet_size ();
5721
5722 xsnprintf (p, endp - p, "vCtrlC");
5723
5724 /* In non-stop, we get an immediate OK reply. The stop reply will
5725 come in asynchronously by notification. */
5726 putpkt (rs->buf);
5727 getpkt (&rs->buf, &rs->buf_size, 0);
5728
5729 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5730 {
5731 case PACKET_OK:
5732 break;
5733 case PACKET_UNKNOWN:
5734 return 0;
5735 case PACKET_ERROR:
5736 error (_("Interrupting target failed: %s"), rs->buf);
5737 }
5738
5739 return 1;
5740}
5741
bfedc46a 5742/* Implement the to_stop function for the remote targets. */
74531fed 5743
c906108c 5744static void
1eab8a48 5745remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5746{
7a292a7a 5747 if (remote_debug)
0f71a2f6 5748 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5749
6efcd9a8 5750 if (target_is_non_stop_p ())
74531fed 5751 remote_stop_ns (ptid);
c906108c 5752 else
bfedc46a
PA
5753 {
5754 /* We don't currently have a way to transparently pause the
5755 remote target in all-stop mode. Interrupt it instead. */
de979965 5756 remote_interrupt_as ();
bfedc46a
PA
5757 }
5758}
5759
5760/* Implement the to_interrupt function for the remote targets. */
5761
5762static void
5763remote_interrupt (struct target_ops *self, ptid_t ptid)
5764{
5765 if (remote_debug)
5766 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5767
de979965 5768 if (non_stop)
bfedc46a 5769 {
de979965 5770 /* In non-stop mode, we always stop with no signal instead. */
bfedc46a
PA
5771 remote_stop_ns (ptid);
5772 }
5773 else
de979965
PA
5774 {
5775 /* In all-stop, we emulate ^C-ing the remote target's
5776 terminal. */
5777 if (target_is_non_stop_p ())
5778 {
5779 if (!remote_interrupt_ns ())
5780 {
5781 /* No support for ^C-ing the remote target. Stop it
5782 (with no signal) instead. */
5783 remote_stop_ns (ptid);
5784 }
5785 }
5786 else
5787 remote_interrupt_as ();
5788 }
c906108c
SS
5789}
5790
5791/* Ask the user what to do when an interrupt is received. */
5792
5793static void
fba45db2 5794interrupt_query (void)
c906108c 5795{
abc56d60
PA
5796 struct remote_state *rs = get_remote_state ();
5797 struct cleanup *old_chain;
5798
5799 old_chain = make_cleanup_restore_target_terminal ();
c906108c
SS
5800 target_terminal_ours ();
5801
abc56d60 5802 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5803 {
abc56d60
PA
5804 if (query (_("The target is not responding to interrupt requests.\n"
5805 "Stop debugging it? ")))
74531fed 5806 {
78a095c3 5807 remote_unpush_target ();
abc56d60 5808 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5809 }
5810 }
abc56d60
PA
5811 else
5812 {
5813 if (query (_("Interrupted while waiting for the program.\n"
5814 "Give up waiting? ")))
5815 quit ();
5816 }
c906108c 5817
abc56d60 5818 do_cleanups (old_chain);
c906108c
SS
5819}
5820
6426a772
JM
5821/* Enable/disable target terminal ownership. Most targets can use
5822 terminal groups to control terminal ownership. Remote targets are
5823 different in that explicit transfer of ownership to/from GDB/target
23860348 5824 is required. */
6426a772
JM
5825
5826static void
d2f640d4 5827remote_terminal_inferior (struct target_ops *self)
6426a772 5828{
c6ebd6cf 5829 if (!target_async_permitted)
75c99385
PA
5830 /* Nothing to do. */
5831 return;
5832
d9d2d8b6
PA
5833 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5834 idempotent. The event-loop GDB talking to an asynchronous target
5835 with a synchronous command calls this function from both
5836 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5837 transfer the terminal to the target when it shouldn't this guard
5838 can go away. */
6426a772
JM
5839 if (!remote_async_terminal_ours_p)
5840 return;
5841 delete_file_handler (input_fd);
5842 remote_async_terminal_ours_p = 0;
934b9bac 5843 async_initialize_sigint_signal_handler ();
6426a772
JM
5844 /* NOTE: At this point we could also register our selves as the
5845 recipient of all input. Any characters typed could then be
23860348 5846 passed on down to the target. */
6426a772
JM
5847}
5848
5849static void
e3594fd1 5850remote_terminal_ours (struct target_ops *self)
6426a772 5851{
c6ebd6cf 5852 if (!target_async_permitted)
75c99385
PA
5853 /* Nothing to do. */
5854 return;
5855
5856 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5857 if (remote_async_terminal_ours_p)
5858 return;
934b9bac 5859 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5860 add_file_handler (input_fd, stdin_event_handler, 0);
5861 remote_async_terminal_ours_p = 1;
5862}
5863
176a6961 5864static void
917317f4 5865remote_console_output (char *msg)
c906108c
SS
5866{
5867 char *p;
5868
c5aa993b 5869 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5870 {
5871 char tb[2];
5872 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5873
c906108c
SS
5874 tb[0] = c;
5875 tb[1] = 0;
43ff13b4 5876 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5877 }
00db5b94
PA
5878 gdb_flush (gdb_stdtarg);
5879}
74531fed
PA
5880
5881typedef struct cached_reg
5882{
5883 int num;
5884 gdb_byte data[MAX_REGISTER_SIZE];
5885} cached_reg_t;
5886
5887DEF_VEC_O(cached_reg_t);
5888
722247f1 5889typedef struct stop_reply
74531fed 5890{
722247f1 5891 struct notif_event base;
74531fed 5892
722247f1 5893 /* The identifier of the thread about this event */
74531fed
PA
5894 ptid_t ptid;
5895
340e3c99 5896 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5897 connection, represented by a remote_state object, is closed,
5898 all the associated stop_reply events should be released. */
5899 struct remote_state *rs;
5900
74531fed
PA
5901 struct target_waitstatus ws;
5902
15148d6a
PA
5903 /* Expedited registers. This makes remote debugging a bit more
5904 efficient for those targets that provide critical registers as
5905 part of their normal status mechanism (as another roundtrip to
5906 fetch them is avoided). */
74531fed
PA
5907 VEC(cached_reg_t) *regcache;
5908
f7e6eed5
PA
5909 enum target_stop_reason stop_reason;
5910
74531fed
PA
5911 CORE_ADDR watch_data_address;
5912
dc146f7c 5913 int core;
722247f1 5914} *stop_reply_p;
a744cf53 5915
722247f1
YQ
5916DECLARE_QUEUE_P (stop_reply_p);
5917DEFINE_QUEUE_P (stop_reply_p);
5918/* The list of already fetched and acknowledged stop events. This
5919 queue is used for notification Stop, and other notifications
5920 don't need queue for their events, because the notification events
5921 of Stop can't be consumed immediately, so that events should be
5922 queued first, and be consumed by remote_wait_{ns,as} one per
5923 time. Other notifications can consume their events immediately,
5924 so queue is not needed for them. */
5925static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5926
5927static void
5928stop_reply_xfree (struct stop_reply *r)
5929{
f48ff2a7 5930 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5931}
5932
221e1a37
PA
5933/* Return the length of the stop reply queue. */
5934
5935static int
5936stop_reply_queue_length (void)
5937{
5938 return QUEUE_length (stop_reply_p, stop_reply_queue);
5939}
5940
722247f1
YQ
5941static void
5942remote_notif_stop_parse (struct notif_client *self, char *buf,
5943 struct notif_event *event)
5944{
5945 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5946}
5947
5948static void
5949remote_notif_stop_ack (struct notif_client *self, char *buf,
5950 struct notif_event *event)
5951{
5952 struct stop_reply *stop_reply = (struct stop_reply *) event;
5953
5954 /* acknowledge */
5955 putpkt ((char *) self->ack_command);
5956
5957 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5958 /* We got an unknown stop reply. */
5959 error (_("Unknown stop reply"));
5960
5961 push_stop_reply (stop_reply);
5962}
5963
5964static int
5965remote_notif_stop_can_get_pending_events (struct notif_client *self)
5966{
5967 /* We can't get pending events in remote_notif_process for
5968 notification stop, and we have to do this in remote_wait_ns
5969 instead. If we fetch all queued events from stub, remote stub
5970 may exit and we have no chance to process them back in
5971 remote_wait_ns. */
5972 mark_async_event_handler (remote_async_inferior_event_token);
5973 return 0;
5974}
5975
5976static void
5977stop_reply_dtr (struct notif_event *event)
5978{
5979 struct stop_reply *r = (struct stop_reply *) event;
5980
5981 VEC_free (cached_reg_t, r->regcache);
5982}
5983
5984static struct notif_event *
5985remote_notif_stop_alloc_reply (void)
5986{
8d749320
SM
5987 /* We cast to a pointer to the "base class". */
5988 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5989
5990 r->dtr = stop_reply_dtr;
5991
5992 return r;
5993}
5994
5995/* A client of notification Stop. */
5996
5997struct notif_client notif_client_stop =
5998{
5999 "Stop",
6000 "vStopped",
6001 remote_notif_stop_parse,
6002 remote_notif_stop_ack,
6003 remote_notif_stop_can_get_pending_events,
6004 remote_notif_stop_alloc_reply,
f48ff2a7 6005 REMOTE_NOTIF_STOP,
722247f1
YQ
6006};
6007
6008/* A parameter to pass data in and out. */
6009
6010struct queue_iter_param
6011{
6012 void *input;
6013 struct stop_reply *output;
6014};
6015
cbb8991c
DB
6016/* Determine if THREAD is a pending fork parent thread. ARG contains
6017 the pid of the process that owns the threads we want to check, or
6018 -1 if we want to check all threads. */
6019
6020static int
6021is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6022 ptid_t thread_ptid)
6023{
6024 if (ws->kind == TARGET_WAITKIND_FORKED
6025 || ws->kind == TARGET_WAITKIND_VFORKED)
6026 {
6027 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6028 return 1;
6029 }
6030
6031 return 0;
6032}
6033
6034/* Check whether EVENT is a fork event, and if it is, remove the
6035 fork child from the context list passed in DATA. */
6036
6037static int
6038remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6039 QUEUE_ITER (stop_reply_p) *iter,
6040 stop_reply_p event,
6041 void *data)
6042{
19ba03f4
SM
6043 struct queue_iter_param *param = (struct queue_iter_param *) data;
6044 struct threads_listing_context *context
6045 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6046
6047 if (event->ws.kind == TARGET_WAITKIND_FORKED
6048 || event->ws.kind == TARGET_WAITKIND_VFORKED)
6049 {
6050 threads_listing_context_remove (&event->ws, context);
6051 }
6052
6053 return 1;
6054}
6055
6056/* If CONTEXT contains any fork child threads that have not been
6057 reported yet, remove them from the CONTEXT list. If such a
6058 thread exists it is because we are stopped at a fork catchpoint
6059 and have not yet called follow_fork, which will set up the
6060 host-side data structures for the new process. */
6061
6062static void
6063remove_new_fork_children (struct threads_listing_context *context)
6064{
6065 struct thread_info * thread;
6066 int pid = -1;
6067 struct notif_client *notif = &notif_client_stop;
6068 struct queue_iter_param param;
6069
6070 /* For any threads stopped at a fork event, remove the corresponding
6071 fork child threads from the CONTEXT list. */
6072 ALL_NON_EXITED_THREADS (thread)
6073 {
6074 struct target_waitstatus *ws = &thread->pending_follow;
6075
6076 if (is_pending_fork_parent (ws, pid, thread->ptid))
6077 {
6078 threads_listing_context_remove (ws, context);
6079 }
6080 }
6081
6082 /* Check for any pending fork events (not reported or processed yet)
6083 in process PID and remove those fork child threads from the
6084 CONTEXT list as well. */
6085 remote_notif_get_pending_events (notif);
6086 param.input = context;
6087 param.output = NULL;
6088 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6089 remove_child_of_pending_fork, &param);
6090}
6091
f48ff2a7
YQ
6092/* Remove stop replies in the queue if its pid is equal to the given
6093 inferior's pid. */
722247f1
YQ
6094
6095static int
f48ff2a7
YQ
6096remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6097 QUEUE_ITER (stop_reply_p) *iter,
6098 stop_reply_p event,
6099 void *data)
722247f1 6100{
19ba03f4
SM
6101 struct queue_iter_param *param = (struct queue_iter_param *) data;
6102 struct inferior *inf = (struct inferior *) param->input;
722247f1 6103
f48ff2a7 6104 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6105 {
6106 stop_reply_xfree (event);
6107 QUEUE_remove_elem (stop_reply_p, q, iter);
6108 }
6109
6110 return 1;
6111}
6112
f48ff2a7 6113/* Discard all pending stop replies of inferior INF. */
c906108c 6114
74531fed 6115static void
5f4cf0bb 6116discard_pending_stop_replies (struct inferior *inf)
c906108c 6117{
722247f1
YQ
6118 int i;
6119 struct queue_iter_param param;
f48ff2a7
YQ
6120 struct stop_reply *reply;
6121 struct remote_state *rs = get_remote_state ();
6122 struct remote_notif_state *rns = rs->notif_state;
6123
6124 /* This function can be notified when an inferior exists. When the
6125 target is not remote, the notification state is NULL. */
6126 if (rs->remote_desc == NULL)
6127 return;
6128
6129 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6130
74531fed 6131 /* Discard the in-flight notification. */
f48ff2a7 6132 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6133 {
722247f1 6134 stop_reply_xfree (reply);
f48ff2a7 6135 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6136 }
c906108c 6137
722247f1
YQ
6138 param.input = inf;
6139 param.output = NULL;
74531fed
PA
6140 /* Discard the stop replies we have already pulled with
6141 vStopped. */
722247f1 6142 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6143 remove_stop_reply_for_inferior, &param);
6144}
6145
bcc75809
YQ
6146/* If its remote state is equal to the given remote state,
6147 remove EVENT from the stop reply queue. */
6148
6149static int
6150remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6151 QUEUE_ITER (stop_reply_p) *iter,
6152 stop_reply_p event,
6153 void *data)
6154{
19ba03f4
SM
6155 struct queue_iter_param *param = (struct queue_iter_param *) data;
6156 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6157
6158 if (event->rs == rs)
6159 {
6160 stop_reply_xfree (event);
6161 QUEUE_remove_elem (stop_reply_p, q, iter);
6162 }
6163
6164 return 1;
6165}
6166
6167/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6168
6169static void
bcc75809 6170discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6171{
6172 struct queue_iter_param param;
6173
bcc75809 6174 param.input = rs;
f48ff2a7
YQ
6175 param.output = NULL;
6176 /* Discard the stop replies we have already pulled with
6177 vStopped. */
6178 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6179 remove_stop_reply_of_remote_state, &param);
722247f1 6180}
74531fed 6181
722247f1
YQ
6182/* A parameter to pass data in and out. */
6183
6184static int
6185remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6186 QUEUE_ITER (stop_reply_p) *iter,
6187 stop_reply_p event,
6188 void *data)
6189{
19ba03f4
SM
6190 struct queue_iter_param *param = (struct queue_iter_param *) data;
6191 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6192
6193 if (ptid_match (event->ptid, *ptid))
6194 {
6195 param->output = event;
6196 QUEUE_remove_elem (stop_reply_p, q, iter);
6197 return 0;
c8e38a49 6198 }
722247f1
YQ
6199
6200 return 1;
74531fed 6201}
43ff13b4 6202
722247f1
YQ
6203/* Remove the first reply in 'stop_reply_queue' which matches
6204 PTID. */
2e9f7625 6205
722247f1
YQ
6206static struct stop_reply *
6207remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6208{
722247f1
YQ
6209 struct queue_iter_param param;
6210
6211 param.input = &ptid;
6212 param.output = NULL;
6213
6214 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6215 remote_notif_remove_once_on_match, &param);
6216 if (notif_debug)
6217 fprintf_unfiltered (gdb_stdlog,
6218 "notif: discard queued event: 'Stop' in %s\n",
6219 target_pid_to_str (ptid));
a744cf53 6220
722247f1 6221 return param.output;
74531fed 6222}
75c99385 6223
74531fed
PA
6224/* Look for a queued stop reply belonging to PTID. If one is found,
6225 remove it from the queue, and return it. Returns NULL if none is
6226 found. If there are still queued events left to process, tell the
6227 event loop to get back to target_wait soon. */
e24a49d8 6228
74531fed
PA
6229static struct stop_reply *
6230queued_stop_reply (ptid_t ptid)
6231{
722247f1 6232 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6233
722247f1 6234 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6235 /* There's still at least an event left. */
6236 mark_async_event_handler (remote_async_inferior_event_token);
6237
722247f1 6238 return r;
74531fed
PA
6239}
6240
6241/* Push a fully parsed stop reply in the stop reply queue. Since we
6242 know that we now have at least one queued event left to pass to the
6243 core side, tell the event loop to get back to target_wait soon. */
6244
6245static void
6246push_stop_reply (struct stop_reply *new_event)
6247{
722247f1 6248 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6249
722247f1
YQ
6250 if (notif_debug)
6251 fprintf_unfiltered (gdb_stdlog,
6252 "notif: push 'Stop' %s to queue %d\n",
6253 target_pid_to_str (new_event->ptid),
6254 QUEUE_length (stop_reply_p,
6255 stop_reply_queue));
74531fed
PA
6256
6257 mark_async_event_handler (remote_async_inferior_event_token);
6258}
6259
722247f1
YQ
6260static int
6261stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6262 QUEUE_ITER (stop_reply_p) *iter,
6263 struct stop_reply *event,
6264 void *data)
6265{
19ba03f4 6266 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6267
6268 return !(ptid_equal (*ptid, event->ptid)
6269 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6270}
6271
74531fed
PA
6272/* Returns true if we have a stop reply for PTID. */
6273
6274static int
6275peek_stop_reply (ptid_t ptid)
6276{
722247f1
YQ
6277 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6278 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6279}
6280
1f10ba14
PA
6281/* Skip PACKET until the next semi-colon (or end of string). */
6282
6283static char *
6284skip_to_semicolon (char *p)
6285{
6286 while (*p != '\0' && *p != ';')
6287 p++;
6288 return p;
6289}
6290
26d56a93
SL
6291/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6292 starting with P and ending with PEND matches PREFIX. */
6293
6294static int
6295strprefix (const char *p, const char *pend, const char *prefix)
6296{
6297 for ( ; p < pend; p++, prefix++)
6298 if (*p != *prefix)
6299 return 0;
6300 return *prefix == '\0';
6301}
6302
74531fed
PA
6303/* Parse the stop reply in BUF. Either the function succeeds, and the
6304 result is stored in EVENT, or throws an error. */
6305
6306static void
6307remote_parse_stop_reply (char *buf, struct stop_reply *event)
6308{
6309 struct remote_arch_state *rsa = get_remote_arch_state ();
6310 ULONGEST addr;
6311 char *p;
94585166 6312 int skipregs = 0;
74531fed
PA
6313
6314 event->ptid = null_ptid;
bcc75809 6315 event->rs = get_remote_state ();
74531fed
PA
6316 event->ws.kind = TARGET_WAITKIND_IGNORE;
6317 event->ws.value.integer = 0;
f7e6eed5 6318 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6319 event->regcache = NULL;
dc146f7c 6320 event->core = -1;
74531fed
PA
6321
6322 switch (buf[0])
6323 {
6324 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6325 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6326 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6327 ss = signal number
6328 n... = register number
6329 r... = register contents
6330 */
6331
6332 p = &buf[3]; /* after Txx */
6333 while (*p)
6334 {
6335 char *p1;
cea39f65 6336 int fieldsize;
43ff13b4 6337
1f10ba14
PA
6338 p1 = strchr (p, ':');
6339 if (p1 == NULL)
6340 error (_("Malformed packet(a) (missing colon): %s\n\
6341Packet: '%s'\n"),
6342 p, buf);
6343 if (p == p1)
6344 error (_("Malformed packet(a) (missing register number): %s\n\
6345Packet: '%s'\n"),
6346 p, buf);
3c3bea1c 6347
1f10ba14
PA
6348 /* Some "registers" are actually extended stop information.
6349 Note if you're adding a new entry here: GDB 7.9 and
6350 earlier assume that all register "numbers" that start
6351 with an hex digit are real register numbers. Make sure
6352 the server only sends such a packet if it knows the
6353 client understands it. */
c8e38a49 6354
26d56a93 6355 if (strprefix (p, p1, "thread"))
1f10ba14 6356 event->ptid = read_ptid (++p1, &p);
26d56a93
SL
6357 else if (strprefix (p, p1, "watch")
6358 || strprefix (p, p1, "rwatch")
6359 || strprefix (p, p1, "awatch"))
cea39f65 6360 {
f7e6eed5 6361 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6362 p = unpack_varlen_hex (++p1, &addr);
6363 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6364 }
26d56a93 6365 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6366 {
6367 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6368
6369 /* Make sure the stub doesn't forget to indicate support
6370 with qSupported. */
6371 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6372 error (_("Unexpected swbreak stop reason"));
6373
6374 /* The value part is documented as "must be empty",
6375 though we ignore it, in case we ever decide to make
6376 use of it in a backward compatible way. */
6377 p = skip_to_semicolon (p1 + 1);
6378 }
26d56a93 6379 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6380 {
6381 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6382
6383 /* Make sure the stub doesn't forget to indicate support
6384 with qSupported. */
6385 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6386 error (_("Unexpected hwbreak stop reason"));
6387
6388 /* See above. */
6389 p = skip_to_semicolon (p1 + 1);
6390 }
26d56a93 6391 else if (strprefix (p, p1, "library"))
cea39f65 6392 {
1f10ba14
PA
6393 event->ws.kind = TARGET_WAITKIND_LOADED;
6394 p = skip_to_semicolon (p1 + 1);
6395 }
26d56a93 6396 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6397 {
6398 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6399 /* p1 will indicate "begin" or "end", but it makes
6400 no difference for now, so ignore it. */
6401 p = skip_to_semicolon (p1 + 1);
6402 }
26d56a93 6403 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6404 {
6405 ULONGEST c;
a744cf53 6406
1f10ba14
PA
6407 p = unpack_varlen_hex (++p1, &c);
6408 event->core = c;
cea39f65 6409 }
26d56a93 6410 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6411 {
6412 event->ws.value.related_pid = read_ptid (++p1, &p);
6413 event->ws.kind = TARGET_WAITKIND_FORKED;
6414 }
26d56a93 6415 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6416 {
6417 event->ws.value.related_pid = read_ptid (++p1, &p);
6418 event->ws.kind = TARGET_WAITKIND_VFORKED;
6419 }
26d56a93 6420 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6421 {
6422 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6423 p = skip_to_semicolon (p1 + 1);
6424 }
6ab24463 6425 else if (strprefix (p, p1, "exec"))
94585166
DB
6426 {
6427 ULONGEST ignored;
6428 char pathname[PATH_MAX];
6429 int pathlen;
6430
6431 /* Determine the length of the execd pathname. */
6432 p = unpack_varlen_hex (++p1, &ignored);
6433 pathlen = (p - p1) / 2;
6434
6435 /* Save the pathname for event reporting and for
6436 the next run command. */
6437 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6438 pathname[pathlen] = '\0';
6439
6440 /* This is freed during event handling. */
6441 event->ws.value.execd_pathname = xstrdup (pathname);
6442 event->ws.kind = TARGET_WAITKIND_EXECD;
6443
6444 /* Skip the registers included in this packet, since
6445 they may be for an architecture different from the
6446 one used by the original program. */
6447 skipregs = 1;
6448 }
cea39f65
MS
6449 else
6450 {
1f10ba14
PA
6451 ULONGEST pnum;
6452 char *p_temp;
6453
94585166
DB
6454 if (skipregs)
6455 {
6456 p = skip_to_semicolon (p1 + 1);
6457 p++;
6458 continue;
6459 }
6460
1f10ba14
PA
6461 /* Maybe a real ``P'' register number. */
6462 p_temp = unpack_varlen_hex (p, &pnum);
6463 /* If the first invalid character is the colon, we got a
6464 register number. Otherwise, it's an unknown stop
6465 reason. */
6466 if (p_temp == p1)
6467 {
6468 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6469 cached_reg_t cached_reg;
43ff13b4 6470
1f10ba14
PA
6471 if (reg == NULL)
6472 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6473Packet: '%s'\n"),
1f10ba14 6474 hex_string (pnum), p, buf);
c8e38a49 6475
1f10ba14 6476 cached_reg.num = reg->regnum;
4100683b 6477
1f10ba14
PA
6478 p = p1 + 1;
6479 fieldsize = hex2bin (p, cached_reg.data,
6480 register_size (target_gdbarch (),
6481 reg->regnum));
6482 p += 2 * fieldsize;
6483 if (fieldsize < register_size (target_gdbarch (),
6484 reg->regnum))
6485 warning (_("Remote reply is too short: %s"), buf);
74531fed 6486
1f10ba14
PA
6487 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6488 }
6489 else
6490 {
6491 /* Not a number. Silently skip unknown optional
6492 info. */
6493 p = skip_to_semicolon (p1 + 1);
6494 }
cea39f65 6495 }
c8e38a49 6496
cea39f65
MS
6497 if (*p != ';')
6498 error (_("Remote register badly formatted: %s\nhere: %s"),
6499 buf, p);
6500 ++p;
6501 }
5b5596ff
PA
6502
6503 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6504 break;
6505
c8e38a49
PA
6506 /* fall through */
6507 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6508 {
6509 int sig;
6510
6511 event->ws.kind = TARGET_WAITKIND_STOPPED;
6512 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6513 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6514 event->ws.value.sig = (enum gdb_signal) sig;
6515 else
6516 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6517 }
c8e38a49
PA
6518 break;
6519 case 'W': /* Target exited. */
6520 case 'X':
6521 {
6522 char *p;
6523 int pid;
6524 ULONGEST value;
82f73884 6525
c8e38a49
PA
6526 /* GDB used to accept only 2 hex chars here. Stubs should
6527 only send more if they detect GDB supports multi-process
6528 support. */
6529 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6530
c8e38a49
PA
6531 if (buf[0] == 'W')
6532 {
6533 /* The remote process exited. */
74531fed
PA
6534 event->ws.kind = TARGET_WAITKIND_EXITED;
6535 event->ws.value.integer = value;
c8e38a49
PA
6536 }
6537 else
6538 {
6539 /* The remote process exited with a signal. */
74531fed 6540 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6541 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6542 event->ws.value.sig = (enum gdb_signal) value;
6543 else
6544 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6545 }
82f73884 6546
c8e38a49
PA
6547 /* If no process is specified, assume inferior_ptid. */
6548 pid = ptid_get_pid (inferior_ptid);
6549 if (*p == '\0')
6550 ;
6551 else if (*p == ';')
6552 {
6553 p++;
6554
0b24eb2d 6555 if (*p == '\0')
82f73884 6556 ;
61012eef 6557 else if (startswith (p, "process:"))
82f73884 6558 {
c8e38a49 6559 ULONGEST upid;
a744cf53 6560
c8e38a49
PA
6561 p += sizeof ("process:") - 1;
6562 unpack_varlen_hex (p, &upid);
6563 pid = upid;
82f73884
PA
6564 }
6565 else
6566 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6567 }
c8e38a49
PA
6568 else
6569 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6570 event->ptid = pid_to_ptid (pid);
6571 }
6572 break;
6573 }
6574
6efcd9a8 6575 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
6576 error (_("No process or thread specified in stop reply: %s"), buf);
6577}
6578
722247f1
YQ
6579/* When the stub wants to tell GDB about a new notification reply, it
6580 sends a notification (%Stop, for example). Those can come it at
6581 any time, hence, we have to make sure that any pending
6582 putpkt/getpkt sequence we're making is finished, before querying
6583 the stub for more events with the corresponding ack command
6584 (vStopped, for example). E.g., if we started a vStopped sequence
6585 immediately upon receiving the notification, something like this
6586 could happen:
74531fed
PA
6587
6588 1.1) --> Hg 1
6589 1.2) <-- OK
6590 1.3) --> g
6591 1.4) <-- %Stop
6592 1.5) --> vStopped
6593 1.6) <-- (registers reply to step #1.3)
6594
6595 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6596 query.
6597
796cb314 6598 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6599 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6600 doing whatever we were doing:
6601
6602 2.1) --> Hg 1
6603 2.2) <-- OK
6604 2.3) --> g
6605 2.4) <-- %Stop
6606 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6607 2.5) <-- (registers reply to step #2.3)
6608
6609 Eventualy after step #2.5, we return to the event loop, which
6610 notices there's an event on the
6611 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6612 associated callback --- the function below. At this point, we're
6613 always safe to start a vStopped sequence. :
6614
6615 2.6) --> vStopped
6616 2.7) <-- T05 thread:2
6617 2.8) --> vStopped
6618 2.9) --> OK
6619*/
6620
722247f1
YQ
6621void
6622remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6623{
6624 struct remote_state *rs = get_remote_state ();
74531fed 6625
f48ff2a7 6626 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6627 {
722247f1
YQ
6628 if (notif_debug)
6629 fprintf_unfiltered (gdb_stdlog,
6630 "notif: process: '%s' ack pending event\n",
6631 nc->name);
74531fed 6632
722247f1 6633 /* acknowledge */
f48ff2a7
YQ
6634 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6635 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6636
6637 while (1)
6638 {
6639 getpkt (&rs->buf, &rs->buf_size, 0);
6640 if (strcmp (rs->buf, "OK") == 0)
6641 break;
6642 else
722247f1 6643 remote_notif_ack (nc, rs->buf);
74531fed
PA
6644 }
6645 }
722247f1
YQ
6646 else
6647 {
6648 if (notif_debug)
6649 fprintf_unfiltered (gdb_stdlog,
6650 "notif: process: '%s' no pending reply\n",
6651 nc->name);
6652 }
74531fed
PA
6653}
6654
74531fed
PA
6655/* Called when it is decided that STOP_REPLY holds the info of the
6656 event that is to be returned to the core. This function always
6657 destroys STOP_REPLY. */
6658
6659static ptid_t
6660process_stop_reply (struct stop_reply *stop_reply,
6661 struct target_waitstatus *status)
6662{
6663 ptid_t ptid;
6664
6665 *status = stop_reply->ws;
6666 ptid = stop_reply->ptid;
6667
6668 /* If no thread/process was reported by the stub, assume the current
6669 inferior. */
6670 if (ptid_equal (ptid, null_ptid))
6671 ptid = inferior_ptid;
6672
5f3563ea
PA
6673 if (status->kind != TARGET_WAITKIND_EXITED
6674 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 6675 {
ee154bee 6676 struct remote_state *rs = get_remote_state ();
799a2abe 6677 struct private_thread_info *remote_thr;
ee154bee 6678
5f3563ea
PA
6679 /* Expedited registers. */
6680 if (stop_reply->regcache)
6681 {
217f1f79 6682 struct regcache *regcache
f5656ead 6683 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6684 cached_reg_t *reg;
6685 int ix;
6686
6687 for (ix = 0;
6688 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6689 ix++)
217f1f79 6690 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6691 VEC_free (cached_reg_t, stop_reply->regcache);
6692 }
74531fed 6693
1941c569 6694 remote_notice_new_inferior (ptid, 0);
799a2abe
PA
6695 remote_thr = demand_private_info (ptid);
6696 remote_thr->core = stop_reply->core;
6697 remote_thr->stop_reason = stop_reply->stop_reason;
6698 remote_thr->watch_data_address = stop_reply->watch_data_address;
74531fed
PA
6699 }
6700
74531fed
PA
6701 stop_reply_xfree (stop_reply);
6702 return ptid;
6703}
6704
6705/* The non-stop mode version of target_wait. */
6706
6707static ptid_t
47608cb1 6708remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6709{
6710 struct remote_state *rs = get_remote_state ();
74531fed
PA
6711 struct stop_reply *stop_reply;
6712 int ret;
fee9eda9 6713 int is_notif = 0;
74531fed
PA
6714
6715 /* If in non-stop mode, get out of getpkt even if a
6716 notification is received. */
6717
6718 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6719 0 /* forever */, &is_notif);
74531fed
PA
6720 while (1)
6721 {
fee9eda9 6722 if (ret != -1 && !is_notif)
74531fed
PA
6723 switch (rs->buf[0])
6724 {
6725 case 'E': /* Error of some sort. */
6726 /* We're out of sync with the target now. Did it continue
6727 or not? We can't tell which thread it was in non-stop,
6728 so just ignore this. */
6729 warning (_("Remote failure reply: %s"), rs->buf);
6730 break;
6731 case 'O': /* Console output. */
6732 remote_console_output (rs->buf + 1);
6733 break;
6734 default:
6735 warning (_("Invalid remote reply: %s"), rs->buf);
6736 break;
6737 }
6738
6739 /* Acknowledge a pending stop reply that may have arrived in the
6740 mean time. */
f48ff2a7 6741 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6742 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6743
6744 /* If indeed we noticed a stop reply, we're done. */
6745 stop_reply = queued_stop_reply (ptid);
6746 if (stop_reply != NULL)
6747 return process_stop_reply (stop_reply, status);
6748
47608cb1 6749 /* Still no event. If we're just polling for an event, then
74531fed 6750 return to the event loop. */
47608cb1 6751 if (options & TARGET_WNOHANG)
74531fed
PA
6752 {
6753 status->kind = TARGET_WAITKIND_IGNORE;
6754 return minus_one_ptid;
6755 }
6756
47608cb1 6757 /* Otherwise do a blocking wait. */
74531fed 6758 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6759 1 /* forever */, &is_notif);
74531fed
PA
6760 }
6761}
6762
6763/* Wait until the remote machine stops, then return, storing status in
6764 STATUS just as `wait' would. */
6765
6766static ptid_t
47608cb1 6767remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6768{
6769 struct remote_state *rs = get_remote_state ();
74531fed 6770 ptid_t event_ptid = null_ptid;
cea39f65 6771 char *buf;
74531fed
PA
6772 struct stop_reply *stop_reply;
6773
47608cb1
PA
6774 again:
6775
74531fed
PA
6776 status->kind = TARGET_WAITKIND_IGNORE;
6777 status->value.integer = 0;
6778
6779 stop_reply = queued_stop_reply (ptid);
6780 if (stop_reply != NULL)
6781 return process_stop_reply (stop_reply, status);
6782
6783 if (rs->cached_wait_status)
6784 /* Use the cached wait status, but only once. */
6785 rs->cached_wait_status = 0;
6786 else
6787 {
6788 int ret;
722247f1 6789 int is_notif;
567420d1
PA
6790 int forever = ((options & TARGET_WNOHANG) == 0
6791 && wait_forever_enabled_p);
6792
6793 if (!rs->waiting_for_stop_reply)
6794 {
6795 status->kind = TARGET_WAITKIND_NO_RESUMED;
6796 return minus_one_ptid;
6797 }
74531fed
PA
6798
6799 if (!target_is_async_p ())
6800 {
934b9bac 6801 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6802 /* If the user hit C-c before this packet, or between packets,
6803 pretend that it was hit right here. */
522002f9 6804 if (check_quit_flag ())
74531fed 6805 {
522002f9 6806 clear_quit_flag ();
934b9bac 6807 sync_remote_interrupt (SIGINT);
74531fed
PA
6808 }
6809 }
6810
6811 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6812 _never_ wait for ever -> test on target_is_async_p().
6813 However, before we do that we need to ensure that the caller
6814 knows how to take the target into/out of async mode. */
722247f1 6815 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6816 forever, &is_notif);
722247f1 6817
5e1b953b
SDJ
6818 if (!target_is_async_p ())
6819 signal (SIGINT, ofunc);
6820
722247f1
YQ
6821 /* GDB gets a notification. Return to core as this event is
6822 not interesting. */
6823 if (ret != -1 && is_notif)
6824 return minus_one_ptid;
567420d1
PA
6825
6826 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6827 return minus_one_ptid;
74531fed
PA
6828 }
6829
6830 buf = rs->buf;
6831
3a29589a
DJ
6832 /* Assume that the target has acknowledged Ctrl-C unless we receive
6833 an 'F' or 'O' packet. */
6834 if (buf[0] != 'F' && buf[0] != 'O')
6835 rs->ctrlc_pending_p = 0;
6836
74531fed
PA
6837 switch (buf[0])
6838 {
6839 case 'E': /* Error of some sort. */
6840 /* We're out of sync with the target now. Did it continue or
6841 not? Not is more likely, so report a stop. */
29090fb6
LM
6842 rs->waiting_for_stop_reply = 0;
6843
74531fed
PA
6844 warning (_("Remote failure reply: %s"), buf);
6845 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6846 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6847 break;
6848 case 'F': /* File-I/O request. */
3a29589a
DJ
6849 remote_fileio_request (buf, rs->ctrlc_pending_p);
6850 rs->ctrlc_pending_p = 0;
74531fed
PA
6851 break;
6852 case 'T': case 'S': case 'X': case 'W':
6853 {
29090fb6
LM
6854 struct stop_reply *stop_reply;
6855
6856 /* There is a stop reply to handle. */
6857 rs->waiting_for_stop_reply = 0;
6858
6859 stop_reply
722247f1
YQ
6860 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6861 rs->buf);
74531fed 6862
74531fed 6863 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6864 break;
6865 }
6866 case 'O': /* Console output. */
6867 remote_console_output (buf + 1);
c8e38a49
PA
6868 break;
6869 case '\0':
b73be471 6870 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6871 {
6872 /* Zero length reply means that we tried 'S' or 'C' and the
6873 remote system doesn't support it. */
6874 target_terminal_ours_for_output ();
6875 printf_filtered
6876 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6877 gdb_signal_to_name (rs->last_sent_signal));
6878 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6879 target_terminal_inferior ();
6880
280ceea3 6881 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49 6882 putpkt ((char *) buf);
c8e38a49 6883 break;
43ff13b4 6884 }
c8e38a49
PA
6885 /* else fallthrough */
6886 default:
6887 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 6888 break;
43ff13b4 6889 }
c8e38a49 6890
c8e38a49 6891 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6892 {
6893 /* Nothing interesting happened. If we're doing a non-blocking
6894 poll, we're done. Otherwise, go back to waiting. */
6895 if (options & TARGET_WNOHANG)
6896 return minus_one_ptid;
6897 else
6898 goto again;
6899 }
74531fed
PA
6900 else if (status->kind != TARGET_WAITKIND_EXITED
6901 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6902 {
6903 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6904 record_currthread (rs, event_ptid);
82f73884
PA
6905 else
6906 event_ptid = inferior_ptid;
43ff13b4 6907 }
74531fed
PA
6908 else
6909 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6910 record_currthread (rs, minus_one_ptid);
79d7f229 6911
82f73884 6912 return event_ptid;
43ff13b4
JM
6913}
6914
74531fed
PA
6915/* Wait until the remote machine stops, then return, storing status in
6916 STATUS just as `wait' would. */
6917
c8e38a49 6918static ptid_t
117de6a9 6919remote_wait (struct target_ops *ops,
47608cb1 6920 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6921{
6922 ptid_t event_ptid;
6923
6efcd9a8 6924 if (target_is_non_stop_p ())
47608cb1 6925 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6926 else
47608cb1 6927 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6928
d9d41e78 6929 if (target_is_async_p ())
c8e38a49 6930 {
74531fed
PA
6931 /* If there are are events left in the queue tell the event loop
6932 to return here. */
722247f1 6933 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6934 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6935 }
c8e38a49
PA
6936
6937 return event_ptid;
6938}
6939
74ca34ce 6940/* Fetch a single register using a 'p' packet. */
c906108c 6941
b96ec7ac 6942static int
56be3814 6943fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6944{
6945 struct remote_state *rs = get_remote_state ();
2e9f7625 6946 char *buf, *p;
b96ec7ac
AC
6947 char regp[MAX_REGISTER_SIZE];
6948 int i;
6949
4082afcc 6950 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6951 return 0;
6952
6953 if (reg->pnum == -1)
6954 return 0;
6955
2e9f7625 6956 p = rs->buf;
fcad0fa4 6957 *p++ = 'p';
74ca34ce 6958 p += hexnumstr (p, reg->pnum);
fcad0fa4 6959 *p++ = '\0';
1f4437a4
MS
6960 putpkt (rs->buf);
6961 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6962
2e9f7625
DJ
6963 buf = rs->buf;
6964
74ca34ce
DJ
6965 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6966 {
6967 case PACKET_OK:
6968 break;
6969 case PACKET_UNKNOWN:
6970 return 0;
6971 case PACKET_ERROR:
27a9c0bf
MS
6972 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6973 gdbarch_register_name (get_regcache_arch (regcache),
6974 reg->regnum),
6975 buf);
74ca34ce 6976 }
3f9a994c
JB
6977
6978 /* If this register is unfetchable, tell the regcache. */
6979 if (buf[0] == 'x')
8480adf2 6980 {
56be3814 6981 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6982 return 1;
b96ec7ac 6983 }
b96ec7ac 6984
3f9a994c
JB
6985 /* Otherwise, parse and supply the value. */
6986 p = buf;
6987 i = 0;
6988 while (p[0] != 0)
6989 {
6990 if (p[1] == 0)
74ca34ce 6991 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6992
6993 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6994 p += 2;
6995 }
56be3814 6996 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6997 return 1;
b96ec7ac
AC
6998}
6999
74ca34ce
DJ
7000/* Fetch the registers included in the target's 'g' packet. */
7001
29709017
DJ
7002static int
7003send_g_packet (void)
c906108c 7004{
d01949b6 7005 struct remote_state *rs = get_remote_state ();
cea39f65 7006 int buf_len;
c906108c 7007
bba74b36 7008 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7009 remote_send (&rs->buf, &rs->buf_size);
c906108c 7010
29709017
DJ
7011 /* We can get out of synch in various cases. If the first character
7012 in the buffer is not a hex character, assume that has happened
7013 and try to fetch another packet to read. */
7014 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7015 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7016 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7017 && rs->buf[0] != 'x') /* New: unavailable register value. */
7018 {
7019 if (remote_debug)
7020 fprintf_unfiltered (gdb_stdlog,
7021 "Bad register packet; fetching a new packet\n");
7022 getpkt (&rs->buf, &rs->buf_size, 0);
7023 }
7024
74ca34ce
DJ
7025 buf_len = strlen (rs->buf);
7026
7027 /* Sanity check the received packet. */
7028 if (buf_len % 2 != 0)
7029 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7030
7031 return buf_len / 2;
7032}
7033
7034static void
56be3814 7035process_g_packet (struct regcache *regcache)
29709017 7036{
4a22f64d 7037 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7038 struct remote_state *rs = get_remote_state ();
7039 struct remote_arch_state *rsa = get_remote_arch_state ();
7040 int i, buf_len;
7041 char *p;
7042 char *regs;
7043
7044 buf_len = strlen (rs->buf);
7045
7046 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7047 if (buf_len > 2 * rsa->sizeof_g_packet)
7048 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7049
7050 /* Save the size of the packet sent to us by the target. It is used
7051 as a heuristic when determining the max size of packets that the
7052 target can safely receive. */
7053 if (rsa->actual_register_packet_size == 0)
7054 rsa->actual_register_packet_size = buf_len;
7055
7056 /* If this is smaller than we guessed the 'g' packet would be,
7057 update our records. A 'g' reply that doesn't include a register's
7058 value implies either that the register is not available, or that
7059 the 'p' packet must be used. */
7060 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7061 {
74ca34ce
DJ
7062 rsa->sizeof_g_packet = buf_len / 2;
7063
4a22f64d 7064 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7065 {
74ca34ce
DJ
7066 if (rsa->regs[i].pnum == -1)
7067 continue;
7068
7069 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7070 rsa->regs[i].in_g_packet = 0;
b96ec7ac 7071 else
74ca34ce 7072 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7073 }
74ca34ce 7074 }
b323314b 7075
224c3ddb 7076 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7077
7078 /* Unimplemented registers read as all bits zero. */
ea9c271d 7079 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7080
c906108c
SS
7081 /* Reply describes registers byte by byte, each byte encoded as two
7082 hex characters. Suck them all up, then supply them to the
7083 register cacheing/storage mechanism. */
7084
74ca34ce 7085 p = rs->buf;
ea9c271d 7086 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7087 {
74ca34ce
DJ
7088 if (p[0] == 0 || p[1] == 0)
7089 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7090 internal_error (__FILE__, __LINE__,
9b20d036 7091 _("unexpected end of 'g' packet reply"));
74ca34ce 7092
c906108c 7093 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7094 regs[i] = 0; /* 'x' */
c906108c
SS
7095 else
7096 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7097 p += 2;
7098 }
7099
a744cf53
MS
7100 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7101 {
7102 struct packet_reg *r = &rsa->regs[i];
7103
7104 if (r->in_g_packet)
7105 {
7106 if (r->offset * 2 >= strlen (rs->buf))
7107 /* This shouldn't happen - we adjusted in_g_packet above. */
7108 internal_error (__FILE__, __LINE__,
9b20d036 7109 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7110 else if (rs->buf[r->offset * 2] == 'x')
7111 {
7112 gdb_assert (r->offset * 2 < strlen (rs->buf));
7113 /* The register isn't available, mark it as such (at
7114 the same time setting the value to zero). */
7115 regcache_raw_supply (regcache, r->regnum, NULL);
7116 }
7117 else
7118 regcache_raw_supply (regcache, r->regnum,
7119 regs + r->offset);
7120 }
7121 }
c906108c
SS
7122}
7123
29709017 7124static void
56be3814 7125fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7126{
7127 send_g_packet ();
56be3814 7128 process_g_packet (regcache);
29709017
DJ
7129}
7130
e6e4e701
PA
7131/* Make the remote selected traceframe match GDB's selected
7132 traceframe. */
7133
7134static void
7135set_remote_traceframe (void)
7136{
7137 int newnum;
262e1174 7138 struct remote_state *rs = get_remote_state ();
e6e4e701 7139
262e1174 7140 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7141 return;
7142
7143 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7144 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7145
7146 newnum = target_trace_find (tfind_number,
7147 get_traceframe_number (), 0, 0, NULL);
7148
7149 /* Should not happen. If it does, all bets are off. */
7150 if (newnum != get_traceframe_number ())
7151 warning (_("could not set remote traceframe"));
7152}
7153
74ca34ce 7154static void
28439f5e
PA
7155remote_fetch_registers (struct target_ops *ops,
7156 struct regcache *regcache, int regnum)
74ca34ce 7157{
74ca34ce
DJ
7158 struct remote_arch_state *rsa = get_remote_arch_state ();
7159 int i;
7160
e6e4e701 7161 set_remote_traceframe ();
79d7f229 7162 set_general_thread (inferior_ptid);
74ca34ce
DJ
7163
7164 if (regnum >= 0)
7165 {
7166 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7167
74ca34ce
DJ
7168 gdb_assert (reg != NULL);
7169
7170 /* If this register might be in the 'g' packet, try that first -
7171 we are likely to read more than one register. If this is the
7172 first 'g' packet, we might be overly optimistic about its
7173 contents, so fall back to 'p'. */
7174 if (reg->in_g_packet)
7175 {
56be3814 7176 fetch_registers_using_g (regcache);
74ca34ce
DJ
7177 if (reg->in_g_packet)
7178 return;
7179 }
7180
56be3814 7181 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7182 return;
7183
7184 /* This register is not available. */
56be3814 7185 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7186
7187 return;
7188 }
7189
56be3814 7190 fetch_registers_using_g (regcache);
74ca34ce 7191
4a22f64d 7192 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7193 if (!rsa->regs[i].in_g_packet)
56be3814 7194 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7195 {
7196 /* This register is not available. */
56be3814 7197 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7198 }
7199}
7200
c906108c
SS
7201/* Prepare to store registers. Since we may send them all (using a
7202 'G' request), we have to read out the ones we don't want to change
7203 first. */
7204
c5aa993b 7205static void
f32dbf8c 7206remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7207{
ea9c271d 7208 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7209 int i;
cfd77fa1 7210 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7211
c906108c 7212 /* Make sure the entire registers array is valid. */
4082afcc 7213 switch (packet_support (PACKET_P))
5a2468f5
JM
7214 {
7215 case PACKET_DISABLE:
7216 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7217 /* Make sure all the necessary registers are cached. */
4a22f64d 7218 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7219 if (rsa->regs[i].in_g_packet)
316f2060 7220 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7221 break;
7222 case PACKET_ENABLE:
7223 break;
7224 }
7225}
7226
ad10f812 7227/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7228 packet was not recognized. */
5a2468f5
JM
7229
7230static int
1f4437a4
MS
7231store_register_using_P (const struct regcache *regcache,
7232 struct packet_reg *reg)
5a2468f5 7233{
4a22f64d 7234 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7235 struct remote_state *rs = get_remote_state ();
5a2468f5 7236 /* Try storing a single register. */
6d820c5c 7237 char *buf = rs->buf;
cfd77fa1 7238 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7239 char *p;
5a2468f5 7240
4082afcc 7241 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7242 return 0;
7243
7244 if (reg->pnum == -1)
7245 return 0;
7246
ea9c271d 7247 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7248 p = buf + strlen (buf);
56be3814 7249 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7250 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7251 putpkt (rs->buf);
7252 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7253
74ca34ce
DJ
7254 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7255 {
7256 case PACKET_OK:
7257 return 1;
7258 case PACKET_ERROR:
27a9c0bf
MS
7259 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7260 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7261 case PACKET_UNKNOWN:
7262 return 0;
7263 default:
7264 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7265 }
c906108c
SS
7266}
7267
23860348
MS
7268/* Store register REGNUM, or all registers if REGNUM == -1, from the
7269 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7270
7271static void
56be3814 7272store_registers_using_G (const struct regcache *regcache)
c906108c 7273{
d01949b6 7274 struct remote_state *rs = get_remote_state ();
ea9c271d 7275 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7276 gdb_byte *regs;
c906108c
SS
7277 char *p;
7278
193cb69f
AC
7279 /* Extract all the registers in the regcache copying them into a
7280 local buffer. */
7281 {
b323314b 7282 int i;
a744cf53 7283
224c3ddb 7284 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7285 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7286 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7287 {
ea9c271d 7288 struct packet_reg *r = &rsa->regs[i];
a744cf53 7289
b323314b 7290 if (r->in_g_packet)
56be3814 7291 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7292 }
7293 }
c906108c
SS
7294
7295 /* Command describes registers byte by byte,
7296 each byte encoded as two hex characters. */
6d820c5c 7297 p = rs->buf;
193cb69f 7298 *p++ = 'G';
74ca34ce
DJ
7299 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7300 updated. */
7301 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7302 putpkt (rs->buf);
7303 getpkt (&rs->buf, &rs->buf_size, 0);
7304 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7305 error (_("Could not write registers; remote failure reply '%s'"),
7306 rs->buf);
c906108c 7307}
74ca34ce
DJ
7308
7309/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7310 of the register cache buffer. FIXME: ignores errors. */
7311
7312static void
28439f5e
PA
7313remote_store_registers (struct target_ops *ops,
7314 struct regcache *regcache, int regnum)
74ca34ce 7315{
74ca34ce
DJ
7316 struct remote_arch_state *rsa = get_remote_arch_state ();
7317 int i;
7318
e6e4e701 7319 set_remote_traceframe ();
79d7f229 7320 set_general_thread (inferior_ptid);
74ca34ce
DJ
7321
7322 if (regnum >= 0)
7323 {
7324 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7325
74ca34ce
DJ
7326 gdb_assert (reg != NULL);
7327
7328 /* Always prefer to store registers using the 'P' packet if
7329 possible; we often change only a small number of registers.
7330 Sometimes we change a larger number; we'd need help from a
7331 higher layer to know to use 'G'. */
56be3814 7332 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7333 return;
7334
7335 /* For now, don't complain if we have no way to write the
7336 register. GDB loses track of unavailable registers too
7337 easily. Some day, this may be an error. We don't have
0df8b418 7338 any way to read the register, either... */
74ca34ce
DJ
7339 if (!reg->in_g_packet)
7340 return;
7341
56be3814 7342 store_registers_using_G (regcache);
74ca34ce
DJ
7343 return;
7344 }
7345
56be3814 7346 store_registers_using_G (regcache);
74ca34ce 7347
4a22f64d 7348 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7349 if (!rsa->regs[i].in_g_packet)
56be3814 7350 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7351 /* See above for why we do not issue an error here. */
7352 continue;
7353}
c906108c
SS
7354\f
7355
7356/* Return the number of hex digits in num. */
7357
7358static int
fba45db2 7359hexnumlen (ULONGEST num)
c906108c
SS
7360{
7361 int i;
7362
7363 for (i = 0; num != 0; i++)
7364 num >>= 4;
7365
7366 return max (i, 1);
7367}
7368
2df3850c 7369/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7370
7371static int
fba45db2 7372hexnumstr (char *buf, ULONGEST num)
c906108c 7373{
c906108c 7374 int len = hexnumlen (num);
a744cf53 7375
2df3850c
JM
7376 return hexnumnstr (buf, num, len);
7377}
7378
c906108c 7379
2df3850c 7380/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7381
2df3850c 7382static int
fba45db2 7383hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7384{
7385 int i;
7386
7387 buf[width] = '\0';
7388
7389 for (i = width - 1; i >= 0; i--)
c906108c 7390 {
c5aa993b 7391 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7392 num >>= 4;
7393 }
7394
2df3850c 7395 return width;
c906108c
SS
7396}
7397
23860348 7398/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7399
7400static CORE_ADDR
fba45db2 7401remote_address_masked (CORE_ADDR addr)
c906108c 7402{
883b9c6c 7403 unsigned int address_size = remote_address_size;
a744cf53 7404
911c95a5
UW
7405 /* If "remoteaddresssize" was not set, default to target address size. */
7406 if (!address_size)
f5656ead 7407 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7408
7409 if (address_size > 0
7410 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7411 {
7412 /* Only create a mask when that mask can safely be constructed
23860348 7413 in a ULONGEST variable. */
c906108c 7414 ULONGEST mask = 1;
a744cf53 7415
911c95a5 7416 mask = (mask << address_size) - 1;
c906108c
SS
7417 addr &= mask;
7418 }
7419 return addr;
7420}
7421
7422/* Determine whether the remote target supports binary downloading.
7423 This is accomplished by sending a no-op memory write of zero length
7424 to the target at the specified address. It does not suffice to send
23860348
MS
7425 the whole packet, since many stubs strip the eighth bit and
7426 subsequently compute a wrong checksum, which causes real havoc with
7427 remote_write_bytes.
7a292a7a 7428
96baa820 7429 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7430 clean. In cases like this, the user should clear "remote
23860348 7431 X-packet". */
96baa820 7432
c906108c 7433static void
fba45db2 7434check_binary_download (CORE_ADDR addr)
c906108c 7435{
d01949b6 7436 struct remote_state *rs = get_remote_state ();
24b06219 7437
4082afcc 7438 switch (packet_support (PACKET_X))
c906108c 7439 {
96baa820
JM
7440 case PACKET_DISABLE:
7441 break;
7442 case PACKET_ENABLE:
7443 break;
7444 case PACKET_SUPPORT_UNKNOWN:
7445 {
96baa820 7446 char *p;
802188a7 7447
2e9f7625 7448 p = rs->buf;
96baa820
JM
7449 *p++ = 'X';
7450 p += hexnumstr (p, (ULONGEST) addr);
7451 *p++ = ',';
7452 p += hexnumstr (p, (ULONGEST) 0);
7453 *p++ = ':';
7454 *p = '\0';
802188a7 7455
2e9f7625 7456 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7457 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7458
2e9f7625 7459 if (rs->buf[0] == '\0')
96baa820
JM
7460 {
7461 if (remote_debug)
7462 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7463 "binary downloading NOT "
7464 "supported by target\n");
444abaca 7465 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7466 }
7467 else
7468 {
7469 if (remote_debug)
7470 fprintf_unfiltered (gdb_stdlog,
64b9b334 7471 "binary downloading supported by target\n");
444abaca 7472 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7473 }
7474 break;
7475 }
c906108c
SS
7476 }
7477}
7478
124e13d9
SM
7479/* Helper function to resize the payload in order to try to get a good
7480 alignment. We try to write an amount of data such that the next write will
7481 start on an address aligned on REMOTE_ALIGN_WRITES. */
7482
7483static int
7484align_for_efficient_write (int todo, CORE_ADDR memaddr)
7485{
7486 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7487}
7488
c906108c
SS
7489/* Write memory data directly to the remote machine.
7490 This does not inform the data cache; the data cache uses this.
a76d924d 7491 HEADER is the starting part of the packet.
c906108c
SS
7492 MEMADDR is the address in the remote memory space.
7493 MYADDR is the address of the buffer in our space.
124e13d9
SM
7494 LEN_UNITS is the number of addressable units to write.
7495 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7496 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7497 should send data as binary ('X'), or hex-encoded ('M').
7498
7499 The function creates packet of the form
7500 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7501
124e13d9 7502 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7503
7504 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7505 are omitted.
7506
9b409511 7507 Return the transferred status, error or OK (an
124e13d9
SM
7508 'enum target_xfer_status' value). Save the number of addressable units
7509 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7510
7511 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7512 exchange between gdb and the stub could look like (?? in place of the
7513 checksum):
7514
7515 -> $m1000,4#??
7516 <- aaaabbbbccccdddd
7517
7518 -> $M1000,3:eeeeffffeeee#??
7519 <- OK
7520
7521 -> $m1000,4#??
7522 <- eeeeffffeeeedddd */
c906108c 7523
9b409511 7524static enum target_xfer_status
a76d924d 7525remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7526 const gdb_byte *myaddr, ULONGEST len_units,
7527 int unit_size, ULONGEST *xfered_len_units,
7528 char packet_format, int use_length)
c906108c 7529{
6d820c5c 7530 struct remote_state *rs = get_remote_state ();
cfd77fa1 7531 char *p;
a76d924d
DJ
7532 char *plen = NULL;
7533 int plenlen = 0;
124e13d9
SM
7534 int todo_units;
7535 int units_written;
7536 int payload_capacity_bytes;
7537 int payload_length_bytes;
a76d924d
DJ
7538
7539 if (packet_format != 'X' && packet_format != 'M')
7540 internal_error (__FILE__, __LINE__,
9b20d036 7541 _("remote_write_bytes_aux: bad packet format"));
c906108c 7542
124e13d9 7543 if (len_units == 0)
9b409511 7544 return TARGET_XFER_EOF;
b2182ed2 7545
124e13d9 7546 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7547
6d820c5c
DJ
7548 /* The packet buffer will be large enough for the payload;
7549 get_memory_packet_size ensures this. */
a76d924d 7550 rs->buf[0] = '\0';
c906108c 7551
a257b5bb 7552 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7553 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7554
124e13d9 7555 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7556 if (!use_length)
0df8b418 7557 /* The comma won't be used. */
124e13d9
SM
7558 payload_capacity_bytes += 1;
7559 payload_capacity_bytes -= strlen (header);
7560 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7561
a76d924d 7562 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7563
a76d924d
DJ
7564 strcat (rs->buf, header);
7565 p = rs->buf + strlen (header);
7566
7567 /* Compute a best guess of the number of bytes actually transfered. */
7568 if (packet_format == 'X')
c906108c 7569 {
23860348 7570 /* Best guess at number of bytes that will fit. */
124e13d9 7571 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7572 if (use_length)
124e13d9
SM
7573 payload_capacity_bytes -= hexnumlen (todo_units);
7574 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7575 }
7576 else
7577 {
124e13d9
SM
7578 /* Number of bytes that will fit. */
7579 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7580 if (use_length)
124e13d9
SM
7581 payload_capacity_bytes -= hexnumlen (todo_units);
7582 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7583 }
a76d924d 7584
124e13d9 7585 if (todo_units <= 0)
3de11b2e 7586 internal_error (__FILE__, __LINE__,
405f8e94 7587 _("minimum packet size too small to write data"));
802188a7 7588
6765f3e5
DJ
7589 /* If we already need another packet, then try to align the end
7590 of this packet to a useful boundary. */
124e13d9
SM
7591 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7592 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7593
a257b5bb 7594 /* Append "<memaddr>". */
917317f4
JM
7595 memaddr = remote_address_masked (memaddr);
7596 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7597
a76d924d
DJ
7598 if (use_length)
7599 {
7600 /* Append ",". */
7601 *p++ = ',';
802188a7 7602
124e13d9
SM
7603 /* Append the length and retain its location and size. It may need to be
7604 adjusted once the packet body has been created. */
a76d924d 7605 plen = p;
124e13d9 7606 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7607 p += plenlen;
7608 }
a257b5bb
AC
7609
7610 /* Append ":". */
917317f4
JM
7611 *p++ = ':';
7612 *p = '\0';
802188a7 7613
a257b5bb 7614 /* Append the packet body. */
a76d924d 7615 if (packet_format == 'X')
917317f4 7616 {
917317f4
JM
7617 /* Binary mode. Send target system values byte by byte, in
7618 increasing byte addresses. Only escape certain critical
7619 characters. */
124e13d9
SM
7620 payload_length_bytes =
7621 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7622 &units_written, payload_capacity_bytes);
6765f3e5 7623
124e13d9 7624 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7625 a second try to keep the end of the packet aligned. Don't do
7626 this if the packet is tiny. */
124e13d9 7627 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7628 {
124e13d9
SM
7629 int new_todo_units;
7630
7631 new_todo_units = align_for_efficient_write (units_written, memaddr);
7632
7633 if (new_todo_units != units_written)
7634 payload_length_bytes =
7635 remote_escape_output (myaddr, new_todo_units, unit_size,
7636 (gdb_byte *) p, &units_written,
7637 payload_capacity_bytes);
6765f3e5
DJ
7638 }
7639
124e13d9
SM
7640 p += payload_length_bytes;
7641 if (use_length && units_written < todo_units)
c906108c 7642 {
802188a7 7643 /* Escape chars have filled up the buffer prematurely,
124e13d9 7644 and we have actually sent fewer units than planned.
917317f4
JM
7645 Fix-up the length field of the packet. Use the same
7646 number of characters as before. */
124e13d9
SM
7647 plen += hexnumnstr (plen, (ULONGEST) units_written,
7648 plenlen);
917317f4 7649 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7650 }
a76d924d
DJ
7651 }
7652 else
7653 {
917317f4
JM
7654 /* Normal mode: Send target system values byte by byte, in
7655 increasing byte addresses. Each byte is encoded as a two hex
7656 value. */
124e13d9
SM
7657 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7658 units_written = todo_units;
c906108c 7659 }
802188a7 7660
2e9f7625 7661 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7662 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7663
2e9f7625 7664 if (rs->buf[0] == 'E')
00d84524 7665 return TARGET_XFER_E_IO;
802188a7 7666
124e13d9
SM
7667 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7668 send fewer units than we'd planned. */
7669 *xfered_len_units = (ULONGEST) units_written;
9b409511 7670 return TARGET_XFER_OK;
c906108c
SS
7671}
7672
a76d924d
DJ
7673/* Write memory data directly to the remote machine.
7674 This does not inform the data cache; the data cache uses this.
7675 MEMADDR is the address in the remote memory space.
7676 MYADDR is the address of the buffer in our space.
7677 LEN is the number of bytes.
7678
9b409511
YQ
7679 Return the transferred status, error or OK (an
7680 'enum target_xfer_status' value). Save the number of bytes
7681 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7682
9b409511
YQ
7683static enum target_xfer_status
7684remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7685 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7686{
7687 char *packet_format = 0;
7688
7689 /* Check whether the target supports binary download. */
7690 check_binary_download (memaddr);
7691
4082afcc 7692 switch (packet_support (PACKET_X))
a76d924d
DJ
7693 {
7694 case PACKET_ENABLE:
7695 packet_format = "X";
7696 break;
7697 case PACKET_DISABLE:
7698 packet_format = "M";
7699 break;
7700 case PACKET_SUPPORT_UNKNOWN:
7701 internal_error (__FILE__, __LINE__,
7702 _("remote_write_bytes: bad internal state"));
7703 default:
7704 internal_error (__FILE__, __LINE__, _("bad switch"));
7705 }
7706
7707 return remote_write_bytes_aux (packet_format,
124e13d9 7708 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7709 packet_format[0], 1);
a76d924d
DJ
7710}
7711
9217e74e
YQ
7712/* Read memory data directly from the remote machine.
7713 This does not use the data cache; the data cache uses this.
7714 MEMADDR is the address in the remote memory space.
7715 MYADDR is the address of the buffer in our space.
124e13d9
SM
7716 LEN_UNITS is the number of addressable memory units to read..
7717 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7718
7719 Return the transferred status, error or OK (an
7720 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7721 transferred in *XFERED_LEN_UNITS.
7722
7723 See the comment of remote_write_bytes_aux for an example of
7724 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7725
7726static enum target_xfer_status
124e13d9
SM
7727remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7728 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7729{
7730 struct remote_state *rs = get_remote_state ();
124e13d9 7731 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7732 char *p;
124e13d9
SM
7733 int todo_units;
7734 int decoded_bytes;
9217e74e 7735
124e13d9 7736 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7737 /* The packet buffer will be large enough for the payload;
7738 get_memory_packet_size ensures this. */
7739
124e13d9
SM
7740 /* Number of units that will fit. */
7741 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7742
7743 /* Construct "m"<memaddr>","<len>". */
7744 memaddr = remote_address_masked (memaddr);
7745 p = rs->buf;
7746 *p++ = 'm';
7747 p += hexnumstr (p, (ULONGEST) memaddr);
7748 *p++ = ',';
124e13d9 7749 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7750 *p = '\0';
7751 putpkt (rs->buf);
7752 getpkt (&rs->buf, &rs->buf_size, 0);
7753 if (rs->buf[0] == 'E'
7754 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7755 && rs->buf[3] == '\0')
7756 return TARGET_XFER_E_IO;
7757 /* Reply describes memory byte by byte, each byte encoded as two hex
7758 characters. */
7759 p = rs->buf;
124e13d9 7760 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7761 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7762 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7763 return TARGET_XFER_OK;
7764}
7765
b55fbac4
YQ
7766/* Using the set of read-only target sections of remote, read live
7767 read-only memory.
8acf9577
YQ
7768
7769 For interface/parameters/return description see target.h,
7770 to_xfer_partial. */
7771
7772static enum target_xfer_status
b55fbac4
YQ
7773remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7774 ULONGEST memaddr, ULONGEST len,
124e13d9 7775 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7776{
7777 struct target_section *secp;
7778 struct target_section_table *table;
7779
7780 secp = target_section_by_addr (ops, memaddr);
7781 if (secp != NULL
7782 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7783 secp->the_bfd_section)
7784 & SEC_READONLY))
7785 {
7786 struct target_section *p;
7787 ULONGEST memend = memaddr + len;
7788
7789 table = target_get_section_table (ops);
7790
7791 for (p = table->sections; p < table->sections_end; p++)
7792 {
7793 if (memaddr >= p->addr)
7794 {
7795 if (memend <= p->endaddr)
7796 {
7797 /* Entire transfer is within this section. */
124e13d9 7798 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7799 xfered_len);
8acf9577
YQ
7800 }
7801 else if (memaddr >= p->endaddr)
7802 {
7803 /* This section ends before the transfer starts. */
7804 continue;
7805 }
7806 else
7807 {
7808 /* This section overlaps the transfer. Just do half. */
7809 len = p->endaddr - memaddr;
124e13d9 7810 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7811 xfered_len);
8acf9577
YQ
7812 }
7813 }
7814 }
7815 }
7816
7817 return TARGET_XFER_EOF;
7818}
7819
9217e74e
YQ
7820/* Similar to remote_read_bytes_1, but it reads from the remote stub
7821 first if the requested memory is unavailable in traceframe.
7822 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7823
9b409511 7824static enum target_xfer_status
8acf9577 7825remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7826 gdb_byte *myaddr, ULONGEST len, int unit_size,
7827 ULONGEST *xfered_len)
c906108c 7828{
6b6aa828 7829 if (len == 0)
96c4f946 7830 return TARGET_XFER_EOF;
b2182ed2 7831
8acf9577
YQ
7832 if (get_traceframe_number () != -1)
7833 {
7834 VEC(mem_range_s) *available;
7835
7836 /* If we fail to get the set of available memory, then the
7837 target does not support querying traceframe info, and so we
7838 attempt reading from the traceframe anyway (assuming the
7839 target implements the old QTro packet then). */
7840 if (traceframe_available_memory (&available, memaddr, len))
7841 {
7842 struct cleanup *old_chain;
7843
7844 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7845
7846 if (VEC_empty (mem_range_s, available)
7847 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7848 {
7849 enum target_xfer_status res;
7850
7851 /* Don't read into the traceframe's available
7852 memory. */
7853 if (!VEC_empty (mem_range_s, available))
7854 {
7855 LONGEST oldlen = len;
7856
7857 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7858 gdb_assert (len <= oldlen);
7859 }
7860
7861 do_cleanups (old_chain);
7862
7863 /* This goes through the topmost target again. */
b55fbac4 7864 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7865 len, unit_size, xfered_len);
8acf9577
YQ
7866 if (res == TARGET_XFER_OK)
7867 return TARGET_XFER_OK;
7868 else
7869 {
7870 /* No use trying further, we know some memory starting
7871 at MEMADDR isn't available. */
7872 *xfered_len = len;
7873 return TARGET_XFER_UNAVAILABLE;
7874 }
7875 }
7876
7877 /* Don't try to read more than how much is available, in
7878 case the target implements the deprecated QTro packet to
7879 cater for older GDBs (the target's knowledge of read-only
7880 sections may be outdated by now). */
7881 len = VEC_index (mem_range_s, available, 0)->length;
7882
7883 do_cleanups (old_chain);
7884 }
7885 }
7886
124e13d9 7887 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7888}
74531fed 7889
c906108c 7890\f
c906108c 7891
a76d924d
DJ
7892/* Sends a packet with content determined by the printf format string
7893 FORMAT and the remaining arguments, then gets the reply. Returns
7894 whether the packet was a success, a failure, or unknown. */
7895
77b64a49
PA
7896static enum packet_result remote_send_printf (const char *format, ...)
7897 ATTRIBUTE_PRINTF (1, 2);
7898
2c0b251b 7899static enum packet_result
a76d924d
DJ
7900remote_send_printf (const char *format, ...)
7901{
7902 struct remote_state *rs = get_remote_state ();
7903 int max_size = get_remote_packet_size ();
a76d924d 7904 va_list ap;
a744cf53 7905
a76d924d
DJ
7906 va_start (ap, format);
7907
7908 rs->buf[0] = '\0';
7909 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7910 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7911
7912 if (putpkt (rs->buf) < 0)
7913 error (_("Communication problem with target."));
7914
7915 rs->buf[0] = '\0';
7916 getpkt (&rs->buf, &rs->buf_size, 0);
7917
7918 return packet_check_result (rs->buf);
7919}
7920
7921static void
7922restore_remote_timeout (void *p)
7923{
7924 int value = *(int *)p;
a744cf53 7925
a76d924d
DJ
7926 remote_timeout = value;
7927}
7928
7929/* Flash writing can take quite some time. We'll set
7930 effectively infinite timeout for flash operations.
7931 In future, we'll need to decide on a better approach. */
7932static const int remote_flash_timeout = 1000;
7933
7934static void
7935remote_flash_erase (struct target_ops *ops,
7936 ULONGEST address, LONGEST length)
7937{
f5656ead 7938 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7939 int saved_remote_timeout = remote_timeout;
7940 enum packet_result ret;
a76d924d
DJ
7941 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7942 &saved_remote_timeout);
a744cf53 7943
a76d924d
DJ
7944 remote_timeout = remote_flash_timeout;
7945
7946 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7947 phex (address, addr_size),
a76d924d
DJ
7948 phex (length, 4));
7949 switch (ret)
7950 {
7951 case PACKET_UNKNOWN:
7952 error (_("Remote target does not support flash erase"));
7953 case PACKET_ERROR:
7954 error (_("Error erasing flash with vFlashErase packet"));
7955 default:
7956 break;
7957 }
7958
7959 do_cleanups (back_to);
7960}
7961
9b409511
YQ
7962static enum target_xfer_status
7963remote_flash_write (struct target_ops *ops, ULONGEST address,
7964 ULONGEST length, ULONGEST *xfered_len,
7965 const gdb_byte *data)
a76d924d
DJ
7966{
7967 int saved_remote_timeout = remote_timeout;
9b409511 7968 enum target_xfer_status ret;
a76d924d 7969 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7970 &saved_remote_timeout);
a76d924d
DJ
7971
7972 remote_timeout = remote_flash_timeout;
124e13d9 7973 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 7974 xfered_len,'X', 0);
a76d924d
DJ
7975 do_cleanups (back_to);
7976
7977 return ret;
7978}
7979
7980static void
7981remote_flash_done (struct target_ops *ops)
7982{
7983 int saved_remote_timeout = remote_timeout;
7984 int ret;
7985 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7986 &saved_remote_timeout);
7987
7988 remote_timeout = remote_flash_timeout;
7989 ret = remote_send_printf ("vFlashDone");
7990 do_cleanups (back_to);
7991
7992 switch (ret)
7993 {
7994 case PACKET_UNKNOWN:
7995 error (_("Remote target does not support vFlashDone"));
7996 case PACKET_ERROR:
7997 error (_("Error finishing flash operation"));
7998 default:
7999 break;
8000 }
8001}
8002
c906108c 8003static void
fba45db2 8004remote_files_info (struct target_ops *ignore)
c906108c
SS
8005{
8006 puts_filtered ("Debugging a target over a serial line.\n");
8007}
8008\f
8009/* Stuff for dealing with the packets which are part of this protocol.
8010 See comment at top of file for details. */
8011
1927e618
PA
8012/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8013 error to higher layers. Called when a serial error is detected.
8014 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8015 the system error message for errno at function entry and final dot
8016 for output compatibility with throw_perror_with_name. */
1927e618
PA
8017
8018static void
8019unpush_and_perror (const char *string)
8020{
d6cb50a2 8021 int saved_errno = errno;
1927e618
PA
8022
8023 remote_unpush_target ();
d6cb50a2
JK
8024 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8025 safe_strerror (saved_errno));
1927e618
PA
8026}
8027
0876f84a 8028/* Read a single character from the remote end. */
c906108c
SS
8029
8030static int
fba45db2 8031readchar (int timeout)
c906108c
SS
8032{
8033 int ch;
5d93a237 8034 struct remote_state *rs = get_remote_state ();
c906108c 8035
5d93a237 8036 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 8037
2acceee2 8038 if (ch >= 0)
0876f84a 8039 return ch;
2acceee2
JM
8040
8041 switch ((enum serial_rc) ch)
c906108c
SS
8042 {
8043 case SERIAL_EOF:
78a095c3 8044 remote_unpush_target ();
598d3636 8045 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8046 /* no return */
c906108c 8047 case SERIAL_ERROR:
1927e618
PA
8048 unpush_and_perror (_("Remote communication error. "
8049 "Target disconnected."));
2acceee2 8050 /* no return */
c906108c 8051 case SERIAL_TIMEOUT:
2acceee2 8052 break;
c906108c 8053 }
2acceee2 8054 return ch;
c906108c
SS
8055}
8056
c33e31fd
PA
8057/* Wrapper for serial_write that closes the target and throws if
8058 writing fails. */
8059
8060static void
8061remote_serial_write (const char *str, int len)
8062{
5d93a237
TT
8063 struct remote_state *rs = get_remote_state ();
8064
8065 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8066 {
1927e618
PA
8067 unpush_and_perror (_("Remote communication error. "
8068 "Target disconnected."));
c33e31fd
PA
8069 }
8070}
8071
6d820c5c
DJ
8072/* Send the command in *BUF to the remote machine, and read the reply
8073 into *BUF. Report an error if we get an error reply. Resize
8074 *BUF using xrealloc if necessary to hold the result, and update
8075 *SIZEOF_BUF. */
c906108c
SS
8076
8077static void
6d820c5c
DJ
8078remote_send (char **buf,
8079 long *sizeof_buf)
c906108c 8080{
6d820c5c 8081 putpkt (*buf);
c2d11a7d 8082 getpkt (buf, sizeof_buf, 0);
c906108c 8083
6d820c5c
DJ
8084 if ((*buf)[0] == 'E')
8085 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8086}
8087
6e5abd65
PA
8088/* Return a pointer to an xmalloc'ed string representing an escaped
8089 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8090 etc. The caller is responsible for releasing the returned
8091 memory. */
8092
8093static char *
8094escape_buffer (const char *buf, int n)
8095{
8096 struct cleanup *old_chain;
8097 struct ui_file *stb;
8098 char *str;
6e5abd65
PA
8099
8100 stb = mem_fileopen ();
8101 old_chain = make_cleanup_ui_file_delete (stb);
8102
6ef284bd 8103 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 8104 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
8105 do_cleanups (old_chain);
8106 return str;
8107}
8108
c906108c
SS
8109/* Display a null-terminated packet on stdout, for debugging, using C
8110 string notation. */
8111
8112static void
baa336ce 8113print_packet (const char *buf)
c906108c
SS
8114{
8115 puts_filtered ("\"");
43e526b9 8116 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8117 puts_filtered ("\"");
8118}
8119
8120int
baa336ce 8121putpkt (const char *buf)
c906108c
SS
8122{
8123 return putpkt_binary (buf, strlen (buf));
8124}
8125
8126/* Send a packet to the remote machine, with error checking. The data
23860348 8127 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8128 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8129 and for a possible /0 if we are debugging (remote_debug) and want
8130 to print the sent packet as a string. */
c906108c
SS
8131
8132static int
baa336ce 8133putpkt_binary (const char *buf, int cnt)
c906108c 8134{
2d717e4f 8135 struct remote_state *rs = get_remote_state ();
c906108c
SS
8136 int i;
8137 unsigned char csum = 0;
224c3ddb 8138 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8139 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8140
c906108c
SS
8141 int ch;
8142 int tcount = 0;
8143 char *p;
dd61ec5c 8144 char *message;
c906108c 8145
e24a49d8
PA
8146 /* Catch cases like trying to read memory or listing threads while
8147 we're waiting for a stop reply. The remote server wouldn't be
8148 ready to handle this request, so we'd hang and timeout. We don't
8149 have to worry about this in synchronous mode, because in that
8150 case it's not possible to issue a command while the target is
74531fed
PA
8151 running. This is not a problem in non-stop mode, because in that
8152 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8153 if (!target_is_non_stop_p ()
8154 && target_is_async_p ()
8155 && rs->waiting_for_stop_reply)
9597b22a
DE
8156 {
8157 error (_("Cannot execute this command while the target is running.\n"
8158 "Use the \"interrupt\" command to stop the target\n"
8159 "and then try again."));
8160 }
e24a49d8 8161
2d717e4f
DJ
8162 /* We're sending out a new packet. Make sure we don't look at a
8163 stale cached response. */
8164 rs->cached_wait_status = 0;
8165
c906108c
SS
8166 /* Copy the packet into buffer BUF2, encapsulating it
8167 and giving it a checksum. */
8168
c906108c
SS
8169 p = buf2;
8170 *p++ = '$';
8171
8172 for (i = 0; i < cnt; i++)
8173 {
8174 csum += buf[i];
8175 *p++ = buf[i];
8176 }
8177 *p++ = '#';
8178 *p++ = tohex ((csum >> 4) & 0xf);
8179 *p++ = tohex (csum & 0xf);
8180
8181 /* Send it over and over until we get a positive ack. */
8182
8183 while (1)
8184 {
8185 int started_error_output = 0;
8186
8187 if (remote_debug)
8188 {
6e5abd65
PA
8189 struct cleanup *old_chain;
8190 char *str;
8191
c906108c 8192 *p = '\0';
6e5abd65
PA
8193 str = escape_buffer (buf2, p - buf2);
8194 old_chain = make_cleanup (xfree, str);
8195 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8196 gdb_flush (gdb_stdlog);
6e5abd65 8197 do_cleanups (old_chain);
c906108c 8198 }
c33e31fd 8199 remote_serial_write (buf2, p - buf2);
c906108c 8200
a6f3e723
SL
8201 /* If this is a no acks version of the remote protocol, send the
8202 packet and move on. */
8203 if (rs->noack_mode)
8204 break;
8205
74531fed
PA
8206 /* Read until either a timeout occurs (-2) or '+' is read.
8207 Handle any notification that arrives in the mean time. */
c906108c
SS
8208 while (1)
8209 {
8210 ch = readchar (remote_timeout);
8211
c5aa993b 8212 if (remote_debug)
c906108c
SS
8213 {
8214 switch (ch)
8215 {
8216 case '+':
1216fa2c 8217 case '-':
c906108c
SS
8218 case SERIAL_TIMEOUT:
8219 case '$':
74531fed 8220 case '%':
c906108c
SS
8221 if (started_error_output)
8222 {
8223 putchar_unfiltered ('\n');
8224 started_error_output = 0;
8225 }
8226 }
8227 }
8228
8229 switch (ch)
8230 {
8231 case '+':
8232 if (remote_debug)
0f71a2f6 8233 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8234 do_cleanups (old_chain);
c906108c 8235 return 1;
1216fa2c
AC
8236 case '-':
8237 if (remote_debug)
8238 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8239 /* FALLTHROUGH */
c906108c 8240 case SERIAL_TIMEOUT:
c5aa993b 8241 tcount++;
c906108c 8242 if (tcount > 3)
a5c0808e
PA
8243 {
8244 do_cleanups (old_chain);
8245 return 0;
8246 }
23860348 8247 break; /* Retransmit buffer. */
c906108c
SS
8248 case '$':
8249 {
40e3f985 8250 if (remote_debug)
2bc416ba 8251 fprintf_unfiltered (gdb_stdlog,
23860348 8252 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8253 /* It's probably an old response sent because an ACK
8254 was lost. Gobble up the packet and ack it so it
8255 doesn't get retransmitted when we resend this
8256 packet. */
6d820c5c 8257 skip_frame ();
c33e31fd 8258 remote_serial_write ("+", 1);
23860348 8259 continue; /* Now, go look for +. */
c906108c 8260 }
74531fed
PA
8261
8262 case '%':
8263 {
8264 int val;
8265
8266 /* If we got a notification, handle it, and go back to looking
8267 for an ack. */
8268 /* We've found the start of a notification. Now
8269 collect the data. */
8270 val = read_frame (&rs->buf, &rs->buf_size);
8271 if (val >= 0)
8272 {
8273 if (remote_debug)
8274 {
6e5abd65
PA
8275 struct cleanup *old_chain;
8276 char *str;
8277
8278 str = escape_buffer (rs->buf, val);
8279 old_chain = make_cleanup (xfree, str);
8280 fprintf_unfiltered (gdb_stdlog,
8281 " Notification received: %s\n",
8282 str);
8283 do_cleanups (old_chain);
74531fed 8284 }
5965e028 8285 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8286 /* We're in sync now, rewait for the ack. */
8287 tcount = 0;
8288 }
8289 else
8290 {
8291 if (remote_debug)
8292 {
8293 if (!started_error_output)
8294 {
8295 started_error_output = 1;
8296 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8297 }
8298 fputc_unfiltered (ch & 0177, gdb_stdlog);
8299 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8300 }
8301 }
8302 continue;
8303 }
8304 /* fall-through */
c906108c
SS
8305 default:
8306 if (remote_debug)
8307 {
8308 if (!started_error_output)
8309 {
8310 started_error_output = 1;
0f71a2f6 8311 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8312 }
0f71a2f6 8313 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8314 }
8315 continue;
8316 }
23860348 8317 break; /* Here to retransmit. */
c906108c
SS
8318 }
8319
8320#if 0
8321 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8322 able to get out next time we call QUIT, without anything as
8323 violent as interrupt_query. If we want to provide a way out of
8324 here without getting to the next QUIT, it should be based on
8325 hitting ^C twice as in remote_wait. */
c906108c
SS
8326 if (quit_flag)
8327 {
8328 quit_flag = 0;
8329 interrupt_query ();
8330 }
8331#endif
8332 }
a5c0808e
PA
8333
8334 do_cleanups (old_chain);
a6f3e723 8335 return 0;
c906108c
SS
8336}
8337
6d820c5c
DJ
8338/* Come here after finding the start of a frame when we expected an
8339 ack. Do our best to discard the rest of this packet. */
8340
8341static void
8342skip_frame (void)
8343{
8344 int c;
8345
8346 while (1)
8347 {
8348 c = readchar (remote_timeout);
8349 switch (c)
8350 {
8351 case SERIAL_TIMEOUT:
8352 /* Nothing we can do. */
8353 return;
8354 case '#':
8355 /* Discard the two bytes of checksum and stop. */
8356 c = readchar (remote_timeout);
8357 if (c >= 0)
8358 c = readchar (remote_timeout);
8359
8360 return;
8361 case '*': /* Run length encoding. */
8362 /* Discard the repeat count. */
8363 c = readchar (remote_timeout);
8364 if (c < 0)
8365 return;
8366 break;
8367 default:
8368 /* A regular character. */
8369 break;
8370 }
8371 }
8372}
8373
c906108c 8374/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8375 into *BUF, verifying the checksum, length, and handling run-length
8376 compression. NUL terminate the buffer. If there is not enough room,
8377 expand *BUF using xrealloc.
c906108c 8378
c2d11a7d
JM
8379 Returns -1 on error, number of characters in buffer (ignoring the
8380 trailing NULL) on success. (could be extended to return one of the
23860348 8381 SERIAL status indications). */
c2d11a7d
JM
8382
8383static long
6d820c5c
DJ
8384read_frame (char **buf_p,
8385 long *sizeof_buf)
c906108c
SS
8386{
8387 unsigned char csum;
c2d11a7d 8388 long bc;
c906108c 8389 int c;
6d820c5c 8390 char *buf = *buf_p;
a6f3e723 8391 struct remote_state *rs = get_remote_state ();
c906108c
SS
8392
8393 csum = 0;
c2d11a7d 8394 bc = 0;
c906108c
SS
8395
8396 while (1)
8397 {
8398 c = readchar (remote_timeout);
c906108c
SS
8399 switch (c)
8400 {
8401 case SERIAL_TIMEOUT:
8402 if (remote_debug)
0f71a2f6 8403 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8404 return -1;
c906108c
SS
8405 case '$':
8406 if (remote_debug)
0f71a2f6
JM
8407 fputs_filtered ("Saw new packet start in middle of old one\n",
8408 gdb_stdlog);
23860348 8409 return -1; /* Start a new packet, count retries. */
c906108c
SS
8410 case '#':
8411 {
8412 unsigned char pktcsum;
e1b09194
AC
8413 int check_0 = 0;
8414 int check_1 = 0;
c906108c 8415
c2d11a7d 8416 buf[bc] = '\0';
c906108c 8417
e1b09194
AC
8418 check_0 = readchar (remote_timeout);
8419 if (check_0 >= 0)
8420 check_1 = readchar (remote_timeout);
802188a7 8421
e1b09194
AC
8422 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8423 {
8424 if (remote_debug)
2bc416ba 8425 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8426 gdb_stdlog);
e1b09194
AC
8427 return -1;
8428 }
8429 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8430 {
8431 if (remote_debug)
2bc416ba 8432 fputs_filtered ("Communication error in checksum\n",
23860348 8433 gdb_stdlog);
40e3f985
FN
8434 return -1;
8435 }
c906108c 8436
a6f3e723
SL
8437 /* Don't recompute the checksum; with no ack packets we
8438 don't have any way to indicate a packet retransmission
8439 is necessary. */
8440 if (rs->noack_mode)
8441 return bc;
8442
e1b09194 8443 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8444 if (csum == pktcsum)
c2d11a7d 8445 return bc;
c906108c 8446
c5aa993b 8447 if (remote_debug)
c906108c 8448 {
6e5abd65
PA
8449 struct cleanup *old_chain;
8450 char *str;
8451
8452 str = escape_buffer (buf, bc);
8453 old_chain = make_cleanup (xfree, str);
8454 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8455 "Bad checksum, sentsum=0x%x, "
8456 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8457 pktcsum, csum, str);
8458 do_cleanups (old_chain);
c906108c 8459 }
c2d11a7d 8460 /* Number of characters in buffer ignoring trailing
23860348 8461 NULL. */
c2d11a7d 8462 return -1;
c906108c 8463 }
23860348 8464 case '*': /* Run length encoding. */
c2c6d25f
JM
8465 {
8466 int repeat;
c906108c 8467
a744cf53 8468 csum += c;
b4501125
AC
8469 c = readchar (remote_timeout);
8470 csum += c;
23860348 8471 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8472
23860348 8473 /* The character before ``*'' is repeated. */
c2d11a7d 8474
6d820c5c 8475 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8476 {
6d820c5c
DJ
8477 if (bc + repeat - 1 >= *sizeof_buf - 1)
8478 {
8479 /* Make some more room in the buffer. */
8480 *sizeof_buf += repeat;
224c3ddb 8481 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
8482 buf = *buf_p;
8483 }
8484
c2d11a7d
JM
8485 memset (&buf[bc], buf[bc - 1], repeat);
8486 bc += repeat;
c2c6d25f
JM
8487 continue;
8488 }
8489
c2d11a7d 8490 buf[bc] = '\0';
6d820c5c 8491 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8492 return -1;
c2c6d25f 8493 }
c906108c 8494 default:
6d820c5c 8495 if (bc >= *sizeof_buf - 1)
c906108c 8496 {
6d820c5c
DJ
8497 /* Make some more room in the buffer. */
8498 *sizeof_buf *= 2;
224c3ddb 8499 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 8500 buf = *buf_p;
c906108c
SS
8501 }
8502
6d820c5c
DJ
8503 buf[bc++] = c;
8504 csum += c;
8505 continue;
c906108c
SS
8506 }
8507 }
8508}
8509
8510/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8511 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8512 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8513 rather than timing out; this is used (in synchronous mode) to wait
8514 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8515/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8516 don't have to change all the calls to getpkt to deal with the
8517 return value, because at the moment I don't know what the right
23860348 8518 thing to do it for those. */
c906108c 8519void
6d820c5c
DJ
8520getpkt (char **buf,
8521 long *sizeof_buf,
c2d11a7d 8522 int forever)
d9fcf2fb
JM
8523{
8524 int timed_out;
8525
8526 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8527}
8528
8529
8530/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8531 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8532 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8533 rather than timing out; this is used (in synchronous mode) to wait
8534 for a target that is is executing user code to stop. If FOREVER ==
8535 0, this function is allowed to time out gracefully and return an
74531fed
PA
8536 indication of this to the caller. Otherwise return the number of
8537 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8538 enough reason to return to the caller. *IS_NOTIF is an output
8539 boolean that indicates whether *BUF holds a notification or not
8540 (a regular packet). */
74531fed 8541
3172dc30 8542static int
74531fed 8543getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8544 int expecting_notif, int *is_notif)
c906108c 8545{
2d717e4f 8546 struct remote_state *rs = get_remote_state ();
c906108c
SS
8547 int c;
8548 int tries;
8549 int timeout;
df4b58fe 8550 int val = -1;
c906108c 8551
2d717e4f
DJ
8552 /* We're reading a new response. Make sure we don't look at a
8553 previously cached response. */
8554 rs->cached_wait_status = 0;
8555
6d820c5c 8556 strcpy (*buf, "timeout");
c906108c
SS
8557
8558 if (forever)
74531fed
PA
8559 timeout = watchdog > 0 ? watchdog : -1;
8560 else if (expecting_notif)
8561 timeout = 0; /* There should already be a char in the buffer. If
8562 not, bail out. */
c906108c
SS
8563 else
8564 timeout = remote_timeout;
8565
8566#define MAX_TRIES 3
8567
74531fed
PA
8568 /* Process any number of notifications, and then return when
8569 we get a packet. */
8570 for (;;)
c906108c 8571 {
d9c43928 8572 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8573 times. */
8574 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8575 {
74531fed
PA
8576 /* This can loop forever if the remote side sends us
8577 characters continuously, but if it pauses, we'll get
8578 SERIAL_TIMEOUT from readchar because of timeout. Then
8579 we'll count that as a retry.
8580
8581 Note that even when forever is set, we will only wait
8582 forever prior to the start of a packet. After that, we
8583 expect characters to arrive at a brisk pace. They should
8584 show up within remote_timeout intervals. */
8585 do
8586 c = readchar (timeout);
8587 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8588
8589 if (c == SERIAL_TIMEOUT)
8590 {
74531fed
PA
8591 if (expecting_notif)
8592 return -1; /* Don't complain, it's normal to not get
8593 anything in this case. */
8594
23860348 8595 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8596 {
2acceee2 8597 QUIT;
78a095c3 8598 remote_unpush_target ();
598d3636
JK
8599 throw_error (TARGET_CLOSE_ERROR,
8600 _("Watchdog timeout has expired. "
8601 "Target detached."));
c906108c 8602 }
c906108c 8603 if (remote_debug)
0f71a2f6 8604 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8605 }
74531fed
PA
8606 else
8607 {
8608 /* We've found the start of a packet or notification.
8609 Now collect the data. */
8610 val = read_frame (buf, sizeof_buf);
8611 if (val >= 0)
8612 break;
8613 }
8614
c33e31fd 8615 remote_serial_write ("-", 1);
c906108c 8616 }
c906108c 8617
74531fed
PA
8618 if (tries > MAX_TRIES)
8619 {
8620 /* We have tried hard enough, and just can't receive the
8621 packet/notification. Give up. */
8622 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8623
74531fed
PA
8624 /* Skip the ack char if we're in no-ack mode. */
8625 if (!rs->noack_mode)
c33e31fd 8626 remote_serial_write ("+", 1);
74531fed
PA
8627 return -1;
8628 }
c906108c 8629
74531fed
PA
8630 /* If we got an ordinary packet, return that to our caller. */
8631 if (c == '$')
c906108c
SS
8632 {
8633 if (remote_debug)
43e526b9 8634 {
6e5abd65
PA
8635 struct cleanup *old_chain;
8636 char *str;
8637
8638 str = escape_buffer (*buf, val);
8639 old_chain = make_cleanup (xfree, str);
8640 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8641 do_cleanups (old_chain);
43e526b9 8642 }
a6f3e723
SL
8643
8644 /* Skip the ack char if we're in no-ack mode. */
8645 if (!rs->noack_mode)
c33e31fd 8646 remote_serial_write ("+", 1);
fee9eda9
YQ
8647 if (is_notif != NULL)
8648 *is_notif = 0;
0876f84a 8649 return val;
c906108c
SS
8650 }
8651
74531fed
PA
8652 /* If we got a notification, handle it, and go back to looking
8653 for a packet. */
8654 else
8655 {
8656 gdb_assert (c == '%');
8657
8658 if (remote_debug)
8659 {
6e5abd65
PA
8660 struct cleanup *old_chain;
8661 char *str;
8662
8663 str = escape_buffer (*buf, val);
8664 old_chain = make_cleanup (xfree, str);
8665 fprintf_unfiltered (gdb_stdlog,
8666 " Notification received: %s\n",
8667 str);
8668 do_cleanups (old_chain);
74531fed 8669 }
fee9eda9
YQ
8670 if (is_notif != NULL)
8671 *is_notif = 1;
c906108c 8672
5965e028 8673 handle_notification (rs->notif_state, *buf);
c906108c 8674
74531fed 8675 /* Notifications require no acknowledgement. */
a6f3e723 8676
74531fed 8677 if (expecting_notif)
fee9eda9 8678 return val;
74531fed
PA
8679 }
8680 }
8681}
8682
8683static int
8684getpkt_sane (char **buf, long *sizeof_buf, int forever)
8685{
fee9eda9 8686 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8687}
8688
8689static int
fee9eda9
YQ
8690getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8691 int *is_notif)
74531fed 8692{
fee9eda9
YQ
8693 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8694 is_notif);
c906108c 8695}
74531fed 8696
cbb8991c
DB
8697/* Check whether EVENT is a fork event for the process specified
8698 by the pid passed in DATA, and if it is, kill the fork child. */
8699
8700static int
8701kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8702 QUEUE_ITER (stop_reply_p) *iter,
8703 stop_reply_p event,
8704 void *data)
8705{
19ba03f4 8706 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
8707 int parent_pid = *(int *) param->input;
8708
8709 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8710 {
8711 struct remote_state *rs = get_remote_state ();
8712 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8713 int res;
8714
8715 res = remote_vkill (child_pid, rs);
8716 if (res != 0)
8717 error (_("Can't kill fork child process %d"), child_pid);
8718 }
8719
8720 return 1;
8721}
8722
8723/* Kill any new fork children of process PID that haven't been
8724 processed by follow_fork. */
8725
8726static void
8727kill_new_fork_children (int pid, struct remote_state *rs)
8728{
8729 struct thread_info *thread;
8730 struct notif_client *notif = &notif_client_stop;
8731 struct queue_iter_param param;
8732
8733 /* Kill the fork child threads of any threads in process PID
8734 that are stopped at a fork event. */
8735 ALL_NON_EXITED_THREADS (thread)
8736 {
8737 struct target_waitstatus *ws = &thread->pending_follow;
8738
8739 if (is_pending_fork_parent (ws, pid, thread->ptid))
8740 {
8741 struct remote_state *rs = get_remote_state ();
8742 int child_pid = ptid_get_pid (ws->value.related_pid);
8743 int res;
8744
8745 res = remote_vkill (child_pid, rs);
8746 if (res != 0)
8747 error (_("Can't kill fork child process %d"), child_pid);
8748 }
8749 }
8750
8751 /* Check for any pending fork events (not reported or processed yet)
8752 in process PID and kill those fork child threads as well. */
8753 remote_notif_get_pending_events (notif);
8754 param.input = &pid;
8755 param.output = NULL;
8756 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8757 kill_child_of_pending_fork, &param);
8758}
8759
c906108c
SS
8760\f
8761static void
7d85a9c0 8762remote_kill (struct target_ops *ops)
43ff13b4 8763{
0fdf84ca
PA
8764
8765 /* Catch errors so the user can quit from gdb even when we
23860348 8766 aren't on speaking terms with the remote system. */
492d29ea 8767 TRY
0fdf84ca
PA
8768 {
8769 putpkt ("k");
8770 }
492d29ea 8771 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
8772 {
8773 if (ex.error == TARGET_CLOSE_ERROR)
8774 {
8775 /* If we got an (EOF) error that caused the target
8776 to go away, then we're done, that's what we wanted.
8777 "k" is susceptible to cause a premature EOF, given
8778 that the remote server isn't actually required to
8779 reply to "k", and it can happen that it doesn't
8780 even get to reply ACK to the "k". */
8781 return;
8782 }
8783
8784 /* Otherwise, something went wrong. We didn't actually kill
8785 the target. Just propagate the exception, and let the
8786 user or higher layers decide what to do. */
8787 throw_exception (ex);
8788 }
492d29ea 8789 END_CATCH
43ff13b4 8790
0fdf84ca
PA
8791 /* We've killed the remote end, we get to mourn it. Since this is
8792 target remote, single-process, mourning the inferior also
8793 unpushes remote_ops. */
43ff13b4
JM
8794 target_mourn_inferior ();
8795}
8796
82f73884
PA
8797static int
8798remote_vkill (int pid, struct remote_state *rs)
8799{
4082afcc 8800 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8801 return -1;
8802
8803 /* Tell the remote target to detach. */
bba74b36 8804 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8805 putpkt (rs->buf);
8806 getpkt (&rs->buf, &rs->buf_size, 0);
8807
4082afcc
PA
8808 switch (packet_ok (rs->buf,
8809 &remote_protocol_packets[PACKET_vKill]))
8810 {
8811 case PACKET_OK:
8812 return 0;
8813 case PACKET_ERROR:
8814 return 1;
8815 case PACKET_UNKNOWN:
8816 return -1;
8817 default:
8818 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8819 }
82f73884
PA
8820}
8821
8822static void
7d85a9c0 8823extended_remote_kill (struct target_ops *ops)
82f73884
PA
8824{
8825 int res;
8826 int pid = ptid_get_pid (inferior_ptid);
8827 struct remote_state *rs = get_remote_state ();
8828
cbb8991c
DB
8829 /* If we're stopped while forking and we haven't followed yet, kill the
8830 child task. We need to do this before killing the parent task
8831 because if this is a vfork then the parent will be sleeping. */
8832 kill_new_fork_children (pid, rs);
8833
82f73884 8834 res = remote_vkill (pid, rs);
901f9912 8835 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
8836 {
8837 /* Don't try 'k' on a multi-process aware stub -- it has no way
8838 to specify the pid. */
8839
8840 putpkt ("k");
8841#if 0
8842 getpkt (&rs->buf, &rs->buf_size, 0);
8843 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8844 res = 1;
8845#else
8846 /* Don't wait for it to die. I'm not really sure it matters whether
8847 we do or not. For the existing stubs, kill is a noop. */
8848 res = 0;
8849#endif
8850 }
8851
8852 if (res != 0)
8853 error (_("Can't kill process"));
8854
82f73884
PA
8855 target_mourn_inferior ();
8856}
8857
c906108c 8858static void
20f796c9 8859remote_mourn (struct target_ops *target)
c906108c
SS
8860{
8861 unpush_target (target);
ce5ce7ed 8862
8a2492ee
PA
8863 /* remote_close takes care of doing most of the clean up. */
8864 generic_mourn_inferior ();
c906108c
SS
8865}
8866
2d717e4f 8867static void
20f796c9 8868extended_remote_mourn (struct target_ops *target)
2d717e4f
DJ
8869{
8870 struct remote_state *rs = get_remote_state ();
c906108c 8871
e24a49d8
PA
8872 /* In case we got here due to an error, but we're going to stay
8873 connected. */
8874 rs->waiting_for_stop_reply = 0;
8875
dc1981d7
PA
8876 /* If the current general thread belonged to the process we just
8877 detached from or has exited, the remote side current general
8878 thread becomes undefined. Considering a case like this:
8879
8880 - We just got here due to a detach.
8881 - The process that we're detaching from happens to immediately
8882 report a global breakpoint being hit in non-stop mode, in the
8883 same thread we had selected before.
8884 - GDB attaches to this process again.
8885 - This event happens to be the next event we handle.
8886
8887 GDB would consider that the current general thread didn't need to
8888 be set on the stub side (with Hg), since for all it knew,
8889 GENERAL_THREAD hadn't changed.
8890
8891 Notice that although in all-stop mode, the remote server always
8892 sets the current thread to the thread reporting the stop event,
8893 that doesn't happen in non-stop mode; in non-stop, the stub *must
8894 not* change the current thread when reporting a breakpoint hit,
8895 due to the decoupling of event reporting and event handling.
8896
8897 To keep things simple, we always invalidate our notion of the
8898 current thread. */
47f8a51d 8899 record_currthread (rs, minus_one_ptid);
dc1981d7 8900
2d717e4f
DJ
8901 /* Unlike "target remote", we do not want to unpush the target; then
8902 the next time the user says "run", we won't be connected. */
8903
48aa3c27
PA
8904 /* Call common code to mark the inferior as not running. */
8905 generic_mourn_inferior ();
8906
d729566a 8907 if (!have_inferiors ())
2d717e4f 8908 {
82f73884
PA
8909 if (!remote_multi_process_p (rs))
8910 {
8911 /* Check whether the target is running now - some remote stubs
8912 automatically restart after kill. */
8913 putpkt ("?");
8914 getpkt (&rs->buf, &rs->buf_size, 0);
8915
8916 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8917 {
3e43a32a
MS
8918 /* Assume that the target has been restarted. Set
8919 inferior_ptid so that bits of core GDB realizes
8920 there's something here, e.g., so that the user can
8921 say "kill" again. */
82f73884
PA
8922 inferior_ptid = magic_null_ptid;
8923 }
82f73884 8924 }
2d717e4f
DJ
8925 }
8926}
c906108c 8927
03583c20 8928static int
2bfc0540 8929extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8930{
4082afcc 8931 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8932}
8933
8934static void
8935extended_remote_disable_randomization (int val)
8936{
8937 struct remote_state *rs = get_remote_state ();
8938 char *reply;
8939
bba74b36
YQ
8940 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8941 val);
03583c20
UW
8942 putpkt (rs->buf);
8943 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8944 if (*reply == '\0')
8945 error (_("Target does not support QDisableRandomization."));
8946 if (strcmp (reply, "OK") != 0)
8947 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8948}
8949
2d717e4f
DJ
8950static int
8951extended_remote_run (char *args)
8952{
8953 struct remote_state *rs = get_remote_state ();
2d717e4f 8954 int len;
94585166 8955 const char *remote_exec_file = get_remote_exec_file ();
c906108c 8956
2d717e4f
DJ
8957 /* If the user has disabled vRun support, or we have detected that
8958 support is not available, do not try it. */
4082afcc 8959 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8960 return -1;
424163ea 8961
2d717e4f
DJ
8962 strcpy (rs->buf, "vRun;");
8963 len = strlen (rs->buf);
c906108c 8964
2d717e4f
DJ
8965 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8966 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8967 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8968 strlen (remote_exec_file));
2d717e4f 8969
d1a41061 8970 gdb_assert (args != NULL);
2d717e4f
DJ
8971 if (*args)
8972 {
8973 struct cleanup *back_to;
8974 int i;
8975 char **argv;
8976
d1a41061 8977 argv = gdb_buildargv (args);
6e366df1 8978 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
8979 for (i = 0; argv[i] != NULL; i++)
8980 {
8981 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8982 error (_("Argument list too long for run packet"));
8983 rs->buf[len++] = ';';
9f1b45b0
TT
8984 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8985 strlen (argv[i]));
2d717e4f
DJ
8986 }
8987 do_cleanups (back_to);
8988 }
8989
8990 rs->buf[len++] = '\0';
8991
8992 putpkt (rs->buf);
8993 getpkt (&rs->buf, &rs->buf_size, 0);
8994
4082afcc 8995 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 8996 {
4082afcc 8997 case PACKET_OK:
3405876a 8998 /* We have a wait response. All is well. */
2d717e4f 8999 return 0;
4082afcc
PA
9000 case PACKET_UNKNOWN:
9001 return -1;
9002 case PACKET_ERROR:
2d717e4f
DJ
9003 if (remote_exec_file[0] == '\0')
9004 error (_("Running the default executable on the remote target failed; "
9005 "try \"set remote exec-file\"?"));
9006 else
9007 error (_("Running \"%s\" on the remote target failed"),
9008 remote_exec_file);
4082afcc
PA
9009 default:
9010 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9011 }
c906108c
SS
9012}
9013
2d717e4f
DJ
9014/* In the extended protocol we want to be able to do things like
9015 "run" and have them basically work as expected. So we need
9016 a special create_inferior function. We support changing the
9017 executable file and the command line arguments, but not the
9018 environment. */
9019
43ff13b4 9020static void
77a19445
TT
9021extended_remote_create_inferior (struct target_ops *ops,
9022 char *exec_file, char *args,
9023 char **env, int from_tty)
43ff13b4 9024{
3405876a
PA
9025 int run_worked;
9026 char *stop_reply;
9027 struct remote_state *rs = get_remote_state ();
94585166 9028 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9029
43ff13b4 9030 /* If running asynchronously, register the target file descriptor
23860348 9031 with the event loop. */
75c99385 9032 if (target_can_async_p ())
6a3753b3 9033 target_async (1);
43ff13b4 9034
03583c20 9035 /* Disable address space randomization if requested (and supported). */
2bfc0540 9036 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9037 extended_remote_disable_randomization (disable_randomization);
9038
43ff13b4 9039 /* Now restart the remote server. */
3405876a
PA
9040 run_worked = extended_remote_run (args) != -1;
9041 if (!run_worked)
2d717e4f
DJ
9042 {
9043 /* vRun was not supported. Fail if we need it to do what the
9044 user requested. */
9045 if (remote_exec_file[0])
9046 error (_("Remote target does not support \"set remote exec-file\""));
9047 if (args[0])
9048 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9049
2d717e4f
DJ
9050 /* Fall back to "R". */
9051 extended_remote_restart ();
9052 }
424163ea 9053
6c95b8df
PA
9054 if (!have_inferiors ())
9055 {
9056 /* Clean up from the last time we ran, before we mark the target
9057 running again. This will mark breakpoints uninserted, and
9058 get_offsets may insert breakpoints. */
9059 init_thread_list ();
9060 init_wait_for_inferior ();
9061 }
45280a52 9062
3405876a
PA
9063 /* vRun's success return is a stop reply. */
9064 stop_reply = run_worked ? rs->buf : NULL;
9065 add_current_inferior_and_thread (stop_reply);
c0a2216e 9066
2d717e4f
DJ
9067 /* Get updated offsets, if the stub uses qOffsets. */
9068 get_offsets ();
2d717e4f 9069}
c906108c 9070\f
c5aa993b 9071
b775012e
LM
9072/* Given a location's target info BP_TGT and the packet buffer BUF, output
9073 the list of conditions (in agent expression bytecode format), if any, the
9074 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9075 started from BUF and ended at BUF_END. */
b775012e
LM
9076
9077static int
9078remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9079 struct bp_target_info *bp_tgt, char *buf,
9080 char *buf_end)
b775012e
LM
9081{
9082 struct agent_expr *aexpr = NULL;
9083 int i, ix;
9084 char *pkt;
9085 char *buf_start = buf;
9086
9087 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9088 return 0;
9089
9090 buf += strlen (buf);
bba74b36 9091 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9092 buf++;
9093
9094 /* Send conditions to the target and free the vector. */
9095 for (ix = 0;
9096 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9097 ix++)
9098 {
bba74b36 9099 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
9100 buf += strlen (buf);
9101 for (i = 0; i < aexpr->len; ++i)
9102 buf = pack_hex_byte (buf, aexpr->buf[i]);
9103 *buf = '\0';
9104 }
b775012e
LM
9105 return 0;
9106}
9107
d3ce09f5
SS
9108static void
9109remote_add_target_side_commands (struct gdbarch *gdbarch,
9110 struct bp_target_info *bp_tgt, char *buf)
9111{
9112 struct agent_expr *aexpr = NULL;
9113 int i, ix;
9114
9115 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9116 return;
9117
9118 buf += strlen (buf);
9119
9120 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9121 buf += strlen (buf);
9122
9123 /* Concatenate all the agent expressions that are commands into the
9124 cmds parameter. */
9125 for (ix = 0;
9126 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9127 ix++)
9128 {
9129 sprintf (buf, "X%x,", aexpr->len);
9130 buf += strlen (buf);
9131 for (i = 0; i < aexpr->len; ++i)
9132 buf = pack_hex_byte (buf, aexpr->buf[i]);
9133 *buf = '\0';
9134 }
d3ce09f5
SS
9135}
9136
8181d85f
DJ
9137/* Insert a breakpoint. On targets that have software breakpoint
9138 support, we ask the remote target to do the work; on targets
9139 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9140
9141static int
3db08215
MM
9142remote_insert_breakpoint (struct target_ops *ops,
9143 struct gdbarch *gdbarch,
a6d9a66e 9144 struct bp_target_info *bp_tgt)
c906108c 9145{
d471ea57
AC
9146 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9147 If it succeeds, then set the support to PACKET_ENABLE. If it
9148 fails, and the user has explicitly requested the Z support then
23860348 9149 report an error, otherwise, mark it disabled and go on. */
802188a7 9150
4082afcc 9151 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9152 {
0d5ed153 9153 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9154 struct remote_state *rs;
bba74b36 9155 char *p, *endbuf;
7c0f6dcc 9156 int bpsize;
b775012e 9157 struct condition_list *cond = NULL;
4fff2411 9158
28439a30
PA
9159 /* Make sure the remote is pointing at the right process, if
9160 necessary. */
9161 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9162 set_general_process ();
9163
a1dcb23a 9164 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
9165
9166 rs = get_remote_state ();
9167 p = rs->buf;
bba74b36 9168 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9169
96baa820
JM
9170 *(p++) = 'Z';
9171 *(p++) = '0';
9172 *(p++) = ',';
7c0f6dcc 9173 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9174 p += hexnumstr (p, addr);
bba74b36 9175 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 9176
efcc2da7 9177 if (remote_supports_cond_breakpoints (ops))
bba74b36 9178 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9179
78eff0ec 9180 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9181 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9182
6d820c5c
DJ
9183 putpkt (rs->buf);
9184 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9185
6d820c5c 9186 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9187 {
d471ea57
AC
9188 case PACKET_ERROR:
9189 return -1;
9190 case PACKET_OK:
7c0f6dcc
JL
9191 bp_tgt->placed_address = addr;
9192 bp_tgt->placed_size = bpsize;
d471ea57
AC
9193 return 0;
9194 case PACKET_UNKNOWN:
9195 break;
96baa820
JM
9196 }
9197 }
c906108c 9198
0000e5cc
PA
9199 /* If this breakpoint has target-side commands but this stub doesn't
9200 support Z0 packets, throw error. */
9201 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9202 throw_error (NOT_SUPPORTED_ERROR, _("\
9203Target doesn't support breakpoints that have target side commands."));
9204
3db08215 9205 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9206}
9207
9208static int
3db08215
MM
9209remote_remove_breakpoint (struct target_ops *ops,
9210 struct gdbarch *gdbarch,
a6d9a66e 9211 struct bp_target_info *bp_tgt)
c906108c 9212{
8181d85f 9213 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9214 struct remote_state *rs = get_remote_state ();
96baa820 9215
4082afcc 9216 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9217 {
6d820c5c 9218 char *p = rs->buf;
bba74b36 9219 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9220
28439a30
PA
9221 /* Make sure the remote is pointing at the right process, if
9222 necessary. */
9223 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9224 set_general_process ();
9225
96baa820
JM
9226 *(p++) = 'z';
9227 *(p++) = '0';
9228 *(p++) = ',';
9229
8181d85f
DJ
9230 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9231 p += hexnumstr (p, addr);
bba74b36 9232 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9233
6d820c5c
DJ
9234 putpkt (rs->buf);
9235 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9236
6d820c5c 9237 return (rs->buf[0] == 'E');
96baa820
JM
9238 }
9239
3db08215 9240 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9241}
9242
f486487f 9243static enum Z_packet_type
d471ea57
AC
9244watchpoint_to_Z_packet (int type)
9245{
9246 switch (type)
9247 {
9248 case hw_write:
bb858e6a 9249 return Z_PACKET_WRITE_WP;
d471ea57
AC
9250 break;
9251 case hw_read:
bb858e6a 9252 return Z_PACKET_READ_WP;
d471ea57
AC
9253 break;
9254 case hw_access:
bb858e6a 9255 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9256 break;
9257 default:
8e65ff28 9258 internal_error (__FILE__, __LINE__,
e2e0b3e5 9259 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9260 }
9261}
9262
3c3bea1c 9263static int
f486487f
SM
9264remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9265 enum target_hw_bp_type type, struct expression *cond)
96baa820 9266{
d01949b6 9267 struct remote_state *rs = get_remote_state ();
bba74b36 9268 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9269 char *p;
d471ea57 9270 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9271
4082afcc 9272 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9273 return 1;
802188a7 9274
28439a30
PA
9275 /* Make sure the remote is pointing at the right process, if
9276 necessary. */
9277 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9278 set_general_process ();
9279
bba74b36 9280 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9281 p = strchr (rs->buf, '\0');
96baa820
JM
9282 addr = remote_address_masked (addr);
9283 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9284 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9285
6d820c5c
DJ
9286 putpkt (rs->buf);
9287 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9288
6d820c5c 9289 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9290 {
9291 case PACKET_ERROR:
d471ea57 9292 return -1;
85d721b8
PA
9293 case PACKET_UNKNOWN:
9294 return 1;
d471ea57
AC
9295 case PACKET_OK:
9296 return 0;
9297 }
8e65ff28 9298 internal_error (__FILE__, __LINE__,
e2e0b3e5 9299 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9300}
9301
283002cf
MR
9302static int
9303remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9304 CORE_ADDR start, int length)
9305{
9306 CORE_ADDR diff = remote_address_masked (addr - start);
9307
9308 return diff < length;
9309}
9310
d471ea57 9311
3c3bea1c 9312static int
f486487f
SM
9313remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9314 enum target_hw_bp_type type, struct expression *cond)
96baa820 9315{
d01949b6 9316 struct remote_state *rs = get_remote_state ();
bba74b36 9317 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9318 char *p;
d471ea57
AC
9319 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9320
4082afcc 9321 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9322 return -1;
802188a7 9323
28439a30
PA
9324 /* Make sure the remote is pointing at the right process, if
9325 necessary. */
9326 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9327 set_general_process ();
9328
bba74b36 9329 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9330 p = strchr (rs->buf, '\0');
96baa820
JM
9331 addr = remote_address_masked (addr);
9332 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9333 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9334 putpkt (rs->buf);
9335 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9336
6d820c5c 9337 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9338 {
9339 case PACKET_ERROR:
9340 case PACKET_UNKNOWN:
9341 return -1;
9342 case PACKET_OK:
9343 return 0;
9344 }
8e65ff28 9345 internal_error (__FILE__, __LINE__,
e2e0b3e5 9346 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9347}
9348
3c3bea1c 9349
501eef12 9350int remote_hw_watchpoint_limit = -1;
480a3f21 9351int remote_hw_watchpoint_length_limit = -1;
501eef12 9352int remote_hw_breakpoint_limit = -1;
d471ea57 9353
480a3f21 9354static int
31568a15
TT
9355remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9356 CORE_ADDR addr, int len)
480a3f21
PW
9357{
9358 if (remote_hw_watchpoint_length_limit == 0)
9359 return 0;
9360 else if (remote_hw_watchpoint_length_limit < 0)
9361 return 1;
9362 else if (len <= remote_hw_watchpoint_length_limit)
9363 return 1;
9364 else
9365 return 0;
9366}
9367
b9362cc7 9368static int
5461485a 9369remote_check_watch_resources (struct target_ops *self,
f486487f 9370 enum bptype type, int cnt, int ot)
96baa820 9371{
3c3bea1c
GS
9372 if (type == bp_hardware_breakpoint)
9373 {
9374 if (remote_hw_breakpoint_limit == 0)
9375 return 0;
501eef12
AC
9376 else if (remote_hw_breakpoint_limit < 0)
9377 return 1;
3c3bea1c
GS
9378 else if (cnt <= remote_hw_breakpoint_limit)
9379 return 1;
9380 }
9381 else
9382 {
9383 if (remote_hw_watchpoint_limit == 0)
9384 return 0;
501eef12
AC
9385 else if (remote_hw_watchpoint_limit < 0)
9386 return 1;
3c3bea1c
GS
9387 else if (ot)
9388 return -1;
9389 else if (cnt <= remote_hw_watchpoint_limit)
9390 return 1;
9391 }
9392 return -1;
9393}
9394
f7e6eed5
PA
9395/* The to_stopped_by_sw_breakpoint method of target remote. */
9396
9397static int
9398remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9399{
799a2abe 9400 struct thread_info *thread = inferior_thread ();
f7e6eed5 9401
799a2abe
PA
9402 return (thread->priv != NULL
9403 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9404}
9405
9406/* The to_supports_stopped_by_sw_breakpoint method of target
9407 remote. */
9408
9409static int
9410remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9411{
9412 struct remote_state *rs = get_remote_state ();
9413
9414 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9415}
9416
9417/* The to_stopped_by_hw_breakpoint method of target remote. */
9418
9419static int
9420remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9421{
799a2abe 9422 struct thread_info *thread = inferior_thread ();
f7e6eed5 9423
799a2abe
PA
9424 return (thread->priv != NULL
9425 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9426}
9427
9428/* The to_supports_stopped_by_hw_breakpoint method of target
9429 remote. */
9430
9431static int
9432remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9433{
9434 struct remote_state *rs = get_remote_state ();
9435
9436 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9437}
9438
b9362cc7 9439static int
6a109b6b 9440remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9441{
799a2abe 9442 struct thread_info *thread = inferior_thread ();
ee154bee 9443
799a2abe
PA
9444 return (thread->priv != NULL
9445 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9446}
9447
4aa7a7f5
JJ
9448static int
9449remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9450{
799a2abe 9451 struct thread_info *thread = inferior_thread ();
a744cf53 9452
799a2abe
PA
9453 if (thread->priv != NULL
9454 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9455 {
799a2abe
PA
9456 *addr_p = thread->priv->watch_data_address;
9457 return 1;
4aa7a7f5
JJ
9458 }
9459
799a2abe 9460 return 0;
3c3bea1c
GS
9461}
9462
9463
9464static int
23a26771 9465remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9466 struct bp_target_info *bp_tgt)
3c3bea1c 9467{
0d5ed153 9468 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9469 struct remote_state *rs;
bba74b36 9470 char *p, *endbuf;
dd61ec5c 9471 char *message;
0d5ed153 9472 int bpsize;
802188a7 9473
c8189ed1 9474 /* The length field should be set to the size of a breakpoint
8181d85f 9475 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9476
0d5ed153 9477 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9478
4082afcc 9479 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9480 return -1;
2bc416ba 9481
28439a30
PA
9482 /* Make sure the remote is pointing at the right process, if
9483 necessary. */
9484 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9485 set_general_process ();
9486
4fff2411
JZ
9487 rs = get_remote_state ();
9488 p = rs->buf;
bba74b36 9489 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9490
96baa820
JM
9491 *(p++) = 'Z';
9492 *(p++) = '1';
9493 *(p++) = ',';
802188a7 9494
0d5ed153 9495 addr = remote_address_masked (addr);
96baa820 9496 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9497 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9498
efcc2da7 9499 if (remote_supports_cond_breakpoints (self))
bba74b36 9500 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9501
78eff0ec 9502 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9503 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9504
6d820c5c
DJ
9505 putpkt (rs->buf);
9506 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9507
6d820c5c 9508 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9509 {
9510 case PACKET_ERROR:
dd61ec5c
MW
9511 if (rs->buf[1] == '.')
9512 {
9513 message = strchr (rs->buf + 2, '.');
9514 if (message)
0316657e 9515 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9516 }
9517 return -1;
d471ea57
AC
9518 case PACKET_UNKNOWN:
9519 return -1;
9520 case PACKET_OK:
0d5ed153
MR
9521 bp_tgt->placed_address = addr;
9522 bp_tgt->placed_size = bpsize;
d471ea57
AC
9523 return 0;
9524 }
8e65ff28 9525 internal_error (__FILE__, __LINE__,
e2e0b3e5 9526 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9527}
9528
d471ea57 9529
802188a7 9530static int
a64dc96c 9531remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9532 struct bp_target_info *bp_tgt)
96baa820 9533{
8181d85f 9534 CORE_ADDR addr;
d01949b6 9535 struct remote_state *rs = get_remote_state ();
6d820c5c 9536 char *p = rs->buf;
bba74b36 9537 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9538
4082afcc 9539 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9540 return -1;
802188a7 9541
28439a30
PA
9542 /* Make sure the remote is pointing at the right process, if
9543 necessary. */
9544 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9545 set_general_process ();
9546
96baa820
JM
9547 *(p++) = 'z';
9548 *(p++) = '1';
9549 *(p++) = ',';
802188a7 9550
8181d85f 9551 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9552 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9553 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9554
6d820c5c
DJ
9555 putpkt (rs->buf);
9556 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9557
6d820c5c 9558 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9559 {
9560 case PACKET_ERROR:
9561 case PACKET_UNKNOWN:
9562 return -1;
9563 case PACKET_OK:
9564 return 0;
9565 }
8e65ff28 9566 internal_error (__FILE__, __LINE__,
e2e0b3e5 9567 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9568}
96baa820 9569
4a5e7a5b
PA
9570/* Verify memory using the "qCRC:" request. */
9571
9572static int
9573remote_verify_memory (struct target_ops *ops,
9574 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9575{
9576 struct remote_state *rs = get_remote_state ();
9577 unsigned long host_crc, target_crc;
9578 char *tmp;
9579
936d2992
PA
9580 /* It doesn't make sense to use qCRC if the remote target is
9581 connected but not running. */
9582 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9583 {
9584 enum packet_result result;
28439a30 9585
936d2992
PA
9586 /* Make sure the remote is pointing at the right process. */
9587 set_general_process ();
4a5e7a5b 9588
936d2992
PA
9589 /* FIXME: assumes lma can fit into long. */
9590 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9591 (long) lma, (long) size);
9592 putpkt (rs->buf);
4a5e7a5b 9593
936d2992
PA
9594 /* Be clever; compute the host_crc before waiting for target
9595 reply. */
9596 host_crc = xcrc32 (data, size, 0xffffffff);
9597
9598 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9599
936d2992
PA
9600 result = packet_ok (rs->buf,
9601 &remote_protocol_packets[PACKET_qCRC]);
9602 if (result == PACKET_ERROR)
9603 return -1;
9604 else if (result == PACKET_OK)
9605 {
9606 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9607 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9608
936d2992
PA
9609 return (host_crc == target_crc);
9610 }
9611 }
4a5e7a5b 9612
936d2992 9613 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9614}
9615
c906108c
SS
9616/* compare-sections command
9617
9618 With no arguments, compares each loadable section in the exec bfd
9619 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9620 Useful for verifying the image on the target against the exec file. */
e514a9d6 9621
c906108c 9622static void
fba45db2 9623compare_sections_command (char *args, int from_tty)
c906108c
SS
9624{
9625 asection *s;
c906108c 9626 struct cleanup *old_chain;
948f8e3d 9627 gdb_byte *sectdata;
ce359b09 9628 const char *sectname;
c906108c
SS
9629 bfd_size_type size;
9630 bfd_vma lma;
9631 int matched = 0;
9632 int mismatched = 0;
4a5e7a5b 9633 int res;
95cf3b38 9634 int read_only = 0;
c906108c
SS
9635
9636 if (!exec_bfd)
8a3fe4f8 9637 error (_("command cannot be used without an exec file"));
c906108c 9638
28439a30
PA
9639 /* Make sure the remote is pointing at the right process. */
9640 set_general_process ();
9641
95cf3b38
DT
9642 if (args != NULL && strcmp (args, "-r") == 0)
9643 {
9644 read_only = 1;
9645 args = NULL;
9646 }
9647
c5aa993b 9648 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9649 {
9650 if (!(s->flags & SEC_LOAD))
0df8b418 9651 continue; /* Skip non-loadable section. */
c906108c 9652
95cf3b38
DT
9653 if (read_only && (s->flags & SEC_READONLY) == 0)
9654 continue; /* Skip writeable sections */
9655
2c500098 9656 size = bfd_get_section_size (s);
c906108c 9657 if (size == 0)
0df8b418 9658 continue; /* Skip zero-length section. */
c906108c 9659
ce359b09 9660 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9661 if (args && strcmp (args, sectname) != 0)
0df8b418 9662 continue; /* Not the section selected by user. */
c906108c 9663
0df8b418 9664 matched = 1; /* Do this section. */
c906108c 9665 lma = s->lma;
c906108c 9666
224c3ddb 9667 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9668 old_chain = make_cleanup (xfree, sectdata);
c906108c 9669 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9670
4a5e7a5b
PA
9671 res = target_verify_memory (sectdata, lma, size);
9672
9673 if (res == -1)
5af949e3 9674 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9675 paddress (target_gdbarch (), lma),
9676 paddress (target_gdbarch (), lma + size));
c906108c 9677
5af949e3 9678 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9679 paddress (target_gdbarch (), lma),
9680 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9681 if (res)
c906108c
SS
9682 printf_filtered ("matched.\n");
9683 else
c5aa993b
JM
9684 {
9685 printf_filtered ("MIS-MATCHED!\n");
9686 mismatched++;
9687 }
c906108c
SS
9688
9689 do_cleanups (old_chain);
9690 }
9691 if (mismatched > 0)
936d2992 9692 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9693the loaded file\n"));
c906108c 9694 if (args && !matched)
a3f17187 9695 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9696}
9697
0e7f50da
UW
9698/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9699 into remote target. The number of bytes written to the remote
9700 target is returned, or -1 for error. */
9701
9b409511 9702static enum target_xfer_status
0e7f50da
UW
9703remote_write_qxfer (struct target_ops *ops, const char *object_name,
9704 const char *annex, const gdb_byte *writebuf,
9b409511 9705 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9706 struct packet_config *packet)
9707{
9708 int i, buf_len;
9709 ULONGEST n;
0e7f50da
UW
9710 struct remote_state *rs = get_remote_state ();
9711 int max_size = get_memory_write_packet_size ();
9712
9713 if (packet->support == PACKET_DISABLE)
2ed4b548 9714 return TARGET_XFER_E_IO;
0e7f50da
UW
9715
9716 /* Insert header. */
9717 i = snprintf (rs->buf, max_size,
9718 "qXfer:%s:write:%s:%s:",
9719 object_name, annex ? annex : "",
9720 phex_nz (offset, sizeof offset));
9721 max_size -= (i + 1);
9722
9723 /* Escape as much data as fits into rs->buf. */
9724 buf_len = remote_escape_output
124e13d9 9725 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9726
9727 if (putpkt_binary (rs->buf, i + buf_len) < 0
9728 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9729 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9730 return TARGET_XFER_E_IO;
0e7f50da
UW
9731
9732 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9733
9734 *xfered_len = n;
9735 return TARGET_XFER_OK;
0e7f50da
UW
9736}
9737
0876f84a
DJ
9738/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9739 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9740 number of bytes read is returned, or 0 for EOF, or -1 for error.
9741 The number of bytes read may be less than LEN without indicating an
9742 EOF. PACKET is checked and updated to indicate whether the remote
9743 target supports this object. */
9744
9b409511 9745static enum target_xfer_status
0876f84a
DJ
9746remote_read_qxfer (struct target_ops *ops, const char *object_name,
9747 const char *annex,
9748 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9749 ULONGEST *xfered_len,
0876f84a
DJ
9750 struct packet_config *packet)
9751{
0876f84a 9752 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9753 LONGEST i, n, packet_len;
9754
9755 if (packet->support == PACKET_DISABLE)
2ed4b548 9756 return TARGET_XFER_E_IO;
0876f84a
DJ
9757
9758 /* Check whether we've cached an end-of-object packet that matches
9759 this request. */
8e88304f 9760 if (rs->finished_object)
0876f84a 9761 {
8e88304f
TT
9762 if (strcmp (object_name, rs->finished_object) == 0
9763 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9764 && offset == rs->finished_offset)
9b409511
YQ
9765 return TARGET_XFER_EOF;
9766
0876f84a
DJ
9767
9768 /* Otherwise, we're now reading something different. Discard
9769 the cache. */
8e88304f
TT
9770 xfree (rs->finished_object);
9771 xfree (rs->finished_annex);
9772 rs->finished_object = NULL;
9773 rs->finished_annex = NULL;
0876f84a
DJ
9774 }
9775
9776 /* Request only enough to fit in a single packet. The actual data
9777 may not, since we don't know how much of it will need to be escaped;
9778 the target is free to respond with slightly less data. We subtract
9779 five to account for the response type and the protocol frame. */
9780 n = min (get_remote_packet_size () - 5, len);
9781 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9782 object_name, annex ? annex : "",
9783 phex_nz (offset, sizeof offset),
9784 phex_nz (n, sizeof n));
9785 i = putpkt (rs->buf);
9786 if (i < 0)
2ed4b548 9787 return TARGET_XFER_E_IO;
0876f84a
DJ
9788
9789 rs->buf[0] = '\0';
9790 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9791 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9792 return TARGET_XFER_E_IO;
0876f84a
DJ
9793
9794 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9795 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9796
9797 /* 'm' means there is (or at least might be) more data after this
9798 batch. That does not make sense unless there's at least one byte
9799 of data in this reply. */
9800 if (rs->buf[0] == 'm' && packet_len == 1)
9801 error (_("Remote qXfer reply contained no data."));
9802
9803 /* Got some data. */
bc20a4af
PA
9804 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9805 packet_len - 1, readbuf, n);
0876f84a
DJ
9806
9807 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9808 or possibly empty. If we have the final block of a non-empty
9809 object, record this fact to bypass a subsequent partial read. */
9810 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9811 {
8e88304f
TT
9812 rs->finished_object = xstrdup (object_name);
9813 rs->finished_annex = xstrdup (annex ? annex : "");
9814 rs->finished_offset = offset + i;
0876f84a
DJ
9815 }
9816
9b409511
YQ
9817 if (i == 0)
9818 return TARGET_XFER_EOF;
9819 else
9820 {
9821 *xfered_len = i;
9822 return TARGET_XFER_OK;
9823 }
0876f84a
DJ
9824}
9825
9b409511 9826static enum target_xfer_status
4b8a223f 9827remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9828 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9829 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9830 ULONGEST *xfered_len)
c906108c 9831{
82f73884 9832 struct remote_state *rs;
c906108c 9833 int i;
6d820c5c 9834 char *p2;
1e3ff5ad 9835 char query_type;
124e13d9 9836 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9837
e6e4e701 9838 set_remote_traceframe ();
82f73884
PA
9839 set_general_thread (inferior_ptid);
9840
9841 rs = get_remote_state ();
9842
b2182ed2 9843 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9844 if (object == TARGET_OBJECT_MEMORY)
9845 {
2d717e4f
DJ
9846 /* If the remote target is connected but not running, we should
9847 pass this request down to a lower stratum (e.g. the executable
9848 file). */
9849 if (!target_has_execution)
9b409511 9850 return TARGET_XFER_EOF;
2d717e4f 9851
21e3b9b9 9852 if (writebuf != NULL)
124e13d9
SM
9853 return remote_write_bytes (offset, writebuf, len, unit_size,
9854 xfered_len);
21e3b9b9 9855 else
124e13d9
SM
9856 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9857 xfered_len);
21e3b9b9
DJ
9858 }
9859
0df8b418 9860 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9861 if (object == TARGET_OBJECT_SPU)
9862 {
9863 if (readbuf)
9864 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9865 xfered_len, &remote_protocol_packets
9866 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9867 else
9868 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9869 xfered_len, &remote_protocol_packets
9870 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9871 }
9872
4aa995e1
PA
9873 /* Handle extra signal info using qxfer packets. */
9874 if (object == TARGET_OBJECT_SIGNAL_INFO)
9875 {
9876 if (readbuf)
9877 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 9878 xfered_len, &remote_protocol_packets
4aa995e1
PA
9879 [PACKET_qXfer_siginfo_read]);
9880 else
3e43a32a 9881 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 9882 writebuf, offset, len, xfered_len,
4aa995e1
PA
9883 &remote_protocol_packets
9884 [PACKET_qXfer_siginfo_write]);
9885 }
9886
0fb4aa4b
PA
9887 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9888 {
9889 if (readbuf)
3e43a32a 9890 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 9891 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
9892 &remote_protocol_packets
9893 [PACKET_qXfer_statictrace_read]);
9894 else
2ed4b548 9895 return TARGET_XFER_E_IO;
0fb4aa4b
PA
9896 }
9897
a76d924d
DJ
9898 /* Only handle flash writes. */
9899 if (writebuf != NULL)
9900 {
9901 LONGEST xfered;
9902
9903 switch (object)
9904 {
9905 case TARGET_OBJECT_FLASH:
9b409511
YQ
9906 return remote_flash_write (ops, offset, len, xfered_len,
9907 writebuf);
a76d924d
DJ
9908
9909 default:
2ed4b548 9910 return TARGET_XFER_E_IO;
a76d924d
DJ
9911 }
9912 }
4b8a223f 9913
1e3ff5ad
AC
9914 /* Map pre-existing objects onto letters. DO NOT do this for new
9915 objects!!! Instead specify new query packets. */
9916 switch (object)
c906108c 9917 {
1e3ff5ad
AC
9918 case TARGET_OBJECT_AVR:
9919 query_type = 'R';
9920 break;
802188a7
RM
9921
9922 case TARGET_OBJECT_AUXV:
0876f84a
DJ
9923 gdb_assert (annex == NULL);
9924 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9925 xfered_len,
0876f84a 9926 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9927
23181151
DJ
9928 case TARGET_OBJECT_AVAILABLE_FEATURES:
9929 return remote_read_qxfer
9b409511 9930 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9931 &remote_protocol_packets[PACKET_qXfer_features]);
9932
cfa9d6d9
DJ
9933 case TARGET_OBJECT_LIBRARIES:
9934 return remote_read_qxfer
9b409511 9935 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9936 &remote_protocol_packets[PACKET_qXfer_libraries]);
9937
2268b414
JK
9938 case TARGET_OBJECT_LIBRARIES_SVR4:
9939 return remote_read_qxfer
9b409511 9940 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9941 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9942
fd79ecee
DJ
9943 case TARGET_OBJECT_MEMORY_MAP:
9944 gdb_assert (annex == NULL);
9945 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9946 xfered_len,
fd79ecee
DJ
9947 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9948
07e059b5
VP
9949 case TARGET_OBJECT_OSDATA:
9950 /* Should only get here if we're connected. */
5d93a237 9951 gdb_assert (rs->remote_desc);
07e059b5 9952 return remote_read_qxfer
9b409511 9953 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9954 &remote_protocol_packets[PACKET_qXfer_osdata]);
9955
dc146f7c
VP
9956 case TARGET_OBJECT_THREADS:
9957 gdb_assert (annex == NULL);
9958 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9959 xfered_len,
dc146f7c
VP
9960 &remote_protocol_packets[PACKET_qXfer_threads]);
9961
b3b9301e
PA
9962 case TARGET_OBJECT_TRACEFRAME_INFO:
9963 gdb_assert (annex == NULL);
9964 return remote_read_qxfer
9b409511 9965 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9966 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9967
9968 case TARGET_OBJECT_FDPIC:
9969 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9970 xfered_len,
78d85199 9971 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9972
9973 case TARGET_OBJECT_OPENVMS_UIB:
9974 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 9975 xfered_len,
169081d0
TG
9976 &remote_protocol_packets[PACKET_qXfer_uib]);
9977
9accd112
MM
9978 case TARGET_OBJECT_BTRACE:
9979 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 9980 xfered_len,
9accd112
MM
9981 &remote_protocol_packets[PACKET_qXfer_btrace]);
9982
f4abbc16
MM
9983 case TARGET_OBJECT_BTRACE_CONF:
9984 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9985 len, xfered_len,
9986 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9987
c78fa86a
GB
9988 case TARGET_OBJECT_EXEC_FILE:
9989 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9990 len, xfered_len,
9991 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9992
1e3ff5ad 9993 default:
2ed4b548 9994 return TARGET_XFER_E_IO;
c906108c
SS
9995 }
9996
0df8b418 9997 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 9998 large enough let the caller deal with it. */
ea9c271d 9999 if (len < get_remote_packet_size ())
2ed4b548 10000 return TARGET_XFER_E_IO;
ea9c271d 10001 len = get_remote_packet_size ();
1e3ff5ad 10002
23860348 10003 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10004 if (!rs->remote_desc)
8a3fe4f8 10005 error (_("remote query is only available after target open"));
c906108c 10006
1e3ff5ad 10007 gdb_assert (annex != NULL);
4b8a223f 10008 gdb_assert (readbuf != NULL);
c906108c 10009
6d820c5c 10010 p2 = rs->buf;
c906108c
SS
10011 *p2++ = 'q';
10012 *p2++ = query_type;
10013
23860348
MS
10014 /* We used one buffer char for the remote protocol q command and
10015 another for the query type. As the remote protocol encapsulation
10016 uses 4 chars plus one extra in case we are debugging
10017 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10018 string. */
c906108c 10019 i = 0;
ea9c271d 10020 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10021 {
1e3ff5ad
AC
10022 /* Bad caller may have sent forbidden characters. */
10023 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10024 *p2++ = annex[i];
c906108c
SS
10025 i++;
10026 }
1e3ff5ad
AC
10027 *p2 = '\0';
10028 gdb_assert (annex[i] == '\0');
c906108c 10029
6d820c5c 10030 i = putpkt (rs->buf);
c5aa993b 10031 if (i < 0)
2ed4b548 10032 return TARGET_XFER_E_IO;
c906108c 10033
6d820c5c
DJ
10034 getpkt (&rs->buf, &rs->buf_size, 0);
10035 strcpy ((char *) readbuf, rs->buf);
c906108c 10036
9b409511
YQ
10037 *xfered_len = strlen ((char *) readbuf);
10038 return TARGET_XFER_OK;
c906108c
SS
10039}
10040
08388c79
DE
10041static int
10042remote_search_memory (struct target_ops* ops,
10043 CORE_ADDR start_addr, ULONGEST search_space_len,
10044 const gdb_byte *pattern, ULONGEST pattern_len,
10045 CORE_ADDR *found_addrp)
10046{
f5656ead 10047 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10048 struct remote_state *rs = get_remote_state ();
10049 int max_size = get_memory_write_packet_size ();
10050 struct packet_config *packet =
10051 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10052 /* Number of packet bytes used to encode the pattern;
10053 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10054 int escaped_pattern_len;
0df8b418 10055 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10056 int used_pattern_len;
10057 int i;
10058 int found;
10059 ULONGEST found_addr;
10060
10061 /* Don't go to the target if we don't have to.
10062 This is done before checking packet->support to avoid the possibility that
10063 a success for this edge case means the facility works in general. */
10064 if (pattern_len > search_space_len)
10065 return 0;
10066 if (pattern_len == 0)
10067 {
10068 *found_addrp = start_addr;
10069 return 1;
10070 }
10071
10072 /* If we already know the packet isn't supported, fall back to the simple
10073 way of searching memory. */
10074
4082afcc 10075 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10076 {
10077 /* Target doesn't provided special support, fall back and use the
10078 standard support (copy memory and do the search here). */
10079 return simple_search_memory (ops, start_addr, search_space_len,
10080 pattern, pattern_len, found_addrp);
10081 }
10082
28439a30
PA
10083 /* Make sure the remote is pointing at the right process. */
10084 set_general_process ();
10085
08388c79
DE
10086 /* Insert header. */
10087 i = snprintf (rs->buf, max_size,
10088 "qSearch:memory:%s;%s;",
5af949e3 10089 phex_nz (start_addr, addr_size),
08388c79
DE
10090 phex_nz (search_space_len, sizeof (search_space_len)));
10091 max_size -= (i + 1);
10092
10093 /* Escape as much data as fits into rs->buf. */
10094 escaped_pattern_len =
124e13d9 10095 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10096 &used_pattern_len, max_size);
10097
10098 /* Bail if the pattern is too large. */
10099 if (used_pattern_len != pattern_len)
9b20d036 10100 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10101
10102 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10103 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10104 || packet_ok (rs->buf, packet) != PACKET_OK)
10105 {
10106 /* The request may not have worked because the command is not
10107 supported. If so, fall back to the simple way. */
10108 if (packet->support == PACKET_DISABLE)
10109 {
10110 return simple_search_memory (ops, start_addr, search_space_len,
10111 pattern, pattern_len, found_addrp);
10112 }
10113 return -1;
10114 }
10115
10116 if (rs->buf[0] == '0')
10117 found = 0;
10118 else if (rs->buf[0] == '1')
10119 {
10120 found = 1;
10121 if (rs->buf[1] != ',')
10e0fa18 10122 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10123 unpack_varlen_hex (rs->buf + 2, &found_addr);
10124 *found_addrp = found_addr;
10125 }
10126 else
10e0fa18 10127 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10128
10129 return found;
10130}
10131
96baa820 10132static void
a30bf1f1 10133remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10134 struct ui_file *outbuf)
96baa820 10135{
d01949b6 10136 struct remote_state *rs = get_remote_state ();
2e9f7625 10137 char *p = rs->buf;
96baa820 10138
5d93a237 10139 if (!rs->remote_desc)
8a3fe4f8 10140 error (_("remote rcmd is only available after target open"));
96baa820 10141
23860348 10142 /* Send a NULL command across as an empty command. */
7be570e7
JM
10143 if (command == NULL)
10144 command = "";
10145
23860348 10146 /* The query prefix. */
2e9f7625
DJ
10147 strcpy (rs->buf, "qRcmd,");
10148 p = strchr (rs->buf, '\0');
96baa820 10149
3e43a32a
MS
10150 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10151 > get_remote_packet_size ())
8a3fe4f8 10152 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10153
23860348 10154 /* Encode the actual command. */
a30bf1f1 10155 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10156
6d820c5c 10157 if (putpkt (rs->buf) < 0)
8a3fe4f8 10158 error (_("Communication problem with target."));
96baa820
JM
10159
10160 /* get/display the response */
10161 while (1)
10162 {
2e9f7625
DJ
10163 char *buf;
10164
00bf0b85 10165 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10166 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10167 rs->buf[0] = '\0';
5b37825d
PW
10168 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10169 {
10170 /* Timeout. Continue to (try to) read responses.
10171 This is better than stopping with an error, assuming the stub
10172 is still executing the (long) monitor command.
10173 If needed, the user can interrupt gdb using C-c, obtaining
10174 an effect similar to stop on timeout. */
10175 continue;
10176 }
2e9f7625 10177 buf = rs->buf;
96baa820 10178 if (buf[0] == '\0')
8a3fe4f8 10179 error (_("Target does not support this command."));
96baa820
JM
10180 if (buf[0] == 'O' && buf[1] != 'K')
10181 {
23860348 10182 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10183 continue;
10184 }
10185 if (strcmp (buf, "OK") == 0)
10186 break;
7be570e7
JM
10187 if (strlen (buf) == 3 && buf[0] == 'E'
10188 && isdigit (buf[1]) && isdigit (buf[2]))
10189 {
8a3fe4f8 10190 error (_("Protocol error with Rcmd"));
7be570e7 10191 }
96baa820
JM
10192 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10193 {
10194 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10195
96baa820
JM
10196 fputc_unfiltered (c, outbuf);
10197 }
10198 break;
10199 }
10200}
10201
fd79ecee
DJ
10202static VEC(mem_region_s) *
10203remote_memory_map (struct target_ops *ops)
10204{
10205 VEC(mem_region_s) *result = NULL;
10206 char *text = target_read_stralloc (&current_target,
10207 TARGET_OBJECT_MEMORY_MAP, NULL);
10208
10209 if (text)
10210 {
10211 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10212
fd79ecee
DJ
10213 result = parse_memory_map (text);
10214 do_cleanups (back_to);
10215 }
10216
10217 return result;
10218}
10219
c906108c 10220static void
fba45db2 10221packet_command (char *args, int from_tty)
c906108c 10222{
d01949b6 10223 struct remote_state *rs = get_remote_state ();
c906108c 10224
5d93a237 10225 if (!rs->remote_desc)
8a3fe4f8 10226 error (_("command can only be used with remote target"));
c906108c 10227
c5aa993b 10228 if (!args)
8a3fe4f8 10229 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10230
10231 puts_filtered ("sending: ");
10232 print_packet (args);
10233 puts_filtered ("\n");
10234 putpkt (args);
10235
6d820c5c 10236 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10237 puts_filtered ("received: ");
6d820c5c 10238 print_packet (rs->buf);
c906108c
SS
10239 puts_filtered ("\n");
10240}
10241
10242#if 0
23860348 10243/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10244
a14ed312 10245static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10246
a14ed312 10247static void threadset_test_cmd (char *cmd, int tty);
c906108c 10248
a14ed312 10249static void threadalive_test (char *cmd, int tty);
c906108c 10250
a14ed312 10251static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10252
23860348 10253int get_and_display_threadinfo (threadref *ref);
c906108c 10254
a14ed312 10255static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10256
23860348 10257static int thread_display_step (threadref *ref, void *context);
c906108c 10258
a14ed312 10259static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10260
a14ed312 10261static void init_remote_threadtests (void);
c906108c 10262
23860348 10263#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10264
10265static void
fba45db2 10266threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10267{
10268 int sample_thread = SAMPLE_THREAD;
10269
a3f17187 10270 printf_filtered (_("Remote threadset test\n"));
79d7f229 10271 set_general_thread (sample_thread);
c906108c
SS
10272}
10273
10274
10275static void
fba45db2 10276threadalive_test (char *cmd, int tty)
c906108c
SS
10277{
10278 int sample_thread = SAMPLE_THREAD;
79d7f229 10279 int pid = ptid_get_pid (inferior_ptid);
ba348170 10280 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10281
79d7f229 10282 if (remote_thread_alive (ptid))
c906108c
SS
10283 printf_filtered ("PASS: Thread alive test\n");
10284 else
10285 printf_filtered ("FAIL: Thread alive test\n");
10286}
10287
23860348 10288void output_threadid (char *title, threadref *ref);
c906108c
SS
10289
10290void
fba45db2 10291output_threadid (char *title, threadref *ref)
c906108c
SS
10292{
10293 char hexid[20];
10294
23860348 10295 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10296 hexid[16] = 0;
10297 printf_filtered ("%s %s\n", title, (&hexid[0]));
10298}
10299
10300static void
fba45db2 10301threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10302{
10303 int startflag = 1;
10304 threadref nextthread;
10305 int done, result_count;
10306 threadref threadlist[3];
10307
10308 printf_filtered ("Remote Threadlist test\n");
10309 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10310 &result_count, &threadlist[0]))
10311 printf_filtered ("FAIL: threadlist test\n");
10312 else
10313 {
10314 threadref *scan = threadlist;
10315 threadref *limit = scan + result_count;
10316
10317 while (scan < limit)
10318 output_threadid (" thread ", scan++);
10319 }
10320}
10321
10322void
fba45db2 10323display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10324{
10325 output_threadid ("Threadid: ", &info->threadid);
10326 printf_filtered ("Name: %s\n ", info->shortname);
10327 printf_filtered ("State: %s\n", info->display);
10328 printf_filtered ("other: %s\n\n", info->more_display);
10329}
10330
10331int
fba45db2 10332get_and_display_threadinfo (threadref *ref)
c906108c
SS
10333{
10334 int result;
10335 int set;
10336 struct gdb_ext_thread_info threadinfo;
10337
10338 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10339 | TAG_MOREDISPLAY | TAG_DISPLAY;
10340 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10341 display_thread_info (&threadinfo);
10342 return result;
10343}
10344
10345static void
fba45db2 10346threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10347{
10348 int athread = SAMPLE_THREAD;
10349 threadref thread;
10350 int set;
10351
10352 int_to_threadref (&thread, athread);
10353 printf_filtered ("Remote Threadinfo test\n");
10354 if (!get_and_display_threadinfo (&thread))
10355 printf_filtered ("FAIL cannot get thread info\n");
10356}
10357
10358static int
fba45db2 10359thread_display_step (threadref *ref, void *context)
c906108c
SS
10360{
10361 /* output_threadid(" threadstep ",ref); *//* simple test */
10362 return get_and_display_threadinfo (ref);
10363}
10364
10365static void
fba45db2 10366threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10367{
10368 printf_filtered ("Remote Threadlist update test\n");
10369 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10370}
10371
10372static void
10373init_remote_threadtests (void)
10374{
3e43a32a
MS
10375 add_com ("tlist", class_obscure, threadlist_test_cmd,
10376 _("Fetch and print the remote list of "
10377 "thread identifiers, one pkt only"));
c906108c 10378 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10379 _("Fetch and display info about one thread"));
c906108c 10380 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10381 _("Test setting to a different thread"));
c906108c 10382 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10383 _("Iterate through updating all remote thread info"));
c906108c 10384 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10385 _(" Remote thread alive test "));
c906108c
SS
10386}
10387
10388#endif /* 0 */
10389
f3fb8c85
MS
10390/* Convert a thread ID to a string. Returns the string in a static
10391 buffer. */
10392
10393static char *
117de6a9 10394remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10395{
79d7f229 10396 static char buf[64];
82f73884 10397 struct remote_state *rs = get_remote_state ();
f3fb8c85 10398
7cee1e54
PA
10399 if (ptid_equal (ptid, null_ptid))
10400 return normal_pid_to_str (ptid);
10401 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10402 {
10403 /* Printing an inferior target id. */
10404
10405 /* When multi-process extensions are off, there's no way in the
10406 remote protocol to know the remote process id, if there's any
10407 at all. There's one exception --- when we're connected with
10408 target extended-remote, and we manually attached to a process
10409 with "attach PID". We don't record anywhere a flag that
10410 allows us to distinguish that case from the case of
10411 connecting with extended-remote and the stub already being
10412 attached to a process, and reporting yes to qAttached, hence
10413 no smart special casing here. */
10414 if (!remote_multi_process_p (rs))
10415 {
10416 xsnprintf (buf, sizeof buf, "Remote target");
10417 return buf;
10418 }
10419
10420 return normal_pid_to_str (ptid);
82f73884 10421 }
ecd0ada5 10422 else
79d7f229 10423 {
ecd0ada5
PA
10424 if (ptid_equal (magic_null_ptid, ptid))
10425 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 10426 else if (rs->extended && remote_multi_process_p (rs))
de0d863e
DB
10427 if (ptid_get_lwp (ptid) == 0)
10428 return normal_pid_to_str (ptid);
10429 else
10430 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10431 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10432 else
10433 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10434 ptid_get_lwp (ptid));
79d7f229
PA
10435 return buf;
10436 }
f3fb8c85
MS
10437}
10438
38691318
KB
10439/* Get the address of the thread local variable in OBJFILE which is
10440 stored at OFFSET within the thread local storage for thread PTID. */
10441
10442static CORE_ADDR
117de6a9
PA
10443remote_get_thread_local_address (struct target_ops *ops,
10444 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10445{
4082afcc 10446 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10447 {
10448 struct remote_state *rs = get_remote_state ();
6d820c5c 10449 char *p = rs->buf;
82f73884 10450 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10451 enum packet_result result;
38691318
KB
10452
10453 strcpy (p, "qGetTLSAddr:");
10454 p += strlen (p);
82f73884 10455 p = write_ptid (p, endp, ptid);
38691318
KB
10456 *p++ = ',';
10457 p += hexnumstr (p, offset);
10458 *p++ = ',';
10459 p += hexnumstr (p, lm);
10460 *p++ = '\0';
10461
6d820c5c
DJ
10462 putpkt (rs->buf);
10463 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10464 result = packet_ok (rs->buf,
10465 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10466 if (result == PACKET_OK)
38691318
KB
10467 {
10468 ULONGEST result;
10469
6d820c5c 10470 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10471 return result;
10472 }
571dd617 10473 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10474 throw_error (TLS_GENERIC_ERROR,
10475 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10476 else
109c3e39
AC
10477 throw_error (TLS_GENERIC_ERROR,
10478 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10479 }
10480 else
109c3e39
AC
10481 throw_error (TLS_GENERIC_ERROR,
10482 _("TLS not supported or disabled on this target"));
38691318
KB
10483 /* Not reached. */
10484 return 0;
10485}
10486
711e434b
PM
10487/* Provide thread local base, i.e. Thread Information Block address.
10488 Returns 1 if ptid is found and thread_local_base is non zero. */
10489
70221824 10490static int
bd7ae0f5 10491remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10492{
4082afcc 10493 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10494 {
10495 struct remote_state *rs = get_remote_state ();
10496 char *p = rs->buf;
10497 char *endp = rs->buf + get_remote_packet_size ();
10498 enum packet_result result;
10499
10500 strcpy (p, "qGetTIBAddr:");
10501 p += strlen (p);
10502 p = write_ptid (p, endp, ptid);
10503 *p++ = '\0';
10504
10505 putpkt (rs->buf);
10506 getpkt (&rs->buf, &rs->buf_size, 0);
10507 result = packet_ok (rs->buf,
10508 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10509 if (result == PACKET_OK)
10510 {
10511 ULONGEST result;
10512
10513 unpack_varlen_hex (rs->buf, &result);
10514 if (addr)
10515 *addr = (CORE_ADDR) result;
10516 return 1;
10517 }
10518 else if (result == PACKET_UNKNOWN)
10519 error (_("Remote target doesn't support qGetTIBAddr packet"));
10520 else
10521 error (_("Remote target failed to process qGetTIBAddr request"));
10522 }
10523 else
10524 error (_("qGetTIBAddr not supported or disabled on this target"));
10525 /* Not reached. */
10526 return 0;
10527}
10528
29709017
DJ
10529/* Support for inferring a target description based on the current
10530 architecture and the size of a 'g' packet. While the 'g' packet
10531 can have any size (since optional registers can be left off the
10532 end), some sizes are easily recognizable given knowledge of the
10533 approximate architecture. */
10534
10535struct remote_g_packet_guess
10536{
10537 int bytes;
10538 const struct target_desc *tdesc;
10539};
10540typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10541DEF_VEC_O(remote_g_packet_guess_s);
10542
10543struct remote_g_packet_data
10544{
10545 VEC(remote_g_packet_guess_s) *guesses;
10546};
10547
10548static struct gdbarch_data *remote_g_packet_data_handle;
10549
10550static void *
10551remote_g_packet_data_init (struct obstack *obstack)
10552{
10553 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10554}
10555
10556void
10557register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10558 const struct target_desc *tdesc)
10559{
10560 struct remote_g_packet_data *data
19ba03f4
SM
10561 = ((struct remote_g_packet_data *)
10562 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10563 struct remote_g_packet_guess new_guess, *guess;
10564 int ix;
10565
10566 gdb_assert (tdesc != NULL);
10567
10568 for (ix = 0;
10569 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10570 ix++)
10571 if (guess->bytes == bytes)
10572 internal_error (__FILE__, __LINE__,
9b20d036 10573 _("Duplicate g packet description added for size %d"),
29709017
DJ
10574 bytes);
10575
10576 new_guess.bytes = bytes;
10577 new_guess.tdesc = tdesc;
10578 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10579}
10580
d962ef82
DJ
10581/* Return 1 if remote_read_description would do anything on this target
10582 and architecture, 0 otherwise. */
10583
10584static int
10585remote_read_description_p (struct target_ops *target)
10586{
10587 struct remote_g_packet_data *data
19ba03f4
SM
10588 = ((struct remote_g_packet_data *)
10589 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10590
10591 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10592 return 1;
10593
10594 return 0;
10595}
10596
29709017
DJ
10597static const struct target_desc *
10598remote_read_description (struct target_ops *target)
10599{
10600 struct remote_g_packet_data *data
19ba03f4
SM
10601 = ((struct remote_g_packet_data *)
10602 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10603
d962ef82
DJ
10604 /* Do not try this during initial connection, when we do not know
10605 whether there is a running but stopped thread. */
10606 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10607 return target->beneath->to_read_description (target->beneath);
d962ef82 10608
29709017
DJ
10609 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10610 {
10611 struct remote_g_packet_guess *guess;
10612 int ix;
10613 int bytes = send_g_packet ();
10614
10615 for (ix = 0;
10616 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10617 ix++)
10618 if (guess->bytes == bytes)
10619 return guess->tdesc;
10620
10621 /* We discard the g packet. A minor optimization would be to
10622 hold on to it, and fill the register cache once we have selected
10623 an architecture, but it's too tricky to do safely. */
10624 }
10625
2117c711 10626 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10627}
10628
a6b151f1
DJ
10629/* Remote file transfer support. This is host-initiated I/O, not
10630 target-initiated; for target-initiated, see remote-fileio.c. */
10631
10632/* If *LEFT is at least the length of STRING, copy STRING to
10633 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10634 decrease *LEFT. Otherwise raise an error. */
10635
10636static void
10637remote_buffer_add_string (char **buffer, int *left, char *string)
10638{
10639 int len = strlen (string);
10640
10641 if (len > *left)
10642 error (_("Packet too long for target."));
10643
10644 memcpy (*buffer, string, len);
10645 *buffer += len;
10646 *left -= len;
10647
10648 /* NUL-terminate the buffer as a convenience, if there is
10649 room. */
10650 if (*left)
10651 **buffer = '\0';
10652}
10653
10654/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10655 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10656 decrease *LEFT. Otherwise raise an error. */
10657
10658static void
10659remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10660 int len)
10661{
10662 if (2 * len > *left)
10663 error (_("Packet too long for target."));
10664
10665 bin2hex (bytes, *buffer, len);
10666 *buffer += 2 * len;
10667 *left -= 2 * len;
10668
10669 /* NUL-terminate the buffer as a convenience, if there is
10670 room. */
10671 if (*left)
10672 **buffer = '\0';
10673}
10674
10675/* If *LEFT is large enough, convert VALUE to hex and add it to
10676 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10677 decrease *LEFT. Otherwise raise an error. */
10678
10679static void
10680remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10681{
10682 int len = hexnumlen (value);
10683
10684 if (len > *left)
10685 error (_("Packet too long for target."));
10686
10687 hexnumstr (*buffer, value);
10688 *buffer += len;
10689 *left -= len;
10690
10691 /* NUL-terminate the buffer as a convenience, if there is
10692 room. */
10693 if (*left)
10694 **buffer = '\0';
10695}
10696
10697/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10698 value, *REMOTE_ERRNO to the remote error number or zero if none
10699 was included, and *ATTACHMENT to point to the start of the annex
10700 if any. The length of the packet isn't needed here; there may
10701 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10702
10703 Return 0 if the packet could be parsed, -1 if it could not. If
10704 -1 is returned, the other variables may not be initialized. */
10705
10706static int
10707remote_hostio_parse_result (char *buffer, int *retcode,
10708 int *remote_errno, char **attachment)
10709{
10710 char *p, *p2;
10711
10712 *remote_errno = 0;
10713 *attachment = NULL;
10714
10715 if (buffer[0] != 'F')
10716 return -1;
10717
10718 errno = 0;
10719 *retcode = strtol (&buffer[1], &p, 16);
10720 if (errno != 0 || p == &buffer[1])
10721 return -1;
10722
10723 /* Check for ",errno". */
10724 if (*p == ',')
10725 {
10726 errno = 0;
10727 *remote_errno = strtol (p + 1, &p2, 16);
10728 if (errno != 0 || p + 1 == p2)
10729 return -1;
10730 p = p2;
10731 }
10732
10733 /* Check for ";attachment". If there is no attachment, the
10734 packet should end here. */
10735 if (*p == ';')
10736 {
10737 *attachment = p + 1;
10738 return 0;
10739 }
10740 else if (*p == '\0')
10741 return 0;
10742 else
10743 return -1;
10744}
10745
10746/* Send a prepared I/O packet to the target and read its response.
10747 The prepared packet is in the global RS->BUF before this function
10748 is called, and the answer is there when we return.
10749
10750 COMMAND_BYTES is the length of the request to send, which may include
10751 binary data. WHICH_PACKET is the packet configuration to check
10752 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10753 is set to the error number and -1 is returned. Otherwise the value
10754 returned by the function is returned.
10755
10756 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10757 attachment is expected; an error will be reported if there's a
10758 mismatch. If one is found, *ATTACHMENT will be set to point into
10759 the packet buffer and *ATTACHMENT_LEN will be set to the
10760 attachment's length. */
10761
10762static int
10763remote_hostio_send_command (int command_bytes, int which_packet,
10764 int *remote_errno, char **attachment,
10765 int *attachment_len)
10766{
10767 struct remote_state *rs = get_remote_state ();
10768 int ret, bytes_read;
10769 char *attachment_tmp;
10770
5d93a237 10771 if (!rs->remote_desc
4082afcc 10772 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10773 {
10774 *remote_errno = FILEIO_ENOSYS;
10775 return -1;
10776 }
10777
10778 putpkt_binary (rs->buf, command_bytes);
10779 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10780
10781 /* If it timed out, something is wrong. Don't try to parse the
10782 buffer. */
10783 if (bytes_read < 0)
10784 {
10785 *remote_errno = FILEIO_EINVAL;
10786 return -1;
10787 }
10788
10789 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10790 {
10791 case PACKET_ERROR:
10792 *remote_errno = FILEIO_EINVAL;
10793 return -1;
10794 case PACKET_UNKNOWN:
10795 *remote_errno = FILEIO_ENOSYS;
10796 return -1;
10797 case PACKET_OK:
10798 break;
10799 }
10800
10801 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10802 &attachment_tmp))
10803 {
10804 *remote_errno = FILEIO_EINVAL;
10805 return -1;
10806 }
10807
10808 /* Make sure we saw an attachment if and only if we expected one. */
10809 if ((attachment_tmp == NULL && attachment != NULL)
10810 || (attachment_tmp != NULL && attachment == NULL))
10811 {
10812 *remote_errno = FILEIO_EINVAL;
10813 return -1;
10814 }
10815
10816 /* If an attachment was found, it must point into the packet buffer;
10817 work out how many bytes there were. */
10818 if (attachment_tmp != NULL)
10819 {
10820 *attachment = attachment_tmp;
10821 *attachment_len = bytes_read - (*attachment - rs->buf);
10822 }
10823
10824 return ret;
10825}
10826
80152258
PA
10827/* Invalidate the readahead cache. */
10828
10829static void
10830readahead_cache_invalidate (void)
10831{
10832 struct remote_state *rs = get_remote_state ();
10833
10834 rs->readahead_cache.fd = -1;
10835}
10836
10837/* Invalidate the readahead cache if it is holding data for FD. */
10838
10839static void
10840readahead_cache_invalidate_fd (int fd)
10841{
10842 struct remote_state *rs = get_remote_state ();
10843
10844 if (rs->readahead_cache.fd == fd)
10845 rs->readahead_cache.fd = -1;
10846}
10847
15a201c8
GB
10848/* Set the filesystem remote_hostio functions that take FILENAME
10849 arguments will use. Return 0 on success, or -1 if an error
10850 occurs (and set *REMOTE_ERRNO). */
10851
10852static int
10853remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10854{
10855 struct remote_state *rs = get_remote_state ();
10856 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10857 char *p = rs->buf;
10858 int left = get_remote_packet_size () - 1;
10859 char arg[9];
10860 int ret;
10861
10862 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10863 return 0;
10864
10865 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10866 return 0;
10867
10868 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10869
10870 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10871 remote_buffer_add_string (&p, &left, arg);
10872
10873 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10874 remote_errno, NULL, NULL);
10875
10876 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10877 return 0;
10878
10879 if (ret == 0)
10880 rs->fs_pid = required_pid;
10881
10882 return ret;
10883}
10884
12e2a5fd 10885/* Implementation of to_fileio_open. */
a6b151f1
DJ
10886
10887static int
cd897586 10888remote_hostio_open (struct target_ops *self,
07c138c8 10889 struct inferior *inf, const char *filename,
4313b8c0
GB
10890 int flags, int mode, int warn_if_slow,
10891 int *remote_errno)
a6b151f1
DJ
10892{
10893 struct remote_state *rs = get_remote_state ();
10894 char *p = rs->buf;
10895 int left = get_remote_packet_size () - 1;
10896
4313b8c0
GB
10897 if (warn_if_slow)
10898 {
10899 static int warning_issued = 0;
10900
10901 printf_unfiltered (_("Reading %s from remote target...\n"),
10902 filename);
10903
10904 if (!warning_issued)
10905 {
10906 warning (_("File transfers from remote targets can be slow."
10907 " Use \"set sysroot\" to access files locally"
10908 " instead."));
10909 warning_issued = 1;
10910 }
10911 }
10912
15a201c8
GB
10913 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10914 return -1;
10915
a6b151f1
DJ
10916 remote_buffer_add_string (&p, &left, "vFile:open:");
10917
10918 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10919 strlen (filename));
10920 remote_buffer_add_string (&p, &left, ",");
10921
10922 remote_buffer_add_int (&p, &left, flags);
10923 remote_buffer_add_string (&p, &left, ",");
10924
10925 remote_buffer_add_int (&p, &left, mode);
10926
10927 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10928 remote_errno, NULL, NULL);
10929}
10930
12e2a5fd 10931/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
10932
10933static int
0d866f62
TT
10934remote_hostio_pwrite (struct target_ops *self,
10935 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
10936 ULONGEST offset, int *remote_errno)
10937{
10938 struct remote_state *rs = get_remote_state ();
10939 char *p = rs->buf;
10940 int left = get_remote_packet_size ();
10941 int out_len;
10942
80152258
PA
10943 readahead_cache_invalidate_fd (fd);
10944
a6b151f1
DJ
10945 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10946
10947 remote_buffer_add_int (&p, &left, fd);
10948 remote_buffer_add_string (&p, &left, ",");
10949
10950 remote_buffer_add_int (&p, &left, offset);
10951 remote_buffer_add_string (&p, &left, ",");
10952
124e13d9 10953 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
10954 get_remote_packet_size () - (p - rs->buf));
10955
10956 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10957 remote_errno, NULL, NULL);
10958}
10959
80152258
PA
10960/* Helper for the implementation of to_fileio_pread. Read the file
10961 from the remote side with vFile:pread. */
a6b151f1
DJ
10962
10963static int
80152258
PA
10964remote_hostio_pread_vFile (struct target_ops *self,
10965 int fd, gdb_byte *read_buf, int len,
10966 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
10967{
10968 struct remote_state *rs = get_remote_state ();
10969 char *p = rs->buf;
10970 char *attachment;
10971 int left = get_remote_packet_size ();
10972 int ret, attachment_len;
10973 int read_len;
10974
10975 remote_buffer_add_string (&p, &left, "vFile:pread:");
10976
10977 remote_buffer_add_int (&p, &left, fd);
10978 remote_buffer_add_string (&p, &left, ",");
10979
10980 remote_buffer_add_int (&p, &left, len);
10981 remote_buffer_add_string (&p, &left, ",");
10982
10983 remote_buffer_add_int (&p, &left, offset);
10984
10985 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10986 remote_errno, &attachment,
10987 &attachment_len);
10988
10989 if (ret < 0)
10990 return ret;
10991
bc20a4af 10992 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
10993 read_buf, len);
10994 if (read_len != ret)
10995 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10996
10997 return ret;
10998}
10999
80152258
PA
11000/* Serve pread from the readahead cache. Returns number of bytes
11001 read, or 0 if the request can't be served from the cache. */
11002
11003static int
11004remote_hostio_pread_from_cache (struct remote_state *rs,
11005 int fd, gdb_byte *read_buf, size_t len,
11006 ULONGEST offset)
11007{
11008 struct readahead_cache *cache = &rs->readahead_cache;
11009
11010 if (cache->fd == fd
11011 && cache->offset <= offset
11012 && offset < cache->offset + cache->bufsize)
11013 {
11014 ULONGEST max = cache->offset + cache->bufsize;
11015
11016 if (offset + len > max)
11017 len = max - offset;
11018
11019 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11020 return len;
11021 }
11022
11023 return 0;
11024}
11025
11026/* Implementation of to_fileio_pread. */
11027
11028static int
11029remote_hostio_pread (struct target_ops *self,
11030 int fd, gdb_byte *read_buf, int len,
11031 ULONGEST offset, int *remote_errno)
11032{
11033 int ret;
11034 struct remote_state *rs = get_remote_state ();
11035 struct readahead_cache *cache = &rs->readahead_cache;
11036
11037 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11038 if (ret > 0)
11039 {
11040 cache->hit_count++;
11041
11042 if (remote_debug)
11043 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11044 pulongest (cache->hit_count));
11045 return ret;
11046 }
11047
11048 cache->miss_count++;
11049 if (remote_debug)
11050 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11051 pulongest (cache->miss_count));
11052
11053 cache->fd = fd;
11054 cache->offset = offset;
11055 cache->bufsize = get_remote_packet_size ();
224c3ddb 11056 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11057
11058 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11059 cache->offset, remote_errno);
11060 if (ret <= 0)
11061 {
11062 readahead_cache_invalidate_fd (fd);
11063 return ret;
11064 }
11065
11066 cache->bufsize = ret;
11067 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11068}
11069
12e2a5fd 11070/* Implementation of to_fileio_close. */
a6b151f1
DJ
11071
11072static int
df39ea25 11073remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11074{
11075 struct remote_state *rs = get_remote_state ();
11076 char *p = rs->buf;
11077 int left = get_remote_packet_size () - 1;
11078
80152258
PA
11079 readahead_cache_invalidate_fd (fd);
11080
a6b151f1
DJ
11081 remote_buffer_add_string (&p, &left, "vFile:close:");
11082
11083 remote_buffer_add_int (&p, &left, fd);
11084
11085 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11086 remote_errno, NULL, NULL);
11087}
11088
12e2a5fd 11089/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11090
11091static int
dbbca37d 11092remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11093 struct inferior *inf, const char *filename,
11094 int *remote_errno)
a6b151f1
DJ
11095{
11096 struct remote_state *rs = get_remote_state ();
11097 char *p = rs->buf;
11098 int left = get_remote_packet_size () - 1;
11099
15a201c8
GB
11100 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11101 return -1;
11102
a6b151f1
DJ
11103 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11104
11105 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11106 strlen (filename));
11107
11108 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11109 remote_errno, NULL, NULL);
11110}
11111
12e2a5fd 11112/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11113
11114static char *
fab5aa7c 11115remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11116 struct inferior *inf, const char *filename,
11117 int *remote_errno)
b9e7b9c3
UW
11118{
11119 struct remote_state *rs = get_remote_state ();
11120 char *p = rs->buf;
11121 char *attachment;
11122 int left = get_remote_packet_size ();
11123 int len, attachment_len;
11124 int read_len;
11125 char *ret;
11126
15a201c8
GB
11127 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11128 return NULL;
11129
b9e7b9c3
UW
11130 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11131
11132 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11133 strlen (filename));
11134
11135 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11136 remote_errno, &attachment,
11137 &attachment_len);
11138
11139 if (len < 0)
11140 return NULL;
11141
224c3ddb 11142 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11143
bc20a4af
PA
11144 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11145 (gdb_byte *) ret, len);
b9e7b9c3
UW
11146 if (read_len != len)
11147 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11148
11149 ret[len] = '\0';
11150 return ret;
11151}
11152
12e2a5fd 11153/* Implementation of to_fileio_fstat. */
0a93529c
GB
11154
11155static int
11156remote_hostio_fstat (struct target_ops *self,
11157 int fd, struct stat *st,
11158 int *remote_errno)
11159{
11160 struct remote_state *rs = get_remote_state ();
11161 char *p = rs->buf;
11162 int left = get_remote_packet_size ();
11163 int attachment_len, ret;
11164 char *attachment;
11165 struct fio_stat fst;
11166 int read_len;
11167
464b0089
GB
11168 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11169
11170 remote_buffer_add_int (&p, &left, fd);
11171
11172 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11173 remote_errno, &attachment,
11174 &attachment_len);
11175 if (ret < 0)
0a93529c 11176 {
464b0089
GB
11177 if (*remote_errno != FILEIO_ENOSYS)
11178 return ret;
11179
0a93529c
GB
11180 /* Strictly we should return -1, ENOSYS here, but when
11181 "set sysroot remote:" was implemented in August 2008
11182 BFD's need for a stat function was sidestepped with
11183 this hack. This was not remedied until March 2015
11184 so we retain the previous behavior to avoid breaking
11185 compatibility.
11186
11187 Note that the memset is a March 2015 addition; older
11188 GDBs set st_size *and nothing else* so the structure
11189 would have garbage in all other fields. This might
11190 break something but retaining the previous behavior
11191 here would be just too wrong. */
11192
11193 memset (st, 0, sizeof (struct stat));
11194 st->st_size = INT_MAX;
11195 return 0;
11196 }
11197
0a93529c
GB
11198 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11199 (gdb_byte *) &fst, sizeof (fst));
11200
11201 if (read_len != ret)
11202 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11203
11204 if (read_len != sizeof (fst))
11205 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11206 read_len, (int) sizeof (fst));
11207
11208 remote_fileio_to_host_stat (&fst, st);
11209
11210 return 0;
11211}
11212
12e2a5fd 11213/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11214
11215static int
11216remote_filesystem_is_local (struct target_ops *self)
11217{
11218 /* Valgrind GDB presents itself as a remote target but works
11219 on the local filesystem: it does not implement remote get
11220 and users are not expected to set a sysroot. To handle
11221 this case we treat the remote filesystem as local if the
11222 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11223 does not support vFile:open. */
a3be80c3 11224 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11225 {
11226 enum packet_support ps = packet_support (PACKET_vFile_open);
11227
11228 if (ps == PACKET_SUPPORT_UNKNOWN)
11229 {
11230 int fd, remote_errno;
11231
11232 /* Try opening a file to probe support. The supplied
11233 filename is irrelevant, we only care about whether
11234 the stub recognizes the packet or not. */
07c138c8 11235 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11236 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11237 &remote_errno);
11238
11239 if (fd >= 0)
11240 remote_hostio_close (self, fd, &remote_errno);
11241
11242 ps = packet_support (PACKET_vFile_open);
11243 }
11244
11245 if (ps == PACKET_DISABLE)
11246 {
11247 static int warning_issued = 0;
11248
11249 if (!warning_issued)
11250 {
11251 warning (_("remote target does not support file"
11252 " transfer, attempting to access files"
11253 " from local filesystem."));
11254 warning_issued = 1;
11255 }
11256
11257 return 1;
11258 }
11259 }
11260
11261 return 0;
11262}
11263
a6b151f1
DJ
11264static int
11265remote_fileio_errno_to_host (int errnum)
11266{
11267 switch (errnum)
11268 {
11269 case FILEIO_EPERM:
11270 return EPERM;
11271 case FILEIO_ENOENT:
11272 return ENOENT;
11273 case FILEIO_EINTR:
11274 return EINTR;
11275 case FILEIO_EIO:
11276 return EIO;
11277 case FILEIO_EBADF:
11278 return EBADF;
11279 case FILEIO_EACCES:
11280 return EACCES;
11281 case FILEIO_EFAULT:
11282 return EFAULT;
11283 case FILEIO_EBUSY:
11284 return EBUSY;
11285 case FILEIO_EEXIST:
11286 return EEXIST;
11287 case FILEIO_ENODEV:
11288 return ENODEV;
11289 case FILEIO_ENOTDIR:
11290 return ENOTDIR;
11291 case FILEIO_EISDIR:
11292 return EISDIR;
11293 case FILEIO_EINVAL:
11294 return EINVAL;
11295 case FILEIO_ENFILE:
11296 return ENFILE;
11297 case FILEIO_EMFILE:
11298 return EMFILE;
11299 case FILEIO_EFBIG:
11300 return EFBIG;
11301 case FILEIO_ENOSPC:
11302 return ENOSPC;
11303 case FILEIO_ESPIPE:
11304 return ESPIPE;
11305 case FILEIO_EROFS:
11306 return EROFS;
11307 case FILEIO_ENOSYS:
11308 return ENOSYS;
11309 case FILEIO_ENAMETOOLONG:
11310 return ENAMETOOLONG;
11311 }
11312 return -1;
11313}
11314
11315static char *
11316remote_hostio_error (int errnum)
11317{
11318 int host_error = remote_fileio_errno_to_host (errnum);
11319
11320 if (host_error == -1)
11321 error (_("Unknown remote I/O error %d"), errnum);
11322 else
11323 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11324}
11325
a6b151f1
DJ
11326static void
11327remote_hostio_close_cleanup (void *opaque)
11328{
11329 int fd = *(int *) opaque;
11330 int remote_errno;
11331
df39ea25 11332 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11333}
11334
11335void
11336remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11337{
11338 struct cleanup *back_to, *close_cleanup;
11339 int retcode, fd, remote_errno, bytes, io_size;
11340 FILE *file;
11341 gdb_byte *buffer;
11342 int bytes_in_buffer;
11343 int saw_eof;
11344 ULONGEST offset;
5d93a237 11345 struct remote_state *rs = get_remote_state ();
a6b151f1 11346
5d93a237 11347 if (!rs->remote_desc)
a6b151f1
DJ
11348 error (_("command can only be used with remote target"));
11349
614c279d 11350 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11351 if (file == NULL)
11352 perror_with_name (local_file);
7c8a8b04 11353 back_to = make_cleanup_fclose (file);
a6b151f1 11354
07c138c8 11355 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11356 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11357 | FILEIO_O_TRUNC),
4313b8c0 11358 0700, 0, &remote_errno);
a6b151f1
DJ
11359 if (fd == -1)
11360 remote_hostio_error (remote_errno);
11361
11362 /* Send up to this many bytes at once. They won't all fit in the
11363 remote packet limit, so we'll transfer slightly fewer. */
11364 io_size = get_remote_packet_size ();
224c3ddb 11365 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11366 make_cleanup (xfree, buffer);
11367
11368 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11369
11370 bytes_in_buffer = 0;
11371 saw_eof = 0;
11372 offset = 0;
11373 while (bytes_in_buffer || !saw_eof)
11374 {
11375 if (!saw_eof)
11376 {
3e43a32a
MS
11377 bytes = fread (buffer + bytes_in_buffer, 1,
11378 io_size - bytes_in_buffer,
a6b151f1
DJ
11379 file);
11380 if (bytes == 0)
11381 {
11382 if (ferror (file))
11383 error (_("Error reading %s."), local_file);
11384 else
11385 {
11386 /* EOF. Unless there is something still in the
11387 buffer from the last iteration, we are done. */
11388 saw_eof = 1;
11389 if (bytes_in_buffer == 0)
11390 break;
11391 }
11392 }
11393 }
11394 else
11395 bytes = 0;
11396
11397 bytes += bytes_in_buffer;
11398 bytes_in_buffer = 0;
11399
0d866f62
TT
11400 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11401 fd, buffer, bytes,
3e43a32a 11402 offset, &remote_errno);
a6b151f1
DJ
11403
11404 if (retcode < 0)
11405 remote_hostio_error (remote_errno);
11406 else if (retcode == 0)
11407 error (_("Remote write of %d bytes returned 0!"), bytes);
11408 else if (retcode < bytes)
11409 {
11410 /* Short write. Save the rest of the read data for the next
11411 write. */
11412 bytes_in_buffer = bytes - retcode;
11413 memmove (buffer, buffer + retcode, bytes_in_buffer);
11414 }
11415
11416 offset += retcode;
11417 }
11418
11419 discard_cleanups (close_cleanup);
df39ea25 11420 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11421 remote_hostio_error (remote_errno);
11422
11423 if (from_tty)
11424 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11425 do_cleanups (back_to);
11426}
11427
11428void
11429remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11430{
11431 struct cleanup *back_to, *close_cleanup;
cea39f65 11432 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11433 FILE *file;
11434 gdb_byte *buffer;
11435 ULONGEST offset;
5d93a237 11436 struct remote_state *rs = get_remote_state ();
a6b151f1 11437
5d93a237 11438 if (!rs->remote_desc)
a6b151f1
DJ
11439 error (_("command can only be used with remote target"));
11440
07c138c8 11441 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11442 remote_file, FILEIO_O_RDONLY, 0, 0,
11443 &remote_errno);
a6b151f1
DJ
11444 if (fd == -1)
11445 remote_hostio_error (remote_errno);
11446
614c279d 11447 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11448 if (file == NULL)
11449 perror_with_name (local_file);
7c8a8b04 11450 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11451
11452 /* Send up to this many bytes at once. They won't all fit in the
11453 remote packet limit, so we'll transfer slightly fewer. */
11454 io_size = get_remote_packet_size ();
224c3ddb 11455 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11456 make_cleanup (xfree, buffer);
11457
11458 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11459
11460 offset = 0;
11461 while (1)
11462 {
a3be983c
TT
11463 bytes = remote_hostio_pread (find_target_at (process_stratum),
11464 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11465 if (bytes == 0)
11466 /* Success, but no bytes, means end-of-file. */
11467 break;
11468 if (bytes == -1)
11469 remote_hostio_error (remote_errno);
11470
11471 offset += bytes;
11472
11473 bytes = fwrite (buffer, 1, bytes, file);
11474 if (bytes == 0)
11475 perror_with_name (local_file);
11476 }
11477
11478 discard_cleanups (close_cleanup);
df39ea25 11479 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11480 remote_hostio_error (remote_errno);
11481
11482 if (from_tty)
11483 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11484 do_cleanups (back_to);
11485}
11486
11487void
11488remote_file_delete (const char *remote_file, int from_tty)
11489{
11490 int retcode, remote_errno;
5d93a237 11491 struct remote_state *rs = get_remote_state ();
a6b151f1 11492
5d93a237 11493 if (!rs->remote_desc)
a6b151f1
DJ
11494 error (_("command can only be used with remote target"));
11495
dbbca37d 11496 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11497 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11498 if (retcode == -1)
11499 remote_hostio_error (remote_errno);
11500
11501 if (from_tty)
11502 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11503}
11504
11505static void
11506remote_put_command (char *args, int from_tty)
11507{
11508 struct cleanup *back_to;
11509 char **argv;
11510
d1a41061
PP
11511 if (args == NULL)
11512 error_no_arg (_("file to put"));
11513
11514 argv = gdb_buildargv (args);
a6b151f1
DJ
11515 back_to = make_cleanup_freeargv (argv);
11516 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11517 error (_("Invalid parameters to remote put"));
11518
11519 remote_file_put (argv[0], argv[1], from_tty);
11520
11521 do_cleanups (back_to);
11522}
11523
11524static void
11525remote_get_command (char *args, int from_tty)
11526{
11527 struct cleanup *back_to;
11528 char **argv;
11529
d1a41061
PP
11530 if (args == NULL)
11531 error_no_arg (_("file to get"));
11532
11533 argv = gdb_buildargv (args);
a6b151f1
DJ
11534 back_to = make_cleanup_freeargv (argv);
11535 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11536 error (_("Invalid parameters to remote get"));
11537
11538 remote_file_get (argv[0], argv[1], from_tty);
11539
11540 do_cleanups (back_to);
11541}
11542
11543static void
11544remote_delete_command (char *args, int from_tty)
11545{
11546 struct cleanup *back_to;
11547 char **argv;
11548
d1a41061
PP
11549 if (args == NULL)
11550 error_no_arg (_("file to delete"));
11551
11552 argv = gdb_buildargv (args);
a6b151f1
DJ
11553 back_to = make_cleanup_freeargv (argv);
11554 if (argv[0] == NULL || argv[1] != NULL)
11555 error (_("Invalid parameters to remote delete"));
11556
11557 remote_file_delete (argv[0], from_tty);
11558
11559 do_cleanups (back_to);
11560}
11561
11562static void
11563remote_command (char *args, int from_tty)
11564{
635c7e8a 11565 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11566}
11567
b2175913 11568static int
19db3e69 11569remote_can_execute_reverse (struct target_ops *self)
b2175913 11570{
4082afcc
PA
11571 if (packet_support (PACKET_bs) == PACKET_ENABLE
11572 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11573 return 1;
11574 else
11575 return 0;
b2175913
MS
11576}
11577
74531fed 11578static int
2a9a2795 11579remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11580{
11581 return 1;
11582}
11583
03583c20 11584static int
2bfc0540 11585remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11586{
11587 /* Only supported in extended mode. */
11588 return 0;
11589}
11590
8a305172 11591static int
86ce2668 11592remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11593{
11594 struct remote_state *rs = get_remote_state ();
a744cf53 11595
901f9912
UW
11596 /* Only extended-remote handles being attached to multiple
11597 processes, even though plain remote can use the multi-process
11598 thread id extensions, so that GDB knows the target process's
11599 PID. */
11600 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
11601}
11602
70221824 11603static int
782b2b07
SS
11604remote_supports_cond_tracepoints (void)
11605{
4082afcc 11606 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11607}
11608
3788aec7 11609static int
efcc2da7 11610remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11611{
4082afcc 11612 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11613}
11614
70221824 11615static int
7a697b8d
SS
11616remote_supports_fast_tracepoints (void)
11617{
4082afcc 11618 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11619}
11620
0fb4aa4b
PA
11621static int
11622remote_supports_static_tracepoints (void)
11623{
4082afcc 11624 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11625}
11626
1e4d1764
YQ
11627static int
11628remote_supports_install_in_trace (void)
11629{
4082afcc 11630 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11631}
11632
d248b706 11633static int
7d178d6a 11634remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11635{
4082afcc
PA
11636 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11637 == PACKET_ENABLE);
d248b706
KY
11638}
11639
3065dfb6 11640static int
6de37a3a 11641remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11642{
4082afcc 11643 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11644}
11645
d3ce09f5 11646static int
78eff0ec 11647remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11648{
4082afcc 11649 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11650}
11651
35b1e5cc 11652static void
ecae04e1 11653remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11654{
11655 putpkt ("QTinit");
11656 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11657 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11658 error (_("Target does not support this command."));
11659}
11660
11661static void free_actions_list (char **actions_list);
11662static void free_actions_list_cleanup_wrapper (void *);
11663static void
11664free_actions_list_cleanup_wrapper (void *al)
11665{
19ba03f4 11666 free_actions_list ((char **) al);
35b1e5cc
SS
11667}
11668
11669static void
11670free_actions_list (char **actions_list)
11671{
11672 int ndx;
11673
11674 if (actions_list == 0)
11675 return;
11676
11677 for (ndx = 0; actions_list[ndx]; ndx++)
11678 xfree (actions_list[ndx]);
11679
11680 xfree (actions_list);
11681}
11682
409873ef
SS
11683/* Recursive routine to walk through command list including loops, and
11684 download packets for each command. */
11685
11686static void
11687remote_download_command_source (int num, ULONGEST addr,
11688 struct command_line *cmds)
11689{
11690 struct remote_state *rs = get_remote_state ();
11691 struct command_line *cmd;
11692
11693 for (cmd = cmds; cmd; cmd = cmd->next)
11694 {
0df8b418 11695 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11696 strcpy (rs->buf, "QTDPsrc:");
11697 encode_source_string (num, addr, "cmd", cmd->line,
11698 rs->buf + strlen (rs->buf),
11699 rs->buf_size - strlen (rs->buf));
11700 putpkt (rs->buf);
11701 remote_get_noisy_reply (&target_buf, &target_buf_size);
11702 if (strcmp (target_buf, "OK"))
11703 warning (_("Target does not support source download."));
11704
11705 if (cmd->control_type == while_control
11706 || cmd->control_type == while_stepping_control)
11707 {
11708 remote_download_command_source (num, addr, *cmd->body_list);
11709
0df8b418 11710 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11711 strcpy (rs->buf, "QTDPsrc:");
11712 encode_source_string (num, addr, "cmd", "end",
11713 rs->buf + strlen (rs->buf),
11714 rs->buf_size - strlen (rs->buf));
11715 putpkt (rs->buf);
11716 remote_get_noisy_reply (&target_buf, &target_buf_size);
11717 if (strcmp (target_buf, "OK"))
11718 warning (_("Target does not support source download."));
11719 }
11720 }
11721}
11722
35b1e5cc 11723static void
548f7808 11724remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11725{
bba74b36 11726#define BUF_SIZE 2048
e8ba3115 11727
35b1e5cc 11728 CORE_ADDR tpaddr;
409873ef 11729 char addrbuf[40];
bba74b36 11730 char buf[BUF_SIZE];
35b1e5cc
SS
11731 char **tdp_actions;
11732 char **stepping_actions;
11733 int ndx;
11734 struct cleanup *old_chain = NULL;
11735 struct agent_expr *aexpr;
11736 struct cleanup *aexpr_chain = NULL;
11737 char *pkt;
e8ba3115 11738 struct breakpoint *b = loc->owner;
d9b3f62e 11739 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11740
dc673c81 11741 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11742 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11743 tdp_actions);
11744 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11745 stepping_actions);
11746
11747 tpaddr = loc->address;
11748 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11749 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11750 addrbuf, /* address */
11751 (b->enable_state == bp_enabled ? 'E' : 'D'),
11752 t->step_count, t->pass_count);
e8ba3115
YQ
11753 /* Fast tracepoints are mostly handled by the target, but we can
11754 tell the target how big of an instruction block should be moved
11755 around. */
11756 if (b->type == bp_fast_tracepoint)
11757 {
11758 /* Only test for support at download time; we may not know
11759 target capabilities at definition time. */
11760 if (remote_supports_fast_tracepoints ())
35b1e5cc 11761 {
6b940e6a
PL
11762 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11763 NULL))
bba74b36 11764 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11765 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11766 else
e8ba3115
YQ
11767 /* If it passed validation at definition but fails now,
11768 something is very wrong. */
11769 internal_error (__FILE__, __LINE__,
11770 _("Fast tracepoint not "
11771 "valid during download"));
35b1e5cc 11772 }
e8ba3115
YQ
11773 else
11774 /* Fast tracepoints are functionally identical to regular
11775 tracepoints, so don't take lack of support as a reason to
11776 give up on the trace run. */
11777 warning (_("Target does not support fast tracepoints, "
11778 "downloading %d as regular tracepoint"), b->number);
11779 }
11780 else if (b->type == bp_static_tracepoint)
11781 {
11782 /* Only test for support at download time; we may not know
11783 target capabilities at definition time. */
11784 if (remote_supports_static_tracepoints ())
0fb4aa4b 11785 {
e8ba3115 11786 struct static_tracepoint_marker marker;
0fb4aa4b 11787
e8ba3115
YQ
11788 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11789 strcat (buf, ":S");
0fb4aa4b 11790 else
e8ba3115 11791 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11792 }
e8ba3115
YQ
11793 else
11794 /* Fast tracepoints are functionally identical to regular
11795 tracepoints, so don't take lack of support as a reason
11796 to give up on the trace run. */
11797 error (_("Target does not support static tracepoints"));
11798 }
11799 /* If the tracepoint has a conditional, make it into an agent
11800 expression and append to the definition. */
11801 if (loc->cond)
11802 {
11803 /* Only test support at download time, we may not know target
11804 capabilities at definition time. */
11805 if (remote_supports_cond_tracepoints ())
35b1e5cc 11806 {
e8ba3115
YQ
11807 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11808 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11809 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11810 aexpr->len);
e8ba3115
YQ
11811 pkt = buf + strlen (buf);
11812 for (ndx = 0; ndx < aexpr->len; ++ndx)
11813 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11814 *pkt = '\0';
11815 do_cleanups (aexpr_chain);
35b1e5cc 11816 }
e8ba3115
YQ
11817 else
11818 warning (_("Target does not support conditional tracepoints, "
11819 "ignoring tp %d cond"), b->number);
11820 }
35b1e5cc 11821
d9b3f62e 11822 if (b->commands || *default_collect)
e8ba3115
YQ
11823 strcat (buf, "-");
11824 putpkt (buf);
11825 remote_get_noisy_reply (&target_buf, &target_buf_size);
11826 if (strcmp (target_buf, "OK"))
11827 error (_("Target does not support tracepoints."));
35b1e5cc 11828
e8ba3115
YQ
11829 /* do_single_steps (t); */
11830 if (tdp_actions)
11831 {
11832 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11833 {
e8ba3115 11834 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11835 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11836 b->number, addrbuf, /* address */
11837 tdp_actions[ndx],
11838 ((tdp_actions[ndx + 1] || stepping_actions)
11839 ? '-' : 0));
e8ba3115
YQ
11840 putpkt (buf);
11841 remote_get_noisy_reply (&target_buf,
11842 &target_buf_size);
11843 if (strcmp (target_buf, "OK"))
11844 error (_("Error on target while setting tracepoints."));
35b1e5cc 11845 }
e8ba3115
YQ
11846 }
11847 if (stepping_actions)
11848 {
11849 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11850 {
e8ba3115 11851 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11852 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11853 b->number, addrbuf, /* address */
11854 ((ndx == 0) ? "S" : ""),
11855 stepping_actions[ndx],
11856 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11857 putpkt (buf);
11858 remote_get_noisy_reply (&target_buf,
11859 &target_buf_size);
11860 if (strcmp (target_buf, "OK"))
11861 error (_("Error on target while setting tracepoints."));
35b1e5cc 11862 }
e8ba3115 11863 }
409873ef 11864
4082afcc 11865 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11866 {
f00aae0f 11867 if (b->location != NULL)
409873ef 11868 {
e8ba3115 11869 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11870 encode_source_string (b->number, loc->address, "at",
11871 event_location_to_string (b->location),
11872 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11873 putpkt (buf);
11874 remote_get_noisy_reply (&target_buf, &target_buf_size);
11875 if (strcmp (target_buf, "OK"))
11876 warning (_("Target does not support source download."));
409873ef 11877 }
e8ba3115
YQ
11878 if (b->cond_string)
11879 {
11880 strcpy (buf, "QTDPsrc:");
11881 encode_source_string (b->number, loc->address,
11882 "cond", b->cond_string, buf + strlen (buf),
11883 2048 - strlen (buf));
11884 putpkt (buf);
11885 remote_get_noisy_reply (&target_buf, &target_buf_size);
11886 if (strcmp (target_buf, "OK"))
11887 warning (_("Target does not support source download."));
11888 }
11889 remote_download_command_source (b->number, loc->address,
11890 breakpoint_commands (b));
35b1e5cc 11891 }
e8ba3115
YQ
11892
11893 do_cleanups (old_chain);
35b1e5cc
SS
11894}
11895
1e4d1764 11896static int
a52a8357 11897remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 11898{
1e51243a
PA
11899 struct remote_state *rs = get_remote_state ();
11900 struct trace_status *ts;
11901 int status;
11902
11903 /* Don't try to install tracepoints until we've relocated our
11904 symbols, and fetched and merged the target's tracepoint list with
11905 ours. */
11906 if (rs->starting_up)
11907 return 0;
11908
11909 ts = current_trace_status ();
8bd200f1 11910 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
11911
11912 if (status == -1 || !ts->running_known || !ts->running)
11913 return 0;
11914
11915 /* If we are in a tracing experiment, but remote stub doesn't support
11916 installing tracepoint in trace, we have to return. */
11917 if (!remote_supports_install_in_trace ())
11918 return 0;
11919
11920 return 1;
11921}
11922
11923
35b1e5cc 11924static void
559d2b81
TT
11925remote_download_trace_state_variable (struct target_ops *self,
11926 struct trace_state_variable *tsv)
35b1e5cc
SS
11927{
11928 struct remote_state *rs = get_remote_state ();
00bf0b85 11929 char *p;
35b1e5cc 11930
bba74b36
YQ
11931 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11932 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11933 tsv->builtin);
00bf0b85
SS
11934 p = rs->buf + strlen (rs->buf);
11935 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11936 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 11937 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 11938 *p++ = '\0';
35b1e5cc
SS
11939 putpkt (rs->buf);
11940 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11941 if (*target_buf == '\0')
11942 error (_("Target does not support this command."));
11943 if (strcmp (target_buf, "OK") != 0)
11944 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
11945}
11946
d248b706 11947static void
46670d57
TT
11948remote_enable_tracepoint (struct target_ops *self,
11949 struct bp_location *location)
d248b706
KY
11950{
11951 struct remote_state *rs = get_remote_state ();
11952 char addr_buf[40];
11953
11954 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11955 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11956 location->owner->number, addr_buf);
d248b706
KY
11957 putpkt (rs->buf);
11958 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11959 if (*rs->buf == '\0')
11960 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11961 if (strcmp (rs->buf, "OK") != 0)
11962 error (_("Error on target while enabling tracepoint."));
11963}
11964
11965static void
780b049c
TT
11966remote_disable_tracepoint (struct target_ops *self,
11967 struct bp_location *location)
d248b706
KY
11968{
11969 struct remote_state *rs = get_remote_state ();
11970 char addr_buf[40];
11971
11972 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11973 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11974 location->owner->number, addr_buf);
d248b706
KY
11975 putpkt (rs->buf);
11976 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11977 if (*rs->buf == '\0')
11978 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11979 if (strcmp (rs->buf, "OK") != 0)
11980 error (_("Error on target while disabling tracepoint."));
11981}
11982
35b1e5cc 11983static void
583f9a86 11984remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
11985{
11986 asection *s;
81b9b86e 11987 bfd *abfd = NULL;
35b1e5cc 11988 bfd_size_type size;
608bcef2 11989 bfd_vma vma;
35b1e5cc 11990 int anysecs = 0;
c2fa21f1 11991 int offset = 0;
35b1e5cc
SS
11992
11993 if (!exec_bfd)
11994 return; /* No information to give. */
11995
11996 strcpy (target_buf, "QTro");
9779ab84 11997 offset = strlen (target_buf);
35b1e5cc
SS
11998 for (s = exec_bfd->sections; s; s = s->next)
11999 {
12000 char tmp1[40], tmp2[40];
c2fa21f1 12001 int sec_length;
35b1e5cc
SS
12002
12003 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12004 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12005 (s->flags & SEC_READONLY) == 0)
12006 continue;
12007
12008 anysecs = 1;
81b9b86e 12009 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12010 size = bfd_get_section_size (s);
608bcef2
HZ
12011 sprintf_vma (tmp1, vma);
12012 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12013 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12014 if (offset + sec_length + 1 > target_buf_size)
12015 {
4082afcc 12016 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12017 warning (_("\
c2fa21f1
HZ
12018Too many sections for read-only sections definition packet."));
12019 break;
12020 }
bba74b36
YQ
12021 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12022 tmp1, tmp2);
c2fa21f1 12023 offset += sec_length;
35b1e5cc
SS
12024 }
12025 if (anysecs)
12026 {
12027 putpkt (target_buf);
12028 getpkt (&target_buf, &target_buf_size, 0);
12029 }
12030}
12031
12032static void
e2d1aae3 12033remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12034{
12035 putpkt ("QTStart");
12036 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12037 if (*target_buf == '\0')
12038 error (_("Target does not support this command."));
12039 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12040 error (_("Bogus reply from target: %s"), target_buf);
12041}
12042
12043static int
8bd200f1 12044remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12045{
953b98d1 12046 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12047 char *p = NULL;
0df8b418 12048 /* FIXME we need to get register block size some other way. */
00bf0b85 12049 extern int trace_regblock_size;
bd3eecc3
PA
12050 enum packet_result result;
12051
4082afcc 12052 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12053 return -1;
a744cf53 12054
00bf0b85
SS
12055 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12056
049dc89b
JK
12057 putpkt ("qTStatus");
12058
492d29ea 12059 TRY
67f41397
JK
12060 {
12061 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12062 }
492d29ea 12063 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12064 {
598d3636
JK
12065 if (ex.error != TARGET_CLOSE_ERROR)
12066 {
12067 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12068 return -1;
12069 }
12070 throw_exception (ex);
67f41397 12071 }
492d29ea 12072 END_CATCH
00bf0b85 12073
bd3eecc3
PA
12074 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12075
00bf0b85 12076 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12077 if (result == PACKET_UNKNOWN)
00bf0b85 12078 return -1;
35b1e5cc 12079
00bf0b85 12080 /* We're working with a live target. */
f5911ea1 12081 ts->filename = NULL;
00bf0b85 12082
00bf0b85 12083 if (*p++ != 'T')
35b1e5cc
SS
12084 error (_("Bogus trace status reply from target: %s"), target_buf);
12085
84cebc4a
YQ
12086 /* Function 'parse_trace_status' sets default value of each field of
12087 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12088 parse_trace_status (p, ts);
12089
12090 return ts->running;
35b1e5cc
SS
12091}
12092
70221824 12093static void
db90e85c 12094remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12095 struct uploaded_tp *utp)
12096{
12097 struct remote_state *rs = get_remote_state ();
f196051f
SS
12098 char *reply;
12099 struct bp_location *loc;
12100 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12101 size_t size = get_remote_packet_size ();
f196051f
SS
12102
12103 if (tp)
12104 {
12105 tp->base.hit_count = 0;
12106 tp->traceframe_usage = 0;
12107 for (loc = tp->base.loc; loc; loc = loc->next)
12108 {
12109 /* If the tracepoint was never downloaded, don't go asking for
12110 any status. */
12111 if (tp->number_on_target == 0)
12112 continue;
bba74b36
YQ
12113 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12114 phex_nz (loc->address, 0));
f196051f
SS
12115 putpkt (rs->buf);
12116 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12117 if (reply && *reply)
12118 {
12119 if (*reply == 'V')
12120 parse_tracepoint_status (reply + 1, bp, utp);
12121 }
12122 }
12123 }
12124 else if (utp)
12125 {
12126 utp->hit_count = 0;
12127 utp->traceframe_usage = 0;
bba74b36
YQ
12128 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12129 phex_nz (utp->addr, 0));
f196051f
SS
12130 putpkt (rs->buf);
12131 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12132 if (reply && *reply)
12133 {
12134 if (*reply == 'V')
12135 parse_tracepoint_status (reply + 1, bp, utp);
12136 }
12137 }
12138}
12139
35b1e5cc 12140static void
74499f1b 12141remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12142{
12143 putpkt ("QTStop");
12144 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12145 if (*target_buf == '\0')
12146 error (_("Target does not support this command."));
12147 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12148 error (_("Bogus reply from target: %s"), target_buf);
12149}
12150
12151static int
bd4c6793
TT
12152remote_trace_find (struct target_ops *self,
12153 enum trace_find_type type, int num,
cc5925ad 12154 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12155 int *tpp)
12156{
12157 struct remote_state *rs = get_remote_state ();
bba74b36 12158 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12159 char *p, *reply;
12160 int target_frameno = -1, target_tracept = -1;
12161
e6e4e701
PA
12162 /* Lookups other than by absolute frame number depend on the current
12163 trace selected, so make sure it is correct on the remote end
12164 first. */
12165 if (type != tfind_number)
12166 set_remote_traceframe ();
12167
35b1e5cc
SS
12168 p = rs->buf;
12169 strcpy (p, "QTFrame:");
12170 p = strchr (p, '\0');
12171 switch (type)
12172 {
12173 case tfind_number:
bba74b36 12174 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12175 break;
12176 case tfind_pc:
bba74b36 12177 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12178 break;
12179 case tfind_tp:
bba74b36 12180 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12181 break;
12182 case tfind_range:
bba74b36
YQ
12183 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12184 phex_nz (addr2, 0));
35b1e5cc
SS
12185 break;
12186 case tfind_outside:
bba74b36
YQ
12187 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12188 phex_nz (addr2, 0));
35b1e5cc
SS
12189 break;
12190 default:
9b20d036 12191 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12192 }
12193
12194 putpkt (rs->buf);
2f65bcb7 12195 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12196 if (*reply == '\0')
12197 error (_("Target does not support this command."));
35b1e5cc
SS
12198
12199 while (reply && *reply)
12200 switch (*reply)
12201 {
12202 case 'F':
f197e0f1
VP
12203 p = ++reply;
12204 target_frameno = (int) strtol (p, &reply, 16);
12205 if (reply == p)
12206 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12207 /* Don't update our remote traceframe number cache on failure
12208 to select a remote traceframe. */
f197e0f1
VP
12209 if (target_frameno == -1)
12210 return -1;
35b1e5cc
SS
12211 break;
12212 case 'T':
f197e0f1
VP
12213 p = ++reply;
12214 target_tracept = (int) strtol (p, &reply, 16);
12215 if (reply == p)
12216 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12217 break;
12218 case 'O': /* "OK"? */
12219 if (reply[1] == 'K' && reply[2] == '\0')
12220 reply += 2;
12221 else
12222 error (_("Bogus reply from target: %s"), reply);
12223 break;
12224 default:
12225 error (_("Bogus reply from target: %s"), reply);
12226 }
12227 if (tpp)
12228 *tpp = target_tracept;
e6e4e701 12229
262e1174 12230 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12231 return target_frameno;
12232}
12233
12234static int
4011015b
TT
12235remote_get_trace_state_variable_value (struct target_ops *self,
12236 int tsvnum, LONGEST *val)
35b1e5cc
SS
12237{
12238 struct remote_state *rs = get_remote_state ();
12239 char *reply;
12240 ULONGEST uval;
12241
e6e4e701
PA
12242 set_remote_traceframe ();
12243
bba74b36 12244 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12245 putpkt (rs->buf);
12246 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12247 if (reply && *reply)
12248 {
12249 if (*reply == 'V')
12250 {
12251 unpack_varlen_hex (reply + 1, &uval);
12252 *val = (LONGEST) uval;
12253 return 1;
12254 }
12255 }
12256 return 0;
12257}
12258
00bf0b85 12259static int
dc3decaf 12260remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12261{
12262 struct remote_state *rs = get_remote_state ();
12263 char *p, *reply;
12264
12265 p = rs->buf;
12266 strcpy (p, "QTSave:");
12267 p += strlen (p);
12268 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12269 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12270 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12271 *p++ = '\0';
12272 putpkt (rs->buf);
ad91cd99 12273 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12274 if (*reply == '\0')
ad91cd99
PA
12275 error (_("Target does not support this command."));
12276 if (strcmp (reply, "OK") != 0)
12277 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12278 return 0;
12279}
12280
12281/* This is basically a memory transfer, but needs to be its own packet
12282 because we don't know how the target actually organizes its trace
12283 memory, plus we want to be able to ask for as much as possible, but
12284 not be unhappy if we don't get as much as we ask for. */
12285
12286static LONGEST
88ee6f45
TT
12287remote_get_raw_trace_data (struct target_ops *self,
12288 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12289{
12290 struct remote_state *rs = get_remote_state ();
12291 char *reply;
12292 char *p;
12293 int rslt;
12294
12295 p = rs->buf;
12296 strcpy (p, "qTBuffer:");
12297 p += strlen (p);
12298 p += hexnumstr (p, offset);
12299 *p++ = ',';
12300 p += hexnumstr (p, len);
12301 *p++ = '\0';
12302
12303 putpkt (rs->buf);
12304 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12305 if (reply && *reply)
12306 {
12307 /* 'l' by itself means we're at the end of the buffer and
12308 there is nothing more to get. */
12309 if (*reply == 'l')
12310 return 0;
12311
12312 /* Convert the reply into binary. Limit the number of bytes to
12313 convert according to our passed-in buffer size, rather than
12314 what was returned in the packet; if the target is
12315 unexpectedly generous and gives us a bigger reply than we
12316 asked for, we don't want to crash. */
12317 rslt = hex2bin (target_buf, buf, len);
12318 return rslt;
12319 }
12320
12321 /* Something went wrong, flag as an error. */
12322 return -1;
12323}
12324
35b1e5cc 12325static void
37b25738 12326remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12327{
12328 struct remote_state *rs = get_remote_state ();
12329
4082afcc 12330 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12331 {
ad91cd99
PA
12332 char *reply;
12333
bba74b36 12334 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12335 putpkt (rs->buf);
ad91cd99
PA
12336 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12337 if (*reply == '\0')
33da3f1c 12338 error (_("Target does not support this command."));
ad91cd99
PA
12339 if (strcmp (reply, "OK") != 0)
12340 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12341 }
12342 else if (val)
12343 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12344}
12345
dc146f7c
VP
12346static int
12347remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12348{
12349 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12350
fe978cb0
PA
12351 if (info && info->priv)
12352 return info->priv->core;
dc146f7c
VP
12353 return -1;
12354}
12355
4daf5ac0 12356static void
736d5b1f 12357remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12358{
12359 struct remote_state *rs = get_remote_state ();
ad91cd99 12360 char *reply;
4daf5ac0 12361
bba74b36 12362 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12363 putpkt (rs->buf);
ad91cd99
PA
12364 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12365 if (*reply == '\0')
4daf5ac0 12366 error (_("Target does not support this command."));
ad91cd99
PA
12367 if (strcmp (reply, "OK") != 0)
12368 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12369}
12370
b3b9301e 12371static struct traceframe_info *
a893e81f 12372remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12373{
12374 char *text;
12375
12376 text = target_read_stralloc (&current_target,
12377 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12378 if (text != NULL)
12379 {
12380 struct traceframe_info *info;
12381 struct cleanup *back_to = make_cleanup (xfree, text);
12382
12383 info = parse_traceframe_info (text);
12384 do_cleanups (back_to);
12385 return info;
12386 }
12387
12388 return NULL;
12389}
12390
405f8e94
SS
12391/* Handle the qTMinFTPILen packet. Returns the minimum length of
12392 instruction on which a fast tracepoint may be placed. Returns -1
12393 if the packet is not supported, and 0 if the minimum instruction
12394 length is unknown. */
12395
12396static int
0e67620a 12397remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12398{
12399 struct remote_state *rs = get_remote_state ();
12400 char *reply;
12401
e886a173
PA
12402 /* If we're not debugging a process yet, the IPA can't be
12403 loaded. */
12404 if (!target_has_execution)
12405 return 0;
12406
12407 /* Make sure the remote is pointing at the right process. */
12408 set_general_process ();
12409
bba74b36 12410 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12411 putpkt (rs->buf);
12412 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12413 if (*reply == '\0')
12414 return -1;
12415 else
12416 {
12417 ULONGEST min_insn_len;
12418
12419 unpack_varlen_hex (reply, &min_insn_len);
12420
12421 return (int) min_insn_len;
12422 }
12423}
12424
f6f899bf 12425static void
4da384be 12426remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12427{
4082afcc 12428 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12429 {
12430 struct remote_state *rs = get_remote_state ();
12431 char *buf = rs->buf;
12432 char *endbuf = rs->buf + get_remote_packet_size ();
12433 enum packet_result result;
12434
12435 gdb_assert (val >= 0 || val == -1);
12436 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12437 /* Send -1 as literal "-1" to avoid host size dependency. */
12438 if (val < 0)
12439 {
12440 *buf++ = '-';
12441 buf += hexnumstr (buf, (ULONGEST) -val);
12442 }
12443 else
12444 buf += hexnumstr (buf, (ULONGEST) val);
12445
12446 putpkt (rs->buf);
12447 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12448 result = packet_ok (rs->buf,
12449 &remote_protocol_packets[PACKET_QTBuffer_size]);
12450
12451 if (result != PACKET_OK)
12452 warning (_("Bogus reply from target: %s"), rs->buf);
12453 }
12454}
12455
f196051f 12456static int
d9e68a2c
TT
12457remote_set_trace_notes (struct target_ops *self,
12458 const char *user, const char *notes,
ca623f82 12459 const char *stop_notes)
f196051f
SS
12460{
12461 struct remote_state *rs = get_remote_state ();
12462 char *reply;
12463 char *buf = rs->buf;
12464 char *endbuf = rs->buf + get_remote_packet_size ();
12465 int nbytes;
12466
12467 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12468 if (user)
12469 {
12470 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12471 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12472 buf += 2 * nbytes;
12473 *buf++ = ';';
12474 }
12475 if (notes)
12476 {
12477 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12478 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12479 buf += 2 * nbytes;
12480 *buf++ = ';';
12481 }
12482 if (stop_notes)
12483 {
12484 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12485 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12486 buf += 2 * nbytes;
12487 *buf++ = ';';
12488 }
12489 /* Ensure the buffer is terminated. */
12490 *buf = '\0';
12491
12492 putpkt (rs->buf);
12493 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12494 if (*reply == '\0')
12495 return 0;
12496
12497 if (strcmp (reply, "OK") != 0)
12498 error (_("Bogus reply from target: %s"), reply);
12499
12500 return 1;
12501}
12502
d1feda86 12503static int
2c152180 12504remote_use_agent (struct target_ops *self, int use)
d1feda86 12505{
4082afcc 12506 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12507 {
12508 struct remote_state *rs = get_remote_state ();
12509
12510 /* If the stub supports QAgent. */
bba74b36 12511 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12512 putpkt (rs->buf);
12513 getpkt (&rs->buf, &rs->buf_size, 0);
12514
12515 if (strcmp (rs->buf, "OK") == 0)
12516 {
12517 use_agent = use;
12518 return 1;
12519 }
12520 }
12521
12522 return 0;
12523}
12524
12525static int
fe38f897 12526remote_can_use_agent (struct target_ops *self)
d1feda86 12527{
4082afcc 12528 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12529}
12530
9accd112
MM
12531struct btrace_target_info
12532{
12533 /* The ptid of the traced thread. */
12534 ptid_t ptid;
f4abbc16
MM
12535
12536 /* The obtained branch trace configuration. */
12537 struct btrace_config conf;
9accd112
MM
12538};
12539
f4abbc16
MM
12540/* Reset our idea of our target's btrace configuration. */
12541
12542static void
12543remote_btrace_reset (void)
12544{
12545 struct remote_state *rs = get_remote_state ();
12546
12547 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12548}
12549
9accd112
MM
12550/* Check whether the target supports branch tracing. */
12551
12552static int
043c3577 12553remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12554{
4082afcc 12555 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12556 return 0;
4082afcc 12557 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12558 return 0;
12559
043c3577
MM
12560 switch (format)
12561 {
12562 case BTRACE_FORMAT_NONE:
12563 return 0;
12564
12565 case BTRACE_FORMAT_BTS:
12566 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12567
12568 case BTRACE_FORMAT_PT:
12569 /* The trace is decoded on the host. Even if our target supports it,
12570 we still need to have libipt to decode the trace. */
12571#if defined (HAVE_LIBIPT)
12572 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12573#else /* !defined (HAVE_LIBIPT) */
12574 return 0;
12575#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12576 }
12577
12578 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12579}
12580
f4abbc16
MM
12581/* Synchronize the configuration with the target. */
12582
12583static void
12584btrace_sync_conf (const struct btrace_config *conf)
12585{
d33501a5
MM
12586 struct packet_config *packet;
12587 struct remote_state *rs;
12588 char *buf, *pos, *endbuf;
12589
12590 rs = get_remote_state ();
12591 buf = rs->buf;
12592 endbuf = buf + get_remote_packet_size ();
12593
12594 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12595 if (packet_config_support (packet) == PACKET_ENABLE
12596 && conf->bts.size != rs->btrace_config.bts.size)
12597 {
12598 pos = buf;
12599 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12600 conf->bts.size);
12601
12602 putpkt (buf);
12603 getpkt (&buf, &rs->buf_size, 0);
12604
12605 if (packet_ok (buf, packet) == PACKET_ERROR)
12606 {
12607 if (buf[0] == 'E' && buf[1] == '.')
12608 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12609 else
12610 error (_("Failed to configure the BTS buffer size."));
12611 }
12612
12613 rs->btrace_config.bts.size = conf->bts.size;
12614 }
b20a6524
MM
12615
12616 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12617 if (packet_config_support (packet) == PACKET_ENABLE
12618 && conf->pt.size != rs->btrace_config.pt.size)
12619 {
12620 pos = buf;
12621 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12622 conf->pt.size);
12623
12624 putpkt (buf);
12625 getpkt (&buf, &rs->buf_size, 0);
12626
12627 if (packet_ok (buf, packet) == PACKET_ERROR)
12628 {
12629 if (buf[0] == 'E' && buf[1] == '.')
12630 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12631 else
12632 error (_("Failed to configure the trace buffer size."));
12633 }
12634
12635 rs->btrace_config.pt.size = conf->pt.size;
12636 }
f4abbc16
MM
12637}
12638
12639/* Read the current thread's btrace configuration from the target and
12640 store it into CONF. */
12641
12642static void
12643btrace_read_config (struct btrace_config *conf)
12644{
12645 char *xml;
12646
12647 xml = target_read_stralloc (&current_target,
b20a6524 12648 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12649 if (xml != NULL)
12650 {
12651 struct cleanup *cleanup;
12652
12653 cleanup = make_cleanup (xfree, xml);
12654 parse_xml_btrace_conf (conf, xml);
12655 do_cleanups (cleanup);
12656 }
12657}
12658
9accd112
MM
12659/* Enable branch tracing. */
12660
12661static struct btrace_target_info *
f4abbc16
MM
12662remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12663 const struct btrace_config *conf)
9accd112
MM
12664{
12665 struct btrace_target_info *tinfo = NULL;
b20a6524 12666 struct packet_config *packet = NULL;
9accd112
MM
12667 struct remote_state *rs = get_remote_state ();
12668 char *buf = rs->buf;
12669 char *endbuf = rs->buf + get_remote_packet_size ();
12670
b20a6524
MM
12671 switch (conf->format)
12672 {
12673 case BTRACE_FORMAT_BTS:
12674 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12675 break;
12676
12677 case BTRACE_FORMAT_PT:
12678 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12679 break;
12680 }
12681
12682 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12683 error (_("Target does not support branch tracing."));
12684
f4abbc16
MM
12685 btrace_sync_conf (conf);
12686
9accd112
MM
12687 set_general_thread (ptid);
12688
12689 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12690 putpkt (rs->buf);
12691 getpkt (&rs->buf, &rs->buf_size, 0);
12692
12693 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12694 {
12695 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12696 error (_("Could not enable branch tracing for %s: %s"),
12697 target_pid_to_str (ptid), rs->buf + 2);
12698 else
12699 error (_("Could not enable branch tracing for %s."),
12700 target_pid_to_str (ptid));
12701 }
12702
8d749320 12703 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12704 tinfo->ptid = ptid;
12705
f4abbc16
MM
12706 /* If we fail to read the configuration, we lose some information, but the
12707 tracing itself is not impacted. */
492d29ea
PA
12708 TRY
12709 {
12710 btrace_read_config (&tinfo->conf);
12711 }
12712 CATCH (err, RETURN_MASK_ERROR)
12713 {
12714 if (err.message != NULL)
12715 warning ("%s", err.message);
12716 }
12717 END_CATCH
f4abbc16 12718
9accd112
MM
12719 return tinfo;
12720}
12721
12722/* Disable branch tracing. */
12723
12724static void
25e95349
TT
12725remote_disable_btrace (struct target_ops *self,
12726 struct btrace_target_info *tinfo)
9accd112
MM
12727{
12728 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12729 struct remote_state *rs = get_remote_state ();
12730 char *buf = rs->buf;
12731 char *endbuf = rs->buf + get_remote_packet_size ();
12732
4082afcc 12733 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12734 error (_("Target does not support branch tracing."));
12735
12736 set_general_thread (tinfo->ptid);
12737
12738 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12739 putpkt (rs->buf);
12740 getpkt (&rs->buf, &rs->buf_size, 0);
12741
12742 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12743 {
12744 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12745 error (_("Could not disable branch tracing for %s: %s"),
12746 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12747 else
12748 error (_("Could not disable branch tracing for %s."),
12749 target_pid_to_str (tinfo->ptid));
12750 }
12751
12752 xfree (tinfo);
12753}
12754
12755/* Teardown branch tracing. */
12756
12757static void
1777056d
TT
12758remote_teardown_btrace (struct target_ops *self,
12759 struct btrace_target_info *tinfo)
9accd112
MM
12760{
12761 /* We must not talk to the target during teardown. */
12762 xfree (tinfo);
12763}
12764
12765/* Read the branch trace. */
12766
969c39fb 12767static enum btrace_error
39c49f83 12768remote_read_btrace (struct target_ops *self,
734b0e4b 12769 struct btrace_data *btrace,
969c39fb 12770 struct btrace_target_info *tinfo,
9accd112
MM
12771 enum btrace_read_type type)
12772{
12773 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12774 struct remote_state *rs = get_remote_state ();
969c39fb 12775 struct cleanup *cleanup;
9accd112
MM
12776 const char *annex;
12777 char *xml;
12778
4082afcc 12779 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12780 error (_("Target does not support branch tracing."));
12781
12782#if !defined(HAVE_LIBEXPAT)
12783 error (_("Cannot process branch tracing result. XML parsing not supported."));
12784#endif
12785
12786 switch (type)
12787 {
864089d2 12788 case BTRACE_READ_ALL:
9accd112
MM
12789 annex = "all";
12790 break;
864089d2 12791 case BTRACE_READ_NEW:
9accd112
MM
12792 annex = "new";
12793 break;
969c39fb
MM
12794 case BTRACE_READ_DELTA:
12795 annex = "delta";
12796 break;
9accd112
MM
12797 default:
12798 internal_error (__FILE__, __LINE__,
12799 _("Bad branch tracing read type: %u."),
12800 (unsigned int) type);
12801 }
12802
12803 xml = target_read_stralloc (&current_target,
b20a6524 12804 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12805 if (xml == NULL)
12806 return BTRACE_ERR_UNKNOWN;
9accd112 12807
969c39fb 12808 cleanup = make_cleanup (xfree, xml);
734b0e4b 12809 parse_xml_btrace (btrace, xml);
969c39fb 12810 do_cleanups (cleanup);
9accd112 12811
969c39fb 12812 return BTRACE_ERR_NONE;
9accd112
MM
12813}
12814
f4abbc16
MM
12815static const struct btrace_config *
12816remote_btrace_conf (struct target_ops *self,
12817 const struct btrace_target_info *tinfo)
12818{
12819 return &tinfo->conf;
12820}
12821
ced63ec0 12822static int
5436ff03 12823remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12824{
4082afcc
PA
12825 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12826 == PACKET_ENABLE);
ced63ec0
GB
12827}
12828
9dd130a0
TT
12829/* Implementation of to_load. */
12830
12831static void
9cbe5fff 12832remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12833{
12834 generic_load (name, from_tty);
12835}
12836
c78fa86a
GB
12837/* Accepts an integer PID; returns a string representing a file that
12838 can be opened on the remote side to get the symbols for the child
12839 process. Returns NULL if the operation is not supported. */
12840
12841static char *
12842remote_pid_to_exec_file (struct target_ops *self, int pid)
12843{
12844 static char *filename = NULL;
835205d0
GB
12845 struct inferior *inf;
12846 char *annex = NULL;
c78fa86a
GB
12847
12848 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12849 return NULL;
12850
12851 if (filename != NULL)
12852 xfree (filename);
12853
835205d0
GB
12854 inf = find_inferior_pid (pid);
12855 if (inf == NULL)
12856 internal_error (__FILE__, __LINE__,
12857 _("not currently attached to process %d"), pid);
12858
12859 if (!inf->fake_pid_p)
12860 {
12861 const int annex_size = 9;
12862
224c3ddb 12863 annex = (char *) alloca (annex_size);
835205d0
GB
12864 xsnprintf (annex, annex_size, "%x", pid);
12865 }
12866
c78fa86a
GB
12867 filename = target_read_stralloc (&current_target,
12868 TARGET_OBJECT_EXEC_FILE, annex);
12869
12870 return filename;
12871}
12872
750ce8d1
YQ
12873/* Implement the to_can_do_single_step target_ops method. */
12874
12875static int
12876remote_can_do_single_step (struct target_ops *ops)
12877{
12878 /* We can only tell whether target supports single step or not by
12879 supported s and S vCont actions if the stub supports vContSupported
12880 feature. If the stub doesn't support vContSupported feature,
12881 we have conservatively to think target doesn't supports single
12882 step. */
12883 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12884 {
12885 struct remote_state *rs = get_remote_state ();
12886
12887 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12888 remote_vcont_probe (rs);
12889
12890 return rs->supports_vCont.s && rs->supports_vCont.S;
12891 }
12892 else
12893 return 0;
12894}
12895
c906108c 12896static void
fba45db2 12897init_remote_ops (void)
c906108c 12898{
c5aa993b 12899 remote_ops.to_shortname = "remote";
c906108c 12900 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 12901 remote_ops.to_doc =
c906108c 12902 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
12903Specify the serial device it is connected to\n\
12904(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
12905 remote_ops.to_open = remote_open;
12906 remote_ops.to_close = remote_close;
c906108c 12907 remote_ops.to_detach = remote_detach;
6ad8ae5c 12908 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 12909 remote_ops.to_resume = remote_resume;
c906108c
SS
12910 remote_ops.to_wait = remote_wait;
12911 remote_ops.to_fetch_registers = remote_fetch_registers;
12912 remote_ops.to_store_registers = remote_store_registers;
12913 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 12914 remote_ops.to_files_info = remote_files_info;
c906108c
SS
12915 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12916 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
12917 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12918 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12919 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12920 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
12921 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12922 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
12923 remote_ops.to_watchpoint_addr_within_range =
12924 remote_watchpoint_addr_within_range;
3c3bea1c
GS
12925 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12926 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12927 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
12928 remote_ops.to_region_ok_for_hw_watchpoint
12929 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
12930 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12931 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 12932 remote_ops.to_kill = remote_kill;
9dd130a0 12933 remote_ops.to_load = remote_load;
c906108c 12934 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 12935 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 12936 remote_ops.to_program_signals = remote_program_signals;
c906108c 12937 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 12938 remote_ops.to_thread_name = remote_thread_name;
e8032dde 12939 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 12940 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 12941 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 12942 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 12943 remote_ops.to_stop = remote_stop;
bfedc46a 12944 remote_ops.to_interrupt = remote_interrupt;
abc56d60 12945 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
4b8a223f 12946 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 12947 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 12948 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 12949 remote_ops.to_log_command = serial_log_command;
38691318 12950 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 12951 remote_ops.to_stratum = process_stratum;
c35b1492
PA
12952 remote_ops.to_has_all_memory = default_child_has_all_memory;
12953 remote_ops.to_has_memory = default_child_has_memory;
12954 remote_ops.to_has_stack = default_child_has_stack;
12955 remote_ops.to_has_registers = default_child_has_registers;
12956 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 12957 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 12958 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 12959 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 12960 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
12961 remote_ops.to_flash_erase = remote_flash_erase;
12962 remote_ops.to_flash_done = remote_flash_done;
29709017 12963 remote_ops.to_read_description = remote_read_description;
08388c79 12964 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
12965 remote_ops.to_can_async_p = remote_can_async_p;
12966 remote_ops.to_is_async_p = remote_is_async_p;
12967 remote_ops.to_async = remote_async;
750ce8d1 12968 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
12969 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12970 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 12971 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 12972 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
12973 remote_ops.to_supports_disable_randomization
12974 = remote_supports_disable_randomization;
4bd7dc42 12975 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
12976 remote_ops.to_fileio_open = remote_hostio_open;
12977 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12978 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 12979 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
12980 remote_ops.to_fileio_close = remote_hostio_close;
12981 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 12982 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 12983 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 12984 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 12985 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 12986 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
12987 remote_ops.to_trace_init = remote_trace_init;
12988 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 12989 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
12990 remote_ops.to_download_trace_state_variable
12991 = remote_download_trace_state_variable;
d248b706
KY
12992 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12993 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
12994 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12995 remote_ops.to_trace_start = remote_trace_start;
12996 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 12997 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
12998 remote_ops.to_trace_stop = remote_trace_stop;
12999 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13000 remote_ops.to_get_trace_state_variable_value
13001 = remote_get_trace_state_variable_value;
00bf0b85
SS
13002 remote_ops.to_save_trace_data = remote_save_trace_data;
13003 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13004 remote_ops.to_upload_trace_state_variables
13005 = remote_upload_trace_state_variables;
00bf0b85 13006 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13007 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13008 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13009 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13010 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13011 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13012 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13013 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13014 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13015 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13016 remote_ops.to_static_tracepoint_marker_at
13017 = remote_static_tracepoint_marker_at;
13018 remote_ops.to_static_tracepoint_markers_by_strid
13019 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13020 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13021 remote_ops.to_use_agent = remote_use_agent;
13022 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13023 remote_ops.to_supports_btrace = remote_supports_btrace;
13024 remote_ops.to_enable_btrace = remote_enable_btrace;
13025 remote_ops.to_disable_btrace = remote_disable_btrace;
13026 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13027 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13028 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13029 remote_ops.to_augmented_libraries_svr4_read =
13030 remote_augmented_libraries_svr4_read;
c906108c
SS
13031}
13032
13033/* Set up the extended remote vector by making a copy of the standard
13034 remote vector and adding to it. */
13035
13036static void
fba45db2 13037init_extended_remote_ops (void)
c906108c
SS
13038{
13039 extended_remote_ops = remote_ops;
13040
0f71a2f6 13041 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13042 extended_remote_ops.to_longname =
c906108c 13043 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13044 extended_remote_ops.to_doc =
c906108c 13045 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13046Specify the serial device it is connected to (e.g. /dev/ttya).";
13047 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
13048 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13049 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
13050 extended_remote_ops.to_detach = extended_remote_detach;
13051 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13052 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 13053 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
13054 extended_remote_ops.to_supports_disable_randomization
13055 = extended_remote_supports_disable_randomization;
de0d863e 13056 extended_remote_ops.to_follow_fork = remote_follow_fork;
94585166 13057 extended_remote_ops.to_follow_exec = remote_follow_exec;
cbb8991c
DB
13058 extended_remote_ops.to_insert_fork_catchpoint
13059 = remote_insert_fork_catchpoint;
13060 extended_remote_ops.to_remove_fork_catchpoint
13061 = remote_remove_fork_catchpoint;
13062 extended_remote_ops.to_insert_vfork_catchpoint
13063 = remote_insert_vfork_catchpoint;
13064 extended_remote_ops.to_remove_vfork_catchpoint
13065 = remote_remove_vfork_catchpoint;
d46addbb
DB
13066 extended_remote_ops.to_insert_exec_catchpoint
13067 = remote_insert_exec_catchpoint;
13068 extended_remote_ops.to_remove_exec_catchpoint
13069 = remote_remove_exec_catchpoint;
0f71a2f6
JM
13070}
13071
6426a772 13072static int
6a109b6b 13073remote_can_async_p (struct target_ops *ops)
6426a772 13074{
5d93a237
TT
13075 struct remote_state *rs = get_remote_state ();
13076
c6ebd6cf 13077 if (!target_async_permitted)
75c99385
PA
13078 /* We only enable async when the user specifically asks for it. */
13079 return 0;
13080
23860348 13081 /* We're async whenever the serial device is. */
5d93a237 13082 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13083}
13084
13085static int
6a109b6b 13086remote_is_async_p (struct target_ops *ops)
6426a772 13087{
5d93a237
TT
13088 struct remote_state *rs = get_remote_state ();
13089
c6ebd6cf 13090 if (!target_async_permitted)
75c99385
PA
13091 /* We only enable async when the user specifically asks for it. */
13092 return 0;
13093
23860348 13094 /* We're async whenever the serial device is. */
5d93a237 13095 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13096}
13097
2acceee2
JM
13098/* Pass the SERIAL event on and up to the client. One day this code
13099 will be able to delay notifying the client of an event until the
23860348 13100 point where an entire packet has been received. */
2acceee2 13101
2acceee2
JM
13102static serial_event_ftype remote_async_serial_handler;
13103
6426a772 13104static void
819cc324 13105remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13106{
19ba03f4 13107 struct remote_state *rs = (struct remote_state *) context;
88b496c3 13108
2acceee2
JM
13109 /* Don't propogate error information up to the client. Instead let
13110 the client find out about the error by querying the target. */
6a3753b3 13111 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13112}
13113
74531fed
PA
13114static void
13115remote_async_inferior_event_handler (gdb_client_data data)
13116{
13117 inferior_event_handler (INF_REG_EVENT, NULL);
13118}
13119
2acceee2 13120static void
6a3753b3 13121remote_async (struct target_ops *ops, int enable)
2acceee2 13122{
5d93a237
TT
13123 struct remote_state *rs = get_remote_state ();
13124
6a3753b3 13125 if (enable)
2acceee2 13126 {
88b496c3 13127 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13128
13129 /* If there are pending events in the stop reply queue tell the
13130 event loop to process them. */
13131 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13132 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13133 /* For simplicity, below we clear the pending events token
13134 without remembering whether it is marked, so here we always
13135 mark it. If there's actually no pending notification to
13136 process, this ends up being a no-op (other than a spurious
13137 event-loop wakeup). */
13138 if (target_is_non_stop_p ())
13139 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13140 }
13141 else
b7d2e916
PA
13142 {
13143 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13144 /* If the core is disabling async, it doesn't want to be
13145 disturbed with target events. Clear all async event sources
13146 too. */
b7d2e916 13147 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13148 if (target_is_non_stop_p ())
13149 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13150 }
6426a772
JM
13151}
13152
5a2468f5 13153static void
c2d11a7d 13154set_remote_cmd (char *args, int from_tty)
5a2468f5 13155{
635c7e8a 13156 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13157}
13158
d471ea57
AC
13159static void
13160show_remote_cmd (char *args, int from_tty)
13161{
37a105a1 13162 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13163 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13164 struct cleanup *showlist_chain;
13165 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13166 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13167
13168 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13169 for (; list != NULL; list = list->next)
13170 if (strcmp (list->name, "Z-packet") == 0)
13171 continue;
427c3a89
DJ
13172 else if (list->type == not_set_cmd)
13173 /* Alias commands are exactly like the original, except they
13174 don't have the normal type. */
13175 continue;
13176 else
37a105a1
DJ
13177 {
13178 struct cleanup *option_chain
13179 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13180
37a105a1
DJ
13181 ui_out_field_string (uiout, "name", list->name);
13182 ui_out_text (uiout, ": ");
427c3a89 13183 if (list->type == show_cmd)
5b9afe8a 13184 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
13185 else
13186 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13187 /* Close the tuple. */
13188 do_cleanups (option_chain);
13189 }
427c3a89
DJ
13190
13191 /* Close the tuple. */
13192 do_cleanups (showlist_chain);
d471ea57 13193}
5a2468f5 13194
0f71a2f6 13195
23860348 13196/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13197static void
13198remote_new_objfile (struct objfile *objfile)
13199{
5d93a237
TT
13200 struct remote_state *rs = get_remote_state ();
13201
13202 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13203 remote_check_symbols ();
dc8acb97
MS
13204}
13205
00bf0b85
SS
13206/* Pull all the tracepoints defined on the target and create local
13207 data structures representing them. We don't want to create real
13208 tracepoints yet, we don't want to mess up the user's existing
13209 collection. */
13210
13211static int
ab6617cc 13212remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13213{
00bf0b85
SS
13214 struct remote_state *rs = get_remote_state ();
13215 char *p;
d5551862 13216
00bf0b85
SS
13217 /* Ask for a first packet of tracepoint definition. */
13218 putpkt ("qTfP");
13219 getpkt (&rs->buf, &rs->buf_size, 0);
13220 p = rs->buf;
13221 while (*p && *p != 'l')
d5551862 13222 {
00bf0b85
SS
13223 parse_tracepoint_definition (p, utpp);
13224 /* Ask for another packet of tracepoint definition. */
13225 putpkt ("qTsP");
13226 getpkt (&rs->buf, &rs->buf_size, 0);
13227 p = rs->buf;
d5551862 13228 }
00bf0b85 13229 return 0;
d5551862
SS
13230}
13231
00bf0b85 13232static int
181e3713
TT
13233remote_upload_trace_state_variables (struct target_ops *self,
13234 struct uploaded_tsv **utsvp)
d5551862 13235{
00bf0b85 13236 struct remote_state *rs = get_remote_state ();
d5551862 13237 char *p;
d5551862 13238
00bf0b85
SS
13239 /* Ask for a first packet of variable definition. */
13240 putpkt ("qTfV");
d5551862
SS
13241 getpkt (&rs->buf, &rs->buf_size, 0);
13242 p = rs->buf;
00bf0b85 13243 while (*p && *p != 'l')
d5551862 13244 {
00bf0b85
SS
13245 parse_tsv_definition (p, utsvp);
13246 /* Ask for another packet of variable definition. */
13247 putpkt ("qTsV");
d5551862
SS
13248 getpkt (&rs->buf, &rs->buf_size, 0);
13249 p = rs->buf;
13250 }
00bf0b85 13251 return 0;
d5551862
SS
13252}
13253
c1e36e3e
PA
13254/* The "set/show range-stepping" show hook. */
13255
13256static void
13257show_range_stepping (struct ui_file *file, int from_tty,
13258 struct cmd_list_element *c,
13259 const char *value)
13260{
13261 fprintf_filtered (file,
13262 _("Debugger's willingness to use range stepping "
13263 "is %s.\n"), value);
13264}
13265
13266/* The "set/show range-stepping" set hook. */
13267
13268static void
13269set_range_stepping (char *ignore_args, int from_tty,
13270 struct cmd_list_element *c)
13271{
5d93a237
TT
13272 struct remote_state *rs = get_remote_state ();
13273
c1e36e3e
PA
13274 /* Whene enabling, check whether range stepping is actually
13275 supported by the target, and warn if not. */
13276 if (use_range_stepping)
13277 {
5d93a237 13278 if (rs->remote_desc != NULL)
c1e36e3e 13279 {
4082afcc 13280 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13281 remote_vcont_probe (rs);
13282
4082afcc 13283 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13284 && rs->supports_vCont.r)
13285 return;
13286 }
13287
13288 warning (_("Range stepping is not supported by the current target"));
13289 }
13290}
13291
c906108c 13292void
fba45db2 13293_initialize_remote (void)
c906108c 13294{
ea9c271d 13295 struct remote_state *rs;
9a7071a8 13296 struct cmd_list_element *cmd;
6f937416 13297 const char *cmd_name;
ea9c271d 13298
0f71a2f6 13299 /* architecture specific data */
2bc416ba 13300 remote_gdbarch_data_handle =
23860348 13301 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13302 remote_g_packet_data_handle =
13303 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13304
94585166
DB
13305 remote_pspace_data
13306 = register_program_space_data_with_cleanup (NULL,
13307 remote_pspace_data_cleanup);
13308
ea9c271d
DJ
13309 /* Initialize the per-target state. At the moment there is only one
13310 of these, not one per target. Only one target is active at a
cf792862
TT
13311 time. */
13312 remote_state = new_remote_state ();
ea9c271d 13313
c906108c
SS
13314 init_remote_ops ();
13315 add_target (&remote_ops);
13316
13317 init_extended_remote_ops ();
13318 add_target (&extended_remote_ops);
cce74817 13319
dc8acb97 13320 /* Hook into new objfile notification. */
06d3b283 13321 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13322 /* We're no longer interested in notification events of an inferior
13323 when it exits. */
13324 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13325
b803fb0f 13326 /* Set up signal handlers. */
934b9bac 13327 async_sigint_remote_token =
b803fb0f 13328 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 13329 async_sigint_remote_twice_token =
6d549500 13330 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 13331
c906108c
SS
13332#if 0
13333 init_remote_threadtests ();
13334#endif
13335
722247f1 13336 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13337 /* set/show remote ... */
d471ea57 13338
1bedd215 13339 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13340Remote protocol specific variables\n\
13341Configure various remote-protocol specific variables such as\n\
1bedd215 13342the packets being used"),
cff3e48b 13343 &remote_set_cmdlist, "set remote ",
23860348 13344 0 /* allow-unknown */, &setlist);
1bedd215 13345 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13346Remote protocol specific variables\n\
13347Configure various remote-protocol specific variables such as\n\
1bedd215 13348the packets being used"),
cff3e48b 13349 &remote_show_cmdlist, "show remote ",
23860348 13350 0 /* allow-unknown */, &showlist);
5a2468f5 13351
1a966eab
AC
13352 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13353Compare section data on target to the exec file.\n\
95cf3b38
DT
13354Argument is a single section name (default: all loaded sections).\n\
13355To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13356 &cmdlist);
13357
1a966eab
AC
13358 add_cmd ("packet", class_maintenance, packet_command, _("\
13359Send an arbitrary packet to a remote target.\n\
c906108c
SS
13360 maintenance packet TEXT\n\
13361If GDB is talking to an inferior via the GDB serial protocol, then\n\
13362this command sends the string TEXT to the inferior, and displays the\n\
13363response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13364terminating `#' character and checksum."),
c906108c
SS
13365 &maintenancelist);
13366
7915a72c
AC
13367 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13368Set whether to send break if interrupted."), _("\
13369Show whether to send break if interrupted."), _("\
13370If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13371 set_remotebreak, show_remotebreak,
e707bbc2 13372 &setlist, &showlist);
9a7071a8
JB
13373 cmd_name = "remotebreak";
13374 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13375 deprecate_cmd (cmd, "set remote interrupt-sequence");
13376 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13377 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13378 deprecate_cmd (cmd, "show remote interrupt-sequence");
13379
13380 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13381 interrupt_sequence_modes, &interrupt_sequence_mode,
13382 _("\
9a7071a8
JB
13383Set interrupt sequence to remote target."), _("\
13384Show interrupt sequence to remote target."), _("\
13385Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13386 NULL, show_interrupt_sequence,
13387 &remote_set_cmdlist,
13388 &remote_show_cmdlist);
13389
13390 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13391 &interrupt_on_connect, _("\
13392Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13393Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13394If set, interrupt sequence is sent to remote target."),
13395 NULL, NULL,
13396 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13397
23860348 13398 /* Install commands for configuring memory read/write packets. */
11cf8741 13399
1a966eab
AC
13400 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13401Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13402 &setlist);
1a966eab
AC
13403 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13404Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13405 &showlist);
13406 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13407 set_memory_write_packet_size, _("\
13408Set the maximum number of bytes per memory-write packet.\n\
13409Specify the number of bytes in a packet or 0 (zero) for the\n\
13410default packet size. The actual limit is further reduced\n\
13411dependent on the target. Specify ``fixed'' to disable the\n\
13412further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13413 &remote_set_cmdlist);
13414 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13415 set_memory_read_packet_size, _("\
13416Set the maximum number of bytes per memory-read packet.\n\
13417Specify the number of bytes in a packet or 0 (zero) for the\n\
13418default packet size. The actual limit is further reduced\n\
13419dependent on the target. Specify ``fixed'' to disable the\n\
13420further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13421 &remote_set_cmdlist);
13422 add_cmd ("memory-write-packet-size", no_class,
13423 show_memory_write_packet_size,
1a966eab 13424 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13425 &remote_show_cmdlist);
13426 add_cmd ("memory-read-packet-size", no_class,
13427 show_memory_read_packet_size,
1a966eab 13428 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13429 &remote_show_cmdlist);
c906108c 13430
b3f42336 13431 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13432 &remote_hw_watchpoint_limit, _("\
13433Set the maximum number of target hardware watchpoints."), _("\
13434Show the maximum number of target hardware watchpoints."), _("\
13435Specify a negative limit for unlimited."),
3e43a32a
MS
13436 NULL, NULL, /* FIXME: i18n: The maximum
13437 number of target hardware
13438 watchpoints is %s. */
b3f42336 13439 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13440 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13441 &remote_hw_watchpoint_length_limit, _("\
13442Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13443Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13444Specify a negative limit for unlimited."),
13445 NULL, NULL, /* FIXME: i18n: The maximum
13446 length (in bytes) of a target
13447 hardware watchpoint is %s. */
13448 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13449 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13450 &remote_hw_breakpoint_limit, _("\
13451Set the maximum number of target hardware breakpoints."), _("\
13452Show the maximum number of target hardware breakpoints."), _("\
13453Specify a negative limit for unlimited."),
3e43a32a
MS
13454 NULL, NULL, /* FIXME: i18n: The maximum
13455 number of target hardware
13456 breakpoints is %s. */
b3f42336 13457 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13458
1b493192
PA
13459 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13460 &remote_address_size, _("\
4d28ad1e
AC
13461Set the maximum size of the address (in bits) in a memory packet."), _("\
13462Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13463 NULL,
13464 NULL, /* FIXME: i18n: */
13465 &setlist, &showlist);
c906108c 13466
ca4f7f8b
PA
13467 init_all_packet_configs ();
13468
444abaca 13469 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13470 "X", "binary-download", 1);
0f71a2f6 13471
444abaca 13472 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13473 "vCont", "verbose-resume", 0);
506fb367 13474
89be2091
DJ
13475 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13476 "QPassSignals", "pass-signals", 0);
13477
9b224c5e
PA
13478 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13479 "QProgramSignals", "program-signals", 0);
13480
444abaca 13481 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13482 "qSymbol", "symbol-lookup", 0);
dc8acb97 13483
444abaca 13484 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13485 "P", "set-register", 1);
d471ea57 13486
444abaca 13487 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13488 "p", "fetch-register", 1);
b96ec7ac 13489
444abaca 13490 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13491 "Z0", "software-breakpoint", 0);
d471ea57 13492
444abaca 13493 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13494 "Z1", "hardware-breakpoint", 0);
d471ea57 13495
444abaca 13496 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13497 "Z2", "write-watchpoint", 0);
d471ea57 13498
444abaca 13499 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13500 "Z3", "read-watchpoint", 0);
d471ea57 13501
444abaca 13502 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13503 "Z4", "access-watchpoint", 0);
d471ea57 13504
0876f84a
DJ
13505 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13506 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13507
c78fa86a
GB
13508 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13509 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13510
23181151
DJ
13511 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13512 "qXfer:features:read", "target-features", 0);
13513
cfa9d6d9
DJ
13514 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13515 "qXfer:libraries:read", "library-info", 0);
13516
2268b414
JK
13517 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13518 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13519
fd79ecee
DJ
13520 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13521 "qXfer:memory-map:read", "memory-map", 0);
13522
0e7f50da
UW
13523 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13524 "qXfer:spu:read", "read-spu-object", 0);
13525
13526 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13527 "qXfer:spu:write", "write-spu-object", 0);
13528
07e059b5
VP
13529 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13530 "qXfer:osdata:read", "osdata", 0);
13531
dc146f7c
VP
13532 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13533 "qXfer:threads:read", "threads", 0);
13534
4aa995e1
PA
13535 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13536 "qXfer:siginfo:read", "read-siginfo-object", 0);
13537
13538 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13539 "qXfer:siginfo:write", "write-siginfo-object", 0);
13540
b3b9301e
PA
13541 add_packet_config_cmd
13542 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13543 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13544
169081d0
TG
13545 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13546 "qXfer:uib:read", "unwind-info-block", 0);
13547
444abaca 13548 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13549 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13550 0);
13551
711e434b
PM
13552 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13553 "qGetTIBAddr", "get-thread-information-block-address",
13554 0);
13555
40ab02ce
MS
13556 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13557 "bc", "reverse-continue", 0);
13558
13559 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13560 "bs", "reverse-step", 0);
13561
be2a5f71
DJ
13562 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13563 "qSupported", "supported-packets", 0);
13564
08388c79
DE
13565 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13566 "qSearch:memory", "search-memory", 0);
13567
bd3eecc3
PA
13568 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13569 "qTStatus", "trace-status", 0);
13570
15a201c8
GB
13571 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13572 "vFile:setfs", "hostio-setfs", 0);
13573
a6b151f1
DJ
13574 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13575 "vFile:open", "hostio-open", 0);
13576
13577 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13578 "vFile:pread", "hostio-pread", 0);
13579
13580 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13581 "vFile:pwrite", "hostio-pwrite", 0);
13582
13583 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13584 "vFile:close", "hostio-close", 0);
13585
13586 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13587 "vFile:unlink", "hostio-unlink", 0);
13588
b9e7b9c3
UW
13589 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13590 "vFile:readlink", "hostio-readlink", 0);
13591
0a93529c
GB
13592 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13593 "vFile:fstat", "hostio-fstat", 0);
13594
2d717e4f
DJ
13595 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13596 "vAttach", "attach", 0);
13597
13598 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13599 "vRun", "run", 0);
13600
a6f3e723
SL
13601 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13602 "QStartNoAckMode", "noack", 0);
13603
82f73884
PA
13604 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13605 "vKill", "kill", 0);
13606
0b16c5cf
PA
13607 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13608 "qAttached", "query-attached", 0);
13609
782b2b07 13610 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13611 "ConditionalTracepoints",
13612 "conditional-tracepoints", 0);
3788aec7
LM
13613
13614 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13615 "ConditionalBreakpoints",
13616 "conditional-breakpoints", 0);
13617
d3ce09f5
SS
13618 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13619 "BreakpointCommands",
13620 "breakpoint-commands", 0);
13621
7a697b8d
SS
13622 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13623 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13624
409873ef
SS
13625 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13626 "TracepointSource", "TracepointSource", 0);
13627
d914c394
SS
13628 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13629 "QAllow", "allow", 0);
13630
0fb4aa4b
PA
13631 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13632 "StaticTracepoints", "static-tracepoints", 0);
13633
1e4d1764
YQ
13634 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13635 "InstallInTrace", "install-in-trace", 0);
13636
0fb4aa4b
PA
13637 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13638 "qXfer:statictrace:read", "read-sdata-object", 0);
13639
78d85199
YQ
13640 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13641 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13642
03583c20
UW
13643 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13644 "QDisableRandomization", "disable-randomization", 0);
13645
d1feda86
YQ
13646 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13647 "QAgent", "agent", 0);
13648
f6f899bf
HAQ
13649 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13650 "QTBuffer:size", "trace-buffer-size", 0);
13651
9accd112
MM
13652 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13653 "Qbtrace:off", "disable-btrace", 0);
13654
13655 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13656 "Qbtrace:bts", "enable-btrace-bts", 0);
13657
13658 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13659 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13660
13661 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13662 "qXfer:btrace", "read-btrace", 0);
13663
f4abbc16
MM
13664 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13665 "qXfer:btrace-conf", "read-btrace-conf", 0);
13666
d33501a5
MM
13667 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13668 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13669
73b8c1fd
PA
13670 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13671 "multiprocess-feature", "multiprocess-feature", 0);
13672
f7e6eed5
PA
13673 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13674 "swbreak-feature", "swbreak-feature", 0);
13675
13676 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13677 "hwbreak-feature", "hwbreak-feature", 0);
13678
89245bc0
DB
13679 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13680 "fork-event-feature", "fork-event-feature", 0);
13681
13682 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13683 "vfork-event-feature", "vfork-event-feature", 0);
13684
b20a6524
MM
13685 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13686 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13687
750ce8d1
YQ
13688 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13689 "vContSupported", "verbose-resume-supported", 0);
13690
94585166
DB
13691 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13692 "exec-event-feature", "exec-event-feature", 0);
13693
de979965
PA
13694 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13695 "vCtrlC", "ctrl-c", 0);
13696
0b736949
DB
13697 /* Assert that we've registered "set remote foo-packet" commands
13698 for all packet configs. */
ca4f7f8b
PA
13699 {
13700 int i;
13701
13702 for (i = 0; i < PACKET_MAX; i++)
13703 {
13704 /* Ideally all configs would have a command associated. Some
13705 still don't though. */
13706 int excepted;
13707
13708 switch (i)
13709 {
13710 case PACKET_QNonStop:
ca4f7f8b
PA
13711 case PACKET_EnableDisableTracepoints_feature:
13712 case PACKET_tracenz_feature:
13713 case PACKET_DisconnectedTracing_feature:
13714 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13715 case PACKET_qCRC:
13716 /* Additions to this list need to be well justified:
13717 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13718 excepted = 1;
13719 break;
13720 default:
13721 excepted = 0;
13722 break;
13723 }
13724
13725 /* This catches both forgetting to add a config command, and
13726 forgetting to remove a packet from the exception list. */
13727 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13728 }
13729 }
13730
37a105a1
DJ
13731 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13732 Z sub-packet has its own set and show commands, but users may
13733 have sets to this variable in their .gdbinit files (or in their
13734 documentation). */
e9e68a56 13735 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13736 &remote_Z_packet_detect, _("\
13737Set use of remote protocol `Z' packets"), _("\
13738Show use of remote protocol `Z' packets "), _("\
3b64bf98 13739When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13740packets."),
e9e68a56 13741 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13742 show_remote_protocol_Z_packet_cmd,
13743 /* FIXME: i18n: Use of remote protocol
13744 `Z' packets is %s. */
e9e68a56 13745 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13746
a6b151f1
DJ
13747 add_prefix_cmd ("remote", class_files, remote_command, _("\
13748Manipulate files on the remote system\n\
13749Transfer files to and from the remote target system."),
13750 &remote_cmdlist, "remote ",
13751 0 /* allow-unknown */, &cmdlist);
13752
13753 add_cmd ("put", class_files, remote_put_command,
13754 _("Copy a local file to the remote system."),
13755 &remote_cmdlist);
13756
13757 add_cmd ("get", class_files, remote_get_command,
13758 _("Copy a remote file to the local system."),
13759 &remote_cmdlist);
13760
13761 add_cmd ("delete", class_files, remote_delete_command,
13762 _("Delete a remote file."),
13763 &remote_cmdlist);
13764
2d717e4f 13765 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13766 &remote_exec_file_var, _("\
2d717e4f 13767Set the remote pathname for \"run\""), _("\
94585166
DB
13768Show the remote pathname for \"run\""), NULL,
13769 set_remote_exec_file,
13770 show_remote_exec_file,
13771 &remote_set_cmdlist,
13772 &remote_show_cmdlist);
2d717e4f 13773
c1e36e3e
PA
13774 add_setshow_boolean_cmd ("range-stepping", class_run,
13775 &use_range_stepping, _("\
13776Enable or disable range stepping."), _("\
13777Show whether target-assisted range stepping is enabled."), _("\
13778If on, and the target supports it, when stepping a source line, GDB\n\
13779tells the target to step the corresponding range of addresses itself instead\n\
13780of issuing multiple single-steps. This speeds up source level\n\
13781stepping. If off, GDB always issues single-steps, even if range\n\
13782stepping is supported by the target. The default is on."),
13783 set_range_stepping,
13784 show_range_stepping,
13785 &setlist,
13786 &showlist);
13787
449092f6
CV
13788 /* Eventually initialize fileio. See fileio.c */
13789 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13790
ba348170 13791 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13792 special ptids with it set to != 0. */
ba348170
PA
13793 magic_null_ptid = ptid_build (42000, -1, 1);
13794 not_sent_ptid = ptid_build (42000, -2, 1);
13795 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13796
13797 target_buf_size = 2048;
224c3ddb 13798 target_buf = (char *) xmalloc (target_buf_size);
c906108c 13799}
10760264 13800
This page took 3.036992 seconds and 4 git commands to generate.