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