]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
btrace: fix test build error in gdb.btrace/instruction_history.c
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
618f726f 3 Copyright (C) 1988-2016 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
35b1e5cc 73
0df8b418 74/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
75static char *target_buf;
76static long target_buf_size;
35b1e5cc 77
94585166
DB
78/* Per-program-space data key. */
79static const struct program_space_data *remote_pspace_data;
80
81/* The variable registered as the control variable used by the
82 remote exec-file commands. While the remote exec-file setting is
83 per-program-space, the set/show machinery uses this as the
84 location of the remote exec-file value. */
85static char *remote_exec_file_var;
86
6765f3e5
DJ
87/* The size to align memory write packets, when practical. The protocol
88 does not guarantee any alignment, and gdb will generate short
89 writes and unaligned writes, but even as a best-effort attempt this
90 can improve bulk transfers. For instance, if a write is misaligned
91 relative to the target's data bus, the stub may need to make an extra
92 round trip fetching data from the target. This doesn't make a
93 huge difference, but it's easy to do, so we try to be helpful.
94
95 The alignment chosen is arbitrary; usually data bus width is
96 important here, not the possibly larger cache line size. */
97enum { REMOTE_ALIGN_WRITES = 16 };
98
23860348 99/* Prototypes for local functions. */
6d820c5c 100static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 101static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 102 int forever, int *is_notif);
6426a772 103
a14ed312 104static void remote_files_info (struct target_ops *ignore);
c906108c 105
f32dbf8c
MM
106static void remote_prepare_to_store (struct target_ops *self,
107 struct regcache *regcache);
c906108c 108
014f9477
TT
109static void remote_open_1 (const char *, int, struct target_ops *,
110 int extended_p);
c906108c 111
de90e03d 112static void remote_close (struct target_ops *self);
c906108c 113
cbb8991c
DB
114struct remote_state;
115
116static int remote_vkill (int pid, struct remote_state *rs);
117
8020350c
DB
118static void remote_kill_k (void);
119
136d6dae 120static void remote_mourn (struct target_ops *ops);
c906108c 121
a14ed312 122static void extended_remote_restart (void);
c906108c 123
6d820c5c 124static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 125
a14ed312 126static int readchar (int timeout);
c906108c 127
c33e31fd
PA
128static void remote_serial_write (const char *str, int len);
129
7d85a9c0 130static void remote_kill (struct target_ops *ops);
c906108c 131
6a109b6b 132static int remote_can_async_p (struct target_ops *);
75c99385 133
6a109b6b 134static int remote_is_async_p (struct target_ops *);
75c99385 135
6a3753b3 136static void remote_async (struct target_ops *ops, int enable);
75c99385 137
65706a29
PA
138static void remote_thread_events (struct target_ops *ops, int enable);
139
a14ed312 140static void interrupt_query (void);
c906108c 141
79d7f229
PA
142static void set_general_thread (struct ptid ptid);
143static void set_continue_thread (struct ptid ptid);
c906108c 144
a14ed312 145static void get_offsets (void);
c906108c 146
6d820c5c
DJ
147static void skip_frame (void);
148
149static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 150
a14ed312 151static int hexnumlen (ULONGEST num);
c906108c 152
a14ed312 153static void init_remote_ops (void);
c906108c 154
a14ed312 155static void init_extended_remote_ops (void);
c906108c 156
1eab8a48 157static void remote_stop (struct target_ops *self, ptid_t);
c906108c 158
a14ed312 159static int stubhex (int ch);
c906108c 160
a14ed312 161static int hexnumstr (char *, ULONGEST);
c906108c 162
a14ed312 163static int hexnumnstr (char *, ULONGEST, int);
2df3850c 164
a14ed312 165static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 166
baa336ce 167static void print_packet (const char *);
c906108c 168
a14ed312 169static void compare_sections_command (char *, int);
c906108c 170
a14ed312 171static void packet_command (char *, int);
c906108c 172
a14ed312 173static int stub_unpack_int (char *buff, int fieldlength);
c906108c 174
39f77062 175static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 176
baa336ce 177static int putpkt_binary (const char *buf, int cnt);
c906108c 178
a14ed312 179static void check_binary_download (CORE_ADDR addr);
c906108c 180
5a2468f5 181struct packet_config;
5a2468f5 182
a14ed312 183static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 184
bb572ddd
DJ
185static void show_remote_protocol_packet_cmd (struct ui_file *file,
186 int from_tty,
187 struct cmd_list_element *c,
188 const char *value);
189
82f73884
PA
190static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
191static ptid_t read_ptid (char *buf, char **obuf);
192
c378d69d 193static void remote_set_permissions (struct target_ops *self);
d914c394 194
8bd200f1
TT
195static int remote_get_trace_status (struct target_ops *self,
196 struct trace_status *ts);
d5551862 197
ab6617cc
TT
198static int remote_upload_tracepoints (struct target_ops *self,
199 struct uploaded_tp **utpp);
00bf0b85 200
181e3713
TT
201static int remote_upload_trace_state_variables (struct target_ops *self,
202 struct uploaded_tsv **utsvp);
00bf0b85 203
c8d104ad
PA
204static void remote_query_supported (void);
205
36d25514 206static void remote_check_symbols (void);
c8d104ad 207
a14ed312 208void _initialize_remote (void);
c906108c 209
74531fed 210struct stop_reply;
74531fed 211static void stop_reply_xfree (struct stop_reply *);
722247f1 212static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 213static void push_stop_reply (struct stop_reply *);
bcc75809 214static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
215static int peek_stop_reply (ptid_t ptid);
216
cbb8991c
DB
217struct threads_listing_context;
218static void remove_new_fork_children (struct threads_listing_context *);
219
74531fed 220static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 221
e3594fd1 222static void remote_terminal_ours (struct target_ops *self);
d3fd5342 223
d962ef82
DJ
224static int remote_read_description_p (struct target_ops *target);
225
176a6961 226static void remote_console_output (char *msg);
dde08ee1 227
efcc2da7 228static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 229
78eff0ec 230static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 231
f4abbc16
MM
232static void remote_btrace_reset (void);
233
221e1a37
PA
234static int stop_reply_queue_length (void);
235
80152258
PA
236static void readahead_cache_invalidate (void);
237
048094ac
PA
238static void remote_unpush_and_throw (void);
239
a6b151f1
DJ
240/* For "remote". */
241
242static struct cmd_list_element *remote_cmdlist;
243
bb572ddd
DJ
244/* For "set remote" and "show remote". */
245
246static struct cmd_list_element *remote_set_cmdlist;
247static struct cmd_list_element *remote_show_cmdlist;
248
d458bd84
PA
249/* Stub vCont actions support.
250
251 Each field is a boolean flag indicating whether the stub reports
252 support for the corresponding action. */
253
254struct vCont_action_support
255{
256 /* vCont;t */
257 int t;
c1e36e3e
PA
258
259 /* vCont;r */
260 int r;
750ce8d1
YQ
261
262 /* vCont;s */
263 int s;
264
265 /* vCont;S */
266 int S;
d458bd84
PA
267};
268
c1e36e3e
PA
269/* Controls whether GDB is willing to use range stepping. */
270
271static int use_range_stepping = 1;
272
0d031856
TT
273#define OPAQUETHREADBYTES 8
274
275/* a 64 bit opaque identifier */
276typedef unsigned char threadref[OPAQUETHREADBYTES];
277
278/* About this many threadisds fit in a packet. */
279
280#define MAXTHREADLISTRESULTS 32
281
80152258
PA
282/* Data for the vFile:pread readahead cache. */
283
284struct readahead_cache
285{
286 /* The file descriptor for the file that is being cached. -1 if the
287 cache is invalid. */
288 int fd;
289
290 /* The offset into the file that the cache buffer corresponds
291 to. */
292 ULONGEST offset;
293
294 /* The buffer holding the cache contents. */
295 gdb_byte *buf;
296 /* The buffer's size. We try to read as much as fits into a packet
297 at a time. */
298 size_t bufsize;
299
300 /* Cache hit and miss counters. */
301 ULONGEST hit_count;
302 ULONGEST miss_count;
303};
304
ea9c271d
DJ
305/* Description of the remote protocol state for the currently
306 connected target. This is per-target state, and independent of the
307 selected architecture. */
308
309struct remote_state
310{
311 /* A buffer to use for incoming packets, and its current size. The
312 buffer is grown dynamically for larger incoming packets.
313 Outgoing packets may also be constructed in this buffer.
314 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
315 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
316 packets. */
317 char *buf;
318 long buf_size;
be2a5f71 319
1e51243a
PA
320 /* True if we're going through initial connection setup (finding out
321 about the remote side's threads, relocating symbols, etc.). */
322 int starting_up;
323
be2a5f71
DJ
324 /* If we negotiated packet size explicitly (and thus can bypass
325 heuristics for the largest packet size that will not overflow
326 a buffer in the stub), this will be set to that packet size.
327 Otherwise zero, meaning to use the guessed size. */
328 long explicit_packet_size;
2d717e4f
DJ
329
330 /* remote_wait is normally called when the target is running and
331 waits for a stop reply packet. But sometimes we need to call it
332 when the target is already stopped. We can send a "?" packet
333 and have remote_wait read the response. Or, if we already have
334 the response, we can stash it in BUF and tell remote_wait to
335 skip calling getpkt. This flag is set when BUF contains a
336 stop reply packet and the target is not waiting. */
337 int cached_wait_status;
a6f3e723
SL
338
339 /* True, if in no ack mode. That is, neither GDB nor the stub will
340 expect acks from each other. The connection is assumed to be
341 reliable. */
342 int noack_mode;
82f73884
PA
343
344 /* True if we're connected in extended remote mode. */
345 int extended;
346
e24a49d8
PA
347 /* True if we resumed the target and we're waiting for the target to
348 stop. In the mean time, we can't start another command/query.
349 The remote server wouldn't be ready to process it, so we'd
350 timeout waiting for a reply that would never come and eventually
351 we'd close the connection. This can happen in asynchronous mode
352 because we allow GDB commands while the target is running. */
353 int waiting_for_stop_reply;
74531fed 354
d458bd84
PA
355 /* The status of the stub support for the various vCont actions. */
356 struct vCont_action_support supports_vCont;
782b2b07 357
3a29589a
DJ
358 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
359 responded to that. */
360 int ctrlc_pending_p;
5d93a237 361
048094ac
PA
362 /* True if we saw a Ctrl-C while reading or writing from/to the
363 remote descriptor. At that point it is not safe to send a remote
364 interrupt packet, so we instead remember we saw the Ctrl-C and
365 process it once we're done with sending/receiving the current
366 packet, which should be shortly. If however that takes too long,
367 and the user presses Ctrl-C again, we offer to disconnect. */
368 int got_ctrlc_during_io;
369
5d93a237
TT
370 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
371 remote_open knows that we don't have a file open when the program
372 starts. */
373 struct serial *remote_desc;
47f8a51d
TT
374
375 /* These are the threads which we last sent to the remote system. The
376 TID member will be -1 for all or -2 for not sent yet. */
377 ptid_t general_thread;
378 ptid_t continue_thread;
262e1174
TT
379
380 /* This is the traceframe which we last selected on the remote system.
381 It will be -1 if no traceframe is selected. */
382 int remote_traceframe_number;
747dc59d
TT
383
384 char *last_pass_packet;
5e4a05c4
TT
385
386 /* The last QProgramSignals packet sent to the target. We bypass
387 sending a new program signals list down to the target if the new
388 packet is exactly the same as the last we sent. IOW, we only let
389 the target know about program signals list changes. */
390 char *last_program_signals_packet;
b73be471
TT
391
392 enum gdb_signal last_sent_signal;
280ceea3
TT
393
394 int last_sent_step;
8e88304f
TT
395
396 char *finished_object;
397 char *finished_annex;
398 ULONGEST finished_offset;
b80fafe3
TT
399
400 /* Should we try the 'ThreadInfo' query packet?
401
402 This variable (NOT available to the user: auto-detect only!)
403 determines whether GDB will use the new, simpler "ThreadInfo"
404 query or the older, more complex syntax for thread queries.
405 This is an auto-detect variable (set to true at each connect,
406 and set to false when the target fails to recognize it). */
407 int use_threadinfo_query;
408 int use_threadextra_query;
88b496c3 409
0d031856
TT
410 threadref echo_nextthread;
411 threadref nextthread;
412 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
413
414 /* The state of remote notification. */
415 struct remote_notif_state *notif_state;
f4abbc16
MM
416
417 /* The branch trace configuration. */
418 struct btrace_config btrace_config;
15a201c8
GB
419
420 /* The argument to the last "vFile:setfs:" packet we sent, used
421 to avoid sending repeated unnecessary "vFile:setfs:" packets.
422 Initialized to -1 to indicate that no "vFile:setfs:" packet
423 has yet been sent. */
424 int fs_pid;
80152258
PA
425
426 /* A readahead cache for vFile:pread. Often, reading a binary
427 involves a sequence of small reads. E.g., when parsing an ELF
428 file. A readahead cache helps mostly the case of remote
429 debugging on a connection with higher latency, due to the
430 request/reply nature of the RSP. We only cache data for a single
431 file descriptor at a time. */
432 struct readahead_cache readahead_cache;
ea9c271d
DJ
433};
434
dc146f7c
VP
435/* Private data that we'll store in (struct thread_info)->private. */
436struct private_thread_info
437{
438 char *extra;
79efa585 439 char *name;
dc146f7c 440 int core;
799a2abe
PA
441
442 /* Whether the target stopped for a breakpoint/watchpoint. */
443 enum target_stop_reason stop_reason;
444
445 /* This is set to the data address of the access causing the target
446 to stop for a watchpoint. */
447 CORE_ADDR watch_data_address;
dc146f7c
VP
448};
449
450static void
451free_private_thread_info (struct private_thread_info *info)
452{
453 xfree (info->extra);
79efa585 454 xfree (info->name);
dc146f7c
VP
455 xfree (info);
456}
457
ea9c271d
DJ
458/* This data could be associated with a target, but we do not always
459 have access to the current target when we need it, so for now it is
460 static. This will be fine for as long as only one target is in use
461 at a time. */
cf792862 462static struct remote_state *remote_state;
ea9c271d
DJ
463
464static struct remote_state *
0b83947e 465get_remote_state_raw (void)
ea9c271d 466{
cf792862
TT
467 return remote_state;
468}
469
470/* Allocate a new struct remote_state with xmalloc, initialize it, and
471 return it. */
472
473static struct remote_state *
474new_remote_state (void)
475{
476 struct remote_state *result = XCNEW (struct remote_state);
477
478 /* The default buffer size is unimportant; it will be expanded
479 whenever a larger buffer is needed. */
480 result->buf_size = 400;
224c3ddb 481 result->buf = (char *) xmalloc (result->buf_size);
262e1174 482 result->remote_traceframe_number = -1;
b73be471 483 result->last_sent_signal = GDB_SIGNAL_0;
15a201c8 484 result->fs_pid = -1;
cf792862
TT
485
486 return result;
ea9c271d
DJ
487}
488
489/* Description of the remote protocol for a given architecture. */
d01949b6 490
ad10f812
AC
491struct packet_reg
492{
493 long offset; /* Offset into G packet. */
494 long regnum; /* GDB's internal register number. */
495 LONGEST pnum; /* Remote protocol register number. */
b323314b 496 int in_g_packet; /* Always part of G packet. */
f5656ead 497 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 498 at present. */
f5656ead 499 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 500 at present. */
ad10f812
AC
501};
502
ea9c271d 503struct remote_arch_state
d01949b6 504{
ad10f812
AC
505 /* Description of the remote protocol registers. */
506 long sizeof_g_packet;
b323314b
AC
507
508 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 509 (making an array gdbarch_num_regs in size). */
b323314b 510 struct packet_reg *regs;
ad10f812 511
d01949b6
AC
512 /* This is the size (in chars) of the first response to the ``g''
513 packet. It is used as a heuristic when determining the maximum
514 size of memory-read and memory-write packets. A target will
515 typically only reserve a buffer large enough to hold the ``g''
516 packet. The size does not include packet overhead (headers and
23860348 517 trailers). */
d01949b6
AC
518 long actual_register_packet_size;
519
520 /* This is the maximum size (in chars) of a non read/write packet.
23860348 521 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
522 long remote_packet_size;
523};
524
35b1e5cc
SS
525/* Utility: generate error from an incoming stub packet. */
526static void
527trace_error (char *buf)
528{
529 if (*buf++ != 'E')
530 return; /* not an error msg */
531 switch (*buf)
532 {
533 case '1': /* malformed packet error */
534 if (*++buf == '0') /* general case: */
535 error (_("remote.c: error in outgoing packet."));
536 else
537 error (_("remote.c: error in outgoing packet at field #%ld."),
538 strtol (buf, NULL, 16));
35b1e5cc
SS
539 default:
540 error (_("Target returns error code '%s'."), buf);
541 }
542}
543
544/* Utility: wait for reply from stub, while accepting "O" packets. */
545static char *
546remote_get_noisy_reply (char **buf_p,
547 long *sizeof_buf)
548{
549 do /* Loop on reply from remote stub. */
550 {
551 char *buf;
a744cf53 552
0df8b418 553 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
554 getpkt (buf_p, sizeof_buf, 0);
555 buf = *buf_p;
ad91cd99 556 if (buf[0] == 'E')
35b1e5cc 557 trace_error (buf);
61012eef 558 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
559 {
560 ULONGEST ul;
561 CORE_ADDR from, to, org_to;
562 char *p, *pp;
563 int adjusted_size = 0;
7556d4a4 564 int relocated = 0;
dde08ee1
PA
565
566 p = buf + strlen ("qRelocInsn:");
567 pp = unpack_varlen_hex (p, &ul);
568 if (*pp != ';')
cb91c06a 569 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
570 from = ul;
571
572 p = pp + 1;
a9cbf802 573 unpack_varlen_hex (p, &ul);
dde08ee1
PA
574 to = ul;
575
576 org_to = to;
577
492d29ea 578 TRY
dde08ee1 579 {
f5656ead 580 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 581 relocated = 1;
dde08ee1 582 }
492d29ea 583 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
584 {
585 if (ex.error == MEMORY_ERROR)
586 {
587 /* Propagate memory errors silently back to the
588 target. The stub may have limited the range of
589 addresses we can write to, for example. */
590 }
591 else
592 {
593 /* Something unexpectedly bad happened. Be verbose
594 so we can tell what, and propagate the error back
595 to the stub, so it doesn't get stuck waiting for
596 a response. */
597 exception_fprintf (gdb_stderr, ex,
598 _("warning: relocating instruction: "));
599 }
600 putpkt ("E01");
601 }
492d29ea 602 END_CATCH
7556d4a4
PA
603
604 if (relocated)
dde08ee1
PA
605 {
606 adjusted_size = to - org_to;
607
bba74b36 608 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
609 putpkt (buf);
610 }
dde08ee1 611 }
ad91cd99 612 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
613 remote_console_output (buf + 1); /* 'O' message from stub */
614 else
0df8b418 615 return buf; /* Here's the actual reply. */
35b1e5cc
SS
616 }
617 while (1);
618}
3c3bea1c 619
d01949b6
AC
620/* Handle for retreving the remote protocol data from gdbarch. */
621static struct gdbarch_data *remote_gdbarch_data_handle;
622
ea9c271d
DJ
623static struct remote_arch_state *
624get_remote_arch_state (void)
d01949b6 625{
17d8546e 626 gdb_assert (target_gdbarch () != NULL);
19ba03f4
SM
627 return ((struct remote_arch_state *)
628 gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle));
d01949b6
AC
629}
630
0b83947e
DJ
631/* Fetch the global remote target state. */
632
633static struct remote_state *
634get_remote_state (void)
635{
636 /* Make sure that the remote architecture state has been
637 initialized, because doing so might reallocate rs->buf. Any
638 function which calls getpkt also needs to be mindful of changes
639 to rs->buf, but this call limits the number of places which run
640 into trouble. */
641 get_remote_arch_state ();
642
643 return get_remote_state_raw ();
644}
645
94585166
DB
646/* Cleanup routine for the remote module's pspace data. */
647
648static void
649remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
650{
19ba03f4 651 char *remote_exec_file = (char *) arg;
94585166
DB
652
653 xfree (remote_exec_file);
654}
655
656/* Fetch the remote exec-file from the current program space. */
657
658static const char *
659get_remote_exec_file (void)
660{
661 char *remote_exec_file;
662
19ba03f4
SM
663 remote_exec_file
664 = (char *) program_space_data (current_program_space,
665 remote_pspace_data);
94585166
DB
666 if (remote_exec_file == NULL)
667 return "";
668
669 return remote_exec_file;
670}
671
672/* Set the remote exec file for PSPACE. */
673
674static void
675set_pspace_remote_exec_file (struct program_space *pspace,
676 char *remote_exec_file)
677{
19ba03f4 678 char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
94585166
DB
679
680 xfree (old_file);
681 set_program_space_data (pspace, remote_pspace_data,
682 xstrdup (remote_exec_file));
683}
684
685/* The "set/show remote exec-file" set command hook. */
686
687static void
688set_remote_exec_file (char *ignored, int from_tty,
689 struct cmd_list_element *c)
690{
691 gdb_assert (remote_exec_file_var != NULL);
692 set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
693}
694
695/* The "set/show remote exec-file" show command hook. */
696
697static void
698show_remote_exec_file (struct ui_file *file, int from_tty,
699 struct cmd_list_element *cmd, const char *value)
700{
701 fprintf_filtered (file, "%s\n", remote_exec_file_var);
702}
703
74ca34ce
DJ
704static int
705compare_pnums (const void *lhs_, const void *rhs_)
706{
19ba03f4
SM
707 const struct packet_reg * const *lhs
708 = (const struct packet_reg * const *) lhs_;
709 const struct packet_reg * const *rhs
710 = (const struct packet_reg * const *) rhs_;
74ca34ce
DJ
711
712 if ((*lhs)->pnum < (*rhs)->pnum)
713 return -1;
714 else if ((*lhs)->pnum == (*rhs)->pnum)
715 return 0;
716 else
717 return 1;
718}
719
c21236dc
PA
720static int
721map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 722{
74ca34ce 723 int regnum, num_remote_regs, offset;
74ca34ce 724 struct packet_reg **remote_regs;
ea9c271d 725
4a22f64d 726 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 727 {
c21236dc 728 struct packet_reg *r = &regs[regnum];
baef701f 729
4a22f64d 730 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
731 /* Do not try to fetch zero-sized (placeholder) registers. */
732 r->pnum = -1;
733 else
734 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
735
b323314b 736 r->regnum = regnum;
74ca34ce
DJ
737 }
738
739 /* Define the g/G packet format as the contents of each register
740 with a remote protocol number, in order of ascending protocol
741 number. */
742
224c3ddb 743 remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
f57d151a 744 for (num_remote_regs = 0, regnum = 0;
4a22f64d 745 regnum < gdbarch_num_regs (gdbarch);
f57d151a 746 regnum++)
c21236dc
PA
747 if (regs[regnum].pnum != -1)
748 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 749
74ca34ce
DJ
750 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
751 compare_pnums);
752
753 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
754 {
755 remote_regs[regnum]->in_g_packet = 1;
756 remote_regs[regnum]->offset = offset;
4a22f64d 757 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
758 }
759
c21236dc
PA
760 return offset;
761}
762
763/* Given the architecture described by GDBARCH, return the remote
764 protocol register's number and the register's offset in the g/G
765 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
766 If the target does not have a mapping for REGNUM, return false,
767 otherwise, return true. */
768
769int
770remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
771 int *pnum, int *poffset)
772{
c21236dc
PA
773 struct packet_reg *regs;
774 struct cleanup *old_chain;
775
776 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
777
224c3ddb 778 regs = XCNEWVEC (struct packet_reg, gdbarch_num_regs (gdbarch));
c21236dc
PA
779 old_chain = make_cleanup (xfree, regs);
780
54887903 781 map_regcache_remote_table (gdbarch, regs);
c21236dc
PA
782
783 *pnum = regs[regnum].pnum;
784 *poffset = regs[regnum].offset;
785
786 do_cleanups (old_chain);
787
788 return *pnum != -1;
789}
790
791static void *
792init_remote_state (struct gdbarch *gdbarch)
793{
794 struct remote_state *rs = get_remote_state_raw ();
795 struct remote_arch_state *rsa;
796
797 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
798
799 /* Use the architecture to build a regnum<->pnum table, which will be
800 1:1 unless a feature set specifies otherwise. */
801 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
802 gdbarch_num_regs (gdbarch),
803 struct packet_reg);
804
74ca34ce
DJ
805 /* Record the maximum possible size of the g packet - it may turn out
806 to be smaller. */
c21236dc 807 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 808
0df8b418 809 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
810 remote stubs have a hardwired buffer size of 400 bytes
811 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
812 as the maximum packet-size to ensure that the packet and an extra
813 NUL character can always fit in the buffer. This stops GDB
814 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
815 already a full buffer (As of 1999-12-04 that was most stubs). */
816 rsa->remote_packet_size = 400 - 1;
d01949b6 817
ea9c271d
DJ
818 /* This one is filled in when a ``g'' packet is received. */
819 rsa->actual_register_packet_size = 0;
820
821 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
822 default, adjust the size accordingly. Remember that each byte is
823 encoded as two characters. 32 is the overhead for the packet
824 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 825 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 826 little. */
ea9c271d
DJ
827 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
828 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 829
ea9c271d
DJ
830 /* Make sure that the packet buffer is plenty big enough for
831 this architecture. */
832 if (rs->buf_size < rsa->remote_packet_size)
833 {
834 rs->buf_size = 2 * rsa->remote_packet_size;
224c3ddb 835 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
ea9c271d 836 }
6d820c5c 837
ea9c271d
DJ
838 return rsa;
839}
840
841/* Return the current allowed size of a remote packet. This is
842 inferred from the current architecture, and should be used to
843 limit the length of outgoing packets. */
844static long
845get_remote_packet_size (void)
846{
be2a5f71 847 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
848 struct remote_arch_state *rsa = get_remote_arch_state ();
849
be2a5f71
DJ
850 if (rs->explicit_packet_size)
851 return rs->explicit_packet_size;
852
ea9c271d 853 return rsa->remote_packet_size;
d01949b6
AC
854}
855
ad10f812 856static struct packet_reg *
ea9c271d 857packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 858{
f5656ead 859 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
860 return NULL;
861 else
ad10f812 862 {
ea9c271d 863 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 864
b323314b
AC
865 gdb_assert (r->regnum == regnum);
866 return r;
ad10f812 867 }
ad10f812
AC
868}
869
870static struct packet_reg *
ea9c271d 871packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 872{
b323314b 873 int i;
a744cf53 874
f5656ead 875 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 876 {
ea9c271d 877 struct packet_reg *r = &rsa->regs[i];
a744cf53 878
b323314b
AC
879 if (r->pnum == pnum)
880 return r;
ad10f812
AC
881 }
882 return NULL;
d01949b6
AC
883}
884
c906108c
SS
885static struct target_ops remote_ops;
886
887static struct target_ops extended_remote_ops;
888
6426a772
JM
889/* FIXME: cagney/1999-09-23: Even though getpkt was called with
890 ``forever'' still use the normal timeout mechanism. This is
891 currently used by the ASYNC code to guarentee that target reads
892 during the initial connect always time-out. Once getpkt has been
893 modified to return a timeout indication and, in turn
894 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 895 this can go away. */
6426a772
JM
896static int wait_forever_enabled_p = 1;
897
9a7071a8
JB
898/* Allow the user to specify what sequence to send to the remote
899 when he requests a program interruption: Although ^C is usually
900 what remote systems expect (this is the default, here), it is
901 sometimes preferable to send a break. On other systems such
902 as the Linux kernel, a break followed by g, which is Magic SysRq g
903 is required in order to interrupt the execution. */
904const char interrupt_sequence_control_c[] = "Ctrl-C";
905const char interrupt_sequence_break[] = "BREAK";
906const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 907static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
908 {
909 interrupt_sequence_control_c,
910 interrupt_sequence_break,
911 interrupt_sequence_break_g,
912 NULL
913 };
914static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
915
916static void
917show_interrupt_sequence (struct ui_file *file, int from_tty,
918 struct cmd_list_element *c,
919 const char *value)
920{
921 if (interrupt_sequence_mode == interrupt_sequence_control_c)
922 fprintf_filtered (file,
923 _("Send the ASCII ETX character (Ctrl-c) "
924 "to the remote target to interrupt the "
925 "execution of the program.\n"));
926 else if (interrupt_sequence_mode == interrupt_sequence_break)
927 fprintf_filtered (file,
928 _("send a break signal to the remote target "
929 "to interrupt the execution of the program.\n"));
930 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
931 fprintf_filtered (file,
932 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
933 "the remote target to interrupt the execution "
934 "of Linux kernel.\n"));
935 else
936 internal_error (__FILE__, __LINE__,
937 _("Invalid value for interrupt_sequence_mode: %s."),
938 interrupt_sequence_mode);
939}
6426a772 940
9a7071a8
JB
941/* This boolean variable specifies whether interrupt_sequence is sent
942 to the remote target when gdb connects to it.
943 This is mostly needed when you debug the Linux kernel: The Linux kernel
944 expects BREAK g which is Magic SysRq g for connecting gdb. */
945static int interrupt_on_connect = 0;
c906108c 946
9a7071a8
JB
947/* This variable is used to implement the "set/show remotebreak" commands.
948 Since these commands are now deprecated in favor of "set/show remote
949 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
950static int remote_break;
951
9a7071a8
JB
952static void
953set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
954{
955 if (remote_break)
956 interrupt_sequence_mode = interrupt_sequence_break;
957 else
958 interrupt_sequence_mode = interrupt_sequence_control_c;
959}
960
961static void
962show_remotebreak (struct ui_file *file, int from_tty,
963 struct cmd_list_element *c,
964 const char *value)
965{
966}
967
c906108c
SS
968/* This variable sets the number of bits in an address that are to be
969 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 970 leading zeros, the entire address would be sent. This variable
c906108c
SS
971 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
972 initial implementation of remote.c restricted the address sent in
973 memory packets to ``host::sizeof long'' bytes - (typically 32
974 bits). Consequently, for 64 bit targets, the upper 32 bits of an
975 address was never sent. Since fixing this bug may cause a break in
976 some remote targets this variable is principly provided to
23860348 977 facilitate backward compatibility. */
c906108c 978
883b9c6c 979static unsigned int remote_address_size;
c906108c 980
75c99385
PA
981/* Temporary to track who currently owns the terminal. See
982 remote_terminal_* for more details. */
6426a772
JM
983
984static int remote_async_terminal_ours_p;
985
11cf8741 986\f
11cf8741 987/* User configurable variables for the number of characters in a
ea9c271d
DJ
988 memory read/write packet. MIN (rsa->remote_packet_size,
989 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 990 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
991 (speed up transfers). The variables ``preferred_*'' (the user
992 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 993 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
994
995struct memory_packet_config
996{
997 char *name;
998 long size;
999 int fixed_p;
1000};
1001
a5c0808e
PA
1002/* The default max memory-write-packet-size. The 16k is historical.
1003 (It came from older GDB's using alloca for buffers and the
1004 knowledge (folklore?) that some hosts don't cope very well with
1005 large alloca calls.) */
1006#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1007
1008/* The minimum remote packet size for memory transfers. Ensures we
1009 can write at least one byte. */
1010#define MIN_MEMORY_PACKET_SIZE 20
1011
11cf8741
JM
1012/* Compute the current size of a read/write packet. Since this makes
1013 use of ``actual_register_packet_size'' the computation is dynamic. */
1014
1015static long
1016get_memory_packet_size (struct memory_packet_config *config)
1017{
d01949b6 1018 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
1019 struct remote_arch_state *rsa = get_remote_arch_state ();
1020
11cf8741
JM
1021 long what_they_get;
1022 if (config->fixed_p)
1023 {
1024 if (config->size <= 0)
a5c0808e 1025 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
1026 else
1027 what_they_get = config->size;
1028 }
1029 else
1030 {
ea9c271d 1031 what_they_get = get_remote_packet_size ();
23860348 1032 /* Limit the packet to the size specified by the user. */
11cf8741
JM
1033 if (config->size > 0
1034 && what_they_get > config->size)
1035 what_they_get = config->size;
be2a5f71
DJ
1036
1037 /* Limit it to the size of the targets ``g'' response unless we have
1038 permission from the stub to use a larger packet size. */
1039 if (rs->explicit_packet_size == 0
1040 && rsa->actual_register_packet_size > 0
1041 && what_they_get > rsa->actual_register_packet_size)
1042 what_they_get = rsa->actual_register_packet_size;
11cf8741 1043 }
a5c0808e
PA
1044 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1045 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
1046
1047 /* Make sure there is room in the global buffer for this packet
1048 (including its trailing NUL byte). */
1049 if (rs->buf_size < what_they_get + 1)
1050 {
1051 rs->buf_size = 2 * what_they_get;
224c3ddb 1052 rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
6d820c5c
DJ
1053 }
1054
11cf8741
JM
1055 return what_they_get;
1056}
1057
0df8b418 1058/* Update the size of a read/write packet. If they user wants
23860348 1059 something really big then do a sanity check. */
11cf8741
JM
1060
1061static void
1062set_memory_packet_size (char *args, struct memory_packet_config *config)
1063{
1064 int fixed_p = config->fixed_p;
1065 long size = config->size;
a744cf53 1066
11cf8741 1067 if (args == NULL)
8a3fe4f8 1068 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
1069 else if (strcmp (args, "hard") == 0
1070 || strcmp (args, "fixed") == 0)
1071 fixed_p = 1;
1072 else if (strcmp (args, "soft") == 0
1073 || strcmp (args, "limit") == 0)
1074 fixed_p = 0;
1075 else
1076 {
1077 char *end;
a744cf53 1078
11cf8741
JM
1079 size = strtoul (args, &end, 0);
1080 if (args == end)
8a3fe4f8 1081 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1082
1083 /* Instead of explicitly capping the size of a packet to or
1084 disallowing it, the user is allowed to set the size to
1085 something arbitrarily large. */
11cf8741 1086 }
a5c0808e
PA
1087
1088 /* So that the query shows the correct value. */
1089 if (size <= 0)
1090 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1091
23860348 1092 /* Extra checks? */
11cf8741
JM
1093 if (fixed_p && !config->fixed_p)
1094 {
e2e0b3e5
AC
1095 if (! query (_("The target may not be able to correctly handle a %s\n"
1096 "of %ld bytes. Change the packet size? "),
11cf8741 1097 config->name, size))
8a3fe4f8 1098 error (_("Packet size not changed."));
11cf8741 1099 }
23860348 1100 /* Update the config. */
11cf8741
JM
1101 config->fixed_p = fixed_p;
1102 config->size = size;
1103}
1104
1105static void
1106show_memory_packet_size (struct memory_packet_config *config)
1107{
a3f17187 1108 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1109 if (config->fixed_p)
a3f17187 1110 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1111 get_memory_packet_size (config));
1112 else
a3f17187 1113 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1114 get_memory_packet_size (config));
1115}
1116
1117static struct memory_packet_config memory_write_packet_config =
1118{
1119 "memory-write-packet-size",
1120};
1121
1122static void
1123set_memory_write_packet_size (char *args, int from_tty)
1124{
1125 set_memory_packet_size (args, &memory_write_packet_config);
1126}
1127
1128static void
1129show_memory_write_packet_size (char *args, int from_tty)
1130{
1131 show_memory_packet_size (&memory_write_packet_config);
1132}
1133
1134static long
1135get_memory_write_packet_size (void)
1136{
1137 return get_memory_packet_size (&memory_write_packet_config);
1138}
1139
1140static struct memory_packet_config memory_read_packet_config =
1141{
1142 "memory-read-packet-size",
1143};
1144
1145static void
1146set_memory_read_packet_size (char *args, int from_tty)
1147{
1148 set_memory_packet_size (args, &memory_read_packet_config);
1149}
1150
1151static void
1152show_memory_read_packet_size (char *args, int from_tty)
1153{
1154 show_memory_packet_size (&memory_read_packet_config);
1155}
1156
1157static long
1158get_memory_read_packet_size (void)
1159{
1160 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1161
11cf8741
JM
1162 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1163 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1164 increased beyond this. */
1165 if (size > get_remote_packet_size ())
1166 size = get_remote_packet_size ();
11cf8741
JM
1167 return size;
1168}
1169
11cf8741 1170\f
5a2468f5 1171/* Generic configuration support for packets the stub optionally
0df8b418 1172 supports. Allows the user to specify the use of the packet as well
23860348 1173 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1174
1175enum packet_support
1176 {
1177 PACKET_SUPPORT_UNKNOWN = 0,
1178 PACKET_ENABLE,
1179 PACKET_DISABLE
1180 };
1181
5a2468f5
JM
1182struct packet_config
1183 {
bb572ddd
DJ
1184 const char *name;
1185 const char *title;
4082afcc
PA
1186
1187 /* If auto, GDB auto-detects support for this packet or feature,
1188 either through qSupported, or by trying the packet and looking
1189 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1190 packet. If false, the packet is disabled. Configs that don't
1191 have an associated command always have this set to auto. */
7f19b9a2 1192 enum auto_boolean detect;
4082afcc
PA
1193
1194 /* Does the target support this packet? */
5a2468f5
JM
1195 enum packet_support support;
1196 };
1197
d471ea57 1198/* Analyze a packet's return value and update the packet config
23860348 1199 accordingly. */
d471ea57
AC
1200
1201enum packet_result
1202{
1203 PACKET_ERROR,
1204 PACKET_OK,
1205 PACKET_UNKNOWN
1206};
1207
4082afcc
PA
1208static enum packet_support packet_config_support (struct packet_config *config);
1209static enum packet_support packet_support (int packet);
5a2468f5
JM
1210
1211static void
fba45db2 1212show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1213{
1214 char *support = "internal-error";
a744cf53 1215
4082afcc 1216 switch (packet_config_support (config))
5a2468f5
JM
1217 {
1218 case PACKET_ENABLE:
1219 support = "enabled";
1220 break;
1221 case PACKET_DISABLE:
1222 support = "disabled";
1223 break;
1224 case PACKET_SUPPORT_UNKNOWN:
1225 support = "unknown";
1226 break;
1227 }
1228 switch (config->detect)
1229 {
7f19b9a2 1230 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1231 printf_filtered (_("Support for the `%s' packet "
1232 "is auto-detected, currently %s.\n"),
37a105a1 1233 config->name, support);
5a2468f5 1234 break;
7f19b9a2
AC
1235 case AUTO_BOOLEAN_TRUE:
1236 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1237 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1238 config->name, support);
8e248173 1239 break;
5a2468f5
JM
1240 }
1241}
1242
1243static void
bb572ddd
DJ
1244add_packet_config_cmd (struct packet_config *config, const char *name,
1245 const char *title, int legacy)
d471ea57 1246{
5a2468f5
JM
1247 char *set_doc;
1248 char *show_doc;
d471ea57 1249 char *cmd_name;
3ed07be4 1250
5a2468f5
JM
1251 config->name = name;
1252 config->title = title;
b435e160
AC
1253 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1254 name, title);
3e43a32a
MS
1255 show_doc = xstrprintf ("Show current use of remote "
1256 "protocol `%s' (%s) packet",
b435e160 1257 name, title);
d471ea57 1258 /* set/show TITLE-packet {auto,on,off} */
b435e160 1259 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1260 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1261 &config->detect, set_doc,
1262 show_doc, NULL, /* help_doc */
4082afcc 1263 NULL,
bb572ddd
DJ
1264 show_remote_protocol_packet_cmd,
1265 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1266 /* The command code copies the documentation strings. */
1267 xfree (set_doc);
1268 xfree (show_doc);
23860348 1269 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1270 if (legacy)
1271 {
1272 char *legacy_name;
a744cf53 1273
b435e160 1274 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1275 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1276 &remote_set_cmdlist);
d471ea57 1277 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1278 &remote_show_cmdlist);
d471ea57 1279 }
5a2468f5
JM
1280}
1281
d471ea57 1282static enum packet_result
a76d924d 1283packet_check_result (const char *buf)
5a2468f5 1284{
d471ea57 1285 if (buf[0] != '\0')
5a2468f5 1286 {
d471ea57 1287 /* The stub recognized the packet request. Check that the
23860348 1288 operation succeeded. */
a76d924d
DJ
1289 if (buf[0] == 'E'
1290 && isxdigit (buf[1]) && isxdigit (buf[2])
1291 && buf[3] == '\0')
1292 /* "Enn" - definitly an error. */
1293 return PACKET_ERROR;
1294
1295 /* Always treat "E." as an error. This will be used for
1296 more verbose error messages, such as E.memtypes. */
1297 if (buf[0] == 'E' && buf[1] == '.')
1298 return PACKET_ERROR;
1299
1300 /* The packet may or may not be OK. Just assume it is. */
1301 return PACKET_OK;
1302 }
1303 else
1304 /* The stub does not support the packet. */
1305 return PACKET_UNKNOWN;
1306}
1307
1308static enum packet_result
1309packet_ok (const char *buf, struct packet_config *config)
1310{
1311 enum packet_result result;
1312
4082afcc
PA
1313 if (config->detect != AUTO_BOOLEAN_TRUE
1314 && config->support == PACKET_DISABLE)
1315 internal_error (__FILE__, __LINE__,
1316 _("packet_ok: attempt to use a disabled packet"));
1317
a76d924d
DJ
1318 result = packet_check_result (buf);
1319 switch (result)
1320 {
1321 case PACKET_OK:
1322 case PACKET_ERROR:
1323 /* The stub recognized the packet request. */
4082afcc 1324 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1325 {
d471ea57
AC
1326 if (remote_debug)
1327 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1328 "Packet %s (%s) is supported\n",
1329 config->name, config->title);
d471ea57 1330 config->support = PACKET_ENABLE;
d471ea57 1331 }
a76d924d
DJ
1332 break;
1333 case PACKET_UNKNOWN:
23860348 1334 /* The stub does not support the packet. */
4082afcc
PA
1335 if (config->detect == AUTO_BOOLEAN_AUTO
1336 && config->support == PACKET_ENABLE)
d471ea57 1337 {
4082afcc
PA
1338 /* If the stub previously indicated that the packet was
1339 supported then there is a protocol error. */
1340 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1341 config->name, config->title);
1342 }
1343 else if (config->detect == AUTO_BOOLEAN_TRUE)
1344 {
1345 /* The user set it wrong. */
1346 error (_("Enabled packet %s (%s) not recognized by stub"),
1347 config->name, config->title);
d471ea57 1348 }
4082afcc
PA
1349
1350 if (remote_debug)
1351 fprintf_unfiltered (gdb_stdlog,
1352 "Packet %s (%s) is NOT supported\n",
1353 config->name, config->title);
1354 config->support = PACKET_DISABLE;
a76d924d 1355 break;
5a2468f5 1356 }
a76d924d
DJ
1357
1358 return result;
5a2468f5
JM
1359}
1360
444abaca
DJ
1361enum {
1362 PACKET_vCont = 0,
1363 PACKET_X,
1364 PACKET_qSymbol,
1365 PACKET_P,
1366 PACKET_p,
1367 PACKET_Z0,
1368 PACKET_Z1,
1369 PACKET_Z2,
1370 PACKET_Z3,
1371 PACKET_Z4,
15a201c8 1372 PACKET_vFile_setfs,
a6b151f1
DJ
1373 PACKET_vFile_open,
1374 PACKET_vFile_pread,
1375 PACKET_vFile_pwrite,
1376 PACKET_vFile_close,
1377 PACKET_vFile_unlink,
b9e7b9c3 1378 PACKET_vFile_readlink,
0a93529c 1379 PACKET_vFile_fstat,
0876f84a 1380 PACKET_qXfer_auxv,
23181151 1381 PACKET_qXfer_features,
c78fa86a 1382 PACKET_qXfer_exec_file,
cfa9d6d9 1383 PACKET_qXfer_libraries,
2268b414 1384 PACKET_qXfer_libraries_svr4,
fd79ecee 1385 PACKET_qXfer_memory_map,
0e7f50da
UW
1386 PACKET_qXfer_spu_read,
1387 PACKET_qXfer_spu_write,
07e059b5 1388 PACKET_qXfer_osdata,
dc146f7c 1389 PACKET_qXfer_threads,
0fb4aa4b 1390 PACKET_qXfer_statictrace_read,
b3b9301e 1391 PACKET_qXfer_traceframe_info,
169081d0 1392 PACKET_qXfer_uib,
711e434b 1393 PACKET_qGetTIBAddr,
444abaca 1394 PACKET_qGetTLSAddr,
be2a5f71 1395 PACKET_qSupported,
bd3eecc3 1396 PACKET_qTStatus,
89be2091 1397 PACKET_QPassSignals,
82075af2 1398 PACKET_QCatchSyscalls,
9b224c5e 1399 PACKET_QProgramSignals,
936d2992 1400 PACKET_qCRC,
08388c79 1401 PACKET_qSearch_memory,
2d717e4f
DJ
1402 PACKET_vAttach,
1403 PACKET_vRun,
a6f3e723 1404 PACKET_QStartNoAckMode,
82f73884 1405 PACKET_vKill,
4aa995e1
PA
1406 PACKET_qXfer_siginfo_read,
1407 PACKET_qXfer_siginfo_write,
0b16c5cf 1408 PACKET_qAttached,
4082afcc
PA
1409
1410 /* Support for conditional tracepoints. */
782b2b07 1411 PACKET_ConditionalTracepoints,
4082afcc
PA
1412
1413 /* Support for target-side breakpoint conditions. */
3788aec7 1414 PACKET_ConditionalBreakpoints,
4082afcc
PA
1415
1416 /* Support for target-side breakpoint commands. */
d3ce09f5 1417 PACKET_BreakpointCommands,
4082afcc
PA
1418
1419 /* Support for fast tracepoints. */
7a697b8d 1420 PACKET_FastTracepoints,
4082afcc
PA
1421
1422 /* Support for static tracepoints. */
0fb4aa4b 1423 PACKET_StaticTracepoints,
4082afcc
PA
1424
1425 /* Support for installing tracepoints while a trace experiment is
1426 running. */
1e4d1764 1427 PACKET_InstallInTrace,
4082afcc 1428
40ab02ce
MS
1429 PACKET_bc,
1430 PACKET_bs,
409873ef 1431 PACKET_TracepointSource,
d914c394 1432 PACKET_QAllow,
78d85199 1433 PACKET_qXfer_fdpic,
03583c20 1434 PACKET_QDisableRandomization,
d1feda86 1435 PACKET_QAgent,
f6f899bf 1436 PACKET_QTBuffer_size,
9accd112
MM
1437 PACKET_Qbtrace_off,
1438 PACKET_Qbtrace_bts,
b20a6524 1439 PACKET_Qbtrace_pt,
9accd112 1440 PACKET_qXfer_btrace,
4082afcc
PA
1441
1442 /* Support for the QNonStop packet. */
1443 PACKET_QNonStop,
1444
65706a29
PA
1445 /* Support for the QThreadEvents packet. */
1446 PACKET_QThreadEvents,
1447
4082afcc
PA
1448 /* Support for multi-process extensions. */
1449 PACKET_multiprocess_feature,
1450
1451 /* Support for enabling and disabling tracepoints while a trace
1452 experiment is running. */
1453 PACKET_EnableDisableTracepoints_feature,
1454
1455 /* Support for collecting strings using the tracenz bytecode. */
1456 PACKET_tracenz_feature,
1457
1458 /* Support for continuing to run a trace experiment while GDB is
1459 disconnected. */
1460 PACKET_DisconnectedTracing_feature,
1461
1462 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1463 PACKET_augmented_libraries_svr4_read_feature,
1464
f4abbc16
MM
1465 /* Support for the qXfer:btrace-conf:read packet. */
1466 PACKET_qXfer_btrace_conf,
1467
d33501a5
MM
1468 /* Support for the Qbtrace-conf:bts:size packet. */
1469 PACKET_Qbtrace_conf_bts_size,
1470
f7e6eed5
PA
1471 /* Support for swbreak+ feature. */
1472 PACKET_swbreak_feature,
1473
1474 /* Support for hwbreak+ feature. */
1475 PACKET_hwbreak_feature,
1476
89245bc0
DB
1477 /* Support for fork events. */
1478 PACKET_fork_event_feature,
1479
1480 /* Support for vfork events. */
1481 PACKET_vfork_event_feature,
1482
b20a6524
MM
1483 /* Support for the Qbtrace-conf:pt:size packet. */
1484 PACKET_Qbtrace_conf_pt_size,
1485
94585166
DB
1486 /* Support for exec events. */
1487 PACKET_exec_event_feature,
1488
750ce8d1
YQ
1489 /* Support for query supported vCont actions. */
1490 PACKET_vContSupported,
1491
de979965
PA
1492 /* Support remote CTRL-C. */
1493 PACKET_vCtrlC,
1494
f2faf941
PA
1495 /* Support TARGET_WAITKIND_NO_RESUMED. */
1496 PACKET_no_resumed,
1497
444abaca
DJ
1498 PACKET_MAX
1499};
506fb367 1500
444abaca 1501static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1502
f7e6eed5
PA
1503/* Returns the packet's corresponding "set remote foo-packet" command
1504 state. See struct packet_config for more details. */
1505
1506static enum auto_boolean
1507packet_set_cmd_state (int packet)
1508{
1509 return remote_protocol_packets[packet].detect;
1510}
1511
4082afcc
PA
1512/* Returns whether a given packet or feature is supported. This takes
1513 into account the state of the corresponding "set remote foo-packet"
1514 command, which may be used to bypass auto-detection. */
dc8acb97 1515
4082afcc
PA
1516static enum packet_support
1517packet_config_support (struct packet_config *config)
1518{
1519 switch (config->detect)
444abaca 1520 {
4082afcc
PA
1521 case AUTO_BOOLEAN_TRUE:
1522 return PACKET_ENABLE;
1523 case AUTO_BOOLEAN_FALSE:
1524 return PACKET_DISABLE;
1525 case AUTO_BOOLEAN_AUTO:
1526 return config->support;
1527 default:
1528 gdb_assert_not_reached (_("bad switch"));
444abaca 1529 }
4082afcc
PA
1530}
1531
1532/* Same as packet_config_support, but takes the packet's enum value as
1533 argument. */
1534
1535static enum packet_support
1536packet_support (int packet)
1537{
1538 struct packet_config *config = &remote_protocol_packets[packet];
1539
1540 return packet_config_support (config);
dc8acb97
MS
1541}
1542
5a2468f5 1543static void
444abaca
DJ
1544show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1545 struct cmd_list_element *c,
1546 const char *value)
5a2468f5 1547{
444abaca 1548 struct packet_config *packet;
5a2468f5 1549
444abaca
DJ
1550 for (packet = remote_protocol_packets;
1551 packet < &remote_protocol_packets[PACKET_MAX];
1552 packet++)
1553 {
1554 if (&packet->detect == c->var)
1555 {
1556 show_packet_config_cmd (packet);
1557 return;
1558 }
1559 }
9b20d036 1560 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1561 c->name);
5a2468f5
JM
1562}
1563
d471ea57
AC
1564/* Should we try one of the 'Z' requests? */
1565
1566enum Z_packet_type
1567{
1568 Z_PACKET_SOFTWARE_BP,
1569 Z_PACKET_HARDWARE_BP,
1570 Z_PACKET_WRITE_WP,
1571 Z_PACKET_READ_WP,
1572 Z_PACKET_ACCESS_WP,
1573 NR_Z_PACKET_TYPES
1574};
96baa820 1575
d471ea57 1576/* For compatibility with older distributions. Provide a ``set remote
23860348 1577 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1578
7f19b9a2 1579static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1580
1581static void
fba45db2
KB
1582set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1583 struct cmd_list_element *c)
96baa820 1584{
d471ea57 1585 int i;
a744cf53 1586
d471ea57 1587 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1588 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1589}
1590
1591static void
08546159
AC
1592show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1593 struct cmd_list_element *c,
1594 const char *value)
96baa820 1595{
d471ea57 1596 int i;
a744cf53 1597
d471ea57
AC
1598 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1599 {
444abaca 1600 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1601 }
96baa820
JM
1602}
1603
4082afcc
PA
1604/* Returns true if the multi-process extensions are in effect. */
1605
1606static int
1607remote_multi_process_p (struct remote_state *rs)
1608{
1609 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1610}
1611
de0d863e
DB
1612/* Returns true if fork events are supported. */
1613
1614static int
1615remote_fork_event_p (struct remote_state *rs)
1616{
1617 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1618}
1619
c269dbdb
DB
1620/* Returns true if vfork events are supported. */
1621
1622static int
1623remote_vfork_event_p (struct remote_state *rs)
1624{
1625 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1626}
1627
d46addbb
DB
1628/* Returns true if exec events are supported. */
1629
1630static int
1631remote_exec_event_p (struct remote_state *rs)
1632{
1633 return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1634}
1635
cbb8991c
DB
1636/* Insert fork catchpoint target routine. If fork events are enabled
1637 then return success, nothing more to do. */
1638
1639static int
1640remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1641{
1642 struct remote_state *rs = get_remote_state ();
1643
1644 return !remote_fork_event_p (rs);
1645}
1646
1647/* Remove fork catchpoint target routine. Nothing to do, just
1648 return success. */
1649
1650static int
1651remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1652{
1653 return 0;
1654}
1655
1656/* Insert vfork catchpoint target routine. If vfork events are enabled
1657 then return success, nothing more to do. */
1658
1659static int
1660remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1661{
1662 struct remote_state *rs = get_remote_state ();
1663
1664 return !remote_vfork_event_p (rs);
1665}
1666
1667/* Remove vfork catchpoint target routine. Nothing to do, just
1668 return success. */
1669
1670static int
1671remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1672{
1673 return 0;
1674}
1675
d46addbb
DB
1676/* Insert exec catchpoint target routine. If exec events are
1677 enabled, just return success. */
1678
1679static int
1680remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1681{
1682 struct remote_state *rs = get_remote_state ();
1683
1684 return !remote_exec_event_p (rs);
1685}
1686
1687/* Remove exec catchpoint target routine. Nothing to do, just
1688 return success. */
1689
1690static int
1691remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1692{
1693 return 0;
1694}
1695
74531fed
PA
1696\f
1697/* Asynchronous signal handle registered as event loop source for
1698 when we have pending events ready to be passed to the core. */
1699
1700static struct async_event_handler *remote_async_inferior_event_token;
1701
c906108c
SS
1702\f
1703
79d7f229
PA
1704static ptid_t magic_null_ptid;
1705static ptid_t not_sent_ptid;
1706static ptid_t any_thread_ptid;
1707
0b16c5cf
PA
1708/* Find out if the stub attached to PID (and hence GDB should offer to
1709 detach instead of killing it when bailing out). */
1710
1711static int
1712remote_query_attached (int pid)
1713{
1714 struct remote_state *rs = get_remote_state ();
bba74b36 1715 size_t size = get_remote_packet_size ();
0b16c5cf 1716
4082afcc 1717 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1718 return 0;
1719
1720 if (remote_multi_process_p (rs))
bba74b36 1721 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1722 else
bba74b36 1723 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1724
1725 putpkt (rs->buf);
1726 getpkt (&rs->buf, &rs->buf_size, 0);
1727
1728 switch (packet_ok (rs->buf,
1554e9be 1729 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1730 {
1731 case PACKET_OK:
1732 if (strcmp (rs->buf, "1") == 0)
1733 return 1;
1734 break;
1735 case PACKET_ERROR:
1736 warning (_("Remote failure reply: %s"), rs->buf);
1737 break;
1738 case PACKET_UNKNOWN:
1739 break;
1740 }
1741
1742 return 0;
1743}
1744
49c62f2e
PA
1745/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1746 has been invented by GDB, instead of reported by the target. Since
1747 we can be connected to a remote system before before knowing about
1748 any inferior, mark the target with execution when we find the first
1749 inferior. If ATTACHED is 1, then we had just attached to this
1750 inferior. If it is 0, then we just created this inferior. If it
1751 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1752 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1753 attempt to open this inferior's executable as the main executable
1754 if no main executable is open already. */
1941c569
PA
1755
1756static struct inferior *
1b6e6f5c
GB
1757remote_add_inferior (int fake_pid_p, int pid, int attached,
1758 int try_open_exec)
1941c569 1759{
1941c569
PA
1760 struct inferior *inf;
1761
0b16c5cf
PA
1762 /* Check whether this process we're learning about is to be
1763 considered attached, or if is to be considered to have been
1764 spawned by the stub. */
1765 if (attached == -1)
1766 attached = remote_query_attached (pid);
1767
f5656ead 1768 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1769 {
1770 /* If the target shares code across all inferiors, then every
1771 attach adds a new inferior. */
1772 inf = add_inferior (pid);
1773
1774 /* ... and every inferior is bound to the same program space.
1775 However, each inferior may still have its own address
1776 space. */
1777 inf->aspace = maybe_new_address_space ();
1778 inf->pspace = current_program_space;
1779 }
1780 else
1781 {
1782 /* In the traditional debugging scenario, there's a 1-1 match
1783 between program/address spaces. We simply bind the inferior
1784 to the program space's address space. */
1785 inf = current_inferior ();
1786 inferior_appeared (inf, pid);
1787 }
1941c569 1788
0b16c5cf 1789 inf->attach_flag = attached;
49c62f2e 1790 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1791
1b6e6f5c
GB
1792 /* If no main executable is currently open then attempt to
1793 open the file that was executed to create this inferior. */
835205d0 1794 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1795 exec_file_locate_attach (pid, 1);
1796
1941c569
PA
1797 return inf;
1798}
1799
1800/* Add thread PTID to GDB's thread list. Tag it as executing/running
1801 according to RUNNING. */
1802
c906108c 1803static void
0d5b594f 1804remote_add_thread (ptid_t ptid, int running, int executing)
c906108c 1805{
b7ea362b
PA
1806 struct remote_state *rs = get_remote_state ();
1807
1808 /* GDB historically didn't pull threads in the initial connection
1809 setup. If the remote target doesn't even have a concept of
1810 threads (e.g., a bare-metal target), even if internally we
1811 consider that a single-threaded target, mentioning a new thread
1812 might be confusing to the user. Be silent then, preserving the
1813 age old behavior. */
1814 if (rs->starting_up)
1815 add_thread_silent (ptid);
1816 else
1817 add_thread (ptid);
1941c569 1818
0d5b594f 1819 set_executing (ptid, executing);
1941c569
PA
1820 set_running (ptid, running);
1821}
1822
1823/* Come here when we learn about a thread id from the remote target.
1824 It may be the first time we hear about such thread, so take the
1825 opportunity to add it to GDB's thread list. In case this is the
1826 first time we're noticing its corresponding inferior, add it to
0d5b594f
PA
1827 GDB's inferior list as well. EXECUTING indicates whether the
1828 thread is (internally) executing or stopped. */
1941c569
PA
1829
1830static void
0d5b594f 1831remote_notice_new_inferior (ptid_t currthread, int executing)
1941c569 1832{
0d5b594f
PA
1833 /* In non-stop mode, we assume new found threads are (externally)
1834 running until proven otherwise with a stop reply. In all-stop,
1835 we can only get here if all threads are stopped. */
1836 int running = target_is_non_stop_p () ? 1 : 0;
1837
c906108c
SS
1838 /* If this is a new thread, add it to GDB's thread list.
1839 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1840
1841 if (in_thread_list (currthread) && is_exited (currthread))
1842 {
1843 /* We're seeing an event on a thread id we knew had exited.
1844 This has to be a new thread reusing the old id. Add it. */
0d5b594f 1845 remote_add_thread (currthread, running, executing);
82f73884
PA
1846 return;
1847 }
1848
79d7f229 1849 if (!in_thread_list (currthread))
c0a2216e 1850 {
1941c569 1851 struct inferior *inf = NULL;
bad34192 1852 int pid = ptid_get_pid (currthread);
1941c569 1853
bad34192
PA
1854 if (ptid_is_pid (inferior_ptid)
1855 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1856 {
1857 /* inferior_ptid has no thread member yet. This can happen
1858 with the vAttach -> remote_wait,"TAAthread:" path if the
1859 stub doesn't support qC. This is the first stop reported
1860 after an attach, so this is the main thread. Update the
1861 ptid in the thread list. */
bad34192
PA
1862 if (in_thread_list (pid_to_ptid (pid)))
1863 thread_change_ptid (inferior_ptid, currthread);
1864 else
1865 {
0d5b594f 1866 remote_add_thread (currthread, running, executing);
bad34192
PA
1867 inferior_ptid = currthread;
1868 }
dc146f7c 1869 return;
c0a2216e 1870 }
82f73884
PA
1871
1872 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1873 {
1874 /* inferior_ptid is not set yet. This can happen with the
1875 vRun -> remote_wait,"TAAthread:" path if the stub
1876 doesn't support qC. This is the first stop reported
1877 after an attach, so this is the main thread. Update the
1878 ptid in the thread list. */
dc146f7c 1879 thread_change_ptid (inferior_ptid, currthread);
82f73884 1880 return;
c0a2216e 1881 }
82f73884 1882
29c87f7f
PA
1883 /* When connecting to a target remote, or to a target
1884 extended-remote which already was debugging an inferior, we
1885 may not know about it yet. Add it before adding its child
1886 thread, so notifications are emitted in a sensible order. */
1887 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1888 {
1889 struct remote_state *rs = get_remote_state ();
1890 int fake_pid_p = !remote_multi_process_p (rs);
1891
1892 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1893 ptid_get_pid (currthread), -1, 1);
49c62f2e 1894 }
29c87f7f 1895
82f73884 1896 /* This is really a new thread. Add it. */
0d5b594f 1897 remote_add_thread (currthread, running, executing);
1941c569
PA
1898
1899 /* If we found a new inferior, let the common code do whatever
1900 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1901 breakpoints), unless we're just setting up an all-stop
1902 connection. */
1941c569 1903 if (inf != NULL)
b7ea362b
PA
1904 {
1905 struct remote_state *rs = get_remote_state ();
1906
6efcd9a8 1907 if (!rs->starting_up)
0d5b594f 1908 notice_new_inferior (currthread, executing, 0);
b7ea362b 1909 }
c0a2216e 1910 }
c906108c
SS
1911}
1912
dc146f7c
VP
1913/* Return the private thread data, creating it if necessary. */
1914
70221824 1915static struct private_thread_info *
dc146f7c
VP
1916demand_private_info (ptid_t ptid)
1917{
1918 struct thread_info *info = find_thread_ptid (ptid);
1919
1920 gdb_assert (info);
1921
fe978cb0 1922 if (!info->priv)
dc146f7c 1923 {
8d749320 1924 info->priv = XNEW (struct private_thread_info);
dc146f7c 1925 info->private_dtor = free_private_thread_info;
fe978cb0 1926 info->priv->core = -1;
8020350c
DB
1927 info->priv->extra = NULL;
1928 info->priv->name = NULL;
dc146f7c
VP
1929 }
1930
fe978cb0 1931 return info->priv;
dc146f7c
VP
1932}
1933
74531fed
PA
1934/* Call this function as a result of
1935 1) A halt indication (T packet) containing a thread id
1936 2) A direct query of currthread
0df8b418 1937 3) Successful execution of set thread */
74531fed
PA
1938
1939static void
47f8a51d 1940record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1941{
47f8a51d 1942 rs->general_thread = currthread;
74531fed
PA
1943}
1944
89be2091
DJ
1945/* If 'QPassSignals' is supported, tell the remote stub what signals
1946 it can simply pass through to the inferior without reporting. */
1947
1948static void
94bedb42
TT
1949remote_pass_signals (struct target_ops *self,
1950 int numsigs, unsigned char *pass_signals)
89be2091 1951{
4082afcc 1952 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1953 {
1954 char *pass_packet, *p;
89be2091 1955 int count = 0, i;
747dc59d 1956 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1957
1958 gdb_assert (numsigs < 256);
1959 for (i = 0; i < numsigs; i++)
1960 {
2455069d 1961 if (pass_signals[i])
89be2091
DJ
1962 count++;
1963 }
224c3ddb 1964 pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
89be2091
DJ
1965 strcpy (pass_packet, "QPassSignals:");
1966 p = pass_packet + strlen (pass_packet);
1967 for (i = 0; i < numsigs; i++)
1968 {
2455069d 1969 if (pass_signals[i])
89be2091
DJ
1970 {
1971 if (i >= 16)
1972 *p++ = tohex (i >> 4);
1973 *p++ = tohex (i & 15);
1974 if (count)
1975 *p++ = ';';
1976 else
1977 break;
1978 count--;
1979 }
1980 }
1981 *p = 0;
747dc59d 1982 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1983 {
89be2091
DJ
1984 putpkt (pass_packet);
1985 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1986 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1987 if (rs->last_pass_packet)
1988 xfree (rs->last_pass_packet);
1989 rs->last_pass_packet = pass_packet;
89be2091
DJ
1990 }
1991 else
1992 xfree (pass_packet);
1993 }
1994}
1995
82075af2
JS
1996/* If 'QCatchSyscalls' is supported, tell the remote stub
1997 to report syscalls to GDB. */
1998
1999static int
2000remote_set_syscall_catchpoint (struct target_ops *self,
2001 int pid, int needed, int any_count,
2002 int table_size, int *table)
2003{
2004 char *catch_packet;
2005 enum packet_result result;
2006 int n_sysno = 0;
2007
2008 if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2009 {
2010 /* Not supported. */
2011 return 1;
2012 }
2013
2014 if (needed && !any_count)
2015 {
2016 int i;
2017
2018 /* Count how many syscalls are to be caught (table[sysno] != 0). */
2019 for (i = 0; i < table_size; i++)
2020 {
2021 if (table[i] != 0)
2022 n_sysno++;
2023 }
2024 }
2025
2026 if (remote_debug)
2027 {
2028 fprintf_unfiltered (gdb_stdlog,
2029 "remote_set_syscall_catchpoint "
2030 "pid %d needed %d any_count %d n_sysno %d\n",
2031 pid, needed, any_count, n_sysno);
2032 }
2033
2034 if (needed)
2035 {
2036 /* Prepare a packet with the sysno list, assuming max 8+1
2037 characters for a sysno. If the resulting packet size is too
2038 big, fallback on the non-selective packet. */
2039 const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2040
c0518081 2041 catch_packet = (char *) xmalloc (maxpktsz);
82075af2
JS
2042 strcpy (catch_packet, "QCatchSyscalls:1");
2043 if (!any_count)
2044 {
2045 int i;
2046 char *p;
2047
2048 p = catch_packet;
2049 p += strlen (p);
2050
2051 /* Add in catch_packet each syscall to be caught (table[i] != 0). */
2052 for (i = 0; i < table_size; i++)
2053 {
2054 if (table[i] != 0)
2055 p += xsnprintf (p, catch_packet + maxpktsz - p, ";%x", i);
2056 }
2057 }
2058 if (strlen (catch_packet) > get_remote_packet_size ())
2059 {
2060 /* catch_packet too big. Fallback to less efficient
2061 non selective mode, with GDB doing the filtering. */
2062 catch_packet[sizeof ("QCatchSyscalls:1") - 1] = 0;
2063 }
2064 }
2065 else
2066 catch_packet = xstrdup ("QCatchSyscalls:0");
2067
2068 {
2069 struct cleanup *old_chain = make_cleanup (xfree, catch_packet);
2070 struct remote_state *rs = get_remote_state ();
2071
2072 putpkt (catch_packet);
2073 getpkt (&rs->buf, &rs->buf_size, 0);
2074 result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2075 do_cleanups (old_chain);
2076 if (result == PACKET_OK)
2077 return 0;
2078 else
2079 return -1;
2080 }
2081}
2082
9b224c5e
PA
2083/* If 'QProgramSignals' is supported, tell the remote stub what
2084 signals it should pass through to the inferior when detaching. */
2085
2086static void
daf5e9b6
TT
2087remote_program_signals (struct target_ops *self,
2088 int numsigs, unsigned char *signals)
9b224c5e 2089{
4082afcc 2090 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
2091 {
2092 char *packet, *p;
2093 int count = 0, i;
5e4a05c4 2094 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
2095
2096 gdb_assert (numsigs < 256);
2097 for (i = 0; i < numsigs; i++)
2098 {
2099 if (signals[i])
2100 count++;
2101 }
224c3ddb 2102 packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
9b224c5e
PA
2103 strcpy (packet, "QProgramSignals:");
2104 p = packet + strlen (packet);
2105 for (i = 0; i < numsigs; i++)
2106 {
2107 if (signal_pass_state (i))
2108 {
2109 if (i >= 16)
2110 *p++ = tohex (i >> 4);
2111 *p++ = tohex (i & 15);
2112 if (count)
2113 *p++ = ';';
2114 else
2115 break;
2116 count--;
2117 }
2118 }
2119 *p = 0;
5e4a05c4
TT
2120 if (!rs->last_program_signals_packet
2121 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 2122 {
9b224c5e
PA
2123 putpkt (packet);
2124 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 2125 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
2126 xfree (rs->last_program_signals_packet);
2127 rs->last_program_signals_packet = packet;
9b224c5e
PA
2128 }
2129 else
2130 xfree (packet);
2131 }
2132}
2133
79d7f229
PA
2134/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
2135 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2136 thread. If GEN is set, set the general thread, if not, then set
2137 the step/continue thread. */
c906108c 2138static void
79d7f229 2139set_thread (struct ptid ptid, int gen)
c906108c 2140{
d01949b6 2141 struct remote_state *rs = get_remote_state ();
47f8a51d 2142 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 2143 char *buf = rs->buf;
79d7f229 2144 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 2145
79d7f229 2146 if (ptid_equal (state, ptid))
c906108c
SS
2147 return;
2148
79d7f229
PA
2149 *buf++ = 'H';
2150 *buf++ = gen ? 'g' : 'c';
2151 if (ptid_equal (ptid, magic_null_ptid))
2152 xsnprintf (buf, endbuf - buf, "0");
2153 else if (ptid_equal (ptid, any_thread_ptid))
2154 xsnprintf (buf, endbuf - buf, "0");
2155 else if (ptid_equal (ptid, minus_one_ptid))
2156 xsnprintf (buf, endbuf - buf, "-1");
2157 else
82f73884 2158 write_ptid (buf, endbuf, ptid);
79d7f229 2159 putpkt (rs->buf);
6d820c5c 2160 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 2161 if (gen)
47f8a51d 2162 rs->general_thread = ptid;
c906108c 2163 else
47f8a51d 2164 rs->continue_thread = ptid;
c906108c 2165}
79d7f229
PA
2166
2167static void
2168set_general_thread (struct ptid ptid)
2169{
2170 set_thread (ptid, 1);
2171}
2172
2173static void
2174set_continue_thread (struct ptid ptid)
2175{
2176 set_thread (ptid, 0);
2177}
2178
3c9c4b83
PA
2179/* Change the remote current process. Which thread within the process
2180 ends up selected isn't important, as long as it is the same process
2181 as what INFERIOR_PTID points to.
2182
2183 This comes from that fact that there is no explicit notion of
2184 "selected process" in the protocol. The selected process for
2185 general operations is the process the selected general thread
2186 belongs to. */
2187
2188static void
2189set_general_process (void)
2190{
2191 struct remote_state *rs = get_remote_state ();
2192
2193 /* If the remote can't handle multiple processes, don't bother. */
8020350c 2194 if (!remote_multi_process_p (rs))
3c9c4b83
PA
2195 return;
2196
2197 /* We only need to change the remote current thread if it's pointing
2198 at some other process. */
47f8a51d 2199 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
2200 set_general_thread (inferior_ptid);
2201}
2202
c906108c 2203\f
7d1a114c
PA
2204/* Return nonzero if this is the main thread that we made up ourselves
2205 to model non-threaded targets as single-threaded. */
c906108c
SS
2206
2207static int
7d1a114c 2208remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 2209{
c0a2216e
PA
2210 if (ptid_equal (ptid, magic_null_ptid))
2211 /* The main thread is always alive. */
2212 return 1;
2213
ba348170 2214 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2215 /* The main thread is always alive. This can happen after a
2216 vAttach, if the remote side doesn't support
2217 multi-threading. */
2218 return 1;
2219
7d1a114c
PA
2220 return 0;
2221}
2222
2223/* Return nonzero if the thread PTID is still alive on the remote
2224 system. */
2225
2226static int
2227remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2228{
2229 struct remote_state *rs = get_remote_state ();
2230 char *p, *endp;
2231
2232 /* Check if this is a thread that we made up ourselves to model
2233 non-threaded targets as single-threaded. */
2234 if (remote_thread_always_alive (ops, ptid))
2235 return 1;
2236
82f73884
PA
2237 p = rs->buf;
2238 endp = rs->buf + get_remote_packet_size ();
2239
2240 *p++ = 'T';
2241 write_ptid (p, endp, ptid);
2242
2e9f7625 2243 putpkt (rs->buf);
6d820c5c 2244 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2245 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2246}
2247
79efa585
SM
2248/* Return a pointer to a thread name if we know it and NULL otherwise.
2249 The thread_info object owns the memory for the name. */
2250
2251static const char *
2252remote_thread_name (struct target_ops *ops, struct thread_info *info)
2253{
2254 if (info->priv != NULL)
2255 return info->priv->name;
2256
2257 return NULL;
2258}
2259
c906108c
SS
2260/* About these extended threadlist and threadinfo packets. They are
2261 variable length packets but, the fields within them are often fixed
2262 length. They are redundent enough to send over UDP as is the
2263 remote protocol in general. There is a matching unit test module
2264 in libstub. */
2265
23860348 2266/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2267 libstub protocol encoding, and remote.c. It is not particularly
23860348 2268 changable. */
cce74817
JM
2269
2270/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2271 Plan to fix this. */
cce74817 2272
23860348 2273typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2274
9d1f7ab2 2275/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2276 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2277
2278struct gdb_ext_thread_info
c5aa993b 2279 {
23860348 2280 threadref threadid; /* External form of thread reference. */
2bc416ba 2281 int active; /* Has state interesting to GDB?
23860348 2282 regs, stack. */
2bc416ba 2283 char display[256]; /* Brief state display, name,
cedea757 2284 blocked/suspended. */
23860348 2285 char shortname[32]; /* To be used to name threads. */
2bc416ba 2286 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2287 whatever. */
c5aa993b 2288 };
cce74817
JM
2289
2290/* The volume of remote transfers can be limited by submitting
2291 a mask containing bits specifying the desired information.
2292 Use a union of these values as the 'selection' parameter to
0df8b418 2293 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2294
2295#define TAG_THREADID 1
2296#define TAG_EXISTS 2
2297#define TAG_DISPLAY 4
2298#define TAG_THREADNAME 8
c5aa993b 2299#define TAG_MOREDISPLAY 16
cce74817 2300
23860348 2301#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2302
a14ed312 2303static char *unpack_nibble (char *buf, int *val);
cce74817 2304
a14ed312 2305static char *unpack_byte (char *buf, int *value);
cce74817 2306
a14ed312 2307static char *pack_int (char *buf, int value);
cce74817 2308
a14ed312 2309static char *unpack_int (char *buf, int *value);
cce74817 2310
a14ed312 2311static char *unpack_string (char *src, char *dest, int length);
cce74817 2312
23860348 2313static char *pack_threadid (char *pkt, threadref *id);
cce74817 2314
23860348 2315static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2316
23860348 2317void int_to_threadref (threadref *id, int value);
cce74817 2318
23860348 2319static int threadref_to_int (threadref *ref);
cce74817 2320
23860348 2321static void copy_threadref (threadref *dest, threadref *src);
cce74817 2322
23860348 2323static int threadmatch (threadref *dest, threadref *src);
cce74817 2324
2bc416ba 2325static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2326 threadref *id);
cce74817 2327
a14ed312 2328static int remote_unpack_thread_info_response (char *pkt,
23860348 2329 threadref *expectedref,
a14ed312
KB
2330 struct gdb_ext_thread_info
2331 *info);
cce74817
JM
2332
2333
2bc416ba 2334static int remote_get_threadinfo (threadref *threadid,
23860348 2335 int fieldset, /*TAG mask */
a14ed312 2336 struct gdb_ext_thread_info *info);
cce74817 2337
a14ed312
KB
2338static char *pack_threadlist_request (char *pkt, int startflag,
2339 int threadcount,
23860348 2340 threadref *nextthread);
cce74817 2341
a14ed312
KB
2342static int parse_threadlist_response (char *pkt,
2343 int result_limit,
23860348 2344 threadref *original_echo,
2bc416ba 2345 threadref *resultlist,
23860348 2346 int *doneflag);
cce74817 2347
a14ed312 2348static int remote_get_threadlist (int startflag,
23860348 2349 threadref *nextthread,
a14ed312
KB
2350 int result_limit,
2351 int *done,
2bc416ba 2352 int *result_count,
23860348 2353 threadref *threadlist);
cce74817 2354
23860348 2355typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2356
a14ed312
KB
2357static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2358 void *context, int looplimit);
cce74817 2359
23860348 2360static int remote_newthread_step (threadref *ref, void *context);
cce74817 2361
82f73884
PA
2362
2363/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2364 buffer we're allowed to write to. Returns
2365 BUF+CHARACTERS_WRITTEN. */
2366
2367static char *
2368write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2369{
2370 int pid, tid;
2371 struct remote_state *rs = get_remote_state ();
2372
2373 if (remote_multi_process_p (rs))
2374 {
2375 pid = ptid_get_pid (ptid);
2376 if (pid < 0)
2377 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2378 else
2379 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2380 }
ba348170 2381 tid = ptid_get_lwp (ptid);
82f73884
PA
2382 if (tid < 0)
2383 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2384 else
2385 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2386
2387 return buf;
2388}
2389
2390/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2391 passed the last parsed char. Returns null_ptid on error. */
2392
2393static ptid_t
2394read_ptid (char *buf, char **obuf)
2395{
2396 char *p = buf;
2397 char *pp;
2398 ULONGEST pid = 0, tid = 0;
82f73884
PA
2399
2400 if (*p == 'p')
2401 {
2402 /* Multi-process ptid. */
2403 pp = unpack_varlen_hex (p + 1, &pid);
2404 if (*pp != '.')
b37520b6 2405 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2406
2407 p = pp;
2408 pp = unpack_varlen_hex (p + 1, &tid);
2409 if (obuf)
2410 *obuf = pp;
ba348170 2411 return ptid_build (pid, tid, 0);
82f73884
PA
2412 }
2413
2414 /* No multi-process. Just a tid. */
2415 pp = unpack_varlen_hex (p, &tid);
2416
c9f35b34
KB
2417 /* Return null_ptid when no thread id is found. */
2418 if (p == pp)
2419 {
2420 if (obuf)
2421 *obuf = pp;
2422 return null_ptid;
2423 }
2424
82f73884 2425 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2426 what's in inferior_ptid, unless it's null at this point. If so,
2427 then since there's no way to know the pid of the reported
2428 threads, use the magic number. */
2429 if (ptid_equal (inferior_ptid, null_ptid))
2430 pid = ptid_get_pid (magic_null_ptid);
2431 else
2432 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2433
2434 if (obuf)
2435 *obuf = pp;
ba348170 2436 return ptid_build (pid, tid, 0);
82f73884
PA
2437}
2438
c906108c 2439static int
fba45db2 2440stubhex (int ch)
c906108c
SS
2441{
2442 if (ch >= 'a' && ch <= 'f')
2443 return ch - 'a' + 10;
2444 if (ch >= '0' && ch <= '9')
2445 return ch - '0';
2446 if (ch >= 'A' && ch <= 'F')
2447 return ch - 'A' + 10;
2448 return -1;
2449}
2450
2451static int
fba45db2 2452stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2453{
2454 int nibble;
2455 int retval = 0;
2456
2457 while (fieldlength)
2458 {
2459 nibble = stubhex (*buff++);
2460 retval |= nibble;
2461 fieldlength--;
2462 if (fieldlength)
2463 retval = retval << 4;
2464 }
2465 return retval;
2466}
2467
c906108c 2468static char *
fba45db2 2469unpack_nibble (char *buf, int *val)
c906108c 2470{
b7589f7d 2471 *val = fromhex (*buf++);
c906108c
SS
2472 return buf;
2473}
2474
c906108c 2475static char *
fba45db2 2476unpack_byte (char *buf, int *value)
c906108c
SS
2477{
2478 *value = stub_unpack_int (buf, 2);
2479 return buf + 2;
2480}
2481
2482static char *
fba45db2 2483pack_int (char *buf, int value)
c906108c
SS
2484{
2485 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2486 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2487 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2488 buf = pack_hex_byte (buf, (value & 0xff));
2489 return buf;
2490}
2491
2492static char *
fba45db2 2493unpack_int (char *buf, int *value)
c906108c
SS
2494{
2495 *value = stub_unpack_int (buf, 8);
2496 return buf + 8;
2497}
2498
23860348 2499#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2500static char *pack_string (char *pkt, char *string);
c906108c
SS
2501
2502static char *
fba45db2 2503pack_string (char *pkt, char *string)
c906108c
SS
2504{
2505 char ch;
2506 int len;
2507
2508 len = strlen (string);
2509 if (len > 200)
23860348 2510 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2511 pkt = pack_hex_byte (pkt, len);
2512 while (len-- > 0)
2513 {
2514 ch = *string++;
2515 if ((ch == '\0') || (ch == '#'))
23860348 2516 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2517 *pkt++ = ch;
2518 }
2519 return pkt;
2520}
2521#endif /* 0 (unused) */
2522
2523static char *
fba45db2 2524unpack_string (char *src, char *dest, int length)
c906108c
SS
2525{
2526 while (length--)
2527 *dest++ = *src++;
2528 *dest = '\0';
2529 return src;
2530}
2531
2532static char *
fba45db2 2533pack_threadid (char *pkt, threadref *id)
c906108c
SS
2534{
2535 char *limit;
2536 unsigned char *altid;
2537
2538 altid = (unsigned char *) id;
2539 limit = pkt + BUF_THREAD_ID_SIZE;
2540 while (pkt < limit)
2541 pkt = pack_hex_byte (pkt, *altid++);
2542 return pkt;
2543}
2544
2545
2546static char *
fba45db2 2547unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2548{
2549 char *altref;
2550 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2551 int x, y;
2552
2553 altref = (char *) id;
2554
2555 while (inbuf < limit)
2556 {
2557 x = stubhex (*inbuf++);
2558 y = stubhex (*inbuf++);
2559 *altref++ = (x << 4) | y;
2560 }
2561 return inbuf;
2562}
2563
2564/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2565 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2566 to use 64bit thread references internally. This is an adapter
2567 function. */
2568
2569void
fba45db2 2570int_to_threadref (threadref *id, int value)
c906108c
SS
2571{
2572 unsigned char *scan;
2573
2574 scan = (unsigned char *) id;
2575 {
2576 int i = 4;
2577 while (i--)
2578 *scan++ = 0;
2579 }
2580 *scan++ = (value >> 24) & 0xff;
2581 *scan++ = (value >> 16) & 0xff;
2582 *scan++ = (value >> 8) & 0xff;
2583 *scan++ = (value & 0xff);
2584}
2585
2586static int
fba45db2 2587threadref_to_int (threadref *ref)
c906108c
SS
2588{
2589 int i, value = 0;
2590 unsigned char *scan;
2591
cfd77fa1 2592 scan = *ref;
c906108c
SS
2593 scan += 4;
2594 i = 4;
2595 while (i-- > 0)
2596 value = (value << 8) | ((*scan++) & 0xff);
2597 return value;
2598}
2599
2600static void
fba45db2 2601copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2602{
2603 int i;
2604 unsigned char *csrc, *cdest;
2605
2606 csrc = (unsigned char *) src;
2607 cdest = (unsigned char *) dest;
2608 i = 8;
2609 while (i--)
2610 *cdest++ = *csrc++;
2611}
2612
2613static int
fba45db2 2614threadmatch (threadref *dest, threadref *src)
c906108c 2615{
23860348 2616 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2617#if 0
2618 unsigned char *srcp, *destp;
2619 int i, result;
2620 srcp = (char *) src;
2621 destp = (char *) dest;
2622
2623 result = 1;
2624 while (i-- > 0)
2625 result &= (*srcp++ == *destp++) ? 1 : 0;
2626 return result;
2627#endif
2628 return 1;
2629}
2630
2631/*
c5aa993b
JM
2632 threadid:1, # always request threadid
2633 context_exists:2,
2634 display:4,
2635 unique_name:8,
2636 more_display:16
2637 */
c906108c
SS
2638
2639/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2640
2641static char *
fba45db2 2642pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2643{
23860348
MS
2644 *pkt++ = 'q'; /* Info Query */
2645 *pkt++ = 'P'; /* process or thread info */
2646 pkt = pack_int (pkt, mode); /* mode */
c906108c 2647 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2648 *pkt = '\0'; /* terminate */
c906108c
SS
2649 return pkt;
2650}
2651
23860348 2652/* These values tag the fields in a thread info response packet. */
c906108c 2653/* Tagging the fields allows us to request specific fields and to
23860348 2654 add more fields as time goes by. */
c906108c 2655
23860348 2656#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2657#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2658 fetch registers and its stack? */
c5aa993b 2659#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2660#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2661#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2662 the process. */
c906108c
SS
2663
2664static int
fba45db2
KB
2665remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2666 struct gdb_ext_thread_info *info)
c906108c 2667{
d01949b6 2668 struct remote_state *rs = get_remote_state ();
c906108c 2669 int mask, length;
cfd77fa1 2670 int tag;
c906108c 2671 threadref ref;
6d820c5c 2672 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2673 int retval = 1;
2674
23860348 2675 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2676 info->active = 0;
2677 info->display[0] = '\0';
2678 info->shortname[0] = '\0';
2679 info->more_display[0] = '\0';
2680
23860348
MS
2681 /* Assume the characters indicating the packet type have been
2682 stripped. */
c906108c
SS
2683 pkt = unpack_int (pkt, &mask); /* arg mask */
2684 pkt = unpack_threadid (pkt, &ref);
2685
2686 if (mask == 0)
8a3fe4f8 2687 warning (_("Incomplete response to threadinfo request."));
c906108c 2688 if (!threadmatch (&ref, expectedref))
23860348 2689 { /* This is an answer to a different request. */
8a3fe4f8 2690 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2691 return 0;
2692 }
2693 copy_threadref (&info->threadid, &ref);
2694
23860348 2695 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2696
23860348
MS
2697 /* Packets are terminated with nulls. */
2698 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2699 {
2700 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2701 pkt = unpack_byte (pkt, &length); /* length */
2702 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2703 {
8a3fe4f8 2704 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2705 retval = 0;
2706 break;
2707 }
2708 if (tag == TAG_THREADID)
2709 {
2710 if (length != 16)
2711 {
8a3fe4f8 2712 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2713 retval = 0;
2714 break;
2715 }
2716 pkt = unpack_threadid (pkt, &ref);
2717 mask = mask & ~TAG_THREADID;
2718 continue;
2719 }
2720 if (tag == TAG_EXISTS)
2721 {
2722 info->active = stub_unpack_int (pkt, length);
2723 pkt += length;
2724 mask = mask & ~(TAG_EXISTS);
2725 if (length > 8)
2726 {
8a3fe4f8 2727 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2728 retval = 0;
2729 break;
2730 }
2731 continue;
2732 }
2733 if (tag == TAG_THREADNAME)
2734 {
2735 pkt = unpack_string (pkt, &info->shortname[0], length);
2736 mask = mask & ~TAG_THREADNAME;
2737 continue;
2738 }
2739 if (tag == TAG_DISPLAY)
2740 {
2741 pkt = unpack_string (pkt, &info->display[0], length);
2742 mask = mask & ~TAG_DISPLAY;
2743 continue;
2744 }
2745 if (tag == TAG_MOREDISPLAY)
2746 {
2747 pkt = unpack_string (pkt, &info->more_display[0], length);
2748 mask = mask & ~TAG_MOREDISPLAY;
2749 continue;
2750 }
8a3fe4f8 2751 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2752 break; /* Not a tag we know about. */
c906108c
SS
2753 }
2754 return retval;
2755}
2756
2757static int
fba45db2
KB
2758remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2759 struct gdb_ext_thread_info *info)
c906108c 2760{
d01949b6 2761 struct remote_state *rs = get_remote_state ();
c906108c 2762 int result;
c906108c 2763
2e9f7625
DJ
2764 pack_threadinfo_request (rs->buf, fieldset, threadid);
2765 putpkt (rs->buf);
6d820c5c 2766 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2767
2768 if (rs->buf[0] == '\0')
2769 return 0;
2770
2e9f7625 2771 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2772 threadid, info);
c906108c
SS
2773 return result;
2774}
2775
c906108c
SS
2776/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2777
2778static char *
fba45db2
KB
2779pack_threadlist_request (char *pkt, int startflag, int threadcount,
2780 threadref *nextthread)
c906108c
SS
2781{
2782 *pkt++ = 'q'; /* info query packet */
2783 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2784 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2785 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2786 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2787 *pkt = '\0';
2788 return pkt;
2789}
2790
2791/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2792
2793static int
fba45db2
KB
2794parse_threadlist_response (char *pkt, int result_limit,
2795 threadref *original_echo, threadref *resultlist,
2796 int *doneflag)
c906108c 2797{
d01949b6 2798 struct remote_state *rs = get_remote_state ();
c906108c
SS
2799 char *limit;
2800 int count, resultcount, done;
2801
2802 resultcount = 0;
2803 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2804 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2805 /* done parse past here */
c906108c
SS
2806 pkt = unpack_byte (pkt, &count); /* count field */
2807 pkt = unpack_nibble (pkt, &done);
2808 /* The first threadid is the argument threadid. */
2809 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2810 while ((count-- > 0) && (pkt < limit))
2811 {
2812 pkt = unpack_threadid (pkt, resultlist++);
2813 if (resultcount++ >= result_limit)
2814 break;
2815 }
2816 if (doneflag)
2817 *doneflag = done;
2818 return resultcount;
2819}
2820
6dc54d91
PA
2821/* Fetch the next batch of threads from the remote. Returns -1 if the
2822 qL packet is not supported, 0 on error and 1 on success. */
2823
c906108c 2824static int
fba45db2
KB
2825remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2826 int *done, int *result_count, threadref *threadlist)
c906108c 2827{
d01949b6 2828 struct remote_state *rs = get_remote_state ();
c906108c
SS
2829 int result = 1;
2830
23860348 2831 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2832 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2833 >= get_remote_packet_size ())
ea9c271d 2834 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2835
6d820c5c
DJ
2836 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2837 putpkt (rs->buf);
2838 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2839 if (*rs->buf == '\0')
6dc54d91
PA
2840 {
2841 /* Packet not supported. */
2842 return -1;
2843 }
2844
2845 *result_count =
2846 parse_threadlist_response (rs->buf + 2, result_limit,
2847 &rs->echo_nextthread, threadlist, done);
c906108c 2848
0d031856 2849 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2850 {
23860348
MS
2851 /* FIXME: This is a good reason to drop the packet. */
2852 /* Possably, there is a duplicate response. */
c906108c
SS
2853 /* Possabilities :
2854 retransmit immediatly - race conditions
2855 retransmit after timeout - yes
2856 exit
2857 wait for packet, then exit
2858 */
8a3fe4f8 2859 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2860 return 0; /* I choose simply exiting. */
c906108c
SS
2861 }
2862 if (*result_count <= 0)
2863 {
2864 if (*done != 1)
2865 {
8a3fe4f8 2866 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2867 result = 0;
2868 }
2869 return result; /* break; */
2870 }
2871 if (*result_count > result_limit)
2872 {
2873 *result_count = 0;
8a3fe4f8 2874 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2875 return 0;
2876 }
2877 return result;
2878}
2879
6dc54d91
PA
2880/* Fetch the list of remote threads, with the qL packet, and call
2881 STEPFUNCTION for each thread found. Stops iterating and returns 1
2882 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2883 STEPFUNCTION returns false. If the packet is not supported,
2884 returns -1. */
c906108c 2885
c906108c 2886static int
fba45db2
KB
2887remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2888 int looplimit)
c906108c 2889{
0d031856 2890 struct remote_state *rs = get_remote_state ();
c906108c
SS
2891 int done, i, result_count;
2892 int startflag = 1;
2893 int result = 1;
2894 int loopcount = 0;
c906108c
SS
2895
2896 done = 0;
2897 while (!done)
2898 {
2899 if (loopcount++ > looplimit)
2900 {
2901 result = 0;
8a3fe4f8 2902 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2903 break;
2904 }
6dc54d91
PA
2905 result = remote_get_threadlist (startflag, &rs->nextthread,
2906 MAXTHREADLISTRESULTS,
2907 &done, &result_count,
2908 rs->resultthreadlist);
2909 if (result <= 0)
2910 break;
23860348 2911 /* Clear for later iterations. */
c906108c
SS
2912 startflag = 0;
2913 /* Setup to resume next batch of thread references, set nextthread. */
2914 if (result_count >= 1)
0d031856
TT
2915 copy_threadref (&rs->nextthread,
2916 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2917 i = 0;
2918 while (result_count--)
6dc54d91
PA
2919 {
2920 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2921 {
2922 result = 0;
2923 break;
2924 }
2925 }
c906108c
SS
2926 }
2927 return result;
2928}
2929
6dc54d91
PA
2930/* A thread found on the remote target. */
2931
2932typedef struct thread_item
2933{
2934 /* The thread's PTID. */
2935 ptid_t ptid;
2936
2937 /* The thread's extra info. May be NULL. */
2938 char *extra;
2939
79efa585
SM
2940 /* The thread's name. May be NULL. */
2941 char *name;
2942
6dc54d91
PA
2943 /* The core the thread was running on. -1 if not known. */
2944 int core;
2945} thread_item_t;
2946DEF_VEC_O(thread_item_t);
2947
2948/* Context passed around to the various methods listing remote
2949 threads. As new threads are found, they're added to the ITEMS
2950 vector. */
2951
2952struct threads_listing_context
2953{
2954 /* The threads found on the remote target. */
2955 VEC (thread_item_t) *items;
2956};
2957
80134cf5
PA
2958/* Discard the contents of the constructed thread listing context. */
2959
2960static void
2961clear_threads_listing_context (void *p)
2962{
19ba03f4
SM
2963 struct threads_listing_context *context
2964 = (struct threads_listing_context *) p;
80134cf5
PA
2965 int i;
2966 struct thread_item *item;
2967
2968 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
79efa585
SM
2969 {
2970 xfree (item->extra);
2971 xfree (item->name);
2972 }
80134cf5
PA
2973
2974 VEC_free (thread_item_t, context->items);
2975}
2976
cbb8991c
DB
2977/* Remove the thread specified as the related_pid field of WS
2978 from the CONTEXT list. */
2979
2980static void
2981threads_listing_context_remove (struct target_waitstatus *ws,
2982 struct threads_listing_context *context)
2983{
2984 struct thread_item *item;
2985 int i;
2986 ptid_t child_ptid = ws->value.related_pid;
2987
2988 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2989 {
2990 if (ptid_equal (item->ptid, child_ptid))
2991 {
2992 VEC_ordered_remove (thread_item_t, context->items, i);
2993 break;
2994 }
2995 }
2996}
2997
c906108c 2998static int
6dc54d91 2999remote_newthread_step (threadref *ref, void *data)
c906108c 3000{
19ba03f4
SM
3001 struct threads_listing_context *context
3002 = (struct threads_listing_context *) data;
6dc54d91 3003 struct thread_item item;
79d7f229 3004 int pid = ptid_get_pid (inferior_ptid);
39f77062 3005
6dc54d91
PA
3006 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
3007 item.core = -1;
2e3b657e 3008 item.name = NULL;
6dc54d91
PA
3009 item.extra = NULL;
3010
3011 VEC_safe_push (thread_item_t, context->items, &item);
3012
c906108c
SS
3013 return 1; /* continue iterator */
3014}
3015
3016#define CRAZY_MAX_THREADS 1000
3017
39f77062
KB
3018static ptid_t
3019remote_current_thread (ptid_t oldpid)
c906108c 3020{
d01949b6 3021 struct remote_state *rs = get_remote_state ();
c906108c
SS
3022
3023 putpkt ("qC");
6d820c5c 3024 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3025 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
3026 {
3027 char *obuf;
3028 ptid_t result;
3029
3030 result = read_ptid (&rs->buf[2], &obuf);
3031 if (*obuf != '\0' && remote_debug)
3032 fprintf_unfiltered (gdb_stdlog,
3033 "warning: garbage in qC reply\n");
3034
3035 return result;
3036 }
c906108c
SS
3037 else
3038 return oldpid;
3039}
3040
6dc54d91 3041/* List remote threads using the deprecated qL packet. */
cce74817 3042
6dc54d91
PA
3043static int
3044remote_get_threads_with_ql (struct target_ops *ops,
3045 struct threads_listing_context *context)
c906108c 3046{
6dc54d91
PA
3047 if (remote_threadlist_iterator (remote_newthread_step, context,
3048 CRAZY_MAX_THREADS) >= 0)
3049 return 1;
3050
3051 return 0;
c906108c
SS
3052}
3053
dc146f7c
VP
3054#if defined(HAVE_LIBEXPAT)
3055
dc146f7c
VP
3056static void
3057start_thread (struct gdb_xml_parser *parser,
3058 const struct gdb_xml_element *element,
3059 void *user_data, VEC(gdb_xml_value_s) *attributes)
3060{
19ba03f4
SM
3061 struct threads_listing_context *data
3062 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3063
3064 struct thread_item item;
3065 char *id;
3d2c1d41 3066 struct gdb_xml_value *attr;
dc146f7c 3067
19ba03f4 3068 id = (char *) xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
3069 item.ptid = read_ptid (id, NULL);
3070
3d2c1d41
PA
3071 attr = xml_find_attribute (attributes, "core");
3072 if (attr != NULL)
3073 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
3074 else
3075 item.core = -1;
3076
79efa585 3077 attr = xml_find_attribute (attributes, "name");
e1961661 3078 item.name = attr != NULL ? xstrdup ((const char *) attr->value) : NULL;
79efa585 3079
dc146f7c
VP
3080 item.extra = 0;
3081
3082 VEC_safe_push (thread_item_t, data->items, &item);
3083}
3084
3085static void
3086end_thread (struct gdb_xml_parser *parser,
3087 const struct gdb_xml_element *element,
3088 void *user_data, const char *body_text)
3089{
19ba03f4
SM
3090 struct threads_listing_context *data
3091 = (struct threads_listing_context *) user_data;
dc146f7c
VP
3092
3093 if (body_text && *body_text)
2ae2a0b7 3094 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
3095}
3096
3097const struct gdb_xml_attribute thread_attributes[] = {
3098 { "id", GDB_XML_AF_NONE, NULL, NULL },
3099 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
79efa585 3100 { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
dc146f7c
VP
3101 { NULL, GDB_XML_AF_NONE, NULL, NULL }
3102};
3103
3104const struct gdb_xml_element thread_children[] = {
3105 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3106};
3107
3108const struct gdb_xml_element threads_children[] = {
3109 { "thread", thread_attributes, thread_children,
3110 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3111 start_thread, end_thread },
3112 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3113};
3114
3115const struct gdb_xml_element threads_elements[] = {
3116 { "threads", NULL, threads_children,
3117 GDB_XML_EF_NONE, NULL, NULL },
3118 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3119};
3120
3121#endif
3122
6dc54d91 3123/* List remote threads using qXfer:threads:read. */
9d1f7ab2 3124
6dc54d91
PA
3125static int
3126remote_get_threads_with_qxfer (struct target_ops *ops,
3127 struct threads_listing_context *context)
0f71a2f6 3128{
dc146f7c 3129#if defined(HAVE_LIBEXPAT)
4082afcc 3130 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 3131 {
6dc54d91 3132 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 3133 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 3134
6dc54d91 3135 if (xml != NULL && *xml != '\0')
dc146f7c 3136 {
6dc54d91
PA
3137 gdb_xml_parse_quick (_("threads"), "threads.dtd",
3138 threads_elements, xml, context);
dc146f7c
VP
3139 }
3140
3141 do_cleanups (back_to);
6dc54d91 3142 return 1;
dc146f7c
VP
3143 }
3144#endif
3145
6dc54d91
PA
3146 return 0;
3147}
3148
3149/* List remote threads using qfThreadInfo/qsThreadInfo. */
3150
3151static int
3152remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3153 struct threads_listing_context *context)
3154{
3155 struct remote_state *rs = get_remote_state ();
3156
b80fafe3 3157 if (rs->use_threadinfo_query)
9d1f7ab2 3158 {
6dc54d91
PA
3159 char *bufp;
3160
9d1f7ab2 3161 putpkt ("qfThreadInfo");
6d820c5c 3162 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3163 bufp = rs->buf;
9d1f7ab2 3164 if (bufp[0] != '\0') /* q packet recognized */
802188a7 3165 {
9d1f7ab2
MS
3166 while (*bufp++ == 'm') /* reply contains one or more TID */
3167 {
3168 do
3169 {
6dc54d91
PA
3170 struct thread_item item;
3171
3172 item.ptid = read_ptid (bufp, &bufp);
3173 item.core = -1;
2e3b657e 3174 item.name = NULL;
6dc54d91
PA
3175 item.extra = NULL;
3176
3177 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
3178 }
3179 while (*bufp++ == ','); /* comma-separated list */
3180 putpkt ("qsThreadInfo");
6d820c5c 3181 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 3182 bufp = rs->buf;
9d1f7ab2 3183 }
6dc54d91
PA
3184 return 1;
3185 }
3186 else
3187 {
3188 /* Packet not recognized. */
3189 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
3190 }
3191 }
3192
6dc54d91
PA
3193 return 0;
3194}
3195
e8032dde 3196/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
3197 targets. */
3198
3199static void
e8032dde 3200remote_update_thread_list (struct target_ops *ops)
6dc54d91 3201{
6dc54d91
PA
3202 struct threads_listing_context context;
3203 struct cleanup *old_chain;
ab970af1 3204 int got_list = 0;
e8032dde 3205
6dc54d91
PA
3206 context.items = NULL;
3207 old_chain = make_cleanup (clear_threads_listing_context, &context);
3208
3209 /* We have a few different mechanisms to fetch the thread list. Try
3210 them all, starting with the most preferred one first, falling
3211 back to older methods. */
3212 if (remote_get_threads_with_qxfer (ops, &context)
3213 || remote_get_threads_with_qthreadinfo (ops, &context)
3214 || remote_get_threads_with_ql (ops, &context))
3215 {
3216 int i;
3217 struct thread_item *item;
ab970af1
PA
3218 struct thread_info *tp, *tmp;
3219
3220 got_list = 1;
3221
7d1a114c
PA
3222 if (VEC_empty (thread_item_t, context.items)
3223 && remote_thread_always_alive (ops, inferior_ptid))
3224 {
3225 /* Some targets don't really support threads, but still
3226 reply an (empty) thread list in response to the thread
3227 listing packets, instead of replying "packet not
3228 supported". Exit early so we don't delete the main
3229 thread. */
3230 do_cleanups (old_chain);
3231 return;
3232 }
3233
ab970af1
PA
3234 /* CONTEXT now holds the current thread list on the remote
3235 target end. Delete GDB-side threads no longer found on the
3236 target. */
8a06aea7 3237 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3238 {
ab970af1
PA
3239 for (i = 0;
3240 VEC_iterate (thread_item_t, context.items, i, item);
3241 ++i)
3242 {
3243 if (ptid_equal (item->ptid, tp->ptid))
3244 break;
3245 }
3246
3247 if (i == VEC_length (thread_item_t, context.items))
3248 {
3249 /* Not found. */
3250 delete_thread (tp->ptid);
3251 }
cbb8991c
DB
3252 }
3253
3254 /* Remove any unreported fork child threads from CONTEXT so
3255 that we don't interfere with follow fork, which is where
3256 creation of such threads is handled. */
3257 remove_new_fork_children (&context);
74531fed 3258
ab970af1 3259 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3260 for (i = 0;
3261 VEC_iterate (thread_item_t, context.items, i, item);
3262 ++i)
3263 {
3264 if (!ptid_equal (item->ptid, null_ptid))
3265 {
3266 struct private_thread_info *info;
3267 /* In non-stop mode, we assume new found threads are
0d5b594f
PA
3268 executing until proven otherwise with a stop reply.
3269 In all-stop, we can only get here if all threads are
6dc54d91 3270 stopped. */
0d5b594f 3271 int executing = target_is_non_stop_p () ? 1 : 0;
6dc54d91 3272
0d5b594f 3273 remote_notice_new_inferior (item->ptid, executing);
6dc54d91
PA
3274
3275 info = demand_private_info (item->ptid);
3276 info->core = item->core;
3277 info->extra = item->extra;
3278 item->extra = NULL;
79efa585
SM
3279 info->name = item->name;
3280 item->name = NULL;
6dc54d91
PA
3281 }
3282 }
3283 }
3284
ab970af1
PA
3285 if (!got_list)
3286 {
3287 /* If no thread listing method is supported, then query whether
3288 each known thread is alive, one by one, with the T packet.
3289 If the target doesn't support threads at all, then this is a
3290 no-op. See remote_thread_alive. */
3291 prune_threads ();
3292 }
3293
6dc54d91 3294 do_cleanups (old_chain);
9d1f7ab2
MS
3295}
3296
802188a7 3297/*
9d1f7ab2
MS
3298 * Collect a descriptive string about the given thread.
3299 * The target may say anything it wants to about the thread
3300 * (typically info about its blocked / runnable state, name, etc.).
3301 * This string will appear in the info threads display.
802188a7 3302 *
9d1f7ab2
MS
3303 * Optional: targets are not required to implement this function.
3304 */
3305
3306static char *
c15906d8 3307remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3308{
d01949b6 3309 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3310 int result;
3311 int set;
3312 threadref id;
3313 struct gdb_ext_thread_info threadinfo;
23860348 3314 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3315 int n = 0; /* position in display_buf */
3316
5d93a237 3317 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3318 internal_error (__FILE__, __LINE__,
e2e0b3e5 3319 _("remote_threads_extra_info"));
9d1f7ab2 3320
60e569b9 3321 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3322 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3323 /* This is the main thread which was added by GDB. The remote
3324 server doesn't know about it. */
3325 return NULL;
3326
4082afcc 3327 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3328 {
3329 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3330
fe978cb0
PA
3331 if (info && info->priv)
3332 return info->priv->extra;
dc146f7c
VP
3333 else
3334 return NULL;
3335 }
3336
b80fafe3 3337 if (rs->use_threadextra_query)
9d1f7ab2 3338 {
82f73884
PA
3339 char *b = rs->buf;
3340 char *endb = rs->buf + get_remote_packet_size ();
3341
3342 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3343 b += strlen (b);
3344 write_ptid (b, endb, tp->ptid);
3345
2e9f7625 3346 putpkt (rs->buf);
6d820c5c 3347 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3348 if (rs->buf[0] != 0)
9d1f7ab2 3349 {
2e9f7625
DJ
3350 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3351 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3352 display_buf [result] = '\0';
9d1f7ab2
MS
3353 return display_buf;
3354 }
0f71a2f6 3355 }
9d1f7ab2
MS
3356
3357 /* If the above query fails, fall back to the old method. */
b80fafe3 3358 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3359 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3360 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3361 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3362 if (remote_get_threadinfo (&id, set, &threadinfo))
3363 if (threadinfo.active)
0f71a2f6 3364 {
9d1f7ab2 3365 if (*threadinfo.shortname)
2bc416ba 3366 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3367 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3368 if (*threadinfo.display)
2bc416ba 3369 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3370 " State: %s,", threadinfo.display);
9d1f7ab2 3371 if (*threadinfo.more_display)
2bc416ba 3372 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3373 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3374
3375 if (n > 0)
c5aa993b 3376 {
23860348 3377 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3378 if (',' == display_buf[n-1])
3379 display_buf[n-1] = ' ';
3380 return display_buf;
c5aa993b 3381 }
0f71a2f6 3382 }
9d1f7ab2 3383 return NULL;
0f71a2f6 3384}
c906108c 3385\f
c5aa993b 3386
0fb4aa4b 3387static int
61fc905d 3388remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3389 struct static_tracepoint_marker *marker)
3390{
3391 struct remote_state *rs = get_remote_state ();
3392 char *p = rs->buf;
3393
bba74b36 3394 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3395 p += strlen (p);
3396 p += hexnumstr (p, addr);
3397 putpkt (rs->buf);
3398 getpkt (&rs->buf, &rs->buf_size, 0);
3399 p = rs->buf;
3400
3401 if (*p == 'E')
3402 error (_("Remote failure reply: %s"), p);
3403
3404 if (*p++ == 'm')
3405 {
3406 parse_static_tracepoint_marker_definition (p, &p, marker);
3407 return 1;
3408 }
3409
3410 return 0;
3411}
3412
0fb4aa4b 3413static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3414remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3415 const char *strid)
0fb4aa4b
PA
3416{
3417 struct remote_state *rs = get_remote_state ();
3418 VEC(static_tracepoint_marker_p) *markers = NULL;
3419 struct static_tracepoint_marker *marker = NULL;
3420 struct cleanup *old_chain;
3421 char *p;
3422
3423 /* Ask for a first packet of static tracepoint marker
3424 definition. */
3425 putpkt ("qTfSTM");
3426 getpkt (&rs->buf, &rs->buf_size, 0);
3427 p = rs->buf;
3428 if (*p == 'E')
3429 error (_("Remote failure reply: %s"), p);
3430
3431 old_chain = make_cleanup (free_current_marker, &marker);
3432
3433 while (*p++ == 'm')
3434 {
3435 if (marker == NULL)
3436 marker = XCNEW (struct static_tracepoint_marker);
3437
3438 do
3439 {
3440 parse_static_tracepoint_marker_definition (p, &p, marker);
3441
3442 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3443 {
3444 VEC_safe_push (static_tracepoint_marker_p,
3445 markers, marker);
3446 marker = NULL;
3447 }
3448 else
3449 {
3450 release_static_tracepoint_marker (marker);
3451 memset (marker, 0, sizeof (*marker));
3452 }
3453 }
3454 while (*p++ == ','); /* comma-separated list */
3455 /* Ask for another packet of static tracepoint definition. */
3456 putpkt ("qTsSTM");
3457 getpkt (&rs->buf, &rs->buf_size, 0);
3458 p = rs->buf;
3459 }
3460
3461 do_cleanups (old_chain);
3462 return markers;
3463}
3464
3465\f
10760264
JB
3466/* Implement the to_get_ada_task_ptid function for the remote targets. */
3467
3468static ptid_t
1e6b91a4 3469remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3470{
ba348170 3471 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3472}
3473\f
3474
24b06219 3475/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3476
3477static void
fba45db2 3478extended_remote_restart (void)
c906108c 3479{
d01949b6 3480 struct remote_state *rs = get_remote_state ();
c906108c
SS
3481
3482 /* Send the restart command; for reasons I don't understand the
3483 remote side really expects a number after the "R". */
ea9c271d 3484 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3485 putpkt (rs->buf);
c906108c 3486
ad9a8f3f 3487 remote_fileio_reset ();
c906108c
SS
3488}
3489\f
3490/* Clean up connection to a remote debugger. */
3491
c906108c 3492static void
de90e03d 3493remote_close (struct target_ops *self)
c906108c 3494{
5d93a237
TT
3495 struct remote_state *rs = get_remote_state ();
3496
3497 if (rs->remote_desc == NULL)
d3fd5342
PA
3498 return; /* already closed */
3499
048094ac 3500 /* Make sure we leave stdin registered in the event loop. */
e3594fd1 3501 remote_terminal_ours (self);
ce5ce7ed 3502
5d93a237
TT
3503 serial_close (rs->remote_desc);
3504 rs->remote_desc = NULL;
ce5ce7ed
PA
3505
3506 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3507 of all the inferiors and their threads we were controlling.
3508 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3509 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3510 inferior_ptid = null_ptid;
f67fd822 3511 discard_all_inferiors ();
ce5ce7ed 3512
f48ff2a7
YQ
3513 /* We are closing the remote target, so we should discard
3514 everything of this target. */
bcc75809 3515 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3516
3517 if (remote_async_inferior_event_token)
3518 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3519
5965e028 3520 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3521
3522 trace_reset_local_state ();
c906108c
SS
3523}
3524
23860348 3525/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3526
3527static void
fba45db2 3528get_offsets (void)
c906108c 3529{
d01949b6 3530 struct remote_state *rs = get_remote_state ();
2e9f7625 3531 char *buf;
085dd6e6 3532 char *ptr;
31d99776
DJ
3533 int lose, num_segments = 0, do_sections, do_segments;
3534 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3535 struct section_offsets *offs;
31d99776
DJ
3536 struct symfile_segment_data *data;
3537
3538 if (symfile_objfile == NULL)
3539 return;
c906108c
SS
3540
3541 putpkt ("qOffsets");
6d820c5c 3542 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3543 buf = rs->buf;
c906108c
SS
3544
3545 if (buf[0] == '\000')
3546 return; /* Return silently. Stub doesn't support
23860348 3547 this command. */
c906108c
SS
3548 if (buf[0] == 'E')
3549 {
8a3fe4f8 3550 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3551 return;
3552 }
3553
3554 /* Pick up each field in turn. This used to be done with scanf, but
3555 scanf will make trouble if CORE_ADDR size doesn't match
3556 conversion directives correctly. The following code will work
3557 with any size of CORE_ADDR. */
3558 text_addr = data_addr = bss_addr = 0;
3559 ptr = buf;
3560 lose = 0;
3561
61012eef 3562 if (startswith (ptr, "Text="))
c906108c
SS
3563 {
3564 ptr += 5;
3565 /* Don't use strtol, could lose on big values. */
3566 while (*ptr && *ptr != ';')
3567 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3568
61012eef 3569 if (startswith (ptr, ";Data="))
31d99776
DJ
3570 {
3571 ptr += 6;
3572 while (*ptr && *ptr != ';')
3573 data_addr = (data_addr << 4) + fromhex (*ptr++);
3574 }
3575 else
3576 lose = 1;
3577
61012eef 3578 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3579 {
3580 ptr += 5;
3581 while (*ptr && *ptr != ';')
3582 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3583
31d99776
DJ
3584 if (bss_addr != data_addr)
3585 warning (_("Target reported unsupported offsets: %s"), buf);
3586 }
3587 else
3588 lose = 1;
3589 }
61012eef 3590 else if (startswith (ptr, "TextSeg="))
c906108c 3591 {
31d99776
DJ
3592 ptr += 8;
3593 /* Don't use strtol, could lose on big values. */
c906108c 3594 while (*ptr && *ptr != ';')
31d99776
DJ
3595 text_addr = (text_addr << 4) + fromhex (*ptr++);
3596 num_segments = 1;
3597
61012eef 3598 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3599 {
3600 ptr += 9;
3601 while (*ptr && *ptr != ';')
3602 data_addr = (data_addr << 4) + fromhex (*ptr++);
3603 num_segments++;
3604 }
c906108c
SS
3605 }
3606 else
3607 lose = 1;
3608
3609 if (lose)
8a3fe4f8 3610 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3611 else if (*ptr != '\0')
3612 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3613
802188a7 3614 offs = ((struct section_offsets *)
a39a16c4 3615 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3616 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3617 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3618
31d99776
DJ
3619 data = get_symfile_segment_data (symfile_objfile->obfd);
3620 do_segments = (data != NULL);
3621 do_sections = num_segments == 0;
c906108c 3622
28c32713 3623 if (num_segments > 0)
31d99776 3624 {
31d99776
DJ
3625 segments[0] = text_addr;
3626 segments[1] = data_addr;
3627 }
28c32713
JB
3628 /* If we have two segments, we can still try to relocate everything
3629 by assuming that the .text and .data offsets apply to the whole
3630 text and data segments. Convert the offsets given in the packet
3631 to base addresses for symfile_map_offsets_to_segments. */
3632 else if (data && data->num_segments == 2)
3633 {
3634 segments[0] = data->segment_bases[0] + text_addr;
3635 segments[1] = data->segment_bases[1] + data_addr;
3636 num_segments = 2;
3637 }
8d385431
DJ
3638 /* If the object file has only one segment, assume that it is text
3639 rather than data; main programs with no writable data are rare,
3640 but programs with no code are useless. Of course the code might
3641 have ended up in the data segment... to detect that we would need
3642 the permissions here. */
3643 else if (data && data->num_segments == 1)
3644 {
3645 segments[0] = data->segment_bases[0] + text_addr;
3646 num_segments = 1;
3647 }
28c32713
JB
3648 /* There's no way to relocate by segment. */
3649 else
3650 do_segments = 0;
31d99776
DJ
3651
3652 if (do_segments)
3653 {
3654 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3655 offs, num_segments, segments);
3656
3657 if (ret == 0 && !do_sections)
3e43a32a
MS
3658 error (_("Can not handle qOffsets TextSeg "
3659 "response with this symbol file"));
31d99776
DJ
3660
3661 if (ret > 0)
3662 do_sections = 0;
3663 }
c906108c 3664
9ef895d6
DJ
3665 if (data)
3666 free_symfile_segment_data (data);
31d99776
DJ
3667
3668 if (do_sections)
3669 {
3670 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3671
3e43a32a
MS
3672 /* This is a temporary kludge to force data and bss to use the
3673 same offsets because that's what nlmconv does now. The real
3674 solution requires changes to the stub and remote.c that I
3675 don't have time to do right now. */
31d99776
DJ
3676
3677 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3678 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3679 }
c906108c
SS
3680
3681 objfile_relocate (symfile_objfile, offs);
3682}
3683
9a7071a8
JB
3684/* Send interrupt_sequence to remote target. */
3685static void
eeae04df 3686send_interrupt_sequence (void)
9a7071a8 3687{
5d93a237
TT
3688 struct remote_state *rs = get_remote_state ();
3689
9a7071a8 3690 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3691 remote_serial_write ("\x03", 1);
9a7071a8 3692 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3693 serial_send_break (rs->remote_desc);
9a7071a8
JB
3694 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3695 {
5d93a237 3696 serial_send_break (rs->remote_desc);
c33e31fd 3697 remote_serial_write ("g", 1);
9a7071a8
JB
3698 }
3699 else
3700 internal_error (__FILE__, __LINE__,
3701 _("Invalid value for interrupt_sequence_mode: %s."),
3702 interrupt_sequence_mode);
3703}
3704
3405876a
PA
3705
3706/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3707 and extract the PTID. Returns NULL_PTID if not found. */
3708
3709static ptid_t
3710stop_reply_extract_thread (char *stop_reply)
3711{
3712 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3713 {
3714 char *p;
3715
3716 /* Txx r:val ; r:val (...) */
3717 p = &stop_reply[3];
3718
3719 /* Look for "register" named "thread". */
3720 while (*p != '\0')
3721 {
3722 char *p1;
3723
3724 p1 = strchr (p, ':');
3725 if (p1 == NULL)
3726 return null_ptid;
3727
3728 if (strncmp (p, "thread", p1 - p) == 0)
3729 return read_ptid (++p1, &p);
3730
3731 p1 = strchr (p, ';');
3732 if (p1 == NULL)
3733 return null_ptid;
3734 p1++;
3735
3736 p = p1;
3737 }
3738 }
3739
3740 return null_ptid;
3741}
3742
b7ea362b
PA
3743/* Determine the remote side's current thread. If we have a stop
3744 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3745 "thread" register we can extract the current thread from. If not,
3746 ask the remote which is the current thread with qC. The former
3747 method avoids a roundtrip. */
3748
3749static ptid_t
3750get_current_thread (char *wait_status)
3751{
6a49a997 3752 ptid_t ptid = null_ptid;
b7ea362b
PA
3753
3754 /* Note we don't use remote_parse_stop_reply as that makes use of
3755 the target architecture, which we haven't yet fully determined at
3756 this point. */
3757 if (wait_status != NULL)
3758 ptid = stop_reply_extract_thread (wait_status);
3759 if (ptid_equal (ptid, null_ptid))
3760 ptid = remote_current_thread (inferior_ptid);
3761
3762 return ptid;
3763}
3764
49c62f2e
PA
3765/* Query the remote target for which is the current thread/process,
3766 add it to our tables, and update INFERIOR_PTID. The caller is
3767 responsible for setting the state such that the remote end is ready
3405876a
PA
3768 to return the current thread.
3769
3770 This function is called after handling the '?' or 'vRun' packets,
3771 whose response is a stop reply from which we can also try
3772 extracting the thread. If the target doesn't support the explicit
3773 qC query, we infer the current thread from that stop reply, passed
3774 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3775
3776static void
3405876a 3777add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3778{
3779 struct remote_state *rs = get_remote_state ();
3780 int fake_pid_p = 0;
6a49a997 3781 ptid_t ptid;
49c62f2e
PA
3782
3783 inferior_ptid = null_ptid;
3784
b7ea362b
PA
3785 /* Now, if we have thread information, update inferior_ptid. */
3786 ptid = get_current_thread (wait_status);
3405876a 3787
49c62f2e
PA
3788 if (!ptid_equal (ptid, null_ptid))
3789 {
3790 if (!remote_multi_process_p (rs))
3791 fake_pid_p = 1;
3792
3793 inferior_ptid = ptid;
3794 }
3795 else
3796 {
3797 /* Without this, some commands which require an active target
3798 (such as kill) won't work. This variable serves (at least)
3799 double duty as both the pid of the target process (if it has
3800 such), and as a flag indicating that a target is active. */
3801 inferior_ptid = magic_null_ptid;
3802 fake_pid_p = 1;
3803 }
3804
1b6e6f5c 3805 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3806
3807 /* Add the main thread. */
3808 add_thread_silent (inferior_ptid);
3809}
3810
6efcd9a8
PA
3811/* Print info about a thread that was found already stopped on
3812 connection. */
3813
3814static void
3815print_one_stopped_thread (struct thread_info *thread)
3816{
3817 struct target_waitstatus *ws = &thread->suspend.waitstatus;
3818
3819 switch_to_thread (thread->ptid);
3820 stop_pc = get_frame_pc (get_current_frame ());
3821 set_current_sal_from_frame (get_current_frame ());
3822
3823 thread->suspend.waitstatus_pending_p = 0;
3824
3825 if (ws->kind == TARGET_WAITKIND_STOPPED)
3826 {
3827 enum gdb_signal sig = ws->value.sig;
3828
3829 if (signal_print_state (sig))
3830 observer_notify_signal_received (sig);
3831 }
3832 observer_notify_normal_stop (NULL, 1);
3833}
3834
221e1a37
PA
3835/* Process all initial stop replies the remote side sent in response
3836 to the ? packet. These indicate threads that were already stopped
3837 on initial connection. We mark these threads as stopped and print
3838 their current frame before giving the user the prompt. */
3839
3840static void
6efcd9a8 3841process_initial_stop_replies (int from_tty)
221e1a37
PA
3842{
3843 int pending_stop_replies = stop_reply_queue_length ();
6efcd9a8
PA
3844 struct inferior *inf;
3845 struct thread_info *thread;
3846 struct thread_info *selected = NULL;
3847 struct thread_info *lowest_stopped = NULL;
3848 struct thread_info *first = NULL;
221e1a37
PA
3849
3850 /* Consume the initial pending events. */
3851 while (pending_stop_replies-- > 0)
3852 {
3853 ptid_t waiton_ptid = minus_one_ptid;
3854 ptid_t event_ptid;
3855 struct target_waitstatus ws;
3856 int ignore_event = 0;
6efcd9a8 3857 struct thread_info *thread;
221e1a37
PA
3858
3859 memset (&ws, 0, sizeof (ws));
3860 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3861 if (remote_debug)
3862 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3863
3864 switch (ws.kind)
3865 {
3866 case TARGET_WAITKIND_IGNORE:
3867 case TARGET_WAITKIND_NO_RESUMED:
3868 case TARGET_WAITKIND_SIGNALLED:
3869 case TARGET_WAITKIND_EXITED:
3870 /* We shouldn't see these, but if we do, just ignore. */
3871 if (remote_debug)
3872 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3873 ignore_event = 1;
3874 break;
3875
3876 case TARGET_WAITKIND_EXECD:
3877 xfree (ws.value.execd_pathname);
3878 break;
3879 default:
3880 break;
3881 }
3882
3883 if (ignore_event)
3884 continue;
3885
6efcd9a8 3886 thread = find_thread_ptid (event_ptid);
221e1a37
PA
3887
3888 if (ws.kind == TARGET_WAITKIND_STOPPED)
3889 {
3890 enum gdb_signal sig = ws.value.sig;
3891
3892 /* Stubs traditionally report SIGTRAP as initial signal,
3893 instead of signal 0. Suppress it. */
3894 if (sig == GDB_SIGNAL_TRAP)
3895 sig = GDB_SIGNAL_0;
6efcd9a8
PA
3896 thread->suspend.stop_signal = sig;
3897 ws.value.sig = sig;
3898 }
221e1a37 3899
6efcd9a8
PA
3900 thread->suspend.waitstatus = ws;
3901
3902 if (ws.kind != TARGET_WAITKIND_STOPPED
3903 || ws.value.sig != GDB_SIGNAL_0)
3904 thread->suspend.waitstatus_pending_p = 1;
3905
3906 set_executing (event_ptid, 0);
3907 set_running (event_ptid, 0);
3908 }
3909
3910 /* "Notice" the new inferiors before anything related to
3911 registers/memory. */
3912 ALL_INFERIORS (inf)
3913 {
3914 if (inf->pid == 0)
3915 continue;
3916
3917 inf->needs_setup = 1;
3918
3919 if (non_stop)
3920 {
3921 thread = any_live_thread_of_process (inf->pid);
3922 notice_new_inferior (thread->ptid,
3923 thread->state == THREAD_RUNNING,
3924 from_tty);
3925 }
3926 }
3927
3928 /* If all-stop on top of non-stop, pause all threads. Note this
3929 records the threads' stop pc, so must be done after "noticing"
3930 the inferiors. */
3931 if (!non_stop)
3932 {
3933 stop_all_threads ();
3934
3935 /* If all threads of an inferior were already stopped, we
3936 haven't setup the inferior yet. */
3937 ALL_INFERIORS (inf)
3938 {
3939 if (inf->pid == 0)
3940 continue;
221e1a37 3941
6efcd9a8
PA
3942 if (inf->needs_setup)
3943 {
3944 thread = any_live_thread_of_process (inf->pid);
3945 switch_to_thread_no_regs (thread);
3946 setup_inferior (0);
3947 }
3948 }
221e1a37 3949 }
6efcd9a8
PA
3950
3951 /* Now go over all threads that are stopped, and print their current
3952 frame. If all-stop, then if there's a signalled thread, pick
3953 that as current. */
3954 ALL_NON_EXITED_THREADS (thread)
3955 {
6efcd9a8
PA
3956 if (first == NULL)
3957 first = thread;
3958
3959 if (!non_stop)
3960 set_running (thread->ptid, 0);
3961 else if (thread->state != THREAD_STOPPED)
3962 continue;
3963
6efcd9a8
PA
3964 if (selected == NULL
3965 && thread->suspend.waitstatus_pending_p)
3966 selected = thread;
3967
5d5658a1
PA
3968 if (lowest_stopped == NULL
3969 || thread->inf->num < lowest_stopped->inf->num
3970 || thread->per_inf_num < lowest_stopped->per_inf_num)
6efcd9a8
PA
3971 lowest_stopped = thread;
3972
3973 if (non_stop)
3974 print_one_stopped_thread (thread);
3975 }
3976
3977 /* In all-stop, we only print the status of one thread, and leave
3978 others with their status pending. */
3979 if (!non_stop)
3980 {
3981 thread = selected;
3982 if (thread == NULL)
3983 thread = lowest_stopped;
3984 if (thread == NULL)
3985 thread = first;
3986
3987 print_one_stopped_thread (thread);
3988 }
3989
3990 /* For "info program". */
3991 thread = inferior_thread ();
3992 if (thread->state == THREAD_STOPPED)
3993 set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
221e1a37
PA
3994}
3995
048094ac
PA
3996/* Start the remote connection and sync state. */
3997
9cbc821d 3998static void
04bd08de 3999remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 4000{
c8d104ad
PA
4001 struct remote_state *rs = get_remote_state ();
4002 struct packet_config *noack_config;
2d717e4f 4003 char *wait_status = NULL;
8621d6a9 4004
048094ac
PA
4005 /* Signal other parts that we're going through the initial setup,
4006 and so things may not be stable yet. E.g., we don't try to
4007 install tracepoints until we've relocated symbols. Also, a
4008 Ctrl-C before we're connected and synced up can't interrupt the
4009 target. Instead, it offers to drop the (potentially wedged)
4010 connection. */
4011 rs->starting_up = 1;
4012
522002f9 4013 QUIT;
c906108c 4014
9a7071a8
JB
4015 if (interrupt_on_connect)
4016 send_interrupt_sequence ();
4017
57e12211 4018 /* Ack any packet which the remote side has already sent. */
048094ac 4019 remote_serial_write ("+", 1);
1e51243a 4020
c8d104ad
PA
4021 /* The first packet we send to the target is the optional "supported
4022 packets" request. If the target can answer this, it will tell us
4023 which later probes to skip. */
4024 remote_query_supported ();
4025
d914c394 4026 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 4027 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 4028 remote_set_permissions (target);
d914c394 4029
c8d104ad
PA
4030 /* Next, we possibly activate noack mode.
4031
4032 If the QStartNoAckMode packet configuration is set to AUTO,
4033 enable noack mode if the stub reported a wish for it with
4034 qSupported.
4035
4036 If set to TRUE, then enable noack mode even if the stub didn't
4037 report it in qSupported. If the stub doesn't reply OK, the
4038 session ends with an error.
4039
4040 If FALSE, then don't activate noack mode, regardless of what the
4041 stub claimed should be the default with qSupported. */
4042
4043 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 4044 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
4045 {
4046 putpkt ("QStartNoAckMode");
4047 getpkt (&rs->buf, &rs->buf_size, 0);
4048 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4049 rs->noack_mode = 1;
4050 }
4051
04bd08de 4052 if (extended_p)
5fe04517
PA
4053 {
4054 /* Tell the remote that we are using the extended protocol. */
4055 putpkt ("!");
4056 getpkt (&rs->buf, &rs->buf_size, 0);
4057 }
4058
9b224c5e
PA
4059 /* Let the target know which signals it is allowed to pass down to
4060 the program. */
4061 update_signals_program_target ();
4062
d962ef82
DJ
4063 /* Next, if the target can specify a description, read it. We do
4064 this before anything involving memory or registers. */
4065 target_find_description ();
4066
6c95b8df
PA
4067 /* Next, now that we know something about the target, update the
4068 address spaces in the program spaces. */
4069 update_address_spaces ();
4070
50c71eaf
PA
4071 /* On OSs where the list of libraries is global to all
4072 processes, we fetch them early. */
f5656ead 4073 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 4074 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 4075
6efcd9a8 4076 if (target_is_non_stop_p ())
74531fed 4077 {
4082afcc 4078 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
4079 error (_("Non-stop mode requested, but remote "
4080 "does not support non-stop"));
74531fed
PA
4081
4082 putpkt ("QNonStop:1");
4083 getpkt (&rs->buf, &rs->buf_size, 0);
4084
4085 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4086 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
4087
4088 /* Find about threads and processes the stub is already
4089 controlling. We default to adding them in the running state.
4090 The '?' query below will then tell us about which threads are
4091 stopped. */
e8032dde 4092 remote_update_thread_list (target);
74531fed 4093 }
4082afcc 4094 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
4095 {
4096 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 4097 Request it explicitly. */
74531fed
PA
4098 putpkt ("QNonStop:0");
4099 getpkt (&rs->buf, &rs->buf_size, 0);
4100
4101 if (strcmp (rs->buf, "OK") != 0)
9b20d036 4102 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
4103 }
4104
a0743c90
YQ
4105 /* Upload TSVs regardless of whether the target is running or not. The
4106 remote stub, such as GDBserver, may have some predefined or builtin
4107 TSVs, even if the target is not running. */
8bd200f1 4108 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
4109 {
4110 struct uploaded_tsv *uploaded_tsvs = NULL;
4111
181e3713 4112 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
4113 merge_uploaded_trace_state_variables (&uploaded_tsvs);
4114 }
4115
2d717e4f
DJ
4116 /* Check whether the target is running now. */
4117 putpkt ("?");
4118 getpkt (&rs->buf, &rs->buf_size, 0);
4119
6efcd9a8 4120 if (!target_is_non_stop_p ())
2d717e4f 4121 {
74531fed 4122 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 4123 {
04bd08de 4124 if (!extended_p)
74531fed 4125 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
4126
4127 /* We're connected, but not running. Drop out before we
4128 call start_remote. */
e278ad5b 4129 rs->starting_up = 0;
c35b1492 4130 return;
2d717e4f
DJ
4131 }
4132 else
74531fed 4133 {
74531fed 4134 /* Save the reply for later. */
224c3ddb 4135 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
4136 strcpy (wait_status, rs->buf);
4137 }
4138
b7ea362b 4139 /* Fetch thread list. */
e8032dde 4140 target_update_thread_list ();
b7ea362b 4141
74531fed
PA
4142 /* Let the stub know that we want it to return the thread. */
4143 set_continue_thread (minus_one_ptid);
4144
b7ea362b
PA
4145 if (thread_count () == 0)
4146 {
4147 /* Target has no concept of threads at all. GDB treats
4148 non-threaded target as single-threaded; add a main
4149 thread. */
4150 add_current_inferior_and_thread (wait_status);
4151 }
4152 else
4153 {
4154 /* We have thread information; select the thread the target
4155 says should be current. If we're reconnecting to a
4156 multi-threaded program, this will ideally be the thread
4157 that last reported an event before GDB disconnected. */
4158 inferior_ptid = get_current_thread (wait_status);
4159 if (ptid_equal (inferior_ptid, null_ptid))
4160 {
4161 /* Odd... The target was able to list threads, but not
4162 tell us which thread was current (no "thread"
4163 register in T stop reply?). Just pick the first
4164 thread in the thread list then. */
c9f35b34
KB
4165
4166 if (remote_debug)
4167 fprintf_unfiltered (gdb_stdlog,
4168 "warning: couldn't determine remote "
4169 "current thread; picking first in list.\n");
4170
b7ea362b
PA
4171 inferior_ptid = thread_list->ptid;
4172 }
4173 }
74531fed 4174
6e586cc5
YQ
4175 /* init_wait_for_inferior should be called before get_offsets in order
4176 to manage `inserted' flag in bp loc in a correct state.
4177 breakpoint_init_inferior, called from init_wait_for_inferior, set
4178 `inserted' flag to 0, while before breakpoint_re_set, called from
4179 start_remote, set `inserted' flag to 1. In the initialization of
4180 inferior, breakpoint_init_inferior should be called first, and then
4181 breakpoint_re_set can be called. If this order is broken, state of
4182 `inserted' flag is wrong, and cause some problems on breakpoint
4183 manipulation. */
4184 init_wait_for_inferior ();
4185
74531fed
PA
4186 get_offsets (); /* Get text, data & bss offsets. */
4187
d962ef82
DJ
4188 /* If we could not find a description using qXfer, and we know
4189 how to do it some other way, try again. This is not
4190 supported for non-stop; it could be, but it is tricky if
4191 there are no stopped threads when we connect. */
04bd08de 4192 if (remote_read_description_p (target)
f5656ead 4193 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
4194 {
4195 target_clear_description ();
4196 target_find_description ();
4197 }
4198
74531fed
PA
4199 /* Use the previously fetched status. */
4200 gdb_assert (wait_status != NULL);
4201 strcpy (rs->buf, wait_status);
4202 rs->cached_wait_status = 1;
4203
04bd08de 4204 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
4205 }
4206 else
4207 {
68c97600
PA
4208 /* Clear WFI global state. Do this before finding about new
4209 threads and inferiors, and setting the current inferior.
4210 Otherwise we would clear the proceed status of the current
4211 inferior when we want its stop_soon state to be preserved
4212 (see notice_new_inferior). */
4213 init_wait_for_inferior ();
4214
74531fed
PA
4215 /* In non-stop, we will either get an "OK", meaning that there
4216 are no stopped threads at this time; or, a regular stop
4217 reply. In the latter case, there may be more than one thread
4218 stopped --- we pull them all out using the vStopped
4219 mechanism. */
4220 if (strcmp (rs->buf, "OK") != 0)
4221 {
722247f1 4222 struct notif_client *notif = &notif_client_stop;
2d717e4f 4223
722247f1
YQ
4224 /* remote_notif_get_pending_replies acks this one, and gets
4225 the rest out. */
f48ff2a7 4226 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
4227 = remote_notif_parse (notif, rs->buf);
4228 remote_notif_get_pending_events (notif);
74531fed 4229 }
2d717e4f 4230
74531fed
PA
4231 if (thread_count () == 0)
4232 {
04bd08de 4233 if (!extended_p)
74531fed 4234 error (_("The target is not running (try extended-remote?)"));
82f73884 4235
c35b1492
PA
4236 /* We're connected, but not running. Drop out before we
4237 call start_remote. */
e278ad5b 4238 rs->starting_up = 0;
c35b1492
PA
4239 return;
4240 }
74531fed 4241
74531fed
PA
4242 /* In non-stop mode, any cached wait status will be stored in
4243 the stop reply queue. */
4244 gdb_assert (wait_status == NULL);
f0223081 4245
2455069d 4246 /* Report all signals during attach/startup. */
94bedb42 4247 remote_pass_signals (target, 0, NULL);
221e1a37
PA
4248
4249 /* If there are already stopped threads, mark them stopped and
4250 report their stops before giving the prompt to the user. */
6efcd9a8 4251 process_initial_stop_replies (from_tty);
221e1a37
PA
4252
4253 if (target_can_async_p ())
4254 target_async (1);
74531fed 4255 }
c8d104ad 4256
c8d104ad
PA
4257 /* If we connected to a live target, do some additional setup. */
4258 if (target_has_execution)
4259 {
f4ccffad 4260 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 4261 remote_check_symbols ();
c8d104ad 4262 }
50c71eaf 4263
d5551862
SS
4264 /* Possibly the target has been engaged in a trace run started
4265 previously; find out where things are at. */
8bd200f1 4266 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 4267 {
00bf0b85 4268 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 4269
00bf0b85
SS
4270 if (current_trace_status ()->running)
4271 printf_filtered (_("Trace is already running on the target.\n"));
4272
ab6617cc 4273 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
4274
4275 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
4276 }
4277
1e51243a
PA
4278 /* The thread and inferior lists are now synchronized with the
4279 target, our symbols have been relocated, and we're merged the
4280 target's tracepoints with ours. We're done with basic start
4281 up. */
4282 rs->starting_up = 0;
4283
a25a5a45
PA
4284 /* Maybe breakpoints are global and need to be inserted now. */
4285 if (breakpoints_should_be_inserted_now ())
50c71eaf 4286 insert_breakpoints ();
c906108c
SS
4287}
4288
4289/* Open a connection to a remote debugger.
4290 NAME is the filename used for communication. */
4291
4292static void
014f9477 4293remote_open (const char *name, int from_tty)
c906108c 4294{
75c99385 4295 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
4296}
4297
c906108c
SS
4298/* Open a connection to a remote debugger using the extended
4299 remote gdb protocol. NAME is the filename used for communication. */
4300
4301static void
014f9477 4302extended_remote_open (const char *name, int from_tty)
c906108c 4303{
75c99385 4304 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
4305}
4306
ca4f7f8b
PA
4307/* Reset all packets back to "unknown support". Called when opening a
4308 new connection to a remote target. */
c906108c 4309
d471ea57 4310static void
ca4f7f8b 4311reset_all_packet_configs_support (void)
d471ea57
AC
4312{
4313 int i;
a744cf53 4314
444abaca 4315 for (i = 0; i < PACKET_MAX; i++)
4082afcc 4316 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
4317}
4318
ca4f7f8b
PA
4319/* Initialize all packet configs. */
4320
4321static void
4322init_all_packet_configs (void)
4323{
4324 int i;
4325
4326 for (i = 0; i < PACKET_MAX; i++)
4327 {
4328 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4329 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4330 }
4331}
4332
23860348 4333/* Symbol look-up. */
dc8acb97
MS
4334
4335static void
36d25514 4336remote_check_symbols (void)
dc8acb97 4337{
d01949b6 4338 struct remote_state *rs = get_remote_state ();
dc8acb97 4339 char *msg, *reply, *tmp;
dc8acb97 4340 int end;
28170b88 4341 long reply_size;
a5c0808e 4342 struct cleanup *old_chain;
dc8acb97 4343
63154eca
PA
4344 /* The remote side has no concept of inferiors that aren't running
4345 yet, it only knows about running processes. If we're connected
4346 but our current inferior is not running, we should not invite the
4347 remote target to request symbol lookups related to its
4348 (unrelated) current process. */
4349 if (!target_has_execution)
4350 return;
4351
4082afcc 4352 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4353 return;
4354
63154eca
PA
4355 /* Make sure the remote is pointing at the right process. Note
4356 there's no way to select "no process". */
3c9c4b83
PA
4357 set_general_process ();
4358
6d820c5c
DJ
4359 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4360 because we need both at the same time. */
224c3ddb 4361 msg = (char *) xmalloc (get_remote_packet_size ());
a5c0808e 4362 old_chain = make_cleanup (xfree, msg);
28170b88
MK
4363 reply = (char *) xmalloc (get_remote_packet_size ());
4364 make_cleanup (free_current_contents, &reply);
4365 reply_size = get_remote_packet_size ();
6d820c5c 4366
23860348 4367 /* Invite target to request symbol lookups. */
dc8acb97
MS
4368
4369 putpkt ("qSymbol::");
28170b88
MK
4370 getpkt (&reply, &reply_size, 0);
4371 packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
dc8acb97 4372
61012eef 4373 while (startswith (reply, "qSymbol:"))
dc8acb97 4374 {
77e371c0
TT
4375 struct bound_minimal_symbol sym;
4376
dc8acb97 4377 tmp = &reply[8];
cfd77fa1 4378 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4379 msg[end] = '\0';
4380 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4381 if (sym.minsym == NULL)
ea9c271d 4382 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4383 else
2bbe3cc1 4384 {
f5656ead 4385 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4386 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4387
4388 /* If this is a function address, return the start of code
4389 instead of any data function descriptor. */
f5656ead 4390 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4391 sym_addr,
4392 &current_target);
4393
4394 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4395 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4396 }
4397
dc8acb97 4398 putpkt (msg);
28170b88 4399 getpkt (&reply, &reply_size, 0);
dc8acb97 4400 }
a5c0808e
PA
4401
4402 do_cleanups (old_chain);
dc8acb97
MS
4403}
4404
9db8d71f 4405static struct serial *
baa336ce 4406remote_serial_open (const char *name)
9db8d71f
DJ
4407{
4408 static int udp_warning = 0;
4409
4410 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4411 of in ser-tcp.c, because it is the remote protocol assuming that the
4412 serial connection is reliable and not the serial connection promising
4413 to be. */
61012eef 4414 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4415 {
3e43a32a
MS
4416 warning (_("The remote protocol may be unreliable over UDP.\n"
4417 "Some events may be lost, rendering further debugging "
4418 "impossible."));
9db8d71f
DJ
4419 udp_warning = 1;
4420 }
4421
4422 return serial_open (name);
4423}
4424
d914c394
SS
4425/* Inform the target of our permission settings. The permission flags
4426 work without this, but if the target knows the settings, it can do
4427 a couple things. First, it can add its own check, to catch cases
4428 that somehow manage to get by the permissions checks in target
4429 methods. Second, if the target is wired to disallow particular
4430 settings (for instance, a system in the field that is not set up to
4431 be able to stop at a breakpoint), it can object to any unavailable
4432 permissions. */
4433
4434void
c378d69d 4435remote_set_permissions (struct target_ops *self)
d914c394
SS
4436{
4437 struct remote_state *rs = get_remote_state ();
4438
bba74b36
YQ
4439 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4440 "WriteReg:%x;WriteMem:%x;"
4441 "InsertBreak:%x;InsertTrace:%x;"
4442 "InsertFastTrace:%x;Stop:%x",
4443 may_write_registers, may_write_memory,
4444 may_insert_breakpoints, may_insert_tracepoints,
4445 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4446 putpkt (rs->buf);
4447 getpkt (&rs->buf, &rs->buf_size, 0);
4448
4449 /* If the target didn't like the packet, warn the user. Do not try
4450 to undo the user's settings, that would just be maddening. */
4451 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4452 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4453}
4454
be2a5f71
DJ
4455/* This type describes each known response to the qSupported
4456 packet. */
4457struct protocol_feature
4458{
4459 /* The name of this protocol feature. */
4460 const char *name;
4461
4462 /* The default for this protocol feature. */
4463 enum packet_support default_support;
4464
4465 /* The function to call when this feature is reported, or after
4466 qSupported processing if the feature is not supported.
4467 The first argument points to this structure. The second
4468 argument indicates whether the packet requested support be
4469 enabled, disabled, or probed (or the default, if this function
4470 is being called at the end of processing and this feature was
4471 not reported). The third argument may be NULL; if not NULL, it
4472 is a NUL-terminated string taken from the packet following
4473 this feature's name and an equals sign. */
4474 void (*func) (const struct protocol_feature *, enum packet_support,
4475 const char *);
4476
4477 /* The corresponding packet for this feature. Only used if
4478 FUNC is remote_supported_packet. */
4479 int packet;
4480};
4481
be2a5f71
DJ
4482static void
4483remote_supported_packet (const struct protocol_feature *feature,
4484 enum packet_support support,
4485 const char *argument)
4486{
4487 if (argument)
4488 {
4489 warning (_("Remote qSupported response supplied an unexpected value for"
4490 " \"%s\"."), feature->name);
4491 return;
4492 }
4493
4082afcc 4494 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4495}
be2a5f71
DJ
4496
4497static void
4498remote_packet_size (const struct protocol_feature *feature,
4499 enum packet_support support, const char *value)
4500{
4501 struct remote_state *rs = get_remote_state ();
4502
4503 int packet_size;
4504 char *value_end;
4505
4506 if (support != PACKET_ENABLE)
4507 return;
4508
4509 if (value == NULL || *value == '\0')
4510 {
4511 warning (_("Remote target reported \"%s\" without a size."),
4512 feature->name);
4513 return;
4514 }
4515
4516 errno = 0;
4517 packet_size = strtol (value, &value_end, 16);
4518 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4519 {
4520 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4521 feature->name, value);
4522 return;
4523 }
4524
be2a5f71
DJ
4525 /* Record the new maximum packet size. */
4526 rs->explicit_packet_size = packet_size;
4527}
4528
dc473cfb 4529static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4530 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4531 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4532 PACKET_qXfer_auxv },
c78fa86a
GB
4533 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4534 PACKET_qXfer_exec_file },
23181151
DJ
4535 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4536 PACKET_qXfer_features },
cfa9d6d9
DJ
4537 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4538 PACKET_qXfer_libraries },
2268b414
JK
4539 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4540 PACKET_qXfer_libraries_svr4 },
ced63ec0 4541 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4542 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4543 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4544 PACKET_qXfer_memory_map },
4de6483e
UW
4545 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4546 PACKET_qXfer_spu_read },
4547 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4548 PACKET_qXfer_spu_write },
07e059b5
VP
4549 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4550 PACKET_qXfer_osdata },
dc146f7c
VP
4551 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4552 PACKET_qXfer_threads },
b3b9301e
PA
4553 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4554 PACKET_qXfer_traceframe_info },
89be2091
DJ
4555 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4556 PACKET_QPassSignals },
82075af2
JS
4557 { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4558 PACKET_QCatchSyscalls },
9b224c5e
PA
4559 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4560 PACKET_QProgramSignals },
a6f3e723
SL
4561 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4562 PACKET_QStartNoAckMode },
4082afcc
PA
4563 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4564 PACKET_multiprocess_feature },
4565 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4566 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4567 PACKET_qXfer_siginfo_read },
4568 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4569 PACKET_qXfer_siginfo_write },
4082afcc 4570 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4571 PACKET_ConditionalTracepoints },
4082afcc 4572 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4573 PACKET_ConditionalBreakpoints },
4082afcc 4574 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4575 PACKET_BreakpointCommands },
4082afcc 4576 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4577 PACKET_FastTracepoints },
4082afcc 4578 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4579 PACKET_StaticTracepoints },
4082afcc 4580 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4581 PACKET_InstallInTrace},
4082afcc
PA
4582 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4583 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4584 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4585 PACKET_bc },
4586 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4587 PACKET_bs },
409873ef
SS
4588 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4589 PACKET_TracepointSource },
d914c394
SS
4590 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4591 PACKET_QAllow },
4082afcc
PA
4592 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4593 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4594 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4595 PACKET_qXfer_fdpic },
169081d0
TG
4596 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4597 PACKET_qXfer_uib },
03583c20
UW
4598 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4599 PACKET_QDisableRandomization },
d1feda86 4600 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4601 { "QTBuffer:size", PACKET_DISABLE,
4602 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4603 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4604 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4605 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4606 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4607 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4608 PACKET_qXfer_btrace },
4609 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4610 PACKET_qXfer_btrace_conf },
4611 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4612 PACKET_Qbtrace_conf_bts_size },
4613 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4614 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4615 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4616 PACKET_fork_event_feature },
4617 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4618 PACKET_vfork_event_feature },
94585166
DB
4619 { "exec-events", PACKET_DISABLE, remote_supported_packet,
4620 PACKET_exec_event_feature },
b20a6524 4621 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
750ce8d1 4622 PACKET_Qbtrace_conf_pt_size },
65706a29
PA
4623 { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4624 { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
f2faf941 4625 { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
be2a5f71
DJ
4626};
4627
c8d5aac9
L
4628static char *remote_support_xml;
4629
4630/* Register string appended to "xmlRegisters=" in qSupported query. */
4631
4632void
6e39997a 4633register_remote_support_xml (const char *xml)
c8d5aac9
L
4634{
4635#if defined(HAVE_LIBEXPAT)
4636 if (remote_support_xml == NULL)
c4f7c687 4637 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4638 else
4639 {
4640 char *copy = xstrdup (remote_support_xml + 13);
4641 char *p = strtok (copy, ",");
4642
4643 do
4644 {
4645 if (strcmp (p, xml) == 0)
4646 {
4647 /* already there */
4648 xfree (copy);
4649 return;
4650 }
4651 }
4652 while ((p = strtok (NULL, ",")) != NULL);
4653 xfree (copy);
4654
94b0dee1
PA
4655 remote_support_xml = reconcat (remote_support_xml,
4656 remote_support_xml, ",", xml,
4657 (char *) NULL);
c8d5aac9
L
4658 }
4659#endif
4660}
4661
4662static char *
4663remote_query_supported_append (char *msg, const char *append)
4664{
4665 if (msg)
94b0dee1 4666 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4667 else
4668 return xstrdup (append);
4669}
4670
be2a5f71
DJ
4671static void
4672remote_query_supported (void)
4673{
4674 struct remote_state *rs = get_remote_state ();
4675 char *next;
4676 int i;
4677 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4678
4679 /* The packet support flags are handled differently for this packet
4680 than for most others. We treat an error, a disabled packet, and
4681 an empty response identically: any features which must be reported
4682 to be used will be automatically disabled. An empty buffer
4683 accomplishes this, since that is also the representation for a list
4684 containing no features. */
4685
4686 rs->buf[0] = 0;
4082afcc 4687 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4688 {
c8d5aac9 4689 char *q = NULL;
94b0dee1 4690 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4691
73b8c1fd
PA
4692 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4693 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4694
f7e6eed5
PA
4695 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4696 q = remote_query_supported_append (q, "swbreak+");
4697 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4698 q = remote_query_supported_append (q, "hwbreak+");
4699
dde08ee1
PA
4700 q = remote_query_supported_append (q, "qRelocInsn+");
4701
8020350c
DB
4702 if (packet_set_cmd_state (PACKET_fork_event_feature)
4703 != AUTO_BOOLEAN_FALSE)
4704 q = remote_query_supported_append (q, "fork-events+");
4705 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4706 != AUTO_BOOLEAN_FALSE)
4707 q = remote_query_supported_append (q, "vfork-events+");
4708 if (packet_set_cmd_state (PACKET_exec_event_feature)
4709 != AUTO_BOOLEAN_FALSE)
4710 q = remote_query_supported_append (q, "exec-events+");
89245bc0 4711
750ce8d1
YQ
4712 if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4713 q = remote_query_supported_append (q, "vContSupported+");
4714
65706a29
PA
4715 if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4716 q = remote_query_supported_append (q, "QThreadEvents+");
4717
f2faf941
PA
4718 if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4719 q = remote_query_supported_append (q, "no-resumed+");
4720
b35d5edb
PA
4721 /* Keep this one last to work around a gdbserver <= 7.10 bug in
4722 the qSupported:xmlRegisters=i386 handling. */
4723 if (remote_support_xml != NULL)
4724 q = remote_query_supported_append (q, remote_support_xml);
4725
dde08ee1
PA
4726 q = reconcat (q, "qSupported:", q, (char *) NULL);
4727 putpkt (q);
82f73884 4728
94b0dee1
PA
4729 do_cleanups (old_chain);
4730
be2a5f71
DJ
4731 getpkt (&rs->buf, &rs->buf_size, 0);
4732
4733 /* If an error occured, warn, but do not return - just reset the
4734 buffer to empty and go on to disable features. */
4735 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4736 == PACKET_ERROR)
4737 {
4738 warning (_("Remote failure reply: %s"), rs->buf);
4739 rs->buf[0] = 0;
4740 }
4741 }
4742
4743 memset (seen, 0, sizeof (seen));
4744
4745 next = rs->buf;
4746 while (*next)
4747 {
4748 enum packet_support is_supported;
4749 char *p, *end, *name_end, *value;
4750
4751 /* First separate out this item from the rest of the packet. If
4752 there's another item after this, we overwrite the separator
4753 (terminated strings are much easier to work with). */
4754 p = next;
4755 end = strchr (p, ';');
4756 if (end == NULL)
4757 {
4758 end = p + strlen (p);
4759 next = end;
4760 }
4761 else
4762 {
89be2091
DJ
4763 *end = '\0';
4764 next = end + 1;
4765
be2a5f71
DJ
4766 if (end == p)
4767 {
4768 warning (_("empty item in \"qSupported\" response"));
4769 continue;
4770 }
be2a5f71
DJ
4771 }
4772
4773 name_end = strchr (p, '=');
4774 if (name_end)
4775 {
4776 /* This is a name=value entry. */
4777 is_supported = PACKET_ENABLE;
4778 value = name_end + 1;
4779 *name_end = '\0';
4780 }
4781 else
4782 {
4783 value = NULL;
4784 switch (end[-1])
4785 {
4786 case '+':
4787 is_supported = PACKET_ENABLE;
4788 break;
4789
4790 case '-':
4791 is_supported = PACKET_DISABLE;
4792 break;
4793
4794 case '?':
4795 is_supported = PACKET_SUPPORT_UNKNOWN;
4796 break;
4797
4798 default:
3e43a32a
MS
4799 warning (_("unrecognized item \"%s\" "
4800 "in \"qSupported\" response"), p);
be2a5f71
DJ
4801 continue;
4802 }
4803 end[-1] = '\0';
4804 }
4805
4806 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4807 if (strcmp (remote_protocol_features[i].name, p) == 0)
4808 {
4809 const struct protocol_feature *feature;
4810
4811 seen[i] = 1;
4812 feature = &remote_protocol_features[i];
4813 feature->func (feature, is_supported, value);
4814 break;
4815 }
4816 }
4817
4818 /* If we increased the packet size, make sure to increase the global
4819 buffer size also. We delay this until after parsing the entire
4820 qSupported packet, because this is the same buffer we were
4821 parsing. */
4822 if (rs->buf_size < rs->explicit_packet_size)
4823 {
4824 rs->buf_size = rs->explicit_packet_size;
224c3ddb 4825 rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
be2a5f71
DJ
4826 }
4827
4828 /* Handle the defaults for unmentioned features. */
4829 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4830 if (!seen[i])
4831 {
4832 const struct protocol_feature *feature;
4833
4834 feature = &remote_protocol_features[i];
4835 feature->func (feature, feature->default_support, NULL);
4836 }
4837}
4838
048094ac
PA
4839/* Serial QUIT handler for the remote serial descriptor.
4840
4841 Defers handling a Ctrl-C until we're done with the current
4842 command/response packet sequence, unless:
4843
4844 - We're setting up the connection. Don't send a remote interrupt
4845 request, as we're not fully synced yet. Quit immediately
4846 instead.
4847
4848 - The target has been resumed in the foreground
4849 (target_terminal_is_ours is false) with a synchronous resume
4850 packet, and we're blocked waiting for the stop reply, thus a
4851 Ctrl-C should be immediately sent to the target.
4852
4853 - We get a second Ctrl-C while still within the same serial read or
4854 write. In that case the serial is seemingly wedged --- offer to
4855 quit/disconnect.
4856
4857 - We see a second Ctrl-C without target response, after having
4858 previously interrupted the target. In that case the target/stub
4859 is probably wedged --- offer to quit/disconnect.
4860*/
4861
4862static void
4863remote_serial_quit_handler (void)
4864{
4865 struct remote_state *rs = get_remote_state ();
4866
4867 if (check_quit_flag ())
4868 {
4869 /* If we're starting up, we're not fully synced yet. Quit
4870 immediately. */
4871 if (rs->starting_up)
4872 quit ();
4873 else if (rs->got_ctrlc_during_io)
4874 {
4875 if (query (_("The target is not responding to GDB commands.\n"
4876 "Stop debugging it? ")))
4877 remote_unpush_and_throw ();
4878 }
4879 /* If ^C has already been sent once, offer to disconnect. */
4880 else if (!target_terminal_is_ours () && rs->ctrlc_pending_p)
4881 interrupt_query ();
4882 /* All-stop protocol, and blocked waiting for stop reply. Send
4883 an interrupt request. */
4884 else if (!target_terminal_is_ours () && rs->waiting_for_stop_reply)
4885 target_interrupt (inferior_ptid);
4886 else
4887 rs->got_ctrlc_during_io = 1;
4888 }
4889}
4890
78a095c3
JK
4891/* Remove any of the remote.c targets from target stack. Upper targets depend
4892 on it so remove them first. */
4893
4894static void
4895remote_unpush_target (void)
4896{
915ef8b1 4897 pop_all_targets_at_and_above (process_stratum);
78a095c3 4898}
be2a5f71 4899
048094ac
PA
4900static void
4901remote_unpush_and_throw (void)
4902{
4903 remote_unpush_target ();
4904 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
4905}
4906
c906108c 4907static void
014f9477 4908remote_open_1 (const char *name, int from_tty,
3e43a32a 4909 struct target_ops *target, int extended_p)
c906108c 4910{
d01949b6 4911 struct remote_state *rs = get_remote_state ();
a6f3e723 4912
c906108c 4913 if (name == 0)
8a3fe4f8 4914 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4915 "serial device is attached to the remote system\n"
8a3fe4f8 4916 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4917
23860348 4918 /* See FIXME above. */
c6ebd6cf 4919 if (!target_async_permitted)
92d1e331 4920 wait_forever_enabled_p = 1;
6426a772 4921
2d717e4f 4922 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4923 Ask this question first, before target_preopen has a chance to kill
4924 anything. */
5d93a237 4925 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4926 {
78a095c3
JK
4927 if (from_tty
4928 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4929 error (_("Still connected."));
4930 }
4931
78a095c3 4932 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4933 target_preopen (from_tty);
4934
89be2091 4935 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4936 xfree (rs->last_pass_packet);
4937 rs->last_pass_packet = NULL;
89be2091 4938
9b224c5e
PA
4939 /* Make sure we send the program signals list the next time we
4940 resume. */
5e4a05c4
TT
4941 xfree (rs->last_program_signals_packet);
4942 rs->last_program_signals_packet = NULL;
9b224c5e 4943
ad9a8f3f 4944 remote_fileio_reset ();
1dd41f16
NS
4945 reopen_exec_file ();
4946 reread_symbols ();
4947
5d93a237
TT
4948 rs->remote_desc = remote_serial_open (name);
4949 if (!rs->remote_desc)
c906108c
SS
4950 perror_with_name (name);
4951
4952 if (baud_rate != -1)
4953 {
5d93a237 4954 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4955 {
9b74d5d3
KB
4956 /* The requested speed could not be set. Error out to
4957 top level after closing remote_desc. Take care to
4958 set remote_desc to NULL to avoid closing remote_desc
4959 more than once. */
5d93a237
TT
4960 serial_close (rs->remote_desc);
4961 rs->remote_desc = NULL;
c906108c
SS
4962 perror_with_name (name);
4963 }
4964 }
4965
236af5e3 4966 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4967 serial_raw (rs->remote_desc);
c906108c
SS
4968
4969 /* If there is something sitting in the buffer we might take it as a
4970 response to a command, which would be bad. */
5d93a237 4971 serial_flush_input (rs->remote_desc);
c906108c
SS
4972
4973 if (from_tty)
4974 {
4975 puts_filtered ("Remote debugging using ");
4976 puts_filtered (name);
4977 puts_filtered ("\n");
4978 }
23860348 4979 push_target (target); /* Switch to using remote target now. */
c906108c 4980
74531fed
PA
4981 /* Register extra event sources in the event loop. */
4982 remote_async_inferior_event_token
4983 = create_async_event_handler (remote_async_inferior_event_handler,
4984 NULL);
5965e028 4985 rs->notif_state = remote_notif_state_allocate ();
74531fed 4986
be2a5f71
DJ
4987 /* Reset the target state; these things will be queried either by
4988 remote_query_supported or as they are needed. */
ca4f7f8b 4989 reset_all_packet_configs_support ();
74531fed 4990 rs->cached_wait_status = 0;
be2a5f71 4991 rs->explicit_packet_size = 0;
a6f3e723 4992 rs->noack_mode = 0;
82f73884 4993 rs->extended = extended_p;
e24a49d8 4994 rs->waiting_for_stop_reply = 0;
3a29589a 4995 rs->ctrlc_pending_p = 0;
048094ac 4996 rs->got_ctrlc_during_io = 0;
802188a7 4997
47f8a51d
TT
4998 rs->general_thread = not_sent_ptid;
4999 rs->continue_thread = not_sent_ptid;
262e1174 5000 rs->remote_traceframe_number = -1;
c906108c 5001
9d1f7ab2 5002 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
5003 rs->use_threadinfo_query = 1;
5004 rs->use_threadextra_query = 1;
9d1f7ab2 5005
80152258
PA
5006 readahead_cache_invalidate ();
5007
048094ac
PA
5008 /* Start out by owning the terminal. */
5009 remote_async_terminal_ours_p = 1;
5010
c6ebd6cf 5011 if (target_async_permitted)
92d1e331 5012 {
92d1e331
DJ
5013 /* FIXME: cagney/1999-09-23: During the initial connection it is
5014 assumed that the target is already ready and able to respond to
0df8b418 5015 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 5016 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 5017 around this. Eventually a mechanism that allows
92d1e331 5018 wait_for_inferior() to expect/get timeouts will be
23860348 5019 implemented. */
92d1e331
DJ
5020 wait_forever_enabled_p = 0;
5021 }
5022
23860348 5023 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 5024 no_shared_libraries (NULL, 0);
f78f6cf1 5025
74531fed
PA
5026 /* Start afresh. */
5027 init_thread_list ();
5028
36918e70 5029 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
5030 target (we'd otherwise be in an inconsistent state) and then
5031 propogate the error on up the exception chain. This ensures that
5032 the caller doesn't stumble along blindly assuming that the
5033 function succeeded. The CLI doesn't have this problem but other
5034 UI's, such as MI do.
36918e70
AC
5035
5036 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5037 this function should return an error indication letting the
ce2826aa 5038 caller restore the previous state. Unfortunately the command
36918e70
AC
5039 ``target remote'' is directly wired to this function making that
5040 impossible. On a positive note, the CLI side of this problem has
5041 been fixed - the function set_cmd_context() makes it possible for
5042 all the ``target ....'' commands to share a common callback
5043 function. See cli-dump.c. */
109c3e39 5044 {
2d717e4f 5045
492d29ea 5046 TRY
04bd08de
TT
5047 {
5048 remote_start_remote (from_tty, target, extended_p);
5049 }
492d29ea 5050 CATCH (ex, RETURN_MASK_ALL)
109c3e39 5051 {
c8d104ad
PA
5052 /* Pop the partially set up target - unless something else did
5053 already before throwing the exception. */
5d93a237 5054 if (rs->remote_desc != NULL)
78a095c3 5055 remote_unpush_target ();
c6ebd6cf 5056 if (target_async_permitted)
109c3e39
AC
5057 wait_forever_enabled_p = 1;
5058 throw_exception (ex);
5059 }
492d29ea 5060 END_CATCH
109c3e39 5061 }
c906108c 5062
f4abbc16
MM
5063 remote_btrace_reset ();
5064
c6ebd6cf 5065 if (target_async_permitted)
92d1e331 5066 wait_forever_enabled_p = 1;
43ff13b4
JM
5067}
5068
de0d863e
DB
5069/* Detach the specified process. */
5070
5071static void
5072remote_detach_pid (int pid)
5073{
5074 struct remote_state *rs = get_remote_state ();
5075
5076 if (remote_multi_process_p (rs))
5077 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5078 else
5079 strcpy (rs->buf, "D");
5080
5081 putpkt (rs->buf);
5082 getpkt (&rs->buf, &rs->buf_size, 0);
5083
5084 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5085 ;
5086 else if (rs->buf[0] == '\0')
5087 error (_("Remote doesn't know how to detach"));
5088 else
5089 error (_("Can't detach process."));
5090}
5091
5092/* This detaches a program to which we previously attached, using
5093 inferior_ptid to identify the process. After this is done, GDB
5094 can be used to debug some other program. We better not have left
5095 any breakpoints in the target program or it'll die when it hits
5096 one. */
c906108c
SS
5097
5098static void
de0d863e 5099remote_detach_1 (const char *args, int from_tty)
c906108c 5100{
82f73884 5101 int pid = ptid_get_pid (inferior_ptid);
d01949b6 5102 struct remote_state *rs = get_remote_state ();
de0d863e
DB
5103 struct thread_info *tp = find_thread_ptid (inferior_ptid);
5104 int is_fork_parent;
c906108c
SS
5105
5106 if (args)
8a3fe4f8 5107 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 5108
2d717e4f
DJ
5109 if (!target_has_execution)
5110 error (_("No process to detach from."));
5111
7cee1e54
PA
5112 if (from_tty)
5113 {
5114 char *exec_file = get_exec_file (0);
5115 if (exec_file == NULL)
5116 exec_file = "";
5117 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
5118 target_pid_to_str (pid_to_ptid (pid)));
5119 gdb_flush (gdb_stdout);
5120 }
5121
c906108c 5122 /* Tell the remote target to detach. */
de0d863e 5123 remote_detach_pid (pid);
82f73884 5124
8020350c
DB
5125 /* Exit only if this is the only active inferior. */
5126 if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
7cee1e54 5127 puts_filtered (_("Ending remote debugging.\n"));
82f73884 5128
de0d863e
DB
5129 /* Check to see if we are detaching a fork parent. Note that if we
5130 are detaching a fork child, tp == NULL. */
5131 is_fork_parent = (tp != NULL
5132 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5133
5134 /* If doing detach-on-fork, we don't mourn, because that will delete
5135 breakpoints that should be available for the followed inferior. */
5136 if (!is_fork_parent)
5137 target_mourn_inferior ();
5138 else
5139 {
5140 inferior_ptid = null_ptid;
5141 detach_inferior (pid);
5142 }
2d717e4f
DJ
5143}
5144
5145static void
52554a0e 5146remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5147{
de0d863e 5148 remote_detach_1 (args, from_tty);
2d717e4f
DJ
5149}
5150
5151static void
52554a0e 5152extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 5153{
de0d863e
DB
5154 remote_detach_1 (args, from_tty);
5155}
5156
5157/* Target follow-fork function for remote targets. On entry, and
5158 at return, the current inferior is the fork parent.
5159
5160 Note that although this is currently only used for extended-remote,
5161 it is named remote_follow_fork in anticipation of using it for the
5162 remote target as well. */
5163
5164static int
5165remote_follow_fork (struct target_ops *ops, int follow_child,
5166 int detach_fork)
5167{
5168 struct remote_state *rs = get_remote_state ();
c269dbdb 5169 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 5170
c269dbdb
DB
5171 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5172 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
5173 {
5174 /* When following the parent and detaching the child, we detach
5175 the child here. For the case of following the child and
5176 detaching the parent, the detach is done in the target-
5177 independent follow fork code in infrun.c. We can't use
5178 target_detach when detaching an unfollowed child because
5179 the client side doesn't know anything about the child. */
5180 if (detach_fork && !follow_child)
5181 {
5182 /* Detach the fork child. */
5183 ptid_t child_ptid;
5184 pid_t child_pid;
5185
5186 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5187 child_pid = ptid_get_pid (child_ptid);
5188
5189 remote_detach_pid (child_pid);
5190 detach_inferior (child_pid);
5191 }
5192 }
5193 return 0;
c906108c
SS
5194}
5195
94585166
DB
5196/* Target follow-exec function for remote targets. Save EXECD_PATHNAME
5197 in the program space of the new inferior. On entry and at return the
5198 current inferior is the exec'ing inferior. INF is the new exec'd
5199 inferior, which may be the same as the exec'ing inferior unless
5200 follow-exec-mode is "new". */
5201
5202static void
5203remote_follow_exec (struct target_ops *ops,
5204 struct inferior *inf, char *execd_pathname)
5205{
5206 /* We know that this is a target file name, so if it has the "target:"
5207 prefix we strip it off before saving it in the program space. */
5208 if (is_target_filename (execd_pathname))
5209 execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5210
5211 set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5212}
5213
6ad8ae5c
DJ
5214/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
5215
43ff13b4 5216static void
fee354ee 5217remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 5218{
43ff13b4 5219 if (args)
2d717e4f 5220 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 5221
8020350c
DB
5222 /* Make sure we unpush even the extended remote targets. Calling
5223 target_mourn_inferior won't unpush, and remote_mourn won't
5224 unpush if there is more than one inferior left. */
5225 unpush_target (target);
5226 generic_mourn_inferior ();
2d717e4f 5227
43ff13b4
JM
5228 if (from_tty)
5229 puts_filtered ("Ending remote debugging.\n");
5230}
5231
2d717e4f
DJ
5232/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
5233 be chatty about it. */
5234
5235static void
20f796c9
GB
5236extended_remote_attach (struct target_ops *target, const char *args,
5237 int from_tty)
2d717e4f
DJ
5238{
5239 struct remote_state *rs = get_remote_state ();
be86555c 5240 int pid;
96ef3384 5241 char *wait_status = NULL;
2d717e4f 5242
74164c56 5243 pid = parse_pid_to_attach (args);
2d717e4f 5244
74164c56
JK
5245 /* Remote PID can be freely equal to getpid, do not check it here the same
5246 way as in other targets. */
2d717e4f 5247
4082afcc 5248 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
5249 error (_("This target does not support attaching to a process"));
5250
7cee1e54
PA
5251 if (from_tty)
5252 {
5253 char *exec_file = get_exec_file (0);
5254
5255 if (exec_file)
5256 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5257 target_pid_to_str (pid_to_ptid (pid)));
5258 else
5259 printf_unfiltered (_("Attaching to %s\n"),
5260 target_pid_to_str (pid_to_ptid (pid)));
5261
5262 gdb_flush (gdb_stdout);
5263 }
5264
bba74b36 5265 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
5266 putpkt (rs->buf);
5267 getpkt (&rs->buf, &rs->buf_size, 0);
5268
4082afcc
PA
5269 switch (packet_ok (rs->buf,
5270 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 5271 {
4082afcc 5272 case PACKET_OK:
6efcd9a8 5273 if (!target_is_non_stop_p ())
74531fed
PA
5274 {
5275 /* Save the reply for later. */
224c3ddb 5276 wait_status = (char *) alloca (strlen (rs->buf) + 1);
74531fed
PA
5277 strcpy (wait_status, rs->buf);
5278 }
5279 else if (strcmp (rs->buf, "OK") != 0)
5280 error (_("Attaching to %s failed with: %s"),
5281 target_pid_to_str (pid_to_ptid (pid)),
5282 rs->buf);
4082afcc
PA
5283 break;
5284 case PACKET_UNKNOWN:
5285 error (_("This target does not support attaching to a process"));
5286 default:
5287 error (_("Attaching to %s failed"),
5288 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 5289 }
2d717e4f 5290
1b6e6f5c 5291 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 5292
2d717e4f 5293 inferior_ptid = pid_to_ptid (pid);
79d7f229 5294
6efcd9a8 5295 if (target_is_non_stop_p ())
bad34192
PA
5296 {
5297 struct thread_info *thread;
79d7f229 5298
bad34192 5299 /* Get list of threads. */
e8032dde 5300 remote_update_thread_list (target);
82f73884 5301
bad34192
PA
5302 thread = first_thread_of_process (pid);
5303 if (thread)
5304 inferior_ptid = thread->ptid;
5305 else
5306 inferior_ptid = pid_to_ptid (pid);
5307
5308 /* Invalidate our notion of the remote current thread. */
47f8a51d 5309 record_currthread (rs, minus_one_ptid);
bad34192 5310 }
74531fed 5311 else
bad34192
PA
5312 {
5313 /* Now, if we have thread information, update inferior_ptid. */
5314 inferior_ptid = remote_current_thread (inferior_ptid);
5315
5316 /* Add the main thread to the thread list. */
5317 add_thread_silent (inferior_ptid);
5318 }
c0a2216e 5319
96ef3384
UW
5320 /* Next, if the target can specify a description, read it. We do
5321 this before anything involving memory or registers. */
5322 target_find_description ();
5323
6efcd9a8 5324 if (!target_is_non_stop_p ())
74531fed
PA
5325 {
5326 /* Use the previously fetched status. */
5327 gdb_assert (wait_status != NULL);
5328
5329 if (target_can_async_p ())
5330 {
722247f1
YQ
5331 struct notif_event *reply
5332 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 5333
722247f1 5334 push_stop_reply ((struct stop_reply *) reply);
74531fed 5335
6a3753b3 5336 target_async (1);
74531fed
PA
5337 }
5338 else
5339 {
5340 gdb_assert (wait_status != NULL);
5341 strcpy (rs->buf, wait_status);
5342 rs->cached_wait_status = 1;
5343 }
5344 }
5345 else
5346 gdb_assert (wait_status == NULL);
2d717e4f
DJ
5347}
5348
b9c1d481
AS
5349/* Implementation of the to_post_attach method. */
5350
5351static void
5352extended_remote_post_attach (struct target_ops *ops, int pid)
5353{
6efcd9a8
PA
5354 /* Get text, data & bss offsets. */
5355 get_offsets ();
5356
b9c1d481
AS
5357 /* In certain cases GDB might not have had the chance to start
5358 symbol lookup up until now. This could happen if the debugged
5359 binary is not using shared libraries, the vsyscall page is not
5360 present (on Linux) and the binary itself hadn't changed since the
5361 debugging process was started. */
5362 if (symfile_objfile != NULL)
5363 remote_check_symbols();
5364}
5365
c906108c 5366\f
506fb367
DJ
5367/* Check for the availability of vCont. This function should also check
5368 the response. */
c906108c
SS
5369
5370static void
6d820c5c 5371remote_vcont_probe (struct remote_state *rs)
c906108c 5372{
2e9f7625 5373 char *buf;
6d820c5c 5374
2e9f7625
DJ
5375 strcpy (rs->buf, "vCont?");
5376 putpkt (rs->buf);
6d820c5c 5377 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 5378 buf = rs->buf;
c906108c 5379
506fb367 5380 /* Make sure that the features we assume are supported. */
61012eef 5381 if (startswith (buf, "vCont"))
506fb367
DJ
5382 {
5383 char *p = &buf[5];
750ce8d1 5384 int support_c, support_C;
506fb367 5385
750ce8d1
YQ
5386 rs->supports_vCont.s = 0;
5387 rs->supports_vCont.S = 0;
506fb367
DJ
5388 support_c = 0;
5389 support_C = 0;
d458bd84 5390 rs->supports_vCont.t = 0;
c1e36e3e 5391 rs->supports_vCont.r = 0;
506fb367
DJ
5392 while (p && *p == ';')
5393 {
5394 p++;
5395 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5396 rs->supports_vCont.s = 1;
506fb367 5397 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
750ce8d1 5398 rs->supports_vCont.S = 1;
506fb367
DJ
5399 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5400 support_c = 1;
5401 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5402 support_C = 1;
74531fed 5403 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 5404 rs->supports_vCont.t = 1;
c1e36e3e
PA
5405 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5406 rs->supports_vCont.r = 1;
506fb367
DJ
5407
5408 p = strchr (p, ';');
5409 }
c906108c 5410
750ce8d1
YQ
5411 /* If c, and C are not all supported, we can't use vCont. Clearing
5412 BUF will make packet_ok disable the packet. */
5413 if (!support_c || !support_C)
506fb367
DJ
5414 buf[0] = 0;
5415 }
c906108c 5416
444abaca 5417 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 5418}
c906108c 5419
0d8f58ca
PA
5420/* Helper function for building "vCont" resumptions. Write a
5421 resumption to P. ENDP points to one-passed-the-end of the buffer
5422 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
5423 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5424 resumed thread should be single-stepped and/or signalled. If PTID
5425 equals minus_one_ptid, then all threads are resumed; if PTID
5426 represents a process, then all threads of the process are resumed;
5427 the thread to be stepped and/or signalled is given in the global
5428 INFERIOR_PTID. */
5429
5430static char *
5431append_resumption (char *p, char *endp,
2ea28649 5432 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5433{
5434 struct remote_state *rs = get_remote_state ();
5435
a493e3e2 5436 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5437 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5438 else if (step
5439 /* GDB is willing to range step. */
5440 && use_range_stepping
5441 /* Target supports range stepping. */
5442 && rs->supports_vCont.r
5443 /* We don't currently support range stepping multiple
5444 threads with a wildcard (though the protocol allows it,
5445 so stubs shouldn't make an active effort to forbid
5446 it). */
5447 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5448 {
5449 struct thread_info *tp;
5450
5451 if (ptid_equal (ptid, minus_one_ptid))
5452 {
5453 /* If we don't know about the target thread's tid, then
5454 we're resuming magic_null_ptid (see caller). */
5455 tp = find_thread_ptid (magic_null_ptid);
5456 }
5457 else
5458 tp = find_thread_ptid (ptid);
5459 gdb_assert (tp != NULL);
5460
5461 if (tp->control.may_range_step)
5462 {
5463 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5464
5465 p += xsnprintf (p, endp - p, ";r%s,%s",
5466 phex_nz (tp->control.step_range_start,
5467 addr_size),
5468 phex_nz (tp->control.step_range_end,
5469 addr_size));
5470 }
5471 else
5472 p += xsnprintf (p, endp - p, ";s");
5473 }
0d8f58ca
PA
5474 else if (step)
5475 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5476 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5477 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5478 else
5479 p += xsnprintf (p, endp - p, ";c");
5480
5481 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5482 {
5483 ptid_t nptid;
5484
5485 /* All (-1) threads of process. */
ba348170 5486 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5487
5488 p += xsnprintf (p, endp - p, ":");
5489 p = write_ptid (p, endp, nptid);
5490 }
5491 else if (!ptid_equal (ptid, minus_one_ptid))
5492 {
5493 p += xsnprintf (p, endp - p, ":");
5494 p = write_ptid (p, endp, ptid);
5495 }
5496
5497 return p;
5498}
5499
799a2abe
PA
5500/* Clear the thread's private info on resume. */
5501
5502static void
5503resume_clear_thread_private_info (struct thread_info *thread)
5504{
5505 if (thread->priv != NULL)
5506 {
5507 thread->priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5508 thread->priv->watch_data_address = 0;
5509 }
5510}
5511
e5ef252a
PA
5512/* Append a vCont continue-with-signal action for threads that have a
5513 non-zero stop signal. */
5514
5515static char *
5516append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5517{
5518 struct thread_info *thread;
5519
034f788c 5520 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5521 if (ptid_match (thread->ptid, ptid)
5522 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5523 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5524 {
5525 p = append_resumption (p, endp, thread->ptid,
5526 0, thread->suspend.stop_signal);
5527 thread->suspend.stop_signal = GDB_SIGNAL_0;
799a2abe 5528 resume_clear_thread_private_info (thread);
e5ef252a
PA
5529 }
5530
5531 return p;
5532}
5533
506fb367
DJ
5534/* Resume the remote inferior by using a "vCont" packet. The thread
5535 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5536 resumed thread should be single-stepped and/or signalled. If PTID
5537 equals minus_one_ptid, then all threads are resumed; the thread to
5538 be stepped and/or signalled is given in the global INFERIOR_PTID.
5539 This function returns non-zero iff it resumes the inferior.
44eaed12 5540
506fb367
DJ
5541 This function issues a strict subset of all possible vCont commands at the
5542 moment. */
44eaed12 5543
506fb367 5544static int
2ea28649 5545remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5546{
5547 struct remote_state *rs = get_remote_state ();
82f73884
PA
5548 char *p;
5549 char *endp;
44eaed12 5550
4082afcc 5551 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5552 remote_vcont_probe (rs);
44eaed12 5553
4082afcc 5554 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5555 return 0;
44eaed12 5556
82f73884
PA
5557 p = rs->buf;
5558 endp = rs->buf + get_remote_packet_size ();
5559
506fb367
DJ
5560 /* If we could generate a wider range of packets, we'd have to worry
5561 about overflowing BUF. Should there be a generic
5562 "multi-part-packet" packet? */
5563
0d8f58ca
PA
5564 p += xsnprintf (p, endp - p, "vCont");
5565
79d7f229 5566 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5567 {
79d7f229
PA
5568 /* MAGIC_NULL_PTID means that we don't have any active threads,
5569 so we don't have any TID numbers the inferior will
5570 understand. Make sure to only send forms that do not specify
5571 a TID. */
a9cbf802 5572 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5573 }
0d8f58ca 5574 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5575 {
0d8f58ca
PA
5576 /* Resume all threads (of all processes, or of a single
5577 process), with preference for INFERIOR_PTID. This assumes
5578 inferior_ptid belongs to the set of all threads we are about
5579 to resume. */
a493e3e2 5580 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5581 {
0d8f58ca
PA
5582 /* Step inferior_ptid, with or without signal. */
5583 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5584 }
0d8f58ca 5585
e5ef252a
PA
5586 /* Also pass down any pending signaled resumption for other
5587 threads not the current. */
5588 p = append_pending_thread_resumptions (p, endp, ptid);
5589
0d8f58ca 5590 /* And continue others without a signal. */
a493e3e2 5591 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5592 }
5593 else
506fb367
DJ
5594 {
5595 /* Scheduler locking; resume only PTID. */
a9cbf802 5596 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5597 }
c906108c 5598
82f73884
PA
5599 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5600 putpkt (rs->buf);
506fb367 5601
6efcd9a8 5602 if (target_is_non_stop_p ())
74531fed
PA
5603 {
5604 /* In non-stop, the stub replies to vCont with "OK". The stop
5605 reply will be reported asynchronously by means of a `%Stop'
5606 notification. */
5607 getpkt (&rs->buf, &rs->buf_size, 0);
5608 if (strcmp (rs->buf, "OK") != 0)
5609 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5610 }
5611
506fb367 5612 return 1;
c906108c 5613}
43ff13b4 5614
506fb367
DJ
5615/* Tell the remote machine to resume. */
5616
43ff13b4 5617static void
28439f5e 5618remote_resume (struct target_ops *ops,
2ea28649 5619 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5620{
d01949b6 5621 struct remote_state *rs = get_remote_state ();
2e9f7625 5622 char *buf;
799a2abe 5623 struct thread_info *thread;
43ff13b4 5624
722247f1
YQ
5625 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5626 (explained in remote-notif.c:handle_notification) so
5627 remote_notif_process is not called. We need find a place where
5628 it is safe to start a 'vNotif' sequence. It is good to do it
5629 before resuming inferior, because inferior was stopped and no RSP
5630 traffic at that moment. */
6efcd9a8 5631 if (!target_is_non_stop_p ())
5965e028 5632 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5633
b73be471 5634 rs->last_sent_signal = siggnal;
280ceea3 5635 rs->last_sent_step = step;
43ff13b4 5636
506fb367 5637 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5638 /* No reverse support (yet) for vCont. */
5639 if (execution_direction != EXEC_REVERSE)
5640 if (remote_vcont_resume (ptid, step, siggnal))
5641 goto done;
506fb367 5642
79d7f229
PA
5643 /* All other supported resume packets do use Hc, so set the continue
5644 thread. */
5645 if (ptid_equal (ptid, minus_one_ptid))
5646 set_continue_thread (any_thread_ptid);
506fb367 5647 else
79d7f229 5648 set_continue_thread (ptid);
506fb367 5649
799a2abe
PA
5650 ALL_NON_EXITED_THREADS (thread)
5651 resume_clear_thread_private_info (thread);
5652
2e9f7625 5653 buf = rs->buf;
b2175913
MS
5654 if (execution_direction == EXEC_REVERSE)
5655 {
5656 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5657 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5658 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5659 siggnal);
40ab02ce 5660
4082afcc 5661 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5662 error (_("Remote reverse-step not supported."));
4082afcc 5663 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5664 error (_("Remote reverse-continue not supported."));
40ab02ce 5665
b2175913
MS
5666 strcpy (buf, step ? "bs" : "bc");
5667 }
a493e3e2 5668 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5669 {
5670 buf[0] = step ? 'S' : 'C';
c5aa993b 5671 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5672 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5673 buf[3] = '\0';
5674 }
5675 else
c5aa993b 5676 strcpy (buf, step ? "s" : "c");
506fb367 5677
44eaed12 5678 putpkt (buf);
43ff13b4 5679
75c99385 5680 done:
2acceee2 5681 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5682 with the event loop. NOTE: this is the one place where all the
5683 execution commands end up. We could alternatively do this in each
23860348 5684 of the execution commands in infcmd.c. */
2acceee2
JM
5685 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5686 into infcmd.c in order to allow inferior function calls to work
23860348 5687 NOT asynchronously. */
362646f5 5688 if (target_can_async_p ())
6a3753b3 5689 target_async (1);
e24a49d8
PA
5690
5691 /* We've just told the target to resume. The remote server will
5692 wait for the inferior to stop, and then send a stop reply. In
5693 the mean time, we can't start another command/query ourselves
74531fed
PA
5694 because the stub wouldn't be ready to process it. This applies
5695 only to the base all-stop protocol, however. In non-stop (which
5696 only supports vCont), the stub replies with an "OK", and is
5697 immediate able to process further serial input. */
6efcd9a8 5698 if (!target_is_non_stop_p ())
74531fed 5699 rs->waiting_for_stop_reply = 1;
43ff13b4 5700}
c906108c 5701\f
43ff13b4 5702
74531fed
PA
5703/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5704 thread, all threads of a remote process, or all threads of all
5705 processes. */
5706
5707static void
5708remote_stop_ns (ptid_t ptid)
5709{
5710 struct remote_state *rs = get_remote_state ();
5711 char *p = rs->buf;
5712 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5713
4082afcc 5714 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5715 remote_vcont_probe (rs);
5716
d458bd84 5717 if (!rs->supports_vCont.t)
74531fed
PA
5718 error (_("Remote server does not support stopping threads"));
5719
f91d3df5
PA
5720 if (ptid_equal (ptid, minus_one_ptid)
5721 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5722 p += xsnprintf (p, endp - p, "vCont;t");
5723 else
5724 {
5725 ptid_t nptid;
5726
74531fed
PA
5727 p += xsnprintf (p, endp - p, "vCont;t:");
5728
5729 if (ptid_is_pid (ptid))
5730 /* All (-1) threads of process. */
ba348170 5731 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5732 else
5733 {
5734 /* Small optimization: if we already have a stop reply for
5735 this thread, no use in telling the stub we want this
5736 stopped. */
5737 if (peek_stop_reply (ptid))
5738 return;
5739
5740 nptid = ptid;
5741 }
5742
a9cbf802 5743 write_ptid (p, endp, nptid);
74531fed
PA
5744 }
5745
5746 /* In non-stop, we get an immediate OK reply. The stop reply will
5747 come in asynchronously by notification. */
5748 putpkt (rs->buf);
5749 getpkt (&rs->buf, &rs->buf_size, 0);
5750 if (strcmp (rs->buf, "OK") != 0)
5751 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5752}
5753
bfedc46a
PA
5754/* All-stop version of target_interrupt. Sends a break or a ^C to
5755 interrupt the remote target. It is undefined which thread of which
5756 process reports the interrupt. */
74531fed
PA
5757
5758static void
de979965 5759remote_interrupt_as (void)
74531fed
PA
5760{
5761 struct remote_state *rs = get_remote_state ();
5762
3a29589a
DJ
5763 rs->ctrlc_pending_p = 1;
5764
74531fed
PA
5765 /* If the inferior is stopped already, but the core didn't know
5766 about it yet, just ignore the request. The cached wait status
5767 will be collected in remote_wait. */
5768 if (rs->cached_wait_status)
5769 return;
5770
9a7071a8
JB
5771 /* Send interrupt_sequence to remote target. */
5772 send_interrupt_sequence ();
74531fed
PA
5773}
5774
de979965
PA
5775/* Non-stop version of target_interrupt. Uses `vCtrlC' to interrupt
5776 the remote target. It is undefined which thread of which process
e42de8c7
PA
5777 reports the interrupt. Throws an error if the packet is not
5778 supported by the server. */
de979965 5779
e42de8c7 5780static void
de979965
PA
5781remote_interrupt_ns (void)
5782{
5783 struct remote_state *rs = get_remote_state ();
5784 char *p = rs->buf;
5785 char *endp = rs->buf + get_remote_packet_size ();
5786
5787 xsnprintf (p, endp - p, "vCtrlC");
5788
5789 /* In non-stop, we get an immediate OK reply. The stop reply will
5790 come in asynchronously by notification. */
5791 putpkt (rs->buf);
5792 getpkt (&rs->buf, &rs->buf_size, 0);
5793
5794 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
5795 {
5796 case PACKET_OK:
5797 break;
5798 case PACKET_UNKNOWN:
e42de8c7 5799 error (_("No support for interrupting the remote target."));
de979965
PA
5800 case PACKET_ERROR:
5801 error (_("Interrupting target failed: %s"), rs->buf);
5802 }
de979965
PA
5803}
5804
bfedc46a 5805/* Implement the to_stop function for the remote targets. */
74531fed 5806
c906108c 5807static void
1eab8a48 5808remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5809{
7a292a7a 5810 if (remote_debug)
0f71a2f6 5811 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5812
6efcd9a8 5813 if (target_is_non_stop_p ())
74531fed 5814 remote_stop_ns (ptid);
c906108c 5815 else
bfedc46a
PA
5816 {
5817 /* We don't currently have a way to transparently pause the
5818 remote target in all-stop mode. Interrupt it instead. */
de979965 5819 remote_interrupt_as ();
bfedc46a
PA
5820 }
5821}
5822
5823/* Implement the to_interrupt function for the remote targets. */
5824
5825static void
5826remote_interrupt (struct target_ops *self, ptid_t ptid)
5827{
e42de8c7
PA
5828 struct remote_state *rs = get_remote_state ();
5829
bfedc46a
PA
5830 if (remote_debug)
5831 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5832
e42de8c7
PA
5833 if (target_is_non_stop_p ())
5834 remote_interrupt_ns ();
bfedc46a 5835 else
e42de8c7 5836 remote_interrupt_as ();
c906108c
SS
5837}
5838
93692b58
PA
5839/* Implement the to_pass_ctrlc function for the remote targets. */
5840
5841static void
5842remote_pass_ctrlc (struct target_ops *self)
5843{
5844 struct remote_state *rs = get_remote_state ();
5845
5846 if (remote_debug)
5847 fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
5848
5849 /* If we're starting up, we're not fully synced yet. Quit
5850 immediately. */
5851 if (rs->starting_up)
5852 quit ();
5853 /* If ^C has already been sent once, offer to disconnect. */
5854 else if (rs->ctrlc_pending_p)
5855 interrupt_query ();
5856 else
5857 target_interrupt (inferior_ptid);
5858}
5859
c906108c
SS
5860/* Ask the user what to do when an interrupt is received. */
5861
5862static void
fba45db2 5863interrupt_query (void)
c906108c 5864{
abc56d60 5865 struct remote_state *rs = get_remote_state ();
c906108c 5866
abc56d60 5867 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5868 {
abc56d60
PA
5869 if (query (_("The target is not responding to interrupt requests.\n"
5870 "Stop debugging it? ")))
74531fed 5871 {
78a095c3 5872 remote_unpush_target ();
abc56d60 5873 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5874 }
5875 }
abc56d60
PA
5876 else
5877 {
5878 if (query (_("Interrupted while waiting for the program.\n"
5879 "Give up waiting? ")))
5880 quit ();
5881 }
c906108c
SS
5882}
5883
6426a772
JM
5884/* Enable/disable target terminal ownership. Most targets can use
5885 terminal groups to control terminal ownership. Remote targets are
5886 different in that explicit transfer of ownership to/from GDB/target
23860348 5887 is required. */
6426a772
JM
5888
5889static void
d2f640d4 5890remote_terminal_inferior (struct target_ops *self)
6426a772 5891{
d9d2d8b6
PA
5892 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5893 idempotent. The event-loop GDB talking to an asynchronous target
5894 with a synchronous command calls this function from both
5895 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5896 transfer the terminal to the target when it shouldn't this guard
5897 can go away. */
6426a772
JM
5898 if (!remote_async_terminal_ours_p)
5899 return;
5900 delete_file_handler (input_fd);
5901 remote_async_terminal_ours_p = 0;
6426a772
JM
5902 /* NOTE: At this point we could also register our selves as the
5903 recipient of all input. Any characters typed could then be
23860348 5904 passed on down to the target. */
6426a772
JM
5905}
5906
5907static void
e3594fd1 5908remote_terminal_ours (struct target_ops *self)
6426a772 5909{
75c99385 5910 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5911 if (remote_async_terminal_ours_p)
5912 return;
6426a772
JM
5913 add_file_handler (input_fd, stdin_event_handler, 0);
5914 remote_async_terminal_ours_p = 1;
5915}
5916
176a6961 5917static void
917317f4 5918remote_console_output (char *msg)
c906108c
SS
5919{
5920 char *p;
5921
c5aa993b 5922 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5923 {
5924 char tb[2];
5925 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5926
c906108c
SS
5927 tb[0] = c;
5928 tb[1] = 0;
43ff13b4 5929 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5930 }
00db5b94
PA
5931 gdb_flush (gdb_stdtarg);
5932}
74531fed
PA
5933
5934typedef struct cached_reg
5935{
5936 int num;
5937 gdb_byte data[MAX_REGISTER_SIZE];
5938} cached_reg_t;
5939
5940DEF_VEC_O(cached_reg_t);
5941
722247f1 5942typedef struct stop_reply
74531fed 5943{
722247f1 5944 struct notif_event base;
74531fed 5945
722247f1 5946 /* The identifier of the thread about this event */
74531fed
PA
5947 ptid_t ptid;
5948
340e3c99 5949 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5950 connection, represented by a remote_state object, is closed,
5951 all the associated stop_reply events should be released. */
5952 struct remote_state *rs;
5953
74531fed
PA
5954 struct target_waitstatus ws;
5955
15148d6a
PA
5956 /* Expedited registers. This makes remote debugging a bit more
5957 efficient for those targets that provide critical registers as
5958 part of their normal status mechanism (as another roundtrip to
5959 fetch them is avoided). */
74531fed
PA
5960 VEC(cached_reg_t) *regcache;
5961
f7e6eed5
PA
5962 enum target_stop_reason stop_reason;
5963
74531fed
PA
5964 CORE_ADDR watch_data_address;
5965
dc146f7c 5966 int core;
722247f1 5967} *stop_reply_p;
a744cf53 5968
722247f1
YQ
5969DECLARE_QUEUE_P (stop_reply_p);
5970DEFINE_QUEUE_P (stop_reply_p);
5971/* The list of already fetched and acknowledged stop events. This
5972 queue is used for notification Stop, and other notifications
5973 don't need queue for their events, because the notification events
5974 of Stop can't be consumed immediately, so that events should be
5975 queued first, and be consumed by remote_wait_{ns,as} one per
5976 time. Other notifications can consume their events immediately,
5977 so queue is not needed for them. */
5978static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5979
5980static void
5981stop_reply_xfree (struct stop_reply *r)
5982{
f48ff2a7 5983 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5984}
5985
221e1a37
PA
5986/* Return the length of the stop reply queue. */
5987
5988static int
5989stop_reply_queue_length (void)
5990{
5991 return QUEUE_length (stop_reply_p, stop_reply_queue);
5992}
5993
722247f1
YQ
5994static void
5995remote_notif_stop_parse (struct notif_client *self, char *buf,
5996 struct notif_event *event)
5997{
5998 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5999}
6000
6001static void
6002remote_notif_stop_ack (struct notif_client *self, char *buf,
6003 struct notif_event *event)
6004{
6005 struct stop_reply *stop_reply = (struct stop_reply *) event;
6006
6007 /* acknowledge */
6008 putpkt ((char *) self->ack_command);
6009
6010 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6011 /* We got an unknown stop reply. */
6012 error (_("Unknown stop reply"));
6013
6014 push_stop_reply (stop_reply);
6015}
6016
6017static int
6018remote_notif_stop_can_get_pending_events (struct notif_client *self)
6019{
6020 /* We can't get pending events in remote_notif_process for
6021 notification stop, and we have to do this in remote_wait_ns
6022 instead. If we fetch all queued events from stub, remote stub
6023 may exit and we have no chance to process them back in
6024 remote_wait_ns. */
6025 mark_async_event_handler (remote_async_inferior_event_token);
6026 return 0;
6027}
6028
6029static void
6030stop_reply_dtr (struct notif_event *event)
6031{
6032 struct stop_reply *r = (struct stop_reply *) event;
6033
6034 VEC_free (cached_reg_t, r->regcache);
6035}
6036
6037static struct notif_event *
6038remote_notif_stop_alloc_reply (void)
6039{
8d749320
SM
6040 /* We cast to a pointer to the "base class". */
6041 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
6042
6043 r->dtr = stop_reply_dtr;
6044
6045 return r;
6046}
6047
6048/* A client of notification Stop. */
6049
6050struct notif_client notif_client_stop =
6051{
6052 "Stop",
6053 "vStopped",
6054 remote_notif_stop_parse,
6055 remote_notif_stop_ack,
6056 remote_notif_stop_can_get_pending_events,
6057 remote_notif_stop_alloc_reply,
f48ff2a7 6058 REMOTE_NOTIF_STOP,
722247f1
YQ
6059};
6060
6061/* A parameter to pass data in and out. */
6062
6063struct queue_iter_param
6064{
6065 void *input;
6066 struct stop_reply *output;
6067};
6068
cbb8991c
DB
6069/* Determine if THREAD is a pending fork parent thread. ARG contains
6070 the pid of the process that owns the threads we want to check, or
6071 -1 if we want to check all threads. */
6072
6073static int
6074is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6075 ptid_t thread_ptid)
6076{
6077 if (ws->kind == TARGET_WAITKIND_FORKED
6078 || ws->kind == TARGET_WAITKIND_VFORKED)
6079 {
6080 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6081 return 1;
6082 }
6083
6084 return 0;
6085}
6086
6087/* Check whether EVENT is a fork event, and if it is, remove the
6088 fork child from the context list passed in DATA. */
6089
6090static int
6091remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6092 QUEUE_ITER (stop_reply_p) *iter,
6093 stop_reply_p event,
6094 void *data)
6095{
19ba03f4
SM
6096 struct queue_iter_param *param = (struct queue_iter_param *) data;
6097 struct threads_listing_context *context
6098 = (struct threads_listing_context *) param->input;
cbb8991c
DB
6099
6100 if (event->ws.kind == TARGET_WAITKIND_FORKED
65706a29
PA
6101 || event->ws.kind == TARGET_WAITKIND_VFORKED
6102 || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6103 threads_listing_context_remove (&event->ws, context);
cbb8991c
DB
6104
6105 return 1;
6106}
6107
6108/* If CONTEXT contains any fork child threads that have not been
6109 reported yet, remove them from the CONTEXT list. If such a
6110 thread exists it is because we are stopped at a fork catchpoint
6111 and have not yet called follow_fork, which will set up the
6112 host-side data structures for the new process. */
6113
6114static void
6115remove_new_fork_children (struct threads_listing_context *context)
6116{
6117 struct thread_info * thread;
6118 int pid = -1;
6119 struct notif_client *notif = &notif_client_stop;
6120 struct queue_iter_param param;
6121
6122 /* For any threads stopped at a fork event, remove the corresponding
6123 fork child threads from the CONTEXT list. */
6124 ALL_NON_EXITED_THREADS (thread)
6125 {
4041ed77
DB
6126 struct target_waitstatus *ws;
6127
6128 if (thread->suspend.waitstatus_pending_p)
6129 ws = &thread->suspend.waitstatus;
6130 else
6131 ws = &thread->pending_follow;
cbb8991c
DB
6132
6133 if (is_pending_fork_parent (ws, pid, thread->ptid))
6134 {
6135 threads_listing_context_remove (ws, context);
6136 }
6137 }
6138
6139 /* Check for any pending fork events (not reported or processed yet)
6140 in process PID and remove those fork child threads from the
6141 CONTEXT list as well. */
6142 remote_notif_get_pending_events (notif);
6143 param.input = context;
6144 param.output = NULL;
6145 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6146 remove_child_of_pending_fork, &param);
6147}
6148
f48ff2a7
YQ
6149/* Remove stop replies in the queue if its pid is equal to the given
6150 inferior's pid. */
722247f1
YQ
6151
6152static int
f48ff2a7
YQ
6153remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6154 QUEUE_ITER (stop_reply_p) *iter,
6155 stop_reply_p event,
6156 void *data)
722247f1 6157{
19ba03f4
SM
6158 struct queue_iter_param *param = (struct queue_iter_param *) data;
6159 struct inferior *inf = (struct inferior *) param->input;
722247f1 6160
f48ff2a7 6161 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
6162 {
6163 stop_reply_xfree (event);
6164 QUEUE_remove_elem (stop_reply_p, q, iter);
6165 }
6166
6167 return 1;
6168}
6169
f48ff2a7 6170/* Discard all pending stop replies of inferior INF. */
c906108c 6171
74531fed 6172static void
5f4cf0bb 6173discard_pending_stop_replies (struct inferior *inf)
c906108c 6174{
722247f1 6175 struct queue_iter_param param;
f48ff2a7
YQ
6176 struct stop_reply *reply;
6177 struct remote_state *rs = get_remote_state ();
6178 struct remote_notif_state *rns = rs->notif_state;
6179
6180 /* This function can be notified when an inferior exists. When the
6181 target is not remote, the notification state is NULL. */
6182 if (rs->remote_desc == NULL)
6183 return;
6184
6185 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 6186
74531fed 6187 /* Discard the in-flight notification. */
f48ff2a7 6188 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 6189 {
722247f1 6190 stop_reply_xfree (reply);
f48ff2a7 6191 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 6192 }
c906108c 6193
722247f1
YQ
6194 param.input = inf;
6195 param.output = NULL;
74531fed
PA
6196 /* Discard the stop replies we have already pulled with
6197 vStopped. */
722247f1 6198 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
6199 remove_stop_reply_for_inferior, &param);
6200}
6201
bcc75809
YQ
6202/* If its remote state is equal to the given remote state,
6203 remove EVENT from the stop reply queue. */
6204
6205static int
6206remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6207 QUEUE_ITER (stop_reply_p) *iter,
6208 stop_reply_p event,
6209 void *data)
6210{
19ba03f4
SM
6211 struct queue_iter_param *param = (struct queue_iter_param *) data;
6212 struct remote_state *rs = (struct remote_state *) param->input;
bcc75809
YQ
6213
6214 if (event->rs == rs)
6215 {
6216 stop_reply_xfree (event);
6217 QUEUE_remove_elem (stop_reply_p, q, iter);
6218 }
6219
6220 return 1;
6221}
6222
6223/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
6224
6225static void
bcc75809 6226discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
6227{
6228 struct queue_iter_param param;
6229
bcc75809 6230 param.input = rs;
f48ff2a7
YQ
6231 param.output = NULL;
6232 /* Discard the stop replies we have already pulled with
6233 vStopped. */
6234 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 6235 remove_stop_reply_of_remote_state, &param);
722247f1 6236}
74531fed 6237
722247f1
YQ
6238/* A parameter to pass data in and out. */
6239
6240static int
6241remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6242 QUEUE_ITER (stop_reply_p) *iter,
6243 stop_reply_p event,
6244 void *data)
6245{
19ba03f4
SM
6246 struct queue_iter_param *param = (struct queue_iter_param *) data;
6247 ptid_t *ptid = (ptid_t *) param->input;
722247f1
YQ
6248
6249 if (ptid_match (event->ptid, *ptid))
6250 {
6251 param->output = event;
6252 QUEUE_remove_elem (stop_reply_p, q, iter);
6253 return 0;
c8e38a49 6254 }
722247f1
YQ
6255
6256 return 1;
74531fed 6257}
43ff13b4 6258
722247f1
YQ
6259/* Remove the first reply in 'stop_reply_queue' which matches
6260 PTID. */
2e9f7625 6261
722247f1
YQ
6262static struct stop_reply *
6263remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 6264{
722247f1
YQ
6265 struct queue_iter_param param;
6266
6267 param.input = &ptid;
6268 param.output = NULL;
6269
6270 QUEUE_iterate (stop_reply_p, stop_reply_queue,
6271 remote_notif_remove_once_on_match, &param);
6272 if (notif_debug)
6273 fprintf_unfiltered (gdb_stdlog,
6274 "notif: discard queued event: 'Stop' in %s\n",
6275 target_pid_to_str (ptid));
a744cf53 6276
722247f1 6277 return param.output;
74531fed 6278}
75c99385 6279
74531fed
PA
6280/* Look for a queued stop reply belonging to PTID. If one is found,
6281 remove it from the queue, and return it. Returns NULL if none is
6282 found. If there are still queued events left to process, tell the
6283 event loop to get back to target_wait soon. */
e24a49d8 6284
74531fed
PA
6285static struct stop_reply *
6286queued_stop_reply (ptid_t ptid)
6287{
722247f1 6288 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 6289
722247f1 6290 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
6291 /* There's still at least an event left. */
6292 mark_async_event_handler (remote_async_inferior_event_token);
6293
722247f1 6294 return r;
74531fed
PA
6295}
6296
6297/* Push a fully parsed stop reply in the stop reply queue. Since we
6298 know that we now have at least one queued event left to pass to the
6299 core side, tell the event loop to get back to target_wait soon. */
6300
6301static void
6302push_stop_reply (struct stop_reply *new_event)
6303{
722247f1 6304 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 6305
722247f1
YQ
6306 if (notif_debug)
6307 fprintf_unfiltered (gdb_stdlog,
6308 "notif: push 'Stop' %s to queue %d\n",
6309 target_pid_to_str (new_event->ptid),
6310 QUEUE_length (stop_reply_p,
6311 stop_reply_queue));
74531fed
PA
6312
6313 mark_async_event_handler (remote_async_inferior_event_token);
6314}
6315
722247f1
YQ
6316static int
6317stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6318 QUEUE_ITER (stop_reply_p) *iter,
6319 struct stop_reply *event,
6320 void *data)
6321{
19ba03f4 6322 ptid_t *ptid = (ptid_t *) data;
722247f1
YQ
6323
6324 return !(ptid_equal (*ptid, event->ptid)
6325 && event->ws.kind == TARGET_WAITKIND_STOPPED);
6326}
6327
74531fed
PA
6328/* Returns true if we have a stop reply for PTID. */
6329
6330static int
6331peek_stop_reply (ptid_t ptid)
6332{
722247f1
YQ
6333 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6334 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
6335}
6336
26d56a93
SL
6337/* Helper for remote_parse_stop_reply. Return nonzero if the substring
6338 starting with P and ending with PEND matches PREFIX. */
6339
6340static int
6341strprefix (const char *p, const char *pend, const char *prefix)
6342{
6343 for ( ; p < pend; p++, prefix++)
6344 if (*p != *prefix)
6345 return 0;
6346 return *prefix == '\0';
6347}
6348
74531fed
PA
6349/* Parse the stop reply in BUF. Either the function succeeds, and the
6350 result is stored in EVENT, or throws an error. */
6351
6352static void
6353remote_parse_stop_reply (char *buf, struct stop_reply *event)
6354{
6355 struct remote_arch_state *rsa = get_remote_arch_state ();
6356 ULONGEST addr;
6357 char *p;
94585166 6358 int skipregs = 0;
74531fed
PA
6359
6360 event->ptid = null_ptid;
bcc75809 6361 event->rs = get_remote_state ();
74531fed
PA
6362 event->ws.kind = TARGET_WAITKIND_IGNORE;
6363 event->ws.value.integer = 0;
f7e6eed5 6364 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 6365 event->regcache = NULL;
dc146f7c 6366 event->core = -1;
74531fed
PA
6367
6368 switch (buf[0])
6369 {
6370 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
6371 /* Expedited reply, containing Signal, {regno, reg} repeat. */
6372 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
6373 ss = signal number
6374 n... = register number
6375 r... = register contents
6376 */
6377
6378 p = &buf[3]; /* after Txx */
6379 while (*p)
6380 {
6381 char *p1;
cea39f65 6382 int fieldsize;
43ff13b4 6383
1f10ba14
PA
6384 p1 = strchr (p, ':');
6385 if (p1 == NULL)
6386 error (_("Malformed packet(a) (missing colon): %s\n\
6387Packet: '%s'\n"),
6388 p, buf);
6389 if (p == p1)
6390 error (_("Malformed packet(a) (missing register number): %s\n\
6391Packet: '%s'\n"),
6392 p, buf);
3c3bea1c 6393
1f10ba14
PA
6394 /* Some "registers" are actually extended stop information.
6395 Note if you're adding a new entry here: GDB 7.9 and
6396 earlier assume that all register "numbers" that start
6397 with an hex digit are real register numbers. Make sure
6398 the server only sends such a packet if it knows the
6399 client understands it. */
c8e38a49 6400
26d56a93 6401 if (strprefix (p, p1, "thread"))
1f10ba14 6402 event->ptid = read_ptid (++p1, &p);
82075af2
JS
6403 else if (strprefix (p, p1, "syscall_entry"))
6404 {
6405 ULONGEST sysno;
6406
6407 event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6408 p = unpack_varlen_hex (++p1, &sysno);
6409 event->ws.value.syscall_number = (int) sysno;
6410 }
6411 else if (strprefix (p, p1, "syscall_return"))
6412 {
6413 ULONGEST sysno;
6414
6415 event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6416 p = unpack_varlen_hex (++p1, &sysno);
6417 event->ws.value.syscall_number = (int) sysno;
6418 }
26d56a93
SL
6419 else if (strprefix (p, p1, "watch")
6420 || strprefix (p, p1, "rwatch")
6421 || strprefix (p, p1, "awatch"))
cea39f65 6422 {
f7e6eed5 6423 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6424 p = unpack_varlen_hex (++p1, &addr);
6425 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6426 }
26d56a93 6427 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6428 {
6429 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6430
6431 /* Make sure the stub doesn't forget to indicate support
6432 with qSupported. */
6433 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6434 error (_("Unexpected swbreak stop reason"));
6435
6436 /* The value part is documented as "must be empty",
6437 though we ignore it, in case we ever decide to make
6438 use of it in a backward compatible way. */
8424cc97 6439 p = strchrnul (p1 + 1, ';');
f7e6eed5 6440 }
26d56a93 6441 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6442 {
6443 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6444
6445 /* Make sure the stub doesn't forget to indicate support
6446 with qSupported. */
6447 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6448 error (_("Unexpected hwbreak stop reason"));
6449
6450 /* See above. */
8424cc97 6451 p = strchrnul (p1 + 1, ';');
f7e6eed5 6452 }
26d56a93 6453 else if (strprefix (p, p1, "library"))
cea39f65 6454 {
1f10ba14 6455 event->ws.kind = TARGET_WAITKIND_LOADED;
8424cc97 6456 p = strchrnul (p1 + 1, ';');
1f10ba14 6457 }
26d56a93 6458 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6459 {
6460 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6461 /* p1 will indicate "begin" or "end", but it makes
6462 no difference for now, so ignore it. */
8424cc97 6463 p = strchrnul (p1 + 1, ';');
1f10ba14 6464 }
26d56a93 6465 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6466 {
6467 ULONGEST c;
a744cf53 6468
1f10ba14
PA
6469 p = unpack_varlen_hex (++p1, &c);
6470 event->core = c;
cea39f65 6471 }
26d56a93 6472 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6473 {
6474 event->ws.value.related_pid = read_ptid (++p1, &p);
6475 event->ws.kind = TARGET_WAITKIND_FORKED;
6476 }
26d56a93 6477 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6478 {
6479 event->ws.value.related_pid = read_ptid (++p1, &p);
6480 event->ws.kind = TARGET_WAITKIND_VFORKED;
6481 }
26d56a93 6482 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6483 {
6484 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
8424cc97 6485 p = strchrnul (p1 + 1, ';');
c269dbdb 6486 }
6ab24463 6487 else if (strprefix (p, p1, "exec"))
94585166
DB
6488 {
6489 ULONGEST ignored;
6490 char pathname[PATH_MAX];
6491 int pathlen;
6492
6493 /* Determine the length of the execd pathname. */
6494 p = unpack_varlen_hex (++p1, &ignored);
6495 pathlen = (p - p1) / 2;
6496
6497 /* Save the pathname for event reporting and for
6498 the next run command. */
6499 hex2bin (p1, (gdb_byte *) pathname, pathlen);
6500 pathname[pathlen] = '\0';
6501
6502 /* This is freed during event handling. */
6503 event->ws.value.execd_pathname = xstrdup (pathname);
6504 event->ws.kind = TARGET_WAITKIND_EXECD;
6505
6506 /* Skip the registers included in this packet, since
6507 they may be for an architecture different from the
6508 one used by the original program. */
6509 skipregs = 1;
6510 }
65706a29
PA
6511 else if (strprefix (p, p1, "create"))
6512 {
6513 event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
8424cc97 6514 p = strchrnul (p1 + 1, ';');
65706a29 6515 }
cea39f65
MS
6516 else
6517 {
1f10ba14
PA
6518 ULONGEST pnum;
6519 char *p_temp;
6520
94585166
DB
6521 if (skipregs)
6522 {
8424cc97 6523 p = strchrnul (p1 + 1, ';');
94585166
DB
6524 p++;
6525 continue;
6526 }
6527
1f10ba14
PA
6528 /* Maybe a real ``P'' register number. */
6529 p_temp = unpack_varlen_hex (p, &pnum);
6530 /* If the first invalid character is the colon, we got a
6531 register number. Otherwise, it's an unknown stop
6532 reason. */
6533 if (p_temp == p1)
6534 {
6535 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6536 cached_reg_t cached_reg;
43ff13b4 6537
1f10ba14
PA
6538 if (reg == NULL)
6539 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6540Packet: '%s'\n"),
1f10ba14 6541 hex_string (pnum), p, buf);
c8e38a49 6542
1f10ba14 6543 cached_reg.num = reg->regnum;
4100683b 6544
1f10ba14
PA
6545 p = p1 + 1;
6546 fieldsize = hex2bin (p, cached_reg.data,
6547 register_size (target_gdbarch (),
6548 reg->regnum));
6549 p += 2 * fieldsize;
6550 if (fieldsize < register_size (target_gdbarch (),
6551 reg->regnum))
6552 warning (_("Remote reply is too short: %s"), buf);
74531fed 6553
1f10ba14
PA
6554 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6555 }
6556 else
6557 {
6558 /* Not a number. Silently skip unknown optional
6559 info. */
8424cc97 6560 p = strchrnul (p1 + 1, ';');
1f10ba14 6561 }
cea39f65 6562 }
c8e38a49 6563
cea39f65
MS
6564 if (*p != ';')
6565 error (_("Remote register badly formatted: %s\nhere: %s"),
6566 buf, p);
6567 ++p;
6568 }
5b5596ff
PA
6569
6570 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6571 break;
6572
c8e38a49
PA
6573 /* fall through */
6574 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6575 {
6576 int sig;
6577
6578 event->ws.kind = TARGET_WAITKIND_STOPPED;
6579 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6580 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6581 event->ws.value.sig = (enum gdb_signal) sig;
6582 else
6583 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6584 }
c8e38a49 6585 break;
65706a29
PA
6586 case 'w': /* Thread exited. */
6587 {
6588 char *p;
6589 ULONGEST value;
6590
6591 event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
6592 p = unpack_varlen_hex (&buf[1], &value);
6593 event->ws.value.integer = value;
6594 if (*p != ';')
6595 error (_("stop reply packet badly formatted: %s"), buf);
974eac9d 6596 event->ptid = read_ptid (++p, NULL);
65706a29
PA
6597 break;
6598 }
c8e38a49
PA
6599 case 'W': /* Target exited. */
6600 case 'X':
6601 {
6602 char *p;
6603 int pid;
6604 ULONGEST value;
82f73884 6605
c8e38a49
PA
6606 /* GDB used to accept only 2 hex chars here. Stubs should
6607 only send more if they detect GDB supports multi-process
6608 support. */
6609 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6610
c8e38a49
PA
6611 if (buf[0] == 'W')
6612 {
6613 /* The remote process exited. */
74531fed
PA
6614 event->ws.kind = TARGET_WAITKIND_EXITED;
6615 event->ws.value.integer = value;
c8e38a49
PA
6616 }
6617 else
6618 {
6619 /* The remote process exited with a signal. */
74531fed 6620 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6621 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6622 event->ws.value.sig = (enum gdb_signal) value;
6623 else
6624 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6625 }
82f73884 6626
c8e38a49
PA
6627 /* If no process is specified, assume inferior_ptid. */
6628 pid = ptid_get_pid (inferior_ptid);
6629 if (*p == '\0')
6630 ;
6631 else if (*p == ';')
6632 {
6633 p++;
6634
0b24eb2d 6635 if (*p == '\0')
82f73884 6636 ;
61012eef 6637 else if (startswith (p, "process:"))
82f73884 6638 {
c8e38a49 6639 ULONGEST upid;
a744cf53 6640
c8e38a49
PA
6641 p += sizeof ("process:") - 1;
6642 unpack_varlen_hex (p, &upid);
6643 pid = upid;
82f73884
PA
6644 }
6645 else
6646 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6647 }
c8e38a49
PA
6648 else
6649 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6650 event->ptid = pid_to_ptid (pid);
6651 }
6652 break;
f2faf941
PA
6653 case 'N':
6654 event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
6655 event->ptid = minus_one_ptid;
6656 break;
74531fed
PA
6657 }
6658
6efcd9a8 6659 if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
74531fed
PA
6660 error (_("No process or thread specified in stop reply: %s"), buf);
6661}
6662
722247f1
YQ
6663/* When the stub wants to tell GDB about a new notification reply, it
6664 sends a notification (%Stop, for example). Those can come it at
6665 any time, hence, we have to make sure that any pending
6666 putpkt/getpkt sequence we're making is finished, before querying
6667 the stub for more events with the corresponding ack command
6668 (vStopped, for example). E.g., if we started a vStopped sequence
6669 immediately upon receiving the notification, something like this
6670 could happen:
74531fed
PA
6671
6672 1.1) --> Hg 1
6673 1.2) <-- OK
6674 1.3) --> g
6675 1.4) <-- %Stop
6676 1.5) --> vStopped
6677 1.6) <-- (registers reply to step #1.3)
6678
6679 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6680 query.
6681
796cb314 6682 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6683 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6684 doing whatever we were doing:
6685
6686 2.1) --> Hg 1
6687 2.2) <-- OK
6688 2.3) --> g
6689 2.4) <-- %Stop
6690 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6691 2.5) <-- (registers reply to step #2.3)
6692
6693 Eventualy after step #2.5, we return to the event loop, which
6694 notices there's an event on the
6695 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6696 associated callback --- the function below. At this point, we're
6697 always safe to start a vStopped sequence. :
6698
6699 2.6) --> vStopped
6700 2.7) <-- T05 thread:2
6701 2.8) --> vStopped
6702 2.9) --> OK
6703*/
6704
722247f1
YQ
6705void
6706remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6707{
6708 struct remote_state *rs = get_remote_state ();
74531fed 6709
f48ff2a7 6710 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6711 {
722247f1
YQ
6712 if (notif_debug)
6713 fprintf_unfiltered (gdb_stdlog,
6714 "notif: process: '%s' ack pending event\n",
6715 nc->name);
74531fed 6716
722247f1 6717 /* acknowledge */
f48ff2a7
YQ
6718 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6719 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6720
6721 while (1)
6722 {
6723 getpkt (&rs->buf, &rs->buf_size, 0);
6724 if (strcmp (rs->buf, "OK") == 0)
6725 break;
6726 else
722247f1 6727 remote_notif_ack (nc, rs->buf);
74531fed
PA
6728 }
6729 }
722247f1
YQ
6730 else
6731 {
6732 if (notif_debug)
6733 fprintf_unfiltered (gdb_stdlog,
6734 "notif: process: '%s' no pending reply\n",
6735 nc->name);
6736 }
74531fed
PA
6737}
6738
74531fed
PA
6739/* Called when it is decided that STOP_REPLY holds the info of the
6740 event that is to be returned to the core. This function always
6741 destroys STOP_REPLY. */
6742
6743static ptid_t
6744process_stop_reply (struct stop_reply *stop_reply,
6745 struct target_waitstatus *status)
6746{
6747 ptid_t ptid;
6748
6749 *status = stop_reply->ws;
6750 ptid = stop_reply->ptid;
6751
6752 /* If no thread/process was reported by the stub, assume the current
6753 inferior. */
6754 if (ptid_equal (ptid, null_ptid))
6755 ptid = inferior_ptid;
6756
5f3563ea 6757 if (status->kind != TARGET_WAITKIND_EXITED
f2faf941
PA
6758 && status->kind != TARGET_WAITKIND_SIGNALLED
6759 && status->kind != TARGET_WAITKIND_NO_RESUMED)
74531fed 6760 {
799a2abe 6761 struct private_thread_info *remote_thr;
ee154bee 6762
5f3563ea
PA
6763 /* Expedited registers. */
6764 if (stop_reply->regcache)
6765 {
217f1f79 6766 struct regcache *regcache
f5656ead 6767 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6768 cached_reg_t *reg;
6769 int ix;
6770
6771 for (ix = 0;
6772 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6773 ix++)
217f1f79 6774 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6775 VEC_free (cached_reg_t, stop_reply->regcache);
6776 }
74531fed 6777
1941c569 6778 remote_notice_new_inferior (ptid, 0);
799a2abe
PA
6779 remote_thr = demand_private_info (ptid);
6780 remote_thr->core = stop_reply->core;
6781 remote_thr->stop_reason = stop_reply->stop_reason;
6782 remote_thr->watch_data_address = stop_reply->watch_data_address;
74531fed
PA
6783 }
6784
74531fed
PA
6785 stop_reply_xfree (stop_reply);
6786 return ptid;
6787}
6788
6789/* The non-stop mode version of target_wait. */
6790
6791static ptid_t
47608cb1 6792remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6793{
6794 struct remote_state *rs = get_remote_state ();
74531fed
PA
6795 struct stop_reply *stop_reply;
6796 int ret;
fee9eda9 6797 int is_notif = 0;
74531fed
PA
6798
6799 /* If in non-stop mode, get out of getpkt even if a
6800 notification is received. */
6801
6802 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6803 0 /* forever */, &is_notif);
74531fed
PA
6804 while (1)
6805 {
fee9eda9 6806 if (ret != -1 && !is_notif)
74531fed
PA
6807 switch (rs->buf[0])
6808 {
6809 case 'E': /* Error of some sort. */
6810 /* We're out of sync with the target now. Did it continue
6811 or not? We can't tell which thread it was in non-stop,
6812 so just ignore this. */
6813 warning (_("Remote failure reply: %s"), rs->buf);
6814 break;
6815 case 'O': /* Console output. */
6816 remote_console_output (rs->buf + 1);
6817 break;
6818 default:
6819 warning (_("Invalid remote reply: %s"), rs->buf);
6820 break;
6821 }
6822
6823 /* Acknowledge a pending stop reply that may have arrived in the
6824 mean time. */
f48ff2a7 6825 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6826 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6827
6828 /* If indeed we noticed a stop reply, we're done. */
6829 stop_reply = queued_stop_reply (ptid);
6830 if (stop_reply != NULL)
6831 return process_stop_reply (stop_reply, status);
6832
47608cb1 6833 /* Still no event. If we're just polling for an event, then
74531fed 6834 return to the event loop. */
47608cb1 6835 if (options & TARGET_WNOHANG)
74531fed
PA
6836 {
6837 status->kind = TARGET_WAITKIND_IGNORE;
6838 return minus_one_ptid;
6839 }
6840
47608cb1 6841 /* Otherwise do a blocking wait. */
74531fed 6842 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6843 1 /* forever */, &is_notif);
74531fed
PA
6844 }
6845}
6846
6847/* Wait until the remote machine stops, then return, storing status in
6848 STATUS just as `wait' would. */
6849
6850static ptid_t
47608cb1 6851remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6852{
6853 struct remote_state *rs = get_remote_state ();
74531fed 6854 ptid_t event_ptid = null_ptid;
cea39f65 6855 char *buf;
74531fed
PA
6856 struct stop_reply *stop_reply;
6857
47608cb1
PA
6858 again:
6859
74531fed
PA
6860 status->kind = TARGET_WAITKIND_IGNORE;
6861 status->value.integer = 0;
6862
6863 stop_reply = queued_stop_reply (ptid);
6864 if (stop_reply != NULL)
6865 return process_stop_reply (stop_reply, status);
6866
6867 if (rs->cached_wait_status)
6868 /* Use the cached wait status, but only once. */
6869 rs->cached_wait_status = 0;
6870 else
6871 {
6872 int ret;
722247f1 6873 int is_notif;
567420d1
PA
6874 int forever = ((options & TARGET_WNOHANG) == 0
6875 && wait_forever_enabled_p);
6876
6877 if (!rs->waiting_for_stop_reply)
6878 {
6879 status->kind = TARGET_WAITKIND_NO_RESUMED;
6880 return minus_one_ptid;
6881 }
74531fed 6882
74531fed
PA
6883 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6884 _never_ wait for ever -> test on target_is_async_p().
6885 However, before we do that we need to ensure that the caller
6886 knows how to take the target into/out of async mode. */
722247f1 6887 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6888 forever, &is_notif);
722247f1
YQ
6889
6890 /* GDB gets a notification. Return to core as this event is
6891 not interesting. */
6892 if (ret != -1 && is_notif)
6893 return minus_one_ptid;
567420d1
PA
6894
6895 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6896 return minus_one_ptid;
74531fed
PA
6897 }
6898
6899 buf = rs->buf;
6900
3a29589a
DJ
6901 /* Assume that the target has acknowledged Ctrl-C unless we receive
6902 an 'F' or 'O' packet. */
6903 if (buf[0] != 'F' && buf[0] != 'O')
6904 rs->ctrlc_pending_p = 0;
6905
74531fed
PA
6906 switch (buf[0])
6907 {
6908 case 'E': /* Error of some sort. */
6909 /* We're out of sync with the target now. Did it continue or
6910 not? Not is more likely, so report a stop. */
29090fb6
LM
6911 rs->waiting_for_stop_reply = 0;
6912
74531fed
PA
6913 warning (_("Remote failure reply: %s"), buf);
6914 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6915 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6916 break;
6917 case 'F': /* File-I/O request. */
e42e5352
YQ
6918 /* GDB may access the inferior memory while handling the File-I/O
6919 request, but we don't want GDB accessing memory while waiting
6920 for a stop reply. See the comments in putpkt_binary. Set
6921 waiting_for_stop_reply to 0 temporarily. */
6922 rs->waiting_for_stop_reply = 0;
3a29589a
DJ
6923 remote_fileio_request (buf, rs->ctrlc_pending_p);
6924 rs->ctrlc_pending_p = 0;
e42e5352
YQ
6925 /* GDB handled the File-I/O request, and the target is running
6926 again. Keep waiting for events. */
6927 rs->waiting_for_stop_reply = 1;
74531fed 6928 break;
f2faf941 6929 case 'N': case 'T': case 'S': case 'X': case 'W':
74531fed 6930 {
29090fb6
LM
6931 struct stop_reply *stop_reply;
6932
6933 /* There is a stop reply to handle. */
6934 rs->waiting_for_stop_reply = 0;
6935
6936 stop_reply
722247f1
YQ
6937 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6938 rs->buf);
74531fed 6939
74531fed 6940 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6941 break;
6942 }
6943 case 'O': /* Console output. */
6944 remote_console_output (buf + 1);
c8e38a49
PA
6945 break;
6946 case '\0':
b73be471 6947 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6948 {
6949 /* Zero length reply means that we tried 'S' or 'C' and the
6950 remote system doesn't support it. */
6951 target_terminal_ours_for_output ();
6952 printf_filtered
6953 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6954 gdb_signal_to_name (rs->last_sent_signal));
6955 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6956 target_terminal_inferior ();
6957
280ceea3 6958 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49 6959 putpkt ((char *) buf);
c8e38a49 6960 break;
43ff13b4 6961 }
c8e38a49
PA
6962 /* else fallthrough */
6963 default:
6964 warning (_("Invalid remote reply: %s"), buf);
c8e38a49 6965 break;
43ff13b4 6966 }
c8e38a49 6967
f2faf941
PA
6968 if (status->kind == TARGET_WAITKIND_NO_RESUMED)
6969 return minus_one_ptid;
6970 else if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6971 {
6972 /* Nothing interesting happened. If we're doing a non-blocking
6973 poll, we're done. Otherwise, go back to waiting. */
6974 if (options & TARGET_WNOHANG)
6975 return minus_one_ptid;
6976 else
6977 goto again;
6978 }
74531fed
PA
6979 else if (status->kind != TARGET_WAITKIND_EXITED
6980 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6981 {
6982 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6983 record_currthread (rs, event_ptid);
82f73884
PA
6984 else
6985 event_ptid = inferior_ptid;
43ff13b4 6986 }
74531fed
PA
6987 else
6988 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6989 record_currthread (rs, minus_one_ptid);
79d7f229 6990
82f73884 6991 return event_ptid;
43ff13b4
JM
6992}
6993
74531fed
PA
6994/* Wait until the remote machine stops, then return, storing status in
6995 STATUS just as `wait' would. */
6996
c8e38a49 6997static ptid_t
117de6a9 6998remote_wait (struct target_ops *ops,
47608cb1 6999 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
7000{
7001 ptid_t event_ptid;
7002
6efcd9a8 7003 if (target_is_non_stop_p ())
47608cb1 7004 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 7005 else
47608cb1 7006 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 7007
d9d41e78 7008 if (target_is_async_p ())
c8e38a49 7009 {
74531fed
PA
7010 /* If there are are events left in the queue tell the event loop
7011 to return here. */
722247f1 7012 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 7013 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 7014 }
c8e38a49
PA
7015
7016 return event_ptid;
7017}
7018
74ca34ce 7019/* Fetch a single register using a 'p' packet. */
c906108c 7020
b96ec7ac 7021static int
56be3814 7022fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
7023{
7024 struct remote_state *rs = get_remote_state ();
2e9f7625 7025 char *buf, *p;
b96ec7ac
AC
7026 char regp[MAX_REGISTER_SIZE];
7027 int i;
7028
4082afcc 7029 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
7030 return 0;
7031
7032 if (reg->pnum == -1)
7033 return 0;
7034
2e9f7625 7035 p = rs->buf;
fcad0fa4 7036 *p++ = 'p';
74ca34ce 7037 p += hexnumstr (p, reg->pnum);
fcad0fa4 7038 *p++ = '\0';
1f4437a4
MS
7039 putpkt (rs->buf);
7040 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 7041
2e9f7625
DJ
7042 buf = rs->buf;
7043
74ca34ce
DJ
7044 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7045 {
7046 case PACKET_OK:
7047 break;
7048 case PACKET_UNKNOWN:
7049 return 0;
7050 case PACKET_ERROR:
27a9c0bf
MS
7051 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7052 gdbarch_register_name (get_regcache_arch (regcache),
7053 reg->regnum),
7054 buf);
74ca34ce 7055 }
3f9a994c
JB
7056
7057 /* If this register is unfetchable, tell the regcache. */
7058 if (buf[0] == 'x')
8480adf2 7059 {
56be3814 7060 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 7061 return 1;
b96ec7ac 7062 }
b96ec7ac 7063
3f9a994c
JB
7064 /* Otherwise, parse and supply the value. */
7065 p = buf;
7066 i = 0;
7067 while (p[0] != 0)
7068 {
7069 if (p[1] == 0)
74ca34ce 7070 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
7071
7072 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7073 p += 2;
7074 }
56be3814 7075 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 7076 return 1;
b96ec7ac
AC
7077}
7078
74ca34ce
DJ
7079/* Fetch the registers included in the target's 'g' packet. */
7080
29709017
DJ
7081static int
7082send_g_packet (void)
c906108c 7083{
d01949b6 7084 struct remote_state *rs = get_remote_state ();
cea39f65 7085 int buf_len;
c906108c 7086
bba74b36 7087 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 7088 remote_send (&rs->buf, &rs->buf_size);
c906108c 7089
29709017
DJ
7090 /* We can get out of synch in various cases. If the first character
7091 in the buffer is not a hex character, assume that has happened
7092 and try to fetch another packet to read. */
7093 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7094 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7095 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7096 && rs->buf[0] != 'x') /* New: unavailable register value. */
7097 {
7098 if (remote_debug)
7099 fprintf_unfiltered (gdb_stdlog,
7100 "Bad register packet; fetching a new packet\n");
7101 getpkt (&rs->buf, &rs->buf_size, 0);
7102 }
7103
74ca34ce
DJ
7104 buf_len = strlen (rs->buf);
7105
7106 /* Sanity check the received packet. */
7107 if (buf_len % 2 != 0)
7108 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
7109
7110 return buf_len / 2;
7111}
7112
7113static void
56be3814 7114process_g_packet (struct regcache *regcache)
29709017 7115{
4a22f64d 7116 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
7117 struct remote_state *rs = get_remote_state ();
7118 struct remote_arch_state *rsa = get_remote_arch_state ();
7119 int i, buf_len;
7120 char *p;
7121 char *regs;
7122
7123 buf_len = strlen (rs->buf);
7124
7125 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
7126 if (buf_len > 2 * rsa->sizeof_g_packet)
7127 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
7128
7129 /* Save the size of the packet sent to us by the target. It is used
7130 as a heuristic when determining the max size of packets that the
7131 target can safely receive. */
7132 if (rsa->actual_register_packet_size == 0)
7133 rsa->actual_register_packet_size = buf_len;
7134
7135 /* If this is smaller than we guessed the 'g' packet would be,
7136 update our records. A 'g' reply that doesn't include a register's
7137 value implies either that the register is not available, or that
7138 the 'p' packet must be used. */
7139 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 7140 {
74ca34ce
DJ
7141 rsa->sizeof_g_packet = buf_len / 2;
7142
4a22f64d 7143 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 7144 {
74ca34ce
DJ
7145 if (rsa->regs[i].pnum == -1)
7146 continue;
7147
7148 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
7149 rsa->regs[i].in_g_packet = 0;
b96ec7ac 7150 else
74ca34ce 7151 rsa->regs[i].in_g_packet = 1;
b96ec7ac 7152 }
74ca34ce 7153 }
b323314b 7154
224c3ddb 7155 regs = (char *) alloca (rsa->sizeof_g_packet);
c906108c
SS
7156
7157 /* Unimplemented registers read as all bits zero. */
ea9c271d 7158 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 7159
c906108c
SS
7160 /* Reply describes registers byte by byte, each byte encoded as two
7161 hex characters. Suck them all up, then supply them to the
7162 register cacheing/storage mechanism. */
7163
74ca34ce 7164 p = rs->buf;
ea9c271d 7165 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 7166 {
74ca34ce
DJ
7167 if (p[0] == 0 || p[1] == 0)
7168 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
7169 internal_error (__FILE__, __LINE__,
9b20d036 7170 _("unexpected end of 'g' packet reply"));
74ca34ce 7171
c906108c 7172 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 7173 regs[i] = 0; /* 'x' */
c906108c
SS
7174 else
7175 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7176 p += 2;
7177 }
7178
a744cf53
MS
7179 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7180 {
7181 struct packet_reg *r = &rsa->regs[i];
7182
7183 if (r->in_g_packet)
7184 {
7185 if (r->offset * 2 >= strlen (rs->buf))
7186 /* This shouldn't happen - we adjusted in_g_packet above. */
7187 internal_error (__FILE__, __LINE__,
9b20d036 7188 _("unexpected end of 'g' packet reply"));
a744cf53
MS
7189 else if (rs->buf[r->offset * 2] == 'x')
7190 {
7191 gdb_assert (r->offset * 2 < strlen (rs->buf));
7192 /* The register isn't available, mark it as such (at
7193 the same time setting the value to zero). */
7194 regcache_raw_supply (regcache, r->regnum, NULL);
7195 }
7196 else
7197 regcache_raw_supply (regcache, r->regnum,
7198 regs + r->offset);
7199 }
7200 }
c906108c
SS
7201}
7202
29709017 7203static void
56be3814 7204fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
7205{
7206 send_g_packet ();
56be3814 7207 process_g_packet (regcache);
29709017
DJ
7208}
7209
e6e4e701
PA
7210/* Make the remote selected traceframe match GDB's selected
7211 traceframe. */
7212
7213static void
7214set_remote_traceframe (void)
7215{
7216 int newnum;
262e1174 7217 struct remote_state *rs = get_remote_state ();
e6e4e701 7218
262e1174 7219 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
7220 return;
7221
7222 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 7223 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
7224
7225 newnum = target_trace_find (tfind_number,
7226 get_traceframe_number (), 0, 0, NULL);
7227
7228 /* Should not happen. If it does, all bets are off. */
7229 if (newnum != get_traceframe_number ())
7230 warning (_("could not set remote traceframe"));
7231}
7232
74ca34ce 7233static void
28439f5e
PA
7234remote_fetch_registers (struct target_ops *ops,
7235 struct regcache *regcache, int regnum)
74ca34ce 7236{
74ca34ce
DJ
7237 struct remote_arch_state *rsa = get_remote_arch_state ();
7238 int i;
7239
e6e4e701 7240 set_remote_traceframe ();
79d7f229 7241 set_general_thread (inferior_ptid);
74ca34ce
DJ
7242
7243 if (regnum >= 0)
7244 {
7245 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7246
74ca34ce
DJ
7247 gdb_assert (reg != NULL);
7248
7249 /* If this register might be in the 'g' packet, try that first -
7250 we are likely to read more than one register. If this is the
7251 first 'g' packet, we might be overly optimistic about its
7252 contents, so fall back to 'p'. */
7253 if (reg->in_g_packet)
7254 {
56be3814 7255 fetch_registers_using_g (regcache);
74ca34ce
DJ
7256 if (reg->in_g_packet)
7257 return;
7258 }
7259
56be3814 7260 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
7261 return;
7262
7263 /* This register is not available. */
56be3814 7264 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
7265
7266 return;
7267 }
7268
56be3814 7269 fetch_registers_using_g (regcache);
74ca34ce 7270
4a22f64d 7271 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7272 if (!rsa->regs[i].in_g_packet)
56be3814 7273 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
7274 {
7275 /* This register is not available. */
56be3814 7276 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
7277 }
7278}
7279
c906108c
SS
7280/* Prepare to store registers. Since we may send them all (using a
7281 'G' request), we have to read out the ones we don't want to change
7282 first. */
7283
c5aa993b 7284static void
f32dbf8c 7285remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 7286{
ea9c271d 7287 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 7288 int i;
cfd77fa1 7289 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 7290
c906108c 7291 /* Make sure the entire registers array is valid. */
4082afcc 7292 switch (packet_support (PACKET_P))
5a2468f5
JM
7293 {
7294 case PACKET_DISABLE:
7295 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 7296 /* Make sure all the necessary registers are cached. */
4a22f64d 7297 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 7298 if (rsa->regs[i].in_g_packet)
316f2060 7299 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
7300 break;
7301 case PACKET_ENABLE:
7302 break;
7303 }
7304}
7305
ad10f812 7306/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 7307 packet was not recognized. */
5a2468f5
JM
7308
7309static int
1f4437a4
MS
7310store_register_using_P (const struct regcache *regcache,
7311 struct packet_reg *reg)
5a2468f5 7312{
4a22f64d 7313 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 7314 struct remote_state *rs = get_remote_state ();
5a2468f5 7315 /* Try storing a single register. */
6d820c5c 7316 char *buf = rs->buf;
cfd77fa1 7317 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 7318 char *p;
5a2468f5 7319
4082afcc 7320 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
7321 return 0;
7322
7323 if (reg->pnum == -1)
7324 return 0;
7325
ea9c271d 7326 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 7327 p = buf + strlen (buf);
56be3814 7328 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 7329 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
7330 putpkt (rs->buf);
7331 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 7332
74ca34ce
DJ
7333 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7334 {
7335 case PACKET_OK:
7336 return 1;
7337 case PACKET_ERROR:
27a9c0bf
MS
7338 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7339 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
7340 case PACKET_UNKNOWN:
7341 return 0;
7342 default:
7343 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7344 }
c906108c
SS
7345}
7346
23860348
MS
7347/* Store register REGNUM, or all registers if REGNUM == -1, from the
7348 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
7349
7350static void
56be3814 7351store_registers_using_G (const struct regcache *regcache)
c906108c 7352{
d01949b6 7353 struct remote_state *rs = get_remote_state ();
ea9c271d 7354 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 7355 gdb_byte *regs;
c906108c
SS
7356 char *p;
7357
193cb69f
AC
7358 /* Extract all the registers in the regcache copying them into a
7359 local buffer. */
7360 {
b323314b 7361 int i;
a744cf53 7362
224c3ddb 7363 regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
ea9c271d 7364 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 7365 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 7366 {
ea9c271d 7367 struct packet_reg *r = &rsa->regs[i];
a744cf53 7368
b323314b 7369 if (r->in_g_packet)
56be3814 7370 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
7371 }
7372 }
c906108c
SS
7373
7374 /* Command describes registers byte by byte,
7375 each byte encoded as two hex characters. */
6d820c5c 7376 p = rs->buf;
193cb69f 7377 *p++ = 'G';
74ca34ce
DJ
7378 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
7379 updated. */
7380 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
7381 putpkt (rs->buf);
7382 getpkt (&rs->buf, &rs->buf_size, 0);
7383 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
7384 error (_("Could not write registers; remote failure reply '%s'"),
7385 rs->buf);
c906108c 7386}
74ca34ce
DJ
7387
7388/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7389 of the register cache buffer. FIXME: ignores errors. */
7390
7391static void
28439f5e
PA
7392remote_store_registers (struct target_ops *ops,
7393 struct regcache *regcache, int regnum)
74ca34ce 7394{
74ca34ce
DJ
7395 struct remote_arch_state *rsa = get_remote_arch_state ();
7396 int i;
7397
e6e4e701 7398 set_remote_traceframe ();
79d7f229 7399 set_general_thread (inferior_ptid);
74ca34ce
DJ
7400
7401 if (regnum >= 0)
7402 {
7403 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 7404
74ca34ce
DJ
7405 gdb_assert (reg != NULL);
7406
7407 /* Always prefer to store registers using the 'P' packet if
7408 possible; we often change only a small number of registers.
7409 Sometimes we change a larger number; we'd need help from a
7410 higher layer to know to use 'G'. */
56be3814 7411 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
7412 return;
7413
7414 /* For now, don't complain if we have no way to write the
7415 register. GDB loses track of unavailable registers too
7416 easily. Some day, this may be an error. We don't have
0df8b418 7417 any way to read the register, either... */
74ca34ce
DJ
7418 if (!reg->in_g_packet)
7419 return;
7420
56be3814 7421 store_registers_using_G (regcache);
74ca34ce
DJ
7422 return;
7423 }
7424
56be3814 7425 store_registers_using_G (regcache);
74ca34ce 7426
4a22f64d 7427 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 7428 if (!rsa->regs[i].in_g_packet)
56be3814 7429 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
7430 /* See above for why we do not issue an error here. */
7431 continue;
7432}
c906108c
SS
7433\f
7434
7435/* Return the number of hex digits in num. */
7436
7437static int
fba45db2 7438hexnumlen (ULONGEST num)
c906108c
SS
7439{
7440 int i;
7441
7442 for (i = 0; num != 0; i++)
7443 num >>= 4;
7444
7445 return max (i, 1);
7446}
7447
2df3850c 7448/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7449
7450static int
fba45db2 7451hexnumstr (char *buf, ULONGEST num)
c906108c 7452{
c906108c 7453 int len = hexnumlen (num);
a744cf53 7454
2df3850c
JM
7455 return hexnumnstr (buf, num, len);
7456}
7457
c906108c 7458
2df3850c 7459/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7460
2df3850c 7461static int
fba45db2 7462hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7463{
7464 int i;
7465
7466 buf[width] = '\0';
7467
7468 for (i = width - 1; i >= 0; i--)
c906108c 7469 {
c5aa993b 7470 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7471 num >>= 4;
7472 }
7473
2df3850c 7474 return width;
c906108c
SS
7475}
7476
23860348 7477/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7478
7479static CORE_ADDR
fba45db2 7480remote_address_masked (CORE_ADDR addr)
c906108c 7481{
883b9c6c 7482 unsigned int address_size = remote_address_size;
a744cf53 7483
911c95a5
UW
7484 /* If "remoteaddresssize" was not set, default to target address size. */
7485 if (!address_size)
f5656ead 7486 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7487
7488 if (address_size > 0
7489 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7490 {
7491 /* Only create a mask when that mask can safely be constructed
23860348 7492 in a ULONGEST variable. */
c906108c 7493 ULONGEST mask = 1;
a744cf53 7494
911c95a5 7495 mask = (mask << address_size) - 1;
c906108c
SS
7496 addr &= mask;
7497 }
7498 return addr;
7499}
7500
7501/* Determine whether the remote target supports binary downloading.
7502 This is accomplished by sending a no-op memory write of zero length
7503 to the target at the specified address. It does not suffice to send
23860348
MS
7504 the whole packet, since many stubs strip the eighth bit and
7505 subsequently compute a wrong checksum, which causes real havoc with
7506 remote_write_bytes.
7a292a7a 7507
96baa820 7508 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7509 clean. In cases like this, the user should clear "remote
23860348 7510 X-packet". */
96baa820 7511
c906108c 7512static void
fba45db2 7513check_binary_download (CORE_ADDR addr)
c906108c 7514{
d01949b6 7515 struct remote_state *rs = get_remote_state ();
24b06219 7516
4082afcc 7517 switch (packet_support (PACKET_X))
c906108c 7518 {
96baa820
JM
7519 case PACKET_DISABLE:
7520 break;
7521 case PACKET_ENABLE:
7522 break;
7523 case PACKET_SUPPORT_UNKNOWN:
7524 {
96baa820 7525 char *p;
802188a7 7526
2e9f7625 7527 p = rs->buf;
96baa820
JM
7528 *p++ = 'X';
7529 p += hexnumstr (p, (ULONGEST) addr);
7530 *p++ = ',';
7531 p += hexnumstr (p, (ULONGEST) 0);
7532 *p++ = ':';
7533 *p = '\0';
802188a7 7534
2e9f7625 7535 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7536 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7537
2e9f7625 7538 if (rs->buf[0] == '\0')
96baa820
JM
7539 {
7540 if (remote_debug)
7541 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7542 "binary downloading NOT "
7543 "supported by target\n");
444abaca 7544 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7545 }
7546 else
7547 {
7548 if (remote_debug)
7549 fprintf_unfiltered (gdb_stdlog,
64b9b334 7550 "binary downloading supported by target\n");
444abaca 7551 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7552 }
7553 break;
7554 }
c906108c
SS
7555 }
7556}
7557
124e13d9
SM
7558/* Helper function to resize the payload in order to try to get a good
7559 alignment. We try to write an amount of data such that the next write will
7560 start on an address aligned on REMOTE_ALIGN_WRITES. */
7561
7562static int
7563align_for_efficient_write (int todo, CORE_ADDR memaddr)
7564{
7565 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7566}
7567
c906108c
SS
7568/* Write memory data directly to the remote machine.
7569 This does not inform the data cache; the data cache uses this.
a76d924d 7570 HEADER is the starting part of the packet.
c906108c
SS
7571 MEMADDR is the address in the remote memory space.
7572 MYADDR is the address of the buffer in our space.
124e13d9
SM
7573 LEN_UNITS is the number of addressable units to write.
7574 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7575 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7576 should send data as binary ('X'), or hex-encoded ('M').
7577
7578 The function creates packet of the form
7579 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7580
124e13d9 7581 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7582
7583 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7584 are omitted.
7585
9b409511 7586 Return the transferred status, error or OK (an
124e13d9
SM
7587 'enum target_xfer_status' value). Save the number of addressable units
7588 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7589
7590 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7591 exchange between gdb and the stub could look like (?? in place of the
7592 checksum):
7593
7594 -> $m1000,4#??
7595 <- aaaabbbbccccdddd
7596
7597 -> $M1000,3:eeeeffffeeee#??
7598 <- OK
7599
7600 -> $m1000,4#??
7601 <- eeeeffffeeeedddd */
c906108c 7602
9b409511 7603static enum target_xfer_status
a76d924d 7604remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7605 const gdb_byte *myaddr, ULONGEST len_units,
7606 int unit_size, ULONGEST *xfered_len_units,
7607 char packet_format, int use_length)
c906108c 7608{
6d820c5c 7609 struct remote_state *rs = get_remote_state ();
cfd77fa1 7610 char *p;
a76d924d
DJ
7611 char *plen = NULL;
7612 int plenlen = 0;
124e13d9
SM
7613 int todo_units;
7614 int units_written;
7615 int payload_capacity_bytes;
7616 int payload_length_bytes;
a76d924d
DJ
7617
7618 if (packet_format != 'X' && packet_format != 'M')
7619 internal_error (__FILE__, __LINE__,
9b20d036 7620 _("remote_write_bytes_aux: bad packet format"));
c906108c 7621
124e13d9 7622 if (len_units == 0)
9b409511 7623 return TARGET_XFER_EOF;
b2182ed2 7624
124e13d9 7625 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7626
6d820c5c
DJ
7627 /* The packet buffer will be large enough for the payload;
7628 get_memory_packet_size ensures this. */
a76d924d 7629 rs->buf[0] = '\0';
c906108c 7630
a257b5bb 7631 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7632 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7633
124e13d9 7634 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7635 if (!use_length)
0df8b418 7636 /* The comma won't be used. */
124e13d9
SM
7637 payload_capacity_bytes += 1;
7638 payload_capacity_bytes -= strlen (header);
7639 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7640
a76d924d 7641 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7642
a76d924d
DJ
7643 strcat (rs->buf, header);
7644 p = rs->buf + strlen (header);
7645
7646 /* Compute a best guess of the number of bytes actually transfered. */
7647 if (packet_format == 'X')
c906108c 7648 {
23860348 7649 /* Best guess at number of bytes that will fit. */
124e13d9 7650 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7651 if (use_length)
124e13d9
SM
7652 payload_capacity_bytes -= hexnumlen (todo_units);
7653 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7654 }
7655 else
7656 {
124e13d9
SM
7657 /* Number of bytes that will fit. */
7658 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7659 if (use_length)
124e13d9
SM
7660 payload_capacity_bytes -= hexnumlen (todo_units);
7661 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7662 }
a76d924d 7663
124e13d9 7664 if (todo_units <= 0)
3de11b2e 7665 internal_error (__FILE__, __LINE__,
405f8e94 7666 _("minimum packet size too small to write data"));
802188a7 7667
6765f3e5
DJ
7668 /* If we already need another packet, then try to align the end
7669 of this packet to a useful boundary. */
124e13d9
SM
7670 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7671 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7672
a257b5bb 7673 /* Append "<memaddr>". */
917317f4
JM
7674 memaddr = remote_address_masked (memaddr);
7675 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7676
a76d924d
DJ
7677 if (use_length)
7678 {
7679 /* Append ",". */
7680 *p++ = ',';
802188a7 7681
124e13d9
SM
7682 /* Append the length and retain its location and size. It may need to be
7683 adjusted once the packet body has been created. */
a76d924d 7684 plen = p;
124e13d9 7685 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7686 p += plenlen;
7687 }
a257b5bb
AC
7688
7689 /* Append ":". */
917317f4
JM
7690 *p++ = ':';
7691 *p = '\0';
802188a7 7692
a257b5bb 7693 /* Append the packet body. */
a76d924d 7694 if (packet_format == 'X')
917317f4 7695 {
917317f4
JM
7696 /* Binary mode. Send target system values byte by byte, in
7697 increasing byte addresses. Only escape certain critical
7698 characters. */
124e13d9
SM
7699 payload_length_bytes =
7700 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7701 &units_written, payload_capacity_bytes);
6765f3e5 7702
124e13d9 7703 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7704 a second try to keep the end of the packet aligned. Don't do
7705 this if the packet is tiny. */
124e13d9 7706 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7707 {
124e13d9
SM
7708 int new_todo_units;
7709
7710 new_todo_units = align_for_efficient_write (units_written, memaddr);
7711
7712 if (new_todo_units != units_written)
7713 payload_length_bytes =
7714 remote_escape_output (myaddr, new_todo_units, unit_size,
7715 (gdb_byte *) p, &units_written,
7716 payload_capacity_bytes);
6765f3e5
DJ
7717 }
7718
124e13d9
SM
7719 p += payload_length_bytes;
7720 if (use_length && units_written < todo_units)
c906108c 7721 {
802188a7 7722 /* Escape chars have filled up the buffer prematurely,
124e13d9 7723 and we have actually sent fewer units than planned.
917317f4
JM
7724 Fix-up the length field of the packet. Use the same
7725 number of characters as before. */
124e13d9
SM
7726 plen += hexnumnstr (plen, (ULONGEST) units_written,
7727 plenlen);
917317f4 7728 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7729 }
a76d924d
DJ
7730 }
7731 else
7732 {
917317f4
JM
7733 /* Normal mode: Send target system values byte by byte, in
7734 increasing byte addresses. Each byte is encoded as a two hex
7735 value. */
124e13d9
SM
7736 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7737 units_written = todo_units;
c906108c 7738 }
802188a7 7739
2e9f7625 7740 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7741 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7742
2e9f7625 7743 if (rs->buf[0] == 'E')
00d84524 7744 return TARGET_XFER_E_IO;
802188a7 7745
124e13d9
SM
7746 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7747 send fewer units than we'd planned. */
7748 *xfered_len_units = (ULONGEST) units_written;
9b409511 7749 return TARGET_XFER_OK;
c906108c
SS
7750}
7751
a76d924d
DJ
7752/* Write memory data directly to the remote machine.
7753 This does not inform the data cache; the data cache uses this.
7754 MEMADDR is the address in the remote memory space.
7755 MYADDR is the address of the buffer in our space.
7756 LEN is the number of bytes.
7757
9b409511
YQ
7758 Return the transferred status, error or OK (an
7759 'enum target_xfer_status' value). Save the number of bytes
7760 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7761
9b409511
YQ
7762static enum target_xfer_status
7763remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7764 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7765{
7766 char *packet_format = 0;
7767
7768 /* Check whether the target supports binary download. */
7769 check_binary_download (memaddr);
7770
4082afcc 7771 switch (packet_support (PACKET_X))
a76d924d
DJ
7772 {
7773 case PACKET_ENABLE:
7774 packet_format = "X";
7775 break;
7776 case PACKET_DISABLE:
7777 packet_format = "M";
7778 break;
7779 case PACKET_SUPPORT_UNKNOWN:
7780 internal_error (__FILE__, __LINE__,
7781 _("remote_write_bytes: bad internal state"));
7782 default:
7783 internal_error (__FILE__, __LINE__, _("bad switch"));
7784 }
7785
7786 return remote_write_bytes_aux (packet_format,
124e13d9 7787 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7788 packet_format[0], 1);
a76d924d
DJ
7789}
7790
9217e74e
YQ
7791/* Read memory data directly from the remote machine.
7792 This does not use the data cache; the data cache uses this.
7793 MEMADDR is the address in the remote memory space.
7794 MYADDR is the address of the buffer in our space.
124e13d9
SM
7795 LEN_UNITS is the number of addressable memory units to read..
7796 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7797
7798 Return the transferred status, error or OK (an
7799 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7800 transferred in *XFERED_LEN_UNITS.
7801
7802 See the comment of remote_write_bytes_aux for an example of
7803 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7804
7805static enum target_xfer_status
124e13d9
SM
7806remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7807 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7808{
7809 struct remote_state *rs = get_remote_state ();
124e13d9 7810 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7811 char *p;
124e13d9
SM
7812 int todo_units;
7813 int decoded_bytes;
9217e74e 7814
124e13d9 7815 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7816 /* The packet buffer will be large enough for the payload;
7817 get_memory_packet_size ensures this. */
7818
124e13d9
SM
7819 /* Number of units that will fit. */
7820 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7821
7822 /* Construct "m"<memaddr>","<len>". */
7823 memaddr = remote_address_masked (memaddr);
7824 p = rs->buf;
7825 *p++ = 'm';
7826 p += hexnumstr (p, (ULONGEST) memaddr);
7827 *p++ = ',';
124e13d9 7828 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7829 *p = '\0';
7830 putpkt (rs->buf);
7831 getpkt (&rs->buf, &rs->buf_size, 0);
7832 if (rs->buf[0] == 'E'
7833 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7834 && rs->buf[3] == '\0')
7835 return TARGET_XFER_E_IO;
7836 /* Reply describes memory byte by byte, each byte encoded as two hex
7837 characters. */
7838 p = rs->buf;
124e13d9 7839 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7840 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7841 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7842 return TARGET_XFER_OK;
7843}
7844
b55fbac4
YQ
7845/* Using the set of read-only target sections of remote, read live
7846 read-only memory.
8acf9577
YQ
7847
7848 For interface/parameters/return description see target.h,
7849 to_xfer_partial. */
7850
7851static enum target_xfer_status
b55fbac4
YQ
7852remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7853 ULONGEST memaddr, ULONGEST len,
124e13d9 7854 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7855{
7856 struct target_section *secp;
7857 struct target_section_table *table;
7858
7859 secp = target_section_by_addr (ops, memaddr);
7860 if (secp != NULL
7861 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7862 secp->the_bfd_section)
7863 & SEC_READONLY))
7864 {
7865 struct target_section *p;
7866 ULONGEST memend = memaddr + len;
7867
7868 table = target_get_section_table (ops);
7869
7870 for (p = table->sections; p < table->sections_end; p++)
7871 {
7872 if (memaddr >= p->addr)
7873 {
7874 if (memend <= p->endaddr)
7875 {
7876 /* Entire transfer is within this section. */
124e13d9 7877 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7878 xfered_len);
8acf9577
YQ
7879 }
7880 else if (memaddr >= p->endaddr)
7881 {
7882 /* This section ends before the transfer starts. */
7883 continue;
7884 }
7885 else
7886 {
7887 /* This section overlaps the transfer. Just do half. */
7888 len = p->endaddr - memaddr;
124e13d9 7889 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7890 xfered_len);
8acf9577
YQ
7891 }
7892 }
7893 }
7894 }
7895
7896 return TARGET_XFER_EOF;
7897}
7898
9217e74e
YQ
7899/* Similar to remote_read_bytes_1, but it reads from the remote stub
7900 first if the requested memory is unavailable in traceframe.
7901 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7902
9b409511 7903static enum target_xfer_status
8acf9577 7904remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7905 gdb_byte *myaddr, ULONGEST len, int unit_size,
7906 ULONGEST *xfered_len)
c906108c 7907{
6b6aa828 7908 if (len == 0)
96c4f946 7909 return TARGET_XFER_EOF;
b2182ed2 7910
8acf9577
YQ
7911 if (get_traceframe_number () != -1)
7912 {
7913 VEC(mem_range_s) *available;
7914
7915 /* If we fail to get the set of available memory, then the
7916 target does not support querying traceframe info, and so we
7917 attempt reading from the traceframe anyway (assuming the
7918 target implements the old QTro packet then). */
7919 if (traceframe_available_memory (&available, memaddr, len))
7920 {
7921 struct cleanup *old_chain;
7922
7923 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7924
7925 if (VEC_empty (mem_range_s, available)
7926 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7927 {
7928 enum target_xfer_status res;
7929
7930 /* Don't read into the traceframe's available
7931 memory. */
7932 if (!VEC_empty (mem_range_s, available))
7933 {
7934 LONGEST oldlen = len;
7935
7936 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7937 gdb_assert (len <= oldlen);
7938 }
7939
7940 do_cleanups (old_chain);
7941
7942 /* This goes through the topmost target again. */
b55fbac4 7943 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7944 len, unit_size, xfered_len);
8acf9577
YQ
7945 if (res == TARGET_XFER_OK)
7946 return TARGET_XFER_OK;
7947 else
7948 {
7949 /* No use trying further, we know some memory starting
7950 at MEMADDR isn't available. */
7951 *xfered_len = len;
7952 return TARGET_XFER_UNAVAILABLE;
7953 }
7954 }
7955
7956 /* Don't try to read more than how much is available, in
7957 case the target implements the deprecated QTro packet to
7958 cater for older GDBs (the target's knowledge of read-only
7959 sections may be outdated by now). */
7960 len = VEC_index (mem_range_s, available, 0)->length;
7961
7962 do_cleanups (old_chain);
7963 }
7964 }
7965
124e13d9 7966 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7967}
74531fed 7968
c906108c 7969\f
c906108c 7970
a76d924d
DJ
7971/* Sends a packet with content determined by the printf format string
7972 FORMAT and the remaining arguments, then gets the reply. Returns
7973 whether the packet was a success, a failure, or unknown. */
7974
77b64a49
PA
7975static enum packet_result remote_send_printf (const char *format, ...)
7976 ATTRIBUTE_PRINTF (1, 2);
7977
2c0b251b 7978static enum packet_result
a76d924d
DJ
7979remote_send_printf (const char *format, ...)
7980{
7981 struct remote_state *rs = get_remote_state ();
7982 int max_size = get_remote_packet_size ();
a76d924d 7983 va_list ap;
a744cf53 7984
a76d924d
DJ
7985 va_start (ap, format);
7986
7987 rs->buf[0] = '\0';
7988 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7989 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7990
7991 if (putpkt (rs->buf) < 0)
7992 error (_("Communication problem with target."));
7993
7994 rs->buf[0] = '\0';
7995 getpkt (&rs->buf, &rs->buf_size, 0);
7996
7997 return packet_check_result (rs->buf);
7998}
7999
8000static void
8001restore_remote_timeout (void *p)
8002{
8003 int value = *(int *)p;
a744cf53 8004
a76d924d
DJ
8005 remote_timeout = value;
8006}
8007
8008/* Flash writing can take quite some time. We'll set
8009 effectively infinite timeout for flash operations.
8010 In future, we'll need to decide on a better approach. */
8011static const int remote_flash_timeout = 1000;
8012
8013static void
8014remote_flash_erase (struct target_ops *ops,
8015 ULONGEST address, LONGEST length)
8016{
f5656ead 8017 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
8018 int saved_remote_timeout = remote_timeout;
8019 enum packet_result ret;
a76d924d
DJ
8020 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8021 &saved_remote_timeout);
a744cf53 8022
a76d924d
DJ
8023 remote_timeout = remote_flash_timeout;
8024
8025 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 8026 phex (address, addr_size),
a76d924d
DJ
8027 phex (length, 4));
8028 switch (ret)
8029 {
8030 case PACKET_UNKNOWN:
8031 error (_("Remote target does not support flash erase"));
8032 case PACKET_ERROR:
8033 error (_("Error erasing flash with vFlashErase packet"));
8034 default:
8035 break;
8036 }
8037
8038 do_cleanups (back_to);
8039}
8040
9b409511
YQ
8041static enum target_xfer_status
8042remote_flash_write (struct target_ops *ops, ULONGEST address,
8043 ULONGEST length, ULONGEST *xfered_len,
8044 const gdb_byte *data)
a76d924d
DJ
8045{
8046 int saved_remote_timeout = remote_timeout;
9b409511 8047 enum target_xfer_status ret;
a76d924d 8048 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 8049 &saved_remote_timeout);
a76d924d
DJ
8050
8051 remote_timeout = remote_flash_timeout;
124e13d9 8052 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 8053 xfered_len,'X', 0);
a76d924d
DJ
8054 do_cleanups (back_to);
8055
8056 return ret;
8057}
8058
8059static void
8060remote_flash_done (struct target_ops *ops)
8061{
8062 int saved_remote_timeout = remote_timeout;
8063 int ret;
8064 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
8065 &saved_remote_timeout);
8066
8067 remote_timeout = remote_flash_timeout;
8068 ret = remote_send_printf ("vFlashDone");
8069 do_cleanups (back_to);
8070
8071 switch (ret)
8072 {
8073 case PACKET_UNKNOWN:
8074 error (_("Remote target does not support vFlashDone"));
8075 case PACKET_ERROR:
8076 error (_("Error finishing flash operation"));
8077 default:
8078 break;
8079 }
8080}
8081
c906108c 8082static void
fba45db2 8083remote_files_info (struct target_ops *ignore)
c906108c
SS
8084{
8085 puts_filtered ("Debugging a target over a serial line.\n");
8086}
8087\f
8088/* Stuff for dealing with the packets which are part of this protocol.
8089 See comment at top of file for details. */
8090
1927e618
PA
8091/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8092 error to higher layers. Called when a serial error is detected.
8093 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
8094 the system error message for errno at function entry and final dot
8095 for output compatibility with throw_perror_with_name. */
1927e618
PA
8096
8097static void
8098unpush_and_perror (const char *string)
8099{
d6cb50a2 8100 int saved_errno = errno;
1927e618
PA
8101
8102 remote_unpush_target ();
d6cb50a2
JK
8103 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8104 safe_strerror (saved_errno));
1927e618
PA
8105}
8106
048094ac
PA
8107/* Read a single character from the remote end. The current quit
8108 handler is overridden to avoid quitting in the middle of packet
8109 sequence, as that would break communication with the remote server.
8110 See remote_serial_quit_handler for more detail. */
c906108c
SS
8111
8112static int
fba45db2 8113readchar (int timeout)
c906108c
SS
8114{
8115 int ch;
5d93a237 8116 struct remote_state *rs = get_remote_state ();
048094ac
PA
8117 struct cleanup *old_chain;
8118
8119 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8120
8121 rs->got_ctrlc_during_io = 0;
c906108c 8122
5d93a237 8123 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 8124
048094ac
PA
8125 if (rs->got_ctrlc_during_io)
8126 set_quit_flag ();
8127
8128 do_cleanups (old_chain);
8129
2acceee2 8130 if (ch >= 0)
0876f84a 8131 return ch;
2acceee2
JM
8132
8133 switch ((enum serial_rc) ch)
c906108c
SS
8134 {
8135 case SERIAL_EOF:
78a095c3 8136 remote_unpush_target ();
598d3636 8137 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 8138 /* no return */
c906108c 8139 case SERIAL_ERROR:
1927e618
PA
8140 unpush_and_perror (_("Remote communication error. "
8141 "Target disconnected."));
2acceee2 8142 /* no return */
c906108c 8143 case SERIAL_TIMEOUT:
2acceee2 8144 break;
c906108c 8145 }
2acceee2 8146 return ch;
c906108c
SS
8147}
8148
c33e31fd 8149/* Wrapper for serial_write that closes the target and throws if
048094ac
PA
8150 writing fails. The current quit handler is overridden to avoid
8151 quitting in the middle of packet sequence, as that would break
8152 communication with the remote server. See
8153 remote_serial_quit_handler for more detail. */
c33e31fd
PA
8154
8155static void
8156remote_serial_write (const char *str, int len)
8157{
5d93a237 8158 struct remote_state *rs = get_remote_state ();
048094ac
PA
8159 struct cleanup *old_chain;
8160
8161 old_chain = make_cleanup_override_quit_handler (remote_serial_quit_handler);
8162
8163 rs->got_ctrlc_during_io = 0;
5d93a237
TT
8164
8165 if (serial_write (rs->remote_desc, str, len))
c33e31fd 8166 {
1927e618
PA
8167 unpush_and_perror (_("Remote communication error. "
8168 "Target disconnected."));
c33e31fd 8169 }
048094ac
PA
8170
8171 if (rs->got_ctrlc_during_io)
8172 set_quit_flag ();
8173
8174 do_cleanups (old_chain);
c33e31fd
PA
8175}
8176
6d820c5c
DJ
8177/* Send the command in *BUF to the remote machine, and read the reply
8178 into *BUF. Report an error if we get an error reply. Resize
8179 *BUF using xrealloc if necessary to hold the result, and update
8180 *SIZEOF_BUF. */
c906108c
SS
8181
8182static void
6d820c5c
DJ
8183remote_send (char **buf,
8184 long *sizeof_buf)
c906108c 8185{
6d820c5c 8186 putpkt (*buf);
c2d11a7d 8187 getpkt (buf, sizeof_buf, 0);
c906108c 8188
6d820c5c
DJ
8189 if ((*buf)[0] == 'E')
8190 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
8191}
8192
6e5abd65
PA
8193/* Return a pointer to an xmalloc'ed string representing an escaped
8194 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
8195 etc. The caller is responsible for releasing the returned
8196 memory. */
8197
8198static char *
8199escape_buffer (const char *buf, int n)
8200{
8201 struct cleanup *old_chain;
8202 struct ui_file *stb;
8203 char *str;
6e5abd65
PA
8204
8205 stb = mem_fileopen ();
8206 old_chain = make_cleanup_ui_file_delete (stb);
8207
6ef284bd 8208 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 8209 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
8210 do_cleanups (old_chain);
8211 return str;
8212}
8213
c906108c
SS
8214/* Display a null-terminated packet on stdout, for debugging, using C
8215 string notation. */
8216
8217static void
baa336ce 8218print_packet (const char *buf)
c906108c
SS
8219{
8220 puts_filtered ("\"");
43e526b9 8221 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
8222 puts_filtered ("\"");
8223}
8224
8225int
baa336ce 8226putpkt (const char *buf)
c906108c
SS
8227{
8228 return putpkt_binary (buf, strlen (buf));
8229}
8230
8231/* Send a packet to the remote machine, with error checking. The data
23860348 8232 of the packet is in BUF. The string in BUF can be at most
ea9c271d 8233 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
8234 and for a possible /0 if we are debugging (remote_debug) and want
8235 to print the sent packet as a string. */
c906108c
SS
8236
8237static int
baa336ce 8238putpkt_binary (const char *buf, int cnt)
c906108c 8239{
2d717e4f 8240 struct remote_state *rs = get_remote_state ();
c906108c
SS
8241 int i;
8242 unsigned char csum = 0;
224c3ddb 8243 char *buf2 = (char *) xmalloc (cnt + 6);
a5c0808e 8244 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 8245
c906108c
SS
8246 int ch;
8247 int tcount = 0;
8248 char *p;
8249
e24a49d8
PA
8250 /* Catch cases like trying to read memory or listing threads while
8251 we're waiting for a stop reply. The remote server wouldn't be
8252 ready to handle this request, so we'd hang and timeout. We don't
8253 have to worry about this in synchronous mode, because in that
8254 case it's not possible to issue a command while the target is
74531fed
PA
8255 running. This is not a problem in non-stop mode, because in that
8256 case, the stub is always ready to process serial input. */
6efcd9a8
PA
8257 if (!target_is_non_stop_p ()
8258 && target_is_async_p ()
8259 && rs->waiting_for_stop_reply)
9597b22a
DE
8260 {
8261 error (_("Cannot execute this command while the target is running.\n"
8262 "Use the \"interrupt\" command to stop the target\n"
8263 "and then try again."));
8264 }
e24a49d8 8265
2d717e4f
DJ
8266 /* We're sending out a new packet. Make sure we don't look at a
8267 stale cached response. */
8268 rs->cached_wait_status = 0;
8269
c906108c
SS
8270 /* Copy the packet into buffer BUF2, encapsulating it
8271 and giving it a checksum. */
8272
c906108c
SS
8273 p = buf2;
8274 *p++ = '$';
8275
8276 for (i = 0; i < cnt; i++)
8277 {
8278 csum += buf[i];
8279 *p++ = buf[i];
8280 }
8281 *p++ = '#';
8282 *p++ = tohex ((csum >> 4) & 0xf);
8283 *p++ = tohex (csum & 0xf);
8284
8285 /* Send it over and over until we get a positive ack. */
8286
8287 while (1)
8288 {
8289 int started_error_output = 0;
8290
8291 if (remote_debug)
8292 {
6e5abd65
PA
8293 struct cleanup *old_chain;
8294 char *str;
8295
c906108c 8296 *p = '\0';
6e5abd65
PA
8297 str = escape_buffer (buf2, p - buf2);
8298 old_chain = make_cleanup (xfree, str);
8299 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 8300 gdb_flush (gdb_stdlog);
6e5abd65 8301 do_cleanups (old_chain);
c906108c 8302 }
c33e31fd 8303 remote_serial_write (buf2, p - buf2);
c906108c 8304
a6f3e723
SL
8305 /* If this is a no acks version of the remote protocol, send the
8306 packet and move on. */
8307 if (rs->noack_mode)
8308 break;
8309
74531fed
PA
8310 /* Read until either a timeout occurs (-2) or '+' is read.
8311 Handle any notification that arrives in the mean time. */
c906108c
SS
8312 while (1)
8313 {
8314 ch = readchar (remote_timeout);
8315
c5aa993b 8316 if (remote_debug)
c906108c
SS
8317 {
8318 switch (ch)
8319 {
8320 case '+':
1216fa2c 8321 case '-':
c906108c
SS
8322 case SERIAL_TIMEOUT:
8323 case '$':
74531fed 8324 case '%':
c906108c
SS
8325 if (started_error_output)
8326 {
8327 putchar_unfiltered ('\n');
8328 started_error_output = 0;
8329 }
8330 }
8331 }
8332
8333 switch (ch)
8334 {
8335 case '+':
8336 if (remote_debug)
0f71a2f6 8337 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 8338 do_cleanups (old_chain);
c906108c 8339 return 1;
1216fa2c
AC
8340 case '-':
8341 if (remote_debug)
8342 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 8343 /* FALLTHROUGH */
c906108c 8344 case SERIAL_TIMEOUT:
c5aa993b 8345 tcount++;
c906108c 8346 if (tcount > 3)
a5c0808e
PA
8347 {
8348 do_cleanups (old_chain);
8349 return 0;
8350 }
23860348 8351 break; /* Retransmit buffer. */
c906108c
SS
8352 case '$':
8353 {
40e3f985 8354 if (remote_debug)
2bc416ba 8355 fprintf_unfiltered (gdb_stdlog,
23860348 8356 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
8357 /* It's probably an old response sent because an ACK
8358 was lost. Gobble up the packet and ack it so it
8359 doesn't get retransmitted when we resend this
8360 packet. */
6d820c5c 8361 skip_frame ();
c33e31fd 8362 remote_serial_write ("+", 1);
23860348 8363 continue; /* Now, go look for +. */
c906108c 8364 }
74531fed
PA
8365
8366 case '%':
8367 {
8368 int val;
8369
8370 /* If we got a notification, handle it, and go back to looking
8371 for an ack. */
8372 /* We've found the start of a notification. Now
8373 collect the data. */
8374 val = read_frame (&rs->buf, &rs->buf_size);
8375 if (val >= 0)
8376 {
8377 if (remote_debug)
8378 {
6e5abd65
PA
8379 struct cleanup *old_chain;
8380 char *str;
8381
8382 str = escape_buffer (rs->buf, val);
8383 old_chain = make_cleanup (xfree, str);
8384 fprintf_unfiltered (gdb_stdlog,
8385 " Notification received: %s\n",
8386 str);
8387 do_cleanups (old_chain);
74531fed 8388 }
5965e028 8389 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
8390 /* We're in sync now, rewait for the ack. */
8391 tcount = 0;
8392 }
8393 else
8394 {
8395 if (remote_debug)
8396 {
8397 if (!started_error_output)
8398 {
8399 started_error_output = 1;
8400 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8401 }
8402 fputc_unfiltered (ch & 0177, gdb_stdlog);
8403 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8404 }
8405 }
8406 continue;
8407 }
8408 /* fall-through */
c906108c
SS
8409 default:
8410 if (remote_debug)
8411 {
8412 if (!started_error_output)
8413 {
8414 started_error_output = 1;
0f71a2f6 8415 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 8416 }
0f71a2f6 8417 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
8418 }
8419 continue;
8420 }
23860348 8421 break; /* Here to retransmit. */
c906108c
SS
8422 }
8423
8424#if 0
8425 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
8426 able to get out next time we call QUIT, without anything as
8427 violent as interrupt_query. If we want to provide a way out of
8428 here without getting to the next QUIT, it should be based on
8429 hitting ^C twice as in remote_wait. */
c906108c
SS
8430 if (quit_flag)
8431 {
8432 quit_flag = 0;
8433 interrupt_query ();
8434 }
8435#endif
8436 }
a5c0808e
PA
8437
8438 do_cleanups (old_chain);
a6f3e723 8439 return 0;
c906108c
SS
8440}
8441
6d820c5c
DJ
8442/* Come here after finding the start of a frame when we expected an
8443 ack. Do our best to discard the rest of this packet. */
8444
8445static void
8446skip_frame (void)
8447{
8448 int c;
8449
8450 while (1)
8451 {
8452 c = readchar (remote_timeout);
8453 switch (c)
8454 {
8455 case SERIAL_TIMEOUT:
8456 /* Nothing we can do. */
8457 return;
8458 case '#':
8459 /* Discard the two bytes of checksum and stop. */
8460 c = readchar (remote_timeout);
8461 if (c >= 0)
8462 c = readchar (remote_timeout);
8463
8464 return;
8465 case '*': /* Run length encoding. */
8466 /* Discard the repeat count. */
8467 c = readchar (remote_timeout);
8468 if (c < 0)
8469 return;
8470 break;
8471 default:
8472 /* A regular character. */
8473 break;
8474 }
8475 }
8476}
8477
c906108c 8478/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8479 into *BUF, verifying the checksum, length, and handling run-length
8480 compression. NUL terminate the buffer. If there is not enough room,
8481 expand *BUF using xrealloc.
c906108c 8482
c2d11a7d
JM
8483 Returns -1 on error, number of characters in buffer (ignoring the
8484 trailing NULL) on success. (could be extended to return one of the
23860348 8485 SERIAL status indications). */
c2d11a7d
JM
8486
8487static long
6d820c5c
DJ
8488read_frame (char **buf_p,
8489 long *sizeof_buf)
c906108c
SS
8490{
8491 unsigned char csum;
c2d11a7d 8492 long bc;
c906108c 8493 int c;
6d820c5c 8494 char *buf = *buf_p;
a6f3e723 8495 struct remote_state *rs = get_remote_state ();
c906108c
SS
8496
8497 csum = 0;
c2d11a7d 8498 bc = 0;
c906108c
SS
8499
8500 while (1)
8501 {
8502 c = readchar (remote_timeout);
c906108c
SS
8503 switch (c)
8504 {
8505 case SERIAL_TIMEOUT:
8506 if (remote_debug)
0f71a2f6 8507 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8508 return -1;
c906108c
SS
8509 case '$':
8510 if (remote_debug)
0f71a2f6
JM
8511 fputs_filtered ("Saw new packet start in middle of old one\n",
8512 gdb_stdlog);
23860348 8513 return -1; /* Start a new packet, count retries. */
c906108c
SS
8514 case '#':
8515 {
8516 unsigned char pktcsum;
e1b09194
AC
8517 int check_0 = 0;
8518 int check_1 = 0;
c906108c 8519
c2d11a7d 8520 buf[bc] = '\0';
c906108c 8521
e1b09194
AC
8522 check_0 = readchar (remote_timeout);
8523 if (check_0 >= 0)
8524 check_1 = readchar (remote_timeout);
802188a7 8525
e1b09194
AC
8526 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8527 {
8528 if (remote_debug)
2bc416ba 8529 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8530 gdb_stdlog);
e1b09194
AC
8531 return -1;
8532 }
8533 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8534 {
8535 if (remote_debug)
2bc416ba 8536 fputs_filtered ("Communication error in checksum\n",
23860348 8537 gdb_stdlog);
40e3f985
FN
8538 return -1;
8539 }
c906108c 8540
a6f3e723
SL
8541 /* Don't recompute the checksum; with no ack packets we
8542 don't have any way to indicate a packet retransmission
8543 is necessary. */
8544 if (rs->noack_mode)
8545 return bc;
8546
e1b09194 8547 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8548 if (csum == pktcsum)
c2d11a7d 8549 return bc;
c906108c 8550
c5aa993b 8551 if (remote_debug)
c906108c 8552 {
6e5abd65
PA
8553 struct cleanup *old_chain;
8554 char *str;
8555
8556 str = escape_buffer (buf, bc);
8557 old_chain = make_cleanup (xfree, str);
8558 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8559 "Bad checksum, sentsum=0x%x, "
8560 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8561 pktcsum, csum, str);
8562 do_cleanups (old_chain);
c906108c 8563 }
c2d11a7d 8564 /* Number of characters in buffer ignoring trailing
23860348 8565 NULL. */
c2d11a7d 8566 return -1;
c906108c 8567 }
23860348 8568 case '*': /* Run length encoding. */
c2c6d25f
JM
8569 {
8570 int repeat;
c906108c 8571
a744cf53 8572 csum += c;
b4501125
AC
8573 c = readchar (remote_timeout);
8574 csum += c;
23860348 8575 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8576
23860348 8577 /* The character before ``*'' is repeated. */
c2d11a7d 8578
6d820c5c 8579 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8580 {
6d820c5c
DJ
8581 if (bc + repeat - 1 >= *sizeof_buf - 1)
8582 {
8583 /* Make some more room in the buffer. */
8584 *sizeof_buf += repeat;
224c3ddb 8585 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c
DJ
8586 buf = *buf_p;
8587 }
8588
c2d11a7d
JM
8589 memset (&buf[bc], buf[bc - 1], repeat);
8590 bc += repeat;
c2c6d25f
JM
8591 continue;
8592 }
8593
c2d11a7d 8594 buf[bc] = '\0';
6d820c5c 8595 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8596 return -1;
c2c6d25f 8597 }
c906108c 8598 default:
6d820c5c 8599 if (bc >= *sizeof_buf - 1)
c906108c 8600 {
6d820c5c
DJ
8601 /* Make some more room in the buffer. */
8602 *sizeof_buf *= 2;
224c3ddb 8603 *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
6d820c5c 8604 buf = *buf_p;
c906108c
SS
8605 }
8606
6d820c5c
DJ
8607 buf[bc++] = c;
8608 csum += c;
8609 continue;
c906108c
SS
8610 }
8611 }
8612}
8613
8614/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8615 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8616 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8617 rather than timing out; this is used (in synchronous mode) to wait
8618 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8619/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8620 don't have to change all the calls to getpkt to deal with the
8621 return value, because at the moment I don't know what the right
23860348 8622 thing to do it for those. */
c906108c 8623void
6d820c5c
DJ
8624getpkt (char **buf,
8625 long *sizeof_buf,
c2d11a7d 8626 int forever)
d9fcf2fb 8627{
54887903 8628 getpkt_sane (buf, sizeof_buf, forever);
d9fcf2fb
JM
8629}
8630
8631
8632/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8633 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8634 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8635 rather than timing out; this is used (in synchronous mode) to wait
8636 for a target that is is executing user code to stop. If FOREVER ==
8637 0, this function is allowed to time out gracefully and return an
74531fed
PA
8638 indication of this to the caller. Otherwise return the number of
8639 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8640 enough reason to return to the caller. *IS_NOTIF is an output
8641 boolean that indicates whether *BUF holds a notification or not
8642 (a regular packet). */
74531fed 8643
3172dc30 8644static int
74531fed 8645getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8646 int expecting_notif, int *is_notif)
c906108c 8647{
2d717e4f 8648 struct remote_state *rs = get_remote_state ();
c906108c
SS
8649 int c;
8650 int tries;
8651 int timeout;
df4b58fe 8652 int val = -1;
c906108c 8653
2d717e4f
DJ
8654 /* We're reading a new response. Make sure we don't look at a
8655 previously cached response. */
8656 rs->cached_wait_status = 0;
8657
6d820c5c 8658 strcpy (*buf, "timeout");
c906108c
SS
8659
8660 if (forever)
74531fed
PA
8661 timeout = watchdog > 0 ? watchdog : -1;
8662 else if (expecting_notif)
8663 timeout = 0; /* There should already be a char in the buffer. If
8664 not, bail out. */
c906108c
SS
8665 else
8666 timeout = remote_timeout;
8667
8668#define MAX_TRIES 3
8669
74531fed
PA
8670 /* Process any number of notifications, and then return when
8671 we get a packet. */
8672 for (;;)
c906108c 8673 {
d9c43928 8674 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8675 times. */
8676 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8677 {
74531fed
PA
8678 /* This can loop forever if the remote side sends us
8679 characters continuously, but if it pauses, we'll get
8680 SERIAL_TIMEOUT from readchar because of timeout. Then
8681 we'll count that as a retry.
8682
8683 Note that even when forever is set, we will only wait
8684 forever prior to the start of a packet. After that, we
8685 expect characters to arrive at a brisk pace. They should
8686 show up within remote_timeout intervals. */
8687 do
8688 c = readchar (timeout);
8689 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8690
8691 if (c == SERIAL_TIMEOUT)
8692 {
74531fed
PA
8693 if (expecting_notif)
8694 return -1; /* Don't complain, it's normal to not get
8695 anything in this case. */
8696
23860348 8697 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8698 {
78a095c3 8699 remote_unpush_target ();
598d3636
JK
8700 throw_error (TARGET_CLOSE_ERROR,
8701 _("Watchdog timeout has expired. "
8702 "Target detached."));
c906108c 8703 }
c906108c 8704 if (remote_debug)
0f71a2f6 8705 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8706 }
74531fed
PA
8707 else
8708 {
8709 /* We've found the start of a packet or notification.
8710 Now collect the data. */
8711 val = read_frame (buf, sizeof_buf);
8712 if (val >= 0)
8713 break;
8714 }
8715
c33e31fd 8716 remote_serial_write ("-", 1);
c906108c 8717 }
c906108c 8718
74531fed
PA
8719 if (tries > MAX_TRIES)
8720 {
8721 /* We have tried hard enough, and just can't receive the
8722 packet/notification. Give up. */
8723 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8724
74531fed
PA
8725 /* Skip the ack char if we're in no-ack mode. */
8726 if (!rs->noack_mode)
c33e31fd 8727 remote_serial_write ("+", 1);
74531fed
PA
8728 return -1;
8729 }
c906108c 8730
74531fed
PA
8731 /* If we got an ordinary packet, return that to our caller. */
8732 if (c == '$')
c906108c
SS
8733 {
8734 if (remote_debug)
43e526b9 8735 {
6e5abd65
PA
8736 struct cleanup *old_chain;
8737 char *str;
8738
8739 str = escape_buffer (*buf, val);
8740 old_chain = make_cleanup (xfree, str);
8741 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8742 do_cleanups (old_chain);
43e526b9 8743 }
a6f3e723
SL
8744
8745 /* Skip the ack char if we're in no-ack mode. */
8746 if (!rs->noack_mode)
c33e31fd 8747 remote_serial_write ("+", 1);
fee9eda9
YQ
8748 if (is_notif != NULL)
8749 *is_notif = 0;
0876f84a 8750 return val;
c906108c
SS
8751 }
8752
74531fed
PA
8753 /* If we got a notification, handle it, and go back to looking
8754 for a packet. */
8755 else
8756 {
8757 gdb_assert (c == '%');
8758
8759 if (remote_debug)
8760 {
6e5abd65
PA
8761 struct cleanup *old_chain;
8762 char *str;
8763
8764 str = escape_buffer (*buf, val);
8765 old_chain = make_cleanup (xfree, str);
8766 fprintf_unfiltered (gdb_stdlog,
8767 " Notification received: %s\n",
8768 str);
8769 do_cleanups (old_chain);
74531fed 8770 }
fee9eda9
YQ
8771 if (is_notif != NULL)
8772 *is_notif = 1;
c906108c 8773
5965e028 8774 handle_notification (rs->notif_state, *buf);
c906108c 8775
74531fed 8776 /* Notifications require no acknowledgement. */
a6f3e723 8777
74531fed 8778 if (expecting_notif)
fee9eda9 8779 return val;
74531fed
PA
8780 }
8781 }
8782}
8783
8784static int
8785getpkt_sane (char **buf, long *sizeof_buf, int forever)
8786{
fee9eda9 8787 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8788}
8789
8790static int
fee9eda9
YQ
8791getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8792 int *is_notif)
74531fed 8793{
fee9eda9
YQ
8794 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8795 is_notif);
c906108c 8796}
74531fed 8797
cbb8991c
DB
8798/* Check whether EVENT is a fork event for the process specified
8799 by the pid passed in DATA, and if it is, kill the fork child. */
8800
8801static int
8802kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8803 QUEUE_ITER (stop_reply_p) *iter,
8804 stop_reply_p event,
8805 void *data)
8806{
19ba03f4 8807 struct queue_iter_param *param = (struct queue_iter_param *) data;
cbb8991c
DB
8808 int parent_pid = *(int *) param->input;
8809
8810 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8811 {
8812 struct remote_state *rs = get_remote_state ();
8813 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8814 int res;
8815
8816 res = remote_vkill (child_pid, rs);
8817 if (res != 0)
8818 error (_("Can't kill fork child process %d"), child_pid);
8819 }
8820
8821 return 1;
8822}
8823
8824/* Kill any new fork children of process PID that haven't been
8825 processed by follow_fork. */
8826
8827static void
8828kill_new_fork_children (int pid, struct remote_state *rs)
8829{
8830 struct thread_info *thread;
8831 struct notif_client *notif = &notif_client_stop;
8832 struct queue_iter_param param;
8833
8834 /* Kill the fork child threads of any threads in process PID
8835 that are stopped at a fork event. */
8836 ALL_NON_EXITED_THREADS (thread)
8837 {
8838 struct target_waitstatus *ws = &thread->pending_follow;
8839
8840 if (is_pending_fork_parent (ws, pid, thread->ptid))
8841 {
8842 struct remote_state *rs = get_remote_state ();
8843 int child_pid = ptid_get_pid (ws->value.related_pid);
8844 int res;
8845
8846 res = remote_vkill (child_pid, rs);
8847 if (res != 0)
8848 error (_("Can't kill fork child process %d"), child_pid);
8849 }
8850 }
8851
8852 /* Check for any pending fork events (not reported or processed yet)
8853 in process PID and kill those fork child threads as well. */
8854 remote_notif_get_pending_events (notif);
8855 param.input = &pid;
8856 param.output = NULL;
8857 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8858 kill_child_of_pending_fork, &param);
8859}
8860
c906108c 8861\f
8020350c
DB
8862/* Target hook to kill the current inferior. */
8863
c906108c 8864static void
7d85a9c0 8865remote_kill (struct target_ops *ops)
43ff13b4 8866{
8020350c
DB
8867 int res = -1;
8868 int pid = ptid_get_pid (inferior_ptid);
8869 struct remote_state *rs = get_remote_state ();
0fdf84ca 8870
8020350c 8871 if (packet_support (PACKET_vKill) != PACKET_DISABLE)
0fdf84ca 8872 {
8020350c
DB
8873 /* If we're stopped while forking and we haven't followed yet,
8874 kill the child task. We need to do this before killing the
8875 parent task because if this is a vfork then the parent will
8876 be sleeping. */
8877 kill_new_fork_children (pid, rs);
8878
8879 res = remote_vkill (pid, rs);
8880 if (res == 0)
0fdf84ca 8881 {
8020350c 8882 target_mourn_inferior ();
0fdf84ca
PA
8883 return;
8884 }
8020350c 8885 }
0fdf84ca 8886
8020350c
DB
8887 /* If we are in 'target remote' mode and we are killing the only
8888 inferior, then we will tell gdbserver to exit and unpush the
8889 target. */
8890 if (res == -1 && !remote_multi_process_p (rs)
8891 && number_of_live_inferiors () == 1)
8892 {
8893 remote_kill_k ();
8894
8895 /* We've killed the remote end, we get to mourn it. If we are
8896 not in extended mode, mourning the inferior also unpushes
8897 remote_ops from the target stack, which closes the remote
8898 connection. */
8899 target_mourn_inferior ();
8900
8901 return;
0fdf84ca 8902 }
43ff13b4 8903
8020350c 8904 error (_("Can't kill process"));
43ff13b4
JM
8905}
8906
8020350c
DB
8907/* Send a kill request to the target using the 'vKill' packet. */
8908
82f73884
PA
8909static int
8910remote_vkill (int pid, struct remote_state *rs)
8911{
4082afcc 8912 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8913 return -1;
8914
8915 /* Tell the remote target to detach. */
bba74b36 8916 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8917 putpkt (rs->buf);
8918 getpkt (&rs->buf, &rs->buf_size, 0);
8919
4082afcc
PA
8920 switch (packet_ok (rs->buf,
8921 &remote_protocol_packets[PACKET_vKill]))
8922 {
8923 case PACKET_OK:
8924 return 0;
8925 case PACKET_ERROR:
8926 return 1;
8927 case PACKET_UNKNOWN:
8928 return -1;
8929 default:
8930 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8931 }
82f73884
PA
8932}
8933
8020350c
DB
8934/* Send a kill request to the target using the 'k' packet. */
8935
82f73884 8936static void
8020350c 8937remote_kill_k (void)
82f73884 8938{
8020350c
DB
8939 /* Catch errors so the user can quit from gdb even when we
8940 aren't on speaking terms with the remote system. */
8941 TRY
82f73884 8942 {
82f73884 8943 putpkt ("k");
82f73884 8944 }
8020350c
DB
8945 CATCH (ex, RETURN_MASK_ERROR)
8946 {
8947 if (ex.error == TARGET_CLOSE_ERROR)
8948 {
8949 /* If we got an (EOF) error that caused the target
8950 to go away, then we're done, that's what we wanted.
8951 "k" is susceptible to cause a premature EOF, given
8952 that the remote server isn't actually required to
8953 reply to "k", and it can happen that it doesn't
8954 even get to reply ACK to the "k". */
8955 return;
8956 }
82f73884 8957
8020350c
DB
8958 /* Otherwise, something went wrong. We didn't actually kill
8959 the target. Just propagate the exception, and let the
8960 user or higher layers decide what to do. */
8961 throw_exception (ex);
8962 }
8963 END_CATCH
82f73884
PA
8964}
8965
c906108c 8966static void
20f796c9 8967remote_mourn (struct target_ops *target)
c906108c 8968{
8020350c 8969 struct remote_state *rs = get_remote_state ();
ce5ce7ed 8970
8020350c
DB
8971 /* In 'target remote' mode with one inferior, we close the connection. */
8972 if (!rs->extended && number_of_live_inferiors () <= 1)
8973 {
8974 unpush_target (target);
c906108c 8975
8020350c
DB
8976 /* remote_close takes care of doing most of the clean up. */
8977 generic_mourn_inferior ();
8978 return;
8979 }
c906108c 8980
e24a49d8
PA
8981 /* In case we got here due to an error, but we're going to stay
8982 connected. */
8983 rs->waiting_for_stop_reply = 0;
8984
dc1981d7
PA
8985 /* If the current general thread belonged to the process we just
8986 detached from or has exited, the remote side current general
8987 thread becomes undefined. Considering a case like this:
8988
8989 - We just got here due to a detach.
8990 - The process that we're detaching from happens to immediately
8991 report a global breakpoint being hit in non-stop mode, in the
8992 same thread we had selected before.
8993 - GDB attaches to this process again.
8994 - This event happens to be the next event we handle.
8995
8996 GDB would consider that the current general thread didn't need to
8997 be set on the stub side (with Hg), since for all it knew,
8998 GENERAL_THREAD hadn't changed.
8999
9000 Notice that although in all-stop mode, the remote server always
9001 sets the current thread to the thread reporting the stop event,
9002 that doesn't happen in non-stop mode; in non-stop, the stub *must
9003 not* change the current thread when reporting a breakpoint hit,
9004 due to the decoupling of event reporting and event handling.
9005
9006 To keep things simple, we always invalidate our notion of the
9007 current thread. */
47f8a51d 9008 record_currthread (rs, minus_one_ptid);
dc1981d7 9009
8020350c 9010 /* Call common code to mark the inferior as not running. */
48aa3c27
PA
9011 generic_mourn_inferior ();
9012
d729566a 9013 if (!have_inferiors ())
2d717e4f 9014 {
82f73884
PA
9015 if (!remote_multi_process_p (rs))
9016 {
9017 /* Check whether the target is running now - some remote stubs
9018 automatically restart after kill. */
9019 putpkt ("?");
9020 getpkt (&rs->buf, &rs->buf_size, 0);
9021
9022 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9023 {
3e43a32a
MS
9024 /* Assume that the target has been restarted. Set
9025 inferior_ptid so that bits of core GDB realizes
9026 there's something here, e.g., so that the user can
9027 say "kill" again. */
82f73884
PA
9028 inferior_ptid = magic_null_ptid;
9029 }
82f73884 9030 }
2d717e4f
DJ
9031 }
9032}
c906108c 9033
03583c20 9034static int
2bfc0540 9035extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 9036{
4082afcc 9037 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
9038}
9039
9040static void
9041extended_remote_disable_randomization (int val)
9042{
9043 struct remote_state *rs = get_remote_state ();
9044 char *reply;
9045
bba74b36
YQ
9046 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9047 val);
03583c20
UW
9048 putpkt (rs->buf);
9049 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
9050 if (*reply == '\0')
9051 error (_("Target does not support QDisableRandomization."));
9052 if (strcmp (reply, "OK") != 0)
9053 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9054}
9055
2d717e4f
DJ
9056static int
9057extended_remote_run (char *args)
9058{
9059 struct remote_state *rs = get_remote_state ();
2d717e4f 9060 int len;
94585166 9061 const char *remote_exec_file = get_remote_exec_file ();
c906108c 9062
2d717e4f
DJ
9063 /* If the user has disabled vRun support, or we have detected that
9064 support is not available, do not try it. */
4082afcc 9065 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 9066 return -1;
424163ea 9067
2d717e4f
DJ
9068 strcpy (rs->buf, "vRun;");
9069 len = strlen (rs->buf);
c906108c 9070
2d717e4f
DJ
9071 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9072 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
9073 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9074 strlen (remote_exec_file));
2d717e4f 9075
d1a41061 9076 gdb_assert (args != NULL);
2d717e4f
DJ
9077 if (*args)
9078 {
9079 struct cleanup *back_to;
9080 int i;
9081 char **argv;
9082
d1a41061 9083 argv = gdb_buildargv (args);
6e366df1 9084 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
9085 for (i = 0; argv[i] != NULL; i++)
9086 {
9087 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9088 error (_("Argument list too long for run packet"));
9089 rs->buf[len++] = ';';
9f1b45b0
TT
9090 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9091 strlen (argv[i]));
2d717e4f
DJ
9092 }
9093 do_cleanups (back_to);
9094 }
9095
9096 rs->buf[len++] = '\0';
9097
9098 putpkt (rs->buf);
9099 getpkt (&rs->buf, &rs->buf_size, 0);
9100
4082afcc 9101 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 9102 {
4082afcc 9103 case PACKET_OK:
3405876a 9104 /* We have a wait response. All is well. */
2d717e4f 9105 return 0;
4082afcc
PA
9106 case PACKET_UNKNOWN:
9107 return -1;
9108 case PACKET_ERROR:
2d717e4f
DJ
9109 if (remote_exec_file[0] == '\0')
9110 error (_("Running the default executable on the remote target failed; "
9111 "try \"set remote exec-file\"?"));
9112 else
9113 error (_("Running \"%s\" on the remote target failed"),
9114 remote_exec_file);
4082afcc
PA
9115 default:
9116 gdb_assert_not_reached (_("bad switch"));
2d717e4f 9117 }
c906108c
SS
9118}
9119
2d717e4f
DJ
9120/* In the extended protocol we want to be able to do things like
9121 "run" and have them basically work as expected. So we need
9122 a special create_inferior function. We support changing the
9123 executable file and the command line arguments, but not the
9124 environment. */
9125
43ff13b4 9126static void
77a19445
TT
9127extended_remote_create_inferior (struct target_ops *ops,
9128 char *exec_file, char *args,
9129 char **env, int from_tty)
43ff13b4 9130{
3405876a
PA
9131 int run_worked;
9132 char *stop_reply;
9133 struct remote_state *rs = get_remote_state ();
94585166 9134 const char *remote_exec_file = get_remote_exec_file ();
3405876a 9135
43ff13b4 9136 /* If running asynchronously, register the target file descriptor
23860348 9137 with the event loop. */
75c99385 9138 if (target_can_async_p ())
6a3753b3 9139 target_async (1);
43ff13b4 9140
03583c20 9141 /* Disable address space randomization if requested (and supported). */
2bfc0540 9142 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
9143 extended_remote_disable_randomization (disable_randomization);
9144
43ff13b4 9145 /* Now restart the remote server. */
3405876a
PA
9146 run_worked = extended_remote_run (args) != -1;
9147 if (!run_worked)
2d717e4f
DJ
9148 {
9149 /* vRun was not supported. Fail if we need it to do what the
9150 user requested. */
9151 if (remote_exec_file[0])
9152 error (_("Remote target does not support \"set remote exec-file\""));
9153 if (args[0])
9154 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 9155
2d717e4f
DJ
9156 /* Fall back to "R". */
9157 extended_remote_restart ();
9158 }
424163ea 9159
6c95b8df
PA
9160 if (!have_inferiors ())
9161 {
9162 /* Clean up from the last time we ran, before we mark the target
9163 running again. This will mark breakpoints uninserted, and
9164 get_offsets may insert breakpoints. */
9165 init_thread_list ();
9166 init_wait_for_inferior ();
9167 }
45280a52 9168
3405876a
PA
9169 /* vRun's success return is a stop reply. */
9170 stop_reply = run_worked ? rs->buf : NULL;
9171 add_current_inferior_and_thread (stop_reply);
c0a2216e 9172
2d717e4f
DJ
9173 /* Get updated offsets, if the stub uses qOffsets. */
9174 get_offsets ();
2d717e4f 9175}
c906108c 9176\f
c5aa993b 9177
b775012e
LM
9178/* Given a location's target info BP_TGT and the packet buffer BUF, output
9179 the list of conditions (in agent expression bytecode format), if any, the
9180 target needs to evaluate. The output is placed into the packet buffer
bba74b36 9181 started from BUF and ended at BUF_END. */
b775012e
LM
9182
9183static int
9184remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
9185 struct bp_target_info *bp_tgt, char *buf,
9186 char *buf_end)
b775012e
LM
9187{
9188 struct agent_expr *aexpr = NULL;
9189 int i, ix;
b775012e
LM
9190
9191 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
9192 return 0;
9193
9194 buf += strlen (buf);
bba74b36 9195 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
9196 buf++;
9197
9198 /* Send conditions to the target and free the vector. */
9199 for (ix = 0;
9200 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
9201 ix++)
9202 {
bba74b36 9203 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
9204 buf += strlen (buf);
9205 for (i = 0; i < aexpr->len; ++i)
9206 buf = pack_hex_byte (buf, aexpr->buf[i]);
9207 *buf = '\0';
9208 }
b775012e
LM
9209 return 0;
9210}
9211
d3ce09f5
SS
9212static void
9213remote_add_target_side_commands (struct gdbarch *gdbarch,
9214 struct bp_target_info *bp_tgt, char *buf)
9215{
9216 struct agent_expr *aexpr = NULL;
9217 int i, ix;
9218
9219 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
9220 return;
9221
9222 buf += strlen (buf);
9223
9224 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9225 buf += strlen (buf);
9226
9227 /* Concatenate all the agent expressions that are commands into the
9228 cmds parameter. */
9229 for (ix = 0;
9230 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
9231 ix++)
9232 {
9233 sprintf (buf, "X%x,", aexpr->len);
9234 buf += strlen (buf);
9235 for (i = 0; i < aexpr->len; ++i)
9236 buf = pack_hex_byte (buf, aexpr->buf[i]);
9237 *buf = '\0';
9238 }
d3ce09f5
SS
9239}
9240
8181d85f
DJ
9241/* Insert a breakpoint. On targets that have software breakpoint
9242 support, we ask the remote target to do the work; on targets
9243 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
9244
9245static int
3db08215
MM
9246remote_insert_breakpoint (struct target_ops *ops,
9247 struct gdbarch *gdbarch,
a6d9a66e 9248 struct bp_target_info *bp_tgt)
c906108c 9249{
d471ea57
AC
9250 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9251 If it succeeds, then set the support to PACKET_ENABLE. If it
9252 fails, and the user has explicitly requested the Z support then
23860348 9253 report an error, otherwise, mark it disabled and go on. */
802188a7 9254
4082afcc 9255 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9256 {
0d5ed153 9257 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9258 struct remote_state *rs;
bba74b36 9259 char *p, *endbuf;
7c0f6dcc 9260 int bpsize;
4fff2411 9261
28439a30
PA
9262 /* Make sure the remote is pointing at the right process, if
9263 necessary. */
9264 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9265 set_general_process ();
9266
a1dcb23a 9267 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
9268
9269 rs = get_remote_state ();
9270 p = rs->buf;
bba74b36 9271 endbuf = rs->buf + get_remote_packet_size ();
802188a7 9272
96baa820
JM
9273 *(p++) = 'Z';
9274 *(p++) = '0';
9275 *(p++) = ',';
7c0f6dcc 9276 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 9277 p += hexnumstr (p, addr);
bba74b36 9278 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 9279
efcc2da7 9280 if (remote_supports_cond_breakpoints (ops))
bba74b36 9281 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9282
78eff0ec 9283 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
9284 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9285
6d820c5c
DJ
9286 putpkt (rs->buf);
9287 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9288
6d820c5c 9289 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 9290 {
d471ea57
AC
9291 case PACKET_ERROR:
9292 return -1;
9293 case PACKET_OK:
7c0f6dcc
JL
9294 bp_tgt->placed_address = addr;
9295 bp_tgt->placed_size = bpsize;
d471ea57
AC
9296 return 0;
9297 case PACKET_UNKNOWN:
9298 break;
96baa820
JM
9299 }
9300 }
c906108c 9301
0000e5cc
PA
9302 /* If this breakpoint has target-side commands but this stub doesn't
9303 support Z0 packets, throw error. */
9304 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
9305 throw_error (NOT_SUPPORTED_ERROR, _("\
9306Target doesn't support breakpoints that have target side commands."));
9307
3db08215 9308 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9309}
9310
9311static int
3db08215
MM
9312remote_remove_breakpoint (struct target_ops *ops,
9313 struct gdbarch *gdbarch,
a6d9a66e 9314 struct bp_target_info *bp_tgt)
c906108c 9315{
8181d85f 9316 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 9317 struct remote_state *rs = get_remote_state ();
96baa820 9318
4082afcc 9319 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 9320 {
6d820c5c 9321 char *p = rs->buf;
bba74b36 9322 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 9323
28439a30
PA
9324 /* Make sure the remote is pointing at the right process, if
9325 necessary. */
9326 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9327 set_general_process ();
9328
96baa820
JM
9329 *(p++) = 'z';
9330 *(p++) = '0';
9331 *(p++) = ',';
9332
8181d85f
DJ
9333 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9334 p += hexnumstr (p, addr);
bba74b36 9335 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 9336
6d820c5c
DJ
9337 putpkt (rs->buf);
9338 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9339
6d820c5c 9340 return (rs->buf[0] == 'E');
96baa820
JM
9341 }
9342
3db08215 9343 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
9344}
9345
f486487f 9346static enum Z_packet_type
d471ea57
AC
9347watchpoint_to_Z_packet (int type)
9348{
9349 switch (type)
9350 {
9351 case hw_write:
bb858e6a 9352 return Z_PACKET_WRITE_WP;
d471ea57
AC
9353 break;
9354 case hw_read:
bb858e6a 9355 return Z_PACKET_READ_WP;
d471ea57
AC
9356 break;
9357 case hw_access:
bb858e6a 9358 return Z_PACKET_ACCESS_WP;
d471ea57
AC
9359 break;
9360 default:
8e65ff28 9361 internal_error (__FILE__, __LINE__,
e2e0b3e5 9362 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
9363 }
9364}
9365
3c3bea1c 9366static int
f486487f
SM
9367remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9368 enum target_hw_bp_type type, struct expression *cond)
96baa820 9369{
d01949b6 9370 struct remote_state *rs = get_remote_state ();
bba74b36 9371 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9372 char *p;
d471ea57 9373 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 9374
4082afcc 9375 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 9376 return 1;
802188a7 9377
28439a30
PA
9378 /* Make sure the remote is pointing at the right process, if
9379 necessary. */
9380 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9381 set_general_process ();
9382
bba74b36 9383 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 9384 p = strchr (rs->buf, '\0');
96baa820
JM
9385 addr = remote_address_masked (addr);
9386 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9387 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 9388
6d820c5c
DJ
9389 putpkt (rs->buf);
9390 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9391
6d820c5c 9392 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9393 {
9394 case PACKET_ERROR:
d471ea57 9395 return -1;
85d721b8
PA
9396 case PACKET_UNKNOWN:
9397 return 1;
d471ea57
AC
9398 case PACKET_OK:
9399 return 0;
9400 }
8e65ff28 9401 internal_error (__FILE__, __LINE__,
e2e0b3e5 9402 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
9403}
9404
283002cf
MR
9405static int
9406remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9407 CORE_ADDR start, int length)
9408{
9409 CORE_ADDR diff = remote_address_masked (addr - start);
9410
9411 return diff < length;
9412}
9413
d471ea57 9414
3c3bea1c 9415static int
f486487f
SM
9416remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9417 enum target_hw_bp_type type, struct expression *cond)
96baa820 9418{
d01949b6 9419 struct remote_state *rs = get_remote_state ();
bba74b36 9420 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 9421 char *p;
d471ea57
AC
9422 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9423
4082afcc 9424 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 9425 return -1;
802188a7 9426
28439a30
PA
9427 /* Make sure the remote is pointing at the right process, if
9428 necessary. */
9429 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9430 set_general_process ();
9431
bba74b36 9432 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 9433 p = strchr (rs->buf, '\0');
96baa820
JM
9434 addr = remote_address_masked (addr);
9435 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9436 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
9437 putpkt (rs->buf);
9438 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9439
6d820c5c 9440 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
9441 {
9442 case PACKET_ERROR:
9443 case PACKET_UNKNOWN:
9444 return -1;
9445 case PACKET_OK:
9446 return 0;
9447 }
8e65ff28 9448 internal_error (__FILE__, __LINE__,
e2e0b3e5 9449 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
9450}
9451
3c3bea1c 9452
501eef12 9453int remote_hw_watchpoint_limit = -1;
480a3f21 9454int remote_hw_watchpoint_length_limit = -1;
501eef12 9455int remote_hw_breakpoint_limit = -1;
d471ea57 9456
480a3f21 9457static int
31568a15
TT
9458remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9459 CORE_ADDR addr, int len)
480a3f21
PW
9460{
9461 if (remote_hw_watchpoint_length_limit == 0)
9462 return 0;
9463 else if (remote_hw_watchpoint_length_limit < 0)
9464 return 1;
9465 else if (len <= remote_hw_watchpoint_length_limit)
9466 return 1;
9467 else
9468 return 0;
9469}
9470
b9362cc7 9471static int
5461485a 9472remote_check_watch_resources (struct target_ops *self,
f486487f 9473 enum bptype type, int cnt, int ot)
96baa820 9474{
3c3bea1c
GS
9475 if (type == bp_hardware_breakpoint)
9476 {
9477 if (remote_hw_breakpoint_limit == 0)
9478 return 0;
501eef12
AC
9479 else if (remote_hw_breakpoint_limit < 0)
9480 return 1;
3c3bea1c
GS
9481 else if (cnt <= remote_hw_breakpoint_limit)
9482 return 1;
9483 }
9484 else
9485 {
9486 if (remote_hw_watchpoint_limit == 0)
9487 return 0;
501eef12
AC
9488 else if (remote_hw_watchpoint_limit < 0)
9489 return 1;
3c3bea1c
GS
9490 else if (ot)
9491 return -1;
9492 else if (cnt <= remote_hw_watchpoint_limit)
9493 return 1;
9494 }
9495 return -1;
9496}
9497
f7e6eed5
PA
9498/* The to_stopped_by_sw_breakpoint method of target remote. */
9499
9500static int
9501remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9502{
799a2abe 9503 struct thread_info *thread = inferior_thread ();
f7e6eed5 9504
799a2abe
PA
9505 return (thread->priv != NULL
9506 && thread->priv->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT);
f7e6eed5
PA
9507}
9508
9509/* The to_supports_stopped_by_sw_breakpoint method of target
9510 remote. */
9511
9512static int
9513remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9514{
f7e6eed5
PA
9515 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9516}
9517
9518/* The to_stopped_by_hw_breakpoint method of target remote. */
9519
9520static int
9521remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9522{
799a2abe 9523 struct thread_info *thread = inferior_thread ();
f7e6eed5 9524
799a2abe
PA
9525 return (thread->priv != NULL
9526 && thread->priv->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT);
f7e6eed5
PA
9527}
9528
9529/* The to_supports_stopped_by_hw_breakpoint method of target
9530 remote. */
9531
9532static int
9533remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9534{
f7e6eed5
PA
9535 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9536}
9537
b9362cc7 9538static int
6a109b6b 9539remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9540{
799a2abe 9541 struct thread_info *thread = inferior_thread ();
ee154bee 9542
799a2abe
PA
9543 return (thread->priv != NULL
9544 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT);
3c3bea1c
GS
9545}
9546
4aa7a7f5
JJ
9547static int
9548remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9549{
799a2abe 9550 struct thread_info *thread = inferior_thread ();
a744cf53 9551
799a2abe
PA
9552 if (thread->priv != NULL
9553 && thread->priv->stop_reason == TARGET_STOPPED_BY_WATCHPOINT)
4aa7a7f5 9554 {
799a2abe
PA
9555 *addr_p = thread->priv->watch_data_address;
9556 return 1;
4aa7a7f5
JJ
9557 }
9558
799a2abe 9559 return 0;
3c3bea1c
GS
9560}
9561
9562
9563static int
23a26771 9564remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9565 struct bp_target_info *bp_tgt)
3c3bea1c 9566{
0d5ed153 9567 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9568 struct remote_state *rs;
bba74b36 9569 char *p, *endbuf;
dd61ec5c 9570 char *message;
0d5ed153 9571 int bpsize;
802188a7 9572
c8189ed1 9573 /* The length field should be set to the size of a breakpoint
8181d85f 9574 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9575
0d5ed153 9576 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9577
4082afcc 9578 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9579 return -1;
2bc416ba 9580
28439a30
PA
9581 /* Make sure the remote is pointing at the right process, if
9582 necessary. */
9583 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9584 set_general_process ();
9585
4fff2411
JZ
9586 rs = get_remote_state ();
9587 p = rs->buf;
bba74b36 9588 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9589
96baa820
JM
9590 *(p++) = 'Z';
9591 *(p++) = '1';
9592 *(p++) = ',';
802188a7 9593
0d5ed153 9594 addr = remote_address_masked (addr);
96baa820 9595 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9596 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9597
efcc2da7 9598 if (remote_supports_cond_breakpoints (self))
bba74b36 9599 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9600
78eff0ec 9601 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9602 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9603
6d820c5c
DJ
9604 putpkt (rs->buf);
9605 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9606
6d820c5c 9607 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9608 {
9609 case PACKET_ERROR:
dd61ec5c
MW
9610 if (rs->buf[1] == '.')
9611 {
9612 message = strchr (rs->buf + 2, '.');
9613 if (message)
0316657e 9614 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9615 }
9616 return -1;
d471ea57
AC
9617 case PACKET_UNKNOWN:
9618 return -1;
9619 case PACKET_OK:
0d5ed153
MR
9620 bp_tgt->placed_address = addr;
9621 bp_tgt->placed_size = bpsize;
d471ea57
AC
9622 return 0;
9623 }
8e65ff28 9624 internal_error (__FILE__, __LINE__,
e2e0b3e5 9625 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9626}
9627
d471ea57 9628
802188a7 9629static int
a64dc96c 9630remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9631 struct bp_target_info *bp_tgt)
96baa820 9632{
8181d85f 9633 CORE_ADDR addr;
d01949b6 9634 struct remote_state *rs = get_remote_state ();
6d820c5c 9635 char *p = rs->buf;
bba74b36 9636 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9637
4082afcc 9638 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9639 return -1;
802188a7 9640
28439a30
PA
9641 /* Make sure the remote is pointing at the right process, if
9642 necessary. */
9643 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9644 set_general_process ();
9645
96baa820
JM
9646 *(p++) = 'z';
9647 *(p++) = '1';
9648 *(p++) = ',';
802188a7 9649
8181d85f 9650 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9651 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9652 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9653
6d820c5c
DJ
9654 putpkt (rs->buf);
9655 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9656
6d820c5c 9657 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9658 {
9659 case PACKET_ERROR:
9660 case PACKET_UNKNOWN:
9661 return -1;
9662 case PACKET_OK:
9663 return 0;
9664 }
8e65ff28 9665 internal_error (__FILE__, __LINE__,
e2e0b3e5 9666 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9667}
96baa820 9668
4a5e7a5b
PA
9669/* Verify memory using the "qCRC:" request. */
9670
9671static int
9672remote_verify_memory (struct target_ops *ops,
9673 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9674{
9675 struct remote_state *rs = get_remote_state ();
9676 unsigned long host_crc, target_crc;
9677 char *tmp;
9678
936d2992
PA
9679 /* It doesn't make sense to use qCRC if the remote target is
9680 connected but not running. */
9681 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9682 {
9683 enum packet_result result;
28439a30 9684
936d2992
PA
9685 /* Make sure the remote is pointing at the right process. */
9686 set_general_process ();
4a5e7a5b 9687
936d2992
PA
9688 /* FIXME: assumes lma can fit into long. */
9689 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9690 (long) lma, (long) size);
9691 putpkt (rs->buf);
4a5e7a5b 9692
936d2992
PA
9693 /* Be clever; compute the host_crc before waiting for target
9694 reply. */
9695 host_crc = xcrc32 (data, size, 0xffffffff);
9696
9697 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9698
936d2992
PA
9699 result = packet_ok (rs->buf,
9700 &remote_protocol_packets[PACKET_qCRC]);
9701 if (result == PACKET_ERROR)
9702 return -1;
9703 else if (result == PACKET_OK)
9704 {
9705 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9706 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9707
936d2992
PA
9708 return (host_crc == target_crc);
9709 }
9710 }
4a5e7a5b 9711
936d2992 9712 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9713}
9714
c906108c
SS
9715/* compare-sections command
9716
9717 With no arguments, compares each loadable section in the exec bfd
9718 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9719 Useful for verifying the image on the target against the exec file. */
e514a9d6 9720
c906108c 9721static void
fba45db2 9722compare_sections_command (char *args, int from_tty)
c906108c
SS
9723{
9724 asection *s;
c906108c 9725 struct cleanup *old_chain;
948f8e3d 9726 gdb_byte *sectdata;
ce359b09 9727 const char *sectname;
c906108c
SS
9728 bfd_size_type size;
9729 bfd_vma lma;
9730 int matched = 0;
9731 int mismatched = 0;
4a5e7a5b 9732 int res;
95cf3b38 9733 int read_only = 0;
c906108c
SS
9734
9735 if (!exec_bfd)
8a3fe4f8 9736 error (_("command cannot be used without an exec file"));
c906108c 9737
28439a30
PA
9738 /* Make sure the remote is pointing at the right process. */
9739 set_general_process ();
9740
95cf3b38
DT
9741 if (args != NULL && strcmp (args, "-r") == 0)
9742 {
9743 read_only = 1;
9744 args = NULL;
9745 }
9746
c5aa993b 9747 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9748 {
9749 if (!(s->flags & SEC_LOAD))
0df8b418 9750 continue; /* Skip non-loadable section. */
c906108c 9751
95cf3b38
DT
9752 if (read_only && (s->flags & SEC_READONLY) == 0)
9753 continue; /* Skip writeable sections */
9754
2c500098 9755 size = bfd_get_section_size (s);
c906108c 9756 if (size == 0)
0df8b418 9757 continue; /* Skip zero-length section. */
c906108c 9758
ce359b09 9759 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9760 if (args && strcmp (args, sectname) != 0)
0df8b418 9761 continue; /* Not the section selected by user. */
c906108c 9762
0df8b418 9763 matched = 1; /* Do this section. */
c906108c 9764 lma = s->lma;
c906108c 9765
224c3ddb 9766 sectdata = (gdb_byte *) xmalloc (size);
b8c9b27d 9767 old_chain = make_cleanup (xfree, sectdata);
c906108c 9768 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9769
4a5e7a5b
PA
9770 res = target_verify_memory (sectdata, lma, size);
9771
9772 if (res == -1)
5af949e3 9773 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9774 paddress (target_gdbarch (), lma),
9775 paddress (target_gdbarch (), lma + size));
c906108c 9776
5af949e3 9777 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9778 paddress (target_gdbarch (), lma),
9779 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9780 if (res)
c906108c
SS
9781 printf_filtered ("matched.\n");
9782 else
c5aa993b
JM
9783 {
9784 printf_filtered ("MIS-MATCHED!\n");
9785 mismatched++;
9786 }
c906108c
SS
9787
9788 do_cleanups (old_chain);
9789 }
9790 if (mismatched > 0)
936d2992 9791 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9792the loaded file\n"));
c906108c 9793 if (args && !matched)
a3f17187 9794 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9795}
9796
0e7f50da
UW
9797/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9798 into remote target. The number of bytes written to the remote
9799 target is returned, or -1 for error. */
9800
9b409511 9801static enum target_xfer_status
0e7f50da
UW
9802remote_write_qxfer (struct target_ops *ops, const char *object_name,
9803 const char *annex, const gdb_byte *writebuf,
9b409511 9804 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9805 struct packet_config *packet)
9806{
9807 int i, buf_len;
9808 ULONGEST n;
0e7f50da
UW
9809 struct remote_state *rs = get_remote_state ();
9810 int max_size = get_memory_write_packet_size ();
9811
9812 if (packet->support == PACKET_DISABLE)
2ed4b548 9813 return TARGET_XFER_E_IO;
0e7f50da
UW
9814
9815 /* Insert header. */
9816 i = snprintf (rs->buf, max_size,
9817 "qXfer:%s:write:%s:%s:",
9818 object_name, annex ? annex : "",
9819 phex_nz (offset, sizeof offset));
9820 max_size -= (i + 1);
9821
9822 /* Escape as much data as fits into rs->buf. */
9823 buf_len = remote_escape_output
124e13d9 9824 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9825
9826 if (putpkt_binary (rs->buf, i + buf_len) < 0
9827 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9828 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9829 return TARGET_XFER_E_IO;
0e7f50da
UW
9830
9831 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9832
9833 *xfered_len = n;
9834 return TARGET_XFER_OK;
0e7f50da
UW
9835}
9836
0876f84a
DJ
9837/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9838 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9839 number of bytes read is returned, or 0 for EOF, or -1 for error.
9840 The number of bytes read may be less than LEN without indicating an
9841 EOF. PACKET is checked and updated to indicate whether the remote
9842 target supports this object. */
9843
9b409511 9844static enum target_xfer_status
0876f84a
DJ
9845remote_read_qxfer (struct target_ops *ops, const char *object_name,
9846 const char *annex,
9847 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9848 ULONGEST *xfered_len,
0876f84a
DJ
9849 struct packet_config *packet)
9850{
0876f84a 9851 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9852 LONGEST i, n, packet_len;
9853
9854 if (packet->support == PACKET_DISABLE)
2ed4b548 9855 return TARGET_XFER_E_IO;
0876f84a
DJ
9856
9857 /* Check whether we've cached an end-of-object packet that matches
9858 this request. */
8e88304f 9859 if (rs->finished_object)
0876f84a 9860 {
8e88304f
TT
9861 if (strcmp (object_name, rs->finished_object) == 0
9862 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9863 && offset == rs->finished_offset)
9b409511
YQ
9864 return TARGET_XFER_EOF;
9865
0876f84a
DJ
9866
9867 /* Otherwise, we're now reading something different. Discard
9868 the cache. */
8e88304f
TT
9869 xfree (rs->finished_object);
9870 xfree (rs->finished_annex);
9871 rs->finished_object = NULL;
9872 rs->finished_annex = NULL;
0876f84a
DJ
9873 }
9874
9875 /* Request only enough to fit in a single packet. The actual data
9876 may not, since we don't know how much of it will need to be escaped;
9877 the target is free to respond with slightly less data. We subtract
9878 five to account for the response type and the protocol frame. */
9879 n = min (get_remote_packet_size () - 5, len);
9880 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9881 object_name, annex ? annex : "",
9882 phex_nz (offset, sizeof offset),
9883 phex_nz (n, sizeof n));
9884 i = putpkt (rs->buf);
9885 if (i < 0)
2ed4b548 9886 return TARGET_XFER_E_IO;
0876f84a
DJ
9887
9888 rs->buf[0] = '\0';
9889 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9890 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9891 return TARGET_XFER_E_IO;
0876f84a
DJ
9892
9893 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9894 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9895
9896 /* 'm' means there is (or at least might be) more data after this
9897 batch. That does not make sense unless there's at least one byte
9898 of data in this reply. */
9899 if (rs->buf[0] == 'm' && packet_len == 1)
9900 error (_("Remote qXfer reply contained no data."));
9901
9902 /* Got some data. */
bc20a4af
PA
9903 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9904 packet_len - 1, readbuf, n);
0876f84a
DJ
9905
9906 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9907 or possibly empty. If we have the final block of a non-empty
9908 object, record this fact to bypass a subsequent partial read. */
9909 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9910 {
8e88304f
TT
9911 rs->finished_object = xstrdup (object_name);
9912 rs->finished_annex = xstrdup (annex ? annex : "");
9913 rs->finished_offset = offset + i;
0876f84a
DJ
9914 }
9915
9b409511
YQ
9916 if (i == 0)
9917 return TARGET_XFER_EOF;
9918 else
9919 {
9920 *xfered_len = i;
9921 return TARGET_XFER_OK;
9922 }
0876f84a
DJ
9923}
9924
9b409511 9925static enum target_xfer_status
4b8a223f 9926remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9927 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9928 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9929 ULONGEST *xfered_len)
c906108c 9930{
82f73884 9931 struct remote_state *rs;
c906108c 9932 int i;
6d820c5c 9933 char *p2;
1e3ff5ad 9934 char query_type;
124e13d9 9935 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9936
e6e4e701 9937 set_remote_traceframe ();
82f73884
PA
9938 set_general_thread (inferior_ptid);
9939
9940 rs = get_remote_state ();
9941
b2182ed2 9942 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9943 if (object == TARGET_OBJECT_MEMORY)
9944 {
2d717e4f
DJ
9945 /* If the remote target is connected but not running, we should
9946 pass this request down to a lower stratum (e.g. the executable
9947 file). */
9948 if (!target_has_execution)
9b409511 9949 return TARGET_XFER_EOF;
2d717e4f 9950
21e3b9b9 9951 if (writebuf != NULL)
124e13d9
SM
9952 return remote_write_bytes (offset, writebuf, len, unit_size,
9953 xfered_len);
21e3b9b9 9954 else
124e13d9
SM
9955 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9956 xfered_len);
21e3b9b9
DJ
9957 }
9958
0df8b418 9959 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9960 if (object == TARGET_OBJECT_SPU)
9961 {
9962 if (readbuf)
9963 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9964 xfered_len, &remote_protocol_packets
9965 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9966 else
9967 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9968 xfered_len, &remote_protocol_packets
9969 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9970 }
9971
4aa995e1
PA
9972 /* Handle extra signal info using qxfer packets. */
9973 if (object == TARGET_OBJECT_SIGNAL_INFO)
9974 {
9975 if (readbuf)
9976 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 9977 xfered_len, &remote_protocol_packets
4aa995e1
PA
9978 [PACKET_qXfer_siginfo_read]);
9979 else
3e43a32a 9980 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 9981 writebuf, offset, len, xfered_len,
4aa995e1
PA
9982 &remote_protocol_packets
9983 [PACKET_qXfer_siginfo_write]);
9984 }
9985
0fb4aa4b
PA
9986 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9987 {
9988 if (readbuf)
3e43a32a 9989 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 9990 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
9991 &remote_protocol_packets
9992 [PACKET_qXfer_statictrace_read]);
9993 else
2ed4b548 9994 return TARGET_XFER_E_IO;
0fb4aa4b
PA
9995 }
9996
a76d924d
DJ
9997 /* Only handle flash writes. */
9998 if (writebuf != NULL)
9999 {
a76d924d
DJ
10000 switch (object)
10001 {
10002 case TARGET_OBJECT_FLASH:
9b409511
YQ
10003 return remote_flash_write (ops, offset, len, xfered_len,
10004 writebuf);
a76d924d
DJ
10005
10006 default:
2ed4b548 10007 return TARGET_XFER_E_IO;
a76d924d
DJ
10008 }
10009 }
4b8a223f 10010
1e3ff5ad
AC
10011 /* Map pre-existing objects onto letters. DO NOT do this for new
10012 objects!!! Instead specify new query packets. */
10013 switch (object)
c906108c 10014 {
1e3ff5ad
AC
10015 case TARGET_OBJECT_AVR:
10016 query_type = 'R';
10017 break;
802188a7
RM
10018
10019 case TARGET_OBJECT_AUXV:
0876f84a
DJ
10020 gdb_assert (annex == NULL);
10021 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 10022 xfered_len,
0876f84a 10023 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 10024
23181151
DJ
10025 case TARGET_OBJECT_AVAILABLE_FEATURES:
10026 return remote_read_qxfer
9b409511 10027 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
10028 &remote_protocol_packets[PACKET_qXfer_features]);
10029
cfa9d6d9
DJ
10030 case TARGET_OBJECT_LIBRARIES:
10031 return remote_read_qxfer
9b409511 10032 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
10033 &remote_protocol_packets[PACKET_qXfer_libraries]);
10034
2268b414
JK
10035 case TARGET_OBJECT_LIBRARIES_SVR4:
10036 return remote_read_qxfer
9b409511 10037 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
10038 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10039
fd79ecee
DJ
10040 case TARGET_OBJECT_MEMORY_MAP:
10041 gdb_assert (annex == NULL);
10042 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 10043 xfered_len,
fd79ecee
DJ
10044 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10045
07e059b5
VP
10046 case TARGET_OBJECT_OSDATA:
10047 /* Should only get here if we're connected. */
5d93a237 10048 gdb_assert (rs->remote_desc);
07e059b5 10049 return remote_read_qxfer
9b409511 10050 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
10051 &remote_protocol_packets[PACKET_qXfer_osdata]);
10052
dc146f7c
VP
10053 case TARGET_OBJECT_THREADS:
10054 gdb_assert (annex == NULL);
10055 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 10056 xfered_len,
dc146f7c
VP
10057 &remote_protocol_packets[PACKET_qXfer_threads]);
10058
b3b9301e
PA
10059 case TARGET_OBJECT_TRACEFRAME_INFO:
10060 gdb_assert (annex == NULL);
10061 return remote_read_qxfer
9b409511 10062 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 10063 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
10064
10065 case TARGET_OBJECT_FDPIC:
10066 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 10067 xfered_len,
78d85199 10068 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
10069
10070 case TARGET_OBJECT_OPENVMS_UIB:
10071 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 10072 xfered_len,
169081d0
TG
10073 &remote_protocol_packets[PACKET_qXfer_uib]);
10074
9accd112
MM
10075 case TARGET_OBJECT_BTRACE:
10076 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 10077 xfered_len,
9accd112
MM
10078 &remote_protocol_packets[PACKET_qXfer_btrace]);
10079
f4abbc16
MM
10080 case TARGET_OBJECT_BTRACE_CONF:
10081 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10082 len, xfered_len,
10083 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10084
c78fa86a
GB
10085 case TARGET_OBJECT_EXEC_FILE:
10086 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10087 len, xfered_len,
10088 &remote_protocol_packets[PACKET_qXfer_exec_file]);
10089
1e3ff5ad 10090 default:
2ed4b548 10091 return TARGET_XFER_E_IO;
c906108c
SS
10092 }
10093
0df8b418 10094 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 10095 large enough let the caller deal with it. */
ea9c271d 10096 if (len < get_remote_packet_size ())
2ed4b548 10097 return TARGET_XFER_E_IO;
ea9c271d 10098 len = get_remote_packet_size ();
1e3ff5ad 10099
23860348 10100 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 10101 if (!rs->remote_desc)
8a3fe4f8 10102 error (_("remote query is only available after target open"));
c906108c 10103
1e3ff5ad 10104 gdb_assert (annex != NULL);
4b8a223f 10105 gdb_assert (readbuf != NULL);
c906108c 10106
6d820c5c 10107 p2 = rs->buf;
c906108c
SS
10108 *p2++ = 'q';
10109 *p2++ = query_type;
10110
23860348
MS
10111 /* We used one buffer char for the remote protocol q command and
10112 another for the query type. As the remote protocol encapsulation
10113 uses 4 chars plus one extra in case we are debugging
10114 (remote_debug), we have PBUFZIZ - 7 left to pack the query
10115 string. */
c906108c 10116 i = 0;
ea9c271d 10117 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 10118 {
1e3ff5ad
AC
10119 /* Bad caller may have sent forbidden characters. */
10120 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10121 *p2++ = annex[i];
c906108c
SS
10122 i++;
10123 }
1e3ff5ad
AC
10124 *p2 = '\0';
10125 gdb_assert (annex[i] == '\0');
c906108c 10126
6d820c5c 10127 i = putpkt (rs->buf);
c5aa993b 10128 if (i < 0)
2ed4b548 10129 return TARGET_XFER_E_IO;
c906108c 10130
6d820c5c
DJ
10131 getpkt (&rs->buf, &rs->buf_size, 0);
10132 strcpy ((char *) readbuf, rs->buf);
c906108c 10133
9b409511
YQ
10134 *xfered_len = strlen ((char *) readbuf);
10135 return TARGET_XFER_OK;
c906108c
SS
10136}
10137
08388c79
DE
10138static int
10139remote_search_memory (struct target_ops* ops,
10140 CORE_ADDR start_addr, ULONGEST search_space_len,
10141 const gdb_byte *pattern, ULONGEST pattern_len,
10142 CORE_ADDR *found_addrp)
10143{
f5656ead 10144 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
10145 struct remote_state *rs = get_remote_state ();
10146 int max_size = get_memory_write_packet_size ();
10147 struct packet_config *packet =
10148 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
10149 /* Number of packet bytes used to encode the pattern;
10150 this could be more than PATTERN_LEN due to escape characters. */
08388c79 10151 int escaped_pattern_len;
0df8b418 10152 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
10153 int used_pattern_len;
10154 int i;
10155 int found;
10156 ULONGEST found_addr;
10157
10158 /* Don't go to the target if we don't have to.
10159 This is done before checking packet->support to avoid the possibility that
10160 a success for this edge case means the facility works in general. */
10161 if (pattern_len > search_space_len)
10162 return 0;
10163 if (pattern_len == 0)
10164 {
10165 *found_addrp = start_addr;
10166 return 1;
10167 }
10168
10169 /* If we already know the packet isn't supported, fall back to the simple
10170 way of searching memory. */
10171
4082afcc 10172 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
10173 {
10174 /* Target doesn't provided special support, fall back and use the
10175 standard support (copy memory and do the search here). */
10176 return simple_search_memory (ops, start_addr, search_space_len,
10177 pattern, pattern_len, found_addrp);
10178 }
10179
28439a30
PA
10180 /* Make sure the remote is pointing at the right process. */
10181 set_general_process ();
10182
08388c79
DE
10183 /* Insert header. */
10184 i = snprintf (rs->buf, max_size,
10185 "qSearch:memory:%s;%s;",
5af949e3 10186 phex_nz (start_addr, addr_size),
08388c79
DE
10187 phex_nz (search_space_len, sizeof (search_space_len)));
10188 max_size -= (i + 1);
10189
10190 /* Escape as much data as fits into rs->buf. */
10191 escaped_pattern_len =
124e13d9 10192 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
10193 &used_pattern_len, max_size);
10194
10195 /* Bail if the pattern is too large. */
10196 if (used_pattern_len != pattern_len)
9b20d036 10197 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
10198
10199 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10200 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10201 || packet_ok (rs->buf, packet) != PACKET_OK)
10202 {
10203 /* The request may not have worked because the command is not
10204 supported. If so, fall back to the simple way. */
10205 if (packet->support == PACKET_DISABLE)
10206 {
10207 return simple_search_memory (ops, start_addr, search_space_len,
10208 pattern, pattern_len, found_addrp);
10209 }
10210 return -1;
10211 }
10212
10213 if (rs->buf[0] == '0')
10214 found = 0;
10215 else if (rs->buf[0] == '1')
10216 {
10217 found = 1;
10218 if (rs->buf[1] != ',')
10e0fa18 10219 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10220 unpack_varlen_hex (rs->buf + 2, &found_addr);
10221 *found_addrp = found_addr;
10222 }
10223 else
10e0fa18 10224 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
10225
10226 return found;
10227}
10228
96baa820 10229static void
a30bf1f1 10230remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 10231 struct ui_file *outbuf)
96baa820 10232{
d01949b6 10233 struct remote_state *rs = get_remote_state ();
2e9f7625 10234 char *p = rs->buf;
96baa820 10235
5d93a237 10236 if (!rs->remote_desc)
8a3fe4f8 10237 error (_("remote rcmd is only available after target open"));
96baa820 10238
23860348 10239 /* Send a NULL command across as an empty command. */
7be570e7
JM
10240 if (command == NULL)
10241 command = "";
10242
23860348 10243 /* The query prefix. */
2e9f7625
DJ
10244 strcpy (rs->buf, "qRcmd,");
10245 p = strchr (rs->buf, '\0');
96baa820 10246
3e43a32a
MS
10247 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10248 > get_remote_packet_size ())
8a3fe4f8 10249 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 10250
23860348 10251 /* Encode the actual command. */
a30bf1f1 10252 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 10253
6d820c5c 10254 if (putpkt (rs->buf) < 0)
8a3fe4f8 10255 error (_("Communication problem with target."));
96baa820
JM
10256
10257 /* get/display the response */
10258 while (1)
10259 {
2e9f7625
DJ
10260 char *buf;
10261
00bf0b85 10262 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 10263 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 10264 rs->buf[0] = '\0';
5b37825d
PW
10265 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10266 {
10267 /* Timeout. Continue to (try to) read responses.
10268 This is better than stopping with an error, assuming the stub
10269 is still executing the (long) monitor command.
10270 If needed, the user can interrupt gdb using C-c, obtaining
10271 an effect similar to stop on timeout. */
10272 continue;
10273 }
2e9f7625 10274 buf = rs->buf;
96baa820 10275 if (buf[0] == '\0')
8a3fe4f8 10276 error (_("Target does not support this command."));
96baa820
JM
10277 if (buf[0] == 'O' && buf[1] != 'K')
10278 {
23860348 10279 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
10280 continue;
10281 }
10282 if (strcmp (buf, "OK") == 0)
10283 break;
7be570e7
JM
10284 if (strlen (buf) == 3 && buf[0] == 'E'
10285 && isdigit (buf[1]) && isdigit (buf[2]))
10286 {
8a3fe4f8 10287 error (_("Protocol error with Rcmd"));
7be570e7 10288 }
96baa820
JM
10289 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10290 {
10291 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 10292
96baa820
JM
10293 fputc_unfiltered (c, outbuf);
10294 }
10295 break;
10296 }
10297}
10298
fd79ecee
DJ
10299static VEC(mem_region_s) *
10300remote_memory_map (struct target_ops *ops)
10301{
10302 VEC(mem_region_s) *result = NULL;
10303 char *text = target_read_stralloc (&current_target,
10304 TARGET_OBJECT_MEMORY_MAP, NULL);
10305
10306 if (text)
10307 {
10308 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 10309
fd79ecee
DJ
10310 result = parse_memory_map (text);
10311 do_cleanups (back_to);
10312 }
10313
10314 return result;
10315}
10316
c906108c 10317static void
fba45db2 10318packet_command (char *args, int from_tty)
c906108c 10319{
d01949b6 10320 struct remote_state *rs = get_remote_state ();
c906108c 10321
5d93a237 10322 if (!rs->remote_desc)
8a3fe4f8 10323 error (_("command can only be used with remote target"));
c906108c 10324
c5aa993b 10325 if (!args)
8a3fe4f8 10326 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
10327
10328 puts_filtered ("sending: ");
10329 print_packet (args);
10330 puts_filtered ("\n");
10331 putpkt (args);
10332
6d820c5c 10333 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 10334 puts_filtered ("received: ");
6d820c5c 10335 print_packet (rs->buf);
c906108c
SS
10336 puts_filtered ("\n");
10337}
10338
10339#if 0
23860348 10340/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 10341
a14ed312 10342static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 10343
a14ed312 10344static void threadset_test_cmd (char *cmd, int tty);
c906108c 10345
a14ed312 10346static void threadalive_test (char *cmd, int tty);
c906108c 10347
a14ed312 10348static void threadlist_test_cmd (char *cmd, int tty);
c906108c 10349
23860348 10350int get_and_display_threadinfo (threadref *ref);
c906108c 10351
a14ed312 10352static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 10353
23860348 10354static int thread_display_step (threadref *ref, void *context);
c906108c 10355
a14ed312 10356static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 10357
a14ed312 10358static void init_remote_threadtests (void);
c906108c 10359
23860348 10360#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
10361
10362static void
fba45db2 10363threadset_test_cmd (char *cmd, int tty)
c906108c
SS
10364{
10365 int sample_thread = SAMPLE_THREAD;
10366
a3f17187 10367 printf_filtered (_("Remote threadset test\n"));
79d7f229 10368 set_general_thread (sample_thread);
c906108c
SS
10369}
10370
10371
10372static void
fba45db2 10373threadalive_test (char *cmd, int tty)
c906108c
SS
10374{
10375 int sample_thread = SAMPLE_THREAD;
79d7f229 10376 int pid = ptid_get_pid (inferior_ptid);
ba348170 10377 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 10378
79d7f229 10379 if (remote_thread_alive (ptid))
c906108c
SS
10380 printf_filtered ("PASS: Thread alive test\n");
10381 else
10382 printf_filtered ("FAIL: Thread alive test\n");
10383}
10384
23860348 10385void output_threadid (char *title, threadref *ref);
c906108c
SS
10386
10387void
fba45db2 10388output_threadid (char *title, threadref *ref)
c906108c
SS
10389{
10390 char hexid[20];
10391
23860348 10392 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
10393 hexid[16] = 0;
10394 printf_filtered ("%s %s\n", title, (&hexid[0]));
10395}
10396
10397static void
fba45db2 10398threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
10399{
10400 int startflag = 1;
10401 threadref nextthread;
10402 int done, result_count;
10403 threadref threadlist[3];
10404
10405 printf_filtered ("Remote Threadlist test\n");
10406 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10407 &result_count, &threadlist[0]))
10408 printf_filtered ("FAIL: threadlist test\n");
10409 else
10410 {
10411 threadref *scan = threadlist;
10412 threadref *limit = scan + result_count;
10413
10414 while (scan < limit)
10415 output_threadid (" thread ", scan++);
10416 }
10417}
10418
10419void
fba45db2 10420display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
10421{
10422 output_threadid ("Threadid: ", &info->threadid);
10423 printf_filtered ("Name: %s\n ", info->shortname);
10424 printf_filtered ("State: %s\n", info->display);
10425 printf_filtered ("other: %s\n\n", info->more_display);
10426}
10427
10428int
fba45db2 10429get_and_display_threadinfo (threadref *ref)
c906108c
SS
10430{
10431 int result;
10432 int set;
10433 struct gdb_ext_thread_info threadinfo;
10434
10435 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10436 | TAG_MOREDISPLAY | TAG_DISPLAY;
10437 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10438 display_thread_info (&threadinfo);
10439 return result;
10440}
10441
10442static void
fba45db2 10443threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
10444{
10445 int athread = SAMPLE_THREAD;
10446 threadref thread;
10447 int set;
10448
10449 int_to_threadref (&thread, athread);
10450 printf_filtered ("Remote Threadinfo test\n");
10451 if (!get_and_display_threadinfo (&thread))
10452 printf_filtered ("FAIL cannot get thread info\n");
10453}
10454
10455static int
fba45db2 10456thread_display_step (threadref *ref, void *context)
c906108c
SS
10457{
10458 /* output_threadid(" threadstep ",ref); *//* simple test */
10459 return get_and_display_threadinfo (ref);
10460}
10461
10462static void
fba45db2 10463threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10464{
10465 printf_filtered ("Remote Threadlist update test\n");
10466 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10467}
10468
10469static void
10470init_remote_threadtests (void)
10471{
3e43a32a
MS
10472 add_com ("tlist", class_obscure, threadlist_test_cmd,
10473 _("Fetch and print the remote list of "
10474 "thread identifiers, one pkt only"));
c906108c 10475 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10476 _("Fetch and display info about one thread"));
c906108c 10477 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10478 _("Test setting to a different thread"));
c906108c 10479 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10480 _("Iterate through updating all remote thread info"));
c906108c 10481 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10482 _(" Remote thread alive test "));
c906108c
SS
10483}
10484
10485#endif /* 0 */
10486
f3fb8c85
MS
10487/* Convert a thread ID to a string. Returns the string in a static
10488 buffer. */
10489
10490static char *
117de6a9 10491remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10492{
79d7f229 10493 static char buf[64];
82f73884 10494 struct remote_state *rs = get_remote_state ();
f3fb8c85 10495
7cee1e54
PA
10496 if (ptid_equal (ptid, null_ptid))
10497 return normal_pid_to_str (ptid);
10498 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10499 {
10500 /* Printing an inferior target id. */
10501
10502 /* When multi-process extensions are off, there's no way in the
10503 remote protocol to know the remote process id, if there's any
10504 at all. There's one exception --- when we're connected with
10505 target extended-remote, and we manually attached to a process
10506 with "attach PID". We don't record anywhere a flag that
10507 allows us to distinguish that case from the case of
10508 connecting with extended-remote and the stub already being
10509 attached to a process, and reporting yes to qAttached, hence
10510 no smart special casing here. */
10511 if (!remote_multi_process_p (rs))
10512 {
10513 xsnprintf (buf, sizeof buf, "Remote target");
10514 return buf;
10515 }
10516
10517 return normal_pid_to_str (ptid);
82f73884 10518 }
ecd0ada5 10519 else
79d7f229 10520 {
ecd0ada5
PA
10521 if (ptid_equal (magic_null_ptid, ptid))
10522 xsnprintf (buf, sizeof buf, "Thread <main>");
8020350c 10523 else if (remote_multi_process_p (rs))
de0d863e
DB
10524 if (ptid_get_lwp (ptid) == 0)
10525 return normal_pid_to_str (ptid);
10526 else
10527 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10528 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10529 else
10530 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10531 ptid_get_lwp (ptid));
79d7f229
PA
10532 return buf;
10533 }
f3fb8c85
MS
10534}
10535
38691318
KB
10536/* Get the address of the thread local variable in OBJFILE which is
10537 stored at OFFSET within the thread local storage for thread PTID. */
10538
10539static CORE_ADDR
117de6a9
PA
10540remote_get_thread_local_address (struct target_ops *ops,
10541 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10542{
4082afcc 10543 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10544 {
10545 struct remote_state *rs = get_remote_state ();
6d820c5c 10546 char *p = rs->buf;
82f73884 10547 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10548 enum packet_result result;
38691318
KB
10549
10550 strcpy (p, "qGetTLSAddr:");
10551 p += strlen (p);
82f73884 10552 p = write_ptid (p, endp, ptid);
38691318
KB
10553 *p++ = ',';
10554 p += hexnumstr (p, offset);
10555 *p++ = ',';
10556 p += hexnumstr (p, lm);
10557 *p++ = '\0';
10558
6d820c5c
DJ
10559 putpkt (rs->buf);
10560 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10561 result = packet_ok (rs->buf,
10562 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10563 if (result == PACKET_OK)
38691318
KB
10564 {
10565 ULONGEST result;
10566
6d820c5c 10567 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10568 return result;
10569 }
571dd617 10570 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10571 throw_error (TLS_GENERIC_ERROR,
10572 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10573 else
109c3e39
AC
10574 throw_error (TLS_GENERIC_ERROR,
10575 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10576 }
10577 else
109c3e39
AC
10578 throw_error (TLS_GENERIC_ERROR,
10579 _("TLS not supported or disabled on this target"));
38691318
KB
10580 /* Not reached. */
10581 return 0;
10582}
10583
711e434b
PM
10584/* Provide thread local base, i.e. Thread Information Block address.
10585 Returns 1 if ptid is found and thread_local_base is non zero. */
10586
70221824 10587static int
bd7ae0f5 10588remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10589{
4082afcc 10590 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10591 {
10592 struct remote_state *rs = get_remote_state ();
10593 char *p = rs->buf;
10594 char *endp = rs->buf + get_remote_packet_size ();
10595 enum packet_result result;
10596
10597 strcpy (p, "qGetTIBAddr:");
10598 p += strlen (p);
10599 p = write_ptid (p, endp, ptid);
10600 *p++ = '\0';
10601
10602 putpkt (rs->buf);
10603 getpkt (&rs->buf, &rs->buf_size, 0);
10604 result = packet_ok (rs->buf,
10605 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10606 if (result == PACKET_OK)
10607 {
10608 ULONGEST result;
10609
10610 unpack_varlen_hex (rs->buf, &result);
10611 if (addr)
10612 *addr = (CORE_ADDR) result;
10613 return 1;
10614 }
10615 else if (result == PACKET_UNKNOWN)
10616 error (_("Remote target doesn't support qGetTIBAddr packet"));
10617 else
10618 error (_("Remote target failed to process qGetTIBAddr request"));
10619 }
10620 else
10621 error (_("qGetTIBAddr not supported or disabled on this target"));
10622 /* Not reached. */
10623 return 0;
10624}
10625
29709017
DJ
10626/* Support for inferring a target description based on the current
10627 architecture and the size of a 'g' packet. While the 'g' packet
10628 can have any size (since optional registers can be left off the
10629 end), some sizes are easily recognizable given knowledge of the
10630 approximate architecture. */
10631
10632struct remote_g_packet_guess
10633{
10634 int bytes;
10635 const struct target_desc *tdesc;
10636};
10637typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10638DEF_VEC_O(remote_g_packet_guess_s);
10639
10640struct remote_g_packet_data
10641{
10642 VEC(remote_g_packet_guess_s) *guesses;
10643};
10644
10645static struct gdbarch_data *remote_g_packet_data_handle;
10646
10647static void *
10648remote_g_packet_data_init (struct obstack *obstack)
10649{
10650 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10651}
10652
10653void
10654register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10655 const struct target_desc *tdesc)
10656{
10657 struct remote_g_packet_data *data
19ba03f4
SM
10658 = ((struct remote_g_packet_data *)
10659 gdbarch_data (gdbarch, remote_g_packet_data_handle));
29709017
DJ
10660 struct remote_g_packet_guess new_guess, *guess;
10661 int ix;
10662
10663 gdb_assert (tdesc != NULL);
10664
10665 for (ix = 0;
10666 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10667 ix++)
10668 if (guess->bytes == bytes)
10669 internal_error (__FILE__, __LINE__,
9b20d036 10670 _("Duplicate g packet description added for size %d"),
29709017
DJ
10671 bytes);
10672
10673 new_guess.bytes = bytes;
10674 new_guess.tdesc = tdesc;
10675 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10676}
10677
d962ef82
DJ
10678/* Return 1 if remote_read_description would do anything on this target
10679 and architecture, 0 otherwise. */
10680
10681static int
10682remote_read_description_p (struct target_ops *target)
10683{
10684 struct remote_g_packet_data *data
19ba03f4
SM
10685 = ((struct remote_g_packet_data *)
10686 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
d962ef82
DJ
10687
10688 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10689 return 1;
10690
10691 return 0;
10692}
10693
29709017
DJ
10694static const struct target_desc *
10695remote_read_description (struct target_ops *target)
10696{
10697 struct remote_g_packet_data *data
19ba03f4
SM
10698 = ((struct remote_g_packet_data *)
10699 gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
29709017 10700
d962ef82
DJ
10701 /* Do not try this during initial connection, when we do not know
10702 whether there is a running but stopped thread. */
10703 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10704 return target->beneath->to_read_description (target->beneath);
d962ef82 10705
29709017
DJ
10706 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10707 {
10708 struct remote_g_packet_guess *guess;
10709 int ix;
10710 int bytes = send_g_packet ();
10711
10712 for (ix = 0;
10713 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10714 ix++)
10715 if (guess->bytes == bytes)
10716 return guess->tdesc;
10717
10718 /* We discard the g packet. A minor optimization would be to
10719 hold on to it, and fill the register cache once we have selected
10720 an architecture, but it's too tricky to do safely. */
10721 }
10722
2117c711 10723 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10724}
10725
a6b151f1
DJ
10726/* Remote file transfer support. This is host-initiated I/O, not
10727 target-initiated; for target-initiated, see remote-fileio.c. */
10728
10729/* If *LEFT is at least the length of STRING, copy STRING to
10730 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10731 decrease *LEFT. Otherwise raise an error. */
10732
10733static void
10734remote_buffer_add_string (char **buffer, int *left, char *string)
10735{
10736 int len = strlen (string);
10737
10738 if (len > *left)
10739 error (_("Packet too long for target."));
10740
10741 memcpy (*buffer, string, len);
10742 *buffer += len;
10743 *left -= len;
10744
10745 /* NUL-terminate the buffer as a convenience, if there is
10746 room. */
10747 if (*left)
10748 **buffer = '\0';
10749}
10750
10751/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10752 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10753 decrease *LEFT. Otherwise raise an error. */
10754
10755static void
10756remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10757 int len)
10758{
10759 if (2 * len > *left)
10760 error (_("Packet too long for target."));
10761
10762 bin2hex (bytes, *buffer, len);
10763 *buffer += 2 * len;
10764 *left -= 2 * len;
10765
10766 /* NUL-terminate the buffer as a convenience, if there is
10767 room. */
10768 if (*left)
10769 **buffer = '\0';
10770}
10771
10772/* If *LEFT is large enough, convert VALUE to hex and add it to
10773 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10774 decrease *LEFT. Otherwise raise an error. */
10775
10776static void
10777remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10778{
10779 int len = hexnumlen (value);
10780
10781 if (len > *left)
10782 error (_("Packet too long for target."));
10783
10784 hexnumstr (*buffer, value);
10785 *buffer += len;
10786 *left -= len;
10787
10788 /* NUL-terminate the buffer as a convenience, if there is
10789 room. */
10790 if (*left)
10791 **buffer = '\0';
10792}
10793
10794/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10795 value, *REMOTE_ERRNO to the remote error number or zero if none
10796 was included, and *ATTACHMENT to point to the start of the annex
10797 if any. The length of the packet isn't needed here; there may
10798 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10799
10800 Return 0 if the packet could be parsed, -1 if it could not. If
10801 -1 is returned, the other variables may not be initialized. */
10802
10803static int
10804remote_hostio_parse_result (char *buffer, int *retcode,
10805 int *remote_errno, char **attachment)
10806{
10807 char *p, *p2;
10808
10809 *remote_errno = 0;
10810 *attachment = NULL;
10811
10812 if (buffer[0] != 'F')
10813 return -1;
10814
10815 errno = 0;
10816 *retcode = strtol (&buffer[1], &p, 16);
10817 if (errno != 0 || p == &buffer[1])
10818 return -1;
10819
10820 /* Check for ",errno". */
10821 if (*p == ',')
10822 {
10823 errno = 0;
10824 *remote_errno = strtol (p + 1, &p2, 16);
10825 if (errno != 0 || p + 1 == p2)
10826 return -1;
10827 p = p2;
10828 }
10829
10830 /* Check for ";attachment". If there is no attachment, the
10831 packet should end here. */
10832 if (*p == ';')
10833 {
10834 *attachment = p + 1;
10835 return 0;
10836 }
10837 else if (*p == '\0')
10838 return 0;
10839 else
10840 return -1;
10841}
10842
10843/* Send a prepared I/O packet to the target and read its response.
10844 The prepared packet is in the global RS->BUF before this function
10845 is called, and the answer is there when we return.
10846
10847 COMMAND_BYTES is the length of the request to send, which may include
10848 binary data. WHICH_PACKET is the packet configuration to check
10849 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10850 is set to the error number and -1 is returned. Otherwise the value
10851 returned by the function is returned.
10852
10853 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10854 attachment is expected; an error will be reported if there's a
10855 mismatch. If one is found, *ATTACHMENT will be set to point into
10856 the packet buffer and *ATTACHMENT_LEN will be set to the
10857 attachment's length. */
10858
10859static int
10860remote_hostio_send_command (int command_bytes, int which_packet,
10861 int *remote_errno, char **attachment,
10862 int *attachment_len)
10863{
10864 struct remote_state *rs = get_remote_state ();
10865 int ret, bytes_read;
10866 char *attachment_tmp;
10867
5d93a237 10868 if (!rs->remote_desc
4082afcc 10869 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10870 {
10871 *remote_errno = FILEIO_ENOSYS;
10872 return -1;
10873 }
10874
10875 putpkt_binary (rs->buf, command_bytes);
10876 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10877
10878 /* If it timed out, something is wrong. Don't try to parse the
10879 buffer. */
10880 if (bytes_read < 0)
10881 {
10882 *remote_errno = FILEIO_EINVAL;
10883 return -1;
10884 }
10885
10886 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10887 {
10888 case PACKET_ERROR:
10889 *remote_errno = FILEIO_EINVAL;
10890 return -1;
10891 case PACKET_UNKNOWN:
10892 *remote_errno = FILEIO_ENOSYS;
10893 return -1;
10894 case PACKET_OK:
10895 break;
10896 }
10897
10898 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10899 &attachment_tmp))
10900 {
10901 *remote_errno = FILEIO_EINVAL;
10902 return -1;
10903 }
10904
10905 /* Make sure we saw an attachment if and only if we expected one. */
10906 if ((attachment_tmp == NULL && attachment != NULL)
10907 || (attachment_tmp != NULL && attachment == NULL))
10908 {
10909 *remote_errno = FILEIO_EINVAL;
10910 return -1;
10911 }
10912
10913 /* If an attachment was found, it must point into the packet buffer;
10914 work out how many bytes there were. */
10915 if (attachment_tmp != NULL)
10916 {
10917 *attachment = attachment_tmp;
10918 *attachment_len = bytes_read - (*attachment - rs->buf);
10919 }
10920
10921 return ret;
10922}
10923
80152258
PA
10924/* Invalidate the readahead cache. */
10925
10926static void
10927readahead_cache_invalidate (void)
10928{
10929 struct remote_state *rs = get_remote_state ();
10930
10931 rs->readahead_cache.fd = -1;
10932}
10933
10934/* Invalidate the readahead cache if it is holding data for FD. */
10935
10936static void
10937readahead_cache_invalidate_fd (int fd)
10938{
10939 struct remote_state *rs = get_remote_state ();
10940
10941 if (rs->readahead_cache.fd == fd)
10942 rs->readahead_cache.fd = -1;
10943}
10944
15a201c8
GB
10945/* Set the filesystem remote_hostio functions that take FILENAME
10946 arguments will use. Return 0 on success, or -1 if an error
10947 occurs (and set *REMOTE_ERRNO). */
10948
10949static int
10950remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10951{
10952 struct remote_state *rs = get_remote_state ();
10953 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10954 char *p = rs->buf;
10955 int left = get_remote_packet_size () - 1;
10956 char arg[9];
10957 int ret;
10958
10959 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10960 return 0;
10961
10962 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10963 return 0;
10964
10965 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10966
10967 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10968 remote_buffer_add_string (&p, &left, arg);
10969
10970 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10971 remote_errno, NULL, NULL);
10972
10973 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10974 return 0;
10975
10976 if (ret == 0)
10977 rs->fs_pid = required_pid;
10978
10979 return ret;
10980}
10981
12e2a5fd 10982/* Implementation of to_fileio_open. */
a6b151f1
DJ
10983
10984static int
cd897586 10985remote_hostio_open (struct target_ops *self,
07c138c8 10986 struct inferior *inf, const char *filename,
4313b8c0
GB
10987 int flags, int mode, int warn_if_slow,
10988 int *remote_errno)
a6b151f1
DJ
10989{
10990 struct remote_state *rs = get_remote_state ();
10991 char *p = rs->buf;
10992 int left = get_remote_packet_size () - 1;
10993
4313b8c0
GB
10994 if (warn_if_slow)
10995 {
10996 static int warning_issued = 0;
10997
10998 printf_unfiltered (_("Reading %s from remote target...\n"),
10999 filename);
11000
11001 if (!warning_issued)
11002 {
11003 warning (_("File transfers from remote targets can be slow."
11004 " Use \"set sysroot\" to access files locally"
11005 " instead."));
11006 warning_issued = 1;
11007 }
11008 }
11009
15a201c8
GB
11010 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11011 return -1;
11012
a6b151f1
DJ
11013 remote_buffer_add_string (&p, &left, "vFile:open:");
11014
11015 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11016 strlen (filename));
11017 remote_buffer_add_string (&p, &left, ",");
11018
11019 remote_buffer_add_int (&p, &left, flags);
11020 remote_buffer_add_string (&p, &left, ",");
11021
11022 remote_buffer_add_int (&p, &left, mode);
11023
11024 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11025 remote_errno, NULL, NULL);
11026}
11027
12e2a5fd 11028/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
11029
11030static int
0d866f62
TT
11031remote_hostio_pwrite (struct target_ops *self,
11032 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
11033 ULONGEST offset, int *remote_errno)
11034{
11035 struct remote_state *rs = get_remote_state ();
11036 char *p = rs->buf;
11037 int left = get_remote_packet_size ();
11038 int out_len;
11039
80152258
PA
11040 readahead_cache_invalidate_fd (fd);
11041
a6b151f1
DJ
11042 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11043
11044 remote_buffer_add_int (&p, &left, fd);
11045 remote_buffer_add_string (&p, &left, ",");
11046
11047 remote_buffer_add_int (&p, &left, offset);
11048 remote_buffer_add_string (&p, &left, ",");
11049
124e13d9 11050 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
11051 get_remote_packet_size () - (p - rs->buf));
11052
11053 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11054 remote_errno, NULL, NULL);
11055}
11056
80152258
PA
11057/* Helper for the implementation of to_fileio_pread. Read the file
11058 from the remote side with vFile:pread. */
a6b151f1
DJ
11059
11060static int
80152258
PA
11061remote_hostio_pread_vFile (struct target_ops *self,
11062 int fd, gdb_byte *read_buf, int len,
11063 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
11064{
11065 struct remote_state *rs = get_remote_state ();
11066 char *p = rs->buf;
11067 char *attachment;
11068 int left = get_remote_packet_size ();
11069 int ret, attachment_len;
11070 int read_len;
11071
11072 remote_buffer_add_string (&p, &left, "vFile:pread:");
11073
11074 remote_buffer_add_int (&p, &left, fd);
11075 remote_buffer_add_string (&p, &left, ",");
11076
11077 remote_buffer_add_int (&p, &left, len);
11078 remote_buffer_add_string (&p, &left, ",");
11079
11080 remote_buffer_add_int (&p, &left, offset);
11081
11082 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11083 remote_errno, &attachment,
11084 &attachment_len);
11085
11086 if (ret < 0)
11087 return ret;
11088
bc20a4af 11089 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
11090 read_buf, len);
11091 if (read_len != ret)
11092 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11093
11094 return ret;
11095}
11096
80152258
PA
11097/* Serve pread from the readahead cache. Returns number of bytes
11098 read, or 0 if the request can't be served from the cache. */
11099
11100static int
11101remote_hostio_pread_from_cache (struct remote_state *rs,
11102 int fd, gdb_byte *read_buf, size_t len,
11103 ULONGEST offset)
11104{
11105 struct readahead_cache *cache = &rs->readahead_cache;
11106
11107 if (cache->fd == fd
11108 && cache->offset <= offset
11109 && offset < cache->offset + cache->bufsize)
11110 {
11111 ULONGEST max = cache->offset + cache->bufsize;
11112
11113 if (offset + len > max)
11114 len = max - offset;
11115
11116 memcpy (read_buf, cache->buf + offset - cache->offset, len);
11117 return len;
11118 }
11119
11120 return 0;
11121}
11122
11123/* Implementation of to_fileio_pread. */
11124
11125static int
11126remote_hostio_pread (struct target_ops *self,
11127 int fd, gdb_byte *read_buf, int len,
11128 ULONGEST offset, int *remote_errno)
11129{
11130 int ret;
11131 struct remote_state *rs = get_remote_state ();
11132 struct readahead_cache *cache = &rs->readahead_cache;
11133
11134 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11135 if (ret > 0)
11136 {
11137 cache->hit_count++;
11138
11139 if (remote_debug)
11140 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11141 pulongest (cache->hit_count));
11142 return ret;
11143 }
11144
11145 cache->miss_count++;
11146 if (remote_debug)
11147 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11148 pulongest (cache->miss_count));
11149
11150 cache->fd = fd;
11151 cache->offset = offset;
11152 cache->bufsize = get_remote_packet_size ();
224c3ddb 11153 cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
80152258
PA
11154
11155 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11156 cache->offset, remote_errno);
11157 if (ret <= 0)
11158 {
11159 readahead_cache_invalidate_fd (fd);
11160 return ret;
11161 }
11162
11163 cache->bufsize = ret;
11164 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11165}
11166
12e2a5fd 11167/* Implementation of to_fileio_close. */
a6b151f1
DJ
11168
11169static int
df39ea25 11170remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
11171{
11172 struct remote_state *rs = get_remote_state ();
11173 char *p = rs->buf;
11174 int left = get_remote_packet_size () - 1;
11175
80152258
PA
11176 readahead_cache_invalidate_fd (fd);
11177
a6b151f1
DJ
11178 remote_buffer_add_string (&p, &left, "vFile:close:");
11179
11180 remote_buffer_add_int (&p, &left, fd);
11181
11182 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11183 remote_errno, NULL, NULL);
11184}
11185
12e2a5fd 11186/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
11187
11188static int
dbbca37d 11189remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
11190 struct inferior *inf, const char *filename,
11191 int *remote_errno)
a6b151f1
DJ
11192{
11193 struct remote_state *rs = get_remote_state ();
11194 char *p = rs->buf;
11195 int left = get_remote_packet_size () - 1;
11196
15a201c8
GB
11197 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11198 return -1;
11199
a6b151f1
DJ
11200 remote_buffer_add_string (&p, &left, "vFile:unlink:");
11201
11202 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11203 strlen (filename));
11204
11205 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11206 remote_errno, NULL, NULL);
11207}
11208
12e2a5fd 11209/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
11210
11211static char *
fab5aa7c 11212remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
11213 struct inferior *inf, const char *filename,
11214 int *remote_errno)
b9e7b9c3
UW
11215{
11216 struct remote_state *rs = get_remote_state ();
11217 char *p = rs->buf;
11218 char *attachment;
11219 int left = get_remote_packet_size ();
11220 int len, attachment_len;
11221 int read_len;
11222 char *ret;
11223
15a201c8
GB
11224 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11225 return NULL;
11226
b9e7b9c3
UW
11227 remote_buffer_add_string (&p, &left, "vFile:readlink:");
11228
11229 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11230 strlen (filename));
11231
11232 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11233 remote_errno, &attachment,
11234 &attachment_len);
11235
11236 if (len < 0)
11237 return NULL;
11238
224c3ddb 11239 ret = (char *) xmalloc (len + 1);
b9e7b9c3 11240
bc20a4af
PA
11241 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11242 (gdb_byte *) ret, len);
b9e7b9c3
UW
11243 if (read_len != len)
11244 error (_("Readlink returned %d, but %d bytes."), len, read_len);
11245
11246 ret[len] = '\0';
11247 return ret;
11248}
11249
12e2a5fd 11250/* Implementation of to_fileio_fstat. */
0a93529c
GB
11251
11252static int
11253remote_hostio_fstat (struct target_ops *self,
11254 int fd, struct stat *st,
11255 int *remote_errno)
11256{
11257 struct remote_state *rs = get_remote_state ();
11258 char *p = rs->buf;
11259 int left = get_remote_packet_size ();
11260 int attachment_len, ret;
11261 char *attachment;
11262 struct fio_stat fst;
11263 int read_len;
11264
464b0089
GB
11265 remote_buffer_add_string (&p, &left, "vFile:fstat:");
11266
11267 remote_buffer_add_int (&p, &left, fd);
11268
11269 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11270 remote_errno, &attachment,
11271 &attachment_len);
11272 if (ret < 0)
0a93529c 11273 {
464b0089
GB
11274 if (*remote_errno != FILEIO_ENOSYS)
11275 return ret;
11276
0a93529c
GB
11277 /* Strictly we should return -1, ENOSYS here, but when
11278 "set sysroot remote:" was implemented in August 2008
11279 BFD's need for a stat function was sidestepped with
11280 this hack. This was not remedied until March 2015
11281 so we retain the previous behavior to avoid breaking
11282 compatibility.
11283
11284 Note that the memset is a March 2015 addition; older
11285 GDBs set st_size *and nothing else* so the structure
11286 would have garbage in all other fields. This might
11287 break something but retaining the previous behavior
11288 here would be just too wrong. */
11289
11290 memset (st, 0, sizeof (struct stat));
11291 st->st_size = INT_MAX;
11292 return 0;
11293 }
11294
0a93529c
GB
11295 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11296 (gdb_byte *) &fst, sizeof (fst));
11297
11298 if (read_len != ret)
11299 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11300
11301 if (read_len != sizeof (fst))
11302 error (_("vFile:fstat returned %d bytes, but expecting %d."),
11303 read_len, (int) sizeof (fst));
11304
11305 remote_fileio_to_host_stat (&fst, st);
11306
11307 return 0;
11308}
11309
12e2a5fd 11310/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
11311
11312static int
11313remote_filesystem_is_local (struct target_ops *self)
11314{
11315 /* Valgrind GDB presents itself as a remote target but works
11316 on the local filesystem: it does not implement remote get
11317 and users are not expected to set a sysroot. To handle
11318 this case we treat the remote filesystem as local if the
11319 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11320 does not support vFile:open. */
a3be80c3 11321 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
11322 {
11323 enum packet_support ps = packet_support (PACKET_vFile_open);
11324
11325 if (ps == PACKET_SUPPORT_UNKNOWN)
11326 {
11327 int fd, remote_errno;
11328
11329 /* Try opening a file to probe support. The supplied
11330 filename is irrelevant, we only care about whether
11331 the stub recognizes the packet or not. */
07c138c8 11332 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 11333 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
11334 &remote_errno);
11335
11336 if (fd >= 0)
11337 remote_hostio_close (self, fd, &remote_errno);
11338
11339 ps = packet_support (PACKET_vFile_open);
11340 }
11341
11342 if (ps == PACKET_DISABLE)
11343 {
11344 static int warning_issued = 0;
11345
11346 if (!warning_issued)
11347 {
11348 warning (_("remote target does not support file"
11349 " transfer, attempting to access files"
11350 " from local filesystem."));
11351 warning_issued = 1;
11352 }
11353
11354 return 1;
11355 }
11356 }
11357
11358 return 0;
11359}
11360
a6b151f1
DJ
11361static int
11362remote_fileio_errno_to_host (int errnum)
11363{
11364 switch (errnum)
11365 {
11366 case FILEIO_EPERM:
11367 return EPERM;
11368 case FILEIO_ENOENT:
11369 return ENOENT;
11370 case FILEIO_EINTR:
11371 return EINTR;
11372 case FILEIO_EIO:
11373 return EIO;
11374 case FILEIO_EBADF:
11375 return EBADF;
11376 case FILEIO_EACCES:
11377 return EACCES;
11378 case FILEIO_EFAULT:
11379 return EFAULT;
11380 case FILEIO_EBUSY:
11381 return EBUSY;
11382 case FILEIO_EEXIST:
11383 return EEXIST;
11384 case FILEIO_ENODEV:
11385 return ENODEV;
11386 case FILEIO_ENOTDIR:
11387 return ENOTDIR;
11388 case FILEIO_EISDIR:
11389 return EISDIR;
11390 case FILEIO_EINVAL:
11391 return EINVAL;
11392 case FILEIO_ENFILE:
11393 return ENFILE;
11394 case FILEIO_EMFILE:
11395 return EMFILE;
11396 case FILEIO_EFBIG:
11397 return EFBIG;
11398 case FILEIO_ENOSPC:
11399 return ENOSPC;
11400 case FILEIO_ESPIPE:
11401 return ESPIPE;
11402 case FILEIO_EROFS:
11403 return EROFS;
11404 case FILEIO_ENOSYS:
11405 return ENOSYS;
11406 case FILEIO_ENAMETOOLONG:
11407 return ENAMETOOLONG;
11408 }
11409 return -1;
11410}
11411
11412static char *
11413remote_hostio_error (int errnum)
11414{
11415 int host_error = remote_fileio_errno_to_host (errnum);
11416
11417 if (host_error == -1)
11418 error (_("Unknown remote I/O error %d"), errnum);
11419 else
11420 error (_("Remote I/O error: %s"), safe_strerror (host_error));
11421}
11422
a6b151f1
DJ
11423static void
11424remote_hostio_close_cleanup (void *opaque)
11425{
11426 int fd = *(int *) opaque;
11427 int remote_errno;
11428
df39ea25 11429 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
11430}
11431
11432void
11433remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11434{
11435 struct cleanup *back_to, *close_cleanup;
11436 int retcode, fd, remote_errno, bytes, io_size;
11437 FILE *file;
11438 gdb_byte *buffer;
11439 int bytes_in_buffer;
11440 int saw_eof;
11441 ULONGEST offset;
5d93a237 11442 struct remote_state *rs = get_remote_state ();
a6b151f1 11443
5d93a237 11444 if (!rs->remote_desc)
a6b151f1
DJ
11445 error (_("command can only be used with remote target"));
11446
614c279d 11447 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
11448 if (file == NULL)
11449 perror_with_name (local_file);
7c8a8b04 11450 back_to = make_cleanup_fclose (file);
a6b151f1 11451
07c138c8 11452 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 11453 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 11454 | FILEIO_O_TRUNC),
4313b8c0 11455 0700, 0, &remote_errno);
a6b151f1
DJ
11456 if (fd == -1)
11457 remote_hostio_error (remote_errno);
11458
11459 /* Send up to this many bytes at once. They won't all fit in the
11460 remote packet limit, so we'll transfer slightly fewer. */
11461 io_size = get_remote_packet_size ();
224c3ddb 11462 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11463 make_cleanup (xfree, buffer);
11464
11465 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11466
11467 bytes_in_buffer = 0;
11468 saw_eof = 0;
11469 offset = 0;
11470 while (bytes_in_buffer || !saw_eof)
11471 {
11472 if (!saw_eof)
11473 {
3e43a32a
MS
11474 bytes = fread (buffer + bytes_in_buffer, 1,
11475 io_size - bytes_in_buffer,
a6b151f1
DJ
11476 file);
11477 if (bytes == 0)
11478 {
11479 if (ferror (file))
11480 error (_("Error reading %s."), local_file);
11481 else
11482 {
11483 /* EOF. Unless there is something still in the
11484 buffer from the last iteration, we are done. */
11485 saw_eof = 1;
11486 if (bytes_in_buffer == 0)
11487 break;
11488 }
11489 }
11490 }
11491 else
11492 bytes = 0;
11493
11494 bytes += bytes_in_buffer;
11495 bytes_in_buffer = 0;
11496
0d866f62
TT
11497 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11498 fd, buffer, bytes,
3e43a32a 11499 offset, &remote_errno);
a6b151f1
DJ
11500
11501 if (retcode < 0)
11502 remote_hostio_error (remote_errno);
11503 else if (retcode == 0)
11504 error (_("Remote write of %d bytes returned 0!"), bytes);
11505 else if (retcode < bytes)
11506 {
11507 /* Short write. Save the rest of the read data for the next
11508 write. */
11509 bytes_in_buffer = bytes - retcode;
11510 memmove (buffer, buffer + retcode, bytes_in_buffer);
11511 }
11512
11513 offset += retcode;
11514 }
11515
11516 discard_cleanups (close_cleanup);
df39ea25 11517 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11518 remote_hostio_error (remote_errno);
11519
11520 if (from_tty)
11521 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11522 do_cleanups (back_to);
11523}
11524
11525void
11526remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11527{
11528 struct cleanup *back_to, *close_cleanup;
cea39f65 11529 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11530 FILE *file;
11531 gdb_byte *buffer;
11532 ULONGEST offset;
5d93a237 11533 struct remote_state *rs = get_remote_state ();
a6b151f1 11534
5d93a237 11535 if (!rs->remote_desc)
a6b151f1
DJ
11536 error (_("command can only be used with remote target"));
11537
07c138c8 11538 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11539 remote_file, FILEIO_O_RDONLY, 0, 0,
11540 &remote_errno);
a6b151f1
DJ
11541 if (fd == -1)
11542 remote_hostio_error (remote_errno);
11543
614c279d 11544 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11545 if (file == NULL)
11546 perror_with_name (local_file);
7c8a8b04 11547 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11548
11549 /* Send up to this many bytes at once. They won't all fit in the
11550 remote packet limit, so we'll transfer slightly fewer. */
11551 io_size = get_remote_packet_size ();
224c3ddb 11552 buffer = (gdb_byte *) xmalloc (io_size);
a6b151f1
DJ
11553 make_cleanup (xfree, buffer);
11554
11555 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11556
11557 offset = 0;
11558 while (1)
11559 {
a3be983c
TT
11560 bytes = remote_hostio_pread (find_target_at (process_stratum),
11561 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11562 if (bytes == 0)
11563 /* Success, but no bytes, means end-of-file. */
11564 break;
11565 if (bytes == -1)
11566 remote_hostio_error (remote_errno);
11567
11568 offset += bytes;
11569
11570 bytes = fwrite (buffer, 1, bytes, file);
11571 if (bytes == 0)
11572 perror_with_name (local_file);
11573 }
11574
11575 discard_cleanups (close_cleanup);
df39ea25 11576 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11577 remote_hostio_error (remote_errno);
11578
11579 if (from_tty)
11580 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11581 do_cleanups (back_to);
11582}
11583
11584void
11585remote_file_delete (const char *remote_file, int from_tty)
11586{
11587 int retcode, remote_errno;
5d93a237 11588 struct remote_state *rs = get_remote_state ();
a6b151f1 11589
5d93a237 11590 if (!rs->remote_desc)
a6b151f1
DJ
11591 error (_("command can only be used with remote target"));
11592
dbbca37d 11593 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11594 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11595 if (retcode == -1)
11596 remote_hostio_error (remote_errno);
11597
11598 if (from_tty)
11599 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11600}
11601
11602static void
11603remote_put_command (char *args, int from_tty)
11604{
11605 struct cleanup *back_to;
11606 char **argv;
11607
d1a41061
PP
11608 if (args == NULL)
11609 error_no_arg (_("file to put"));
11610
11611 argv = gdb_buildargv (args);
a6b151f1
DJ
11612 back_to = make_cleanup_freeargv (argv);
11613 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11614 error (_("Invalid parameters to remote put"));
11615
11616 remote_file_put (argv[0], argv[1], from_tty);
11617
11618 do_cleanups (back_to);
11619}
11620
11621static void
11622remote_get_command (char *args, int from_tty)
11623{
11624 struct cleanup *back_to;
11625 char **argv;
11626
d1a41061
PP
11627 if (args == NULL)
11628 error_no_arg (_("file to get"));
11629
11630 argv = gdb_buildargv (args);
a6b151f1
DJ
11631 back_to = make_cleanup_freeargv (argv);
11632 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11633 error (_("Invalid parameters to remote get"));
11634
11635 remote_file_get (argv[0], argv[1], from_tty);
11636
11637 do_cleanups (back_to);
11638}
11639
11640static void
11641remote_delete_command (char *args, int from_tty)
11642{
11643 struct cleanup *back_to;
11644 char **argv;
11645
d1a41061
PP
11646 if (args == NULL)
11647 error_no_arg (_("file to delete"));
11648
11649 argv = gdb_buildargv (args);
a6b151f1
DJ
11650 back_to = make_cleanup_freeargv (argv);
11651 if (argv[0] == NULL || argv[1] != NULL)
11652 error (_("Invalid parameters to remote delete"));
11653
11654 remote_file_delete (argv[0], from_tty);
11655
11656 do_cleanups (back_to);
11657}
11658
11659static void
11660remote_command (char *args, int from_tty)
11661{
635c7e8a 11662 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11663}
11664
b2175913 11665static int
19db3e69 11666remote_can_execute_reverse (struct target_ops *self)
b2175913 11667{
4082afcc
PA
11668 if (packet_support (PACKET_bs) == PACKET_ENABLE
11669 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11670 return 1;
11671 else
11672 return 0;
b2175913
MS
11673}
11674
74531fed 11675static int
2a9a2795 11676remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11677{
11678 return 1;
11679}
11680
03583c20 11681static int
2bfc0540 11682remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11683{
11684 /* Only supported in extended mode. */
11685 return 0;
11686}
11687
8a305172 11688static int
86ce2668 11689remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11690{
11691 struct remote_state *rs = get_remote_state ();
a744cf53 11692
8020350c 11693 return remote_multi_process_p (rs);
8a305172
PA
11694}
11695
70221824 11696static int
782b2b07
SS
11697remote_supports_cond_tracepoints (void)
11698{
4082afcc 11699 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11700}
11701
3788aec7 11702static int
efcc2da7 11703remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11704{
4082afcc 11705 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11706}
11707
70221824 11708static int
7a697b8d
SS
11709remote_supports_fast_tracepoints (void)
11710{
4082afcc 11711 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11712}
11713
0fb4aa4b
PA
11714static int
11715remote_supports_static_tracepoints (void)
11716{
4082afcc 11717 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11718}
11719
1e4d1764
YQ
11720static int
11721remote_supports_install_in_trace (void)
11722{
4082afcc 11723 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11724}
11725
d248b706 11726static int
7d178d6a 11727remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11728{
4082afcc
PA
11729 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11730 == PACKET_ENABLE);
d248b706
KY
11731}
11732
3065dfb6 11733static int
6de37a3a 11734remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11735{
4082afcc 11736 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11737}
11738
d3ce09f5 11739static int
78eff0ec 11740remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11741{
4082afcc 11742 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11743}
11744
35b1e5cc 11745static void
ecae04e1 11746remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11747{
11748 putpkt ("QTinit");
11749 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11750 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11751 error (_("Target does not support this command."));
11752}
11753
11754static void free_actions_list (char **actions_list);
11755static void free_actions_list_cleanup_wrapper (void *);
11756static void
11757free_actions_list_cleanup_wrapper (void *al)
11758{
19ba03f4 11759 free_actions_list ((char **) al);
35b1e5cc
SS
11760}
11761
11762static void
11763free_actions_list (char **actions_list)
11764{
11765 int ndx;
11766
11767 if (actions_list == 0)
11768 return;
11769
11770 for (ndx = 0; actions_list[ndx]; ndx++)
11771 xfree (actions_list[ndx]);
11772
11773 xfree (actions_list);
11774}
11775
409873ef
SS
11776/* Recursive routine to walk through command list including loops, and
11777 download packets for each command. */
11778
11779static void
11780remote_download_command_source (int num, ULONGEST addr,
11781 struct command_line *cmds)
11782{
11783 struct remote_state *rs = get_remote_state ();
11784 struct command_line *cmd;
11785
11786 for (cmd = cmds; cmd; cmd = cmd->next)
11787 {
0df8b418 11788 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11789 strcpy (rs->buf, "QTDPsrc:");
11790 encode_source_string (num, addr, "cmd", cmd->line,
11791 rs->buf + strlen (rs->buf),
11792 rs->buf_size - strlen (rs->buf));
11793 putpkt (rs->buf);
11794 remote_get_noisy_reply (&target_buf, &target_buf_size);
11795 if (strcmp (target_buf, "OK"))
11796 warning (_("Target does not support source download."));
11797
11798 if (cmd->control_type == while_control
11799 || cmd->control_type == while_stepping_control)
11800 {
11801 remote_download_command_source (num, addr, *cmd->body_list);
11802
0df8b418 11803 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11804 strcpy (rs->buf, "QTDPsrc:");
11805 encode_source_string (num, addr, "cmd", "end",
11806 rs->buf + strlen (rs->buf),
11807 rs->buf_size - strlen (rs->buf));
11808 putpkt (rs->buf);
11809 remote_get_noisy_reply (&target_buf, &target_buf_size);
11810 if (strcmp (target_buf, "OK"))
11811 warning (_("Target does not support source download."));
11812 }
11813 }
11814}
11815
35b1e5cc 11816static void
548f7808 11817remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11818{
bba74b36 11819#define BUF_SIZE 2048
e8ba3115 11820
35b1e5cc 11821 CORE_ADDR tpaddr;
409873ef 11822 char addrbuf[40];
bba74b36 11823 char buf[BUF_SIZE];
35b1e5cc
SS
11824 char **tdp_actions;
11825 char **stepping_actions;
11826 int ndx;
11827 struct cleanup *old_chain = NULL;
11828 struct agent_expr *aexpr;
11829 struct cleanup *aexpr_chain = NULL;
11830 char *pkt;
e8ba3115 11831 struct breakpoint *b = loc->owner;
d9b3f62e 11832 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11833
dc673c81 11834 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11835 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11836 tdp_actions);
11837 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11838 stepping_actions);
11839
11840 tpaddr = loc->address;
11841 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11842 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11843 addrbuf, /* address */
11844 (b->enable_state == bp_enabled ? 'E' : 'D'),
11845 t->step_count, t->pass_count);
e8ba3115
YQ
11846 /* Fast tracepoints are mostly handled by the target, but we can
11847 tell the target how big of an instruction block should be moved
11848 around. */
11849 if (b->type == bp_fast_tracepoint)
11850 {
11851 /* Only test for support at download time; we may not know
11852 target capabilities at definition time. */
11853 if (remote_supports_fast_tracepoints ())
35b1e5cc 11854 {
6b940e6a
PL
11855 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11856 NULL))
bba74b36 11857 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11858 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11859 else
e8ba3115
YQ
11860 /* If it passed validation at definition but fails now,
11861 something is very wrong. */
11862 internal_error (__FILE__, __LINE__,
11863 _("Fast tracepoint not "
11864 "valid during download"));
35b1e5cc 11865 }
e8ba3115
YQ
11866 else
11867 /* Fast tracepoints are functionally identical to regular
11868 tracepoints, so don't take lack of support as a reason to
11869 give up on the trace run. */
11870 warning (_("Target does not support fast tracepoints, "
11871 "downloading %d as regular tracepoint"), b->number);
11872 }
11873 else if (b->type == bp_static_tracepoint)
11874 {
11875 /* Only test for support at download time; we may not know
11876 target capabilities at definition time. */
11877 if (remote_supports_static_tracepoints ())
0fb4aa4b 11878 {
e8ba3115 11879 struct static_tracepoint_marker marker;
0fb4aa4b 11880
e8ba3115
YQ
11881 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11882 strcat (buf, ":S");
0fb4aa4b 11883 else
e8ba3115 11884 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11885 }
e8ba3115
YQ
11886 else
11887 /* Fast tracepoints are functionally identical to regular
11888 tracepoints, so don't take lack of support as a reason
11889 to give up on the trace run. */
11890 error (_("Target does not support static tracepoints"));
11891 }
11892 /* If the tracepoint has a conditional, make it into an agent
11893 expression and append to the definition. */
11894 if (loc->cond)
11895 {
11896 /* Only test support at download time, we may not know target
11897 capabilities at definition time. */
11898 if (remote_supports_cond_tracepoints ())
35b1e5cc 11899 {
e8ba3115
YQ
11900 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11901 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11902 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11903 aexpr->len);
e8ba3115
YQ
11904 pkt = buf + strlen (buf);
11905 for (ndx = 0; ndx < aexpr->len; ++ndx)
11906 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11907 *pkt = '\0';
11908 do_cleanups (aexpr_chain);
35b1e5cc 11909 }
e8ba3115
YQ
11910 else
11911 warning (_("Target does not support conditional tracepoints, "
11912 "ignoring tp %d cond"), b->number);
11913 }
35b1e5cc 11914
d9b3f62e 11915 if (b->commands || *default_collect)
e8ba3115
YQ
11916 strcat (buf, "-");
11917 putpkt (buf);
11918 remote_get_noisy_reply (&target_buf, &target_buf_size);
11919 if (strcmp (target_buf, "OK"))
11920 error (_("Target does not support tracepoints."));
35b1e5cc 11921
e8ba3115
YQ
11922 /* do_single_steps (t); */
11923 if (tdp_actions)
11924 {
11925 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11926 {
e8ba3115 11927 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11928 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11929 b->number, addrbuf, /* address */
11930 tdp_actions[ndx],
11931 ((tdp_actions[ndx + 1] || stepping_actions)
11932 ? '-' : 0));
e8ba3115
YQ
11933 putpkt (buf);
11934 remote_get_noisy_reply (&target_buf,
11935 &target_buf_size);
11936 if (strcmp (target_buf, "OK"))
11937 error (_("Error on target while setting tracepoints."));
35b1e5cc 11938 }
e8ba3115
YQ
11939 }
11940 if (stepping_actions)
11941 {
11942 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11943 {
e8ba3115 11944 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11945 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11946 b->number, addrbuf, /* address */
11947 ((ndx == 0) ? "S" : ""),
11948 stepping_actions[ndx],
11949 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11950 putpkt (buf);
11951 remote_get_noisy_reply (&target_buf,
11952 &target_buf_size);
11953 if (strcmp (target_buf, "OK"))
11954 error (_("Error on target while setting tracepoints."));
35b1e5cc 11955 }
e8ba3115 11956 }
409873ef 11957
4082afcc 11958 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11959 {
f00aae0f 11960 if (b->location != NULL)
409873ef 11961 {
e8ba3115 11962 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11963 encode_source_string (b->number, loc->address, "at",
11964 event_location_to_string (b->location),
11965 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11966 putpkt (buf);
11967 remote_get_noisy_reply (&target_buf, &target_buf_size);
11968 if (strcmp (target_buf, "OK"))
11969 warning (_("Target does not support source download."));
409873ef 11970 }
e8ba3115
YQ
11971 if (b->cond_string)
11972 {
11973 strcpy (buf, "QTDPsrc:");
11974 encode_source_string (b->number, loc->address,
11975 "cond", b->cond_string, buf + strlen (buf),
11976 2048 - strlen (buf));
11977 putpkt (buf);
11978 remote_get_noisy_reply (&target_buf, &target_buf_size);
11979 if (strcmp (target_buf, "OK"))
11980 warning (_("Target does not support source download."));
11981 }
11982 remote_download_command_source (b->number, loc->address,
11983 breakpoint_commands (b));
35b1e5cc 11984 }
e8ba3115
YQ
11985
11986 do_cleanups (old_chain);
35b1e5cc
SS
11987}
11988
1e4d1764 11989static int
a52a8357 11990remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 11991{
1e51243a
PA
11992 struct remote_state *rs = get_remote_state ();
11993 struct trace_status *ts;
11994 int status;
11995
11996 /* Don't try to install tracepoints until we've relocated our
11997 symbols, and fetched and merged the target's tracepoint list with
11998 ours. */
11999 if (rs->starting_up)
12000 return 0;
12001
12002 ts = current_trace_status ();
8bd200f1 12003 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
12004
12005 if (status == -1 || !ts->running_known || !ts->running)
12006 return 0;
12007
12008 /* If we are in a tracing experiment, but remote stub doesn't support
12009 installing tracepoint in trace, we have to return. */
12010 if (!remote_supports_install_in_trace ())
12011 return 0;
12012
12013 return 1;
12014}
12015
12016
35b1e5cc 12017static void
559d2b81
TT
12018remote_download_trace_state_variable (struct target_ops *self,
12019 struct trace_state_variable *tsv)
35b1e5cc
SS
12020{
12021 struct remote_state *rs = get_remote_state ();
00bf0b85 12022 char *p;
35b1e5cc 12023
bba74b36
YQ
12024 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12025 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
12026 tsv->builtin);
00bf0b85
SS
12027 p = rs->buf + strlen (rs->buf);
12028 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
12029 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 12030 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 12031 *p++ = '\0';
35b1e5cc
SS
12032 putpkt (rs->buf);
12033 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12034 if (*target_buf == '\0')
12035 error (_("Target does not support this command."));
12036 if (strcmp (target_buf, "OK") != 0)
12037 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
12038}
12039
d248b706 12040static void
46670d57
TT
12041remote_enable_tracepoint (struct target_ops *self,
12042 struct bp_location *location)
d248b706
KY
12043{
12044 struct remote_state *rs = get_remote_state ();
12045 char addr_buf[40];
12046
12047 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12048 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12049 location->owner->number, addr_buf);
d248b706
KY
12050 putpkt (rs->buf);
12051 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12052 if (*rs->buf == '\0')
12053 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12054 if (strcmp (rs->buf, "OK") != 0)
12055 error (_("Error on target while enabling tracepoint."));
12056}
12057
12058static void
780b049c
TT
12059remote_disable_tracepoint (struct target_ops *self,
12060 struct bp_location *location)
d248b706
KY
12061{
12062 struct remote_state *rs = get_remote_state ();
12063 char addr_buf[40];
12064
12065 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
12066 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12067 location->owner->number, addr_buf);
d248b706
KY
12068 putpkt (rs->buf);
12069 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12070 if (*rs->buf == '\0')
12071 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12072 if (strcmp (rs->buf, "OK") != 0)
12073 error (_("Error on target while disabling tracepoint."));
12074}
12075
35b1e5cc 12076static void
583f9a86 12077remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
12078{
12079 asection *s;
81b9b86e 12080 bfd *abfd = NULL;
35b1e5cc 12081 bfd_size_type size;
608bcef2 12082 bfd_vma vma;
35b1e5cc 12083 int anysecs = 0;
c2fa21f1 12084 int offset = 0;
35b1e5cc
SS
12085
12086 if (!exec_bfd)
12087 return; /* No information to give. */
12088
12089 strcpy (target_buf, "QTro");
9779ab84 12090 offset = strlen (target_buf);
35b1e5cc
SS
12091 for (s = exec_bfd->sections; s; s = s->next)
12092 {
12093 char tmp1[40], tmp2[40];
c2fa21f1 12094 int sec_length;
35b1e5cc
SS
12095
12096 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 12097 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
12098 (s->flags & SEC_READONLY) == 0)
12099 continue;
12100
12101 anysecs = 1;
81b9b86e 12102 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 12103 size = bfd_get_section_size (s);
608bcef2
HZ
12104 sprintf_vma (tmp1, vma);
12105 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
12106 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12107 if (offset + sec_length + 1 > target_buf_size)
12108 {
4082afcc 12109 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 12110 warning (_("\
c2fa21f1
HZ
12111Too many sections for read-only sections definition packet."));
12112 break;
12113 }
bba74b36
YQ
12114 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
12115 tmp1, tmp2);
c2fa21f1 12116 offset += sec_length;
35b1e5cc
SS
12117 }
12118 if (anysecs)
12119 {
12120 putpkt (target_buf);
12121 getpkt (&target_buf, &target_buf_size, 0);
12122 }
12123}
12124
12125static void
e2d1aae3 12126remote_trace_start (struct target_ops *self)
35b1e5cc
SS
12127{
12128 putpkt ("QTStart");
12129 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12130 if (*target_buf == '\0')
12131 error (_("Target does not support this command."));
12132 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12133 error (_("Bogus reply from target: %s"), target_buf);
12134}
12135
12136static int
8bd200f1 12137remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 12138{
953b98d1 12139 /* Initialize it just to avoid a GCC false warning. */
f652de6f 12140 char *p = NULL;
0df8b418 12141 /* FIXME we need to get register block size some other way. */
00bf0b85 12142 extern int trace_regblock_size;
bd3eecc3
PA
12143 enum packet_result result;
12144
4082afcc 12145 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 12146 return -1;
a744cf53 12147
00bf0b85
SS
12148 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
12149
049dc89b
JK
12150 putpkt ("qTStatus");
12151
492d29ea 12152 TRY
67f41397
JK
12153 {
12154 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
12155 }
492d29ea 12156 CATCH (ex, RETURN_MASK_ERROR)
67f41397 12157 {
598d3636
JK
12158 if (ex.error != TARGET_CLOSE_ERROR)
12159 {
12160 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12161 return -1;
12162 }
12163 throw_exception (ex);
67f41397 12164 }
492d29ea 12165 END_CATCH
00bf0b85 12166
bd3eecc3
PA
12167 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12168
00bf0b85 12169 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 12170 if (result == PACKET_UNKNOWN)
00bf0b85 12171 return -1;
35b1e5cc 12172
00bf0b85 12173 /* We're working with a live target. */
f5911ea1 12174 ts->filename = NULL;
00bf0b85 12175
00bf0b85 12176 if (*p++ != 'T')
35b1e5cc
SS
12177 error (_("Bogus trace status reply from target: %s"), target_buf);
12178
84cebc4a
YQ
12179 /* Function 'parse_trace_status' sets default value of each field of
12180 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
12181 parse_trace_status (p, ts);
12182
12183 return ts->running;
35b1e5cc
SS
12184}
12185
70221824 12186static void
db90e85c 12187remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
12188 struct uploaded_tp *utp)
12189{
12190 struct remote_state *rs = get_remote_state ();
f196051f
SS
12191 char *reply;
12192 struct bp_location *loc;
12193 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 12194 size_t size = get_remote_packet_size ();
f196051f
SS
12195
12196 if (tp)
12197 {
12198 tp->base.hit_count = 0;
12199 tp->traceframe_usage = 0;
12200 for (loc = tp->base.loc; loc; loc = loc->next)
12201 {
12202 /* If the tracepoint was never downloaded, don't go asking for
12203 any status. */
12204 if (tp->number_on_target == 0)
12205 continue;
bba74b36
YQ
12206 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12207 phex_nz (loc->address, 0));
f196051f
SS
12208 putpkt (rs->buf);
12209 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12210 if (reply && *reply)
12211 {
12212 if (*reply == 'V')
12213 parse_tracepoint_status (reply + 1, bp, utp);
12214 }
12215 }
12216 }
12217 else if (utp)
12218 {
12219 utp->hit_count = 0;
12220 utp->traceframe_usage = 0;
bba74b36
YQ
12221 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12222 phex_nz (utp->addr, 0));
f196051f
SS
12223 putpkt (rs->buf);
12224 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12225 if (reply && *reply)
12226 {
12227 if (*reply == 'V')
12228 parse_tracepoint_status (reply + 1, bp, utp);
12229 }
12230 }
12231}
12232
35b1e5cc 12233static void
74499f1b 12234remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
12235{
12236 putpkt ("QTStop");
12237 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
12238 if (*target_buf == '\0')
12239 error (_("Target does not support this command."));
12240 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
12241 error (_("Bogus reply from target: %s"), target_buf);
12242}
12243
12244static int
bd4c6793
TT
12245remote_trace_find (struct target_ops *self,
12246 enum trace_find_type type, int num,
cc5925ad 12247 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
12248 int *tpp)
12249{
12250 struct remote_state *rs = get_remote_state ();
bba74b36 12251 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
12252 char *p, *reply;
12253 int target_frameno = -1, target_tracept = -1;
12254
e6e4e701
PA
12255 /* Lookups other than by absolute frame number depend on the current
12256 trace selected, so make sure it is correct on the remote end
12257 first. */
12258 if (type != tfind_number)
12259 set_remote_traceframe ();
12260
35b1e5cc
SS
12261 p = rs->buf;
12262 strcpy (p, "QTFrame:");
12263 p = strchr (p, '\0');
12264 switch (type)
12265 {
12266 case tfind_number:
bba74b36 12267 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
12268 break;
12269 case tfind_pc:
bba74b36 12270 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
12271 break;
12272 case tfind_tp:
bba74b36 12273 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
12274 break;
12275 case tfind_range:
bba74b36
YQ
12276 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12277 phex_nz (addr2, 0));
35b1e5cc
SS
12278 break;
12279 case tfind_outside:
bba74b36
YQ
12280 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12281 phex_nz (addr2, 0));
35b1e5cc
SS
12282 break;
12283 default:
9b20d036 12284 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
12285 }
12286
12287 putpkt (rs->buf);
2f65bcb7 12288 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
12289 if (*reply == '\0')
12290 error (_("Target does not support this command."));
35b1e5cc
SS
12291
12292 while (reply && *reply)
12293 switch (*reply)
12294 {
12295 case 'F':
f197e0f1
VP
12296 p = ++reply;
12297 target_frameno = (int) strtol (p, &reply, 16);
12298 if (reply == p)
12299 error (_("Unable to parse trace frame number"));
e6e4e701
PA
12300 /* Don't update our remote traceframe number cache on failure
12301 to select a remote traceframe. */
f197e0f1
VP
12302 if (target_frameno == -1)
12303 return -1;
35b1e5cc
SS
12304 break;
12305 case 'T':
f197e0f1
VP
12306 p = ++reply;
12307 target_tracept = (int) strtol (p, &reply, 16);
12308 if (reply == p)
12309 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
12310 break;
12311 case 'O': /* "OK"? */
12312 if (reply[1] == 'K' && reply[2] == '\0')
12313 reply += 2;
12314 else
12315 error (_("Bogus reply from target: %s"), reply);
12316 break;
12317 default:
12318 error (_("Bogus reply from target: %s"), reply);
12319 }
12320 if (tpp)
12321 *tpp = target_tracept;
e6e4e701 12322
262e1174 12323 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
12324 return target_frameno;
12325}
12326
12327static int
4011015b
TT
12328remote_get_trace_state_variable_value (struct target_ops *self,
12329 int tsvnum, LONGEST *val)
35b1e5cc
SS
12330{
12331 struct remote_state *rs = get_remote_state ();
12332 char *reply;
12333 ULONGEST uval;
12334
e6e4e701
PA
12335 set_remote_traceframe ();
12336
bba74b36 12337 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
12338 putpkt (rs->buf);
12339 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12340 if (reply && *reply)
12341 {
12342 if (*reply == 'V')
12343 {
12344 unpack_varlen_hex (reply + 1, &uval);
12345 *val = (LONGEST) uval;
12346 return 1;
12347 }
12348 }
12349 return 0;
12350}
12351
00bf0b85 12352static int
dc3decaf 12353remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
12354{
12355 struct remote_state *rs = get_remote_state ();
12356 char *p, *reply;
12357
12358 p = rs->buf;
12359 strcpy (p, "QTSave:");
12360 p += strlen (p);
12361 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12362 error (_("Remote file name too long for trace save packet"));
9f1b45b0 12363 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
12364 *p++ = '\0';
12365 putpkt (rs->buf);
ad91cd99 12366 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 12367 if (*reply == '\0')
ad91cd99
PA
12368 error (_("Target does not support this command."));
12369 if (strcmp (reply, "OK") != 0)
12370 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
12371 return 0;
12372}
12373
12374/* This is basically a memory transfer, but needs to be its own packet
12375 because we don't know how the target actually organizes its trace
12376 memory, plus we want to be able to ask for as much as possible, but
12377 not be unhappy if we don't get as much as we ask for. */
12378
12379static LONGEST
88ee6f45
TT
12380remote_get_raw_trace_data (struct target_ops *self,
12381 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
12382{
12383 struct remote_state *rs = get_remote_state ();
12384 char *reply;
12385 char *p;
12386 int rslt;
12387
12388 p = rs->buf;
12389 strcpy (p, "qTBuffer:");
12390 p += strlen (p);
12391 p += hexnumstr (p, offset);
12392 *p++ = ',';
12393 p += hexnumstr (p, len);
12394 *p++ = '\0';
12395
12396 putpkt (rs->buf);
12397 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12398 if (reply && *reply)
12399 {
12400 /* 'l' by itself means we're at the end of the buffer and
12401 there is nothing more to get. */
12402 if (*reply == 'l')
12403 return 0;
12404
12405 /* Convert the reply into binary. Limit the number of bytes to
12406 convert according to our passed-in buffer size, rather than
12407 what was returned in the packet; if the target is
12408 unexpectedly generous and gives us a bigger reply than we
12409 asked for, we don't want to crash. */
12410 rslt = hex2bin (target_buf, buf, len);
12411 return rslt;
12412 }
12413
12414 /* Something went wrong, flag as an error. */
12415 return -1;
12416}
12417
35b1e5cc 12418static void
37b25738 12419remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
12420{
12421 struct remote_state *rs = get_remote_state ();
12422
4082afcc 12423 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 12424 {
ad91cd99
PA
12425 char *reply;
12426
bba74b36 12427 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 12428 putpkt (rs->buf);
ad91cd99
PA
12429 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12430 if (*reply == '\0')
33da3f1c 12431 error (_("Target does not support this command."));
ad91cd99
PA
12432 if (strcmp (reply, "OK") != 0)
12433 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
12434 }
12435 else if (val)
12436 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
12437}
12438
dc146f7c
VP
12439static int
12440remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12441{
12442 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 12443
fe978cb0
PA
12444 if (info && info->priv)
12445 return info->priv->core;
dc146f7c
VP
12446 return -1;
12447}
12448
4daf5ac0 12449static void
736d5b1f 12450remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
12451{
12452 struct remote_state *rs = get_remote_state ();
ad91cd99 12453 char *reply;
4daf5ac0 12454
bba74b36 12455 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 12456 putpkt (rs->buf);
ad91cd99
PA
12457 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12458 if (*reply == '\0')
4daf5ac0 12459 error (_("Target does not support this command."));
ad91cd99
PA
12460 if (strcmp (reply, "OK") != 0)
12461 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12462}
12463
b3b9301e 12464static struct traceframe_info *
a893e81f 12465remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12466{
12467 char *text;
12468
12469 text = target_read_stralloc (&current_target,
12470 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12471 if (text != NULL)
12472 {
12473 struct traceframe_info *info;
12474 struct cleanup *back_to = make_cleanup (xfree, text);
12475
12476 info = parse_traceframe_info (text);
12477 do_cleanups (back_to);
12478 return info;
12479 }
12480
12481 return NULL;
12482}
12483
405f8e94
SS
12484/* Handle the qTMinFTPILen packet. Returns the minimum length of
12485 instruction on which a fast tracepoint may be placed. Returns -1
12486 if the packet is not supported, and 0 if the minimum instruction
12487 length is unknown. */
12488
12489static int
0e67620a 12490remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12491{
12492 struct remote_state *rs = get_remote_state ();
12493 char *reply;
12494
e886a173
PA
12495 /* If we're not debugging a process yet, the IPA can't be
12496 loaded. */
12497 if (!target_has_execution)
12498 return 0;
12499
12500 /* Make sure the remote is pointing at the right process. */
12501 set_general_process ();
12502
bba74b36 12503 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12504 putpkt (rs->buf);
12505 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12506 if (*reply == '\0')
12507 return -1;
12508 else
12509 {
12510 ULONGEST min_insn_len;
12511
12512 unpack_varlen_hex (reply, &min_insn_len);
12513
12514 return (int) min_insn_len;
12515 }
12516}
12517
f6f899bf 12518static void
4da384be 12519remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12520{
4082afcc 12521 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12522 {
12523 struct remote_state *rs = get_remote_state ();
12524 char *buf = rs->buf;
12525 char *endbuf = rs->buf + get_remote_packet_size ();
12526 enum packet_result result;
12527
12528 gdb_assert (val >= 0 || val == -1);
12529 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12530 /* Send -1 as literal "-1" to avoid host size dependency. */
12531 if (val < 0)
12532 {
12533 *buf++ = '-';
12534 buf += hexnumstr (buf, (ULONGEST) -val);
12535 }
12536 else
12537 buf += hexnumstr (buf, (ULONGEST) val);
12538
12539 putpkt (rs->buf);
12540 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12541 result = packet_ok (rs->buf,
12542 &remote_protocol_packets[PACKET_QTBuffer_size]);
12543
12544 if (result != PACKET_OK)
12545 warning (_("Bogus reply from target: %s"), rs->buf);
12546 }
12547}
12548
f196051f 12549static int
d9e68a2c
TT
12550remote_set_trace_notes (struct target_ops *self,
12551 const char *user, const char *notes,
ca623f82 12552 const char *stop_notes)
f196051f
SS
12553{
12554 struct remote_state *rs = get_remote_state ();
12555 char *reply;
12556 char *buf = rs->buf;
12557 char *endbuf = rs->buf + get_remote_packet_size ();
12558 int nbytes;
12559
12560 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12561 if (user)
12562 {
12563 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12564 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12565 buf += 2 * nbytes;
12566 *buf++ = ';';
12567 }
12568 if (notes)
12569 {
12570 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12571 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12572 buf += 2 * nbytes;
12573 *buf++ = ';';
12574 }
12575 if (stop_notes)
12576 {
12577 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12578 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12579 buf += 2 * nbytes;
12580 *buf++ = ';';
12581 }
12582 /* Ensure the buffer is terminated. */
12583 *buf = '\0';
12584
12585 putpkt (rs->buf);
12586 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12587 if (*reply == '\0')
12588 return 0;
12589
12590 if (strcmp (reply, "OK") != 0)
12591 error (_("Bogus reply from target: %s"), reply);
12592
12593 return 1;
12594}
12595
d1feda86 12596static int
2c152180 12597remote_use_agent (struct target_ops *self, int use)
d1feda86 12598{
4082afcc 12599 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12600 {
12601 struct remote_state *rs = get_remote_state ();
12602
12603 /* If the stub supports QAgent. */
bba74b36 12604 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12605 putpkt (rs->buf);
12606 getpkt (&rs->buf, &rs->buf_size, 0);
12607
12608 if (strcmp (rs->buf, "OK") == 0)
12609 {
12610 use_agent = use;
12611 return 1;
12612 }
12613 }
12614
12615 return 0;
12616}
12617
12618static int
fe38f897 12619remote_can_use_agent (struct target_ops *self)
d1feda86 12620{
4082afcc 12621 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12622}
12623
9accd112
MM
12624struct btrace_target_info
12625{
12626 /* The ptid of the traced thread. */
12627 ptid_t ptid;
f4abbc16
MM
12628
12629 /* The obtained branch trace configuration. */
12630 struct btrace_config conf;
9accd112
MM
12631};
12632
f4abbc16
MM
12633/* Reset our idea of our target's btrace configuration. */
12634
12635static void
12636remote_btrace_reset (void)
12637{
12638 struct remote_state *rs = get_remote_state ();
12639
12640 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12641}
12642
9accd112
MM
12643/* Check whether the target supports branch tracing. */
12644
12645static int
043c3577 12646remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12647{
4082afcc 12648 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12649 return 0;
4082afcc 12650 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12651 return 0;
12652
043c3577
MM
12653 switch (format)
12654 {
12655 case BTRACE_FORMAT_NONE:
12656 return 0;
12657
12658 case BTRACE_FORMAT_BTS:
12659 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12660
12661 case BTRACE_FORMAT_PT:
12662 /* The trace is decoded on the host. Even if our target supports it,
12663 we still need to have libipt to decode the trace. */
12664#if defined (HAVE_LIBIPT)
12665 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12666#else /* !defined (HAVE_LIBIPT) */
12667 return 0;
12668#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12669 }
12670
12671 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12672}
12673
f4abbc16
MM
12674/* Synchronize the configuration with the target. */
12675
12676static void
12677btrace_sync_conf (const struct btrace_config *conf)
12678{
d33501a5
MM
12679 struct packet_config *packet;
12680 struct remote_state *rs;
12681 char *buf, *pos, *endbuf;
12682
12683 rs = get_remote_state ();
12684 buf = rs->buf;
12685 endbuf = buf + get_remote_packet_size ();
12686
12687 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12688 if (packet_config_support (packet) == PACKET_ENABLE
12689 && conf->bts.size != rs->btrace_config.bts.size)
12690 {
12691 pos = buf;
12692 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12693 conf->bts.size);
12694
12695 putpkt (buf);
12696 getpkt (&buf, &rs->buf_size, 0);
12697
12698 if (packet_ok (buf, packet) == PACKET_ERROR)
12699 {
12700 if (buf[0] == 'E' && buf[1] == '.')
12701 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12702 else
12703 error (_("Failed to configure the BTS buffer size."));
12704 }
12705
12706 rs->btrace_config.bts.size = conf->bts.size;
12707 }
b20a6524
MM
12708
12709 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12710 if (packet_config_support (packet) == PACKET_ENABLE
12711 && conf->pt.size != rs->btrace_config.pt.size)
12712 {
12713 pos = buf;
12714 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12715 conf->pt.size);
12716
12717 putpkt (buf);
12718 getpkt (&buf, &rs->buf_size, 0);
12719
12720 if (packet_ok (buf, packet) == PACKET_ERROR)
12721 {
12722 if (buf[0] == 'E' && buf[1] == '.')
12723 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12724 else
12725 error (_("Failed to configure the trace buffer size."));
12726 }
12727
12728 rs->btrace_config.pt.size = conf->pt.size;
12729 }
f4abbc16
MM
12730}
12731
12732/* Read the current thread's btrace configuration from the target and
12733 store it into CONF. */
12734
12735static void
12736btrace_read_config (struct btrace_config *conf)
12737{
12738 char *xml;
12739
12740 xml = target_read_stralloc (&current_target,
b20a6524 12741 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12742 if (xml != NULL)
12743 {
12744 struct cleanup *cleanup;
12745
12746 cleanup = make_cleanup (xfree, xml);
12747 parse_xml_btrace_conf (conf, xml);
12748 do_cleanups (cleanup);
12749 }
12750}
12751
9accd112
MM
12752/* Enable branch tracing. */
12753
12754static struct btrace_target_info *
f4abbc16
MM
12755remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12756 const struct btrace_config *conf)
9accd112
MM
12757{
12758 struct btrace_target_info *tinfo = NULL;
b20a6524 12759 struct packet_config *packet = NULL;
9accd112
MM
12760 struct remote_state *rs = get_remote_state ();
12761 char *buf = rs->buf;
12762 char *endbuf = rs->buf + get_remote_packet_size ();
12763
b20a6524
MM
12764 switch (conf->format)
12765 {
12766 case BTRACE_FORMAT_BTS:
12767 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12768 break;
12769
12770 case BTRACE_FORMAT_PT:
12771 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12772 break;
12773 }
12774
12775 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12776 error (_("Target does not support branch tracing."));
12777
f4abbc16
MM
12778 btrace_sync_conf (conf);
12779
9accd112
MM
12780 set_general_thread (ptid);
12781
12782 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12783 putpkt (rs->buf);
12784 getpkt (&rs->buf, &rs->buf_size, 0);
12785
12786 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12787 {
12788 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12789 error (_("Could not enable branch tracing for %s: %s"),
12790 target_pid_to_str (ptid), rs->buf + 2);
12791 else
12792 error (_("Could not enable branch tracing for %s."),
12793 target_pid_to_str (ptid));
12794 }
12795
8d749320 12796 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12797 tinfo->ptid = ptid;
12798
f4abbc16
MM
12799 /* If we fail to read the configuration, we lose some information, but the
12800 tracing itself is not impacted. */
492d29ea
PA
12801 TRY
12802 {
12803 btrace_read_config (&tinfo->conf);
12804 }
12805 CATCH (err, RETURN_MASK_ERROR)
12806 {
12807 if (err.message != NULL)
12808 warning ("%s", err.message);
12809 }
12810 END_CATCH
f4abbc16 12811
9accd112
MM
12812 return tinfo;
12813}
12814
12815/* Disable branch tracing. */
12816
12817static void
25e95349
TT
12818remote_disable_btrace (struct target_ops *self,
12819 struct btrace_target_info *tinfo)
9accd112
MM
12820{
12821 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12822 struct remote_state *rs = get_remote_state ();
12823 char *buf = rs->buf;
12824 char *endbuf = rs->buf + get_remote_packet_size ();
12825
4082afcc 12826 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12827 error (_("Target does not support branch tracing."));
12828
12829 set_general_thread (tinfo->ptid);
12830
12831 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12832 putpkt (rs->buf);
12833 getpkt (&rs->buf, &rs->buf_size, 0);
12834
12835 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12836 {
12837 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12838 error (_("Could not disable branch tracing for %s: %s"),
12839 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12840 else
12841 error (_("Could not disable branch tracing for %s."),
12842 target_pid_to_str (tinfo->ptid));
12843 }
12844
12845 xfree (tinfo);
12846}
12847
12848/* Teardown branch tracing. */
12849
12850static void
1777056d
TT
12851remote_teardown_btrace (struct target_ops *self,
12852 struct btrace_target_info *tinfo)
9accd112
MM
12853{
12854 /* We must not talk to the target during teardown. */
12855 xfree (tinfo);
12856}
12857
12858/* Read the branch trace. */
12859
969c39fb 12860static enum btrace_error
39c49f83 12861remote_read_btrace (struct target_ops *self,
734b0e4b 12862 struct btrace_data *btrace,
969c39fb 12863 struct btrace_target_info *tinfo,
9accd112
MM
12864 enum btrace_read_type type)
12865{
12866 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
969c39fb 12867 struct cleanup *cleanup;
9accd112
MM
12868 const char *annex;
12869 char *xml;
12870
4082afcc 12871 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12872 error (_("Target does not support branch tracing."));
12873
12874#if !defined(HAVE_LIBEXPAT)
12875 error (_("Cannot process branch tracing result. XML parsing not supported."));
12876#endif
12877
12878 switch (type)
12879 {
864089d2 12880 case BTRACE_READ_ALL:
9accd112
MM
12881 annex = "all";
12882 break;
864089d2 12883 case BTRACE_READ_NEW:
9accd112
MM
12884 annex = "new";
12885 break;
969c39fb
MM
12886 case BTRACE_READ_DELTA:
12887 annex = "delta";
12888 break;
9accd112
MM
12889 default:
12890 internal_error (__FILE__, __LINE__,
12891 _("Bad branch tracing read type: %u."),
12892 (unsigned int) type);
12893 }
12894
12895 xml = target_read_stralloc (&current_target,
b20a6524 12896 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12897 if (xml == NULL)
12898 return BTRACE_ERR_UNKNOWN;
9accd112 12899
969c39fb 12900 cleanup = make_cleanup (xfree, xml);
734b0e4b 12901 parse_xml_btrace (btrace, xml);
969c39fb 12902 do_cleanups (cleanup);
9accd112 12903
969c39fb 12904 return BTRACE_ERR_NONE;
9accd112
MM
12905}
12906
f4abbc16
MM
12907static const struct btrace_config *
12908remote_btrace_conf (struct target_ops *self,
12909 const struct btrace_target_info *tinfo)
12910{
12911 return &tinfo->conf;
12912}
12913
ced63ec0 12914static int
5436ff03 12915remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12916{
4082afcc
PA
12917 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12918 == PACKET_ENABLE);
ced63ec0
GB
12919}
12920
9dd130a0
TT
12921/* Implementation of to_load. */
12922
12923static void
9cbe5fff 12924remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12925{
12926 generic_load (name, from_tty);
12927}
12928
c78fa86a
GB
12929/* Accepts an integer PID; returns a string representing a file that
12930 can be opened on the remote side to get the symbols for the child
12931 process. Returns NULL if the operation is not supported. */
12932
12933static char *
12934remote_pid_to_exec_file (struct target_ops *self, int pid)
12935{
12936 static char *filename = NULL;
835205d0
GB
12937 struct inferior *inf;
12938 char *annex = NULL;
c78fa86a
GB
12939
12940 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12941 return NULL;
12942
12943 if (filename != NULL)
12944 xfree (filename);
12945
835205d0
GB
12946 inf = find_inferior_pid (pid);
12947 if (inf == NULL)
12948 internal_error (__FILE__, __LINE__,
12949 _("not currently attached to process %d"), pid);
12950
12951 if (!inf->fake_pid_p)
12952 {
12953 const int annex_size = 9;
12954
224c3ddb 12955 annex = (char *) alloca (annex_size);
835205d0
GB
12956 xsnprintf (annex, annex_size, "%x", pid);
12957 }
12958
c78fa86a
GB
12959 filename = target_read_stralloc (&current_target,
12960 TARGET_OBJECT_EXEC_FILE, annex);
12961
12962 return filename;
12963}
12964
750ce8d1
YQ
12965/* Implement the to_can_do_single_step target_ops method. */
12966
12967static int
12968remote_can_do_single_step (struct target_ops *ops)
12969{
12970 /* We can only tell whether target supports single step or not by
12971 supported s and S vCont actions if the stub supports vContSupported
12972 feature. If the stub doesn't support vContSupported feature,
12973 we have conservatively to think target doesn't supports single
12974 step. */
12975 if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
12976 {
12977 struct remote_state *rs = get_remote_state ();
12978
12979 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12980 remote_vcont_probe (rs);
12981
12982 return rs->supports_vCont.s && rs->supports_vCont.S;
12983 }
12984 else
12985 return 0;
12986}
12987
c906108c 12988static void
fba45db2 12989init_remote_ops (void)
c906108c 12990{
c5aa993b 12991 remote_ops.to_shortname = "remote";
c906108c 12992 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 12993 remote_ops.to_doc =
c906108c 12994 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
12995Specify the serial device it is connected to\n\
12996(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
12997 remote_ops.to_open = remote_open;
12998 remote_ops.to_close = remote_close;
c906108c 12999 remote_ops.to_detach = remote_detach;
6ad8ae5c 13000 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 13001 remote_ops.to_resume = remote_resume;
c906108c
SS
13002 remote_ops.to_wait = remote_wait;
13003 remote_ops.to_fetch_registers = remote_fetch_registers;
13004 remote_ops.to_store_registers = remote_store_registers;
13005 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 13006 remote_ops.to_files_info = remote_files_info;
c906108c
SS
13007 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13008 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
13009 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13010 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13011 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13012 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
13013 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13014 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
13015 remote_ops.to_watchpoint_addr_within_range =
13016 remote_watchpoint_addr_within_range;
3c3bea1c
GS
13017 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13018 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13019 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
13020 remote_ops.to_region_ok_for_hw_watchpoint
13021 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
13022 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13023 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 13024 remote_ops.to_kill = remote_kill;
9dd130a0 13025 remote_ops.to_load = remote_load;
c906108c 13026 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 13027 remote_ops.to_pass_signals = remote_pass_signals;
82075af2 13028 remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
9b224c5e 13029 remote_ops.to_program_signals = remote_program_signals;
c906108c 13030 remote_ops.to_thread_alive = remote_thread_alive;
79efa585 13031 remote_ops.to_thread_name = remote_thread_name;
e8032dde 13032 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 13033 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 13034 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 13035 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 13036 remote_ops.to_stop = remote_stop;
bfedc46a 13037 remote_ops.to_interrupt = remote_interrupt;
93692b58 13038 remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
4b8a223f 13039 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 13040 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 13041 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 13042 remote_ops.to_log_command = serial_log_command;
38691318 13043 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 13044 remote_ops.to_stratum = process_stratum;
c35b1492
PA
13045 remote_ops.to_has_all_memory = default_child_has_all_memory;
13046 remote_ops.to_has_memory = default_child_has_memory;
13047 remote_ops.to_has_stack = default_child_has_stack;
13048 remote_ops.to_has_registers = default_child_has_registers;
13049 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 13050 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 13051 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 13052 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 13053 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
13054 remote_ops.to_flash_erase = remote_flash_erase;
13055 remote_ops.to_flash_done = remote_flash_done;
29709017 13056 remote_ops.to_read_description = remote_read_description;
08388c79 13057 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
13058 remote_ops.to_can_async_p = remote_can_async_p;
13059 remote_ops.to_is_async_p = remote_is_async_p;
13060 remote_ops.to_async = remote_async;
65706a29 13061 remote_ops.to_thread_events = remote_thread_events;
750ce8d1 13062 remote_ops.to_can_do_single_step = remote_can_do_single_step;
75c99385
PA
13063 remote_ops.to_terminal_inferior = remote_terminal_inferior;
13064 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 13065 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 13066 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
13067 remote_ops.to_supports_disable_randomization
13068 = remote_supports_disable_randomization;
4bd7dc42 13069 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
13070 remote_ops.to_fileio_open = remote_hostio_open;
13071 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13072 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 13073 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
13074 remote_ops.to_fileio_close = remote_hostio_close;
13075 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 13076 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 13077 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 13078 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 13079 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 13080 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
13081 remote_ops.to_trace_init = remote_trace_init;
13082 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 13083 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
13084 remote_ops.to_download_trace_state_variable
13085 = remote_download_trace_state_variable;
d248b706
KY
13086 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13087 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
13088 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13089 remote_ops.to_trace_start = remote_trace_start;
13090 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 13091 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
13092 remote_ops.to_trace_stop = remote_trace_stop;
13093 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
13094 remote_ops.to_get_trace_state_variable_value
13095 = remote_get_trace_state_variable_value;
00bf0b85
SS
13096 remote_ops.to_save_trace_data = remote_save_trace_data;
13097 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
13098 remote_ops.to_upload_trace_state_variables
13099 = remote_upload_trace_state_variables;
00bf0b85 13100 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 13101 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 13102 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 13103 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 13104 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 13105 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 13106 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 13107 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 13108 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 13109 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
13110 remote_ops.to_static_tracepoint_marker_at
13111 = remote_static_tracepoint_marker_at;
13112 remote_ops.to_static_tracepoint_markers_by_strid
13113 = remote_static_tracepoint_markers_by_strid;
b3b9301e 13114 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
13115 remote_ops.to_use_agent = remote_use_agent;
13116 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
13117 remote_ops.to_supports_btrace = remote_supports_btrace;
13118 remote_ops.to_enable_btrace = remote_enable_btrace;
13119 remote_ops.to_disable_btrace = remote_disable_btrace;
13120 remote_ops.to_teardown_btrace = remote_teardown_btrace;
13121 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 13122 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
13123 remote_ops.to_augmented_libraries_svr4_read =
13124 remote_augmented_libraries_svr4_read;
8020350c
DB
13125 remote_ops.to_follow_fork = remote_follow_fork;
13126 remote_ops.to_follow_exec = remote_follow_exec;
13127 remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13128 remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13129 remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13130 remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13131 remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13132 remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
c906108c
SS
13133}
13134
13135/* Set up the extended remote vector by making a copy of the standard
13136 remote vector and adding to it. */
13137
13138static void
fba45db2 13139init_extended_remote_ops (void)
c906108c
SS
13140{
13141 extended_remote_ops = remote_ops;
13142
0f71a2f6 13143 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 13144 extended_remote_ops.to_longname =
c906108c 13145 "Extended remote serial target in gdb-specific protocol";
c5aa993b 13146 extended_remote_ops.to_doc =
c906108c 13147 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
13148Specify the serial device it is connected to (e.g. /dev/ttya).";
13149 extended_remote_ops.to_open = extended_remote_open;
c906108c 13150 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
2d717e4f
DJ
13151 extended_remote_ops.to_detach = extended_remote_detach;
13152 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 13153 extended_remote_ops.to_post_attach = extended_remote_post_attach;
03583c20
UW
13154 extended_remote_ops.to_supports_disable_randomization
13155 = extended_remote_supports_disable_randomization;
0f71a2f6
JM
13156}
13157
6426a772 13158static int
6a109b6b 13159remote_can_async_p (struct target_ops *ops)
6426a772 13160{
5d93a237
TT
13161 struct remote_state *rs = get_remote_state ();
13162
c6ebd6cf 13163 if (!target_async_permitted)
75c99385
PA
13164 /* We only enable async when the user specifically asks for it. */
13165 return 0;
13166
23860348 13167 /* We're async whenever the serial device is. */
5d93a237 13168 return serial_can_async_p (rs->remote_desc);
6426a772
JM
13169}
13170
13171static int
6a109b6b 13172remote_is_async_p (struct target_ops *ops)
6426a772 13173{
5d93a237
TT
13174 struct remote_state *rs = get_remote_state ();
13175
c6ebd6cf 13176 if (!target_async_permitted)
75c99385
PA
13177 /* We only enable async when the user specifically asks for it. */
13178 return 0;
13179
23860348 13180 /* We're async whenever the serial device is. */
5d93a237 13181 return serial_is_async_p (rs->remote_desc);
6426a772
JM
13182}
13183
2acceee2
JM
13184/* Pass the SERIAL event on and up to the client. One day this code
13185 will be able to delay notifying the client of an event until the
23860348 13186 point where an entire packet has been received. */
2acceee2 13187
2acceee2
JM
13188static serial_event_ftype remote_async_serial_handler;
13189
6426a772 13190static void
819cc324 13191remote_async_serial_handler (struct serial *scb, void *context)
6426a772 13192{
2acceee2
JM
13193 /* Don't propogate error information up to the client. Instead let
13194 the client find out about the error by querying the target. */
6a3753b3 13195 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
13196}
13197
74531fed
PA
13198static void
13199remote_async_inferior_event_handler (gdb_client_data data)
13200{
13201 inferior_event_handler (INF_REG_EVENT, NULL);
13202}
13203
2acceee2 13204static void
6a3753b3 13205remote_async (struct target_ops *ops, int enable)
2acceee2 13206{
5d93a237
TT
13207 struct remote_state *rs = get_remote_state ();
13208
6a3753b3 13209 if (enable)
2acceee2 13210 {
88b496c3 13211 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
13212
13213 /* If there are pending events in the stop reply queue tell the
13214 event loop to process them. */
13215 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13216 mark_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13217 /* For simplicity, below we clear the pending events token
13218 without remembering whether it is marked, so here we always
13219 mark it. If there's actually no pending notification to
13220 process, this ends up being a no-op (other than a spurious
13221 event-loop wakeup). */
13222 if (target_is_non_stop_p ())
13223 mark_async_event_handler (rs->notif_state->get_pending_events_token);
2acceee2
JM
13224 }
13225 else
b7d2e916
PA
13226 {
13227 serial_async (rs->remote_desc, NULL, NULL);
6efcd9a8
PA
13228 /* If the core is disabling async, it doesn't want to be
13229 disturbed with target events. Clear all async event sources
13230 too. */
b7d2e916 13231 clear_async_event_handler (remote_async_inferior_event_token);
6efcd9a8
PA
13232 if (target_is_non_stop_p ())
13233 clear_async_event_handler (rs->notif_state->get_pending_events_token);
b7d2e916 13234 }
6426a772
JM
13235}
13236
65706a29
PA
13237/* Implementation of the to_thread_events method. */
13238
13239static void
13240remote_thread_events (struct target_ops *ops, int enable)
13241{
13242 struct remote_state *rs = get_remote_state ();
13243 size_t size = get_remote_packet_size ();
65706a29
PA
13244
13245 if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13246 return;
13247
13248 xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13249 putpkt (rs->buf);
13250 getpkt (&rs->buf, &rs->buf_size, 0);
13251
13252 switch (packet_ok (rs->buf,
13253 &remote_protocol_packets[PACKET_QThreadEvents]))
13254 {
13255 case PACKET_OK:
13256 if (strcmp (rs->buf, "OK") != 0)
13257 error (_("Remote refused setting thread events: %s"), rs->buf);
13258 break;
13259 case PACKET_ERROR:
13260 warning (_("Remote failure reply: %s"), rs->buf);
13261 break;
13262 case PACKET_UNKNOWN:
13263 break;
13264 }
13265}
13266
5a2468f5 13267static void
c2d11a7d 13268set_remote_cmd (char *args, int from_tty)
5a2468f5 13269{
635c7e8a 13270 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
13271}
13272
d471ea57
AC
13273static void
13274show_remote_cmd (char *args, int from_tty)
13275{
37a105a1 13276 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 13277 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
13278 struct cleanup *showlist_chain;
13279 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 13280 struct ui_out *uiout = current_uiout;
37a105a1
DJ
13281
13282 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
13283 for (; list != NULL; list = list->next)
13284 if (strcmp (list->name, "Z-packet") == 0)
13285 continue;
427c3a89
DJ
13286 else if (list->type == not_set_cmd)
13287 /* Alias commands are exactly like the original, except they
13288 don't have the normal type. */
13289 continue;
13290 else
37a105a1
DJ
13291 {
13292 struct cleanup *option_chain
13293 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 13294
37a105a1
DJ
13295 ui_out_field_string (uiout, "name", list->name);
13296 ui_out_text (uiout, ": ");
427c3a89 13297 if (list->type == show_cmd)
5b9afe8a 13298 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
13299 else
13300 cmd_func (list, NULL, from_tty);
37a105a1
DJ
13301 /* Close the tuple. */
13302 do_cleanups (option_chain);
13303 }
427c3a89
DJ
13304
13305 /* Close the tuple. */
13306 do_cleanups (showlist_chain);
d471ea57 13307}
5a2468f5 13308
0f71a2f6 13309
23860348 13310/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
13311static void
13312remote_new_objfile (struct objfile *objfile)
13313{
5d93a237
TT
13314 struct remote_state *rs = get_remote_state ();
13315
13316 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 13317 remote_check_symbols ();
dc8acb97
MS
13318}
13319
00bf0b85
SS
13320/* Pull all the tracepoints defined on the target and create local
13321 data structures representing them. We don't want to create real
13322 tracepoints yet, we don't want to mess up the user's existing
13323 collection. */
13324
13325static int
ab6617cc 13326remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 13327{
00bf0b85
SS
13328 struct remote_state *rs = get_remote_state ();
13329 char *p;
d5551862 13330
00bf0b85
SS
13331 /* Ask for a first packet of tracepoint definition. */
13332 putpkt ("qTfP");
13333 getpkt (&rs->buf, &rs->buf_size, 0);
13334 p = rs->buf;
13335 while (*p && *p != 'l')
d5551862 13336 {
00bf0b85
SS
13337 parse_tracepoint_definition (p, utpp);
13338 /* Ask for another packet of tracepoint definition. */
13339 putpkt ("qTsP");
13340 getpkt (&rs->buf, &rs->buf_size, 0);
13341 p = rs->buf;
d5551862 13342 }
00bf0b85 13343 return 0;
d5551862
SS
13344}
13345
00bf0b85 13346static int
181e3713
TT
13347remote_upload_trace_state_variables (struct target_ops *self,
13348 struct uploaded_tsv **utsvp)
d5551862 13349{
00bf0b85 13350 struct remote_state *rs = get_remote_state ();
d5551862 13351 char *p;
d5551862 13352
00bf0b85
SS
13353 /* Ask for a first packet of variable definition. */
13354 putpkt ("qTfV");
d5551862
SS
13355 getpkt (&rs->buf, &rs->buf_size, 0);
13356 p = rs->buf;
00bf0b85 13357 while (*p && *p != 'l')
d5551862 13358 {
00bf0b85
SS
13359 parse_tsv_definition (p, utsvp);
13360 /* Ask for another packet of variable definition. */
13361 putpkt ("qTsV");
d5551862
SS
13362 getpkt (&rs->buf, &rs->buf_size, 0);
13363 p = rs->buf;
13364 }
00bf0b85 13365 return 0;
d5551862
SS
13366}
13367
c1e36e3e
PA
13368/* The "set/show range-stepping" show hook. */
13369
13370static void
13371show_range_stepping (struct ui_file *file, int from_tty,
13372 struct cmd_list_element *c,
13373 const char *value)
13374{
13375 fprintf_filtered (file,
13376 _("Debugger's willingness to use range stepping "
13377 "is %s.\n"), value);
13378}
13379
13380/* The "set/show range-stepping" set hook. */
13381
13382static void
13383set_range_stepping (char *ignore_args, int from_tty,
13384 struct cmd_list_element *c)
13385{
5d93a237
TT
13386 struct remote_state *rs = get_remote_state ();
13387
c1e36e3e
PA
13388 /* Whene enabling, check whether range stepping is actually
13389 supported by the target, and warn if not. */
13390 if (use_range_stepping)
13391 {
5d93a237 13392 if (rs->remote_desc != NULL)
c1e36e3e 13393 {
4082afcc 13394 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
13395 remote_vcont_probe (rs);
13396
4082afcc 13397 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
13398 && rs->supports_vCont.r)
13399 return;
13400 }
13401
13402 warning (_("Range stepping is not supported by the current target"));
13403 }
13404}
13405
c906108c 13406void
fba45db2 13407_initialize_remote (void)
c906108c 13408{
9a7071a8 13409 struct cmd_list_element *cmd;
6f937416 13410 const char *cmd_name;
ea9c271d 13411
0f71a2f6 13412 /* architecture specific data */
2bc416ba 13413 remote_gdbarch_data_handle =
23860348 13414 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
13415 remote_g_packet_data_handle =
13416 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 13417
94585166
DB
13418 remote_pspace_data
13419 = register_program_space_data_with_cleanup (NULL,
13420 remote_pspace_data_cleanup);
13421
ea9c271d
DJ
13422 /* Initialize the per-target state. At the moment there is only one
13423 of these, not one per target. Only one target is active at a
cf792862
TT
13424 time. */
13425 remote_state = new_remote_state ();
ea9c271d 13426
c906108c
SS
13427 init_remote_ops ();
13428 add_target (&remote_ops);
13429
13430 init_extended_remote_ops ();
13431 add_target (&extended_remote_ops);
cce74817 13432
dc8acb97 13433 /* Hook into new objfile notification. */
06d3b283 13434 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
13435 /* We're no longer interested in notification events of an inferior
13436 when it exits. */
13437 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 13438
c906108c
SS
13439#if 0
13440 init_remote_threadtests ();
13441#endif
13442
722247f1 13443 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 13444 /* set/show remote ... */
d471ea57 13445
1bedd215 13446 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
13447Remote protocol specific variables\n\
13448Configure various remote-protocol specific variables such as\n\
1bedd215 13449the packets being used"),
cff3e48b 13450 &remote_set_cmdlist, "set remote ",
23860348 13451 0 /* allow-unknown */, &setlist);
1bedd215 13452 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
13453Remote protocol specific variables\n\
13454Configure various remote-protocol specific variables such as\n\
1bedd215 13455the packets being used"),
cff3e48b 13456 &remote_show_cmdlist, "show remote ",
23860348 13457 0 /* allow-unknown */, &showlist);
5a2468f5 13458
1a966eab
AC
13459 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13460Compare section data on target to the exec file.\n\
95cf3b38
DT
13461Argument is a single section name (default: all loaded sections).\n\
13462To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
13463 &cmdlist);
13464
1a966eab
AC
13465 add_cmd ("packet", class_maintenance, packet_command, _("\
13466Send an arbitrary packet to a remote target.\n\
c906108c
SS
13467 maintenance packet TEXT\n\
13468If GDB is talking to an inferior via the GDB serial protocol, then\n\
13469this command sends the string TEXT to the inferior, and displays the\n\
13470response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 13471terminating `#' character and checksum."),
c906108c
SS
13472 &maintenancelist);
13473
7915a72c
AC
13474 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13475Set whether to send break if interrupted."), _("\
13476Show whether to send break if interrupted."), _("\
13477If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 13478 set_remotebreak, show_remotebreak,
e707bbc2 13479 &setlist, &showlist);
9a7071a8
JB
13480 cmd_name = "remotebreak";
13481 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13482 deprecate_cmd (cmd, "set remote interrupt-sequence");
13483 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13484 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13485 deprecate_cmd (cmd, "show remote interrupt-sequence");
13486
13487 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
13488 interrupt_sequence_modes, &interrupt_sequence_mode,
13489 _("\
9a7071a8
JB
13490Set interrupt sequence to remote target."), _("\
13491Show interrupt sequence to remote target."), _("\
13492Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13493 NULL, show_interrupt_sequence,
13494 &remote_set_cmdlist,
13495 &remote_show_cmdlist);
13496
13497 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13498 &interrupt_on_connect, _("\
13499Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13500Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
13501If set, interrupt sequence is sent to remote target."),
13502 NULL, NULL,
13503 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 13504
23860348 13505 /* Install commands for configuring memory read/write packets. */
11cf8741 13506
1a966eab
AC
13507 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13508Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 13509 &setlist);
1a966eab
AC
13510 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13511Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
13512 &showlist);
13513 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
13514 set_memory_write_packet_size, _("\
13515Set the maximum number of bytes per memory-write packet.\n\
13516Specify the number of bytes in a packet or 0 (zero) for the\n\
13517default packet size. The actual limit is further reduced\n\
13518dependent on the target. Specify ``fixed'' to disable the\n\
13519further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13520 &remote_set_cmdlist);
13521 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13522 set_memory_read_packet_size, _("\
13523Set the maximum number of bytes per memory-read packet.\n\
13524Specify the number of bytes in a packet or 0 (zero) for the\n\
13525default packet size. The actual limit is further reduced\n\
13526dependent on the target. Specify ``fixed'' to disable the\n\
13527further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13528 &remote_set_cmdlist);
13529 add_cmd ("memory-write-packet-size", no_class,
13530 show_memory_write_packet_size,
1a966eab 13531 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13532 &remote_show_cmdlist);
13533 add_cmd ("memory-read-packet-size", no_class,
13534 show_memory_read_packet_size,
1a966eab 13535 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13536 &remote_show_cmdlist);
c906108c 13537
b3f42336 13538 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13539 &remote_hw_watchpoint_limit, _("\
13540Set the maximum number of target hardware watchpoints."), _("\
13541Show the maximum number of target hardware watchpoints."), _("\
13542Specify a negative limit for unlimited."),
3e43a32a
MS
13543 NULL, NULL, /* FIXME: i18n: The maximum
13544 number of target hardware
13545 watchpoints is %s. */
b3f42336 13546 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13547 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13548 &remote_hw_watchpoint_length_limit, _("\
13549Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13550Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13551Specify a negative limit for unlimited."),
13552 NULL, NULL, /* FIXME: i18n: The maximum
13553 length (in bytes) of a target
13554 hardware watchpoint is %s. */
13555 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13556 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13557 &remote_hw_breakpoint_limit, _("\
13558Set the maximum number of target hardware breakpoints."), _("\
13559Show the maximum number of target hardware breakpoints."), _("\
13560Specify a negative limit for unlimited."),
3e43a32a
MS
13561 NULL, NULL, /* FIXME: i18n: The maximum
13562 number of target hardware
13563 breakpoints is %s. */
b3f42336 13564 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13565
1b493192
PA
13566 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13567 &remote_address_size, _("\
4d28ad1e
AC
13568Set the maximum size of the address (in bits) in a memory packet."), _("\
13569Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13570 NULL,
13571 NULL, /* FIXME: i18n: */
13572 &setlist, &showlist);
c906108c 13573
ca4f7f8b
PA
13574 init_all_packet_configs ();
13575
444abaca 13576 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13577 "X", "binary-download", 1);
0f71a2f6 13578
444abaca 13579 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13580 "vCont", "verbose-resume", 0);
506fb367 13581
89be2091
DJ
13582 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13583 "QPassSignals", "pass-signals", 0);
13584
82075af2
JS
13585 add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
13586 "QCatchSyscalls", "catch-syscalls", 0);
13587
9b224c5e
PA
13588 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13589 "QProgramSignals", "program-signals", 0);
13590
444abaca 13591 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13592 "qSymbol", "symbol-lookup", 0);
dc8acb97 13593
444abaca 13594 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13595 "P", "set-register", 1);
d471ea57 13596
444abaca 13597 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13598 "p", "fetch-register", 1);
b96ec7ac 13599
444abaca 13600 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13601 "Z0", "software-breakpoint", 0);
d471ea57 13602
444abaca 13603 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13604 "Z1", "hardware-breakpoint", 0);
d471ea57 13605
444abaca 13606 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13607 "Z2", "write-watchpoint", 0);
d471ea57 13608
444abaca 13609 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13610 "Z3", "read-watchpoint", 0);
d471ea57 13611
444abaca 13612 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13613 "Z4", "access-watchpoint", 0);
d471ea57 13614
0876f84a
DJ
13615 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13616 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13617
c78fa86a
GB
13618 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13619 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13620
23181151
DJ
13621 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13622 "qXfer:features:read", "target-features", 0);
13623
cfa9d6d9
DJ
13624 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13625 "qXfer:libraries:read", "library-info", 0);
13626
2268b414
JK
13627 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13628 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13629
fd79ecee
DJ
13630 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13631 "qXfer:memory-map:read", "memory-map", 0);
13632
0e7f50da
UW
13633 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13634 "qXfer:spu:read", "read-spu-object", 0);
13635
13636 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13637 "qXfer:spu:write", "write-spu-object", 0);
13638
07e059b5
VP
13639 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13640 "qXfer:osdata:read", "osdata", 0);
13641
dc146f7c
VP
13642 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13643 "qXfer:threads:read", "threads", 0);
13644
4aa995e1
PA
13645 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13646 "qXfer:siginfo:read", "read-siginfo-object", 0);
13647
13648 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13649 "qXfer:siginfo:write", "write-siginfo-object", 0);
13650
b3b9301e
PA
13651 add_packet_config_cmd
13652 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13653 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13654
169081d0
TG
13655 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13656 "qXfer:uib:read", "unwind-info-block", 0);
13657
444abaca 13658 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13659 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13660 0);
13661
711e434b
PM
13662 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13663 "qGetTIBAddr", "get-thread-information-block-address",
13664 0);
13665
40ab02ce
MS
13666 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13667 "bc", "reverse-continue", 0);
13668
13669 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13670 "bs", "reverse-step", 0);
13671
be2a5f71
DJ
13672 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13673 "qSupported", "supported-packets", 0);
13674
08388c79
DE
13675 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13676 "qSearch:memory", "search-memory", 0);
13677
bd3eecc3
PA
13678 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13679 "qTStatus", "trace-status", 0);
13680
15a201c8
GB
13681 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13682 "vFile:setfs", "hostio-setfs", 0);
13683
a6b151f1
DJ
13684 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13685 "vFile:open", "hostio-open", 0);
13686
13687 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13688 "vFile:pread", "hostio-pread", 0);
13689
13690 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13691 "vFile:pwrite", "hostio-pwrite", 0);
13692
13693 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13694 "vFile:close", "hostio-close", 0);
13695
13696 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13697 "vFile:unlink", "hostio-unlink", 0);
13698
b9e7b9c3
UW
13699 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13700 "vFile:readlink", "hostio-readlink", 0);
13701
0a93529c
GB
13702 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13703 "vFile:fstat", "hostio-fstat", 0);
13704
2d717e4f
DJ
13705 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13706 "vAttach", "attach", 0);
13707
13708 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13709 "vRun", "run", 0);
13710
a6f3e723
SL
13711 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13712 "QStartNoAckMode", "noack", 0);
13713
82f73884
PA
13714 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13715 "vKill", "kill", 0);
13716
0b16c5cf
PA
13717 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13718 "qAttached", "query-attached", 0);
13719
782b2b07 13720 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13721 "ConditionalTracepoints",
13722 "conditional-tracepoints", 0);
3788aec7
LM
13723
13724 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13725 "ConditionalBreakpoints",
13726 "conditional-breakpoints", 0);
13727
d3ce09f5
SS
13728 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13729 "BreakpointCommands",
13730 "breakpoint-commands", 0);
13731
7a697b8d
SS
13732 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13733 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13734
409873ef
SS
13735 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13736 "TracepointSource", "TracepointSource", 0);
13737
d914c394
SS
13738 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13739 "QAllow", "allow", 0);
13740
0fb4aa4b
PA
13741 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13742 "StaticTracepoints", "static-tracepoints", 0);
13743
1e4d1764
YQ
13744 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13745 "InstallInTrace", "install-in-trace", 0);
13746
0fb4aa4b
PA
13747 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13748 "qXfer:statictrace:read", "read-sdata-object", 0);
13749
78d85199
YQ
13750 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13751 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13752
03583c20
UW
13753 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13754 "QDisableRandomization", "disable-randomization", 0);
13755
d1feda86
YQ
13756 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13757 "QAgent", "agent", 0);
13758
f6f899bf
HAQ
13759 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13760 "QTBuffer:size", "trace-buffer-size", 0);
13761
9accd112
MM
13762 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13763 "Qbtrace:off", "disable-btrace", 0);
13764
13765 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13766 "Qbtrace:bts", "enable-btrace-bts", 0);
13767
13768 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13769 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13770
13771 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13772 "qXfer:btrace", "read-btrace", 0);
13773
f4abbc16
MM
13774 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13775 "qXfer:btrace-conf", "read-btrace-conf", 0);
13776
d33501a5
MM
13777 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13778 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13779
73b8c1fd
PA
13780 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13781 "multiprocess-feature", "multiprocess-feature", 0);
13782
f7e6eed5
PA
13783 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13784 "swbreak-feature", "swbreak-feature", 0);
13785
13786 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13787 "hwbreak-feature", "hwbreak-feature", 0);
13788
89245bc0
DB
13789 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13790 "fork-event-feature", "fork-event-feature", 0);
13791
13792 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13793 "vfork-event-feature", "vfork-event-feature", 0);
13794
b20a6524
MM
13795 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13796 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13797
750ce8d1
YQ
13798 add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
13799 "vContSupported", "verbose-resume-supported", 0);
13800
94585166
DB
13801 add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
13802 "exec-event-feature", "exec-event-feature", 0);
13803
de979965
PA
13804 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
13805 "vCtrlC", "ctrl-c", 0);
13806
65706a29
PA
13807 add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
13808 "QThreadEvents", "thread-events", 0);
13809
f2faf941
PA
13810 add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
13811 "N stop reply", "no-resumed-stop-reply", 0);
13812
0b736949
DB
13813 /* Assert that we've registered "set remote foo-packet" commands
13814 for all packet configs. */
ca4f7f8b
PA
13815 {
13816 int i;
13817
13818 for (i = 0; i < PACKET_MAX; i++)
13819 {
13820 /* Ideally all configs would have a command associated. Some
13821 still don't though. */
13822 int excepted;
13823
13824 switch (i)
13825 {
13826 case PACKET_QNonStop:
ca4f7f8b
PA
13827 case PACKET_EnableDisableTracepoints_feature:
13828 case PACKET_tracenz_feature:
13829 case PACKET_DisconnectedTracing_feature:
13830 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13831 case PACKET_qCRC:
13832 /* Additions to this list need to be well justified:
13833 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13834 excepted = 1;
13835 break;
13836 default:
13837 excepted = 0;
13838 break;
13839 }
13840
13841 /* This catches both forgetting to add a config command, and
13842 forgetting to remove a packet from the exception list. */
13843 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13844 }
13845 }
13846
37a105a1
DJ
13847 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13848 Z sub-packet has its own set and show commands, but users may
13849 have sets to this variable in their .gdbinit files (or in their
13850 documentation). */
e9e68a56 13851 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13852 &remote_Z_packet_detect, _("\
13853Set use of remote protocol `Z' packets"), _("\
13854Show use of remote protocol `Z' packets "), _("\
3b64bf98 13855When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13856packets."),
e9e68a56 13857 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13858 show_remote_protocol_Z_packet_cmd,
13859 /* FIXME: i18n: Use of remote protocol
13860 `Z' packets is %s. */
e9e68a56 13861 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13862
a6b151f1
DJ
13863 add_prefix_cmd ("remote", class_files, remote_command, _("\
13864Manipulate files on the remote system\n\
13865Transfer files to and from the remote target system."),
13866 &remote_cmdlist, "remote ",
13867 0 /* allow-unknown */, &cmdlist);
13868
13869 add_cmd ("put", class_files, remote_put_command,
13870 _("Copy a local file to the remote system."),
13871 &remote_cmdlist);
13872
13873 add_cmd ("get", class_files, remote_get_command,
13874 _("Copy a remote file to the local system."),
13875 &remote_cmdlist);
13876
13877 add_cmd ("delete", class_files, remote_delete_command,
13878 _("Delete a remote file."),
13879 &remote_cmdlist);
13880
2d717e4f 13881 add_setshow_string_noescape_cmd ("exec-file", class_files,
94585166 13882 &remote_exec_file_var, _("\
2d717e4f 13883Set the remote pathname for \"run\""), _("\
94585166
DB
13884Show the remote pathname for \"run\""), NULL,
13885 set_remote_exec_file,
13886 show_remote_exec_file,
13887 &remote_set_cmdlist,
13888 &remote_show_cmdlist);
2d717e4f 13889
c1e36e3e
PA
13890 add_setshow_boolean_cmd ("range-stepping", class_run,
13891 &use_range_stepping, _("\
13892Enable or disable range stepping."), _("\
13893Show whether target-assisted range stepping is enabled."), _("\
13894If on, and the target supports it, when stepping a source line, GDB\n\
13895tells the target to step the corresponding range of addresses itself instead\n\
13896of issuing multiple single-steps. This speeds up source level\n\
13897stepping. If off, GDB always issues single-steps, even if range\n\
13898stepping is supported by the target. The default is on."),
13899 set_range_stepping,
13900 show_range_stepping,
13901 &setlist,
13902 &showlist);
13903
449092f6
CV
13904 /* Eventually initialize fileio. See fileio.c */
13905 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13906
ba348170 13907 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13908 special ptids with it set to != 0. */
ba348170
PA
13909 magic_null_ptid = ptid_build (42000, -1, 1);
13910 not_sent_ptid = ptid_build (42000, -2, 1);
13911 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13912
13913 target_buf_size = 2048;
224c3ddb 13914 target_buf = (char *) xmalloc (target_buf_size);
c906108c 13915}
10760264 13916