]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/remote.c
New test for follow-exec-mode
[thirdparty/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
32d0add0 3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
35b1e5cc 73
0df8b418 74/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
75static char *target_buf;
76static long target_buf_size;
35b1e5cc 77
6765f3e5
DJ
78/* The size to align memory write packets, when practical. The protocol
79 does not guarantee any alignment, and gdb will generate short
80 writes and unaligned writes, but even as a best-effort attempt this
81 can improve bulk transfers. For instance, if a write is misaligned
82 relative to the target's data bus, the stub may need to make an extra
83 round trip fetching data from the target. This doesn't make a
84 huge difference, but it's easy to do, so we try to be helpful.
85
86 The alignment chosen is arbitrary; usually data bus width is
87 important here, not the possibly larger cache line size. */
88enum { REMOTE_ALIGN_WRITES = 16 };
89
23860348 90/* Prototypes for local functions. */
934b9bac 91static void async_cleanup_sigint_signal_handler (void *dummy);
6d820c5c 92static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
74531fed 93static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
fee9eda9 94 int forever, int *is_notif);
6426a772 95
934b9bac
JK
96static void async_handle_remote_sigint (int);
97static void async_handle_remote_sigint_twice (int);
43ff13b4 98
a14ed312 99static void remote_files_info (struct target_ops *ignore);
c906108c 100
f32dbf8c
MM
101static void remote_prepare_to_store (struct target_ops *self,
102 struct regcache *regcache);
c906108c 103
014f9477
TT
104static void remote_open_1 (const char *, int, struct target_ops *,
105 int extended_p);
c906108c 106
de90e03d 107static void remote_close (struct target_ops *self);
c906108c 108
cbb8991c
DB
109struct remote_state;
110
111static int remote_vkill (int pid, struct remote_state *rs);
112
136d6dae 113static void remote_mourn (struct target_ops *ops);
c906108c 114
a14ed312 115static void extended_remote_restart (void);
c906108c 116
136d6dae 117static void extended_remote_mourn (struct target_ops *);
c906108c 118
6d820c5c 119static void remote_send (char **buf, long *sizeof_buf_p);
c906108c 120
a14ed312 121static int readchar (int timeout);
c906108c 122
c33e31fd
PA
123static void remote_serial_write (const char *str, int len);
124
7d85a9c0 125static void remote_kill (struct target_ops *ops);
c906108c 126
6a109b6b 127static int remote_can_async_p (struct target_ops *);
75c99385 128
6a109b6b 129static int remote_is_async_p (struct target_ops *);
75c99385 130
6a3753b3 131static void remote_async (struct target_ops *ops, int enable);
75c99385 132
934b9bac 133static void sync_remote_interrupt_twice (int signo);
7a292a7a 134
a14ed312 135static void interrupt_query (void);
c906108c 136
79d7f229
PA
137static void set_general_thread (struct ptid ptid);
138static void set_continue_thread (struct ptid ptid);
c906108c 139
a14ed312 140static void get_offsets (void);
c906108c 141
6d820c5c
DJ
142static void skip_frame (void);
143
144static long read_frame (char **buf_p, long *sizeof_buf);
c906108c 145
a14ed312 146static int hexnumlen (ULONGEST num);
c906108c 147
a14ed312 148static void init_remote_ops (void);
c906108c 149
a14ed312 150static void init_extended_remote_ops (void);
c906108c 151
1eab8a48 152static void remote_stop (struct target_ops *self, ptid_t);
c906108c 153
a14ed312 154static int stubhex (int ch);
c906108c 155
a14ed312 156static int hexnumstr (char *, ULONGEST);
c906108c 157
a14ed312 158static int hexnumnstr (char *, ULONGEST, int);
2df3850c 159
a14ed312 160static CORE_ADDR remote_address_masked (CORE_ADDR);
c906108c 161
baa336ce 162static void print_packet (const char *);
c906108c 163
a14ed312 164static void compare_sections_command (char *, int);
c906108c 165
a14ed312 166static void packet_command (char *, int);
c906108c 167
a14ed312 168static int stub_unpack_int (char *buff, int fieldlength);
c906108c 169
39f77062 170static ptid_t remote_current_thread (ptid_t oldptid);
c906108c 171
baa336ce 172static int putpkt_binary (const char *buf, int cnt);
c906108c 173
a14ed312 174static void check_binary_download (CORE_ADDR addr);
c906108c 175
5a2468f5 176struct packet_config;
5a2468f5 177
a14ed312 178static void show_packet_config_cmd (struct packet_config *config);
5a2468f5 179
bb572ddd
DJ
180static void show_remote_protocol_packet_cmd (struct ui_file *file,
181 int from_tty,
182 struct cmd_list_element *c,
183 const char *value);
184
82f73884
PA
185static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
186static ptid_t read_ptid (char *buf, char **obuf);
187
c378d69d 188static void remote_set_permissions (struct target_ops *self);
d914c394 189
8bd200f1
TT
190static int remote_get_trace_status (struct target_ops *self,
191 struct trace_status *ts);
d5551862 192
ab6617cc
TT
193static int remote_upload_tracepoints (struct target_ops *self,
194 struct uploaded_tp **utpp);
00bf0b85 195
181e3713
TT
196static int remote_upload_trace_state_variables (struct target_ops *self,
197 struct uploaded_tsv **utsvp);
00bf0b85 198
c8d104ad
PA
199static void remote_query_supported (void);
200
36d25514 201static void remote_check_symbols (void);
c8d104ad 202
a14ed312 203void _initialize_remote (void);
c906108c 204
74531fed 205struct stop_reply;
74531fed 206static void stop_reply_xfree (struct stop_reply *);
722247f1 207static void remote_parse_stop_reply (char *, struct stop_reply *);
74531fed 208static void push_stop_reply (struct stop_reply *);
bcc75809 209static void discard_pending_stop_replies_in_queue (struct remote_state *);
74531fed
PA
210static int peek_stop_reply (ptid_t ptid);
211
cbb8991c
DB
212struct threads_listing_context;
213static void remove_new_fork_children (struct threads_listing_context *);
214
74531fed 215static void remote_async_inferior_event_handler (gdb_client_data);
74531fed 216
e3594fd1 217static void remote_terminal_ours (struct target_ops *self);
d3fd5342 218
d962ef82
DJ
219static int remote_read_description_p (struct target_ops *target);
220
176a6961 221static void remote_console_output (char *msg);
dde08ee1 222
efcc2da7 223static int remote_supports_cond_breakpoints (struct target_ops *self);
b775012e 224
78eff0ec 225static int remote_can_run_breakpoint_commands (struct target_ops *self);
d3ce09f5 226
f4abbc16
MM
227static void remote_btrace_reset (void);
228
221e1a37
PA
229static int stop_reply_queue_length (void);
230
80152258
PA
231static void readahead_cache_invalidate (void);
232
a6b151f1
DJ
233/* For "remote". */
234
235static struct cmd_list_element *remote_cmdlist;
236
bb572ddd
DJ
237/* For "set remote" and "show remote". */
238
239static struct cmd_list_element *remote_set_cmdlist;
240static struct cmd_list_element *remote_show_cmdlist;
241
d458bd84
PA
242/* Stub vCont actions support.
243
244 Each field is a boolean flag indicating whether the stub reports
245 support for the corresponding action. */
246
247struct vCont_action_support
248{
249 /* vCont;t */
250 int t;
c1e36e3e
PA
251
252 /* vCont;r */
253 int r;
d458bd84
PA
254};
255
c1e36e3e
PA
256/* Controls whether GDB is willing to use range stepping. */
257
258static int use_range_stepping = 1;
259
0d031856
TT
260#define OPAQUETHREADBYTES 8
261
262/* a 64 bit opaque identifier */
263typedef unsigned char threadref[OPAQUETHREADBYTES];
264
265/* About this many threadisds fit in a packet. */
266
267#define MAXTHREADLISTRESULTS 32
268
80152258
PA
269/* Data for the vFile:pread readahead cache. */
270
271struct readahead_cache
272{
273 /* The file descriptor for the file that is being cached. -1 if the
274 cache is invalid. */
275 int fd;
276
277 /* The offset into the file that the cache buffer corresponds
278 to. */
279 ULONGEST offset;
280
281 /* The buffer holding the cache contents. */
282 gdb_byte *buf;
283 /* The buffer's size. We try to read as much as fits into a packet
284 at a time. */
285 size_t bufsize;
286
287 /* Cache hit and miss counters. */
288 ULONGEST hit_count;
289 ULONGEST miss_count;
290};
291
ea9c271d
DJ
292/* Description of the remote protocol state for the currently
293 connected target. This is per-target state, and independent of the
294 selected architecture. */
295
296struct remote_state
297{
298 /* A buffer to use for incoming packets, and its current size. The
299 buffer is grown dynamically for larger incoming packets.
300 Outgoing packets may also be constructed in this buffer.
301 BUF_SIZE is always at least REMOTE_PACKET_SIZE;
302 REMOTE_PACKET_SIZE should be used to limit the length of outgoing
303 packets. */
304 char *buf;
305 long buf_size;
be2a5f71 306
1e51243a
PA
307 /* True if we're going through initial connection setup (finding out
308 about the remote side's threads, relocating symbols, etc.). */
309 int starting_up;
310
be2a5f71
DJ
311 /* If we negotiated packet size explicitly (and thus can bypass
312 heuristics for the largest packet size that will not overflow
313 a buffer in the stub), this will be set to that packet size.
314 Otherwise zero, meaning to use the guessed size. */
315 long explicit_packet_size;
2d717e4f
DJ
316
317 /* remote_wait is normally called when the target is running and
318 waits for a stop reply packet. But sometimes we need to call it
319 when the target is already stopped. We can send a "?" packet
320 and have remote_wait read the response. Or, if we already have
321 the response, we can stash it in BUF and tell remote_wait to
322 skip calling getpkt. This flag is set when BUF contains a
323 stop reply packet and the target is not waiting. */
324 int cached_wait_status;
a6f3e723
SL
325
326 /* True, if in no ack mode. That is, neither GDB nor the stub will
327 expect acks from each other. The connection is assumed to be
328 reliable. */
329 int noack_mode;
82f73884
PA
330
331 /* True if we're connected in extended remote mode. */
332 int extended;
333
e24a49d8
PA
334 /* True if we resumed the target and we're waiting for the target to
335 stop. In the mean time, we can't start another command/query.
336 The remote server wouldn't be ready to process it, so we'd
337 timeout waiting for a reply that would never come and eventually
338 we'd close the connection. This can happen in asynchronous mode
339 because we allow GDB commands while the target is running. */
340 int waiting_for_stop_reply;
74531fed 341
d458bd84
PA
342 /* The status of the stub support for the various vCont actions. */
343 struct vCont_action_support supports_vCont;
782b2b07 344
3a29589a
DJ
345 /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
346 responded to that. */
347 int ctrlc_pending_p;
5d93a237
TT
348
349 /* Descriptor for I/O to remote machine. Initialize it to NULL so that
350 remote_open knows that we don't have a file open when the program
351 starts. */
352 struct serial *remote_desc;
47f8a51d
TT
353
354 /* These are the threads which we last sent to the remote system. The
355 TID member will be -1 for all or -2 for not sent yet. */
356 ptid_t general_thread;
357 ptid_t continue_thread;
262e1174
TT
358
359 /* This is the traceframe which we last selected on the remote system.
360 It will be -1 if no traceframe is selected. */
361 int remote_traceframe_number;
747dc59d
TT
362
363 char *last_pass_packet;
5e4a05c4
TT
364
365 /* The last QProgramSignals packet sent to the target. We bypass
366 sending a new program signals list down to the target if the new
367 packet is exactly the same as the last we sent. IOW, we only let
368 the target know about program signals list changes. */
369 char *last_program_signals_packet;
b73be471
TT
370
371 enum gdb_signal last_sent_signal;
280ceea3
TT
372
373 int last_sent_step;
8e88304f
TT
374
375 char *finished_object;
376 char *finished_annex;
377 ULONGEST finished_offset;
b80fafe3
TT
378
379 /* Should we try the 'ThreadInfo' query packet?
380
381 This variable (NOT available to the user: auto-detect only!)
382 determines whether GDB will use the new, simpler "ThreadInfo"
383 query or the older, more complex syntax for thread queries.
384 This is an auto-detect variable (set to true at each connect,
385 and set to false when the target fails to recognize it). */
386 int use_threadinfo_query;
387 int use_threadextra_query;
88b496c3 388
ee154bee
TT
389 /* This is set to the data address of the access causing the target
390 to stop for a watchpoint. */
391 CORE_ADDR remote_watch_data_address;
392
f7e6eed5
PA
393 /* Whether the target stopped for a breakpoint/watchpoint. */
394 enum target_stop_reason stop_reason;
0d031856
TT
395
396 threadref echo_nextthread;
397 threadref nextthread;
398 threadref resultthreadlist[MAXTHREADLISTRESULTS];
5965e028
YQ
399
400 /* The state of remote notification. */
401 struct remote_notif_state *notif_state;
f4abbc16
MM
402
403 /* The branch trace configuration. */
404 struct btrace_config btrace_config;
15a201c8
GB
405
406 /* The argument to the last "vFile:setfs:" packet we sent, used
407 to avoid sending repeated unnecessary "vFile:setfs:" packets.
408 Initialized to -1 to indicate that no "vFile:setfs:" packet
409 has yet been sent. */
410 int fs_pid;
80152258
PA
411
412 /* A readahead cache for vFile:pread. Often, reading a binary
413 involves a sequence of small reads. E.g., when parsing an ELF
414 file. A readahead cache helps mostly the case of remote
415 debugging on a connection with higher latency, due to the
416 request/reply nature of the RSP. We only cache data for a single
417 file descriptor at a time. */
418 struct readahead_cache readahead_cache;
ea9c271d
DJ
419};
420
dc146f7c
VP
421/* Private data that we'll store in (struct thread_info)->private. */
422struct private_thread_info
423{
424 char *extra;
425 int core;
426};
427
428static void
429free_private_thread_info (struct private_thread_info *info)
430{
431 xfree (info->extra);
432 xfree (info);
433}
434
ea9c271d
DJ
435/* This data could be associated with a target, but we do not always
436 have access to the current target when we need it, so for now it is
437 static. This will be fine for as long as only one target is in use
438 at a time. */
cf792862 439static struct remote_state *remote_state;
ea9c271d
DJ
440
441static struct remote_state *
0b83947e 442get_remote_state_raw (void)
ea9c271d 443{
cf792862
TT
444 return remote_state;
445}
446
447/* Allocate a new struct remote_state with xmalloc, initialize it, and
448 return it. */
449
450static struct remote_state *
451new_remote_state (void)
452{
453 struct remote_state *result = XCNEW (struct remote_state);
454
455 /* The default buffer size is unimportant; it will be expanded
456 whenever a larger buffer is needed. */
457 result->buf_size = 400;
458 result->buf = xmalloc (result->buf_size);
262e1174 459 result->remote_traceframe_number = -1;
b73be471 460 result->last_sent_signal = GDB_SIGNAL_0;
15a201c8 461 result->fs_pid = -1;
cf792862
TT
462
463 return result;
ea9c271d
DJ
464}
465
466/* Description of the remote protocol for a given architecture. */
d01949b6 467
ad10f812
AC
468struct packet_reg
469{
470 long offset; /* Offset into G packet. */
471 long regnum; /* GDB's internal register number. */
472 LONGEST pnum; /* Remote protocol register number. */
b323314b 473 int in_g_packet; /* Always part of G packet. */
f5656ead 474 /* long size in bytes; == register_size (target_gdbarch (), regnum);
23860348 475 at present. */
f5656ead 476 /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
c9f4d572 477 at present. */
ad10f812
AC
478};
479
ea9c271d 480struct remote_arch_state
d01949b6 481{
ad10f812
AC
482 /* Description of the remote protocol registers. */
483 long sizeof_g_packet;
b323314b
AC
484
485 /* Description of the remote protocol registers indexed by REGNUM
f57d151a 486 (making an array gdbarch_num_regs in size). */
b323314b 487 struct packet_reg *regs;
ad10f812 488
d01949b6
AC
489 /* This is the size (in chars) of the first response to the ``g''
490 packet. It is used as a heuristic when determining the maximum
491 size of memory-read and memory-write packets. A target will
492 typically only reserve a buffer large enough to hold the ``g''
493 packet. The size does not include packet overhead (headers and
23860348 494 trailers). */
d01949b6
AC
495 long actual_register_packet_size;
496
497 /* This is the maximum size (in chars) of a non read/write packet.
23860348 498 It is also used as a cap on the size of read/write packets. */
d01949b6
AC
499 long remote_packet_size;
500};
501
35b1e5cc
SS
502/* Utility: generate error from an incoming stub packet. */
503static void
504trace_error (char *buf)
505{
506 if (*buf++ != 'E')
507 return; /* not an error msg */
508 switch (*buf)
509 {
510 case '1': /* malformed packet error */
511 if (*++buf == '0') /* general case: */
512 error (_("remote.c: error in outgoing packet."));
513 else
514 error (_("remote.c: error in outgoing packet at field #%ld."),
515 strtol (buf, NULL, 16));
35b1e5cc
SS
516 default:
517 error (_("Target returns error code '%s'."), buf);
518 }
519}
520
521/* Utility: wait for reply from stub, while accepting "O" packets. */
522static char *
523remote_get_noisy_reply (char **buf_p,
524 long *sizeof_buf)
525{
526 do /* Loop on reply from remote stub. */
527 {
528 char *buf;
a744cf53 529
0df8b418 530 QUIT; /* Allow user to bail out with ^C. */
35b1e5cc
SS
531 getpkt (buf_p, sizeof_buf, 0);
532 buf = *buf_p;
ad91cd99 533 if (buf[0] == 'E')
35b1e5cc 534 trace_error (buf);
61012eef 535 else if (startswith (buf, "qRelocInsn:"))
dde08ee1
PA
536 {
537 ULONGEST ul;
538 CORE_ADDR from, to, org_to;
539 char *p, *pp;
540 int adjusted_size = 0;
7556d4a4 541 int relocated = 0;
dde08ee1
PA
542
543 p = buf + strlen ("qRelocInsn:");
544 pp = unpack_varlen_hex (p, &ul);
545 if (*pp != ';')
cb91c06a 546 error (_("invalid qRelocInsn packet: %s"), buf);
dde08ee1
PA
547 from = ul;
548
549 p = pp + 1;
a9cbf802 550 unpack_varlen_hex (p, &ul);
dde08ee1
PA
551 to = ul;
552
553 org_to = to;
554
492d29ea 555 TRY
dde08ee1 556 {
f5656ead 557 gdbarch_relocate_instruction (target_gdbarch (), &to, from);
7556d4a4 558 relocated = 1;
dde08ee1 559 }
492d29ea 560 CATCH (ex, RETURN_MASK_ALL)
7556d4a4
PA
561 {
562 if (ex.error == MEMORY_ERROR)
563 {
564 /* Propagate memory errors silently back to the
565 target. The stub may have limited the range of
566 addresses we can write to, for example. */
567 }
568 else
569 {
570 /* Something unexpectedly bad happened. Be verbose
571 so we can tell what, and propagate the error back
572 to the stub, so it doesn't get stuck waiting for
573 a response. */
574 exception_fprintf (gdb_stderr, ex,
575 _("warning: relocating instruction: "));
576 }
577 putpkt ("E01");
578 }
492d29ea 579 END_CATCH
7556d4a4
PA
580
581 if (relocated)
dde08ee1
PA
582 {
583 adjusted_size = to - org_to;
584
bba74b36 585 xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
dde08ee1
PA
586 putpkt (buf);
587 }
dde08ee1 588 }
ad91cd99 589 else if (buf[0] == 'O' && buf[1] != 'K')
35b1e5cc
SS
590 remote_console_output (buf + 1); /* 'O' message from stub */
591 else
0df8b418 592 return buf; /* Here's the actual reply. */
35b1e5cc
SS
593 }
594 while (1);
595}
3c3bea1c 596
d01949b6
AC
597/* Handle for retreving the remote protocol data from gdbarch. */
598static struct gdbarch_data *remote_gdbarch_data_handle;
599
ea9c271d
DJ
600static struct remote_arch_state *
601get_remote_arch_state (void)
d01949b6 602{
f5656ead 603 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
d01949b6
AC
604}
605
0b83947e
DJ
606/* Fetch the global remote target state. */
607
608static struct remote_state *
609get_remote_state (void)
610{
611 /* Make sure that the remote architecture state has been
612 initialized, because doing so might reallocate rs->buf. Any
613 function which calls getpkt also needs to be mindful of changes
614 to rs->buf, but this call limits the number of places which run
615 into trouble. */
616 get_remote_arch_state ();
617
618 return get_remote_state_raw ();
619}
620
74ca34ce
DJ
621static int
622compare_pnums (const void *lhs_, const void *rhs_)
623{
624 const struct packet_reg * const *lhs = lhs_;
625 const struct packet_reg * const *rhs = rhs_;
626
627 if ((*lhs)->pnum < (*rhs)->pnum)
628 return -1;
629 else if ((*lhs)->pnum == (*rhs)->pnum)
630 return 0;
631 else
632 return 1;
633}
634
c21236dc
PA
635static int
636map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 637{
74ca34ce 638 int regnum, num_remote_regs, offset;
74ca34ce 639 struct packet_reg **remote_regs;
ea9c271d 640
4a22f64d 641 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 642 {
c21236dc 643 struct packet_reg *r = &regs[regnum];
baef701f 644
4a22f64d 645 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
646 /* Do not try to fetch zero-sized (placeholder) registers. */
647 r->pnum = -1;
648 else
649 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
650
b323314b 651 r->regnum = regnum;
74ca34ce
DJ
652 }
653
654 /* Define the g/G packet format as the contents of each register
655 with a remote protocol number, in order of ascending protocol
656 number. */
657
4a22f64d 658 remote_regs = alloca (gdbarch_num_regs (gdbarch)
c21236dc 659 * sizeof (struct packet_reg *));
f57d151a 660 for (num_remote_regs = 0, regnum = 0;
4a22f64d 661 regnum < gdbarch_num_regs (gdbarch);
f57d151a 662 regnum++)
c21236dc
PA
663 if (regs[regnum].pnum != -1)
664 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 665
74ca34ce
DJ
666 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
667 compare_pnums);
668
669 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
670 {
671 remote_regs[regnum]->in_g_packet = 1;
672 remote_regs[regnum]->offset = offset;
4a22f64d 673 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
674 }
675
c21236dc
PA
676 return offset;
677}
678
679/* Given the architecture described by GDBARCH, return the remote
680 protocol register's number and the register's offset in the g/G
681 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
682 If the target does not have a mapping for REGNUM, return false,
683 otherwise, return true. */
684
685int
686remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
687 int *pnum, int *poffset)
688{
689 int sizeof_g_packet;
690 struct packet_reg *regs;
691 struct cleanup *old_chain;
692
693 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
694
695 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
696 old_chain = make_cleanup (xfree, regs);
697
698 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
699
700 *pnum = regs[regnum].pnum;
701 *poffset = regs[regnum].offset;
702
703 do_cleanups (old_chain);
704
705 return *pnum != -1;
706}
707
708static void *
709init_remote_state (struct gdbarch *gdbarch)
710{
711 struct remote_state *rs = get_remote_state_raw ();
712 struct remote_arch_state *rsa;
713
714 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
715
716 /* Use the architecture to build a regnum<->pnum table, which will be
717 1:1 unless a feature set specifies otherwise. */
718 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
719 gdbarch_num_regs (gdbarch),
720 struct packet_reg);
721
74ca34ce
DJ
722 /* Record the maximum possible size of the g packet - it may turn out
723 to be smaller. */
c21236dc 724 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 725
0df8b418 726 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
727 remote stubs have a hardwired buffer size of 400 bytes
728 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
729 as the maximum packet-size to ensure that the packet and an extra
730 NUL character can always fit in the buffer. This stops GDB
731 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
732 already a full buffer (As of 1999-12-04 that was most stubs). */
733 rsa->remote_packet_size = 400 - 1;
d01949b6 734
ea9c271d
DJ
735 /* This one is filled in when a ``g'' packet is received. */
736 rsa->actual_register_packet_size = 0;
737
738 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
739 default, adjust the size accordingly. Remember that each byte is
740 encoded as two characters. 32 is the overhead for the packet
741 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 742 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 743 little. */
ea9c271d
DJ
744 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
745 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 746
ea9c271d
DJ
747 /* Make sure that the packet buffer is plenty big enough for
748 this architecture. */
749 if (rs->buf_size < rsa->remote_packet_size)
750 {
751 rs->buf_size = 2 * rsa->remote_packet_size;
7fca722e 752 rs->buf = xrealloc (rs->buf, rs->buf_size);
ea9c271d 753 }
6d820c5c 754
ea9c271d
DJ
755 return rsa;
756}
757
758/* Return the current allowed size of a remote packet. This is
759 inferred from the current architecture, and should be used to
760 limit the length of outgoing packets. */
761static long
762get_remote_packet_size (void)
763{
be2a5f71 764 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
765 struct remote_arch_state *rsa = get_remote_arch_state ();
766
be2a5f71
DJ
767 if (rs->explicit_packet_size)
768 return rs->explicit_packet_size;
769
ea9c271d 770 return rsa->remote_packet_size;
d01949b6
AC
771}
772
ad10f812 773static struct packet_reg *
ea9c271d 774packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 775{
f5656ead 776 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
777 return NULL;
778 else
ad10f812 779 {
ea9c271d 780 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 781
b323314b
AC
782 gdb_assert (r->regnum == regnum);
783 return r;
ad10f812 784 }
ad10f812
AC
785}
786
787static struct packet_reg *
ea9c271d 788packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 789{
b323314b 790 int i;
a744cf53 791
f5656ead 792 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 793 {
ea9c271d 794 struct packet_reg *r = &rsa->regs[i];
a744cf53 795
b323314b
AC
796 if (r->pnum == pnum)
797 return r;
ad10f812
AC
798 }
799 return NULL;
d01949b6
AC
800}
801
c906108c
SS
802static struct target_ops remote_ops;
803
804static struct target_ops extended_remote_ops;
805
6426a772
JM
806/* FIXME: cagney/1999-09-23: Even though getpkt was called with
807 ``forever'' still use the normal timeout mechanism. This is
808 currently used by the ASYNC code to guarentee that target reads
809 during the initial connect always time-out. Once getpkt has been
810 modified to return a timeout indication and, in turn
811 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 812 this can go away. */
6426a772
JM
813static int wait_forever_enabled_p = 1;
814
9a7071a8
JB
815/* Allow the user to specify what sequence to send to the remote
816 when he requests a program interruption: Although ^C is usually
817 what remote systems expect (this is the default, here), it is
818 sometimes preferable to send a break. On other systems such
819 as the Linux kernel, a break followed by g, which is Magic SysRq g
820 is required in order to interrupt the execution. */
821const char interrupt_sequence_control_c[] = "Ctrl-C";
822const char interrupt_sequence_break[] = "BREAK";
823const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 824static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
825 {
826 interrupt_sequence_control_c,
827 interrupt_sequence_break,
828 interrupt_sequence_break_g,
829 NULL
830 };
831static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
832
833static void
834show_interrupt_sequence (struct ui_file *file, int from_tty,
835 struct cmd_list_element *c,
836 const char *value)
837{
838 if (interrupt_sequence_mode == interrupt_sequence_control_c)
839 fprintf_filtered (file,
840 _("Send the ASCII ETX character (Ctrl-c) "
841 "to the remote target to interrupt the "
842 "execution of the program.\n"));
843 else if (interrupt_sequence_mode == interrupt_sequence_break)
844 fprintf_filtered (file,
845 _("send a break signal to the remote target "
846 "to interrupt the execution of the program.\n"));
847 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
848 fprintf_filtered (file,
849 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
850 "the remote target to interrupt the execution "
851 "of Linux kernel.\n"));
852 else
853 internal_error (__FILE__, __LINE__,
854 _("Invalid value for interrupt_sequence_mode: %s."),
855 interrupt_sequence_mode);
856}
6426a772 857
9a7071a8
JB
858/* This boolean variable specifies whether interrupt_sequence is sent
859 to the remote target when gdb connects to it.
860 This is mostly needed when you debug the Linux kernel: The Linux kernel
861 expects BREAK g which is Magic SysRq g for connecting gdb. */
862static int interrupt_on_connect = 0;
c906108c 863
9a7071a8
JB
864/* This variable is used to implement the "set/show remotebreak" commands.
865 Since these commands are now deprecated in favor of "set/show remote
866 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
867static int remote_break;
868
9a7071a8
JB
869static void
870set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
871{
872 if (remote_break)
873 interrupt_sequence_mode = interrupt_sequence_break;
874 else
875 interrupt_sequence_mode = interrupt_sequence_control_c;
876}
877
878static void
879show_remotebreak (struct ui_file *file, int from_tty,
880 struct cmd_list_element *c,
881 const char *value)
882{
883}
884
c906108c
SS
885/* This variable sets the number of bits in an address that are to be
886 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 887 leading zeros, the entire address would be sent. This variable
c906108c
SS
888 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
889 initial implementation of remote.c restricted the address sent in
890 memory packets to ``host::sizeof long'' bytes - (typically 32
891 bits). Consequently, for 64 bit targets, the upper 32 bits of an
892 address was never sent. Since fixing this bug may cause a break in
893 some remote targets this variable is principly provided to
23860348 894 facilitate backward compatibility. */
c906108c 895
883b9c6c 896static unsigned int remote_address_size;
c906108c 897
75c99385
PA
898/* Temporary to track who currently owns the terminal. See
899 remote_terminal_* for more details. */
6426a772
JM
900
901static int remote_async_terminal_ours_p;
902
2d717e4f
DJ
903/* The executable file to use for "run" on the remote side. */
904
905static char *remote_exec_file = "";
906
11cf8741 907\f
11cf8741 908/* User configurable variables for the number of characters in a
ea9c271d
DJ
909 memory read/write packet. MIN (rsa->remote_packet_size,
910 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 911 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
912 (speed up transfers). The variables ``preferred_*'' (the user
913 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 914 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
915
916struct memory_packet_config
917{
918 char *name;
919 long size;
920 int fixed_p;
921};
922
923/* Compute the current size of a read/write packet. Since this makes
924 use of ``actual_register_packet_size'' the computation is dynamic. */
925
926static long
927get_memory_packet_size (struct memory_packet_config *config)
928{
d01949b6 929 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
930 struct remote_arch_state *rsa = get_remote_arch_state ();
931
11cf8741
JM
932 /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
933 law?) that some hosts don't cope very well with large alloca()
934 calls. Eventually the alloca() code will be replaced by calls to
935 xmalloc() and make_cleanups() allowing this restriction to either
23860348 936 be lifted or removed. */
11cf8741
JM
937#ifndef MAX_REMOTE_PACKET_SIZE
938#define MAX_REMOTE_PACKET_SIZE 16384
939#endif
3de11b2e 940 /* NOTE: 20 ensures we can write at least one byte. */
11cf8741 941#ifndef MIN_REMOTE_PACKET_SIZE
3de11b2e 942#define MIN_REMOTE_PACKET_SIZE 20
11cf8741
JM
943#endif
944 long what_they_get;
945 if (config->fixed_p)
946 {
947 if (config->size <= 0)
948 what_they_get = MAX_REMOTE_PACKET_SIZE;
949 else
950 what_they_get = config->size;
951 }
952 else
953 {
ea9c271d 954 what_they_get = get_remote_packet_size ();
23860348 955 /* Limit the packet to the size specified by the user. */
11cf8741
JM
956 if (config->size > 0
957 && what_they_get > config->size)
958 what_they_get = config->size;
be2a5f71
DJ
959
960 /* Limit it to the size of the targets ``g'' response unless we have
961 permission from the stub to use a larger packet size. */
962 if (rs->explicit_packet_size == 0
963 && rsa->actual_register_packet_size > 0
964 && what_they_get > rsa->actual_register_packet_size)
965 what_they_get = rsa->actual_register_packet_size;
11cf8741
JM
966 }
967 if (what_they_get > MAX_REMOTE_PACKET_SIZE)
968 what_they_get = MAX_REMOTE_PACKET_SIZE;
969 if (what_they_get < MIN_REMOTE_PACKET_SIZE)
970 what_they_get = MIN_REMOTE_PACKET_SIZE;
6d820c5c
DJ
971
972 /* Make sure there is room in the global buffer for this packet
973 (including its trailing NUL byte). */
974 if (rs->buf_size < what_they_get + 1)
975 {
976 rs->buf_size = 2 * what_they_get;
977 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
978 }
979
11cf8741
JM
980 return what_they_get;
981}
982
0df8b418 983/* Update the size of a read/write packet. If they user wants
23860348 984 something really big then do a sanity check. */
11cf8741
JM
985
986static void
987set_memory_packet_size (char *args, struct memory_packet_config *config)
988{
989 int fixed_p = config->fixed_p;
990 long size = config->size;
a744cf53 991
11cf8741 992 if (args == NULL)
8a3fe4f8 993 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
994 else if (strcmp (args, "hard") == 0
995 || strcmp (args, "fixed") == 0)
996 fixed_p = 1;
997 else if (strcmp (args, "soft") == 0
998 || strcmp (args, "limit") == 0)
999 fixed_p = 0;
1000 else
1001 {
1002 char *end;
a744cf53 1003
11cf8741
JM
1004 size = strtoul (args, &end, 0);
1005 if (args == end)
8a3fe4f8 1006 error (_("Invalid %s (bad syntax)."), config->name);
11cf8741
JM
1007#if 0
1008 /* Instead of explicitly capping the size of a packet to
1009 MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
1010 instead allowed to set the size to something arbitrarily
23860348 1011 large. */
11cf8741 1012 if (size > MAX_REMOTE_PACKET_SIZE)
8a3fe4f8 1013 error (_("Invalid %s (too large)."), config->name);
11cf8741
JM
1014#endif
1015 }
23860348 1016 /* Extra checks? */
11cf8741
JM
1017 if (fixed_p && !config->fixed_p)
1018 {
e2e0b3e5
AC
1019 if (! query (_("The target may not be able to correctly handle a %s\n"
1020 "of %ld bytes. Change the packet size? "),
11cf8741 1021 config->name, size))
8a3fe4f8 1022 error (_("Packet size not changed."));
11cf8741 1023 }
23860348 1024 /* Update the config. */
11cf8741
JM
1025 config->fixed_p = fixed_p;
1026 config->size = size;
1027}
1028
1029static void
1030show_memory_packet_size (struct memory_packet_config *config)
1031{
a3f17187 1032 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1033 if (config->fixed_p)
a3f17187 1034 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1035 get_memory_packet_size (config));
1036 else
a3f17187 1037 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1038 get_memory_packet_size (config));
1039}
1040
1041static struct memory_packet_config memory_write_packet_config =
1042{
1043 "memory-write-packet-size",
1044};
1045
1046static void
1047set_memory_write_packet_size (char *args, int from_tty)
1048{
1049 set_memory_packet_size (args, &memory_write_packet_config);
1050}
1051
1052static void
1053show_memory_write_packet_size (char *args, int from_tty)
1054{
1055 show_memory_packet_size (&memory_write_packet_config);
1056}
1057
1058static long
1059get_memory_write_packet_size (void)
1060{
1061 return get_memory_packet_size (&memory_write_packet_config);
1062}
1063
1064static struct memory_packet_config memory_read_packet_config =
1065{
1066 "memory-read-packet-size",
1067};
1068
1069static void
1070set_memory_read_packet_size (char *args, int from_tty)
1071{
1072 set_memory_packet_size (args, &memory_read_packet_config);
1073}
1074
1075static void
1076show_memory_read_packet_size (char *args, int from_tty)
1077{
1078 show_memory_packet_size (&memory_read_packet_config);
1079}
1080
1081static long
1082get_memory_read_packet_size (void)
1083{
1084 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1085
11cf8741
JM
1086 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1087 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1088 increased beyond this. */
1089 if (size > get_remote_packet_size ())
1090 size = get_remote_packet_size ();
11cf8741
JM
1091 return size;
1092}
1093
11cf8741 1094\f
5a2468f5 1095/* Generic configuration support for packets the stub optionally
0df8b418 1096 supports. Allows the user to specify the use of the packet as well
23860348 1097 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1098
1099enum packet_support
1100 {
1101 PACKET_SUPPORT_UNKNOWN = 0,
1102 PACKET_ENABLE,
1103 PACKET_DISABLE
1104 };
1105
5a2468f5
JM
1106struct packet_config
1107 {
bb572ddd
DJ
1108 const char *name;
1109 const char *title;
4082afcc
PA
1110
1111 /* If auto, GDB auto-detects support for this packet or feature,
1112 either through qSupported, or by trying the packet and looking
1113 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1114 packet. If false, the packet is disabled. Configs that don't
1115 have an associated command always have this set to auto. */
7f19b9a2 1116 enum auto_boolean detect;
4082afcc
PA
1117
1118 /* Does the target support this packet? */
5a2468f5
JM
1119 enum packet_support support;
1120 };
1121
d471ea57 1122/* Analyze a packet's return value and update the packet config
23860348 1123 accordingly. */
d471ea57
AC
1124
1125enum packet_result
1126{
1127 PACKET_ERROR,
1128 PACKET_OK,
1129 PACKET_UNKNOWN
1130};
1131
4082afcc
PA
1132static enum packet_support packet_config_support (struct packet_config *config);
1133static enum packet_support packet_support (int packet);
5a2468f5
JM
1134
1135static void
fba45db2 1136show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1137{
1138 char *support = "internal-error";
a744cf53 1139
4082afcc 1140 switch (packet_config_support (config))
5a2468f5
JM
1141 {
1142 case PACKET_ENABLE:
1143 support = "enabled";
1144 break;
1145 case PACKET_DISABLE:
1146 support = "disabled";
1147 break;
1148 case PACKET_SUPPORT_UNKNOWN:
1149 support = "unknown";
1150 break;
1151 }
1152 switch (config->detect)
1153 {
7f19b9a2 1154 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1155 printf_filtered (_("Support for the `%s' packet "
1156 "is auto-detected, currently %s.\n"),
37a105a1 1157 config->name, support);
5a2468f5 1158 break;
7f19b9a2
AC
1159 case AUTO_BOOLEAN_TRUE:
1160 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1161 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1162 config->name, support);
8e248173 1163 break;
5a2468f5
JM
1164 }
1165}
1166
1167static void
bb572ddd
DJ
1168add_packet_config_cmd (struct packet_config *config, const char *name,
1169 const char *title, int legacy)
d471ea57 1170{
5a2468f5
JM
1171 char *set_doc;
1172 char *show_doc;
d471ea57 1173 char *cmd_name;
3ed07be4 1174
5a2468f5
JM
1175 config->name = name;
1176 config->title = title;
b435e160
AC
1177 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1178 name, title);
3e43a32a
MS
1179 show_doc = xstrprintf ("Show current use of remote "
1180 "protocol `%s' (%s) packet",
b435e160 1181 name, title);
d471ea57 1182 /* set/show TITLE-packet {auto,on,off} */
b435e160 1183 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1184 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1185 &config->detect, set_doc,
1186 show_doc, NULL, /* help_doc */
4082afcc 1187 NULL,
bb572ddd
DJ
1188 show_remote_protocol_packet_cmd,
1189 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1190 /* The command code copies the documentation strings. */
1191 xfree (set_doc);
1192 xfree (show_doc);
23860348 1193 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1194 if (legacy)
1195 {
1196 char *legacy_name;
a744cf53 1197
b435e160 1198 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1199 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1200 &remote_set_cmdlist);
d471ea57 1201 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1202 &remote_show_cmdlist);
d471ea57 1203 }
5a2468f5
JM
1204}
1205
d471ea57 1206static enum packet_result
a76d924d 1207packet_check_result (const char *buf)
5a2468f5 1208{
d471ea57 1209 if (buf[0] != '\0')
5a2468f5 1210 {
d471ea57 1211 /* The stub recognized the packet request. Check that the
23860348 1212 operation succeeded. */
a76d924d
DJ
1213 if (buf[0] == 'E'
1214 && isxdigit (buf[1]) && isxdigit (buf[2])
1215 && buf[3] == '\0')
1216 /* "Enn" - definitly an error. */
1217 return PACKET_ERROR;
1218
1219 /* Always treat "E." as an error. This will be used for
1220 more verbose error messages, such as E.memtypes. */
1221 if (buf[0] == 'E' && buf[1] == '.')
1222 return PACKET_ERROR;
1223
1224 /* The packet may or may not be OK. Just assume it is. */
1225 return PACKET_OK;
1226 }
1227 else
1228 /* The stub does not support the packet. */
1229 return PACKET_UNKNOWN;
1230}
1231
1232static enum packet_result
1233packet_ok (const char *buf, struct packet_config *config)
1234{
1235 enum packet_result result;
1236
4082afcc
PA
1237 if (config->detect != AUTO_BOOLEAN_TRUE
1238 && config->support == PACKET_DISABLE)
1239 internal_error (__FILE__, __LINE__,
1240 _("packet_ok: attempt to use a disabled packet"));
1241
a76d924d
DJ
1242 result = packet_check_result (buf);
1243 switch (result)
1244 {
1245 case PACKET_OK:
1246 case PACKET_ERROR:
1247 /* The stub recognized the packet request. */
4082afcc 1248 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1249 {
d471ea57
AC
1250 if (remote_debug)
1251 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1252 "Packet %s (%s) is supported\n",
1253 config->name, config->title);
d471ea57 1254 config->support = PACKET_ENABLE;
d471ea57 1255 }
a76d924d
DJ
1256 break;
1257 case PACKET_UNKNOWN:
23860348 1258 /* The stub does not support the packet. */
4082afcc
PA
1259 if (config->detect == AUTO_BOOLEAN_AUTO
1260 && config->support == PACKET_ENABLE)
d471ea57 1261 {
4082afcc
PA
1262 /* If the stub previously indicated that the packet was
1263 supported then there is a protocol error. */
1264 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1265 config->name, config->title);
1266 }
1267 else if (config->detect == AUTO_BOOLEAN_TRUE)
1268 {
1269 /* The user set it wrong. */
1270 error (_("Enabled packet %s (%s) not recognized by stub"),
1271 config->name, config->title);
d471ea57 1272 }
4082afcc
PA
1273
1274 if (remote_debug)
1275 fprintf_unfiltered (gdb_stdlog,
1276 "Packet %s (%s) is NOT supported\n",
1277 config->name, config->title);
1278 config->support = PACKET_DISABLE;
a76d924d 1279 break;
5a2468f5 1280 }
a76d924d
DJ
1281
1282 return result;
5a2468f5
JM
1283}
1284
444abaca
DJ
1285enum {
1286 PACKET_vCont = 0,
1287 PACKET_X,
1288 PACKET_qSymbol,
1289 PACKET_P,
1290 PACKET_p,
1291 PACKET_Z0,
1292 PACKET_Z1,
1293 PACKET_Z2,
1294 PACKET_Z3,
1295 PACKET_Z4,
15a201c8 1296 PACKET_vFile_setfs,
a6b151f1
DJ
1297 PACKET_vFile_open,
1298 PACKET_vFile_pread,
1299 PACKET_vFile_pwrite,
1300 PACKET_vFile_close,
1301 PACKET_vFile_unlink,
b9e7b9c3 1302 PACKET_vFile_readlink,
0a93529c 1303 PACKET_vFile_fstat,
0876f84a 1304 PACKET_qXfer_auxv,
23181151 1305 PACKET_qXfer_features,
c78fa86a 1306 PACKET_qXfer_exec_file,
cfa9d6d9 1307 PACKET_qXfer_libraries,
2268b414 1308 PACKET_qXfer_libraries_svr4,
fd79ecee 1309 PACKET_qXfer_memory_map,
0e7f50da
UW
1310 PACKET_qXfer_spu_read,
1311 PACKET_qXfer_spu_write,
07e059b5 1312 PACKET_qXfer_osdata,
dc146f7c 1313 PACKET_qXfer_threads,
0fb4aa4b 1314 PACKET_qXfer_statictrace_read,
b3b9301e 1315 PACKET_qXfer_traceframe_info,
169081d0 1316 PACKET_qXfer_uib,
711e434b 1317 PACKET_qGetTIBAddr,
444abaca 1318 PACKET_qGetTLSAddr,
be2a5f71 1319 PACKET_qSupported,
bd3eecc3 1320 PACKET_qTStatus,
89be2091 1321 PACKET_QPassSignals,
9b224c5e 1322 PACKET_QProgramSignals,
936d2992 1323 PACKET_qCRC,
08388c79 1324 PACKET_qSearch_memory,
2d717e4f
DJ
1325 PACKET_vAttach,
1326 PACKET_vRun,
a6f3e723 1327 PACKET_QStartNoAckMode,
82f73884 1328 PACKET_vKill,
4aa995e1
PA
1329 PACKET_qXfer_siginfo_read,
1330 PACKET_qXfer_siginfo_write,
0b16c5cf 1331 PACKET_qAttached,
4082afcc
PA
1332
1333 /* Support for conditional tracepoints. */
782b2b07 1334 PACKET_ConditionalTracepoints,
4082afcc
PA
1335
1336 /* Support for target-side breakpoint conditions. */
3788aec7 1337 PACKET_ConditionalBreakpoints,
4082afcc
PA
1338
1339 /* Support for target-side breakpoint commands. */
d3ce09f5 1340 PACKET_BreakpointCommands,
4082afcc
PA
1341
1342 /* Support for fast tracepoints. */
7a697b8d 1343 PACKET_FastTracepoints,
4082afcc
PA
1344
1345 /* Support for static tracepoints. */
0fb4aa4b 1346 PACKET_StaticTracepoints,
4082afcc
PA
1347
1348 /* Support for installing tracepoints while a trace experiment is
1349 running. */
1e4d1764 1350 PACKET_InstallInTrace,
4082afcc 1351
40ab02ce
MS
1352 PACKET_bc,
1353 PACKET_bs,
409873ef 1354 PACKET_TracepointSource,
d914c394 1355 PACKET_QAllow,
78d85199 1356 PACKET_qXfer_fdpic,
03583c20 1357 PACKET_QDisableRandomization,
d1feda86 1358 PACKET_QAgent,
f6f899bf 1359 PACKET_QTBuffer_size,
9accd112
MM
1360 PACKET_Qbtrace_off,
1361 PACKET_Qbtrace_bts,
b20a6524 1362 PACKET_Qbtrace_pt,
9accd112 1363 PACKET_qXfer_btrace,
4082afcc
PA
1364
1365 /* Support for the QNonStop packet. */
1366 PACKET_QNonStop,
1367
1368 /* Support for multi-process extensions. */
1369 PACKET_multiprocess_feature,
1370
1371 /* Support for enabling and disabling tracepoints while a trace
1372 experiment is running. */
1373 PACKET_EnableDisableTracepoints_feature,
1374
1375 /* Support for collecting strings using the tracenz bytecode. */
1376 PACKET_tracenz_feature,
1377
1378 /* Support for continuing to run a trace experiment while GDB is
1379 disconnected. */
1380 PACKET_DisconnectedTracing_feature,
1381
1382 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1383 PACKET_augmented_libraries_svr4_read_feature,
1384
f4abbc16
MM
1385 /* Support for the qXfer:btrace-conf:read packet. */
1386 PACKET_qXfer_btrace_conf,
1387
d33501a5
MM
1388 /* Support for the Qbtrace-conf:bts:size packet. */
1389 PACKET_Qbtrace_conf_bts_size,
1390
f7e6eed5
PA
1391 /* Support for swbreak+ feature. */
1392 PACKET_swbreak_feature,
1393
1394 /* Support for hwbreak+ feature. */
1395 PACKET_hwbreak_feature,
1396
89245bc0
DB
1397 /* Support for fork events. */
1398 PACKET_fork_event_feature,
1399
1400 /* Support for vfork events. */
1401 PACKET_vfork_event_feature,
1402
b20a6524
MM
1403 /* Support for the Qbtrace-conf:pt:size packet. */
1404 PACKET_Qbtrace_conf_pt_size,
1405
444abaca
DJ
1406 PACKET_MAX
1407};
506fb367 1408
444abaca 1409static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1410
f7e6eed5
PA
1411/* Returns the packet's corresponding "set remote foo-packet" command
1412 state. See struct packet_config for more details. */
1413
1414static enum auto_boolean
1415packet_set_cmd_state (int packet)
1416{
1417 return remote_protocol_packets[packet].detect;
1418}
1419
4082afcc
PA
1420/* Returns whether a given packet or feature is supported. This takes
1421 into account the state of the corresponding "set remote foo-packet"
1422 command, which may be used to bypass auto-detection. */
dc8acb97 1423
4082afcc
PA
1424static enum packet_support
1425packet_config_support (struct packet_config *config)
1426{
1427 switch (config->detect)
444abaca 1428 {
4082afcc
PA
1429 case AUTO_BOOLEAN_TRUE:
1430 return PACKET_ENABLE;
1431 case AUTO_BOOLEAN_FALSE:
1432 return PACKET_DISABLE;
1433 case AUTO_BOOLEAN_AUTO:
1434 return config->support;
1435 default:
1436 gdb_assert_not_reached (_("bad switch"));
444abaca 1437 }
4082afcc
PA
1438}
1439
1440/* Same as packet_config_support, but takes the packet's enum value as
1441 argument. */
1442
1443static enum packet_support
1444packet_support (int packet)
1445{
1446 struct packet_config *config = &remote_protocol_packets[packet];
1447
1448 return packet_config_support (config);
dc8acb97
MS
1449}
1450
5a2468f5 1451static void
444abaca
DJ
1452show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1453 struct cmd_list_element *c,
1454 const char *value)
5a2468f5 1455{
444abaca 1456 struct packet_config *packet;
5a2468f5 1457
444abaca
DJ
1458 for (packet = remote_protocol_packets;
1459 packet < &remote_protocol_packets[PACKET_MAX];
1460 packet++)
1461 {
1462 if (&packet->detect == c->var)
1463 {
1464 show_packet_config_cmd (packet);
1465 return;
1466 }
1467 }
9b20d036 1468 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1469 c->name);
5a2468f5
JM
1470}
1471
d471ea57
AC
1472/* Should we try one of the 'Z' requests? */
1473
1474enum Z_packet_type
1475{
1476 Z_PACKET_SOFTWARE_BP,
1477 Z_PACKET_HARDWARE_BP,
1478 Z_PACKET_WRITE_WP,
1479 Z_PACKET_READ_WP,
1480 Z_PACKET_ACCESS_WP,
1481 NR_Z_PACKET_TYPES
1482};
96baa820 1483
d471ea57 1484/* For compatibility with older distributions. Provide a ``set remote
23860348 1485 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1486
7f19b9a2 1487static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1488
1489static void
fba45db2
KB
1490set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1491 struct cmd_list_element *c)
96baa820 1492{
d471ea57 1493 int i;
a744cf53 1494
d471ea57 1495 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1496 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1497}
1498
1499static void
08546159
AC
1500show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1501 struct cmd_list_element *c,
1502 const char *value)
96baa820 1503{
d471ea57 1504 int i;
a744cf53 1505
d471ea57
AC
1506 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1507 {
444abaca 1508 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1509 }
96baa820
JM
1510}
1511
4082afcc
PA
1512/* Returns true if the multi-process extensions are in effect. */
1513
1514static int
1515remote_multi_process_p (struct remote_state *rs)
1516{
1517 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1518}
1519
de0d863e
DB
1520/* Returns true if fork events are supported. */
1521
1522static int
1523remote_fork_event_p (struct remote_state *rs)
1524{
1525 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1526}
1527
c269dbdb
DB
1528/* Returns true if vfork events are supported. */
1529
1530static int
1531remote_vfork_event_p (struct remote_state *rs)
1532{
1533 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1534}
1535
cbb8991c
DB
1536/* Insert fork catchpoint target routine. If fork events are enabled
1537 then return success, nothing more to do. */
1538
1539static int
1540remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1541{
1542 struct remote_state *rs = get_remote_state ();
1543
1544 return !remote_fork_event_p (rs);
1545}
1546
1547/* Remove fork catchpoint target routine. Nothing to do, just
1548 return success. */
1549
1550static int
1551remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1552{
1553 return 0;
1554}
1555
1556/* Insert vfork catchpoint target routine. If vfork events are enabled
1557 then return success, nothing more to do. */
1558
1559static int
1560remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1561{
1562 struct remote_state *rs = get_remote_state ();
1563
1564 return !remote_vfork_event_p (rs);
1565}
1566
1567/* Remove vfork catchpoint target routine. Nothing to do, just
1568 return success. */
1569
1570static int
1571remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1572{
1573 return 0;
1574}
1575
23860348 1576/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1577static struct async_signal_handler *async_sigint_remote_twice_token;
1578static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1579
74531fed
PA
1580\f
1581/* Asynchronous signal handle registered as event loop source for
1582 when we have pending events ready to be passed to the core. */
1583
1584static struct async_event_handler *remote_async_inferior_event_token;
1585
c906108c
SS
1586\f
1587
79d7f229
PA
1588static ptid_t magic_null_ptid;
1589static ptid_t not_sent_ptid;
1590static ptid_t any_thread_ptid;
1591
0b16c5cf
PA
1592/* Find out if the stub attached to PID (and hence GDB should offer to
1593 detach instead of killing it when bailing out). */
1594
1595static int
1596remote_query_attached (int pid)
1597{
1598 struct remote_state *rs = get_remote_state ();
bba74b36 1599 size_t size = get_remote_packet_size ();
0b16c5cf 1600
4082afcc 1601 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1602 return 0;
1603
1604 if (remote_multi_process_p (rs))
bba74b36 1605 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1606 else
bba74b36 1607 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1608
1609 putpkt (rs->buf);
1610 getpkt (&rs->buf, &rs->buf_size, 0);
1611
1612 switch (packet_ok (rs->buf,
1554e9be 1613 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1614 {
1615 case PACKET_OK:
1616 if (strcmp (rs->buf, "1") == 0)
1617 return 1;
1618 break;
1619 case PACKET_ERROR:
1620 warning (_("Remote failure reply: %s"), rs->buf);
1621 break;
1622 case PACKET_UNKNOWN:
1623 break;
1624 }
1625
1626 return 0;
1627}
1628
49c62f2e
PA
1629/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1630 has been invented by GDB, instead of reported by the target. Since
1631 we can be connected to a remote system before before knowing about
1632 any inferior, mark the target with execution when we find the first
1633 inferior. If ATTACHED is 1, then we had just attached to this
1634 inferior. If it is 0, then we just created this inferior. If it
1635 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1636 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1637 attempt to open this inferior's executable as the main executable
1638 if no main executable is open already. */
1941c569
PA
1639
1640static struct inferior *
1b6e6f5c
GB
1641remote_add_inferior (int fake_pid_p, int pid, int attached,
1642 int try_open_exec)
1941c569 1643{
1941c569
PA
1644 struct inferior *inf;
1645
0b16c5cf
PA
1646 /* Check whether this process we're learning about is to be
1647 considered attached, or if is to be considered to have been
1648 spawned by the stub. */
1649 if (attached == -1)
1650 attached = remote_query_attached (pid);
1651
f5656ead 1652 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1653 {
1654 /* If the target shares code across all inferiors, then every
1655 attach adds a new inferior. */
1656 inf = add_inferior (pid);
1657
1658 /* ... and every inferior is bound to the same program space.
1659 However, each inferior may still have its own address
1660 space. */
1661 inf->aspace = maybe_new_address_space ();
1662 inf->pspace = current_program_space;
1663 }
1664 else
1665 {
1666 /* In the traditional debugging scenario, there's a 1-1 match
1667 between program/address spaces. We simply bind the inferior
1668 to the program space's address space. */
1669 inf = current_inferior ();
1670 inferior_appeared (inf, pid);
1671 }
1941c569 1672
0b16c5cf 1673 inf->attach_flag = attached;
49c62f2e 1674 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1675
1b6e6f5c
GB
1676 /* If no main executable is currently open then attempt to
1677 open the file that was executed to create this inferior. */
835205d0 1678 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1679 exec_file_locate_attach (pid, 1);
1680
1941c569
PA
1681 return inf;
1682}
1683
1684/* Add thread PTID to GDB's thread list. Tag it as executing/running
1685 according to RUNNING. */
1686
c906108c 1687static void
1941c569 1688remote_add_thread (ptid_t ptid, int running)
c906108c 1689{
b7ea362b
PA
1690 struct remote_state *rs = get_remote_state ();
1691
1692 /* GDB historically didn't pull threads in the initial connection
1693 setup. If the remote target doesn't even have a concept of
1694 threads (e.g., a bare-metal target), even if internally we
1695 consider that a single-threaded target, mentioning a new thread
1696 might be confusing to the user. Be silent then, preserving the
1697 age old behavior. */
1698 if (rs->starting_up)
1699 add_thread_silent (ptid);
1700 else
1701 add_thread (ptid);
1941c569
PA
1702
1703 set_executing (ptid, running);
1704 set_running (ptid, running);
1705}
1706
1707/* Come here when we learn about a thread id from the remote target.
1708 It may be the first time we hear about such thread, so take the
1709 opportunity to add it to GDB's thread list. In case this is the
1710 first time we're noticing its corresponding inferior, add it to
1711 GDB's inferior list as well. */
1712
1713static void
1714remote_notice_new_inferior (ptid_t currthread, int running)
1715{
c906108c
SS
1716 /* If this is a new thread, add it to GDB's thread list.
1717 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1718
1719 if (in_thread_list (currthread) && is_exited (currthread))
1720 {
1721 /* We're seeing an event on a thread id we knew had exited.
1722 This has to be a new thread reusing the old id. Add it. */
1941c569 1723 remote_add_thread (currthread, running);
82f73884
PA
1724 return;
1725 }
1726
79d7f229 1727 if (!in_thread_list (currthread))
c0a2216e 1728 {
1941c569 1729 struct inferior *inf = NULL;
bad34192 1730 int pid = ptid_get_pid (currthread);
1941c569 1731
bad34192
PA
1732 if (ptid_is_pid (inferior_ptid)
1733 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1734 {
1735 /* inferior_ptid has no thread member yet. This can happen
1736 with the vAttach -> remote_wait,"TAAthread:" path if the
1737 stub doesn't support qC. This is the first stop reported
1738 after an attach, so this is the main thread. Update the
1739 ptid in the thread list. */
bad34192
PA
1740 if (in_thread_list (pid_to_ptid (pid)))
1741 thread_change_ptid (inferior_ptid, currthread);
1742 else
1743 {
1744 remote_add_thread (currthread, running);
1745 inferior_ptid = currthread;
1746 }
dc146f7c 1747 return;
c0a2216e 1748 }
82f73884
PA
1749
1750 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1751 {
1752 /* inferior_ptid is not set yet. This can happen with the
1753 vRun -> remote_wait,"TAAthread:" path if the stub
1754 doesn't support qC. This is the first stop reported
1755 after an attach, so this is the main thread. Update the
1756 ptid in the thread list. */
dc146f7c 1757 thread_change_ptid (inferior_ptid, currthread);
82f73884 1758 return;
c0a2216e 1759 }
82f73884 1760
29c87f7f
PA
1761 /* When connecting to a target remote, or to a target
1762 extended-remote which already was debugging an inferior, we
1763 may not know about it yet. Add it before adding its child
1764 thread, so notifications are emitted in a sensible order. */
1765 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1766 {
1767 struct remote_state *rs = get_remote_state ();
1768 int fake_pid_p = !remote_multi_process_p (rs);
1769
1770 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1771 ptid_get_pid (currthread), -1, 1);
49c62f2e 1772 }
29c87f7f 1773
82f73884 1774 /* This is really a new thread. Add it. */
1941c569
PA
1775 remote_add_thread (currthread, running);
1776
1777 /* If we found a new inferior, let the common code do whatever
1778 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1779 breakpoints), unless we're just setting up an all-stop
1780 connection. */
1941c569 1781 if (inf != NULL)
b7ea362b
PA
1782 {
1783 struct remote_state *rs = get_remote_state ();
1784
1785 if (non_stop || !rs->starting_up)
1786 notice_new_inferior (currthread, running, 0);
1787 }
c0a2216e 1788 }
c906108c
SS
1789}
1790
dc146f7c
VP
1791/* Return the private thread data, creating it if necessary. */
1792
70221824 1793static struct private_thread_info *
dc146f7c
VP
1794demand_private_info (ptid_t ptid)
1795{
1796 struct thread_info *info = find_thread_ptid (ptid);
1797
1798 gdb_assert (info);
1799
fe978cb0 1800 if (!info->priv)
dc146f7c 1801 {
fe978cb0 1802 info->priv = xmalloc (sizeof (*(info->priv)));
dc146f7c 1803 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1804 info->priv->core = -1;
1805 info->priv->extra = 0;
dc146f7c
VP
1806 }
1807
fe978cb0 1808 return info->priv;
dc146f7c
VP
1809}
1810
74531fed
PA
1811/* Call this function as a result of
1812 1) A halt indication (T packet) containing a thread id
1813 2) A direct query of currthread
0df8b418 1814 3) Successful execution of set thread */
74531fed
PA
1815
1816static void
47f8a51d 1817record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1818{
47f8a51d 1819 rs->general_thread = currthread;
74531fed
PA
1820}
1821
89be2091
DJ
1822/* If 'QPassSignals' is supported, tell the remote stub what signals
1823 it can simply pass through to the inferior without reporting. */
1824
1825static void
94bedb42
TT
1826remote_pass_signals (struct target_ops *self,
1827 int numsigs, unsigned char *pass_signals)
89be2091 1828{
4082afcc 1829 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1830 {
1831 char *pass_packet, *p;
89be2091 1832 int count = 0, i;
747dc59d 1833 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1834
1835 gdb_assert (numsigs < 256);
1836 for (i = 0; i < numsigs; i++)
1837 {
2455069d 1838 if (pass_signals[i])
89be2091
DJ
1839 count++;
1840 }
1841 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1842 strcpy (pass_packet, "QPassSignals:");
1843 p = pass_packet + strlen (pass_packet);
1844 for (i = 0; i < numsigs; i++)
1845 {
2455069d 1846 if (pass_signals[i])
89be2091
DJ
1847 {
1848 if (i >= 16)
1849 *p++ = tohex (i >> 4);
1850 *p++ = tohex (i & 15);
1851 if (count)
1852 *p++ = ';';
1853 else
1854 break;
1855 count--;
1856 }
1857 }
1858 *p = 0;
747dc59d 1859 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1860 {
89be2091
DJ
1861 putpkt (pass_packet);
1862 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1863 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1864 if (rs->last_pass_packet)
1865 xfree (rs->last_pass_packet);
1866 rs->last_pass_packet = pass_packet;
89be2091
DJ
1867 }
1868 else
1869 xfree (pass_packet);
1870 }
1871}
1872
9b224c5e
PA
1873/* If 'QProgramSignals' is supported, tell the remote stub what
1874 signals it should pass through to the inferior when detaching. */
1875
1876static void
daf5e9b6
TT
1877remote_program_signals (struct target_ops *self,
1878 int numsigs, unsigned char *signals)
9b224c5e 1879{
4082afcc 1880 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1881 {
1882 char *packet, *p;
1883 int count = 0, i;
5e4a05c4 1884 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1885
1886 gdb_assert (numsigs < 256);
1887 for (i = 0; i < numsigs; i++)
1888 {
1889 if (signals[i])
1890 count++;
1891 }
1892 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1893 strcpy (packet, "QProgramSignals:");
1894 p = packet + strlen (packet);
1895 for (i = 0; i < numsigs; i++)
1896 {
1897 if (signal_pass_state (i))
1898 {
1899 if (i >= 16)
1900 *p++ = tohex (i >> 4);
1901 *p++ = tohex (i & 15);
1902 if (count)
1903 *p++ = ';';
1904 else
1905 break;
1906 count--;
1907 }
1908 }
1909 *p = 0;
5e4a05c4
TT
1910 if (!rs->last_program_signals_packet
1911 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 1912 {
9b224c5e
PA
1913 putpkt (packet);
1914 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1915 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
1916 xfree (rs->last_program_signals_packet);
1917 rs->last_program_signals_packet = packet;
9b224c5e
PA
1918 }
1919 else
1920 xfree (packet);
1921 }
1922}
1923
79d7f229
PA
1924/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1925 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1926 thread. If GEN is set, set the general thread, if not, then set
1927 the step/continue thread. */
c906108c 1928static void
79d7f229 1929set_thread (struct ptid ptid, int gen)
c906108c 1930{
d01949b6 1931 struct remote_state *rs = get_remote_state ();
47f8a51d 1932 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 1933 char *buf = rs->buf;
79d7f229 1934 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1935
79d7f229 1936 if (ptid_equal (state, ptid))
c906108c
SS
1937 return;
1938
79d7f229
PA
1939 *buf++ = 'H';
1940 *buf++ = gen ? 'g' : 'c';
1941 if (ptid_equal (ptid, magic_null_ptid))
1942 xsnprintf (buf, endbuf - buf, "0");
1943 else if (ptid_equal (ptid, any_thread_ptid))
1944 xsnprintf (buf, endbuf - buf, "0");
1945 else if (ptid_equal (ptid, minus_one_ptid))
1946 xsnprintf (buf, endbuf - buf, "-1");
1947 else
82f73884 1948 write_ptid (buf, endbuf, ptid);
79d7f229 1949 putpkt (rs->buf);
6d820c5c 1950 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1951 if (gen)
47f8a51d 1952 rs->general_thread = ptid;
c906108c 1953 else
47f8a51d 1954 rs->continue_thread = ptid;
c906108c 1955}
79d7f229
PA
1956
1957static void
1958set_general_thread (struct ptid ptid)
1959{
1960 set_thread (ptid, 1);
1961}
1962
1963static void
1964set_continue_thread (struct ptid ptid)
1965{
1966 set_thread (ptid, 0);
1967}
1968
3c9c4b83
PA
1969/* Change the remote current process. Which thread within the process
1970 ends up selected isn't important, as long as it is the same process
1971 as what INFERIOR_PTID points to.
1972
1973 This comes from that fact that there is no explicit notion of
1974 "selected process" in the protocol. The selected process for
1975 general operations is the process the selected general thread
1976 belongs to. */
1977
1978static void
1979set_general_process (void)
1980{
1981 struct remote_state *rs = get_remote_state ();
1982
1983 /* If the remote can't handle multiple processes, don't bother. */
901f9912 1984 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
1985 return;
1986
1987 /* We only need to change the remote current thread if it's pointing
1988 at some other process. */
47f8a51d 1989 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
1990 set_general_thread (inferior_ptid);
1991}
1992
c906108c 1993\f
7d1a114c
PA
1994/* Return nonzero if this is the main thread that we made up ourselves
1995 to model non-threaded targets as single-threaded. */
c906108c
SS
1996
1997static int
7d1a114c 1998remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 1999{
6d820c5c 2000 struct remote_state *rs = get_remote_state ();
82f73884 2001 char *p, *endp;
c906108c 2002
c0a2216e
PA
2003 if (ptid_equal (ptid, magic_null_ptid))
2004 /* The main thread is always alive. */
2005 return 1;
2006
ba348170 2007 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2008 /* The main thread is always alive. This can happen after a
2009 vAttach, if the remote side doesn't support
2010 multi-threading. */
2011 return 1;
2012
7d1a114c
PA
2013 return 0;
2014}
2015
2016/* Return nonzero if the thread PTID is still alive on the remote
2017 system. */
2018
2019static int
2020remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2021{
2022 struct remote_state *rs = get_remote_state ();
2023 char *p, *endp;
2024
2025 /* Check if this is a thread that we made up ourselves to model
2026 non-threaded targets as single-threaded. */
2027 if (remote_thread_always_alive (ops, ptid))
2028 return 1;
2029
82f73884
PA
2030 p = rs->buf;
2031 endp = rs->buf + get_remote_packet_size ();
2032
2033 *p++ = 'T';
2034 write_ptid (p, endp, ptid);
2035
2e9f7625 2036 putpkt (rs->buf);
6d820c5c 2037 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2038 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2039}
2040
2041/* About these extended threadlist and threadinfo packets. They are
2042 variable length packets but, the fields within them are often fixed
2043 length. They are redundent enough to send over UDP as is the
2044 remote protocol in general. There is a matching unit test module
2045 in libstub. */
2046
23860348 2047/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2048 libstub protocol encoding, and remote.c. It is not particularly
23860348 2049 changable. */
cce74817
JM
2050
2051/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2052 Plan to fix this. */
cce74817 2053
23860348 2054typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2055
9d1f7ab2 2056/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2057 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2058
2059struct gdb_ext_thread_info
c5aa993b 2060 {
23860348 2061 threadref threadid; /* External form of thread reference. */
2bc416ba 2062 int active; /* Has state interesting to GDB?
23860348 2063 regs, stack. */
2bc416ba 2064 char display[256]; /* Brief state display, name,
cedea757 2065 blocked/suspended. */
23860348 2066 char shortname[32]; /* To be used to name threads. */
2bc416ba 2067 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2068 whatever. */
c5aa993b 2069 };
cce74817
JM
2070
2071/* The volume of remote transfers can be limited by submitting
2072 a mask containing bits specifying the desired information.
2073 Use a union of these values as the 'selection' parameter to
0df8b418 2074 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2075
2076#define TAG_THREADID 1
2077#define TAG_EXISTS 2
2078#define TAG_DISPLAY 4
2079#define TAG_THREADNAME 8
c5aa993b 2080#define TAG_MOREDISPLAY 16
cce74817 2081
23860348 2082#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2083
a14ed312 2084static char *unpack_nibble (char *buf, int *val);
cce74817 2085
a14ed312 2086static char *unpack_byte (char *buf, int *value);
cce74817 2087
a14ed312 2088static char *pack_int (char *buf, int value);
cce74817 2089
a14ed312 2090static char *unpack_int (char *buf, int *value);
cce74817 2091
a14ed312 2092static char *unpack_string (char *src, char *dest, int length);
cce74817 2093
23860348 2094static char *pack_threadid (char *pkt, threadref *id);
cce74817 2095
23860348 2096static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2097
23860348 2098void int_to_threadref (threadref *id, int value);
cce74817 2099
23860348 2100static int threadref_to_int (threadref *ref);
cce74817 2101
23860348 2102static void copy_threadref (threadref *dest, threadref *src);
cce74817 2103
23860348 2104static int threadmatch (threadref *dest, threadref *src);
cce74817 2105
2bc416ba 2106static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2107 threadref *id);
cce74817 2108
a14ed312 2109static int remote_unpack_thread_info_response (char *pkt,
23860348 2110 threadref *expectedref,
a14ed312
KB
2111 struct gdb_ext_thread_info
2112 *info);
cce74817
JM
2113
2114
2bc416ba 2115static int remote_get_threadinfo (threadref *threadid,
23860348 2116 int fieldset, /*TAG mask */
a14ed312 2117 struct gdb_ext_thread_info *info);
cce74817 2118
a14ed312
KB
2119static char *pack_threadlist_request (char *pkt, int startflag,
2120 int threadcount,
23860348 2121 threadref *nextthread);
cce74817 2122
a14ed312
KB
2123static int parse_threadlist_response (char *pkt,
2124 int result_limit,
23860348 2125 threadref *original_echo,
2bc416ba 2126 threadref *resultlist,
23860348 2127 int *doneflag);
cce74817 2128
a14ed312 2129static int remote_get_threadlist (int startflag,
23860348 2130 threadref *nextthread,
a14ed312
KB
2131 int result_limit,
2132 int *done,
2bc416ba 2133 int *result_count,
23860348 2134 threadref *threadlist);
cce74817 2135
23860348 2136typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2137
a14ed312
KB
2138static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2139 void *context, int looplimit);
cce74817 2140
23860348 2141static int remote_newthread_step (threadref *ref, void *context);
cce74817 2142
82f73884
PA
2143
2144/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2145 buffer we're allowed to write to. Returns
2146 BUF+CHARACTERS_WRITTEN. */
2147
2148static char *
2149write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2150{
2151 int pid, tid;
2152 struct remote_state *rs = get_remote_state ();
2153
2154 if (remote_multi_process_p (rs))
2155 {
2156 pid = ptid_get_pid (ptid);
2157 if (pid < 0)
2158 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2159 else
2160 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2161 }
ba348170 2162 tid = ptid_get_lwp (ptid);
82f73884
PA
2163 if (tid < 0)
2164 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2165 else
2166 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2167
2168 return buf;
2169}
2170
2171/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2172 passed the last parsed char. Returns null_ptid on error. */
2173
2174static ptid_t
2175read_ptid (char *buf, char **obuf)
2176{
2177 char *p = buf;
2178 char *pp;
2179 ULONGEST pid = 0, tid = 0;
82f73884
PA
2180
2181 if (*p == 'p')
2182 {
2183 /* Multi-process ptid. */
2184 pp = unpack_varlen_hex (p + 1, &pid);
2185 if (*pp != '.')
b37520b6 2186 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2187
2188 p = pp;
2189 pp = unpack_varlen_hex (p + 1, &tid);
2190 if (obuf)
2191 *obuf = pp;
ba348170 2192 return ptid_build (pid, tid, 0);
82f73884
PA
2193 }
2194
2195 /* No multi-process. Just a tid. */
2196 pp = unpack_varlen_hex (p, &tid);
2197
c9f35b34
KB
2198 /* Return null_ptid when no thread id is found. */
2199 if (p == pp)
2200 {
2201 if (obuf)
2202 *obuf = pp;
2203 return null_ptid;
2204 }
2205
82f73884 2206 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2207 what's in inferior_ptid, unless it's null at this point. If so,
2208 then since there's no way to know the pid of the reported
2209 threads, use the magic number. */
2210 if (ptid_equal (inferior_ptid, null_ptid))
2211 pid = ptid_get_pid (magic_null_ptid);
2212 else
2213 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2214
2215 if (obuf)
2216 *obuf = pp;
ba348170 2217 return ptid_build (pid, tid, 0);
82f73884
PA
2218}
2219
c906108c 2220static int
fba45db2 2221stubhex (int ch)
c906108c
SS
2222{
2223 if (ch >= 'a' && ch <= 'f')
2224 return ch - 'a' + 10;
2225 if (ch >= '0' && ch <= '9')
2226 return ch - '0';
2227 if (ch >= 'A' && ch <= 'F')
2228 return ch - 'A' + 10;
2229 return -1;
2230}
2231
2232static int
fba45db2 2233stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2234{
2235 int nibble;
2236 int retval = 0;
2237
2238 while (fieldlength)
2239 {
2240 nibble = stubhex (*buff++);
2241 retval |= nibble;
2242 fieldlength--;
2243 if (fieldlength)
2244 retval = retval << 4;
2245 }
2246 return retval;
2247}
2248
c906108c 2249static char *
fba45db2 2250unpack_nibble (char *buf, int *val)
c906108c 2251{
b7589f7d 2252 *val = fromhex (*buf++);
c906108c
SS
2253 return buf;
2254}
2255
c906108c 2256static char *
fba45db2 2257unpack_byte (char *buf, int *value)
c906108c
SS
2258{
2259 *value = stub_unpack_int (buf, 2);
2260 return buf + 2;
2261}
2262
2263static char *
fba45db2 2264pack_int (char *buf, int value)
c906108c
SS
2265{
2266 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2267 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2268 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2269 buf = pack_hex_byte (buf, (value & 0xff));
2270 return buf;
2271}
2272
2273static char *
fba45db2 2274unpack_int (char *buf, int *value)
c906108c
SS
2275{
2276 *value = stub_unpack_int (buf, 8);
2277 return buf + 8;
2278}
2279
23860348 2280#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2281static char *pack_string (char *pkt, char *string);
c906108c
SS
2282
2283static char *
fba45db2 2284pack_string (char *pkt, char *string)
c906108c
SS
2285{
2286 char ch;
2287 int len;
2288
2289 len = strlen (string);
2290 if (len > 200)
23860348 2291 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2292 pkt = pack_hex_byte (pkt, len);
2293 while (len-- > 0)
2294 {
2295 ch = *string++;
2296 if ((ch == '\0') || (ch == '#'))
23860348 2297 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2298 *pkt++ = ch;
2299 }
2300 return pkt;
2301}
2302#endif /* 0 (unused) */
2303
2304static char *
fba45db2 2305unpack_string (char *src, char *dest, int length)
c906108c
SS
2306{
2307 while (length--)
2308 *dest++ = *src++;
2309 *dest = '\0';
2310 return src;
2311}
2312
2313static char *
fba45db2 2314pack_threadid (char *pkt, threadref *id)
c906108c
SS
2315{
2316 char *limit;
2317 unsigned char *altid;
2318
2319 altid = (unsigned char *) id;
2320 limit = pkt + BUF_THREAD_ID_SIZE;
2321 while (pkt < limit)
2322 pkt = pack_hex_byte (pkt, *altid++);
2323 return pkt;
2324}
2325
2326
2327static char *
fba45db2 2328unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2329{
2330 char *altref;
2331 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2332 int x, y;
2333
2334 altref = (char *) id;
2335
2336 while (inbuf < limit)
2337 {
2338 x = stubhex (*inbuf++);
2339 y = stubhex (*inbuf++);
2340 *altref++ = (x << 4) | y;
2341 }
2342 return inbuf;
2343}
2344
2345/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2346 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2347 to use 64bit thread references internally. This is an adapter
2348 function. */
2349
2350void
fba45db2 2351int_to_threadref (threadref *id, int value)
c906108c
SS
2352{
2353 unsigned char *scan;
2354
2355 scan = (unsigned char *) id;
2356 {
2357 int i = 4;
2358 while (i--)
2359 *scan++ = 0;
2360 }
2361 *scan++ = (value >> 24) & 0xff;
2362 *scan++ = (value >> 16) & 0xff;
2363 *scan++ = (value >> 8) & 0xff;
2364 *scan++ = (value & 0xff);
2365}
2366
2367static int
fba45db2 2368threadref_to_int (threadref *ref)
c906108c
SS
2369{
2370 int i, value = 0;
2371 unsigned char *scan;
2372
cfd77fa1 2373 scan = *ref;
c906108c
SS
2374 scan += 4;
2375 i = 4;
2376 while (i-- > 0)
2377 value = (value << 8) | ((*scan++) & 0xff);
2378 return value;
2379}
2380
2381static void
fba45db2 2382copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2383{
2384 int i;
2385 unsigned char *csrc, *cdest;
2386
2387 csrc = (unsigned char *) src;
2388 cdest = (unsigned char *) dest;
2389 i = 8;
2390 while (i--)
2391 *cdest++ = *csrc++;
2392}
2393
2394static int
fba45db2 2395threadmatch (threadref *dest, threadref *src)
c906108c 2396{
23860348 2397 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2398#if 0
2399 unsigned char *srcp, *destp;
2400 int i, result;
2401 srcp = (char *) src;
2402 destp = (char *) dest;
2403
2404 result = 1;
2405 while (i-- > 0)
2406 result &= (*srcp++ == *destp++) ? 1 : 0;
2407 return result;
2408#endif
2409 return 1;
2410}
2411
2412/*
c5aa993b
JM
2413 threadid:1, # always request threadid
2414 context_exists:2,
2415 display:4,
2416 unique_name:8,
2417 more_display:16
2418 */
c906108c
SS
2419
2420/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2421
2422static char *
fba45db2 2423pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2424{
23860348
MS
2425 *pkt++ = 'q'; /* Info Query */
2426 *pkt++ = 'P'; /* process or thread info */
2427 pkt = pack_int (pkt, mode); /* mode */
c906108c 2428 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2429 *pkt = '\0'; /* terminate */
c906108c
SS
2430 return pkt;
2431}
2432
23860348 2433/* These values tag the fields in a thread info response packet. */
c906108c 2434/* Tagging the fields allows us to request specific fields and to
23860348 2435 add more fields as time goes by. */
c906108c 2436
23860348 2437#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2438#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2439 fetch registers and its stack? */
c5aa993b 2440#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2441#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2442#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2443 the process. */
c906108c
SS
2444
2445static int
fba45db2
KB
2446remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2447 struct gdb_ext_thread_info *info)
c906108c 2448{
d01949b6 2449 struct remote_state *rs = get_remote_state ();
c906108c 2450 int mask, length;
cfd77fa1 2451 int tag;
c906108c 2452 threadref ref;
6d820c5c 2453 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2454 int retval = 1;
2455
23860348 2456 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2457 info->active = 0;
2458 info->display[0] = '\0';
2459 info->shortname[0] = '\0';
2460 info->more_display[0] = '\0';
2461
23860348
MS
2462 /* Assume the characters indicating the packet type have been
2463 stripped. */
c906108c
SS
2464 pkt = unpack_int (pkt, &mask); /* arg mask */
2465 pkt = unpack_threadid (pkt, &ref);
2466
2467 if (mask == 0)
8a3fe4f8 2468 warning (_("Incomplete response to threadinfo request."));
c906108c 2469 if (!threadmatch (&ref, expectedref))
23860348 2470 { /* This is an answer to a different request. */
8a3fe4f8 2471 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2472 return 0;
2473 }
2474 copy_threadref (&info->threadid, &ref);
2475
23860348 2476 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2477
23860348
MS
2478 /* Packets are terminated with nulls. */
2479 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2480 {
2481 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2482 pkt = unpack_byte (pkt, &length); /* length */
2483 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2484 {
8a3fe4f8 2485 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2486 retval = 0;
2487 break;
2488 }
2489 if (tag == TAG_THREADID)
2490 {
2491 if (length != 16)
2492 {
8a3fe4f8 2493 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2494 retval = 0;
2495 break;
2496 }
2497 pkt = unpack_threadid (pkt, &ref);
2498 mask = mask & ~TAG_THREADID;
2499 continue;
2500 }
2501 if (tag == TAG_EXISTS)
2502 {
2503 info->active = stub_unpack_int (pkt, length);
2504 pkt += length;
2505 mask = mask & ~(TAG_EXISTS);
2506 if (length > 8)
2507 {
8a3fe4f8 2508 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2509 retval = 0;
2510 break;
2511 }
2512 continue;
2513 }
2514 if (tag == TAG_THREADNAME)
2515 {
2516 pkt = unpack_string (pkt, &info->shortname[0], length);
2517 mask = mask & ~TAG_THREADNAME;
2518 continue;
2519 }
2520 if (tag == TAG_DISPLAY)
2521 {
2522 pkt = unpack_string (pkt, &info->display[0], length);
2523 mask = mask & ~TAG_DISPLAY;
2524 continue;
2525 }
2526 if (tag == TAG_MOREDISPLAY)
2527 {
2528 pkt = unpack_string (pkt, &info->more_display[0], length);
2529 mask = mask & ~TAG_MOREDISPLAY;
2530 continue;
2531 }
8a3fe4f8 2532 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2533 break; /* Not a tag we know about. */
c906108c
SS
2534 }
2535 return retval;
2536}
2537
2538static int
fba45db2
KB
2539remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2540 struct gdb_ext_thread_info *info)
c906108c 2541{
d01949b6 2542 struct remote_state *rs = get_remote_state ();
c906108c 2543 int result;
c906108c 2544
2e9f7625
DJ
2545 pack_threadinfo_request (rs->buf, fieldset, threadid);
2546 putpkt (rs->buf);
6d820c5c 2547 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2548
2549 if (rs->buf[0] == '\0')
2550 return 0;
2551
2e9f7625 2552 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2553 threadid, info);
c906108c
SS
2554 return result;
2555}
2556
c906108c
SS
2557/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2558
2559static char *
fba45db2
KB
2560pack_threadlist_request (char *pkt, int startflag, int threadcount,
2561 threadref *nextthread)
c906108c
SS
2562{
2563 *pkt++ = 'q'; /* info query packet */
2564 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2565 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2566 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2567 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2568 *pkt = '\0';
2569 return pkt;
2570}
2571
2572/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2573
2574static int
fba45db2
KB
2575parse_threadlist_response (char *pkt, int result_limit,
2576 threadref *original_echo, threadref *resultlist,
2577 int *doneflag)
c906108c 2578{
d01949b6 2579 struct remote_state *rs = get_remote_state ();
c906108c
SS
2580 char *limit;
2581 int count, resultcount, done;
2582
2583 resultcount = 0;
2584 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2585 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2586 /* done parse past here */
c906108c
SS
2587 pkt = unpack_byte (pkt, &count); /* count field */
2588 pkt = unpack_nibble (pkt, &done);
2589 /* The first threadid is the argument threadid. */
2590 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2591 while ((count-- > 0) && (pkt < limit))
2592 {
2593 pkt = unpack_threadid (pkt, resultlist++);
2594 if (resultcount++ >= result_limit)
2595 break;
2596 }
2597 if (doneflag)
2598 *doneflag = done;
2599 return resultcount;
2600}
2601
6dc54d91
PA
2602/* Fetch the next batch of threads from the remote. Returns -1 if the
2603 qL packet is not supported, 0 on error and 1 on success. */
2604
c906108c 2605static int
fba45db2
KB
2606remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2607 int *done, int *result_count, threadref *threadlist)
c906108c 2608{
d01949b6 2609 struct remote_state *rs = get_remote_state ();
c906108c
SS
2610 int result = 1;
2611
23860348 2612 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2613 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2614 >= get_remote_packet_size ())
ea9c271d 2615 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2616
6d820c5c
DJ
2617 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2618 putpkt (rs->buf);
2619 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2620 if (*rs->buf == '\0')
6dc54d91
PA
2621 {
2622 /* Packet not supported. */
2623 return -1;
2624 }
2625
2626 *result_count =
2627 parse_threadlist_response (rs->buf + 2, result_limit,
2628 &rs->echo_nextthread, threadlist, done);
c906108c 2629
0d031856 2630 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2631 {
23860348
MS
2632 /* FIXME: This is a good reason to drop the packet. */
2633 /* Possably, there is a duplicate response. */
c906108c
SS
2634 /* Possabilities :
2635 retransmit immediatly - race conditions
2636 retransmit after timeout - yes
2637 exit
2638 wait for packet, then exit
2639 */
8a3fe4f8 2640 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2641 return 0; /* I choose simply exiting. */
c906108c
SS
2642 }
2643 if (*result_count <= 0)
2644 {
2645 if (*done != 1)
2646 {
8a3fe4f8 2647 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2648 result = 0;
2649 }
2650 return result; /* break; */
2651 }
2652 if (*result_count > result_limit)
2653 {
2654 *result_count = 0;
8a3fe4f8 2655 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2656 return 0;
2657 }
2658 return result;
2659}
2660
6dc54d91
PA
2661/* Fetch the list of remote threads, with the qL packet, and call
2662 STEPFUNCTION for each thread found. Stops iterating and returns 1
2663 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2664 STEPFUNCTION returns false. If the packet is not supported,
2665 returns -1. */
c906108c 2666
c906108c 2667static int
fba45db2
KB
2668remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2669 int looplimit)
c906108c 2670{
0d031856 2671 struct remote_state *rs = get_remote_state ();
c906108c
SS
2672 int done, i, result_count;
2673 int startflag = 1;
2674 int result = 1;
2675 int loopcount = 0;
c906108c
SS
2676
2677 done = 0;
2678 while (!done)
2679 {
2680 if (loopcount++ > looplimit)
2681 {
2682 result = 0;
8a3fe4f8 2683 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2684 break;
2685 }
6dc54d91
PA
2686 result = remote_get_threadlist (startflag, &rs->nextthread,
2687 MAXTHREADLISTRESULTS,
2688 &done, &result_count,
2689 rs->resultthreadlist);
2690 if (result <= 0)
2691 break;
23860348 2692 /* Clear for later iterations. */
c906108c
SS
2693 startflag = 0;
2694 /* Setup to resume next batch of thread references, set nextthread. */
2695 if (result_count >= 1)
0d031856
TT
2696 copy_threadref (&rs->nextthread,
2697 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2698 i = 0;
2699 while (result_count--)
6dc54d91
PA
2700 {
2701 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2702 {
2703 result = 0;
2704 break;
2705 }
2706 }
c906108c
SS
2707 }
2708 return result;
2709}
2710
6dc54d91
PA
2711/* A thread found on the remote target. */
2712
2713typedef struct thread_item
2714{
2715 /* The thread's PTID. */
2716 ptid_t ptid;
2717
2718 /* The thread's extra info. May be NULL. */
2719 char *extra;
2720
2721 /* The core the thread was running on. -1 if not known. */
2722 int core;
2723} thread_item_t;
2724DEF_VEC_O(thread_item_t);
2725
2726/* Context passed around to the various methods listing remote
2727 threads. As new threads are found, they're added to the ITEMS
2728 vector. */
2729
2730struct threads_listing_context
2731{
2732 /* The threads found on the remote target. */
2733 VEC (thread_item_t) *items;
2734};
2735
80134cf5
PA
2736/* Discard the contents of the constructed thread listing context. */
2737
2738static void
2739clear_threads_listing_context (void *p)
2740{
2741 struct threads_listing_context *context = p;
2742 int i;
2743 struct thread_item *item;
2744
2745 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2746 xfree (item->extra);
2747
2748 VEC_free (thread_item_t, context->items);
2749}
2750
cbb8991c
DB
2751/* Remove the thread specified as the related_pid field of WS
2752 from the CONTEXT list. */
2753
2754static void
2755threads_listing_context_remove (struct target_waitstatus *ws,
2756 struct threads_listing_context *context)
2757{
2758 struct thread_item *item;
2759 int i;
2760 ptid_t child_ptid = ws->value.related_pid;
2761
2762 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2763 {
2764 if (ptid_equal (item->ptid, child_ptid))
2765 {
2766 VEC_ordered_remove (thread_item_t, context->items, i);
2767 break;
2768 }
2769 }
2770}
2771
c906108c 2772static int
6dc54d91 2773remote_newthread_step (threadref *ref, void *data)
c906108c 2774{
6dc54d91
PA
2775 struct threads_listing_context *context = data;
2776 struct thread_item item;
79d7f229 2777 int pid = ptid_get_pid (inferior_ptid);
39f77062 2778
6dc54d91
PA
2779 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2780 item.core = -1;
2781 item.extra = NULL;
2782
2783 VEC_safe_push (thread_item_t, context->items, &item);
2784
c906108c
SS
2785 return 1; /* continue iterator */
2786}
2787
2788#define CRAZY_MAX_THREADS 1000
2789
39f77062
KB
2790static ptid_t
2791remote_current_thread (ptid_t oldpid)
c906108c 2792{
d01949b6 2793 struct remote_state *rs = get_remote_state ();
c906108c
SS
2794
2795 putpkt ("qC");
6d820c5c 2796 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2797 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
2798 {
2799 char *obuf;
2800 ptid_t result;
2801
2802 result = read_ptid (&rs->buf[2], &obuf);
2803 if (*obuf != '\0' && remote_debug)
2804 fprintf_unfiltered (gdb_stdlog,
2805 "warning: garbage in qC reply\n");
2806
2807 return result;
2808 }
c906108c
SS
2809 else
2810 return oldpid;
2811}
2812
6dc54d91 2813/* List remote threads using the deprecated qL packet. */
cce74817 2814
6dc54d91
PA
2815static int
2816remote_get_threads_with_ql (struct target_ops *ops,
2817 struct threads_listing_context *context)
c906108c 2818{
6dc54d91
PA
2819 if (remote_threadlist_iterator (remote_newthread_step, context,
2820 CRAZY_MAX_THREADS) >= 0)
2821 return 1;
2822
2823 return 0;
c906108c
SS
2824}
2825
dc146f7c
VP
2826#if defined(HAVE_LIBEXPAT)
2827
dc146f7c
VP
2828static void
2829start_thread (struct gdb_xml_parser *parser,
2830 const struct gdb_xml_element *element,
2831 void *user_data, VEC(gdb_xml_value_s) *attributes)
2832{
6dc54d91 2833 struct threads_listing_context *data = user_data;
dc146f7c
VP
2834
2835 struct thread_item item;
2836 char *id;
3d2c1d41 2837 struct gdb_xml_value *attr;
dc146f7c 2838
3d2c1d41 2839 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2840 item.ptid = read_ptid (id, NULL);
2841
3d2c1d41
PA
2842 attr = xml_find_attribute (attributes, "core");
2843 if (attr != NULL)
2844 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2845 else
2846 item.core = -1;
2847
2848 item.extra = 0;
2849
2850 VEC_safe_push (thread_item_t, data->items, &item);
2851}
2852
2853static void
2854end_thread (struct gdb_xml_parser *parser,
2855 const struct gdb_xml_element *element,
2856 void *user_data, const char *body_text)
2857{
6dc54d91 2858 struct threads_listing_context *data = user_data;
dc146f7c
VP
2859
2860 if (body_text && *body_text)
2ae2a0b7 2861 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2862}
2863
2864const struct gdb_xml_attribute thread_attributes[] = {
2865 { "id", GDB_XML_AF_NONE, NULL, NULL },
2866 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2867 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2868};
2869
2870const struct gdb_xml_element thread_children[] = {
2871 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2872};
2873
2874const struct gdb_xml_element threads_children[] = {
2875 { "thread", thread_attributes, thread_children,
2876 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2877 start_thread, end_thread },
2878 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2879};
2880
2881const struct gdb_xml_element threads_elements[] = {
2882 { "threads", NULL, threads_children,
2883 GDB_XML_EF_NONE, NULL, NULL },
2884 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2885};
2886
2887#endif
2888
6dc54d91 2889/* List remote threads using qXfer:threads:read. */
9d1f7ab2 2890
6dc54d91
PA
2891static int
2892remote_get_threads_with_qxfer (struct target_ops *ops,
2893 struct threads_listing_context *context)
0f71a2f6 2894{
dc146f7c 2895#if defined(HAVE_LIBEXPAT)
4082afcc 2896 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 2897 {
6dc54d91 2898 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 2899 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2900
6dc54d91 2901 if (xml != NULL && *xml != '\0')
dc146f7c 2902 {
6dc54d91
PA
2903 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2904 threads_elements, xml, context);
dc146f7c
VP
2905 }
2906
2907 do_cleanups (back_to);
6dc54d91 2908 return 1;
dc146f7c
VP
2909 }
2910#endif
2911
6dc54d91
PA
2912 return 0;
2913}
2914
2915/* List remote threads using qfThreadInfo/qsThreadInfo. */
2916
2917static int
2918remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2919 struct threads_listing_context *context)
2920{
2921 struct remote_state *rs = get_remote_state ();
2922
b80fafe3 2923 if (rs->use_threadinfo_query)
9d1f7ab2 2924 {
6dc54d91
PA
2925 char *bufp;
2926
9d1f7ab2 2927 putpkt ("qfThreadInfo");
6d820c5c 2928 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2929 bufp = rs->buf;
9d1f7ab2 2930 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2931 {
9d1f7ab2
MS
2932 while (*bufp++ == 'm') /* reply contains one or more TID */
2933 {
2934 do
2935 {
6dc54d91
PA
2936 struct thread_item item;
2937
2938 item.ptid = read_ptid (bufp, &bufp);
2939 item.core = -1;
2940 item.extra = NULL;
2941
2942 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
2943 }
2944 while (*bufp++ == ','); /* comma-separated list */
2945 putpkt ("qsThreadInfo");
6d820c5c 2946 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 2947 bufp = rs->buf;
9d1f7ab2 2948 }
6dc54d91
PA
2949 return 1;
2950 }
2951 else
2952 {
2953 /* Packet not recognized. */
2954 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
2955 }
2956 }
2957
6dc54d91
PA
2958 return 0;
2959}
2960
e8032dde 2961/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
2962 targets. */
2963
2964static void
e8032dde 2965remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
2966{
2967 struct remote_state *rs = get_remote_state ();
2968 struct threads_listing_context context;
2969 struct cleanup *old_chain;
ab970af1 2970 int got_list = 0;
e8032dde 2971
6dc54d91
PA
2972 context.items = NULL;
2973 old_chain = make_cleanup (clear_threads_listing_context, &context);
2974
2975 /* We have a few different mechanisms to fetch the thread list. Try
2976 them all, starting with the most preferred one first, falling
2977 back to older methods. */
2978 if (remote_get_threads_with_qxfer (ops, &context)
2979 || remote_get_threads_with_qthreadinfo (ops, &context)
2980 || remote_get_threads_with_ql (ops, &context))
2981 {
2982 int i;
2983 struct thread_item *item;
ab970af1
PA
2984 struct thread_info *tp, *tmp;
2985
2986 got_list = 1;
2987
7d1a114c
PA
2988 if (VEC_empty (thread_item_t, context.items)
2989 && remote_thread_always_alive (ops, inferior_ptid))
2990 {
2991 /* Some targets don't really support threads, but still
2992 reply an (empty) thread list in response to the thread
2993 listing packets, instead of replying "packet not
2994 supported". Exit early so we don't delete the main
2995 thread. */
2996 do_cleanups (old_chain);
2997 return;
2998 }
2999
ab970af1
PA
3000 /* CONTEXT now holds the current thread list on the remote
3001 target end. Delete GDB-side threads no longer found on the
3002 target. */
8a06aea7 3003 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3004 {
ab970af1
PA
3005 for (i = 0;
3006 VEC_iterate (thread_item_t, context.items, i, item);
3007 ++i)
3008 {
3009 if (ptid_equal (item->ptid, tp->ptid))
3010 break;
3011 }
3012
3013 if (i == VEC_length (thread_item_t, context.items))
3014 {
3015 /* Not found. */
3016 delete_thread (tp->ptid);
3017 }
cbb8991c
DB
3018 }
3019
3020 /* Remove any unreported fork child threads from CONTEXT so
3021 that we don't interfere with follow fork, which is where
3022 creation of such threads is handled. */
3023 remove_new_fork_children (&context);
74531fed 3024
ab970af1 3025 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3026 for (i = 0;
3027 VEC_iterate (thread_item_t, context.items, i, item);
3028 ++i)
3029 {
3030 if (!ptid_equal (item->ptid, null_ptid))
3031 {
3032 struct private_thread_info *info;
3033 /* In non-stop mode, we assume new found threads are
3034 running until proven otherwise with a stop reply. In
3035 all-stop, we can only get here if all threads are
3036 stopped. */
3037 int running = non_stop ? 1 : 0;
3038
3039 remote_notice_new_inferior (item->ptid, running);
3040
3041 info = demand_private_info (item->ptid);
3042 info->core = item->core;
3043 info->extra = item->extra;
3044 item->extra = NULL;
3045 }
3046 }
3047 }
3048
ab970af1
PA
3049 if (!got_list)
3050 {
3051 /* If no thread listing method is supported, then query whether
3052 each known thread is alive, one by one, with the T packet.
3053 If the target doesn't support threads at all, then this is a
3054 no-op. See remote_thread_alive. */
3055 prune_threads ();
3056 }
3057
6dc54d91 3058 do_cleanups (old_chain);
9d1f7ab2
MS
3059}
3060
802188a7 3061/*
9d1f7ab2
MS
3062 * Collect a descriptive string about the given thread.
3063 * The target may say anything it wants to about the thread
3064 * (typically info about its blocked / runnable state, name, etc.).
3065 * This string will appear in the info threads display.
802188a7 3066 *
9d1f7ab2
MS
3067 * Optional: targets are not required to implement this function.
3068 */
3069
3070static char *
c15906d8 3071remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3072{
d01949b6 3073 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3074 int result;
3075 int set;
3076 threadref id;
3077 struct gdb_ext_thread_info threadinfo;
23860348 3078 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3079 int n = 0; /* position in display_buf */
3080
5d93a237 3081 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3082 internal_error (__FILE__, __LINE__,
e2e0b3e5 3083 _("remote_threads_extra_info"));
9d1f7ab2 3084
60e569b9 3085 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3086 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3087 /* This is the main thread which was added by GDB. The remote
3088 server doesn't know about it. */
3089 return NULL;
3090
4082afcc 3091 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3092 {
3093 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3094
fe978cb0
PA
3095 if (info && info->priv)
3096 return info->priv->extra;
dc146f7c
VP
3097 else
3098 return NULL;
3099 }
3100
b80fafe3 3101 if (rs->use_threadextra_query)
9d1f7ab2 3102 {
82f73884
PA
3103 char *b = rs->buf;
3104 char *endb = rs->buf + get_remote_packet_size ();
3105
3106 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3107 b += strlen (b);
3108 write_ptid (b, endb, tp->ptid);
3109
2e9f7625 3110 putpkt (rs->buf);
6d820c5c 3111 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3112 if (rs->buf[0] != 0)
9d1f7ab2 3113 {
2e9f7625
DJ
3114 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3115 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3116 display_buf [result] = '\0';
9d1f7ab2
MS
3117 return display_buf;
3118 }
0f71a2f6 3119 }
9d1f7ab2
MS
3120
3121 /* If the above query fails, fall back to the old method. */
b80fafe3 3122 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3123 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3124 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3125 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3126 if (remote_get_threadinfo (&id, set, &threadinfo))
3127 if (threadinfo.active)
0f71a2f6 3128 {
9d1f7ab2 3129 if (*threadinfo.shortname)
2bc416ba 3130 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3131 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3132 if (*threadinfo.display)
2bc416ba 3133 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3134 " State: %s,", threadinfo.display);
9d1f7ab2 3135 if (*threadinfo.more_display)
2bc416ba 3136 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3137 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3138
3139 if (n > 0)
c5aa993b 3140 {
23860348 3141 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3142 if (',' == display_buf[n-1])
3143 display_buf[n-1] = ' ';
3144 return display_buf;
c5aa993b 3145 }
0f71a2f6 3146 }
9d1f7ab2 3147 return NULL;
0f71a2f6 3148}
c906108c 3149\f
c5aa993b 3150
0fb4aa4b 3151static int
61fc905d 3152remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3153 struct static_tracepoint_marker *marker)
3154{
3155 struct remote_state *rs = get_remote_state ();
3156 char *p = rs->buf;
3157
bba74b36 3158 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3159 p += strlen (p);
3160 p += hexnumstr (p, addr);
3161 putpkt (rs->buf);
3162 getpkt (&rs->buf, &rs->buf_size, 0);
3163 p = rs->buf;
3164
3165 if (*p == 'E')
3166 error (_("Remote failure reply: %s"), p);
3167
3168 if (*p++ == 'm')
3169 {
3170 parse_static_tracepoint_marker_definition (p, &p, marker);
3171 return 1;
3172 }
3173
3174 return 0;
3175}
3176
0fb4aa4b 3177static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3178remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3179 const char *strid)
0fb4aa4b
PA
3180{
3181 struct remote_state *rs = get_remote_state ();
3182 VEC(static_tracepoint_marker_p) *markers = NULL;
3183 struct static_tracepoint_marker *marker = NULL;
3184 struct cleanup *old_chain;
3185 char *p;
3186
3187 /* Ask for a first packet of static tracepoint marker
3188 definition. */
3189 putpkt ("qTfSTM");
3190 getpkt (&rs->buf, &rs->buf_size, 0);
3191 p = rs->buf;
3192 if (*p == 'E')
3193 error (_("Remote failure reply: %s"), p);
3194
3195 old_chain = make_cleanup (free_current_marker, &marker);
3196
3197 while (*p++ == 'm')
3198 {
3199 if (marker == NULL)
3200 marker = XCNEW (struct static_tracepoint_marker);
3201
3202 do
3203 {
3204 parse_static_tracepoint_marker_definition (p, &p, marker);
3205
3206 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3207 {
3208 VEC_safe_push (static_tracepoint_marker_p,
3209 markers, marker);
3210 marker = NULL;
3211 }
3212 else
3213 {
3214 release_static_tracepoint_marker (marker);
3215 memset (marker, 0, sizeof (*marker));
3216 }
3217 }
3218 while (*p++ == ','); /* comma-separated list */
3219 /* Ask for another packet of static tracepoint definition. */
3220 putpkt ("qTsSTM");
3221 getpkt (&rs->buf, &rs->buf_size, 0);
3222 p = rs->buf;
3223 }
3224
3225 do_cleanups (old_chain);
3226 return markers;
3227}
3228
3229\f
10760264
JB
3230/* Implement the to_get_ada_task_ptid function for the remote targets. */
3231
3232static ptid_t
1e6b91a4 3233remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3234{
ba348170 3235 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3236}
3237\f
3238
24b06219 3239/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3240
3241static void
fba45db2 3242extended_remote_restart (void)
c906108c 3243{
d01949b6 3244 struct remote_state *rs = get_remote_state ();
c906108c
SS
3245
3246 /* Send the restart command; for reasons I don't understand the
3247 remote side really expects a number after the "R". */
ea9c271d 3248 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3249 putpkt (rs->buf);
c906108c 3250
ad9a8f3f 3251 remote_fileio_reset ();
c906108c
SS
3252}
3253\f
3254/* Clean up connection to a remote debugger. */
3255
c906108c 3256static void
de90e03d 3257remote_close (struct target_ops *self)
c906108c 3258{
5d93a237
TT
3259 struct remote_state *rs = get_remote_state ();
3260
3261 if (rs->remote_desc == NULL)
d3fd5342
PA
3262 return; /* already closed */
3263
3264 /* Make sure we leave stdin registered in the event loop, and we
3265 don't leave the async SIGINT signal handler installed. */
e3594fd1 3266 remote_terminal_ours (self);
ce5ce7ed 3267
5d93a237
TT
3268 serial_close (rs->remote_desc);
3269 rs->remote_desc = NULL;
ce5ce7ed
PA
3270
3271 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3272 of all the inferiors and their threads we were controlling.
3273 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3274 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3275 inferior_ptid = null_ptid;
f67fd822 3276 discard_all_inferiors ();
ce5ce7ed 3277
f48ff2a7
YQ
3278 /* We are closing the remote target, so we should discard
3279 everything of this target. */
bcc75809 3280 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3281
3282 if (remote_async_inferior_event_token)
3283 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3284
5965e028 3285 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3286
3287 trace_reset_local_state ();
c906108c
SS
3288}
3289
23860348 3290/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3291
3292static void
fba45db2 3293get_offsets (void)
c906108c 3294{
d01949b6 3295 struct remote_state *rs = get_remote_state ();
2e9f7625 3296 char *buf;
085dd6e6 3297 char *ptr;
31d99776
DJ
3298 int lose, num_segments = 0, do_sections, do_segments;
3299 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3300 struct section_offsets *offs;
31d99776
DJ
3301 struct symfile_segment_data *data;
3302
3303 if (symfile_objfile == NULL)
3304 return;
c906108c
SS
3305
3306 putpkt ("qOffsets");
6d820c5c 3307 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3308 buf = rs->buf;
c906108c
SS
3309
3310 if (buf[0] == '\000')
3311 return; /* Return silently. Stub doesn't support
23860348 3312 this command. */
c906108c
SS
3313 if (buf[0] == 'E')
3314 {
8a3fe4f8 3315 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3316 return;
3317 }
3318
3319 /* Pick up each field in turn. This used to be done with scanf, but
3320 scanf will make trouble if CORE_ADDR size doesn't match
3321 conversion directives correctly. The following code will work
3322 with any size of CORE_ADDR. */
3323 text_addr = data_addr = bss_addr = 0;
3324 ptr = buf;
3325 lose = 0;
3326
61012eef 3327 if (startswith (ptr, "Text="))
c906108c
SS
3328 {
3329 ptr += 5;
3330 /* Don't use strtol, could lose on big values. */
3331 while (*ptr && *ptr != ';')
3332 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3333
61012eef 3334 if (startswith (ptr, ";Data="))
31d99776
DJ
3335 {
3336 ptr += 6;
3337 while (*ptr && *ptr != ';')
3338 data_addr = (data_addr << 4) + fromhex (*ptr++);
3339 }
3340 else
3341 lose = 1;
3342
61012eef 3343 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3344 {
3345 ptr += 5;
3346 while (*ptr && *ptr != ';')
3347 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3348
31d99776
DJ
3349 if (bss_addr != data_addr)
3350 warning (_("Target reported unsupported offsets: %s"), buf);
3351 }
3352 else
3353 lose = 1;
3354 }
61012eef 3355 else if (startswith (ptr, "TextSeg="))
c906108c 3356 {
31d99776
DJ
3357 ptr += 8;
3358 /* Don't use strtol, could lose on big values. */
c906108c 3359 while (*ptr && *ptr != ';')
31d99776
DJ
3360 text_addr = (text_addr << 4) + fromhex (*ptr++);
3361 num_segments = 1;
3362
61012eef 3363 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3364 {
3365 ptr += 9;
3366 while (*ptr && *ptr != ';')
3367 data_addr = (data_addr << 4) + fromhex (*ptr++);
3368 num_segments++;
3369 }
c906108c
SS
3370 }
3371 else
3372 lose = 1;
3373
3374 if (lose)
8a3fe4f8 3375 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3376 else if (*ptr != '\0')
3377 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3378
802188a7 3379 offs = ((struct section_offsets *)
a39a16c4 3380 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3381 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3382 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3383
31d99776
DJ
3384 data = get_symfile_segment_data (symfile_objfile->obfd);
3385 do_segments = (data != NULL);
3386 do_sections = num_segments == 0;
c906108c 3387
28c32713 3388 if (num_segments > 0)
31d99776 3389 {
31d99776
DJ
3390 segments[0] = text_addr;
3391 segments[1] = data_addr;
3392 }
28c32713
JB
3393 /* If we have two segments, we can still try to relocate everything
3394 by assuming that the .text and .data offsets apply to the whole
3395 text and data segments. Convert the offsets given in the packet
3396 to base addresses for symfile_map_offsets_to_segments. */
3397 else if (data && data->num_segments == 2)
3398 {
3399 segments[0] = data->segment_bases[0] + text_addr;
3400 segments[1] = data->segment_bases[1] + data_addr;
3401 num_segments = 2;
3402 }
8d385431
DJ
3403 /* If the object file has only one segment, assume that it is text
3404 rather than data; main programs with no writable data are rare,
3405 but programs with no code are useless. Of course the code might
3406 have ended up in the data segment... to detect that we would need
3407 the permissions here. */
3408 else if (data && data->num_segments == 1)
3409 {
3410 segments[0] = data->segment_bases[0] + text_addr;
3411 num_segments = 1;
3412 }
28c32713
JB
3413 /* There's no way to relocate by segment. */
3414 else
3415 do_segments = 0;
31d99776
DJ
3416
3417 if (do_segments)
3418 {
3419 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3420 offs, num_segments, segments);
3421
3422 if (ret == 0 && !do_sections)
3e43a32a
MS
3423 error (_("Can not handle qOffsets TextSeg "
3424 "response with this symbol file"));
31d99776
DJ
3425
3426 if (ret > 0)
3427 do_sections = 0;
3428 }
c906108c 3429
9ef895d6
DJ
3430 if (data)
3431 free_symfile_segment_data (data);
31d99776
DJ
3432
3433 if (do_sections)
3434 {
3435 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3436
3e43a32a
MS
3437 /* This is a temporary kludge to force data and bss to use the
3438 same offsets because that's what nlmconv does now. The real
3439 solution requires changes to the stub and remote.c that I
3440 don't have time to do right now. */
31d99776
DJ
3441
3442 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3443 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3444 }
c906108c
SS
3445
3446 objfile_relocate (symfile_objfile, offs);
3447}
3448
9a7071a8
JB
3449/* Send interrupt_sequence to remote target. */
3450static void
eeae04df 3451send_interrupt_sequence (void)
9a7071a8 3452{
5d93a237
TT
3453 struct remote_state *rs = get_remote_state ();
3454
9a7071a8 3455 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3456 remote_serial_write ("\x03", 1);
9a7071a8 3457 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3458 serial_send_break (rs->remote_desc);
9a7071a8
JB
3459 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3460 {
5d93a237 3461 serial_send_break (rs->remote_desc);
c33e31fd 3462 remote_serial_write ("g", 1);
9a7071a8
JB
3463 }
3464 else
3465 internal_error (__FILE__, __LINE__,
3466 _("Invalid value for interrupt_sequence_mode: %s."),
3467 interrupt_sequence_mode);
3468}
3469
3405876a
PA
3470
3471/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3472 and extract the PTID. Returns NULL_PTID if not found. */
3473
3474static ptid_t
3475stop_reply_extract_thread (char *stop_reply)
3476{
3477 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3478 {
3479 char *p;
3480
3481 /* Txx r:val ; r:val (...) */
3482 p = &stop_reply[3];
3483
3484 /* Look for "register" named "thread". */
3485 while (*p != '\0')
3486 {
3487 char *p1;
3488
3489 p1 = strchr (p, ':');
3490 if (p1 == NULL)
3491 return null_ptid;
3492
3493 if (strncmp (p, "thread", p1 - p) == 0)
3494 return read_ptid (++p1, &p);
3495
3496 p1 = strchr (p, ';');
3497 if (p1 == NULL)
3498 return null_ptid;
3499 p1++;
3500
3501 p = p1;
3502 }
3503 }
3504
3505 return null_ptid;
3506}
3507
b7ea362b
PA
3508/* Determine the remote side's current thread. If we have a stop
3509 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3510 "thread" register we can extract the current thread from. If not,
3511 ask the remote which is the current thread with qC. The former
3512 method avoids a roundtrip. */
3513
3514static ptid_t
3515get_current_thread (char *wait_status)
3516{
6a49a997 3517 ptid_t ptid = null_ptid;
b7ea362b
PA
3518
3519 /* Note we don't use remote_parse_stop_reply as that makes use of
3520 the target architecture, which we haven't yet fully determined at
3521 this point. */
3522 if (wait_status != NULL)
3523 ptid = stop_reply_extract_thread (wait_status);
3524 if (ptid_equal (ptid, null_ptid))
3525 ptid = remote_current_thread (inferior_ptid);
3526
3527 return ptid;
3528}
3529
49c62f2e
PA
3530/* Query the remote target for which is the current thread/process,
3531 add it to our tables, and update INFERIOR_PTID. The caller is
3532 responsible for setting the state such that the remote end is ready
3405876a
PA
3533 to return the current thread.
3534
3535 This function is called after handling the '?' or 'vRun' packets,
3536 whose response is a stop reply from which we can also try
3537 extracting the thread. If the target doesn't support the explicit
3538 qC query, we infer the current thread from that stop reply, passed
3539 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3540
3541static void
3405876a 3542add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3543{
3544 struct remote_state *rs = get_remote_state ();
3545 int fake_pid_p = 0;
6a49a997 3546 ptid_t ptid;
49c62f2e
PA
3547
3548 inferior_ptid = null_ptid;
3549
b7ea362b
PA
3550 /* Now, if we have thread information, update inferior_ptid. */
3551 ptid = get_current_thread (wait_status);
3405876a 3552
49c62f2e
PA
3553 if (!ptid_equal (ptid, null_ptid))
3554 {
3555 if (!remote_multi_process_p (rs))
3556 fake_pid_p = 1;
3557
3558 inferior_ptid = ptid;
3559 }
3560 else
3561 {
3562 /* Without this, some commands which require an active target
3563 (such as kill) won't work. This variable serves (at least)
3564 double duty as both the pid of the target process (if it has
3565 such), and as a flag indicating that a target is active. */
3566 inferior_ptid = magic_null_ptid;
3567 fake_pid_p = 1;
3568 }
3569
1b6e6f5c 3570 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3571
3572 /* Add the main thread. */
3573 add_thread_silent (inferior_ptid);
3574}
3575
221e1a37
PA
3576/* Process all initial stop replies the remote side sent in response
3577 to the ? packet. These indicate threads that were already stopped
3578 on initial connection. We mark these threads as stopped and print
3579 their current frame before giving the user the prompt. */
3580
3581static void
3582process_initial_stop_replies (void)
3583{
3584 int pending_stop_replies = stop_reply_queue_length ();
3585
3586 /* Consume the initial pending events. */
3587 while (pending_stop_replies-- > 0)
3588 {
3589 ptid_t waiton_ptid = minus_one_ptid;
3590 ptid_t event_ptid;
3591 struct target_waitstatus ws;
3592 int ignore_event = 0;
3593
3594 memset (&ws, 0, sizeof (ws));
3595 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3596 if (remote_debug)
3597 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3598
3599 switch (ws.kind)
3600 {
3601 case TARGET_WAITKIND_IGNORE:
3602 case TARGET_WAITKIND_NO_RESUMED:
3603 case TARGET_WAITKIND_SIGNALLED:
3604 case TARGET_WAITKIND_EXITED:
3605 /* We shouldn't see these, but if we do, just ignore. */
3606 if (remote_debug)
3607 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3608 ignore_event = 1;
3609 break;
3610
3611 case TARGET_WAITKIND_EXECD:
3612 xfree (ws.value.execd_pathname);
3613 break;
3614 default:
3615 break;
3616 }
3617
3618 if (ignore_event)
3619 continue;
3620
3621 switch_to_thread (event_ptid);
3622 set_executing (event_ptid, 0);
3623 set_running (event_ptid, 0);
3624
3625 stop_pc = get_frame_pc (get_current_frame ());
3626 set_current_sal_from_frame (get_current_frame ());
3627
3628 if (ws.kind == TARGET_WAITKIND_STOPPED)
3629 {
3630 enum gdb_signal sig = ws.value.sig;
3631
3632 /* Stubs traditionally report SIGTRAP as initial signal,
3633 instead of signal 0. Suppress it. */
3634 if (sig == GDB_SIGNAL_TRAP)
3635 sig = GDB_SIGNAL_0;
3636 inferior_thread ()->suspend.stop_signal = sig;
3637
3638 if (signal_print_state (sig))
3639 observer_notify_signal_received (sig);
3640 }
3641
3642 print_stop_event (&ws);
3643 observer_notify_normal_stop (NULL, 1);
3644 }
3645}
3646
9cbc821d 3647static void
04bd08de 3648remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3649{
c8d104ad
PA
3650 struct remote_state *rs = get_remote_state ();
3651 struct packet_config *noack_config;
2d717e4f 3652 char *wait_status = NULL;
8621d6a9 3653
23860348 3654 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3655 QUIT;
c906108c 3656
9a7071a8
JB
3657 if (interrupt_on_connect)
3658 send_interrupt_sequence ();
3659
57e12211 3660 /* Ack any packet which the remote side has already sent. */
5d93a237 3661 serial_write (rs->remote_desc, "+", 1);
57e12211 3662
1e51243a
PA
3663 /* Signal other parts that we're going through the initial setup,
3664 and so things may not be stable yet. */
3665 rs->starting_up = 1;
3666
c8d104ad
PA
3667 /* The first packet we send to the target is the optional "supported
3668 packets" request. If the target can answer this, it will tell us
3669 which later probes to skip. */
3670 remote_query_supported ();
3671
d914c394 3672 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3673 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3674 remote_set_permissions (target);
d914c394 3675
c8d104ad
PA
3676 /* Next, we possibly activate noack mode.
3677
3678 If the QStartNoAckMode packet configuration is set to AUTO,
3679 enable noack mode if the stub reported a wish for it with
3680 qSupported.
3681
3682 If set to TRUE, then enable noack mode even if the stub didn't
3683 report it in qSupported. If the stub doesn't reply OK, the
3684 session ends with an error.
3685
3686 If FALSE, then don't activate noack mode, regardless of what the
3687 stub claimed should be the default with qSupported. */
3688
3689 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3690 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3691 {
3692 putpkt ("QStartNoAckMode");
3693 getpkt (&rs->buf, &rs->buf_size, 0);
3694 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3695 rs->noack_mode = 1;
3696 }
3697
04bd08de 3698 if (extended_p)
5fe04517
PA
3699 {
3700 /* Tell the remote that we are using the extended protocol. */
3701 putpkt ("!");
3702 getpkt (&rs->buf, &rs->buf_size, 0);
3703 }
3704
9b224c5e
PA
3705 /* Let the target know which signals it is allowed to pass down to
3706 the program. */
3707 update_signals_program_target ();
3708
d962ef82
DJ
3709 /* Next, if the target can specify a description, read it. We do
3710 this before anything involving memory or registers. */
3711 target_find_description ();
3712
6c95b8df
PA
3713 /* Next, now that we know something about the target, update the
3714 address spaces in the program spaces. */
3715 update_address_spaces ();
3716
50c71eaf
PA
3717 /* On OSs where the list of libraries is global to all
3718 processes, we fetch them early. */
f5656ead 3719 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3720 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3721
74531fed
PA
3722 if (non_stop)
3723 {
4082afcc 3724 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3725 error (_("Non-stop mode requested, but remote "
3726 "does not support non-stop"));
74531fed
PA
3727
3728 putpkt ("QNonStop:1");
3729 getpkt (&rs->buf, &rs->buf_size, 0);
3730
3731 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3732 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3733
3734 /* Find about threads and processes the stub is already
3735 controlling. We default to adding them in the running state.
3736 The '?' query below will then tell us about which threads are
3737 stopped. */
e8032dde 3738 remote_update_thread_list (target);
74531fed 3739 }
4082afcc 3740 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3741 {
3742 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3743 Request it explicitly. */
74531fed
PA
3744 putpkt ("QNonStop:0");
3745 getpkt (&rs->buf, &rs->buf_size, 0);
3746
3747 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3748 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3749 }
3750
a0743c90
YQ
3751 /* Upload TSVs regardless of whether the target is running or not. The
3752 remote stub, such as GDBserver, may have some predefined or builtin
3753 TSVs, even if the target is not running. */
8bd200f1 3754 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
3755 {
3756 struct uploaded_tsv *uploaded_tsvs = NULL;
3757
181e3713 3758 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
3759 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3760 }
3761
2d717e4f
DJ
3762 /* Check whether the target is running now. */
3763 putpkt ("?");
3764 getpkt (&rs->buf, &rs->buf_size, 0);
3765
74531fed 3766 if (!non_stop)
2d717e4f 3767 {
e714e1bf
UW
3768 ptid_t ptid;
3769 int fake_pid_p = 0;
3770 struct inferior *inf;
3771
74531fed 3772 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3773 {
04bd08de 3774 if (!extended_p)
74531fed 3775 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3776
3777 /* We're connected, but not running. Drop out before we
3778 call start_remote. */
e278ad5b 3779 rs->starting_up = 0;
c35b1492 3780 return;
2d717e4f
DJ
3781 }
3782 else
74531fed 3783 {
74531fed
PA
3784 /* Save the reply for later. */
3785 wait_status = alloca (strlen (rs->buf) + 1);
3786 strcpy (wait_status, rs->buf);
3787 }
3788
b7ea362b 3789 /* Fetch thread list. */
e8032dde 3790 target_update_thread_list ();
b7ea362b 3791
74531fed
PA
3792 /* Let the stub know that we want it to return the thread. */
3793 set_continue_thread (minus_one_ptid);
3794
b7ea362b
PA
3795 if (thread_count () == 0)
3796 {
3797 /* Target has no concept of threads at all. GDB treats
3798 non-threaded target as single-threaded; add a main
3799 thread. */
3800 add_current_inferior_and_thread (wait_status);
3801 }
3802 else
3803 {
3804 /* We have thread information; select the thread the target
3805 says should be current. If we're reconnecting to a
3806 multi-threaded program, this will ideally be the thread
3807 that last reported an event before GDB disconnected. */
3808 inferior_ptid = get_current_thread (wait_status);
3809 if (ptid_equal (inferior_ptid, null_ptid))
3810 {
3811 /* Odd... The target was able to list threads, but not
3812 tell us which thread was current (no "thread"
3813 register in T stop reply?). Just pick the first
3814 thread in the thread list then. */
c9f35b34
KB
3815
3816 if (remote_debug)
3817 fprintf_unfiltered (gdb_stdlog,
3818 "warning: couldn't determine remote "
3819 "current thread; picking first in list.\n");
3820
b7ea362b
PA
3821 inferior_ptid = thread_list->ptid;
3822 }
3823 }
74531fed 3824
6e586cc5
YQ
3825 /* init_wait_for_inferior should be called before get_offsets in order
3826 to manage `inserted' flag in bp loc in a correct state.
3827 breakpoint_init_inferior, called from init_wait_for_inferior, set
3828 `inserted' flag to 0, while before breakpoint_re_set, called from
3829 start_remote, set `inserted' flag to 1. In the initialization of
3830 inferior, breakpoint_init_inferior should be called first, and then
3831 breakpoint_re_set can be called. If this order is broken, state of
3832 `inserted' flag is wrong, and cause some problems on breakpoint
3833 manipulation. */
3834 init_wait_for_inferior ();
3835
74531fed
PA
3836 get_offsets (); /* Get text, data & bss offsets. */
3837
d962ef82
DJ
3838 /* If we could not find a description using qXfer, and we know
3839 how to do it some other way, try again. This is not
3840 supported for non-stop; it could be, but it is tricky if
3841 there are no stopped threads when we connect. */
04bd08de 3842 if (remote_read_description_p (target)
f5656ead 3843 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
3844 {
3845 target_clear_description ();
3846 target_find_description ();
3847 }
3848
74531fed
PA
3849 /* Use the previously fetched status. */
3850 gdb_assert (wait_status != NULL);
3851 strcpy (rs->buf, wait_status);
3852 rs->cached_wait_status = 1;
3853
3854 immediate_quit--;
04bd08de 3855 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3856 }
3857 else
3858 {
221e1a37
PA
3859 ptid_t current_ptid;
3860
68c97600
PA
3861 /* Clear WFI global state. Do this before finding about new
3862 threads and inferiors, and setting the current inferior.
3863 Otherwise we would clear the proceed status of the current
3864 inferior when we want its stop_soon state to be preserved
3865 (see notice_new_inferior). */
3866 init_wait_for_inferior ();
3867
74531fed
PA
3868 /* In non-stop, we will either get an "OK", meaning that there
3869 are no stopped threads at this time; or, a regular stop
3870 reply. In the latter case, there may be more than one thread
3871 stopped --- we pull them all out using the vStopped
3872 mechanism. */
3873 if (strcmp (rs->buf, "OK") != 0)
3874 {
722247f1 3875 struct notif_client *notif = &notif_client_stop;
2d717e4f 3876
722247f1
YQ
3877 /* remote_notif_get_pending_replies acks this one, and gets
3878 the rest out. */
f48ff2a7 3879 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
3880 = remote_notif_parse (notif, rs->buf);
3881 remote_notif_get_pending_events (notif);
74531fed 3882 }
2d717e4f 3883
74531fed
PA
3884 if (thread_count () == 0)
3885 {
04bd08de 3886 if (!extended_p)
74531fed 3887 error (_("The target is not running (try extended-remote?)"));
82f73884 3888
c35b1492
PA
3889 /* We're connected, but not running. Drop out before we
3890 call start_remote. */
e278ad5b 3891 rs->starting_up = 0;
c35b1492
PA
3892 return;
3893 }
74531fed
PA
3894
3895 /* Let the stub know that we want it to return the thread. */
c0a2216e 3896
74531fed
PA
3897 /* Force the stub to choose a thread. */
3898 set_general_thread (null_ptid);
c906108c 3899
74531fed 3900 /* Query it. */
221e1a37 3901 current_ptid = remote_current_thread (minus_one_ptid);
74531fed
PA
3902 if (ptid_equal (inferior_ptid, minus_one_ptid))
3903 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3904
221e1a37 3905 inferior_ptid = current_ptid;
74531fed
PA
3906 get_offsets (); /* Get text, data & bss offsets. */
3907
3908 /* In non-stop mode, any cached wait status will be stored in
3909 the stop reply queue. */
3910 gdb_assert (wait_status == NULL);
f0223081 3911
2455069d 3912 /* Report all signals during attach/startup. */
94bedb42 3913 remote_pass_signals (target, 0, NULL);
221e1a37
PA
3914
3915 /* If there are already stopped threads, mark them stopped and
3916 report their stops before giving the prompt to the user. */
3917 process_initial_stop_replies ();
3918
3919 switch_to_thread (current_ptid);
3920
3921 if (target_can_async_p ())
3922 target_async (1);
74531fed 3923 }
c8d104ad 3924
c8d104ad
PA
3925 /* If we connected to a live target, do some additional setup. */
3926 if (target_has_execution)
3927 {
f4ccffad 3928 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 3929 remote_check_symbols ();
c8d104ad 3930 }
50c71eaf 3931
d5551862
SS
3932 /* Possibly the target has been engaged in a trace run started
3933 previously; find out where things are at. */
8bd200f1 3934 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 3935 {
00bf0b85 3936 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 3937
00bf0b85
SS
3938 if (current_trace_status ()->running)
3939 printf_filtered (_("Trace is already running on the target.\n"));
3940
ab6617cc 3941 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
3942
3943 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3944 }
3945
1e51243a
PA
3946 /* The thread and inferior lists are now synchronized with the
3947 target, our symbols have been relocated, and we're merged the
3948 target's tracepoints with ours. We're done with basic start
3949 up. */
3950 rs->starting_up = 0;
3951
a25a5a45
PA
3952 /* Maybe breakpoints are global and need to be inserted now. */
3953 if (breakpoints_should_be_inserted_now ())
50c71eaf 3954 insert_breakpoints ();
c906108c
SS
3955}
3956
3957/* Open a connection to a remote debugger.
3958 NAME is the filename used for communication. */
3959
3960static void
014f9477 3961remote_open (const char *name, int from_tty)
c906108c 3962{
75c99385 3963 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3964}
3965
c906108c
SS
3966/* Open a connection to a remote debugger using the extended
3967 remote gdb protocol. NAME is the filename used for communication. */
3968
3969static void
014f9477 3970extended_remote_open (const char *name, int from_tty)
c906108c 3971{
75c99385 3972 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3973}
3974
ca4f7f8b
PA
3975/* Reset all packets back to "unknown support". Called when opening a
3976 new connection to a remote target. */
c906108c 3977
d471ea57 3978static void
ca4f7f8b 3979reset_all_packet_configs_support (void)
d471ea57
AC
3980{
3981 int i;
a744cf53 3982
444abaca 3983 for (i = 0; i < PACKET_MAX; i++)
4082afcc 3984 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
3985}
3986
ca4f7f8b
PA
3987/* Initialize all packet configs. */
3988
3989static void
3990init_all_packet_configs (void)
3991{
3992 int i;
3993
3994 for (i = 0; i < PACKET_MAX; i++)
3995 {
3996 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3997 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3998 }
3999}
4000
23860348 4001/* Symbol look-up. */
dc8acb97
MS
4002
4003static void
36d25514 4004remote_check_symbols (void)
dc8acb97 4005{
d01949b6 4006 struct remote_state *rs = get_remote_state ();
dc8acb97 4007 char *msg, *reply, *tmp;
3b7344d5 4008 struct bound_minimal_symbol sym;
dc8acb97
MS
4009 int end;
4010
63154eca
PA
4011 /* The remote side has no concept of inferiors that aren't running
4012 yet, it only knows about running processes. If we're connected
4013 but our current inferior is not running, we should not invite the
4014 remote target to request symbol lookups related to its
4015 (unrelated) current process. */
4016 if (!target_has_execution)
4017 return;
4018
4082afcc 4019 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4020 return;
4021
63154eca
PA
4022 /* Make sure the remote is pointing at the right process. Note
4023 there's no way to select "no process". */
3c9c4b83
PA
4024 set_general_process ();
4025
6d820c5c
DJ
4026 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4027 because we need both at the same time. */
ea9c271d 4028 msg = alloca (get_remote_packet_size ());
6d820c5c 4029
23860348 4030 /* Invite target to request symbol lookups. */
dc8acb97
MS
4031
4032 putpkt ("qSymbol::");
6d820c5c
DJ
4033 getpkt (&rs->buf, &rs->buf_size, 0);
4034 packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2e9f7625 4035 reply = rs->buf;
dc8acb97 4036
61012eef 4037 while (startswith (reply, "qSymbol:"))
dc8acb97 4038 {
77e371c0
TT
4039 struct bound_minimal_symbol sym;
4040
dc8acb97 4041 tmp = &reply[8];
cfd77fa1 4042 end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
dc8acb97
MS
4043 msg[end] = '\0';
4044 sym = lookup_minimal_symbol (msg, NULL, NULL);
3b7344d5 4045 if (sym.minsym == NULL)
ea9c271d 4046 xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
dc8acb97 4047 else
2bbe3cc1 4048 {
f5656ead 4049 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
77e371c0 4050 CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
2bbe3cc1
DJ
4051
4052 /* If this is a function address, return the start of code
4053 instead of any data function descriptor. */
f5656ead 4054 sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
2bbe3cc1
DJ
4055 sym_addr,
4056 &current_target);
4057
4058 xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
5af949e3 4059 phex_nz (sym_addr, addr_size), &reply[8]);
2bbe3cc1
DJ
4060 }
4061
dc8acb97 4062 putpkt (msg);
6d820c5c 4063 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4064 reply = rs->buf;
dc8acb97
MS
4065 }
4066}
4067
9db8d71f 4068static struct serial *
baa336ce 4069remote_serial_open (const char *name)
9db8d71f
DJ
4070{
4071 static int udp_warning = 0;
4072
4073 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4074 of in ser-tcp.c, because it is the remote protocol assuming that the
4075 serial connection is reliable and not the serial connection promising
4076 to be. */
61012eef 4077 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4078 {
3e43a32a
MS
4079 warning (_("The remote protocol may be unreliable over UDP.\n"
4080 "Some events may be lost, rendering further debugging "
4081 "impossible."));
9db8d71f
DJ
4082 udp_warning = 1;
4083 }
4084
4085 return serial_open (name);
4086}
4087
d914c394
SS
4088/* Inform the target of our permission settings. The permission flags
4089 work without this, but if the target knows the settings, it can do
4090 a couple things. First, it can add its own check, to catch cases
4091 that somehow manage to get by the permissions checks in target
4092 methods. Second, if the target is wired to disallow particular
4093 settings (for instance, a system in the field that is not set up to
4094 be able to stop at a breakpoint), it can object to any unavailable
4095 permissions. */
4096
4097void
c378d69d 4098remote_set_permissions (struct target_ops *self)
d914c394
SS
4099{
4100 struct remote_state *rs = get_remote_state ();
4101
bba74b36
YQ
4102 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4103 "WriteReg:%x;WriteMem:%x;"
4104 "InsertBreak:%x;InsertTrace:%x;"
4105 "InsertFastTrace:%x;Stop:%x",
4106 may_write_registers, may_write_memory,
4107 may_insert_breakpoints, may_insert_tracepoints,
4108 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4109 putpkt (rs->buf);
4110 getpkt (&rs->buf, &rs->buf_size, 0);
4111
4112 /* If the target didn't like the packet, warn the user. Do not try
4113 to undo the user's settings, that would just be maddening. */
4114 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4115 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4116}
4117
be2a5f71
DJ
4118/* This type describes each known response to the qSupported
4119 packet. */
4120struct protocol_feature
4121{
4122 /* The name of this protocol feature. */
4123 const char *name;
4124
4125 /* The default for this protocol feature. */
4126 enum packet_support default_support;
4127
4128 /* The function to call when this feature is reported, or after
4129 qSupported processing if the feature is not supported.
4130 The first argument points to this structure. The second
4131 argument indicates whether the packet requested support be
4132 enabled, disabled, or probed (or the default, if this function
4133 is being called at the end of processing and this feature was
4134 not reported). The third argument may be NULL; if not NULL, it
4135 is a NUL-terminated string taken from the packet following
4136 this feature's name and an equals sign. */
4137 void (*func) (const struct protocol_feature *, enum packet_support,
4138 const char *);
4139
4140 /* The corresponding packet for this feature. Only used if
4141 FUNC is remote_supported_packet. */
4142 int packet;
4143};
4144
be2a5f71
DJ
4145static void
4146remote_supported_packet (const struct protocol_feature *feature,
4147 enum packet_support support,
4148 const char *argument)
4149{
4150 if (argument)
4151 {
4152 warning (_("Remote qSupported response supplied an unexpected value for"
4153 " \"%s\"."), feature->name);
4154 return;
4155 }
4156
4082afcc 4157 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4158}
be2a5f71
DJ
4159
4160static void
4161remote_packet_size (const struct protocol_feature *feature,
4162 enum packet_support support, const char *value)
4163{
4164 struct remote_state *rs = get_remote_state ();
4165
4166 int packet_size;
4167 char *value_end;
4168
4169 if (support != PACKET_ENABLE)
4170 return;
4171
4172 if (value == NULL || *value == '\0')
4173 {
4174 warning (_("Remote target reported \"%s\" without a size."),
4175 feature->name);
4176 return;
4177 }
4178
4179 errno = 0;
4180 packet_size = strtol (value, &value_end, 16);
4181 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4182 {
4183 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4184 feature->name, value);
4185 return;
4186 }
4187
4188 if (packet_size > MAX_REMOTE_PACKET_SIZE)
4189 {
4190 warning (_("limiting remote suggested packet size (%d bytes) to %d"),
4191 packet_size, MAX_REMOTE_PACKET_SIZE);
4192 packet_size = MAX_REMOTE_PACKET_SIZE;
4193 }
4194
4195 /* Record the new maximum packet size. */
4196 rs->explicit_packet_size = packet_size;
4197}
4198
dc473cfb 4199static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4200 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4201 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4202 PACKET_qXfer_auxv },
c78fa86a
GB
4203 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4204 PACKET_qXfer_exec_file },
23181151
DJ
4205 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4206 PACKET_qXfer_features },
cfa9d6d9
DJ
4207 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4208 PACKET_qXfer_libraries },
2268b414
JK
4209 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4210 PACKET_qXfer_libraries_svr4 },
ced63ec0 4211 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4212 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4213 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4214 PACKET_qXfer_memory_map },
4de6483e
UW
4215 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4216 PACKET_qXfer_spu_read },
4217 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4218 PACKET_qXfer_spu_write },
07e059b5
VP
4219 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4220 PACKET_qXfer_osdata },
dc146f7c
VP
4221 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4222 PACKET_qXfer_threads },
b3b9301e
PA
4223 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4224 PACKET_qXfer_traceframe_info },
89be2091
DJ
4225 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4226 PACKET_QPassSignals },
9b224c5e
PA
4227 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4228 PACKET_QProgramSignals },
a6f3e723
SL
4229 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4230 PACKET_QStartNoAckMode },
4082afcc
PA
4231 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4232 PACKET_multiprocess_feature },
4233 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4234 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4235 PACKET_qXfer_siginfo_read },
4236 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4237 PACKET_qXfer_siginfo_write },
4082afcc 4238 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4239 PACKET_ConditionalTracepoints },
4082afcc 4240 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4241 PACKET_ConditionalBreakpoints },
4082afcc 4242 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4243 PACKET_BreakpointCommands },
4082afcc 4244 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4245 PACKET_FastTracepoints },
4082afcc 4246 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4247 PACKET_StaticTracepoints },
4082afcc 4248 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4249 PACKET_InstallInTrace},
4082afcc
PA
4250 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4251 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4252 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4253 PACKET_bc },
4254 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4255 PACKET_bs },
409873ef
SS
4256 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4257 PACKET_TracepointSource },
d914c394
SS
4258 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4259 PACKET_QAllow },
4082afcc
PA
4260 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4261 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4262 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4263 PACKET_qXfer_fdpic },
169081d0
TG
4264 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4265 PACKET_qXfer_uib },
03583c20
UW
4266 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4267 PACKET_QDisableRandomization },
d1feda86 4268 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4269 { "QTBuffer:size", PACKET_DISABLE,
4270 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4271 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4272 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4273 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4274 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4275 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4276 PACKET_qXfer_btrace },
4277 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4278 PACKET_qXfer_btrace_conf },
4279 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4280 PACKET_Qbtrace_conf_bts_size },
4281 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4282 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4283 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4284 PACKET_fork_event_feature },
4285 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4286 PACKET_vfork_event_feature },
b20a6524
MM
4287 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4288 PACKET_Qbtrace_conf_pt_size }
be2a5f71
DJ
4289};
4290
c8d5aac9
L
4291static char *remote_support_xml;
4292
4293/* Register string appended to "xmlRegisters=" in qSupported query. */
4294
4295void
6e39997a 4296register_remote_support_xml (const char *xml)
c8d5aac9
L
4297{
4298#if defined(HAVE_LIBEXPAT)
4299 if (remote_support_xml == NULL)
c4f7c687 4300 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4301 else
4302 {
4303 char *copy = xstrdup (remote_support_xml + 13);
4304 char *p = strtok (copy, ",");
4305
4306 do
4307 {
4308 if (strcmp (p, xml) == 0)
4309 {
4310 /* already there */
4311 xfree (copy);
4312 return;
4313 }
4314 }
4315 while ((p = strtok (NULL, ",")) != NULL);
4316 xfree (copy);
4317
94b0dee1
PA
4318 remote_support_xml = reconcat (remote_support_xml,
4319 remote_support_xml, ",", xml,
4320 (char *) NULL);
c8d5aac9
L
4321 }
4322#endif
4323}
4324
4325static char *
4326remote_query_supported_append (char *msg, const char *append)
4327{
4328 if (msg)
94b0dee1 4329 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4330 else
4331 return xstrdup (append);
4332}
4333
be2a5f71
DJ
4334static void
4335remote_query_supported (void)
4336{
4337 struct remote_state *rs = get_remote_state ();
4338 char *next;
4339 int i;
4340 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4341
4342 /* The packet support flags are handled differently for this packet
4343 than for most others. We treat an error, a disabled packet, and
4344 an empty response identically: any features which must be reported
4345 to be used will be automatically disabled. An empty buffer
4346 accomplishes this, since that is also the representation for a list
4347 containing no features. */
4348
4349 rs->buf[0] = 0;
4082afcc 4350 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4351 {
c8d5aac9 4352 char *q = NULL;
94b0dee1 4353 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4354
73b8c1fd
PA
4355 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4356 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4357
f7e6eed5
PA
4358 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4359 q = remote_query_supported_append (q, "swbreak+");
4360 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4361 q = remote_query_supported_append (q, "hwbreak+");
4362
c8d5aac9
L
4363 if (remote_support_xml)
4364 q = remote_query_supported_append (q, remote_support_xml);
4365
dde08ee1
PA
4366 q = remote_query_supported_append (q, "qRelocInsn+");
4367
89245bc0
DB
4368 if (rs->extended)
4369 {
4370 if (packet_set_cmd_state (PACKET_fork_event_feature)
4371 != AUTO_BOOLEAN_FALSE)
4372 q = remote_query_supported_append (q, "fork-events+");
4373 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4374 != AUTO_BOOLEAN_FALSE)
4375 q = remote_query_supported_append (q, "vfork-events+");
4376 }
4377
dde08ee1
PA
4378 q = reconcat (q, "qSupported:", q, (char *) NULL);
4379 putpkt (q);
82f73884 4380
94b0dee1
PA
4381 do_cleanups (old_chain);
4382
be2a5f71
DJ
4383 getpkt (&rs->buf, &rs->buf_size, 0);
4384
4385 /* If an error occured, warn, but do not return - just reset the
4386 buffer to empty and go on to disable features. */
4387 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4388 == PACKET_ERROR)
4389 {
4390 warning (_("Remote failure reply: %s"), rs->buf);
4391 rs->buf[0] = 0;
4392 }
4393 }
4394
4395 memset (seen, 0, sizeof (seen));
4396
4397 next = rs->buf;
4398 while (*next)
4399 {
4400 enum packet_support is_supported;
4401 char *p, *end, *name_end, *value;
4402
4403 /* First separate out this item from the rest of the packet. If
4404 there's another item after this, we overwrite the separator
4405 (terminated strings are much easier to work with). */
4406 p = next;
4407 end = strchr (p, ';');
4408 if (end == NULL)
4409 {
4410 end = p + strlen (p);
4411 next = end;
4412 }
4413 else
4414 {
89be2091
DJ
4415 *end = '\0';
4416 next = end + 1;
4417
be2a5f71
DJ
4418 if (end == p)
4419 {
4420 warning (_("empty item in \"qSupported\" response"));
4421 continue;
4422 }
be2a5f71
DJ
4423 }
4424
4425 name_end = strchr (p, '=');
4426 if (name_end)
4427 {
4428 /* This is a name=value entry. */
4429 is_supported = PACKET_ENABLE;
4430 value = name_end + 1;
4431 *name_end = '\0';
4432 }
4433 else
4434 {
4435 value = NULL;
4436 switch (end[-1])
4437 {
4438 case '+':
4439 is_supported = PACKET_ENABLE;
4440 break;
4441
4442 case '-':
4443 is_supported = PACKET_DISABLE;
4444 break;
4445
4446 case '?':
4447 is_supported = PACKET_SUPPORT_UNKNOWN;
4448 break;
4449
4450 default:
3e43a32a
MS
4451 warning (_("unrecognized item \"%s\" "
4452 "in \"qSupported\" response"), p);
be2a5f71
DJ
4453 continue;
4454 }
4455 end[-1] = '\0';
4456 }
4457
4458 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4459 if (strcmp (remote_protocol_features[i].name, p) == 0)
4460 {
4461 const struct protocol_feature *feature;
4462
4463 seen[i] = 1;
4464 feature = &remote_protocol_features[i];
4465 feature->func (feature, is_supported, value);
4466 break;
4467 }
4468 }
4469
4470 /* If we increased the packet size, make sure to increase the global
4471 buffer size also. We delay this until after parsing the entire
4472 qSupported packet, because this is the same buffer we were
4473 parsing. */
4474 if (rs->buf_size < rs->explicit_packet_size)
4475 {
4476 rs->buf_size = rs->explicit_packet_size;
4477 rs->buf = xrealloc (rs->buf, rs->buf_size);
4478 }
4479
4480 /* Handle the defaults for unmentioned features. */
4481 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4482 if (!seen[i])
4483 {
4484 const struct protocol_feature *feature;
4485
4486 feature = &remote_protocol_features[i];
4487 feature->func (feature, feature->default_support, NULL);
4488 }
4489}
4490
78a095c3
JK
4491/* Remove any of the remote.c targets from target stack. Upper targets depend
4492 on it so remove them first. */
4493
4494static void
4495remote_unpush_target (void)
4496{
4497 pop_all_targets_above (process_stratum - 1);
4498}
be2a5f71 4499
c906108c 4500static void
014f9477 4501remote_open_1 (const char *name, int from_tty,
3e43a32a 4502 struct target_ops *target, int extended_p)
c906108c 4503{
d01949b6 4504 struct remote_state *rs = get_remote_state ();
a6f3e723 4505
c906108c 4506 if (name == 0)
8a3fe4f8 4507 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4508 "serial device is attached to the remote system\n"
8a3fe4f8 4509 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4510
23860348 4511 /* See FIXME above. */
c6ebd6cf 4512 if (!target_async_permitted)
92d1e331 4513 wait_forever_enabled_p = 1;
6426a772 4514
2d717e4f 4515 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4516 Ask this question first, before target_preopen has a chance to kill
4517 anything. */
5d93a237 4518 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4519 {
78a095c3
JK
4520 if (from_tty
4521 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4522 error (_("Still connected."));
4523 }
4524
78a095c3 4525 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4526 target_preopen (from_tty);
4527
89be2091 4528 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4529 xfree (rs->last_pass_packet);
4530 rs->last_pass_packet = NULL;
89be2091 4531
9b224c5e
PA
4532 /* Make sure we send the program signals list the next time we
4533 resume. */
5e4a05c4
TT
4534 xfree (rs->last_program_signals_packet);
4535 rs->last_program_signals_packet = NULL;
9b224c5e 4536
ad9a8f3f 4537 remote_fileio_reset ();
1dd41f16
NS
4538 reopen_exec_file ();
4539 reread_symbols ();
4540
5d93a237
TT
4541 rs->remote_desc = remote_serial_open (name);
4542 if (!rs->remote_desc)
c906108c
SS
4543 perror_with_name (name);
4544
4545 if (baud_rate != -1)
4546 {
5d93a237 4547 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4548 {
9b74d5d3
KB
4549 /* The requested speed could not be set. Error out to
4550 top level after closing remote_desc. Take care to
4551 set remote_desc to NULL to avoid closing remote_desc
4552 more than once. */
5d93a237
TT
4553 serial_close (rs->remote_desc);
4554 rs->remote_desc = NULL;
c906108c
SS
4555 perror_with_name (name);
4556 }
4557 }
4558
236af5e3 4559 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4560 serial_raw (rs->remote_desc);
c906108c
SS
4561
4562 /* If there is something sitting in the buffer we might take it as a
4563 response to a command, which would be bad. */
5d93a237 4564 serial_flush_input (rs->remote_desc);
c906108c
SS
4565
4566 if (from_tty)
4567 {
4568 puts_filtered ("Remote debugging using ");
4569 puts_filtered (name);
4570 puts_filtered ("\n");
4571 }
23860348 4572 push_target (target); /* Switch to using remote target now. */
c906108c 4573
74531fed
PA
4574 /* Register extra event sources in the event loop. */
4575 remote_async_inferior_event_token
4576 = create_async_event_handler (remote_async_inferior_event_handler,
4577 NULL);
5965e028 4578 rs->notif_state = remote_notif_state_allocate ();
74531fed 4579
be2a5f71
DJ
4580 /* Reset the target state; these things will be queried either by
4581 remote_query_supported or as they are needed. */
ca4f7f8b 4582 reset_all_packet_configs_support ();
74531fed 4583 rs->cached_wait_status = 0;
be2a5f71 4584 rs->explicit_packet_size = 0;
a6f3e723 4585 rs->noack_mode = 0;
82f73884 4586 rs->extended = extended_p;
e24a49d8 4587 rs->waiting_for_stop_reply = 0;
3a29589a 4588 rs->ctrlc_pending_p = 0;
802188a7 4589
47f8a51d
TT
4590 rs->general_thread = not_sent_ptid;
4591 rs->continue_thread = not_sent_ptid;
262e1174 4592 rs->remote_traceframe_number = -1;
c906108c 4593
9d1f7ab2 4594 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4595 rs->use_threadinfo_query = 1;
4596 rs->use_threadextra_query = 1;
9d1f7ab2 4597
80152258
PA
4598 readahead_cache_invalidate ();
4599
c6ebd6cf 4600 if (target_async_permitted)
92d1e331 4601 {
23860348 4602 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4603 remote_async_terminal_ours_p = 1;
4604
4605 /* FIXME: cagney/1999-09-23: During the initial connection it is
4606 assumed that the target is already ready and able to respond to
0df8b418 4607 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4608 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4609 around this. Eventually a mechanism that allows
92d1e331 4610 wait_for_inferior() to expect/get timeouts will be
23860348 4611 implemented. */
92d1e331
DJ
4612 wait_forever_enabled_p = 0;
4613 }
4614
23860348 4615 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4616 no_shared_libraries (NULL, 0);
f78f6cf1 4617
74531fed
PA
4618 /* Start afresh. */
4619 init_thread_list ();
4620
36918e70 4621 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4622 target (we'd otherwise be in an inconsistent state) and then
4623 propogate the error on up the exception chain. This ensures that
4624 the caller doesn't stumble along blindly assuming that the
4625 function succeeded. The CLI doesn't have this problem but other
4626 UI's, such as MI do.
36918e70
AC
4627
4628 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4629 this function should return an error indication letting the
ce2826aa 4630 caller restore the previous state. Unfortunately the command
36918e70
AC
4631 ``target remote'' is directly wired to this function making that
4632 impossible. On a positive note, the CLI side of this problem has
4633 been fixed - the function set_cmd_context() makes it possible for
4634 all the ``target ....'' commands to share a common callback
4635 function. See cli-dump.c. */
109c3e39 4636 {
2d717e4f 4637
492d29ea 4638 TRY
04bd08de
TT
4639 {
4640 remote_start_remote (from_tty, target, extended_p);
4641 }
492d29ea 4642 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4643 {
c8d104ad
PA
4644 /* Pop the partially set up target - unless something else did
4645 already before throwing the exception. */
5d93a237 4646 if (rs->remote_desc != NULL)
78a095c3 4647 remote_unpush_target ();
c6ebd6cf 4648 if (target_async_permitted)
109c3e39
AC
4649 wait_forever_enabled_p = 1;
4650 throw_exception (ex);
4651 }
492d29ea 4652 END_CATCH
109c3e39 4653 }
c906108c 4654
f4abbc16
MM
4655 remote_btrace_reset ();
4656
c6ebd6cf 4657 if (target_async_permitted)
92d1e331 4658 wait_forever_enabled_p = 1;
43ff13b4
JM
4659}
4660
de0d863e
DB
4661/* Detach the specified process. */
4662
4663static void
4664remote_detach_pid (int pid)
4665{
4666 struct remote_state *rs = get_remote_state ();
4667
4668 if (remote_multi_process_p (rs))
4669 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4670 else
4671 strcpy (rs->buf, "D");
4672
4673 putpkt (rs->buf);
4674 getpkt (&rs->buf, &rs->buf_size, 0);
4675
4676 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4677 ;
4678 else if (rs->buf[0] == '\0')
4679 error (_("Remote doesn't know how to detach"));
4680 else
4681 error (_("Can't detach process."));
4682}
4683
4684/* This detaches a program to which we previously attached, using
4685 inferior_ptid to identify the process. After this is done, GDB
4686 can be used to debug some other program. We better not have left
4687 any breakpoints in the target program or it'll die when it hits
4688 one. */
c906108c
SS
4689
4690static void
de0d863e 4691remote_detach_1 (const char *args, int from_tty)
c906108c 4692{
82f73884 4693 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4694 struct remote_state *rs = get_remote_state ();
de0d863e
DB
4695 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4696 int is_fork_parent;
c906108c
SS
4697
4698 if (args)
8a3fe4f8 4699 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4700
2d717e4f
DJ
4701 if (!target_has_execution)
4702 error (_("No process to detach from."));
4703
7cee1e54
PA
4704 if (from_tty)
4705 {
4706 char *exec_file = get_exec_file (0);
4707 if (exec_file == NULL)
4708 exec_file = "";
4709 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4710 target_pid_to_str (pid_to_ptid (pid)));
4711 gdb_flush (gdb_stdout);
4712 }
4713
c906108c 4714 /* Tell the remote target to detach. */
de0d863e 4715 remote_detach_pid (pid);
82f73884 4716
de0d863e 4717 if (from_tty && !rs->extended)
7cee1e54 4718 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4719
de0d863e
DB
4720 /* Check to see if we are detaching a fork parent. Note that if we
4721 are detaching a fork child, tp == NULL. */
4722 is_fork_parent = (tp != NULL
4723 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4724
4725 /* If doing detach-on-fork, we don't mourn, because that will delete
4726 breakpoints that should be available for the followed inferior. */
4727 if (!is_fork_parent)
4728 target_mourn_inferior ();
4729 else
4730 {
4731 inferior_ptid = null_ptid;
4732 detach_inferior (pid);
4733 }
2d717e4f
DJ
4734}
4735
4736static void
52554a0e 4737remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4738{
de0d863e 4739 remote_detach_1 (args, from_tty);
2d717e4f
DJ
4740}
4741
4742static void
52554a0e 4743extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4744{
de0d863e
DB
4745 remote_detach_1 (args, from_tty);
4746}
4747
4748/* Target follow-fork function for remote targets. On entry, and
4749 at return, the current inferior is the fork parent.
4750
4751 Note that although this is currently only used for extended-remote,
4752 it is named remote_follow_fork in anticipation of using it for the
4753 remote target as well. */
4754
4755static int
4756remote_follow_fork (struct target_ops *ops, int follow_child,
4757 int detach_fork)
4758{
4759 struct remote_state *rs = get_remote_state ();
c269dbdb 4760 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 4761
c269dbdb
DB
4762 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4763 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
4764 {
4765 /* When following the parent and detaching the child, we detach
4766 the child here. For the case of following the child and
4767 detaching the parent, the detach is done in the target-
4768 independent follow fork code in infrun.c. We can't use
4769 target_detach when detaching an unfollowed child because
4770 the client side doesn't know anything about the child. */
4771 if (detach_fork && !follow_child)
4772 {
4773 /* Detach the fork child. */
4774 ptid_t child_ptid;
4775 pid_t child_pid;
4776
4777 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4778 child_pid = ptid_get_pid (child_ptid);
4779
4780 remote_detach_pid (child_pid);
4781 detach_inferior (child_pid);
4782 }
4783 }
4784 return 0;
c906108c
SS
4785}
4786
6ad8ae5c
DJ
4787/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4788
43ff13b4 4789static void
fee354ee 4790remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 4791{
43ff13b4 4792 if (args)
2d717e4f 4793 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4794
2d717e4f 4795 /* Make sure we unpush even the extended remote targets; mourn
20f796c9 4796 won't do it. So call remote_mourn directly instead of
2d717e4f 4797 target_mourn_inferior. */
20f796c9 4798 remote_mourn (target);
2d717e4f 4799
43ff13b4
JM
4800 if (from_tty)
4801 puts_filtered ("Ending remote debugging.\n");
4802}
4803
2d717e4f
DJ
4804/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4805 be chatty about it. */
4806
4807static void
20f796c9
GB
4808extended_remote_attach (struct target_ops *target, const char *args,
4809 int from_tty)
2d717e4f
DJ
4810{
4811 struct remote_state *rs = get_remote_state ();
be86555c 4812 int pid;
96ef3384 4813 char *wait_status = NULL;
2d717e4f 4814
74164c56 4815 pid = parse_pid_to_attach (args);
2d717e4f 4816
74164c56
JK
4817 /* Remote PID can be freely equal to getpid, do not check it here the same
4818 way as in other targets. */
2d717e4f 4819
4082afcc 4820 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
4821 error (_("This target does not support attaching to a process"));
4822
7cee1e54
PA
4823 if (from_tty)
4824 {
4825 char *exec_file = get_exec_file (0);
4826
4827 if (exec_file)
4828 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4829 target_pid_to_str (pid_to_ptid (pid)));
4830 else
4831 printf_unfiltered (_("Attaching to %s\n"),
4832 target_pid_to_str (pid_to_ptid (pid)));
4833
4834 gdb_flush (gdb_stdout);
4835 }
4836
bba74b36 4837 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4838 putpkt (rs->buf);
4839 getpkt (&rs->buf, &rs->buf_size, 0);
4840
4082afcc
PA
4841 switch (packet_ok (rs->buf,
4842 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 4843 {
4082afcc 4844 case PACKET_OK:
74531fed
PA
4845 if (!non_stop)
4846 {
4847 /* Save the reply for later. */
4848 wait_status = alloca (strlen (rs->buf) + 1);
4849 strcpy (wait_status, rs->buf);
4850 }
4851 else if (strcmp (rs->buf, "OK") != 0)
4852 error (_("Attaching to %s failed with: %s"),
4853 target_pid_to_str (pid_to_ptid (pid)),
4854 rs->buf);
4082afcc
PA
4855 break;
4856 case PACKET_UNKNOWN:
4857 error (_("This target does not support attaching to a process"));
4858 default:
4859 error (_("Attaching to %s failed"),
4860 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4861 }
2d717e4f 4862
1b6e6f5c 4863 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 4864
2d717e4f 4865 inferior_ptid = pid_to_ptid (pid);
79d7f229 4866
bad34192
PA
4867 if (non_stop)
4868 {
4869 struct thread_info *thread;
79d7f229 4870
bad34192 4871 /* Get list of threads. */
e8032dde 4872 remote_update_thread_list (target);
82f73884 4873
bad34192
PA
4874 thread = first_thread_of_process (pid);
4875 if (thread)
4876 inferior_ptid = thread->ptid;
4877 else
4878 inferior_ptid = pid_to_ptid (pid);
4879
4880 /* Invalidate our notion of the remote current thread. */
47f8a51d 4881 record_currthread (rs, minus_one_ptid);
bad34192 4882 }
74531fed 4883 else
bad34192
PA
4884 {
4885 /* Now, if we have thread information, update inferior_ptid. */
4886 inferior_ptid = remote_current_thread (inferior_ptid);
4887
4888 /* Add the main thread to the thread list. */
4889 add_thread_silent (inferior_ptid);
4890 }
c0a2216e 4891
96ef3384
UW
4892 /* Next, if the target can specify a description, read it. We do
4893 this before anything involving memory or registers. */
4894 target_find_description ();
4895
74531fed
PA
4896 if (!non_stop)
4897 {
4898 /* Use the previously fetched status. */
4899 gdb_assert (wait_status != NULL);
4900
4901 if (target_can_async_p ())
4902 {
722247f1
YQ
4903 struct notif_event *reply
4904 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4905
722247f1 4906 push_stop_reply ((struct stop_reply *) reply);
74531fed 4907
6a3753b3 4908 target_async (1);
74531fed
PA
4909 }
4910 else
4911 {
4912 gdb_assert (wait_status != NULL);
4913 strcpy (rs->buf, wait_status);
4914 rs->cached_wait_status = 1;
4915 }
4916 }
4917 else
4918 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4919}
4920
b9c1d481
AS
4921/* Implementation of the to_post_attach method. */
4922
4923static void
4924extended_remote_post_attach (struct target_ops *ops, int pid)
4925{
4926 /* In certain cases GDB might not have had the chance to start
4927 symbol lookup up until now. This could happen if the debugged
4928 binary is not using shared libraries, the vsyscall page is not
4929 present (on Linux) and the binary itself hadn't changed since the
4930 debugging process was started. */
4931 if (symfile_objfile != NULL)
4932 remote_check_symbols();
4933}
4934
c906108c 4935\f
506fb367
DJ
4936/* Check for the availability of vCont. This function should also check
4937 the response. */
c906108c
SS
4938
4939static void
6d820c5c 4940remote_vcont_probe (struct remote_state *rs)
c906108c 4941{
2e9f7625 4942 char *buf;
6d820c5c 4943
2e9f7625
DJ
4944 strcpy (rs->buf, "vCont?");
4945 putpkt (rs->buf);
6d820c5c 4946 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4947 buf = rs->buf;
c906108c 4948
506fb367 4949 /* Make sure that the features we assume are supported. */
61012eef 4950 if (startswith (buf, "vCont"))
506fb367
DJ
4951 {
4952 char *p = &buf[5];
4953 int support_s, support_S, support_c, support_C;
4954
4955 support_s = 0;
4956 support_S = 0;
4957 support_c = 0;
4958 support_C = 0;
d458bd84 4959 rs->supports_vCont.t = 0;
c1e36e3e 4960 rs->supports_vCont.r = 0;
506fb367
DJ
4961 while (p && *p == ';')
4962 {
4963 p++;
4964 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4965 support_s = 1;
4966 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4967 support_S = 1;
4968 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4969 support_c = 1;
4970 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4971 support_C = 1;
74531fed 4972 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4973 rs->supports_vCont.t = 1;
c1e36e3e
PA
4974 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4975 rs->supports_vCont.r = 1;
506fb367
DJ
4976
4977 p = strchr (p, ';');
4978 }
c906108c 4979
506fb367
DJ
4980 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4981 BUF will make packet_ok disable the packet. */
4982 if (!support_s || !support_S || !support_c || !support_C)
4983 buf[0] = 0;
4984 }
c906108c 4985
444abaca 4986 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4987}
c906108c 4988
0d8f58ca
PA
4989/* Helper function for building "vCont" resumptions. Write a
4990 resumption to P. ENDP points to one-passed-the-end of the buffer
4991 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4992 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4993 resumed thread should be single-stepped and/or signalled. If PTID
4994 equals minus_one_ptid, then all threads are resumed; if PTID
4995 represents a process, then all threads of the process are resumed;
4996 the thread to be stepped and/or signalled is given in the global
4997 INFERIOR_PTID. */
4998
4999static char *
5000append_resumption (char *p, char *endp,
2ea28649 5001 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5002{
5003 struct remote_state *rs = get_remote_state ();
5004
a493e3e2 5005 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5006 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5007 else if (step
5008 /* GDB is willing to range step. */
5009 && use_range_stepping
5010 /* Target supports range stepping. */
5011 && rs->supports_vCont.r
5012 /* We don't currently support range stepping multiple
5013 threads with a wildcard (though the protocol allows it,
5014 so stubs shouldn't make an active effort to forbid
5015 it). */
5016 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5017 {
5018 struct thread_info *tp;
5019
5020 if (ptid_equal (ptid, minus_one_ptid))
5021 {
5022 /* If we don't know about the target thread's tid, then
5023 we're resuming magic_null_ptid (see caller). */
5024 tp = find_thread_ptid (magic_null_ptid);
5025 }
5026 else
5027 tp = find_thread_ptid (ptid);
5028 gdb_assert (tp != NULL);
5029
5030 if (tp->control.may_range_step)
5031 {
5032 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5033
5034 p += xsnprintf (p, endp - p, ";r%s,%s",
5035 phex_nz (tp->control.step_range_start,
5036 addr_size),
5037 phex_nz (tp->control.step_range_end,
5038 addr_size));
5039 }
5040 else
5041 p += xsnprintf (p, endp - p, ";s");
5042 }
0d8f58ca
PA
5043 else if (step)
5044 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5045 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5046 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5047 else
5048 p += xsnprintf (p, endp - p, ";c");
5049
5050 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5051 {
5052 ptid_t nptid;
5053
5054 /* All (-1) threads of process. */
ba348170 5055 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5056
5057 p += xsnprintf (p, endp - p, ":");
5058 p = write_ptid (p, endp, nptid);
5059 }
5060 else if (!ptid_equal (ptid, minus_one_ptid))
5061 {
5062 p += xsnprintf (p, endp - p, ":");
5063 p = write_ptid (p, endp, ptid);
5064 }
5065
5066 return p;
5067}
5068
e5ef252a
PA
5069/* Append a vCont continue-with-signal action for threads that have a
5070 non-zero stop signal. */
5071
5072static char *
5073append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5074{
5075 struct thread_info *thread;
5076
034f788c 5077 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5078 if (ptid_match (thread->ptid, ptid)
5079 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5080 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5081 {
5082 p = append_resumption (p, endp, thread->ptid,
5083 0, thread->suspend.stop_signal);
5084 thread->suspend.stop_signal = GDB_SIGNAL_0;
5085 }
5086
5087 return p;
5088}
5089
506fb367
DJ
5090/* Resume the remote inferior by using a "vCont" packet. The thread
5091 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5092 resumed thread should be single-stepped and/or signalled. If PTID
5093 equals minus_one_ptid, then all threads are resumed; the thread to
5094 be stepped and/or signalled is given in the global INFERIOR_PTID.
5095 This function returns non-zero iff it resumes the inferior.
44eaed12 5096
506fb367
DJ
5097 This function issues a strict subset of all possible vCont commands at the
5098 moment. */
44eaed12 5099
506fb367 5100static int
2ea28649 5101remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5102{
5103 struct remote_state *rs = get_remote_state ();
82f73884
PA
5104 char *p;
5105 char *endp;
44eaed12 5106
4082afcc 5107 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5108 remote_vcont_probe (rs);
44eaed12 5109
4082afcc 5110 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5111 return 0;
44eaed12 5112
82f73884
PA
5113 p = rs->buf;
5114 endp = rs->buf + get_remote_packet_size ();
5115
506fb367
DJ
5116 /* If we could generate a wider range of packets, we'd have to worry
5117 about overflowing BUF. Should there be a generic
5118 "multi-part-packet" packet? */
5119
0d8f58ca
PA
5120 p += xsnprintf (p, endp - p, "vCont");
5121
79d7f229 5122 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5123 {
79d7f229
PA
5124 /* MAGIC_NULL_PTID means that we don't have any active threads,
5125 so we don't have any TID numbers the inferior will
5126 understand. Make sure to only send forms that do not specify
5127 a TID. */
a9cbf802 5128 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5129 }
0d8f58ca 5130 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5131 {
0d8f58ca
PA
5132 /* Resume all threads (of all processes, or of a single
5133 process), with preference for INFERIOR_PTID. This assumes
5134 inferior_ptid belongs to the set of all threads we are about
5135 to resume. */
a493e3e2 5136 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5137 {
0d8f58ca
PA
5138 /* Step inferior_ptid, with or without signal. */
5139 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5140 }
0d8f58ca 5141
e5ef252a
PA
5142 /* Also pass down any pending signaled resumption for other
5143 threads not the current. */
5144 p = append_pending_thread_resumptions (p, endp, ptid);
5145
0d8f58ca 5146 /* And continue others without a signal. */
a493e3e2 5147 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5148 }
5149 else
506fb367
DJ
5150 {
5151 /* Scheduler locking; resume only PTID. */
a9cbf802 5152 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5153 }
c906108c 5154
82f73884
PA
5155 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5156 putpkt (rs->buf);
506fb367 5157
74531fed
PA
5158 if (non_stop)
5159 {
5160 /* In non-stop, the stub replies to vCont with "OK". The stop
5161 reply will be reported asynchronously by means of a `%Stop'
5162 notification. */
5163 getpkt (&rs->buf, &rs->buf_size, 0);
5164 if (strcmp (rs->buf, "OK") != 0)
5165 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5166 }
5167
506fb367 5168 return 1;
c906108c 5169}
43ff13b4 5170
506fb367
DJ
5171/* Tell the remote machine to resume. */
5172
43ff13b4 5173static void
28439f5e 5174remote_resume (struct target_ops *ops,
2ea28649 5175 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5176{
d01949b6 5177 struct remote_state *rs = get_remote_state ();
2e9f7625 5178 char *buf;
43ff13b4 5179
722247f1
YQ
5180 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5181 (explained in remote-notif.c:handle_notification) so
5182 remote_notif_process is not called. We need find a place where
5183 it is safe to start a 'vNotif' sequence. It is good to do it
5184 before resuming inferior, because inferior was stopped and no RSP
5185 traffic at that moment. */
5186 if (!non_stop)
5965e028 5187 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5188
b73be471 5189 rs->last_sent_signal = siggnal;
280ceea3 5190 rs->last_sent_step = step;
43ff13b4 5191
506fb367 5192 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5193 /* No reverse support (yet) for vCont. */
5194 if (execution_direction != EXEC_REVERSE)
5195 if (remote_vcont_resume (ptid, step, siggnal))
5196 goto done;
506fb367 5197
79d7f229
PA
5198 /* All other supported resume packets do use Hc, so set the continue
5199 thread. */
5200 if (ptid_equal (ptid, minus_one_ptid))
5201 set_continue_thread (any_thread_ptid);
506fb367 5202 else
79d7f229 5203 set_continue_thread (ptid);
506fb367 5204
2e9f7625 5205 buf = rs->buf;
b2175913
MS
5206 if (execution_direction == EXEC_REVERSE)
5207 {
5208 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5209 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5210 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5211 siggnal);
40ab02ce 5212
4082afcc 5213 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5214 error (_("Remote reverse-step not supported."));
4082afcc 5215 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5216 error (_("Remote reverse-continue not supported."));
40ab02ce 5217
b2175913
MS
5218 strcpy (buf, step ? "bs" : "bc");
5219 }
a493e3e2 5220 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5221 {
5222 buf[0] = step ? 'S' : 'C';
c5aa993b 5223 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5224 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5225 buf[3] = '\0';
5226 }
5227 else
c5aa993b 5228 strcpy (buf, step ? "s" : "c");
506fb367 5229
44eaed12 5230 putpkt (buf);
43ff13b4 5231
75c99385 5232 done:
2acceee2 5233 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5234 with the event loop. NOTE: this is the one place where all the
5235 execution commands end up. We could alternatively do this in each
23860348 5236 of the execution commands in infcmd.c. */
2acceee2
JM
5237 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5238 into infcmd.c in order to allow inferior function calls to work
23860348 5239 NOT asynchronously. */
362646f5 5240 if (target_can_async_p ())
6a3753b3 5241 target_async (1);
e24a49d8
PA
5242
5243 /* We've just told the target to resume. The remote server will
5244 wait for the inferior to stop, and then send a stop reply. In
5245 the mean time, we can't start another command/query ourselves
74531fed
PA
5246 because the stub wouldn't be ready to process it. This applies
5247 only to the base all-stop protocol, however. In non-stop (which
5248 only supports vCont), the stub replies with an "OK", and is
5249 immediate able to process further serial input. */
5250 if (!non_stop)
5251 rs->waiting_for_stop_reply = 1;
43ff13b4 5252}
c906108c 5253\f
43ff13b4
JM
5254
5255/* Set up the signal handler for SIGINT, while the target is
23860348 5256 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5257static void
934b9bac 5258async_initialize_sigint_signal_handler (void)
43ff13b4 5259{
934b9bac 5260 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5261}
5262
23860348 5263/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5264static void
934b9bac 5265async_handle_remote_sigint (int sig)
43ff13b4 5266{
934b9bac 5267 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5268 /* Note we need to go through gdb_call_async_signal_handler in order
5269 to wake up the event loop on Windows. */
5270 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5271}
5272
5273/* Signal handler for SIGINT, installed after SIGINT has already been
5274 sent once. It will take effect the second time that the user sends
23860348 5275 a ^C. */
43ff13b4 5276static void
934b9bac 5277async_handle_remote_sigint_twice (int sig)
43ff13b4 5278{
934b9bac 5279 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5280 /* See note in async_handle_remote_sigint. */
5281 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5282}
5283
abc56d60
PA
5284/* Implementation of to_check_pending_interrupt. */
5285
5286static void
5287remote_check_pending_interrupt (struct target_ops *self)
5288{
5289 struct async_signal_handler *token = async_sigint_remote_twice_token;
5290
5291 if (async_signal_handler_is_marked (token))
5292 {
5293 clear_async_signal_handler (token);
5294 call_async_signal_handler (token);
5295 }
5296}
5297
6426a772 5298/* Perform the real interruption of the target execution, in response
23860348 5299 to a ^C. */
c5aa993b 5300static void
fba45db2 5301async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5302{
5303 if (remote_debug)
248fd3bf 5304 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5305
94cc34af 5306 target_stop (inferior_ptid);
43ff13b4
JM
5307}
5308
0df8b418 5309/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5310 up on the target alltogether. */
47e1ce27 5311static void
fba45db2 5312async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5313{
2df3850c 5314 if (remote_debug)
248fd3bf 5315 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5316
5317 interrupt_query ();
43ff13b4
JM
5318}
5319
5320/* Reinstall the usual SIGINT handlers, after the target has
23860348 5321 stopped. */
6426a772 5322static void
934b9bac 5323async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5324{
5325 signal (SIGINT, handle_sigint);
43ff13b4
JM
5326}
5327
c906108c
SS
5328/* Send ^C to target to halt it. Target will respond, and send us a
5329 packet. */
507f3c78 5330static void (*ofunc) (int);
c906108c 5331
bfedc46a
PA
5332/* The command line interface's interrupt routine. This function is installed
5333 as a signal handler for SIGINT. The first time a user requests an
5334 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5335 response from the target (it didn't stop when the user requested it),
23860348 5336 we ask the user if he'd like to detach from the target. */
bfedc46a 5337
c906108c 5338static void
934b9bac 5339sync_remote_interrupt (int signo)
c906108c 5340{
23860348 5341 /* If this doesn't work, try more severe steps. */
934b9bac 5342 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5343
934b9bac 5344 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5345}
5346
5347/* The user typed ^C twice. */
5348
5349static void
934b9bac 5350sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5351{
5352 signal (signo, ofunc);
934b9bac
JK
5353 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5354 signal (signo, sync_remote_interrupt);
c906108c 5355}
7a292a7a 5356
74531fed
PA
5357/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5358 thread, all threads of a remote process, or all threads of all
5359 processes. */
5360
5361static void
5362remote_stop_ns (ptid_t ptid)
5363{
5364 struct remote_state *rs = get_remote_state ();
5365 char *p = rs->buf;
5366 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5367
4082afcc 5368 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5369 remote_vcont_probe (rs);
5370
d458bd84 5371 if (!rs->supports_vCont.t)
74531fed
PA
5372 error (_("Remote server does not support stopping threads"));
5373
f91d3df5
PA
5374 if (ptid_equal (ptid, minus_one_ptid)
5375 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5376 p += xsnprintf (p, endp - p, "vCont;t");
5377 else
5378 {
5379 ptid_t nptid;
5380
74531fed
PA
5381 p += xsnprintf (p, endp - p, "vCont;t:");
5382
5383 if (ptid_is_pid (ptid))
5384 /* All (-1) threads of process. */
ba348170 5385 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5386 else
5387 {
5388 /* Small optimization: if we already have a stop reply for
5389 this thread, no use in telling the stub we want this
5390 stopped. */
5391 if (peek_stop_reply (ptid))
5392 return;
5393
5394 nptid = ptid;
5395 }
5396
a9cbf802 5397 write_ptid (p, endp, nptid);
74531fed
PA
5398 }
5399
5400 /* In non-stop, we get an immediate OK reply. The stop reply will
5401 come in asynchronously by notification. */
5402 putpkt (rs->buf);
5403 getpkt (&rs->buf, &rs->buf_size, 0);
5404 if (strcmp (rs->buf, "OK") != 0)
5405 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5406}
5407
bfedc46a
PA
5408/* All-stop version of target_interrupt. Sends a break or a ^C to
5409 interrupt the remote target. It is undefined which thread of which
5410 process reports the interrupt. */
74531fed
PA
5411
5412static void
bfedc46a 5413remote_interrupt_as (ptid_t ptid)
74531fed
PA
5414{
5415 struct remote_state *rs = get_remote_state ();
5416
3a29589a
DJ
5417 rs->ctrlc_pending_p = 1;
5418
74531fed
PA
5419 /* If the inferior is stopped already, but the core didn't know
5420 about it yet, just ignore the request. The cached wait status
5421 will be collected in remote_wait. */
5422 if (rs->cached_wait_status)
5423 return;
5424
9a7071a8
JB
5425 /* Send interrupt_sequence to remote target. */
5426 send_interrupt_sequence ();
74531fed
PA
5427}
5428
bfedc46a 5429/* Implement the to_stop function for the remote targets. */
74531fed 5430
c906108c 5431static void
1eab8a48 5432remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5433{
7a292a7a 5434 if (remote_debug)
0f71a2f6 5435 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5436
74531fed
PA
5437 if (non_stop)
5438 remote_stop_ns (ptid);
c906108c 5439 else
bfedc46a
PA
5440 {
5441 /* We don't currently have a way to transparently pause the
5442 remote target in all-stop mode. Interrupt it instead. */
5443 remote_interrupt_as (ptid);
5444 }
5445}
5446
5447/* Implement the to_interrupt function for the remote targets. */
5448
5449static void
5450remote_interrupt (struct target_ops *self, ptid_t ptid)
5451{
5452 if (remote_debug)
5453 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5454
5455 if (non_stop)
5456 {
5457 /* We don't currently have a way to ^C the remote target in
5458 non-stop mode. Stop it (with no signal) instead. */
5459 remote_stop_ns (ptid);
5460 }
5461 else
5462 remote_interrupt_as (ptid);
c906108c
SS
5463}
5464
5465/* Ask the user what to do when an interrupt is received. */
5466
5467static void
fba45db2 5468interrupt_query (void)
c906108c 5469{
abc56d60
PA
5470 struct remote_state *rs = get_remote_state ();
5471 struct cleanup *old_chain;
5472
5473 old_chain = make_cleanup_restore_target_terminal ();
c906108c
SS
5474 target_terminal_ours ();
5475
abc56d60 5476 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5477 {
abc56d60
PA
5478 if (query (_("The target is not responding to interrupt requests.\n"
5479 "Stop debugging it? ")))
74531fed 5480 {
78a095c3 5481 remote_unpush_target ();
abc56d60 5482 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5483 }
5484 }
abc56d60
PA
5485 else
5486 {
5487 if (query (_("Interrupted while waiting for the program.\n"
5488 "Give up waiting? ")))
5489 quit ();
5490 }
c906108c 5491
abc56d60 5492 do_cleanups (old_chain);
c906108c
SS
5493}
5494
6426a772
JM
5495/* Enable/disable target terminal ownership. Most targets can use
5496 terminal groups to control terminal ownership. Remote targets are
5497 different in that explicit transfer of ownership to/from GDB/target
23860348 5498 is required. */
6426a772
JM
5499
5500static void
d2f640d4 5501remote_terminal_inferior (struct target_ops *self)
6426a772 5502{
c6ebd6cf 5503 if (!target_async_permitted)
75c99385
PA
5504 /* Nothing to do. */
5505 return;
5506
d9d2d8b6
PA
5507 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5508 idempotent. The event-loop GDB talking to an asynchronous target
5509 with a synchronous command calls this function from both
5510 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5511 transfer the terminal to the target when it shouldn't this guard
5512 can go away. */
6426a772
JM
5513 if (!remote_async_terminal_ours_p)
5514 return;
5515 delete_file_handler (input_fd);
5516 remote_async_terminal_ours_p = 0;
934b9bac 5517 async_initialize_sigint_signal_handler ();
6426a772
JM
5518 /* NOTE: At this point we could also register our selves as the
5519 recipient of all input. Any characters typed could then be
23860348 5520 passed on down to the target. */
6426a772
JM
5521}
5522
5523static void
e3594fd1 5524remote_terminal_ours (struct target_ops *self)
6426a772 5525{
c6ebd6cf 5526 if (!target_async_permitted)
75c99385
PA
5527 /* Nothing to do. */
5528 return;
5529
5530 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5531 if (remote_async_terminal_ours_p)
5532 return;
934b9bac 5533 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5534 add_file_handler (input_fd, stdin_event_handler, 0);
5535 remote_async_terminal_ours_p = 1;
5536}
5537
176a6961 5538static void
917317f4 5539remote_console_output (char *msg)
c906108c
SS
5540{
5541 char *p;
5542
c5aa993b 5543 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5544 {
5545 char tb[2];
5546 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5547
c906108c
SS
5548 tb[0] = c;
5549 tb[1] = 0;
43ff13b4 5550 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5551 }
00db5b94
PA
5552 gdb_flush (gdb_stdtarg);
5553}
74531fed
PA
5554
5555typedef struct cached_reg
5556{
5557 int num;
5558 gdb_byte data[MAX_REGISTER_SIZE];
5559} cached_reg_t;
5560
5561DEF_VEC_O(cached_reg_t);
5562
722247f1 5563typedef struct stop_reply
74531fed 5564{
722247f1 5565 struct notif_event base;
74531fed 5566
722247f1 5567 /* The identifier of the thread about this event */
74531fed
PA
5568 ptid_t ptid;
5569
340e3c99 5570 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5571 connection, represented by a remote_state object, is closed,
5572 all the associated stop_reply events should be released. */
5573 struct remote_state *rs;
5574
74531fed
PA
5575 struct target_waitstatus ws;
5576
15148d6a
PA
5577 /* Expedited registers. This makes remote debugging a bit more
5578 efficient for those targets that provide critical registers as
5579 part of their normal status mechanism (as another roundtrip to
5580 fetch them is avoided). */
74531fed
PA
5581 VEC(cached_reg_t) *regcache;
5582
f7e6eed5
PA
5583 enum target_stop_reason stop_reason;
5584
74531fed
PA
5585 CORE_ADDR watch_data_address;
5586
dc146f7c 5587 int core;
722247f1 5588} *stop_reply_p;
a744cf53 5589
722247f1
YQ
5590DECLARE_QUEUE_P (stop_reply_p);
5591DEFINE_QUEUE_P (stop_reply_p);
5592/* The list of already fetched and acknowledged stop events. This
5593 queue is used for notification Stop, and other notifications
5594 don't need queue for their events, because the notification events
5595 of Stop can't be consumed immediately, so that events should be
5596 queued first, and be consumed by remote_wait_{ns,as} one per
5597 time. Other notifications can consume their events immediately,
5598 so queue is not needed for them. */
5599static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5600
5601static void
5602stop_reply_xfree (struct stop_reply *r)
5603{
f48ff2a7 5604 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5605}
5606
221e1a37
PA
5607/* Return the length of the stop reply queue. */
5608
5609static int
5610stop_reply_queue_length (void)
5611{
5612 return QUEUE_length (stop_reply_p, stop_reply_queue);
5613}
5614
722247f1
YQ
5615static void
5616remote_notif_stop_parse (struct notif_client *self, char *buf,
5617 struct notif_event *event)
5618{
5619 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5620}
5621
5622static void
5623remote_notif_stop_ack (struct notif_client *self, char *buf,
5624 struct notif_event *event)
5625{
5626 struct stop_reply *stop_reply = (struct stop_reply *) event;
5627
5628 /* acknowledge */
5629 putpkt ((char *) self->ack_command);
5630
5631 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5632 /* We got an unknown stop reply. */
5633 error (_("Unknown stop reply"));
5634
5635 push_stop_reply (stop_reply);
5636}
5637
5638static int
5639remote_notif_stop_can_get_pending_events (struct notif_client *self)
5640{
5641 /* We can't get pending events in remote_notif_process for
5642 notification stop, and we have to do this in remote_wait_ns
5643 instead. If we fetch all queued events from stub, remote stub
5644 may exit and we have no chance to process them back in
5645 remote_wait_ns. */
5646 mark_async_event_handler (remote_async_inferior_event_token);
5647 return 0;
5648}
5649
5650static void
5651stop_reply_dtr (struct notif_event *event)
5652{
5653 struct stop_reply *r = (struct stop_reply *) event;
5654
5655 VEC_free (cached_reg_t, r->regcache);
5656}
5657
5658static struct notif_event *
5659remote_notif_stop_alloc_reply (void)
5660{
5661 struct notif_event *r
70ba0933 5662 = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5663
5664 r->dtr = stop_reply_dtr;
5665
5666 return r;
5667}
5668
5669/* A client of notification Stop. */
5670
5671struct notif_client notif_client_stop =
5672{
5673 "Stop",
5674 "vStopped",
5675 remote_notif_stop_parse,
5676 remote_notif_stop_ack,
5677 remote_notif_stop_can_get_pending_events,
5678 remote_notif_stop_alloc_reply,
f48ff2a7 5679 REMOTE_NOTIF_STOP,
722247f1
YQ
5680};
5681
5682/* A parameter to pass data in and out. */
5683
5684struct queue_iter_param
5685{
5686 void *input;
5687 struct stop_reply *output;
5688};
5689
cbb8991c
DB
5690/* Determine if THREAD is a pending fork parent thread. ARG contains
5691 the pid of the process that owns the threads we want to check, or
5692 -1 if we want to check all threads. */
5693
5694static int
5695is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5696 ptid_t thread_ptid)
5697{
5698 if (ws->kind == TARGET_WAITKIND_FORKED
5699 || ws->kind == TARGET_WAITKIND_VFORKED)
5700 {
5701 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5702 return 1;
5703 }
5704
5705 return 0;
5706}
5707
5708/* Check whether EVENT is a fork event, and if it is, remove the
5709 fork child from the context list passed in DATA. */
5710
5711static int
5712remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5713 QUEUE_ITER (stop_reply_p) *iter,
5714 stop_reply_p event,
5715 void *data)
5716{
5717 struct queue_iter_param *param = data;
5718 struct threads_listing_context *context = param->input;
5719
5720 if (event->ws.kind == TARGET_WAITKIND_FORKED
5721 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5722 {
5723 threads_listing_context_remove (&event->ws, context);
5724 }
5725
5726 return 1;
5727}
5728
5729/* If CONTEXT contains any fork child threads that have not been
5730 reported yet, remove them from the CONTEXT list. If such a
5731 thread exists it is because we are stopped at a fork catchpoint
5732 and have not yet called follow_fork, which will set up the
5733 host-side data structures for the new process. */
5734
5735static void
5736remove_new_fork_children (struct threads_listing_context *context)
5737{
5738 struct thread_info * thread;
5739 int pid = -1;
5740 struct notif_client *notif = &notif_client_stop;
5741 struct queue_iter_param param;
5742
5743 /* For any threads stopped at a fork event, remove the corresponding
5744 fork child threads from the CONTEXT list. */
5745 ALL_NON_EXITED_THREADS (thread)
5746 {
5747 struct target_waitstatus *ws = &thread->pending_follow;
5748
5749 if (is_pending_fork_parent (ws, pid, thread->ptid))
5750 {
5751 threads_listing_context_remove (ws, context);
5752 }
5753 }
5754
5755 /* Check for any pending fork events (not reported or processed yet)
5756 in process PID and remove those fork child threads from the
5757 CONTEXT list as well. */
5758 remote_notif_get_pending_events (notif);
5759 param.input = context;
5760 param.output = NULL;
5761 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5762 remove_child_of_pending_fork, &param);
5763}
5764
f48ff2a7
YQ
5765/* Remove stop replies in the queue if its pid is equal to the given
5766 inferior's pid. */
722247f1
YQ
5767
5768static int
f48ff2a7
YQ
5769remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5770 QUEUE_ITER (stop_reply_p) *iter,
5771 stop_reply_p event,
5772 void *data)
722247f1
YQ
5773{
5774 struct queue_iter_param *param = data;
5775 struct inferior *inf = param->input;
5776
f48ff2a7 5777 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5778 {
5779 stop_reply_xfree (event);
5780 QUEUE_remove_elem (stop_reply_p, q, iter);
5781 }
5782
5783 return 1;
5784}
5785
f48ff2a7 5786/* Discard all pending stop replies of inferior INF. */
c906108c 5787
74531fed 5788static void
5f4cf0bb 5789discard_pending_stop_replies (struct inferior *inf)
c906108c 5790{
722247f1
YQ
5791 int i;
5792 struct queue_iter_param param;
f48ff2a7
YQ
5793 struct stop_reply *reply;
5794 struct remote_state *rs = get_remote_state ();
5795 struct remote_notif_state *rns = rs->notif_state;
5796
5797 /* This function can be notified when an inferior exists. When the
5798 target is not remote, the notification state is NULL. */
5799 if (rs->remote_desc == NULL)
5800 return;
5801
5802 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5803
74531fed 5804 /* Discard the in-flight notification. */
f48ff2a7 5805 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5806 {
722247f1 5807 stop_reply_xfree (reply);
f48ff2a7 5808 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5809 }
c906108c 5810
722247f1
YQ
5811 param.input = inf;
5812 param.output = NULL;
74531fed
PA
5813 /* Discard the stop replies we have already pulled with
5814 vStopped. */
722247f1 5815 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5816 remove_stop_reply_for_inferior, &param);
5817}
5818
bcc75809
YQ
5819/* If its remote state is equal to the given remote state,
5820 remove EVENT from the stop reply queue. */
5821
5822static int
5823remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5824 QUEUE_ITER (stop_reply_p) *iter,
5825 stop_reply_p event,
5826 void *data)
5827{
5828 struct queue_iter_param *param = data;
5829 struct remote_state *rs = param->input;
5830
5831 if (event->rs == rs)
5832 {
5833 stop_reply_xfree (event);
5834 QUEUE_remove_elem (stop_reply_p, q, iter);
5835 }
5836
5837 return 1;
5838}
5839
5840/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5841
5842static void
bcc75809 5843discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5844{
5845 struct queue_iter_param param;
5846
bcc75809 5847 param.input = rs;
f48ff2a7
YQ
5848 param.output = NULL;
5849 /* Discard the stop replies we have already pulled with
5850 vStopped. */
5851 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5852 remove_stop_reply_of_remote_state, &param);
722247f1 5853}
74531fed 5854
722247f1
YQ
5855/* A parameter to pass data in and out. */
5856
5857static int
5858remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5859 QUEUE_ITER (stop_reply_p) *iter,
5860 stop_reply_p event,
5861 void *data)
5862{
5863 struct queue_iter_param *param = data;
5864 ptid_t *ptid = param->input;
5865
5866 if (ptid_match (event->ptid, *ptid))
5867 {
5868 param->output = event;
5869 QUEUE_remove_elem (stop_reply_p, q, iter);
5870 return 0;
c8e38a49 5871 }
722247f1
YQ
5872
5873 return 1;
74531fed 5874}
43ff13b4 5875
722247f1
YQ
5876/* Remove the first reply in 'stop_reply_queue' which matches
5877 PTID. */
2e9f7625 5878
722247f1
YQ
5879static struct stop_reply *
5880remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5881{
722247f1
YQ
5882 struct queue_iter_param param;
5883
5884 param.input = &ptid;
5885 param.output = NULL;
5886
5887 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5888 remote_notif_remove_once_on_match, &param);
5889 if (notif_debug)
5890 fprintf_unfiltered (gdb_stdlog,
5891 "notif: discard queued event: 'Stop' in %s\n",
5892 target_pid_to_str (ptid));
a744cf53 5893
722247f1 5894 return param.output;
74531fed 5895}
75c99385 5896
74531fed
PA
5897/* Look for a queued stop reply belonging to PTID. If one is found,
5898 remove it from the queue, and return it. Returns NULL if none is
5899 found. If there are still queued events left to process, tell the
5900 event loop to get back to target_wait soon. */
e24a49d8 5901
74531fed
PA
5902static struct stop_reply *
5903queued_stop_reply (ptid_t ptid)
5904{
722247f1 5905 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5906
722247f1 5907 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5908 /* There's still at least an event left. */
5909 mark_async_event_handler (remote_async_inferior_event_token);
5910
722247f1 5911 return r;
74531fed
PA
5912}
5913
5914/* Push a fully parsed stop reply in the stop reply queue. Since we
5915 know that we now have at least one queued event left to pass to the
5916 core side, tell the event loop to get back to target_wait soon. */
5917
5918static void
5919push_stop_reply (struct stop_reply *new_event)
5920{
722247f1 5921 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5922
722247f1
YQ
5923 if (notif_debug)
5924 fprintf_unfiltered (gdb_stdlog,
5925 "notif: push 'Stop' %s to queue %d\n",
5926 target_pid_to_str (new_event->ptid),
5927 QUEUE_length (stop_reply_p,
5928 stop_reply_queue));
74531fed
PA
5929
5930 mark_async_event_handler (remote_async_inferior_event_token);
5931}
5932
722247f1
YQ
5933static int
5934stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5935 QUEUE_ITER (stop_reply_p) *iter,
5936 struct stop_reply *event,
5937 void *data)
5938{
5939 ptid_t *ptid = data;
5940
5941 return !(ptid_equal (*ptid, event->ptid)
5942 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5943}
5944
74531fed
PA
5945/* Returns true if we have a stop reply for PTID. */
5946
5947static int
5948peek_stop_reply (ptid_t ptid)
5949{
722247f1
YQ
5950 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5951 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5952}
5953
1f10ba14
PA
5954/* Skip PACKET until the next semi-colon (or end of string). */
5955
5956static char *
5957skip_to_semicolon (char *p)
5958{
5959 while (*p != '\0' && *p != ';')
5960 p++;
5961 return p;
5962}
5963
26d56a93
SL
5964/* Helper for remote_parse_stop_reply. Return nonzero if the substring
5965 starting with P and ending with PEND matches PREFIX. */
5966
5967static int
5968strprefix (const char *p, const char *pend, const char *prefix)
5969{
5970 for ( ; p < pend; p++, prefix++)
5971 if (*p != *prefix)
5972 return 0;
5973 return *prefix == '\0';
5974}
5975
74531fed
PA
5976/* Parse the stop reply in BUF. Either the function succeeds, and the
5977 result is stored in EVENT, or throws an error. */
5978
5979static void
5980remote_parse_stop_reply (char *buf, struct stop_reply *event)
5981{
5982 struct remote_arch_state *rsa = get_remote_arch_state ();
5983 ULONGEST addr;
5984 char *p;
5985
5986 event->ptid = null_ptid;
bcc75809 5987 event->rs = get_remote_state ();
74531fed
PA
5988 event->ws.kind = TARGET_WAITKIND_IGNORE;
5989 event->ws.value.integer = 0;
f7e6eed5 5990 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 5991 event->regcache = NULL;
dc146f7c 5992 event->core = -1;
74531fed
PA
5993
5994 switch (buf[0])
5995 {
5996 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5997 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5998 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5999 ss = signal number
6000 n... = register number
6001 r... = register contents
6002 */
6003
6004 p = &buf[3]; /* after Txx */
6005 while (*p)
6006 {
6007 char *p1;
cea39f65 6008 int fieldsize;
43ff13b4 6009
1f10ba14
PA
6010 p1 = strchr (p, ':');
6011 if (p1 == NULL)
6012 error (_("Malformed packet(a) (missing colon): %s\n\
6013Packet: '%s'\n"),
6014 p, buf);
6015 if (p == p1)
6016 error (_("Malformed packet(a) (missing register number): %s\n\
6017Packet: '%s'\n"),
6018 p, buf);
3c3bea1c 6019
1f10ba14
PA
6020 /* Some "registers" are actually extended stop information.
6021 Note if you're adding a new entry here: GDB 7.9 and
6022 earlier assume that all register "numbers" that start
6023 with an hex digit are real register numbers. Make sure
6024 the server only sends such a packet if it knows the
6025 client understands it. */
c8e38a49 6026
26d56a93 6027 if (strprefix (p, p1, "thread"))
1f10ba14 6028 event->ptid = read_ptid (++p1, &p);
26d56a93
SL
6029 else if (strprefix (p, p1, "watch")
6030 || strprefix (p, p1, "rwatch")
6031 || strprefix (p, p1, "awatch"))
cea39f65 6032 {
f7e6eed5 6033 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6034 p = unpack_varlen_hex (++p1, &addr);
6035 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6036 }
26d56a93 6037 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6038 {
6039 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6040
6041 /* Make sure the stub doesn't forget to indicate support
6042 with qSupported. */
6043 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6044 error (_("Unexpected swbreak stop reason"));
6045
6046 /* The value part is documented as "must be empty",
6047 though we ignore it, in case we ever decide to make
6048 use of it in a backward compatible way. */
6049 p = skip_to_semicolon (p1 + 1);
6050 }
26d56a93 6051 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6052 {
6053 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6054
6055 /* Make sure the stub doesn't forget to indicate support
6056 with qSupported. */
6057 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6058 error (_("Unexpected hwbreak stop reason"));
6059
6060 /* See above. */
6061 p = skip_to_semicolon (p1 + 1);
6062 }
26d56a93 6063 else if (strprefix (p, p1, "library"))
cea39f65 6064 {
1f10ba14
PA
6065 event->ws.kind = TARGET_WAITKIND_LOADED;
6066 p = skip_to_semicolon (p1 + 1);
6067 }
26d56a93 6068 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6069 {
6070 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6071 /* p1 will indicate "begin" or "end", but it makes
6072 no difference for now, so ignore it. */
6073 p = skip_to_semicolon (p1 + 1);
6074 }
26d56a93 6075 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6076 {
6077 ULONGEST c;
a744cf53 6078
1f10ba14
PA
6079 p = unpack_varlen_hex (++p1, &c);
6080 event->core = c;
cea39f65 6081 }
26d56a93 6082 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6083 {
6084 event->ws.value.related_pid = read_ptid (++p1, &p);
6085 event->ws.kind = TARGET_WAITKIND_FORKED;
6086 }
26d56a93 6087 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6088 {
6089 event->ws.value.related_pid = read_ptid (++p1, &p);
6090 event->ws.kind = TARGET_WAITKIND_VFORKED;
6091 }
26d56a93 6092 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6093 {
6094 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6095 p = skip_to_semicolon (p1 + 1);
6096 }
cea39f65
MS
6097 else
6098 {
1f10ba14
PA
6099 ULONGEST pnum;
6100 char *p_temp;
6101
6102 /* Maybe a real ``P'' register number. */
6103 p_temp = unpack_varlen_hex (p, &pnum);
6104 /* If the first invalid character is the colon, we got a
6105 register number. Otherwise, it's an unknown stop
6106 reason. */
6107 if (p_temp == p1)
6108 {
6109 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6110 cached_reg_t cached_reg;
43ff13b4 6111
1f10ba14
PA
6112 if (reg == NULL)
6113 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6114Packet: '%s'\n"),
1f10ba14 6115 hex_string (pnum), p, buf);
c8e38a49 6116
1f10ba14 6117 cached_reg.num = reg->regnum;
4100683b 6118
1f10ba14
PA
6119 p = p1 + 1;
6120 fieldsize = hex2bin (p, cached_reg.data,
6121 register_size (target_gdbarch (),
6122 reg->regnum));
6123 p += 2 * fieldsize;
6124 if (fieldsize < register_size (target_gdbarch (),
6125 reg->regnum))
6126 warning (_("Remote reply is too short: %s"), buf);
74531fed 6127
1f10ba14
PA
6128 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6129 }
6130 else
6131 {
6132 /* Not a number. Silently skip unknown optional
6133 info. */
6134 p = skip_to_semicolon (p1 + 1);
6135 }
cea39f65 6136 }
c8e38a49 6137
cea39f65
MS
6138 if (*p != ';')
6139 error (_("Remote register badly formatted: %s\nhere: %s"),
6140 buf, p);
6141 ++p;
6142 }
5b5596ff
PA
6143
6144 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6145 break;
6146
c8e38a49
PA
6147 /* fall through */
6148 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6149 {
6150 int sig;
6151
6152 event->ws.kind = TARGET_WAITKIND_STOPPED;
6153 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6154 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6155 event->ws.value.sig = (enum gdb_signal) sig;
6156 else
6157 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6158 }
c8e38a49
PA
6159 break;
6160 case 'W': /* Target exited. */
6161 case 'X':
6162 {
6163 char *p;
6164 int pid;
6165 ULONGEST value;
82f73884 6166
c8e38a49
PA
6167 /* GDB used to accept only 2 hex chars here. Stubs should
6168 only send more if they detect GDB supports multi-process
6169 support. */
6170 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6171
c8e38a49
PA
6172 if (buf[0] == 'W')
6173 {
6174 /* The remote process exited. */
74531fed
PA
6175 event->ws.kind = TARGET_WAITKIND_EXITED;
6176 event->ws.value.integer = value;
c8e38a49
PA
6177 }
6178 else
6179 {
6180 /* The remote process exited with a signal. */
74531fed 6181 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6182 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6183 event->ws.value.sig = (enum gdb_signal) value;
6184 else
6185 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6186 }
82f73884 6187
c8e38a49
PA
6188 /* If no process is specified, assume inferior_ptid. */
6189 pid = ptid_get_pid (inferior_ptid);
6190 if (*p == '\0')
6191 ;
6192 else if (*p == ';')
6193 {
6194 p++;
6195
0b24eb2d 6196 if (*p == '\0')
82f73884 6197 ;
61012eef 6198 else if (startswith (p, "process:"))
82f73884 6199 {
c8e38a49 6200 ULONGEST upid;
a744cf53 6201
c8e38a49
PA
6202 p += sizeof ("process:") - 1;
6203 unpack_varlen_hex (p, &upid);
6204 pid = upid;
82f73884
PA
6205 }
6206 else
6207 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6208 }
c8e38a49
PA
6209 else
6210 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6211 event->ptid = pid_to_ptid (pid);
6212 }
6213 break;
6214 }
6215
6216 if (non_stop && ptid_equal (event->ptid, null_ptid))
6217 error (_("No process or thread specified in stop reply: %s"), buf);
6218}
6219
722247f1
YQ
6220/* When the stub wants to tell GDB about a new notification reply, it
6221 sends a notification (%Stop, for example). Those can come it at
6222 any time, hence, we have to make sure that any pending
6223 putpkt/getpkt sequence we're making is finished, before querying
6224 the stub for more events with the corresponding ack command
6225 (vStopped, for example). E.g., if we started a vStopped sequence
6226 immediately upon receiving the notification, something like this
6227 could happen:
74531fed
PA
6228
6229 1.1) --> Hg 1
6230 1.2) <-- OK
6231 1.3) --> g
6232 1.4) <-- %Stop
6233 1.5) --> vStopped
6234 1.6) <-- (registers reply to step #1.3)
6235
6236 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6237 query.
6238
796cb314 6239 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6240 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6241 doing whatever we were doing:
6242
6243 2.1) --> Hg 1
6244 2.2) <-- OK
6245 2.3) --> g
6246 2.4) <-- %Stop
6247 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6248 2.5) <-- (registers reply to step #2.3)
6249
6250 Eventualy after step #2.5, we return to the event loop, which
6251 notices there's an event on the
6252 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6253 associated callback --- the function below. At this point, we're
6254 always safe to start a vStopped sequence. :
6255
6256 2.6) --> vStopped
6257 2.7) <-- T05 thread:2
6258 2.8) --> vStopped
6259 2.9) --> OK
6260*/
6261
722247f1
YQ
6262void
6263remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6264{
6265 struct remote_state *rs = get_remote_state ();
74531fed 6266
f48ff2a7 6267 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6268 {
722247f1
YQ
6269 if (notif_debug)
6270 fprintf_unfiltered (gdb_stdlog,
6271 "notif: process: '%s' ack pending event\n",
6272 nc->name);
74531fed 6273
722247f1 6274 /* acknowledge */
f48ff2a7
YQ
6275 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6276 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6277
6278 while (1)
6279 {
6280 getpkt (&rs->buf, &rs->buf_size, 0);
6281 if (strcmp (rs->buf, "OK") == 0)
6282 break;
6283 else
722247f1 6284 remote_notif_ack (nc, rs->buf);
74531fed
PA
6285 }
6286 }
722247f1
YQ
6287 else
6288 {
6289 if (notif_debug)
6290 fprintf_unfiltered (gdb_stdlog,
6291 "notif: process: '%s' no pending reply\n",
6292 nc->name);
6293 }
74531fed
PA
6294}
6295
74531fed
PA
6296/* Called when it is decided that STOP_REPLY holds the info of the
6297 event that is to be returned to the core. This function always
6298 destroys STOP_REPLY. */
6299
6300static ptid_t
6301process_stop_reply (struct stop_reply *stop_reply,
6302 struct target_waitstatus *status)
6303{
6304 ptid_t ptid;
6305
6306 *status = stop_reply->ws;
6307 ptid = stop_reply->ptid;
6308
6309 /* If no thread/process was reported by the stub, assume the current
6310 inferior. */
6311 if (ptid_equal (ptid, null_ptid))
6312 ptid = inferior_ptid;
6313
5f3563ea
PA
6314 if (status->kind != TARGET_WAITKIND_EXITED
6315 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 6316 {
ee154bee
TT
6317 struct remote_state *rs = get_remote_state ();
6318
5f3563ea
PA
6319 /* Expedited registers. */
6320 if (stop_reply->regcache)
6321 {
217f1f79 6322 struct regcache *regcache
f5656ead 6323 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6324 cached_reg_t *reg;
6325 int ix;
6326
6327 for (ix = 0;
6328 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6329 ix++)
217f1f79 6330 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6331 VEC_free (cached_reg_t, stop_reply->regcache);
6332 }
74531fed 6333
f7e6eed5 6334 rs->stop_reason = stop_reply->stop_reason;
ee154bee 6335 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
6336
6337 remote_notice_new_inferior (ptid, 0);
dc146f7c 6338 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
6339 }
6340
74531fed
PA
6341 stop_reply_xfree (stop_reply);
6342 return ptid;
6343}
6344
6345/* The non-stop mode version of target_wait. */
6346
6347static ptid_t
47608cb1 6348remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6349{
6350 struct remote_state *rs = get_remote_state ();
74531fed
PA
6351 struct stop_reply *stop_reply;
6352 int ret;
fee9eda9 6353 int is_notif = 0;
74531fed
PA
6354
6355 /* If in non-stop mode, get out of getpkt even if a
6356 notification is received. */
6357
6358 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6359 0 /* forever */, &is_notif);
74531fed
PA
6360 while (1)
6361 {
fee9eda9 6362 if (ret != -1 && !is_notif)
74531fed
PA
6363 switch (rs->buf[0])
6364 {
6365 case 'E': /* Error of some sort. */
6366 /* We're out of sync with the target now. Did it continue
6367 or not? We can't tell which thread it was in non-stop,
6368 so just ignore this. */
6369 warning (_("Remote failure reply: %s"), rs->buf);
6370 break;
6371 case 'O': /* Console output. */
6372 remote_console_output (rs->buf + 1);
6373 break;
6374 default:
6375 warning (_("Invalid remote reply: %s"), rs->buf);
6376 break;
6377 }
6378
6379 /* Acknowledge a pending stop reply that may have arrived in the
6380 mean time. */
f48ff2a7 6381 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6382 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6383
6384 /* If indeed we noticed a stop reply, we're done. */
6385 stop_reply = queued_stop_reply (ptid);
6386 if (stop_reply != NULL)
6387 return process_stop_reply (stop_reply, status);
6388
47608cb1 6389 /* Still no event. If we're just polling for an event, then
74531fed 6390 return to the event loop. */
47608cb1 6391 if (options & TARGET_WNOHANG)
74531fed
PA
6392 {
6393 status->kind = TARGET_WAITKIND_IGNORE;
6394 return minus_one_ptid;
6395 }
6396
47608cb1 6397 /* Otherwise do a blocking wait. */
74531fed 6398 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6399 1 /* forever */, &is_notif);
74531fed
PA
6400 }
6401}
6402
6403/* Wait until the remote machine stops, then return, storing status in
6404 STATUS just as `wait' would. */
6405
6406static ptid_t
47608cb1 6407remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6408{
6409 struct remote_state *rs = get_remote_state ();
74531fed 6410 ptid_t event_ptid = null_ptid;
cea39f65 6411 char *buf;
74531fed
PA
6412 struct stop_reply *stop_reply;
6413
47608cb1
PA
6414 again:
6415
74531fed
PA
6416 status->kind = TARGET_WAITKIND_IGNORE;
6417 status->value.integer = 0;
6418
6419 stop_reply = queued_stop_reply (ptid);
6420 if (stop_reply != NULL)
6421 return process_stop_reply (stop_reply, status);
6422
6423 if (rs->cached_wait_status)
6424 /* Use the cached wait status, but only once. */
6425 rs->cached_wait_status = 0;
6426 else
6427 {
6428 int ret;
722247f1 6429 int is_notif;
567420d1
PA
6430 int forever = ((options & TARGET_WNOHANG) == 0
6431 && wait_forever_enabled_p);
6432
6433 if (!rs->waiting_for_stop_reply)
6434 {
6435 status->kind = TARGET_WAITKIND_NO_RESUMED;
6436 return minus_one_ptid;
6437 }
74531fed
PA
6438
6439 if (!target_is_async_p ())
6440 {
934b9bac 6441 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6442 /* If the user hit C-c before this packet, or between packets,
6443 pretend that it was hit right here. */
522002f9 6444 if (check_quit_flag ())
74531fed 6445 {
522002f9 6446 clear_quit_flag ();
934b9bac 6447 sync_remote_interrupt (SIGINT);
74531fed
PA
6448 }
6449 }
6450
6451 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6452 _never_ wait for ever -> test on target_is_async_p().
6453 However, before we do that we need to ensure that the caller
6454 knows how to take the target into/out of async mode. */
722247f1 6455 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6456 forever, &is_notif);
722247f1 6457
5e1b953b
SDJ
6458 if (!target_is_async_p ())
6459 signal (SIGINT, ofunc);
6460
722247f1
YQ
6461 /* GDB gets a notification. Return to core as this event is
6462 not interesting. */
6463 if (ret != -1 && is_notif)
6464 return minus_one_ptid;
567420d1
PA
6465
6466 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6467 return minus_one_ptid;
74531fed
PA
6468 }
6469
6470 buf = rs->buf;
6471
f7e6eed5 6472 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed
PA
6473
6474 /* We got something. */
6475 rs->waiting_for_stop_reply = 0;
6476
3a29589a
DJ
6477 /* Assume that the target has acknowledged Ctrl-C unless we receive
6478 an 'F' or 'O' packet. */
6479 if (buf[0] != 'F' && buf[0] != 'O')
6480 rs->ctrlc_pending_p = 0;
6481
74531fed
PA
6482 switch (buf[0])
6483 {
6484 case 'E': /* Error of some sort. */
6485 /* We're out of sync with the target now. Did it continue or
6486 not? Not is more likely, so report a stop. */
6487 warning (_("Remote failure reply: %s"), buf);
6488 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6489 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6490 break;
6491 case 'F': /* File-I/O request. */
3a29589a
DJ
6492 remote_fileio_request (buf, rs->ctrlc_pending_p);
6493 rs->ctrlc_pending_p = 0;
74531fed
PA
6494 break;
6495 case 'T': case 'S': case 'X': case 'W':
6496 {
722247f1
YQ
6497 struct stop_reply *stop_reply
6498 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6499 rs->buf);
74531fed 6500
74531fed 6501 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6502 break;
6503 }
6504 case 'O': /* Console output. */
6505 remote_console_output (buf + 1);
e24a49d8 6506
c8e38a49
PA
6507 /* The target didn't really stop; keep waiting. */
6508 rs->waiting_for_stop_reply = 1;
e24a49d8 6509
c8e38a49
PA
6510 break;
6511 case '\0':
b73be471 6512 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6513 {
6514 /* Zero length reply means that we tried 'S' or 'C' and the
6515 remote system doesn't support it. */
6516 target_terminal_ours_for_output ();
6517 printf_filtered
6518 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6519 gdb_signal_to_name (rs->last_sent_signal));
6520 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6521 target_terminal_inferior ();
6522
280ceea3 6523 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6524 putpkt ((char *) buf);
6525
6526 /* We just told the target to resume, so a stop reply is in
6527 order. */
e24a49d8 6528 rs->waiting_for_stop_reply = 1;
c8e38a49 6529 break;
43ff13b4 6530 }
c8e38a49
PA
6531 /* else fallthrough */
6532 default:
6533 warning (_("Invalid remote reply: %s"), buf);
6534 /* Keep waiting. */
6535 rs->waiting_for_stop_reply = 1;
6536 break;
43ff13b4 6537 }
c8e38a49 6538
c8e38a49 6539 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6540 {
6541 /* Nothing interesting happened. If we're doing a non-blocking
6542 poll, we're done. Otherwise, go back to waiting. */
6543 if (options & TARGET_WNOHANG)
6544 return minus_one_ptid;
6545 else
6546 goto again;
6547 }
74531fed
PA
6548 else if (status->kind != TARGET_WAITKIND_EXITED
6549 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6550 {
6551 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6552 record_currthread (rs, event_ptid);
82f73884
PA
6553 else
6554 event_ptid = inferior_ptid;
43ff13b4 6555 }
74531fed
PA
6556 else
6557 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6558 record_currthread (rs, minus_one_ptid);
79d7f229 6559
82f73884 6560 return event_ptid;
43ff13b4
JM
6561}
6562
74531fed
PA
6563/* Wait until the remote machine stops, then return, storing status in
6564 STATUS just as `wait' would. */
6565
c8e38a49 6566static ptid_t
117de6a9 6567remote_wait (struct target_ops *ops,
47608cb1 6568 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6569{
6570 ptid_t event_ptid;
6571
74531fed 6572 if (non_stop)
47608cb1 6573 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6574 else
47608cb1 6575 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6576
d9d41e78 6577 if (target_is_async_p ())
c8e38a49 6578 {
74531fed
PA
6579 /* If there are are events left in the queue tell the event loop
6580 to return here. */
722247f1 6581 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6582 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6583 }
c8e38a49
PA
6584
6585 return event_ptid;
6586}
6587
74ca34ce 6588/* Fetch a single register using a 'p' packet. */
c906108c 6589
b96ec7ac 6590static int
56be3814 6591fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6592{
6593 struct remote_state *rs = get_remote_state ();
2e9f7625 6594 char *buf, *p;
b96ec7ac
AC
6595 char regp[MAX_REGISTER_SIZE];
6596 int i;
6597
4082afcc 6598 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6599 return 0;
6600
6601 if (reg->pnum == -1)
6602 return 0;
6603
2e9f7625 6604 p = rs->buf;
fcad0fa4 6605 *p++ = 'p';
74ca34ce 6606 p += hexnumstr (p, reg->pnum);
fcad0fa4 6607 *p++ = '\0';
1f4437a4
MS
6608 putpkt (rs->buf);
6609 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6610
2e9f7625
DJ
6611 buf = rs->buf;
6612
74ca34ce
DJ
6613 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6614 {
6615 case PACKET_OK:
6616 break;
6617 case PACKET_UNKNOWN:
6618 return 0;
6619 case PACKET_ERROR:
27a9c0bf
MS
6620 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6621 gdbarch_register_name (get_regcache_arch (regcache),
6622 reg->regnum),
6623 buf);
74ca34ce 6624 }
3f9a994c
JB
6625
6626 /* If this register is unfetchable, tell the regcache. */
6627 if (buf[0] == 'x')
8480adf2 6628 {
56be3814 6629 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6630 return 1;
b96ec7ac 6631 }
b96ec7ac 6632
3f9a994c
JB
6633 /* Otherwise, parse and supply the value. */
6634 p = buf;
6635 i = 0;
6636 while (p[0] != 0)
6637 {
6638 if (p[1] == 0)
74ca34ce 6639 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6640
6641 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6642 p += 2;
6643 }
56be3814 6644 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6645 return 1;
b96ec7ac
AC
6646}
6647
74ca34ce
DJ
6648/* Fetch the registers included in the target's 'g' packet. */
6649
29709017
DJ
6650static int
6651send_g_packet (void)
c906108c 6652{
d01949b6 6653 struct remote_state *rs = get_remote_state ();
cea39f65 6654 int buf_len;
c906108c 6655
bba74b36 6656 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6657 remote_send (&rs->buf, &rs->buf_size);
c906108c 6658
29709017
DJ
6659 /* We can get out of synch in various cases. If the first character
6660 in the buffer is not a hex character, assume that has happened
6661 and try to fetch another packet to read. */
6662 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6663 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6664 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6665 && rs->buf[0] != 'x') /* New: unavailable register value. */
6666 {
6667 if (remote_debug)
6668 fprintf_unfiltered (gdb_stdlog,
6669 "Bad register packet; fetching a new packet\n");
6670 getpkt (&rs->buf, &rs->buf_size, 0);
6671 }
6672
74ca34ce
DJ
6673 buf_len = strlen (rs->buf);
6674
6675 /* Sanity check the received packet. */
6676 if (buf_len % 2 != 0)
6677 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6678
6679 return buf_len / 2;
6680}
6681
6682static void
56be3814 6683process_g_packet (struct regcache *regcache)
29709017 6684{
4a22f64d 6685 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6686 struct remote_state *rs = get_remote_state ();
6687 struct remote_arch_state *rsa = get_remote_arch_state ();
6688 int i, buf_len;
6689 char *p;
6690 char *regs;
6691
6692 buf_len = strlen (rs->buf);
6693
6694 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6695 if (buf_len > 2 * rsa->sizeof_g_packet)
6696 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6697
6698 /* Save the size of the packet sent to us by the target. It is used
6699 as a heuristic when determining the max size of packets that the
6700 target can safely receive. */
6701 if (rsa->actual_register_packet_size == 0)
6702 rsa->actual_register_packet_size = buf_len;
6703
6704 /* If this is smaller than we guessed the 'g' packet would be,
6705 update our records. A 'g' reply that doesn't include a register's
6706 value implies either that the register is not available, or that
6707 the 'p' packet must be used. */
6708 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6709 {
74ca34ce
DJ
6710 rsa->sizeof_g_packet = buf_len / 2;
6711
4a22f64d 6712 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6713 {
74ca34ce
DJ
6714 if (rsa->regs[i].pnum == -1)
6715 continue;
6716
6717 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6718 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6719 else
74ca34ce 6720 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6721 }
74ca34ce 6722 }
b323314b 6723
74ca34ce 6724 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6725
6726 /* Unimplemented registers read as all bits zero. */
ea9c271d 6727 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6728
c906108c
SS
6729 /* Reply describes registers byte by byte, each byte encoded as two
6730 hex characters. Suck them all up, then supply them to the
6731 register cacheing/storage mechanism. */
6732
74ca34ce 6733 p = rs->buf;
ea9c271d 6734 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6735 {
74ca34ce
DJ
6736 if (p[0] == 0 || p[1] == 0)
6737 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6738 internal_error (__FILE__, __LINE__,
9b20d036 6739 _("unexpected end of 'g' packet reply"));
74ca34ce 6740
c906108c 6741 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6742 regs[i] = 0; /* 'x' */
c906108c
SS
6743 else
6744 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6745 p += 2;
6746 }
6747
a744cf53
MS
6748 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6749 {
6750 struct packet_reg *r = &rsa->regs[i];
6751
6752 if (r->in_g_packet)
6753 {
6754 if (r->offset * 2 >= strlen (rs->buf))
6755 /* This shouldn't happen - we adjusted in_g_packet above. */
6756 internal_error (__FILE__, __LINE__,
9b20d036 6757 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6758 else if (rs->buf[r->offset * 2] == 'x')
6759 {
6760 gdb_assert (r->offset * 2 < strlen (rs->buf));
6761 /* The register isn't available, mark it as such (at
6762 the same time setting the value to zero). */
6763 regcache_raw_supply (regcache, r->regnum, NULL);
6764 }
6765 else
6766 regcache_raw_supply (regcache, r->regnum,
6767 regs + r->offset);
6768 }
6769 }
c906108c
SS
6770}
6771
29709017 6772static void
56be3814 6773fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6774{
6775 send_g_packet ();
56be3814 6776 process_g_packet (regcache);
29709017
DJ
6777}
6778
e6e4e701
PA
6779/* Make the remote selected traceframe match GDB's selected
6780 traceframe. */
6781
6782static void
6783set_remote_traceframe (void)
6784{
6785 int newnum;
262e1174 6786 struct remote_state *rs = get_remote_state ();
e6e4e701 6787
262e1174 6788 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6789 return;
6790
6791 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6792 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6793
6794 newnum = target_trace_find (tfind_number,
6795 get_traceframe_number (), 0, 0, NULL);
6796
6797 /* Should not happen. If it does, all bets are off. */
6798 if (newnum != get_traceframe_number ())
6799 warning (_("could not set remote traceframe"));
6800}
6801
74ca34ce 6802static void
28439f5e
PA
6803remote_fetch_registers (struct target_ops *ops,
6804 struct regcache *regcache, int regnum)
74ca34ce 6805{
74ca34ce
DJ
6806 struct remote_arch_state *rsa = get_remote_arch_state ();
6807 int i;
6808
e6e4e701 6809 set_remote_traceframe ();
79d7f229 6810 set_general_thread (inferior_ptid);
74ca34ce
DJ
6811
6812 if (regnum >= 0)
6813 {
6814 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6815
74ca34ce
DJ
6816 gdb_assert (reg != NULL);
6817
6818 /* If this register might be in the 'g' packet, try that first -
6819 we are likely to read more than one register. If this is the
6820 first 'g' packet, we might be overly optimistic about its
6821 contents, so fall back to 'p'. */
6822 if (reg->in_g_packet)
6823 {
56be3814 6824 fetch_registers_using_g (regcache);
74ca34ce
DJ
6825 if (reg->in_g_packet)
6826 return;
6827 }
6828
56be3814 6829 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6830 return;
6831
6832 /* This register is not available. */
56be3814 6833 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6834
6835 return;
6836 }
6837
56be3814 6838 fetch_registers_using_g (regcache);
74ca34ce 6839
4a22f64d 6840 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6841 if (!rsa->regs[i].in_g_packet)
56be3814 6842 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6843 {
6844 /* This register is not available. */
56be3814 6845 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6846 }
6847}
6848
c906108c
SS
6849/* Prepare to store registers. Since we may send them all (using a
6850 'G' request), we have to read out the ones we don't want to change
6851 first. */
6852
c5aa993b 6853static void
f32dbf8c 6854remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6855{
ea9c271d 6856 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6857 int i;
cfd77fa1 6858 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6859
c906108c 6860 /* Make sure the entire registers array is valid. */
4082afcc 6861 switch (packet_support (PACKET_P))
5a2468f5
JM
6862 {
6863 case PACKET_DISABLE:
6864 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6865 /* Make sure all the necessary registers are cached. */
4a22f64d 6866 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6867 if (rsa->regs[i].in_g_packet)
316f2060 6868 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6869 break;
6870 case PACKET_ENABLE:
6871 break;
6872 }
6873}
6874
ad10f812 6875/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6876 packet was not recognized. */
5a2468f5
JM
6877
6878static int
1f4437a4
MS
6879store_register_using_P (const struct regcache *regcache,
6880 struct packet_reg *reg)
5a2468f5 6881{
4a22f64d 6882 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6883 struct remote_state *rs = get_remote_state ();
5a2468f5 6884 /* Try storing a single register. */
6d820c5c 6885 char *buf = rs->buf;
cfd77fa1 6886 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6887 char *p;
5a2468f5 6888
4082afcc 6889 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
6890 return 0;
6891
6892 if (reg->pnum == -1)
6893 return 0;
6894
ea9c271d 6895 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6896 p = buf + strlen (buf);
56be3814 6897 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6898 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6899 putpkt (rs->buf);
6900 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6901
74ca34ce
DJ
6902 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6903 {
6904 case PACKET_OK:
6905 return 1;
6906 case PACKET_ERROR:
27a9c0bf
MS
6907 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6908 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6909 case PACKET_UNKNOWN:
6910 return 0;
6911 default:
6912 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6913 }
c906108c
SS
6914}
6915
23860348
MS
6916/* Store register REGNUM, or all registers if REGNUM == -1, from the
6917 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6918
6919static void
56be3814 6920store_registers_using_G (const struct regcache *regcache)
c906108c 6921{
d01949b6 6922 struct remote_state *rs = get_remote_state ();
ea9c271d 6923 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6924 gdb_byte *regs;
c906108c
SS
6925 char *p;
6926
193cb69f
AC
6927 /* Extract all the registers in the regcache copying them into a
6928 local buffer. */
6929 {
b323314b 6930 int i;
a744cf53 6931
ea9c271d
DJ
6932 regs = alloca (rsa->sizeof_g_packet);
6933 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6934 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6935 {
ea9c271d 6936 struct packet_reg *r = &rsa->regs[i];
a744cf53 6937
b323314b 6938 if (r->in_g_packet)
56be3814 6939 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6940 }
6941 }
c906108c
SS
6942
6943 /* Command describes registers byte by byte,
6944 each byte encoded as two hex characters. */
6d820c5c 6945 p = rs->buf;
193cb69f 6946 *p++ = 'G';
74ca34ce
DJ
6947 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6948 updated. */
6949 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6950 putpkt (rs->buf);
6951 getpkt (&rs->buf, &rs->buf_size, 0);
6952 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6953 error (_("Could not write registers; remote failure reply '%s'"),
6954 rs->buf);
c906108c 6955}
74ca34ce
DJ
6956
6957/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6958 of the register cache buffer. FIXME: ignores errors. */
6959
6960static void
28439f5e
PA
6961remote_store_registers (struct target_ops *ops,
6962 struct regcache *regcache, int regnum)
74ca34ce 6963{
74ca34ce
DJ
6964 struct remote_arch_state *rsa = get_remote_arch_state ();
6965 int i;
6966
e6e4e701 6967 set_remote_traceframe ();
79d7f229 6968 set_general_thread (inferior_ptid);
74ca34ce
DJ
6969
6970 if (regnum >= 0)
6971 {
6972 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6973
74ca34ce
DJ
6974 gdb_assert (reg != NULL);
6975
6976 /* Always prefer to store registers using the 'P' packet if
6977 possible; we often change only a small number of registers.
6978 Sometimes we change a larger number; we'd need help from a
6979 higher layer to know to use 'G'. */
56be3814 6980 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6981 return;
6982
6983 /* For now, don't complain if we have no way to write the
6984 register. GDB loses track of unavailable registers too
6985 easily. Some day, this may be an error. We don't have
0df8b418 6986 any way to read the register, either... */
74ca34ce
DJ
6987 if (!reg->in_g_packet)
6988 return;
6989
56be3814 6990 store_registers_using_G (regcache);
74ca34ce
DJ
6991 return;
6992 }
6993
56be3814 6994 store_registers_using_G (regcache);
74ca34ce 6995
4a22f64d 6996 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6997 if (!rsa->regs[i].in_g_packet)
56be3814 6998 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6999 /* See above for why we do not issue an error here. */
7000 continue;
7001}
c906108c
SS
7002\f
7003
7004/* Return the number of hex digits in num. */
7005
7006static int
fba45db2 7007hexnumlen (ULONGEST num)
c906108c
SS
7008{
7009 int i;
7010
7011 for (i = 0; num != 0; i++)
7012 num >>= 4;
7013
7014 return max (i, 1);
7015}
7016
2df3850c 7017/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7018
7019static int
fba45db2 7020hexnumstr (char *buf, ULONGEST num)
c906108c 7021{
c906108c 7022 int len = hexnumlen (num);
a744cf53 7023
2df3850c
JM
7024 return hexnumnstr (buf, num, len);
7025}
7026
c906108c 7027
2df3850c 7028/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7029
2df3850c 7030static int
fba45db2 7031hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7032{
7033 int i;
7034
7035 buf[width] = '\0';
7036
7037 for (i = width - 1; i >= 0; i--)
c906108c 7038 {
c5aa993b 7039 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7040 num >>= 4;
7041 }
7042
2df3850c 7043 return width;
c906108c
SS
7044}
7045
23860348 7046/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7047
7048static CORE_ADDR
fba45db2 7049remote_address_masked (CORE_ADDR addr)
c906108c 7050{
883b9c6c 7051 unsigned int address_size = remote_address_size;
a744cf53 7052
911c95a5
UW
7053 /* If "remoteaddresssize" was not set, default to target address size. */
7054 if (!address_size)
f5656ead 7055 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7056
7057 if (address_size > 0
7058 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7059 {
7060 /* Only create a mask when that mask can safely be constructed
23860348 7061 in a ULONGEST variable. */
c906108c 7062 ULONGEST mask = 1;
a744cf53 7063
911c95a5 7064 mask = (mask << address_size) - 1;
c906108c
SS
7065 addr &= mask;
7066 }
7067 return addr;
7068}
7069
7070/* Determine whether the remote target supports binary downloading.
7071 This is accomplished by sending a no-op memory write of zero length
7072 to the target at the specified address. It does not suffice to send
23860348
MS
7073 the whole packet, since many stubs strip the eighth bit and
7074 subsequently compute a wrong checksum, which causes real havoc with
7075 remote_write_bytes.
7a292a7a 7076
96baa820 7077 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7078 clean. In cases like this, the user should clear "remote
23860348 7079 X-packet". */
96baa820 7080
c906108c 7081static void
fba45db2 7082check_binary_download (CORE_ADDR addr)
c906108c 7083{
d01949b6 7084 struct remote_state *rs = get_remote_state ();
24b06219 7085
4082afcc 7086 switch (packet_support (PACKET_X))
c906108c 7087 {
96baa820
JM
7088 case PACKET_DISABLE:
7089 break;
7090 case PACKET_ENABLE:
7091 break;
7092 case PACKET_SUPPORT_UNKNOWN:
7093 {
96baa820 7094 char *p;
802188a7 7095
2e9f7625 7096 p = rs->buf;
96baa820
JM
7097 *p++ = 'X';
7098 p += hexnumstr (p, (ULONGEST) addr);
7099 *p++ = ',';
7100 p += hexnumstr (p, (ULONGEST) 0);
7101 *p++ = ':';
7102 *p = '\0';
802188a7 7103
2e9f7625 7104 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7105 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7106
2e9f7625 7107 if (rs->buf[0] == '\0')
96baa820
JM
7108 {
7109 if (remote_debug)
7110 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7111 "binary downloading NOT "
7112 "supported by target\n");
444abaca 7113 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7114 }
7115 else
7116 {
7117 if (remote_debug)
7118 fprintf_unfiltered (gdb_stdlog,
64b9b334 7119 "binary downloading supported by target\n");
444abaca 7120 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7121 }
7122 break;
7123 }
c906108c
SS
7124 }
7125}
7126
124e13d9
SM
7127/* Helper function to resize the payload in order to try to get a good
7128 alignment. We try to write an amount of data such that the next write will
7129 start on an address aligned on REMOTE_ALIGN_WRITES. */
7130
7131static int
7132align_for_efficient_write (int todo, CORE_ADDR memaddr)
7133{
7134 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7135}
7136
c906108c
SS
7137/* Write memory data directly to the remote machine.
7138 This does not inform the data cache; the data cache uses this.
a76d924d 7139 HEADER is the starting part of the packet.
c906108c
SS
7140 MEMADDR is the address in the remote memory space.
7141 MYADDR is the address of the buffer in our space.
124e13d9
SM
7142 LEN_UNITS is the number of addressable units to write.
7143 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7144 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7145 should send data as binary ('X'), or hex-encoded ('M').
7146
7147 The function creates packet of the form
7148 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7149
124e13d9 7150 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7151
7152 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7153 are omitted.
7154
9b409511 7155 Return the transferred status, error or OK (an
124e13d9
SM
7156 'enum target_xfer_status' value). Save the number of addressable units
7157 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7158
7159 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7160 exchange between gdb and the stub could look like (?? in place of the
7161 checksum):
7162
7163 -> $m1000,4#??
7164 <- aaaabbbbccccdddd
7165
7166 -> $M1000,3:eeeeffffeeee#??
7167 <- OK
7168
7169 -> $m1000,4#??
7170 <- eeeeffffeeeedddd */
c906108c 7171
9b409511 7172static enum target_xfer_status
a76d924d 7173remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7174 const gdb_byte *myaddr, ULONGEST len_units,
7175 int unit_size, ULONGEST *xfered_len_units,
7176 char packet_format, int use_length)
c906108c 7177{
6d820c5c 7178 struct remote_state *rs = get_remote_state ();
cfd77fa1 7179 char *p;
a76d924d
DJ
7180 char *plen = NULL;
7181 int plenlen = 0;
124e13d9
SM
7182 int todo_units;
7183 int units_written;
7184 int payload_capacity_bytes;
7185 int payload_length_bytes;
a76d924d
DJ
7186
7187 if (packet_format != 'X' && packet_format != 'M')
7188 internal_error (__FILE__, __LINE__,
9b20d036 7189 _("remote_write_bytes_aux: bad packet format"));
c906108c 7190
124e13d9 7191 if (len_units == 0)
9b409511 7192 return TARGET_XFER_EOF;
b2182ed2 7193
124e13d9 7194 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7195
6d820c5c
DJ
7196 /* The packet buffer will be large enough for the payload;
7197 get_memory_packet_size ensures this. */
a76d924d 7198 rs->buf[0] = '\0';
c906108c 7199
a257b5bb 7200 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7201 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7202
124e13d9 7203 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7204 if (!use_length)
0df8b418 7205 /* The comma won't be used. */
124e13d9
SM
7206 payload_capacity_bytes += 1;
7207 payload_capacity_bytes -= strlen (header);
7208 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7209
a76d924d 7210 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7211
a76d924d
DJ
7212 strcat (rs->buf, header);
7213 p = rs->buf + strlen (header);
7214
7215 /* Compute a best guess of the number of bytes actually transfered. */
7216 if (packet_format == 'X')
c906108c 7217 {
23860348 7218 /* Best guess at number of bytes that will fit. */
124e13d9 7219 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7220 if (use_length)
124e13d9
SM
7221 payload_capacity_bytes -= hexnumlen (todo_units);
7222 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7223 }
7224 else
7225 {
124e13d9
SM
7226 /* Number of bytes that will fit. */
7227 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7228 if (use_length)
124e13d9
SM
7229 payload_capacity_bytes -= hexnumlen (todo_units);
7230 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7231 }
a76d924d 7232
124e13d9 7233 if (todo_units <= 0)
3de11b2e 7234 internal_error (__FILE__, __LINE__,
405f8e94 7235 _("minimum packet size too small to write data"));
802188a7 7236
6765f3e5
DJ
7237 /* If we already need another packet, then try to align the end
7238 of this packet to a useful boundary. */
124e13d9
SM
7239 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7240 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7241
a257b5bb 7242 /* Append "<memaddr>". */
917317f4
JM
7243 memaddr = remote_address_masked (memaddr);
7244 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7245
a76d924d
DJ
7246 if (use_length)
7247 {
7248 /* Append ",". */
7249 *p++ = ',';
802188a7 7250
124e13d9
SM
7251 /* Append the length and retain its location and size. It may need to be
7252 adjusted once the packet body has been created. */
a76d924d 7253 plen = p;
124e13d9 7254 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7255 p += plenlen;
7256 }
a257b5bb
AC
7257
7258 /* Append ":". */
917317f4
JM
7259 *p++ = ':';
7260 *p = '\0';
802188a7 7261
a257b5bb 7262 /* Append the packet body. */
a76d924d 7263 if (packet_format == 'X')
917317f4 7264 {
917317f4
JM
7265 /* Binary mode. Send target system values byte by byte, in
7266 increasing byte addresses. Only escape certain critical
7267 characters. */
124e13d9
SM
7268 payload_length_bytes =
7269 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7270 &units_written, payload_capacity_bytes);
6765f3e5 7271
124e13d9 7272 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7273 a second try to keep the end of the packet aligned. Don't do
7274 this if the packet is tiny. */
124e13d9 7275 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7276 {
124e13d9
SM
7277 int new_todo_units;
7278
7279 new_todo_units = align_for_efficient_write (units_written, memaddr);
7280
7281 if (new_todo_units != units_written)
7282 payload_length_bytes =
7283 remote_escape_output (myaddr, new_todo_units, unit_size,
7284 (gdb_byte *) p, &units_written,
7285 payload_capacity_bytes);
6765f3e5
DJ
7286 }
7287
124e13d9
SM
7288 p += payload_length_bytes;
7289 if (use_length && units_written < todo_units)
c906108c 7290 {
802188a7 7291 /* Escape chars have filled up the buffer prematurely,
124e13d9 7292 and we have actually sent fewer units than planned.
917317f4
JM
7293 Fix-up the length field of the packet. Use the same
7294 number of characters as before. */
124e13d9
SM
7295 plen += hexnumnstr (plen, (ULONGEST) units_written,
7296 plenlen);
917317f4 7297 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7298 }
a76d924d
DJ
7299 }
7300 else
7301 {
917317f4
JM
7302 /* Normal mode: Send target system values byte by byte, in
7303 increasing byte addresses. Each byte is encoded as a two hex
7304 value. */
124e13d9
SM
7305 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7306 units_written = todo_units;
c906108c 7307 }
802188a7 7308
2e9f7625 7309 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7310 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7311
2e9f7625 7312 if (rs->buf[0] == 'E')
00d84524 7313 return TARGET_XFER_E_IO;
802188a7 7314
124e13d9
SM
7315 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7316 send fewer units than we'd planned. */
7317 *xfered_len_units = (ULONGEST) units_written;
9b409511 7318 return TARGET_XFER_OK;
c906108c
SS
7319}
7320
a76d924d
DJ
7321/* Write memory data directly to the remote machine.
7322 This does not inform the data cache; the data cache uses this.
7323 MEMADDR is the address in the remote memory space.
7324 MYADDR is the address of the buffer in our space.
7325 LEN is the number of bytes.
7326
9b409511
YQ
7327 Return the transferred status, error or OK (an
7328 'enum target_xfer_status' value). Save the number of bytes
7329 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7330
9b409511
YQ
7331static enum target_xfer_status
7332remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7333 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7334{
7335 char *packet_format = 0;
7336
7337 /* Check whether the target supports binary download. */
7338 check_binary_download (memaddr);
7339
4082afcc 7340 switch (packet_support (PACKET_X))
a76d924d
DJ
7341 {
7342 case PACKET_ENABLE:
7343 packet_format = "X";
7344 break;
7345 case PACKET_DISABLE:
7346 packet_format = "M";
7347 break;
7348 case PACKET_SUPPORT_UNKNOWN:
7349 internal_error (__FILE__, __LINE__,
7350 _("remote_write_bytes: bad internal state"));
7351 default:
7352 internal_error (__FILE__, __LINE__, _("bad switch"));
7353 }
7354
7355 return remote_write_bytes_aux (packet_format,
124e13d9 7356 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7357 packet_format[0], 1);
a76d924d
DJ
7358}
7359
9217e74e
YQ
7360/* Read memory data directly from the remote machine.
7361 This does not use the data cache; the data cache uses this.
7362 MEMADDR is the address in the remote memory space.
7363 MYADDR is the address of the buffer in our space.
124e13d9
SM
7364 LEN_UNITS is the number of addressable memory units to read..
7365 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7366
7367 Return the transferred status, error or OK (an
7368 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7369 transferred in *XFERED_LEN_UNITS.
7370
7371 See the comment of remote_write_bytes_aux for an example of
7372 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7373
7374static enum target_xfer_status
124e13d9
SM
7375remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7376 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7377{
7378 struct remote_state *rs = get_remote_state ();
124e13d9 7379 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7380 char *p;
124e13d9
SM
7381 int todo_units;
7382 int decoded_bytes;
9217e74e 7383
124e13d9 7384 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7385 /* The packet buffer will be large enough for the payload;
7386 get_memory_packet_size ensures this. */
7387
124e13d9
SM
7388 /* Number of units that will fit. */
7389 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7390
7391 /* Construct "m"<memaddr>","<len>". */
7392 memaddr = remote_address_masked (memaddr);
7393 p = rs->buf;
7394 *p++ = 'm';
7395 p += hexnumstr (p, (ULONGEST) memaddr);
7396 *p++ = ',';
124e13d9 7397 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7398 *p = '\0';
7399 putpkt (rs->buf);
7400 getpkt (&rs->buf, &rs->buf_size, 0);
7401 if (rs->buf[0] == 'E'
7402 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7403 && rs->buf[3] == '\0')
7404 return TARGET_XFER_E_IO;
7405 /* Reply describes memory byte by byte, each byte encoded as two hex
7406 characters. */
7407 p = rs->buf;
124e13d9 7408 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7409 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7410 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7411 return TARGET_XFER_OK;
7412}
7413
b55fbac4
YQ
7414/* Using the set of read-only target sections of remote, read live
7415 read-only memory.
8acf9577
YQ
7416
7417 For interface/parameters/return description see target.h,
7418 to_xfer_partial. */
7419
7420static enum target_xfer_status
b55fbac4
YQ
7421remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7422 ULONGEST memaddr, ULONGEST len,
124e13d9 7423 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7424{
7425 struct target_section *secp;
7426 struct target_section_table *table;
7427
7428 secp = target_section_by_addr (ops, memaddr);
7429 if (secp != NULL
7430 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7431 secp->the_bfd_section)
7432 & SEC_READONLY))
7433 {
7434 struct target_section *p;
7435 ULONGEST memend = memaddr + len;
7436
7437 table = target_get_section_table (ops);
7438
7439 for (p = table->sections; p < table->sections_end; p++)
7440 {
7441 if (memaddr >= p->addr)
7442 {
7443 if (memend <= p->endaddr)
7444 {
7445 /* Entire transfer is within this section. */
124e13d9 7446 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7447 xfered_len);
8acf9577
YQ
7448 }
7449 else if (memaddr >= p->endaddr)
7450 {
7451 /* This section ends before the transfer starts. */
7452 continue;
7453 }
7454 else
7455 {
7456 /* This section overlaps the transfer. Just do half. */
7457 len = p->endaddr - memaddr;
124e13d9 7458 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7459 xfered_len);
8acf9577
YQ
7460 }
7461 }
7462 }
7463 }
7464
7465 return TARGET_XFER_EOF;
7466}
7467
9217e74e
YQ
7468/* Similar to remote_read_bytes_1, but it reads from the remote stub
7469 first if the requested memory is unavailable in traceframe.
7470 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7471
9b409511 7472static enum target_xfer_status
8acf9577 7473remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7474 gdb_byte *myaddr, ULONGEST len, int unit_size,
7475 ULONGEST *xfered_len)
c906108c 7476{
6b6aa828 7477 if (len == 0)
96c4f946 7478 return TARGET_XFER_EOF;
b2182ed2 7479
8acf9577
YQ
7480 if (get_traceframe_number () != -1)
7481 {
7482 VEC(mem_range_s) *available;
7483
7484 /* If we fail to get the set of available memory, then the
7485 target does not support querying traceframe info, and so we
7486 attempt reading from the traceframe anyway (assuming the
7487 target implements the old QTro packet then). */
7488 if (traceframe_available_memory (&available, memaddr, len))
7489 {
7490 struct cleanup *old_chain;
7491
7492 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7493
7494 if (VEC_empty (mem_range_s, available)
7495 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7496 {
7497 enum target_xfer_status res;
7498
7499 /* Don't read into the traceframe's available
7500 memory. */
7501 if (!VEC_empty (mem_range_s, available))
7502 {
7503 LONGEST oldlen = len;
7504
7505 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7506 gdb_assert (len <= oldlen);
7507 }
7508
7509 do_cleanups (old_chain);
7510
7511 /* This goes through the topmost target again. */
b55fbac4 7512 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7513 len, unit_size, xfered_len);
8acf9577
YQ
7514 if (res == TARGET_XFER_OK)
7515 return TARGET_XFER_OK;
7516 else
7517 {
7518 /* No use trying further, we know some memory starting
7519 at MEMADDR isn't available. */
7520 *xfered_len = len;
7521 return TARGET_XFER_UNAVAILABLE;
7522 }
7523 }
7524
7525 /* Don't try to read more than how much is available, in
7526 case the target implements the deprecated QTro packet to
7527 cater for older GDBs (the target's knowledge of read-only
7528 sections may be outdated by now). */
7529 len = VEC_index (mem_range_s, available, 0)->length;
7530
7531 do_cleanups (old_chain);
7532 }
7533 }
7534
124e13d9 7535 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7536}
74531fed 7537
c906108c 7538\f
c906108c 7539
a76d924d
DJ
7540/* Sends a packet with content determined by the printf format string
7541 FORMAT and the remaining arguments, then gets the reply. Returns
7542 whether the packet was a success, a failure, or unknown. */
7543
77b64a49
PA
7544static enum packet_result remote_send_printf (const char *format, ...)
7545 ATTRIBUTE_PRINTF (1, 2);
7546
2c0b251b 7547static enum packet_result
a76d924d
DJ
7548remote_send_printf (const char *format, ...)
7549{
7550 struct remote_state *rs = get_remote_state ();
7551 int max_size = get_remote_packet_size ();
a76d924d 7552 va_list ap;
a744cf53 7553
a76d924d
DJ
7554 va_start (ap, format);
7555
7556 rs->buf[0] = '\0';
7557 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7558 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7559
7560 if (putpkt (rs->buf) < 0)
7561 error (_("Communication problem with target."));
7562
7563 rs->buf[0] = '\0';
7564 getpkt (&rs->buf, &rs->buf_size, 0);
7565
7566 return packet_check_result (rs->buf);
7567}
7568
7569static void
7570restore_remote_timeout (void *p)
7571{
7572 int value = *(int *)p;
a744cf53 7573
a76d924d
DJ
7574 remote_timeout = value;
7575}
7576
7577/* Flash writing can take quite some time. We'll set
7578 effectively infinite timeout for flash operations.
7579 In future, we'll need to decide on a better approach. */
7580static const int remote_flash_timeout = 1000;
7581
7582static void
7583remote_flash_erase (struct target_ops *ops,
7584 ULONGEST address, LONGEST length)
7585{
f5656ead 7586 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7587 int saved_remote_timeout = remote_timeout;
7588 enum packet_result ret;
a76d924d
DJ
7589 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7590 &saved_remote_timeout);
a744cf53 7591
a76d924d
DJ
7592 remote_timeout = remote_flash_timeout;
7593
7594 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7595 phex (address, addr_size),
a76d924d
DJ
7596 phex (length, 4));
7597 switch (ret)
7598 {
7599 case PACKET_UNKNOWN:
7600 error (_("Remote target does not support flash erase"));
7601 case PACKET_ERROR:
7602 error (_("Error erasing flash with vFlashErase packet"));
7603 default:
7604 break;
7605 }
7606
7607 do_cleanups (back_to);
7608}
7609
9b409511
YQ
7610static enum target_xfer_status
7611remote_flash_write (struct target_ops *ops, ULONGEST address,
7612 ULONGEST length, ULONGEST *xfered_len,
7613 const gdb_byte *data)
a76d924d
DJ
7614{
7615 int saved_remote_timeout = remote_timeout;
9b409511 7616 enum target_xfer_status ret;
a76d924d 7617 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7618 &saved_remote_timeout);
a76d924d
DJ
7619
7620 remote_timeout = remote_flash_timeout;
124e13d9 7621 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 7622 xfered_len,'X', 0);
a76d924d
DJ
7623 do_cleanups (back_to);
7624
7625 return ret;
7626}
7627
7628static void
7629remote_flash_done (struct target_ops *ops)
7630{
7631 int saved_remote_timeout = remote_timeout;
7632 int ret;
7633 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7634 &saved_remote_timeout);
7635
7636 remote_timeout = remote_flash_timeout;
7637 ret = remote_send_printf ("vFlashDone");
7638 do_cleanups (back_to);
7639
7640 switch (ret)
7641 {
7642 case PACKET_UNKNOWN:
7643 error (_("Remote target does not support vFlashDone"));
7644 case PACKET_ERROR:
7645 error (_("Error finishing flash operation"));
7646 default:
7647 break;
7648 }
7649}
7650
c906108c 7651static void
fba45db2 7652remote_files_info (struct target_ops *ignore)
c906108c
SS
7653{
7654 puts_filtered ("Debugging a target over a serial line.\n");
7655}
7656\f
7657/* Stuff for dealing with the packets which are part of this protocol.
7658 See comment at top of file for details. */
7659
1927e618
PA
7660/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7661 error to higher layers. Called when a serial error is detected.
7662 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7663 the system error message for errno at function entry and final dot
7664 for output compatibility with throw_perror_with_name. */
1927e618
PA
7665
7666static void
7667unpush_and_perror (const char *string)
7668{
d6cb50a2 7669 int saved_errno = errno;
1927e618
PA
7670
7671 remote_unpush_target ();
d6cb50a2
JK
7672 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7673 safe_strerror (saved_errno));
1927e618
PA
7674}
7675
0876f84a 7676/* Read a single character from the remote end. */
c906108c
SS
7677
7678static int
fba45db2 7679readchar (int timeout)
c906108c
SS
7680{
7681 int ch;
5d93a237 7682 struct remote_state *rs = get_remote_state ();
c906108c 7683
5d93a237 7684 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7685
2acceee2 7686 if (ch >= 0)
0876f84a 7687 return ch;
2acceee2
JM
7688
7689 switch ((enum serial_rc) ch)
c906108c
SS
7690 {
7691 case SERIAL_EOF:
78a095c3 7692 remote_unpush_target ();
598d3636 7693 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7694 /* no return */
c906108c 7695 case SERIAL_ERROR:
1927e618
PA
7696 unpush_and_perror (_("Remote communication error. "
7697 "Target disconnected."));
2acceee2 7698 /* no return */
c906108c 7699 case SERIAL_TIMEOUT:
2acceee2 7700 break;
c906108c 7701 }
2acceee2 7702 return ch;
c906108c
SS
7703}
7704
c33e31fd
PA
7705/* Wrapper for serial_write that closes the target and throws if
7706 writing fails. */
7707
7708static void
7709remote_serial_write (const char *str, int len)
7710{
5d93a237
TT
7711 struct remote_state *rs = get_remote_state ();
7712
7713 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7714 {
1927e618
PA
7715 unpush_and_perror (_("Remote communication error. "
7716 "Target disconnected."));
c33e31fd
PA
7717 }
7718}
7719
6d820c5c
DJ
7720/* Send the command in *BUF to the remote machine, and read the reply
7721 into *BUF. Report an error if we get an error reply. Resize
7722 *BUF using xrealloc if necessary to hold the result, and update
7723 *SIZEOF_BUF. */
c906108c
SS
7724
7725static void
6d820c5c
DJ
7726remote_send (char **buf,
7727 long *sizeof_buf)
c906108c 7728{
6d820c5c 7729 putpkt (*buf);
c2d11a7d 7730 getpkt (buf, sizeof_buf, 0);
c906108c 7731
6d820c5c
DJ
7732 if ((*buf)[0] == 'E')
7733 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7734}
7735
6e5abd65
PA
7736/* Return a pointer to an xmalloc'ed string representing an escaped
7737 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7738 etc. The caller is responsible for releasing the returned
7739 memory. */
7740
7741static char *
7742escape_buffer (const char *buf, int n)
7743{
7744 struct cleanup *old_chain;
7745 struct ui_file *stb;
7746 char *str;
6e5abd65
PA
7747
7748 stb = mem_fileopen ();
7749 old_chain = make_cleanup_ui_file_delete (stb);
7750
6ef284bd 7751 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 7752 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7753 do_cleanups (old_chain);
7754 return str;
7755}
7756
c906108c
SS
7757/* Display a null-terminated packet on stdout, for debugging, using C
7758 string notation. */
7759
7760static void
baa336ce 7761print_packet (const char *buf)
c906108c
SS
7762{
7763 puts_filtered ("\"");
43e526b9 7764 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7765 puts_filtered ("\"");
7766}
7767
7768int
baa336ce 7769putpkt (const char *buf)
c906108c
SS
7770{
7771 return putpkt_binary (buf, strlen (buf));
7772}
7773
7774/* Send a packet to the remote machine, with error checking. The data
23860348 7775 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7776 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7777 and for a possible /0 if we are debugging (remote_debug) and want
7778 to print the sent packet as a string. */
c906108c
SS
7779
7780static int
baa336ce 7781putpkt_binary (const char *buf, int cnt)
c906108c 7782{
2d717e4f 7783 struct remote_state *rs = get_remote_state ();
c906108c
SS
7784 int i;
7785 unsigned char csum = 0;
11cf8741 7786 char *buf2 = alloca (cnt + 6);
085dd6e6 7787
c906108c
SS
7788 int ch;
7789 int tcount = 0;
7790 char *p;
dd61ec5c 7791 char *message;
c906108c 7792
e24a49d8
PA
7793 /* Catch cases like trying to read memory or listing threads while
7794 we're waiting for a stop reply. The remote server wouldn't be
7795 ready to handle this request, so we'd hang and timeout. We don't
7796 have to worry about this in synchronous mode, because in that
7797 case it's not possible to issue a command while the target is
74531fed
PA
7798 running. This is not a problem in non-stop mode, because in that
7799 case, the stub is always ready to process serial input. */
d9d41e78 7800 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
9597b22a
DE
7801 {
7802 error (_("Cannot execute this command while the target is running.\n"
7803 "Use the \"interrupt\" command to stop the target\n"
7804 "and then try again."));
7805 }
e24a49d8 7806
2d717e4f
DJ
7807 /* We're sending out a new packet. Make sure we don't look at a
7808 stale cached response. */
7809 rs->cached_wait_status = 0;
7810
c906108c
SS
7811 /* Copy the packet into buffer BUF2, encapsulating it
7812 and giving it a checksum. */
7813
c906108c
SS
7814 p = buf2;
7815 *p++ = '$';
7816
7817 for (i = 0; i < cnt; i++)
7818 {
7819 csum += buf[i];
7820 *p++ = buf[i];
7821 }
7822 *p++ = '#';
7823 *p++ = tohex ((csum >> 4) & 0xf);
7824 *p++ = tohex (csum & 0xf);
7825
7826 /* Send it over and over until we get a positive ack. */
7827
7828 while (1)
7829 {
7830 int started_error_output = 0;
7831
7832 if (remote_debug)
7833 {
6e5abd65
PA
7834 struct cleanup *old_chain;
7835 char *str;
7836
c906108c 7837 *p = '\0';
6e5abd65
PA
7838 str = escape_buffer (buf2, p - buf2);
7839 old_chain = make_cleanup (xfree, str);
7840 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7841 gdb_flush (gdb_stdlog);
6e5abd65 7842 do_cleanups (old_chain);
c906108c 7843 }
c33e31fd 7844 remote_serial_write (buf2, p - buf2);
c906108c 7845
a6f3e723
SL
7846 /* If this is a no acks version of the remote protocol, send the
7847 packet and move on. */
7848 if (rs->noack_mode)
7849 break;
7850
74531fed
PA
7851 /* Read until either a timeout occurs (-2) or '+' is read.
7852 Handle any notification that arrives in the mean time. */
c906108c
SS
7853 while (1)
7854 {
7855 ch = readchar (remote_timeout);
7856
c5aa993b 7857 if (remote_debug)
c906108c
SS
7858 {
7859 switch (ch)
7860 {
7861 case '+':
1216fa2c 7862 case '-':
c906108c
SS
7863 case SERIAL_TIMEOUT:
7864 case '$':
74531fed 7865 case '%':
c906108c
SS
7866 if (started_error_output)
7867 {
7868 putchar_unfiltered ('\n');
7869 started_error_output = 0;
7870 }
7871 }
7872 }
7873
7874 switch (ch)
7875 {
7876 case '+':
7877 if (remote_debug)
0f71a2f6 7878 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7879 return 1;
1216fa2c
AC
7880 case '-':
7881 if (remote_debug)
7882 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7883 /* FALLTHROUGH */
c906108c 7884 case SERIAL_TIMEOUT:
c5aa993b 7885 tcount++;
c906108c
SS
7886 if (tcount > 3)
7887 return 0;
23860348 7888 break; /* Retransmit buffer. */
c906108c
SS
7889 case '$':
7890 {
40e3f985 7891 if (remote_debug)
2bc416ba 7892 fprintf_unfiltered (gdb_stdlog,
23860348 7893 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7894 /* It's probably an old response sent because an ACK
7895 was lost. Gobble up the packet and ack it so it
7896 doesn't get retransmitted when we resend this
7897 packet. */
6d820c5c 7898 skip_frame ();
c33e31fd 7899 remote_serial_write ("+", 1);
23860348 7900 continue; /* Now, go look for +. */
c906108c 7901 }
74531fed
PA
7902
7903 case '%':
7904 {
7905 int val;
7906
7907 /* If we got a notification, handle it, and go back to looking
7908 for an ack. */
7909 /* We've found the start of a notification. Now
7910 collect the data. */
7911 val = read_frame (&rs->buf, &rs->buf_size);
7912 if (val >= 0)
7913 {
7914 if (remote_debug)
7915 {
6e5abd65
PA
7916 struct cleanup *old_chain;
7917 char *str;
7918
7919 str = escape_buffer (rs->buf, val);
7920 old_chain = make_cleanup (xfree, str);
7921 fprintf_unfiltered (gdb_stdlog,
7922 " Notification received: %s\n",
7923 str);
7924 do_cleanups (old_chain);
74531fed 7925 }
5965e028 7926 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7927 /* We're in sync now, rewait for the ack. */
7928 tcount = 0;
7929 }
7930 else
7931 {
7932 if (remote_debug)
7933 {
7934 if (!started_error_output)
7935 {
7936 started_error_output = 1;
7937 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7938 }
7939 fputc_unfiltered (ch & 0177, gdb_stdlog);
7940 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7941 }
7942 }
7943 continue;
7944 }
7945 /* fall-through */
c906108c
SS
7946 default:
7947 if (remote_debug)
7948 {
7949 if (!started_error_output)
7950 {
7951 started_error_output = 1;
0f71a2f6 7952 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7953 }
0f71a2f6 7954 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7955 }
7956 continue;
7957 }
23860348 7958 break; /* Here to retransmit. */
c906108c
SS
7959 }
7960
7961#if 0
7962 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7963 able to get out next time we call QUIT, without anything as
7964 violent as interrupt_query. If we want to provide a way out of
7965 here without getting to the next QUIT, it should be based on
7966 hitting ^C twice as in remote_wait. */
c906108c
SS
7967 if (quit_flag)
7968 {
7969 quit_flag = 0;
7970 interrupt_query ();
7971 }
7972#endif
7973 }
a6f3e723 7974 return 0;
c906108c
SS
7975}
7976
6d820c5c
DJ
7977/* Come here after finding the start of a frame when we expected an
7978 ack. Do our best to discard the rest of this packet. */
7979
7980static void
7981skip_frame (void)
7982{
7983 int c;
7984
7985 while (1)
7986 {
7987 c = readchar (remote_timeout);
7988 switch (c)
7989 {
7990 case SERIAL_TIMEOUT:
7991 /* Nothing we can do. */
7992 return;
7993 case '#':
7994 /* Discard the two bytes of checksum and stop. */
7995 c = readchar (remote_timeout);
7996 if (c >= 0)
7997 c = readchar (remote_timeout);
7998
7999 return;
8000 case '*': /* Run length encoding. */
8001 /* Discard the repeat count. */
8002 c = readchar (remote_timeout);
8003 if (c < 0)
8004 return;
8005 break;
8006 default:
8007 /* A regular character. */
8008 break;
8009 }
8010 }
8011}
8012
c906108c 8013/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8014 into *BUF, verifying the checksum, length, and handling run-length
8015 compression. NUL terminate the buffer. If there is not enough room,
8016 expand *BUF using xrealloc.
c906108c 8017
c2d11a7d
JM
8018 Returns -1 on error, number of characters in buffer (ignoring the
8019 trailing NULL) on success. (could be extended to return one of the
23860348 8020 SERIAL status indications). */
c2d11a7d
JM
8021
8022static long
6d820c5c
DJ
8023read_frame (char **buf_p,
8024 long *sizeof_buf)
c906108c
SS
8025{
8026 unsigned char csum;
c2d11a7d 8027 long bc;
c906108c 8028 int c;
6d820c5c 8029 char *buf = *buf_p;
a6f3e723 8030 struct remote_state *rs = get_remote_state ();
c906108c
SS
8031
8032 csum = 0;
c2d11a7d 8033 bc = 0;
c906108c
SS
8034
8035 while (1)
8036 {
8037 c = readchar (remote_timeout);
c906108c
SS
8038 switch (c)
8039 {
8040 case SERIAL_TIMEOUT:
8041 if (remote_debug)
0f71a2f6 8042 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8043 return -1;
c906108c
SS
8044 case '$':
8045 if (remote_debug)
0f71a2f6
JM
8046 fputs_filtered ("Saw new packet start in middle of old one\n",
8047 gdb_stdlog);
23860348 8048 return -1; /* Start a new packet, count retries. */
c906108c
SS
8049 case '#':
8050 {
8051 unsigned char pktcsum;
e1b09194
AC
8052 int check_0 = 0;
8053 int check_1 = 0;
c906108c 8054
c2d11a7d 8055 buf[bc] = '\0';
c906108c 8056
e1b09194
AC
8057 check_0 = readchar (remote_timeout);
8058 if (check_0 >= 0)
8059 check_1 = readchar (remote_timeout);
802188a7 8060
e1b09194
AC
8061 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8062 {
8063 if (remote_debug)
2bc416ba 8064 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8065 gdb_stdlog);
e1b09194
AC
8066 return -1;
8067 }
8068 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8069 {
8070 if (remote_debug)
2bc416ba 8071 fputs_filtered ("Communication error in checksum\n",
23860348 8072 gdb_stdlog);
40e3f985
FN
8073 return -1;
8074 }
c906108c 8075
a6f3e723
SL
8076 /* Don't recompute the checksum; with no ack packets we
8077 don't have any way to indicate a packet retransmission
8078 is necessary. */
8079 if (rs->noack_mode)
8080 return bc;
8081
e1b09194 8082 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8083 if (csum == pktcsum)
c2d11a7d 8084 return bc;
c906108c 8085
c5aa993b 8086 if (remote_debug)
c906108c 8087 {
6e5abd65
PA
8088 struct cleanup *old_chain;
8089 char *str;
8090
8091 str = escape_buffer (buf, bc);
8092 old_chain = make_cleanup (xfree, str);
8093 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8094 "Bad checksum, sentsum=0x%x, "
8095 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8096 pktcsum, csum, str);
8097 do_cleanups (old_chain);
c906108c 8098 }
c2d11a7d 8099 /* Number of characters in buffer ignoring trailing
23860348 8100 NULL. */
c2d11a7d 8101 return -1;
c906108c 8102 }
23860348 8103 case '*': /* Run length encoding. */
c2c6d25f
JM
8104 {
8105 int repeat;
c906108c 8106
a744cf53 8107 csum += c;
b4501125
AC
8108 c = readchar (remote_timeout);
8109 csum += c;
23860348 8110 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8111
23860348 8112 /* The character before ``*'' is repeated. */
c2d11a7d 8113
6d820c5c 8114 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8115 {
6d820c5c
DJ
8116 if (bc + repeat - 1 >= *sizeof_buf - 1)
8117 {
8118 /* Make some more room in the buffer. */
8119 *sizeof_buf += repeat;
8120 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8121 buf = *buf_p;
8122 }
8123
c2d11a7d
JM
8124 memset (&buf[bc], buf[bc - 1], repeat);
8125 bc += repeat;
c2c6d25f
JM
8126 continue;
8127 }
8128
c2d11a7d 8129 buf[bc] = '\0';
6d820c5c 8130 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8131 return -1;
c2c6d25f 8132 }
c906108c 8133 default:
6d820c5c 8134 if (bc >= *sizeof_buf - 1)
c906108c 8135 {
6d820c5c
DJ
8136 /* Make some more room in the buffer. */
8137 *sizeof_buf *= 2;
8138 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8139 buf = *buf_p;
c906108c
SS
8140 }
8141
6d820c5c
DJ
8142 buf[bc++] = c;
8143 csum += c;
8144 continue;
c906108c
SS
8145 }
8146 }
8147}
8148
8149/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8150 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8151 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8152 rather than timing out; this is used (in synchronous mode) to wait
8153 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8154/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8155 don't have to change all the calls to getpkt to deal with the
8156 return value, because at the moment I don't know what the right
23860348 8157 thing to do it for those. */
c906108c 8158void
6d820c5c
DJ
8159getpkt (char **buf,
8160 long *sizeof_buf,
c2d11a7d 8161 int forever)
d9fcf2fb
JM
8162{
8163 int timed_out;
8164
8165 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8166}
8167
8168
8169/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8170 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8171 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8172 rather than timing out; this is used (in synchronous mode) to wait
8173 for a target that is is executing user code to stop. If FOREVER ==
8174 0, this function is allowed to time out gracefully and return an
74531fed
PA
8175 indication of this to the caller. Otherwise return the number of
8176 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8177 enough reason to return to the caller. *IS_NOTIF is an output
8178 boolean that indicates whether *BUF holds a notification or not
8179 (a regular packet). */
74531fed 8180
3172dc30 8181static int
74531fed 8182getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8183 int expecting_notif, int *is_notif)
c906108c 8184{
2d717e4f 8185 struct remote_state *rs = get_remote_state ();
c906108c
SS
8186 int c;
8187 int tries;
8188 int timeout;
df4b58fe 8189 int val = -1;
c906108c 8190
2d717e4f
DJ
8191 /* We're reading a new response. Make sure we don't look at a
8192 previously cached response. */
8193 rs->cached_wait_status = 0;
8194
6d820c5c 8195 strcpy (*buf, "timeout");
c906108c
SS
8196
8197 if (forever)
74531fed
PA
8198 timeout = watchdog > 0 ? watchdog : -1;
8199 else if (expecting_notif)
8200 timeout = 0; /* There should already be a char in the buffer. If
8201 not, bail out. */
c906108c
SS
8202 else
8203 timeout = remote_timeout;
8204
8205#define MAX_TRIES 3
8206
74531fed
PA
8207 /* Process any number of notifications, and then return when
8208 we get a packet. */
8209 for (;;)
c906108c 8210 {
d9c43928 8211 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8212 times. */
8213 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8214 {
74531fed
PA
8215 /* This can loop forever if the remote side sends us
8216 characters continuously, but if it pauses, we'll get
8217 SERIAL_TIMEOUT from readchar because of timeout. Then
8218 we'll count that as a retry.
8219
8220 Note that even when forever is set, we will only wait
8221 forever prior to the start of a packet. After that, we
8222 expect characters to arrive at a brisk pace. They should
8223 show up within remote_timeout intervals. */
8224 do
8225 c = readchar (timeout);
8226 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8227
8228 if (c == SERIAL_TIMEOUT)
8229 {
74531fed
PA
8230 if (expecting_notif)
8231 return -1; /* Don't complain, it's normal to not get
8232 anything in this case. */
8233
23860348 8234 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8235 {
2acceee2 8236 QUIT;
78a095c3 8237 remote_unpush_target ();
598d3636
JK
8238 throw_error (TARGET_CLOSE_ERROR,
8239 _("Watchdog timeout has expired. "
8240 "Target detached."));
c906108c 8241 }
c906108c 8242 if (remote_debug)
0f71a2f6 8243 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8244 }
74531fed
PA
8245 else
8246 {
8247 /* We've found the start of a packet or notification.
8248 Now collect the data. */
8249 val = read_frame (buf, sizeof_buf);
8250 if (val >= 0)
8251 break;
8252 }
8253
c33e31fd 8254 remote_serial_write ("-", 1);
c906108c 8255 }
c906108c 8256
74531fed
PA
8257 if (tries > MAX_TRIES)
8258 {
8259 /* We have tried hard enough, and just can't receive the
8260 packet/notification. Give up. */
8261 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8262
74531fed
PA
8263 /* Skip the ack char if we're in no-ack mode. */
8264 if (!rs->noack_mode)
c33e31fd 8265 remote_serial_write ("+", 1);
74531fed
PA
8266 return -1;
8267 }
c906108c 8268
74531fed
PA
8269 /* If we got an ordinary packet, return that to our caller. */
8270 if (c == '$')
c906108c
SS
8271 {
8272 if (remote_debug)
43e526b9 8273 {
6e5abd65
PA
8274 struct cleanup *old_chain;
8275 char *str;
8276
8277 str = escape_buffer (*buf, val);
8278 old_chain = make_cleanup (xfree, str);
8279 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8280 do_cleanups (old_chain);
43e526b9 8281 }
a6f3e723
SL
8282
8283 /* Skip the ack char if we're in no-ack mode. */
8284 if (!rs->noack_mode)
c33e31fd 8285 remote_serial_write ("+", 1);
fee9eda9
YQ
8286 if (is_notif != NULL)
8287 *is_notif = 0;
0876f84a 8288 return val;
c906108c
SS
8289 }
8290
74531fed
PA
8291 /* If we got a notification, handle it, and go back to looking
8292 for a packet. */
8293 else
8294 {
8295 gdb_assert (c == '%');
8296
8297 if (remote_debug)
8298 {
6e5abd65
PA
8299 struct cleanup *old_chain;
8300 char *str;
8301
8302 str = escape_buffer (*buf, val);
8303 old_chain = make_cleanup (xfree, str);
8304 fprintf_unfiltered (gdb_stdlog,
8305 " Notification received: %s\n",
8306 str);
8307 do_cleanups (old_chain);
74531fed 8308 }
fee9eda9
YQ
8309 if (is_notif != NULL)
8310 *is_notif = 1;
c906108c 8311
5965e028 8312 handle_notification (rs->notif_state, *buf);
c906108c 8313
74531fed 8314 /* Notifications require no acknowledgement. */
a6f3e723 8315
74531fed 8316 if (expecting_notif)
fee9eda9 8317 return val;
74531fed
PA
8318 }
8319 }
8320}
8321
8322static int
8323getpkt_sane (char **buf, long *sizeof_buf, int forever)
8324{
fee9eda9 8325 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8326}
8327
8328static int
fee9eda9
YQ
8329getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8330 int *is_notif)
74531fed 8331{
fee9eda9
YQ
8332 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8333 is_notif);
c906108c 8334}
74531fed 8335
cbb8991c
DB
8336/* Check whether EVENT is a fork event for the process specified
8337 by the pid passed in DATA, and if it is, kill the fork child. */
8338
8339static int
8340kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8341 QUEUE_ITER (stop_reply_p) *iter,
8342 stop_reply_p event,
8343 void *data)
8344{
8345 struct queue_iter_param *param = data;
8346 int parent_pid = *(int *) param->input;
8347
8348 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8349 {
8350 struct remote_state *rs = get_remote_state ();
8351 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8352 int res;
8353
8354 res = remote_vkill (child_pid, rs);
8355 if (res != 0)
8356 error (_("Can't kill fork child process %d"), child_pid);
8357 }
8358
8359 return 1;
8360}
8361
8362/* Kill any new fork children of process PID that haven't been
8363 processed by follow_fork. */
8364
8365static void
8366kill_new_fork_children (int pid, struct remote_state *rs)
8367{
8368 struct thread_info *thread;
8369 struct notif_client *notif = &notif_client_stop;
8370 struct queue_iter_param param;
8371
8372 /* Kill the fork child threads of any threads in process PID
8373 that are stopped at a fork event. */
8374 ALL_NON_EXITED_THREADS (thread)
8375 {
8376 struct target_waitstatus *ws = &thread->pending_follow;
8377
8378 if (is_pending_fork_parent (ws, pid, thread->ptid))
8379 {
8380 struct remote_state *rs = get_remote_state ();
8381 int child_pid = ptid_get_pid (ws->value.related_pid);
8382 int res;
8383
8384 res = remote_vkill (child_pid, rs);
8385 if (res != 0)
8386 error (_("Can't kill fork child process %d"), child_pid);
8387 }
8388 }
8389
8390 /* Check for any pending fork events (not reported or processed yet)
8391 in process PID and kill those fork child threads as well. */
8392 remote_notif_get_pending_events (notif);
8393 param.input = &pid;
8394 param.output = NULL;
8395 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8396 kill_child_of_pending_fork, &param);
8397}
8398
c906108c
SS
8399\f
8400static void
7d85a9c0 8401remote_kill (struct target_ops *ops)
43ff13b4 8402{
0fdf84ca
PA
8403
8404 /* Catch errors so the user can quit from gdb even when we
23860348 8405 aren't on speaking terms with the remote system. */
492d29ea 8406 TRY
0fdf84ca
PA
8407 {
8408 putpkt ("k");
8409 }
492d29ea 8410 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
8411 {
8412 if (ex.error == TARGET_CLOSE_ERROR)
8413 {
8414 /* If we got an (EOF) error that caused the target
8415 to go away, then we're done, that's what we wanted.
8416 "k" is susceptible to cause a premature EOF, given
8417 that the remote server isn't actually required to
8418 reply to "k", and it can happen that it doesn't
8419 even get to reply ACK to the "k". */
8420 return;
8421 }
8422
8423 /* Otherwise, something went wrong. We didn't actually kill
8424 the target. Just propagate the exception, and let the
8425 user or higher layers decide what to do. */
8426 throw_exception (ex);
8427 }
492d29ea 8428 END_CATCH
43ff13b4 8429
0fdf84ca
PA
8430 /* We've killed the remote end, we get to mourn it. Since this is
8431 target remote, single-process, mourning the inferior also
8432 unpushes remote_ops. */
43ff13b4
JM
8433 target_mourn_inferior ();
8434}
8435
82f73884
PA
8436static int
8437remote_vkill (int pid, struct remote_state *rs)
8438{
4082afcc 8439 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8440 return -1;
8441
8442 /* Tell the remote target to detach. */
bba74b36 8443 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8444 putpkt (rs->buf);
8445 getpkt (&rs->buf, &rs->buf_size, 0);
8446
4082afcc
PA
8447 switch (packet_ok (rs->buf,
8448 &remote_protocol_packets[PACKET_vKill]))
8449 {
8450 case PACKET_OK:
8451 return 0;
8452 case PACKET_ERROR:
8453 return 1;
8454 case PACKET_UNKNOWN:
8455 return -1;
8456 default:
8457 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8458 }
82f73884
PA
8459}
8460
8461static void
7d85a9c0 8462extended_remote_kill (struct target_ops *ops)
82f73884
PA
8463{
8464 int res;
8465 int pid = ptid_get_pid (inferior_ptid);
8466 struct remote_state *rs = get_remote_state ();
8467
cbb8991c
DB
8468 /* If we're stopped while forking and we haven't followed yet, kill the
8469 child task. We need to do this before killing the parent task
8470 because if this is a vfork then the parent will be sleeping. */
8471 kill_new_fork_children (pid, rs);
8472
82f73884 8473 res = remote_vkill (pid, rs);
901f9912 8474 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
8475 {
8476 /* Don't try 'k' on a multi-process aware stub -- it has no way
8477 to specify the pid. */
8478
8479 putpkt ("k");
8480#if 0
8481 getpkt (&rs->buf, &rs->buf_size, 0);
8482 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8483 res = 1;
8484#else
8485 /* Don't wait for it to die. I'm not really sure it matters whether
8486 we do or not. For the existing stubs, kill is a noop. */
8487 res = 0;
8488#endif
8489 }
8490
8491 if (res != 0)
8492 error (_("Can't kill process"));
8493
82f73884
PA
8494 target_mourn_inferior ();
8495}
8496
c906108c 8497static void
20f796c9 8498remote_mourn (struct target_ops *target)
c906108c
SS
8499{
8500 unpush_target (target);
ce5ce7ed 8501
8a2492ee
PA
8502 /* remote_close takes care of doing most of the clean up. */
8503 generic_mourn_inferior ();
c906108c
SS
8504}
8505
2d717e4f 8506static void
20f796c9 8507extended_remote_mourn (struct target_ops *target)
2d717e4f
DJ
8508{
8509 struct remote_state *rs = get_remote_state ();
c906108c 8510
e24a49d8
PA
8511 /* In case we got here due to an error, but we're going to stay
8512 connected. */
8513 rs->waiting_for_stop_reply = 0;
8514
dc1981d7
PA
8515 /* If the current general thread belonged to the process we just
8516 detached from or has exited, the remote side current general
8517 thread becomes undefined. Considering a case like this:
8518
8519 - We just got here due to a detach.
8520 - The process that we're detaching from happens to immediately
8521 report a global breakpoint being hit in non-stop mode, in the
8522 same thread we had selected before.
8523 - GDB attaches to this process again.
8524 - This event happens to be the next event we handle.
8525
8526 GDB would consider that the current general thread didn't need to
8527 be set on the stub side (with Hg), since for all it knew,
8528 GENERAL_THREAD hadn't changed.
8529
8530 Notice that although in all-stop mode, the remote server always
8531 sets the current thread to the thread reporting the stop event,
8532 that doesn't happen in non-stop mode; in non-stop, the stub *must
8533 not* change the current thread when reporting a breakpoint hit,
8534 due to the decoupling of event reporting and event handling.
8535
8536 To keep things simple, we always invalidate our notion of the
8537 current thread. */
47f8a51d 8538 record_currthread (rs, minus_one_ptid);
dc1981d7 8539
2d717e4f
DJ
8540 /* Unlike "target remote", we do not want to unpush the target; then
8541 the next time the user says "run", we won't be connected. */
8542
48aa3c27
PA
8543 /* Call common code to mark the inferior as not running. */
8544 generic_mourn_inferior ();
8545
d729566a 8546 if (!have_inferiors ())
2d717e4f 8547 {
82f73884
PA
8548 if (!remote_multi_process_p (rs))
8549 {
8550 /* Check whether the target is running now - some remote stubs
8551 automatically restart after kill. */
8552 putpkt ("?");
8553 getpkt (&rs->buf, &rs->buf_size, 0);
8554
8555 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8556 {
3e43a32a
MS
8557 /* Assume that the target has been restarted. Set
8558 inferior_ptid so that bits of core GDB realizes
8559 there's something here, e.g., so that the user can
8560 say "kill" again. */
82f73884
PA
8561 inferior_ptid = magic_null_ptid;
8562 }
82f73884 8563 }
2d717e4f
DJ
8564 }
8565}
c906108c 8566
03583c20 8567static int
2bfc0540 8568extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8569{
4082afcc 8570 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8571}
8572
8573static void
8574extended_remote_disable_randomization (int val)
8575{
8576 struct remote_state *rs = get_remote_state ();
8577 char *reply;
8578
bba74b36
YQ
8579 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8580 val);
03583c20
UW
8581 putpkt (rs->buf);
8582 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8583 if (*reply == '\0')
8584 error (_("Target does not support QDisableRandomization."));
8585 if (strcmp (reply, "OK") != 0)
8586 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8587}
8588
2d717e4f
DJ
8589static int
8590extended_remote_run (char *args)
8591{
8592 struct remote_state *rs = get_remote_state ();
2d717e4f 8593 int len;
c906108c 8594
2d717e4f
DJ
8595 /* If the user has disabled vRun support, or we have detected that
8596 support is not available, do not try it. */
4082afcc 8597 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8598 return -1;
424163ea 8599
2d717e4f
DJ
8600 strcpy (rs->buf, "vRun;");
8601 len = strlen (rs->buf);
c906108c 8602
2d717e4f
DJ
8603 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8604 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8605 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8606 strlen (remote_exec_file));
2d717e4f 8607
d1a41061 8608 gdb_assert (args != NULL);
2d717e4f
DJ
8609 if (*args)
8610 {
8611 struct cleanup *back_to;
8612 int i;
8613 char **argv;
8614
d1a41061 8615 argv = gdb_buildargv (args);
6e366df1 8616 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
8617 for (i = 0; argv[i] != NULL; i++)
8618 {
8619 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8620 error (_("Argument list too long for run packet"));
8621 rs->buf[len++] = ';';
9f1b45b0
TT
8622 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8623 strlen (argv[i]));
2d717e4f
DJ
8624 }
8625 do_cleanups (back_to);
8626 }
8627
8628 rs->buf[len++] = '\0';
8629
8630 putpkt (rs->buf);
8631 getpkt (&rs->buf, &rs->buf_size, 0);
8632
4082afcc 8633 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 8634 {
4082afcc 8635 case PACKET_OK:
3405876a 8636 /* We have a wait response. All is well. */
2d717e4f 8637 return 0;
4082afcc
PA
8638 case PACKET_UNKNOWN:
8639 return -1;
8640 case PACKET_ERROR:
2d717e4f
DJ
8641 if (remote_exec_file[0] == '\0')
8642 error (_("Running the default executable on the remote target failed; "
8643 "try \"set remote exec-file\"?"));
8644 else
8645 error (_("Running \"%s\" on the remote target failed"),
8646 remote_exec_file);
4082afcc
PA
8647 default:
8648 gdb_assert_not_reached (_("bad switch"));
2d717e4f 8649 }
c906108c
SS
8650}
8651
2d717e4f
DJ
8652/* In the extended protocol we want to be able to do things like
8653 "run" and have them basically work as expected. So we need
8654 a special create_inferior function. We support changing the
8655 executable file and the command line arguments, but not the
8656 environment. */
8657
43ff13b4 8658static void
77a19445
TT
8659extended_remote_create_inferior (struct target_ops *ops,
8660 char *exec_file, char *args,
8661 char **env, int from_tty)
43ff13b4 8662{
3405876a
PA
8663 int run_worked;
8664 char *stop_reply;
8665 struct remote_state *rs = get_remote_state ();
8666
43ff13b4 8667 /* If running asynchronously, register the target file descriptor
23860348 8668 with the event loop. */
75c99385 8669 if (target_can_async_p ())
6a3753b3 8670 target_async (1);
43ff13b4 8671
03583c20 8672 /* Disable address space randomization if requested (and supported). */
2bfc0540 8673 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
8674 extended_remote_disable_randomization (disable_randomization);
8675
43ff13b4 8676 /* Now restart the remote server. */
3405876a
PA
8677 run_worked = extended_remote_run (args) != -1;
8678 if (!run_worked)
2d717e4f
DJ
8679 {
8680 /* vRun was not supported. Fail if we need it to do what the
8681 user requested. */
8682 if (remote_exec_file[0])
8683 error (_("Remote target does not support \"set remote exec-file\""));
8684 if (args[0])
8685 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 8686
2d717e4f
DJ
8687 /* Fall back to "R". */
8688 extended_remote_restart ();
8689 }
424163ea 8690
6c95b8df
PA
8691 if (!have_inferiors ())
8692 {
8693 /* Clean up from the last time we ran, before we mark the target
8694 running again. This will mark breakpoints uninserted, and
8695 get_offsets may insert breakpoints. */
8696 init_thread_list ();
8697 init_wait_for_inferior ();
8698 }
45280a52 8699
3405876a
PA
8700 /* vRun's success return is a stop reply. */
8701 stop_reply = run_worked ? rs->buf : NULL;
8702 add_current_inferior_and_thread (stop_reply);
c0a2216e 8703
2d717e4f
DJ
8704 /* Get updated offsets, if the stub uses qOffsets. */
8705 get_offsets ();
2d717e4f 8706}
c906108c 8707\f
c5aa993b 8708
b775012e
LM
8709/* Given a location's target info BP_TGT and the packet buffer BUF, output
8710 the list of conditions (in agent expression bytecode format), if any, the
8711 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8712 started from BUF and ended at BUF_END. */
b775012e
LM
8713
8714static int
8715remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8716 struct bp_target_info *bp_tgt, char *buf,
8717 char *buf_end)
b775012e
LM
8718{
8719 struct agent_expr *aexpr = NULL;
8720 int i, ix;
8721 char *pkt;
8722 char *buf_start = buf;
8723
8724 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8725 return 0;
8726
8727 buf += strlen (buf);
bba74b36 8728 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8729 buf++;
8730
8731 /* Send conditions to the target and free the vector. */
8732 for (ix = 0;
8733 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8734 ix++)
8735 {
bba74b36 8736 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8737 buf += strlen (buf);
8738 for (i = 0; i < aexpr->len; ++i)
8739 buf = pack_hex_byte (buf, aexpr->buf[i]);
8740 *buf = '\0';
8741 }
b775012e
LM
8742 return 0;
8743}
8744
d3ce09f5
SS
8745static void
8746remote_add_target_side_commands (struct gdbarch *gdbarch,
8747 struct bp_target_info *bp_tgt, char *buf)
8748{
8749 struct agent_expr *aexpr = NULL;
8750 int i, ix;
8751
8752 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8753 return;
8754
8755 buf += strlen (buf);
8756
8757 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8758 buf += strlen (buf);
8759
8760 /* Concatenate all the agent expressions that are commands into the
8761 cmds parameter. */
8762 for (ix = 0;
8763 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8764 ix++)
8765 {
8766 sprintf (buf, "X%x,", aexpr->len);
8767 buf += strlen (buf);
8768 for (i = 0; i < aexpr->len; ++i)
8769 buf = pack_hex_byte (buf, aexpr->buf[i]);
8770 *buf = '\0';
8771 }
d3ce09f5
SS
8772}
8773
8181d85f
DJ
8774/* Insert a breakpoint. On targets that have software breakpoint
8775 support, we ask the remote target to do the work; on targets
8776 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8777
8778static int
3db08215
MM
8779remote_insert_breakpoint (struct target_ops *ops,
8780 struct gdbarch *gdbarch,
a6d9a66e 8781 struct bp_target_info *bp_tgt)
c906108c 8782{
d471ea57
AC
8783 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8784 If it succeeds, then set the support to PACKET_ENABLE. If it
8785 fails, and the user has explicitly requested the Z support then
23860348 8786 report an error, otherwise, mark it disabled and go on. */
802188a7 8787
4082afcc 8788 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8789 {
0d5ed153 8790 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8791 struct remote_state *rs;
bba74b36 8792 char *p, *endbuf;
7c0f6dcc 8793 int bpsize;
b775012e 8794 struct condition_list *cond = NULL;
4fff2411 8795
28439a30
PA
8796 /* Make sure the remote is pointing at the right process, if
8797 necessary. */
8798 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8799 set_general_process ();
8800
a1dcb23a 8801 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8802
8803 rs = get_remote_state ();
8804 p = rs->buf;
bba74b36 8805 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8806
96baa820
JM
8807 *(p++) = 'Z';
8808 *(p++) = '0';
8809 *(p++) = ',';
7c0f6dcc 8810 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8811 p += hexnumstr (p, addr);
bba74b36 8812 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8813
efcc2da7 8814 if (remote_supports_cond_breakpoints (ops))
bba74b36 8815 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8816
78eff0ec 8817 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8818 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8819
6d820c5c
DJ
8820 putpkt (rs->buf);
8821 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8822
6d820c5c 8823 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8824 {
d471ea57
AC
8825 case PACKET_ERROR:
8826 return -1;
8827 case PACKET_OK:
7c0f6dcc
JL
8828 bp_tgt->placed_address = addr;
8829 bp_tgt->placed_size = bpsize;
d471ea57
AC
8830 return 0;
8831 case PACKET_UNKNOWN:
8832 break;
96baa820
JM
8833 }
8834 }
c906108c 8835
0000e5cc
PA
8836 /* If this breakpoint has target-side commands but this stub doesn't
8837 support Z0 packets, throw error. */
8838 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8839 throw_error (NOT_SUPPORTED_ERROR, _("\
8840Target doesn't support breakpoints that have target side commands."));
8841
3db08215 8842 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8843}
8844
8845static int
3db08215
MM
8846remote_remove_breakpoint (struct target_ops *ops,
8847 struct gdbarch *gdbarch,
a6d9a66e 8848 struct bp_target_info *bp_tgt)
c906108c 8849{
8181d85f 8850 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8851 struct remote_state *rs = get_remote_state ();
96baa820 8852
4082afcc 8853 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8854 {
6d820c5c 8855 char *p = rs->buf;
bba74b36 8856 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8857
28439a30
PA
8858 /* Make sure the remote is pointing at the right process, if
8859 necessary. */
8860 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8861 set_general_process ();
8862
96baa820
JM
8863 *(p++) = 'z';
8864 *(p++) = '0';
8865 *(p++) = ',';
8866
8181d85f
DJ
8867 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8868 p += hexnumstr (p, addr);
bba74b36 8869 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8870
6d820c5c
DJ
8871 putpkt (rs->buf);
8872 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8873
6d820c5c 8874 return (rs->buf[0] == 'E');
96baa820
JM
8875 }
8876
3db08215 8877 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8878}
8879
f486487f 8880static enum Z_packet_type
d471ea57
AC
8881watchpoint_to_Z_packet (int type)
8882{
8883 switch (type)
8884 {
8885 case hw_write:
bb858e6a 8886 return Z_PACKET_WRITE_WP;
d471ea57
AC
8887 break;
8888 case hw_read:
bb858e6a 8889 return Z_PACKET_READ_WP;
d471ea57
AC
8890 break;
8891 case hw_access:
bb858e6a 8892 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8893 break;
8894 default:
8e65ff28 8895 internal_error (__FILE__, __LINE__,
e2e0b3e5 8896 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8897 }
8898}
8899
3c3bea1c 8900static int
f486487f
SM
8901remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8902 enum target_hw_bp_type type, struct expression *cond)
96baa820 8903{
d01949b6 8904 struct remote_state *rs = get_remote_state ();
bba74b36 8905 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8906 char *p;
d471ea57 8907 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8908
4082afcc 8909 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 8910 return 1;
802188a7 8911
28439a30
PA
8912 /* Make sure the remote is pointing at the right process, if
8913 necessary. */
8914 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8915 set_general_process ();
8916
bba74b36 8917 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8918 p = strchr (rs->buf, '\0');
96baa820
JM
8919 addr = remote_address_masked (addr);
8920 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8921 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8922
6d820c5c
DJ
8923 putpkt (rs->buf);
8924 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8925
6d820c5c 8926 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8927 {
8928 case PACKET_ERROR:
d471ea57 8929 return -1;
85d721b8
PA
8930 case PACKET_UNKNOWN:
8931 return 1;
d471ea57
AC
8932 case PACKET_OK:
8933 return 0;
8934 }
8e65ff28 8935 internal_error (__FILE__, __LINE__,
e2e0b3e5 8936 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8937}
8938
283002cf
MR
8939static int
8940remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8941 CORE_ADDR start, int length)
8942{
8943 CORE_ADDR diff = remote_address_masked (addr - start);
8944
8945 return diff < length;
8946}
8947
d471ea57 8948
3c3bea1c 8949static int
f486487f
SM
8950remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8951 enum target_hw_bp_type type, struct expression *cond)
96baa820 8952{
d01949b6 8953 struct remote_state *rs = get_remote_state ();
bba74b36 8954 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8955 char *p;
d471ea57
AC
8956 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8957
4082afcc 8958 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 8959 return -1;
802188a7 8960
28439a30
PA
8961 /* Make sure the remote is pointing at the right process, if
8962 necessary. */
8963 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8964 set_general_process ();
8965
bba74b36 8966 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8967 p = strchr (rs->buf, '\0');
96baa820
JM
8968 addr = remote_address_masked (addr);
8969 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8970 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8971 putpkt (rs->buf);
8972 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8973
6d820c5c 8974 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8975 {
8976 case PACKET_ERROR:
8977 case PACKET_UNKNOWN:
8978 return -1;
8979 case PACKET_OK:
8980 return 0;
8981 }
8e65ff28 8982 internal_error (__FILE__, __LINE__,
e2e0b3e5 8983 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8984}
8985
3c3bea1c 8986
501eef12 8987int remote_hw_watchpoint_limit = -1;
480a3f21 8988int remote_hw_watchpoint_length_limit = -1;
501eef12 8989int remote_hw_breakpoint_limit = -1;
d471ea57 8990
480a3f21 8991static int
31568a15
TT
8992remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8993 CORE_ADDR addr, int len)
480a3f21
PW
8994{
8995 if (remote_hw_watchpoint_length_limit == 0)
8996 return 0;
8997 else if (remote_hw_watchpoint_length_limit < 0)
8998 return 1;
8999 else if (len <= remote_hw_watchpoint_length_limit)
9000 return 1;
9001 else
9002 return 0;
9003}
9004
b9362cc7 9005static int
5461485a 9006remote_check_watch_resources (struct target_ops *self,
f486487f 9007 enum bptype type, int cnt, int ot)
96baa820 9008{
3c3bea1c
GS
9009 if (type == bp_hardware_breakpoint)
9010 {
9011 if (remote_hw_breakpoint_limit == 0)
9012 return 0;
501eef12
AC
9013 else if (remote_hw_breakpoint_limit < 0)
9014 return 1;
3c3bea1c
GS
9015 else if (cnt <= remote_hw_breakpoint_limit)
9016 return 1;
9017 }
9018 else
9019 {
9020 if (remote_hw_watchpoint_limit == 0)
9021 return 0;
501eef12
AC
9022 else if (remote_hw_watchpoint_limit < 0)
9023 return 1;
3c3bea1c
GS
9024 else if (ot)
9025 return -1;
9026 else if (cnt <= remote_hw_watchpoint_limit)
9027 return 1;
9028 }
9029 return -1;
9030}
9031
f7e6eed5
PA
9032/* The to_stopped_by_sw_breakpoint method of target remote. */
9033
9034static int
9035remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9036{
9037 struct remote_state *rs = get_remote_state ();
9038
9039 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
9040}
9041
9042/* The to_supports_stopped_by_sw_breakpoint method of target
9043 remote. */
9044
9045static int
9046remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9047{
9048 struct remote_state *rs = get_remote_state ();
9049
9050 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9051}
9052
9053/* The to_stopped_by_hw_breakpoint method of target remote. */
9054
9055static int
9056remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9057{
9058 struct remote_state *rs = get_remote_state ();
9059
9060 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9061}
9062
9063/* The to_supports_stopped_by_hw_breakpoint method of target
9064 remote. */
9065
9066static int
9067remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9068{
9069 struct remote_state *rs = get_remote_state ();
9070
9071 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9072}
9073
b9362cc7 9074static int
6a109b6b 9075remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9076{
ee154bee
TT
9077 struct remote_state *rs = get_remote_state ();
9078
f7e6eed5 9079 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
3c3bea1c
GS
9080}
9081
4aa7a7f5
JJ
9082static int
9083remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9084{
ee154bee 9085 struct remote_state *rs = get_remote_state ();
4aa7a7f5 9086 int rc = 0;
a744cf53 9087
6a109b6b 9088 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 9089 {
ee154bee 9090 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
9091 rc = 1;
9092 }
9093
9094 return rc;
3c3bea1c
GS
9095}
9096
9097
9098static int
23a26771 9099remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9100 struct bp_target_info *bp_tgt)
3c3bea1c 9101{
0d5ed153 9102 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9103 struct remote_state *rs;
bba74b36 9104 char *p, *endbuf;
dd61ec5c 9105 char *message;
0d5ed153 9106 int bpsize;
802188a7 9107
c8189ed1 9108 /* The length field should be set to the size of a breakpoint
8181d85f 9109 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9110
0d5ed153 9111 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9112
4082afcc 9113 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9114 return -1;
2bc416ba 9115
28439a30
PA
9116 /* Make sure the remote is pointing at the right process, if
9117 necessary. */
9118 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9119 set_general_process ();
9120
4fff2411
JZ
9121 rs = get_remote_state ();
9122 p = rs->buf;
bba74b36 9123 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9124
96baa820
JM
9125 *(p++) = 'Z';
9126 *(p++) = '1';
9127 *(p++) = ',';
802188a7 9128
0d5ed153 9129 addr = remote_address_masked (addr);
96baa820 9130 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9131 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9132
efcc2da7 9133 if (remote_supports_cond_breakpoints (self))
bba74b36 9134 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9135
78eff0ec 9136 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9137 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9138
6d820c5c
DJ
9139 putpkt (rs->buf);
9140 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9141
6d820c5c 9142 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9143 {
9144 case PACKET_ERROR:
dd61ec5c
MW
9145 if (rs->buf[1] == '.')
9146 {
9147 message = strchr (rs->buf + 2, '.');
9148 if (message)
0316657e 9149 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9150 }
9151 return -1;
d471ea57
AC
9152 case PACKET_UNKNOWN:
9153 return -1;
9154 case PACKET_OK:
0d5ed153
MR
9155 bp_tgt->placed_address = addr;
9156 bp_tgt->placed_size = bpsize;
d471ea57
AC
9157 return 0;
9158 }
8e65ff28 9159 internal_error (__FILE__, __LINE__,
e2e0b3e5 9160 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9161}
9162
d471ea57 9163
802188a7 9164static int
a64dc96c 9165remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9166 struct bp_target_info *bp_tgt)
96baa820 9167{
8181d85f 9168 CORE_ADDR addr;
d01949b6 9169 struct remote_state *rs = get_remote_state ();
6d820c5c 9170 char *p = rs->buf;
bba74b36 9171 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9172
4082afcc 9173 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9174 return -1;
802188a7 9175
28439a30
PA
9176 /* Make sure the remote is pointing at the right process, if
9177 necessary. */
9178 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9179 set_general_process ();
9180
96baa820
JM
9181 *(p++) = 'z';
9182 *(p++) = '1';
9183 *(p++) = ',';
802188a7 9184
8181d85f 9185 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9186 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9187 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9188
6d820c5c
DJ
9189 putpkt (rs->buf);
9190 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9191
6d820c5c 9192 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9193 {
9194 case PACKET_ERROR:
9195 case PACKET_UNKNOWN:
9196 return -1;
9197 case PACKET_OK:
9198 return 0;
9199 }
8e65ff28 9200 internal_error (__FILE__, __LINE__,
e2e0b3e5 9201 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9202}
96baa820 9203
4a5e7a5b
PA
9204/* Verify memory using the "qCRC:" request. */
9205
9206static int
9207remote_verify_memory (struct target_ops *ops,
9208 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9209{
9210 struct remote_state *rs = get_remote_state ();
9211 unsigned long host_crc, target_crc;
9212 char *tmp;
9213
936d2992
PA
9214 /* It doesn't make sense to use qCRC if the remote target is
9215 connected but not running. */
9216 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9217 {
9218 enum packet_result result;
28439a30 9219
936d2992
PA
9220 /* Make sure the remote is pointing at the right process. */
9221 set_general_process ();
4a5e7a5b 9222
936d2992
PA
9223 /* FIXME: assumes lma can fit into long. */
9224 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9225 (long) lma, (long) size);
9226 putpkt (rs->buf);
4a5e7a5b 9227
936d2992
PA
9228 /* Be clever; compute the host_crc before waiting for target
9229 reply. */
9230 host_crc = xcrc32 (data, size, 0xffffffff);
9231
9232 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9233
936d2992
PA
9234 result = packet_ok (rs->buf,
9235 &remote_protocol_packets[PACKET_qCRC]);
9236 if (result == PACKET_ERROR)
9237 return -1;
9238 else if (result == PACKET_OK)
9239 {
9240 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9241 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9242
936d2992
PA
9243 return (host_crc == target_crc);
9244 }
9245 }
4a5e7a5b 9246
936d2992 9247 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9248}
9249
c906108c
SS
9250/* compare-sections command
9251
9252 With no arguments, compares each loadable section in the exec bfd
9253 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9254 Useful for verifying the image on the target against the exec file. */
e514a9d6 9255
c906108c 9256static void
fba45db2 9257compare_sections_command (char *args, int from_tty)
c906108c
SS
9258{
9259 asection *s;
c906108c 9260 struct cleanup *old_chain;
948f8e3d 9261 gdb_byte *sectdata;
ce359b09 9262 const char *sectname;
c906108c
SS
9263 bfd_size_type size;
9264 bfd_vma lma;
9265 int matched = 0;
9266 int mismatched = 0;
4a5e7a5b 9267 int res;
95cf3b38 9268 int read_only = 0;
c906108c
SS
9269
9270 if (!exec_bfd)
8a3fe4f8 9271 error (_("command cannot be used without an exec file"));
c906108c 9272
28439a30
PA
9273 /* Make sure the remote is pointing at the right process. */
9274 set_general_process ();
9275
95cf3b38
DT
9276 if (args != NULL && strcmp (args, "-r") == 0)
9277 {
9278 read_only = 1;
9279 args = NULL;
9280 }
9281
c5aa993b 9282 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9283 {
9284 if (!(s->flags & SEC_LOAD))
0df8b418 9285 continue; /* Skip non-loadable section. */
c906108c 9286
95cf3b38
DT
9287 if (read_only && (s->flags & SEC_READONLY) == 0)
9288 continue; /* Skip writeable sections */
9289
2c500098 9290 size = bfd_get_section_size (s);
c906108c 9291 if (size == 0)
0df8b418 9292 continue; /* Skip zero-length section. */
c906108c 9293
ce359b09 9294 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9295 if (args && strcmp (args, sectname) != 0)
0df8b418 9296 continue; /* Not the section selected by user. */
c906108c 9297
0df8b418 9298 matched = 1; /* Do this section. */
c906108c 9299 lma = s->lma;
c906108c 9300
c906108c 9301 sectdata = xmalloc (size);
b8c9b27d 9302 old_chain = make_cleanup (xfree, sectdata);
c906108c 9303 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9304
4a5e7a5b
PA
9305 res = target_verify_memory (sectdata, lma, size);
9306
9307 if (res == -1)
5af949e3 9308 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9309 paddress (target_gdbarch (), lma),
9310 paddress (target_gdbarch (), lma + size));
c906108c 9311
5af949e3 9312 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9313 paddress (target_gdbarch (), lma),
9314 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9315 if (res)
c906108c
SS
9316 printf_filtered ("matched.\n");
9317 else
c5aa993b
JM
9318 {
9319 printf_filtered ("MIS-MATCHED!\n");
9320 mismatched++;
9321 }
c906108c
SS
9322
9323 do_cleanups (old_chain);
9324 }
9325 if (mismatched > 0)
936d2992 9326 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9327the loaded file\n"));
c906108c 9328 if (args && !matched)
a3f17187 9329 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9330}
9331
0e7f50da
UW
9332/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9333 into remote target. The number of bytes written to the remote
9334 target is returned, or -1 for error. */
9335
9b409511 9336static enum target_xfer_status
0e7f50da
UW
9337remote_write_qxfer (struct target_ops *ops, const char *object_name,
9338 const char *annex, const gdb_byte *writebuf,
9b409511 9339 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9340 struct packet_config *packet)
9341{
9342 int i, buf_len;
9343 ULONGEST n;
0e7f50da
UW
9344 struct remote_state *rs = get_remote_state ();
9345 int max_size = get_memory_write_packet_size ();
9346
9347 if (packet->support == PACKET_DISABLE)
2ed4b548 9348 return TARGET_XFER_E_IO;
0e7f50da
UW
9349
9350 /* Insert header. */
9351 i = snprintf (rs->buf, max_size,
9352 "qXfer:%s:write:%s:%s:",
9353 object_name, annex ? annex : "",
9354 phex_nz (offset, sizeof offset));
9355 max_size -= (i + 1);
9356
9357 /* Escape as much data as fits into rs->buf. */
9358 buf_len = remote_escape_output
124e13d9 9359 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9360
9361 if (putpkt_binary (rs->buf, i + buf_len) < 0
9362 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9363 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9364 return TARGET_XFER_E_IO;
0e7f50da
UW
9365
9366 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9367
9368 *xfered_len = n;
9369 return TARGET_XFER_OK;
0e7f50da
UW
9370}
9371
0876f84a
DJ
9372/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9373 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9374 number of bytes read is returned, or 0 for EOF, or -1 for error.
9375 The number of bytes read may be less than LEN without indicating an
9376 EOF. PACKET is checked and updated to indicate whether the remote
9377 target supports this object. */
9378
9b409511 9379static enum target_xfer_status
0876f84a
DJ
9380remote_read_qxfer (struct target_ops *ops, const char *object_name,
9381 const char *annex,
9382 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9383 ULONGEST *xfered_len,
0876f84a
DJ
9384 struct packet_config *packet)
9385{
0876f84a 9386 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9387 LONGEST i, n, packet_len;
9388
9389 if (packet->support == PACKET_DISABLE)
2ed4b548 9390 return TARGET_XFER_E_IO;
0876f84a
DJ
9391
9392 /* Check whether we've cached an end-of-object packet that matches
9393 this request. */
8e88304f 9394 if (rs->finished_object)
0876f84a 9395 {
8e88304f
TT
9396 if (strcmp (object_name, rs->finished_object) == 0
9397 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9398 && offset == rs->finished_offset)
9b409511
YQ
9399 return TARGET_XFER_EOF;
9400
0876f84a
DJ
9401
9402 /* Otherwise, we're now reading something different. Discard
9403 the cache. */
8e88304f
TT
9404 xfree (rs->finished_object);
9405 xfree (rs->finished_annex);
9406 rs->finished_object = NULL;
9407 rs->finished_annex = NULL;
0876f84a
DJ
9408 }
9409
9410 /* Request only enough to fit in a single packet. The actual data
9411 may not, since we don't know how much of it will need to be escaped;
9412 the target is free to respond with slightly less data. We subtract
9413 five to account for the response type and the protocol frame. */
9414 n = min (get_remote_packet_size () - 5, len);
9415 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9416 object_name, annex ? annex : "",
9417 phex_nz (offset, sizeof offset),
9418 phex_nz (n, sizeof n));
9419 i = putpkt (rs->buf);
9420 if (i < 0)
2ed4b548 9421 return TARGET_XFER_E_IO;
0876f84a
DJ
9422
9423 rs->buf[0] = '\0';
9424 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9425 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9426 return TARGET_XFER_E_IO;
0876f84a
DJ
9427
9428 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9429 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9430
9431 /* 'm' means there is (or at least might be) more data after this
9432 batch. That does not make sense unless there's at least one byte
9433 of data in this reply. */
9434 if (rs->buf[0] == 'm' && packet_len == 1)
9435 error (_("Remote qXfer reply contained no data."));
9436
9437 /* Got some data. */
bc20a4af
PA
9438 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9439 packet_len - 1, readbuf, n);
0876f84a
DJ
9440
9441 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9442 or possibly empty. If we have the final block of a non-empty
9443 object, record this fact to bypass a subsequent partial read. */
9444 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9445 {
8e88304f
TT
9446 rs->finished_object = xstrdup (object_name);
9447 rs->finished_annex = xstrdup (annex ? annex : "");
9448 rs->finished_offset = offset + i;
0876f84a
DJ
9449 }
9450
9b409511
YQ
9451 if (i == 0)
9452 return TARGET_XFER_EOF;
9453 else
9454 {
9455 *xfered_len = i;
9456 return TARGET_XFER_OK;
9457 }
0876f84a
DJ
9458}
9459
9b409511 9460static enum target_xfer_status
4b8a223f 9461remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9462 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9463 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9464 ULONGEST *xfered_len)
c906108c 9465{
82f73884 9466 struct remote_state *rs;
c906108c 9467 int i;
6d820c5c 9468 char *p2;
1e3ff5ad 9469 char query_type;
124e13d9 9470 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9471
e6e4e701 9472 set_remote_traceframe ();
82f73884
PA
9473 set_general_thread (inferior_ptid);
9474
9475 rs = get_remote_state ();
9476
b2182ed2 9477 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9478 if (object == TARGET_OBJECT_MEMORY)
9479 {
2d717e4f
DJ
9480 /* If the remote target is connected but not running, we should
9481 pass this request down to a lower stratum (e.g. the executable
9482 file). */
9483 if (!target_has_execution)
9b409511 9484 return TARGET_XFER_EOF;
2d717e4f 9485
21e3b9b9 9486 if (writebuf != NULL)
124e13d9
SM
9487 return remote_write_bytes (offset, writebuf, len, unit_size,
9488 xfered_len);
21e3b9b9 9489 else
124e13d9
SM
9490 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9491 xfered_len);
21e3b9b9
DJ
9492 }
9493
0df8b418 9494 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9495 if (object == TARGET_OBJECT_SPU)
9496 {
9497 if (readbuf)
9498 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9499 xfered_len, &remote_protocol_packets
9500 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9501 else
9502 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9503 xfered_len, &remote_protocol_packets
9504 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9505 }
9506
4aa995e1
PA
9507 /* Handle extra signal info using qxfer packets. */
9508 if (object == TARGET_OBJECT_SIGNAL_INFO)
9509 {
9510 if (readbuf)
9511 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 9512 xfered_len, &remote_protocol_packets
4aa995e1
PA
9513 [PACKET_qXfer_siginfo_read]);
9514 else
3e43a32a 9515 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 9516 writebuf, offset, len, xfered_len,
4aa995e1
PA
9517 &remote_protocol_packets
9518 [PACKET_qXfer_siginfo_write]);
9519 }
9520
0fb4aa4b
PA
9521 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9522 {
9523 if (readbuf)
3e43a32a 9524 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 9525 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
9526 &remote_protocol_packets
9527 [PACKET_qXfer_statictrace_read]);
9528 else
2ed4b548 9529 return TARGET_XFER_E_IO;
0fb4aa4b
PA
9530 }
9531
a76d924d
DJ
9532 /* Only handle flash writes. */
9533 if (writebuf != NULL)
9534 {
9535 LONGEST xfered;
9536
9537 switch (object)
9538 {
9539 case TARGET_OBJECT_FLASH:
9b409511
YQ
9540 return remote_flash_write (ops, offset, len, xfered_len,
9541 writebuf);
a76d924d
DJ
9542
9543 default:
2ed4b548 9544 return TARGET_XFER_E_IO;
a76d924d
DJ
9545 }
9546 }
4b8a223f 9547
1e3ff5ad
AC
9548 /* Map pre-existing objects onto letters. DO NOT do this for new
9549 objects!!! Instead specify new query packets. */
9550 switch (object)
c906108c 9551 {
1e3ff5ad
AC
9552 case TARGET_OBJECT_AVR:
9553 query_type = 'R';
9554 break;
802188a7
RM
9555
9556 case TARGET_OBJECT_AUXV:
0876f84a
DJ
9557 gdb_assert (annex == NULL);
9558 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9559 xfered_len,
0876f84a 9560 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9561
23181151
DJ
9562 case TARGET_OBJECT_AVAILABLE_FEATURES:
9563 return remote_read_qxfer
9b409511 9564 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9565 &remote_protocol_packets[PACKET_qXfer_features]);
9566
cfa9d6d9
DJ
9567 case TARGET_OBJECT_LIBRARIES:
9568 return remote_read_qxfer
9b409511 9569 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9570 &remote_protocol_packets[PACKET_qXfer_libraries]);
9571
2268b414
JK
9572 case TARGET_OBJECT_LIBRARIES_SVR4:
9573 return remote_read_qxfer
9b409511 9574 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9575 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9576
fd79ecee
DJ
9577 case TARGET_OBJECT_MEMORY_MAP:
9578 gdb_assert (annex == NULL);
9579 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9580 xfered_len,
fd79ecee
DJ
9581 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9582
07e059b5
VP
9583 case TARGET_OBJECT_OSDATA:
9584 /* Should only get here if we're connected. */
5d93a237 9585 gdb_assert (rs->remote_desc);
07e059b5 9586 return remote_read_qxfer
9b409511 9587 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9588 &remote_protocol_packets[PACKET_qXfer_osdata]);
9589
dc146f7c
VP
9590 case TARGET_OBJECT_THREADS:
9591 gdb_assert (annex == NULL);
9592 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9593 xfered_len,
dc146f7c
VP
9594 &remote_protocol_packets[PACKET_qXfer_threads]);
9595
b3b9301e
PA
9596 case TARGET_OBJECT_TRACEFRAME_INFO:
9597 gdb_assert (annex == NULL);
9598 return remote_read_qxfer
9b409511 9599 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9600 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9601
9602 case TARGET_OBJECT_FDPIC:
9603 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9604 xfered_len,
78d85199 9605 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9606
9607 case TARGET_OBJECT_OPENVMS_UIB:
9608 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 9609 xfered_len,
169081d0
TG
9610 &remote_protocol_packets[PACKET_qXfer_uib]);
9611
9accd112
MM
9612 case TARGET_OBJECT_BTRACE:
9613 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 9614 xfered_len,
9accd112
MM
9615 &remote_protocol_packets[PACKET_qXfer_btrace]);
9616
f4abbc16
MM
9617 case TARGET_OBJECT_BTRACE_CONF:
9618 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9619 len, xfered_len,
9620 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9621
c78fa86a
GB
9622 case TARGET_OBJECT_EXEC_FILE:
9623 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9624 len, xfered_len,
9625 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9626
1e3ff5ad 9627 default:
2ed4b548 9628 return TARGET_XFER_E_IO;
c906108c
SS
9629 }
9630
0df8b418 9631 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 9632 large enough let the caller deal with it. */
ea9c271d 9633 if (len < get_remote_packet_size ())
2ed4b548 9634 return TARGET_XFER_E_IO;
ea9c271d 9635 len = get_remote_packet_size ();
1e3ff5ad 9636
23860348 9637 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 9638 if (!rs->remote_desc)
8a3fe4f8 9639 error (_("remote query is only available after target open"));
c906108c 9640
1e3ff5ad 9641 gdb_assert (annex != NULL);
4b8a223f 9642 gdb_assert (readbuf != NULL);
c906108c 9643
6d820c5c 9644 p2 = rs->buf;
c906108c
SS
9645 *p2++ = 'q';
9646 *p2++ = query_type;
9647
23860348
MS
9648 /* We used one buffer char for the remote protocol q command and
9649 another for the query type. As the remote protocol encapsulation
9650 uses 4 chars plus one extra in case we are debugging
9651 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9652 string. */
c906108c 9653 i = 0;
ea9c271d 9654 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 9655 {
1e3ff5ad
AC
9656 /* Bad caller may have sent forbidden characters. */
9657 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9658 *p2++ = annex[i];
c906108c
SS
9659 i++;
9660 }
1e3ff5ad
AC
9661 *p2 = '\0';
9662 gdb_assert (annex[i] == '\0');
c906108c 9663
6d820c5c 9664 i = putpkt (rs->buf);
c5aa993b 9665 if (i < 0)
2ed4b548 9666 return TARGET_XFER_E_IO;
c906108c 9667
6d820c5c
DJ
9668 getpkt (&rs->buf, &rs->buf_size, 0);
9669 strcpy ((char *) readbuf, rs->buf);
c906108c 9670
9b409511
YQ
9671 *xfered_len = strlen ((char *) readbuf);
9672 return TARGET_XFER_OK;
c906108c
SS
9673}
9674
08388c79
DE
9675static int
9676remote_search_memory (struct target_ops* ops,
9677 CORE_ADDR start_addr, ULONGEST search_space_len,
9678 const gdb_byte *pattern, ULONGEST pattern_len,
9679 CORE_ADDR *found_addrp)
9680{
f5656ead 9681 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
9682 struct remote_state *rs = get_remote_state ();
9683 int max_size = get_memory_write_packet_size ();
9684 struct packet_config *packet =
9685 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
9686 /* Number of packet bytes used to encode the pattern;
9687 this could be more than PATTERN_LEN due to escape characters. */
08388c79 9688 int escaped_pattern_len;
0df8b418 9689 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
9690 int used_pattern_len;
9691 int i;
9692 int found;
9693 ULONGEST found_addr;
9694
9695 /* Don't go to the target if we don't have to.
9696 This is done before checking packet->support to avoid the possibility that
9697 a success for this edge case means the facility works in general. */
9698 if (pattern_len > search_space_len)
9699 return 0;
9700 if (pattern_len == 0)
9701 {
9702 *found_addrp = start_addr;
9703 return 1;
9704 }
9705
9706 /* If we already know the packet isn't supported, fall back to the simple
9707 way of searching memory. */
9708
4082afcc 9709 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
9710 {
9711 /* Target doesn't provided special support, fall back and use the
9712 standard support (copy memory and do the search here). */
9713 return simple_search_memory (ops, start_addr, search_space_len,
9714 pattern, pattern_len, found_addrp);
9715 }
9716
28439a30
PA
9717 /* Make sure the remote is pointing at the right process. */
9718 set_general_process ();
9719
08388c79
DE
9720 /* Insert header. */
9721 i = snprintf (rs->buf, max_size,
9722 "qSearch:memory:%s;%s;",
5af949e3 9723 phex_nz (start_addr, addr_size),
08388c79
DE
9724 phex_nz (search_space_len, sizeof (search_space_len)));
9725 max_size -= (i + 1);
9726
9727 /* Escape as much data as fits into rs->buf. */
9728 escaped_pattern_len =
124e13d9 9729 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
9730 &used_pattern_len, max_size);
9731
9732 /* Bail if the pattern is too large. */
9733 if (used_pattern_len != pattern_len)
9b20d036 9734 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
9735
9736 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9737 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9738 || packet_ok (rs->buf, packet) != PACKET_OK)
9739 {
9740 /* The request may not have worked because the command is not
9741 supported. If so, fall back to the simple way. */
9742 if (packet->support == PACKET_DISABLE)
9743 {
9744 return simple_search_memory (ops, start_addr, search_space_len,
9745 pattern, pattern_len, found_addrp);
9746 }
9747 return -1;
9748 }
9749
9750 if (rs->buf[0] == '0')
9751 found = 0;
9752 else if (rs->buf[0] == '1')
9753 {
9754 found = 1;
9755 if (rs->buf[1] != ',')
10e0fa18 9756 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9757 unpack_varlen_hex (rs->buf + 2, &found_addr);
9758 *found_addrp = found_addr;
9759 }
9760 else
10e0fa18 9761 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9762
9763 return found;
9764}
9765
96baa820 9766static void
a30bf1f1 9767remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 9768 struct ui_file *outbuf)
96baa820 9769{
d01949b6 9770 struct remote_state *rs = get_remote_state ();
2e9f7625 9771 char *p = rs->buf;
96baa820 9772
5d93a237 9773 if (!rs->remote_desc)
8a3fe4f8 9774 error (_("remote rcmd is only available after target open"));
96baa820 9775
23860348 9776 /* Send a NULL command across as an empty command. */
7be570e7
JM
9777 if (command == NULL)
9778 command = "";
9779
23860348 9780 /* The query prefix. */
2e9f7625
DJ
9781 strcpy (rs->buf, "qRcmd,");
9782 p = strchr (rs->buf, '\0');
96baa820 9783
3e43a32a
MS
9784 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9785 > get_remote_packet_size ())
8a3fe4f8 9786 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9787
23860348 9788 /* Encode the actual command. */
a30bf1f1 9789 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 9790
6d820c5c 9791 if (putpkt (rs->buf) < 0)
8a3fe4f8 9792 error (_("Communication problem with target."));
96baa820
JM
9793
9794 /* get/display the response */
9795 while (1)
9796 {
2e9f7625
DJ
9797 char *buf;
9798
00bf0b85 9799 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9800 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9801 rs->buf[0] = '\0';
5b37825d
PW
9802 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9803 {
9804 /* Timeout. Continue to (try to) read responses.
9805 This is better than stopping with an error, assuming the stub
9806 is still executing the (long) monitor command.
9807 If needed, the user can interrupt gdb using C-c, obtaining
9808 an effect similar to stop on timeout. */
9809 continue;
9810 }
2e9f7625 9811 buf = rs->buf;
96baa820 9812 if (buf[0] == '\0')
8a3fe4f8 9813 error (_("Target does not support this command."));
96baa820
JM
9814 if (buf[0] == 'O' && buf[1] != 'K')
9815 {
23860348 9816 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9817 continue;
9818 }
9819 if (strcmp (buf, "OK") == 0)
9820 break;
7be570e7
JM
9821 if (strlen (buf) == 3 && buf[0] == 'E'
9822 && isdigit (buf[1]) && isdigit (buf[2]))
9823 {
8a3fe4f8 9824 error (_("Protocol error with Rcmd"));
7be570e7 9825 }
96baa820
JM
9826 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9827 {
9828 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9829
96baa820
JM
9830 fputc_unfiltered (c, outbuf);
9831 }
9832 break;
9833 }
9834}
9835
fd79ecee
DJ
9836static VEC(mem_region_s) *
9837remote_memory_map (struct target_ops *ops)
9838{
9839 VEC(mem_region_s) *result = NULL;
9840 char *text = target_read_stralloc (&current_target,
9841 TARGET_OBJECT_MEMORY_MAP, NULL);
9842
9843 if (text)
9844 {
9845 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9846
fd79ecee
DJ
9847 result = parse_memory_map (text);
9848 do_cleanups (back_to);
9849 }
9850
9851 return result;
9852}
9853
c906108c 9854static void
fba45db2 9855packet_command (char *args, int from_tty)
c906108c 9856{
d01949b6 9857 struct remote_state *rs = get_remote_state ();
c906108c 9858
5d93a237 9859 if (!rs->remote_desc)
8a3fe4f8 9860 error (_("command can only be used with remote target"));
c906108c 9861
c5aa993b 9862 if (!args)
8a3fe4f8 9863 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9864
9865 puts_filtered ("sending: ");
9866 print_packet (args);
9867 puts_filtered ("\n");
9868 putpkt (args);
9869
6d820c5c 9870 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9871 puts_filtered ("received: ");
6d820c5c 9872 print_packet (rs->buf);
c906108c
SS
9873 puts_filtered ("\n");
9874}
9875
9876#if 0
23860348 9877/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9878
a14ed312 9879static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9880
a14ed312 9881static void threadset_test_cmd (char *cmd, int tty);
c906108c 9882
a14ed312 9883static void threadalive_test (char *cmd, int tty);
c906108c 9884
a14ed312 9885static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9886
23860348 9887int get_and_display_threadinfo (threadref *ref);
c906108c 9888
a14ed312 9889static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9890
23860348 9891static int thread_display_step (threadref *ref, void *context);
c906108c 9892
a14ed312 9893static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9894
a14ed312 9895static void init_remote_threadtests (void);
c906108c 9896
23860348 9897#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9898
9899static void
fba45db2 9900threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9901{
9902 int sample_thread = SAMPLE_THREAD;
9903
a3f17187 9904 printf_filtered (_("Remote threadset test\n"));
79d7f229 9905 set_general_thread (sample_thread);
c906108c
SS
9906}
9907
9908
9909static void
fba45db2 9910threadalive_test (char *cmd, int tty)
c906108c
SS
9911{
9912 int sample_thread = SAMPLE_THREAD;
79d7f229 9913 int pid = ptid_get_pid (inferior_ptid);
ba348170 9914 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 9915
79d7f229 9916 if (remote_thread_alive (ptid))
c906108c
SS
9917 printf_filtered ("PASS: Thread alive test\n");
9918 else
9919 printf_filtered ("FAIL: Thread alive test\n");
9920}
9921
23860348 9922void output_threadid (char *title, threadref *ref);
c906108c
SS
9923
9924void
fba45db2 9925output_threadid (char *title, threadref *ref)
c906108c
SS
9926{
9927 char hexid[20];
9928
23860348 9929 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9930 hexid[16] = 0;
9931 printf_filtered ("%s %s\n", title, (&hexid[0]));
9932}
9933
9934static void
fba45db2 9935threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9936{
9937 int startflag = 1;
9938 threadref nextthread;
9939 int done, result_count;
9940 threadref threadlist[3];
9941
9942 printf_filtered ("Remote Threadlist test\n");
9943 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9944 &result_count, &threadlist[0]))
9945 printf_filtered ("FAIL: threadlist test\n");
9946 else
9947 {
9948 threadref *scan = threadlist;
9949 threadref *limit = scan + result_count;
9950
9951 while (scan < limit)
9952 output_threadid (" thread ", scan++);
9953 }
9954}
9955
9956void
fba45db2 9957display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9958{
9959 output_threadid ("Threadid: ", &info->threadid);
9960 printf_filtered ("Name: %s\n ", info->shortname);
9961 printf_filtered ("State: %s\n", info->display);
9962 printf_filtered ("other: %s\n\n", info->more_display);
9963}
9964
9965int
fba45db2 9966get_and_display_threadinfo (threadref *ref)
c906108c
SS
9967{
9968 int result;
9969 int set;
9970 struct gdb_ext_thread_info threadinfo;
9971
9972 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9973 | TAG_MOREDISPLAY | TAG_DISPLAY;
9974 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9975 display_thread_info (&threadinfo);
9976 return result;
9977}
9978
9979static void
fba45db2 9980threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9981{
9982 int athread = SAMPLE_THREAD;
9983 threadref thread;
9984 int set;
9985
9986 int_to_threadref (&thread, athread);
9987 printf_filtered ("Remote Threadinfo test\n");
9988 if (!get_and_display_threadinfo (&thread))
9989 printf_filtered ("FAIL cannot get thread info\n");
9990}
9991
9992static int
fba45db2 9993thread_display_step (threadref *ref, void *context)
c906108c
SS
9994{
9995 /* output_threadid(" threadstep ",ref); *//* simple test */
9996 return get_and_display_threadinfo (ref);
9997}
9998
9999static void
fba45db2 10000threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10001{
10002 printf_filtered ("Remote Threadlist update test\n");
10003 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10004}
10005
10006static void
10007init_remote_threadtests (void)
10008{
3e43a32a
MS
10009 add_com ("tlist", class_obscure, threadlist_test_cmd,
10010 _("Fetch and print the remote list of "
10011 "thread identifiers, one pkt only"));
c906108c 10012 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10013 _("Fetch and display info about one thread"));
c906108c 10014 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10015 _("Test setting to a different thread"));
c906108c 10016 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10017 _("Iterate through updating all remote thread info"));
c906108c 10018 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10019 _(" Remote thread alive test "));
c906108c
SS
10020}
10021
10022#endif /* 0 */
10023
f3fb8c85
MS
10024/* Convert a thread ID to a string. Returns the string in a static
10025 buffer. */
10026
10027static char *
117de6a9 10028remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10029{
79d7f229 10030 static char buf[64];
82f73884 10031 struct remote_state *rs = get_remote_state ();
f3fb8c85 10032
7cee1e54
PA
10033 if (ptid_equal (ptid, null_ptid))
10034 return normal_pid_to_str (ptid);
10035 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10036 {
10037 /* Printing an inferior target id. */
10038
10039 /* When multi-process extensions are off, there's no way in the
10040 remote protocol to know the remote process id, if there's any
10041 at all. There's one exception --- when we're connected with
10042 target extended-remote, and we manually attached to a process
10043 with "attach PID". We don't record anywhere a flag that
10044 allows us to distinguish that case from the case of
10045 connecting with extended-remote and the stub already being
10046 attached to a process, and reporting yes to qAttached, hence
10047 no smart special casing here. */
10048 if (!remote_multi_process_p (rs))
10049 {
10050 xsnprintf (buf, sizeof buf, "Remote target");
10051 return buf;
10052 }
10053
10054 return normal_pid_to_str (ptid);
82f73884 10055 }
ecd0ada5 10056 else
79d7f229 10057 {
ecd0ada5
PA
10058 if (ptid_equal (magic_null_ptid, ptid))
10059 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 10060 else if (rs->extended && remote_multi_process_p (rs))
de0d863e
DB
10061 if (ptid_get_lwp (ptid) == 0)
10062 return normal_pid_to_str (ptid);
10063 else
10064 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10065 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10066 else
10067 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10068 ptid_get_lwp (ptid));
79d7f229
PA
10069 return buf;
10070 }
f3fb8c85
MS
10071}
10072
38691318
KB
10073/* Get the address of the thread local variable in OBJFILE which is
10074 stored at OFFSET within the thread local storage for thread PTID. */
10075
10076static CORE_ADDR
117de6a9
PA
10077remote_get_thread_local_address (struct target_ops *ops,
10078 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10079{
4082afcc 10080 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10081 {
10082 struct remote_state *rs = get_remote_state ();
6d820c5c 10083 char *p = rs->buf;
82f73884 10084 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10085 enum packet_result result;
38691318
KB
10086
10087 strcpy (p, "qGetTLSAddr:");
10088 p += strlen (p);
82f73884 10089 p = write_ptid (p, endp, ptid);
38691318
KB
10090 *p++ = ',';
10091 p += hexnumstr (p, offset);
10092 *p++ = ',';
10093 p += hexnumstr (p, lm);
10094 *p++ = '\0';
10095
6d820c5c
DJ
10096 putpkt (rs->buf);
10097 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10098 result = packet_ok (rs->buf,
10099 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10100 if (result == PACKET_OK)
38691318
KB
10101 {
10102 ULONGEST result;
10103
6d820c5c 10104 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10105 return result;
10106 }
571dd617 10107 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10108 throw_error (TLS_GENERIC_ERROR,
10109 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10110 else
109c3e39
AC
10111 throw_error (TLS_GENERIC_ERROR,
10112 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10113 }
10114 else
109c3e39
AC
10115 throw_error (TLS_GENERIC_ERROR,
10116 _("TLS not supported or disabled on this target"));
38691318
KB
10117 /* Not reached. */
10118 return 0;
10119}
10120
711e434b
PM
10121/* Provide thread local base, i.e. Thread Information Block address.
10122 Returns 1 if ptid is found and thread_local_base is non zero. */
10123
70221824 10124static int
bd7ae0f5 10125remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10126{
4082afcc 10127 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10128 {
10129 struct remote_state *rs = get_remote_state ();
10130 char *p = rs->buf;
10131 char *endp = rs->buf + get_remote_packet_size ();
10132 enum packet_result result;
10133
10134 strcpy (p, "qGetTIBAddr:");
10135 p += strlen (p);
10136 p = write_ptid (p, endp, ptid);
10137 *p++ = '\0';
10138
10139 putpkt (rs->buf);
10140 getpkt (&rs->buf, &rs->buf_size, 0);
10141 result = packet_ok (rs->buf,
10142 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10143 if (result == PACKET_OK)
10144 {
10145 ULONGEST result;
10146
10147 unpack_varlen_hex (rs->buf, &result);
10148 if (addr)
10149 *addr = (CORE_ADDR) result;
10150 return 1;
10151 }
10152 else if (result == PACKET_UNKNOWN)
10153 error (_("Remote target doesn't support qGetTIBAddr packet"));
10154 else
10155 error (_("Remote target failed to process qGetTIBAddr request"));
10156 }
10157 else
10158 error (_("qGetTIBAddr not supported or disabled on this target"));
10159 /* Not reached. */
10160 return 0;
10161}
10162
29709017
DJ
10163/* Support for inferring a target description based on the current
10164 architecture and the size of a 'g' packet. While the 'g' packet
10165 can have any size (since optional registers can be left off the
10166 end), some sizes are easily recognizable given knowledge of the
10167 approximate architecture. */
10168
10169struct remote_g_packet_guess
10170{
10171 int bytes;
10172 const struct target_desc *tdesc;
10173};
10174typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10175DEF_VEC_O(remote_g_packet_guess_s);
10176
10177struct remote_g_packet_data
10178{
10179 VEC(remote_g_packet_guess_s) *guesses;
10180};
10181
10182static struct gdbarch_data *remote_g_packet_data_handle;
10183
10184static void *
10185remote_g_packet_data_init (struct obstack *obstack)
10186{
10187 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10188}
10189
10190void
10191register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10192 const struct target_desc *tdesc)
10193{
10194 struct remote_g_packet_data *data
10195 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
10196 struct remote_g_packet_guess new_guess, *guess;
10197 int ix;
10198
10199 gdb_assert (tdesc != NULL);
10200
10201 for (ix = 0;
10202 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10203 ix++)
10204 if (guess->bytes == bytes)
10205 internal_error (__FILE__, __LINE__,
9b20d036 10206 _("Duplicate g packet description added for size %d"),
29709017
DJ
10207 bytes);
10208
10209 new_guess.bytes = bytes;
10210 new_guess.tdesc = tdesc;
10211 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10212}
10213
d962ef82
DJ
10214/* Return 1 if remote_read_description would do anything on this target
10215 and architecture, 0 otherwise. */
10216
10217static int
10218remote_read_description_p (struct target_ops *target)
10219{
10220 struct remote_g_packet_data *data
f5656ead 10221 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
10222
10223 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10224 return 1;
10225
10226 return 0;
10227}
10228
29709017
DJ
10229static const struct target_desc *
10230remote_read_description (struct target_ops *target)
10231{
10232 struct remote_g_packet_data *data
f5656ead 10233 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 10234
d962ef82
DJ
10235 /* Do not try this during initial connection, when we do not know
10236 whether there is a running but stopped thread. */
10237 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10238 return target->beneath->to_read_description (target->beneath);
d962ef82 10239
29709017
DJ
10240 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10241 {
10242 struct remote_g_packet_guess *guess;
10243 int ix;
10244 int bytes = send_g_packet ();
10245
10246 for (ix = 0;
10247 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10248 ix++)
10249 if (guess->bytes == bytes)
10250 return guess->tdesc;
10251
10252 /* We discard the g packet. A minor optimization would be to
10253 hold on to it, and fill the register cache once we have selected
10254 an architecture, but it's too tricky to do safely. */
10255 }
10256
2117c711 10257 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10258}
10259
a6b151f1
DJ
10260/* Remote file transfer support. This is host-initiated I/O, not
10261 target-initiated; for target-initiated, see remote-fileio.c. */
10262
10263/* If *LEFT is at least the length of STRING, copy STRING to
10264 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10265 decrease *LEFT. Otherwise raise an error. */
10266
10267static void
10268remote_buffer_add_string (char **buffer, int *left, char *string)
10269{
10270 int len = strlen (string);
10271
10272 if (len > *left)
10273 error (_("Packet too long for target."));
10274
10275 memcpy (*buffer, string, len);
10276 *buffer += len;
10277 *left -= len;
10278
10279 /* NUL-terminate the buffer as a convenience, if there is
10280 room. */
10281 if (*left)
10282 **buffer = '\0';
10283}
10284
10285/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10286 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10287 decrease *LEFT. Otherwise raise an error. */
10288
10289static void
10290remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10291 int len)
10292{
10293 if (2 * len > *left)
10294 error (_("Packet too long for target."));
10295
10296 bin2hex (bytes, *buffer, len);
10297 *buffer += 2 * len;
10298 *left -= 2 * len;
10299
10300 /* NUL-terminate the buffer as a convenience, if there is
10301 room. */
10302 if (*left)
10303 **buffer = '\0';
10304}
10305
10306/* If *LEFT is large enough, convert VALUE to hex and add it to
10307 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10308 decrease *LEFT. Otherwise raise an error. */
10309
10310static void
10311remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10312{
10313 int len = hexnumlen (value);
10314
10315 if (len > *left)
10316 error (_("Packet too long for target."));
10317
10318 hexnumstr (*buffer, value);
10319 *buffer += len;
10320 *left -= len;
10321
10322 /* NUL-terminate the buffer as a convenience, if there is
10323 room. */
10324 if (*left)
10325 **buffer = '\0';
10326}
10327
10328/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10329 value, *REMOTE_ERRNO to the remote error number or zero if none
10330 was included, and *ATTACHMENT to point to the start of the annex
10331 if any. The length of the packet isn't needed here; there may
10332 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10333
10334 Return 0 if the packet could be parsed, -1 if it could not. If
10335 -1 is returned, the other variables may not be initialized. */
10336
10337static int
10338remote_hostio_parse_result (char *buffer, int *retcode,
10339 int *remote_errno, char **attachment)
10340{
10341 char *p, *p2;
10342
10343 *remote_errno = 0;
10344 *attachment = NULL;
10345
10346 if (buffer[0] != 'F')
10347 return -1;
10348
10349 errno = 0;
10350 *retcode = strtol (&buffer[1], &p, 16);
10351 if (errno != 0 || p == &buffer[1])
10352 return -1;
10353
10354 /* Check for ",errno". */
10355 if (*p == ',')
10356 {
10357 errno = 0;
10358 *remote_errno = strtol (p + 1, &p2, 16);
10359 if (errno != 0 || p + 1 == p2)
10360 return -1;
10361 p = p2;
10362 }
10363
10364 /* Check for ";attachment". If there is no attachment, the
10365 packet should end here. */
10366 if (*p == ';')
10367 {
10368 *attachment = p + 1;
10369 return 0;
10370 }
10371 else if (*p == '\0')
10372 return 0;
10373 else
10374 return -1;
10375}
10376
10377/* Send a prepared I/O packet to the target and read its response.
10378 The prepared packet is in the global RS->BUF before this function
10379 is called, and the answer is there when we return.
10380
10381 COMMAND_BYTES is the length of the request to send, which may include
10382 binary data. WHICH_PACKET is the packet configuration to check
10383 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10384 is set to the error number and -1 is returned. Otherwise the value
10385 returned by the function is returned.
10386
10387 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10388 attachment is expected; an error will be reported if there's a
10389 mismatch. If one is found, *ATTACHMENT will be set to point into
10390 the packet buffer and *ATTACHMENT_LEN will be set to the
10391 attachment's length. */
10392
10393static int
10394remote_hostio_send_command (int command_bytes, int which_packet,
10395 int *remote_errno, char **attachment,
10396 int *attachment_len)
10397{
10398 struct remote_state *rs = get_remote_state ();
10399 int ret, bytes_read;
10400 char *attachment_tmp;
10401
5d93a237 10402 if (!rs->remote_desc
4082afcc 10403 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10404 {
10405 *remote_errno = FILEIO_ENOSYS;
10406 return -1;
10407 }
10408
10409 putpkt_binary (rs->buf, command_bytes);
10410 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10411
10412 /* If it timed out, something is wrong. Don't try to parse the
10413 buffer. */
10414 if (bytes_read < 0)
10415 {
10416 *remote_errno = FILEIO_EINVAL;
10417 return -1;
10418 }
10419
10420 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10421 {
10422 case PACKET_ERROR:
10423 *remote_errno = FILEIO_EINVAL;
10424 return -1;
10425 case PACKET_UNKNOWN:
10426 *remote_errno = FILEIO_ENOSYS;
10427 return -1;
10428 case PACKET_OK:
10429 break;
10430 }
10431
10432 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10433 &attachment_tmp))
10434 {
10435 *remote_errno = FILEIO_EINVAL;
10436 return -1;
10437 }
10438
10439 /* Make sure we saw an attachment if and only if we expected one. */
10440 if ((attachment_tmp == NULL && attachment != NULL)
10441 || (attachment_tmp != NULL && attachment == NULL))
10442 {
10443 *remote_errno = FILEIO_EINVAL;
10444 return -1;
10445 }
10446
10447 /* If an attachment was found, it must point into the packet buffer;
10448 work out how many bytes there were. */
10449 if (attachment_tmp != NULL)
10450 {
10451 *attachment = attachment_tmp;
10452 *attachment_len = bytes_read - (*attachment - rs->buf);
10453 }
10454
10455 return ret;
10456}
10457
80152258
PA
10458/* Invalidate the readahead cache. */
10459
10460static void
10461readahead_cache_invalidate (void)
10462{
10463 struct remote_state *rs = get_remote_state ();
10464
10465 rs->readahead_cache.fd = -1;
10466}
10467
10468/* Invalidate the readahead cache if it is holding data for FD. */
10469
10470static void
10471readahead_cache_invalidate_fd (int fd)
10472{
10473 struct remote_state *rs = get_remote_state ();
10474
10475 if (rs->readahead_cache.fd == fd)
10476 rs->readahead_cache.fd = -1;
10477}
10478
15a201c8
GB
10479/* Set the filesystem remote_hostio functions that take FILENAME
10480 arguments will use. Return 0 on success, or -1 if an error
10481 occurs (and set *REMOTE_ERRNO). */
10482
10483static int
10484remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10485{
10486 struct remote_state *rs = get_remote_state ();
10487 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10488 char *p = rs->buf;
10489 int left = get_remote_packet_size () - 1;
10490 char arg[9];
10491 int ret;
10492
10493 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10494 return 0;
10495
10496 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10497 return 0;
10498
10499 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10500
10501 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10502 remote_buffer_add_string (&p, &left, arg);
10503
10504 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10505 remote_errno, NULL, NULL);
10506
10507 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10508 return 0;
10509
10510 if (ret == 0)
10511 rs->fs_pid = required_pid;
10512
10513 return ret;
10514}
10515
12e2a5fd 10516/* Implementation of to_fileio_open. */
a6b151f1
DJ
10517
10518static int
cd897586 10519remote_hostio_open (struct target_ops *self,
07c138c8 10520 struct inferior *inf, const char *filename,
4313b8c0
GB
10521 int flags, int mode, int warn_if_slow,
10522 int *remote_errno)
a6b151f1
DJ
10523{
10524 struct remote_state *rs = get_remote_state ();
10525 char *p = rs->buf;
10526 int left = get_remote_packet_size () - 1;
10527
4313b8c0
GB
10528 if (warn_if_slow)
10529 {
10530 static int warning_issued = 0;
10531
10532 printf_unfiltered (_("Reading %s from remote target...\n"),
10533 filename);
10534
10535 if (!warning_issued)
10536 {
10537 warning (_("File transfers from remote targets can be slow."
10538 " Use \"set sysroot\" to access files locally"
10539 " instead."));
10540 warning_issued = 1;
10541 }
10542 }
10543
15a201c8
GB
10544 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10545 return -1;
10546
a6b151f1
DJ
10547 remote_buffer_add_string (&p, &left, "vFile:open:");
10548
10549 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10550 strlen (filename));
10551 remote_buffer_add_string (&p, &left, ",");
10552
10553 remote_buffer_add_int (&p, &left, flags);
10554 remote_buffer_add_string (&p, &left, ",");
10555
10556 remote_buffer_add_int (&p, &left, mode);
10557
10558 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10559 remote_errno, NULL, NULL);
10560}
10561
12e2a5fd 10562/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
10563
10564static int
0d866f62
TT
10565remote_hostio_pwrite (struct target_ops *self,
10566 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
10567 ULONGEST offset, int *remote_errno)
10568{
10569 struct remote_state *rs = get_remote_state ();
10570 char *p = rs->buf;
10571 int left = get_remote_packet_size ();
10572 int out_len;
10573
80152258
PA
10574 readahead_cache_invalidate_fd (fd);
10575
a6b151f1
DJ
10576 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10577
10578 remote_buffer_add_int (&p, &left, fd);
10579 remote_buffer_add_string (&p, &left, ",");
10580
10581 remote_buffer_add_int (&p, &left, offset);
10582 remote_buffer_add_string (&p, &left, ",");
10583
124e13d9 10584 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
10585 get_remote_packet_size () - (p - rs->buf));
10586
10587 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10588 remote_errno, NULL, NULL);
10589}
10590
80152258
PA
10591/* Helper for the implementation of to_fileio_pread. Read the file
10592 from the remote side with vFile:pread. */
a6b151f1
DJ
10593
10594static int
80152258
PA
10595remote_hostio_pread_vFile (struct target_ops *self,
10596 int fd, gdb_byte *read_buf, int len,
10597 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
10598{
10599 struct remote_state *rs = get_remote_state ();
10600 char *p = rs->buf;
10601 char *attachment;
10602 int left = get_remote_packet_size ();
10603 int ret, attachment_len;
10604 int read_len;
10605
10606 remote_buffer_add_string (&p, &left, "vFile:pread:");
10607
10608 remote_buffer_add_int (&p, &left, fd);
10609 remote_buffer_add_string (&p, &left, ",");
10610
10611 remote_buffer_add_int (&p, &left, len);
10612 remote_buffer_add_string (&p, &left, ",");
10613
10614 remote_buffer_add_int (&p, &left, offset);
10615
10616 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10617 remote_errno, &attachment,
10618 &attachment_len);
10619
10620 if (ret < 0)
10621 return ret;
10622
bc20a4af 10623 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
10624 read_buf, len);
10625 if (read_len != ret)
10626 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10627
10628 return ret;
10629}
10630
80152258
PA
10631/* Serve pread from the readahead cache. Returns number of bytes
10632 read, or 0 if the request can't be served from the cache. */
10633
10634static int
10635remote_hostio_pread_from_cache (struct remote_state *rs,
10636 int fd, gdb_byte *read_buf, size_t len,
10637 ULONGEST offset)
10638{
10639 struct readahead_cache *cache = &rs->readahead_cache;
10640
10641 if (cache->fd == fd
10642 && cache->offset <= offset
10643 && offset < cache->offset + cache->bufsize)
10644 {
10645 ULONGEST max = cache->offset + cache->bufsize;
10646
10647 if (offset + len > max)
10648 len = max - offset;
10649
10650 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10651 return len;
10652 }
10653
10654 return 0;
10655}
10656
10657/* Implementation of to_fileio_pread. */
10658
10659static int
10660remote_hostio_pread (struct target_ops *self,
10661 int fd, gdb_byte *read_buf, int len,
10662 ULONGEST offset, int *remote_errno)
10663{
10664 int ret;
10665 struct remote_state *rs = get_remote_state ();
10666 struct readahead_cache *cache = &rs->readahead_cache;
10667
10668 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10669 if (ret > 0)
10670 {
10671 cache->hit_count++;
10672
10673 if (remote_debug)
10674 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10675 pulongest (cache->hit_count));
10676 return ret;
10677 }
10678
10679 cache->miss_count++;
10680 if (remote_debug)
10681 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10682 pulongest (cache->miss_count));
10683
10684 cache->fd = fd;
10685 cache->offset = offset;
10686 cache->bufsize = get_remote_packet_size ();
10687 cache->buf = xrealloc (cache->buf, cache->bufsize);
10688
10689 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10690 cache->offset, remote_errno);
10691 if (ret <= 0)
10692 {
10693 readahead_cache_invalidate_fd (fd);
10694 return ret;
10695 }
10696
10697 cache->bufsize = ret;
10698 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10699}
10700
12e2a5fd 10701/* Implementation of to_fileio_close. */
a6b151f1
DJ
10702
10703static int
df39ea25 10704remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
10705{
10706 struct remote_state *rs = get_remote_state ();
10707 char *p = rs->buf;
10708 int left = get_remote_packet_size () - 1;
10709
80152258
PA
10710 readahead_cache_invalidate_fd (fd);
10711
a6b151f1
DJ
10712 remote_buffer_add_string (&p, &left, "vFile:close:");
10713
10714 remote_buffer_add_int (&p, &left, fd);
10715
10716 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10717 remote_errno, NULL, NULL);
10718}
10719
12e2a5fd 10720/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
10721
10722static int
dbbca37d 10723remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
10724 struct inferior *inf, const char *filename,
10725 int *remote_errno)
a6b151f1
DJ
10726{
10727 struct remote_state *rs = get_remote_state ();
10728 char *p = rs->buf;
10729 int left = get_remote_packet_size () - 1;
10730
15a201c8
GB
10731 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10732 return -1;
10733
a6b151f1
DJ
10734 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10735
10736 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10737 strlen (filename));
10738
10739 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10740 remote_errno, NULL, NULL);
10741}
10742
12e2a5fd 10743/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
10744
10745static char *
fab5aa7c 10746remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
10747 struct inferior *inf, const char *filename,
10748 int *remote_errno)
b9e7b9c3
UW
10749{
10750 struct remote_state *rs = get_remote_state ();
10751 char *p = rs->buf;
10752 char *attachment;
10753 int left = get_remote_packet_size ();
10754 int len, attachment_len;
10755 int read_len;
10756 char *ret;
10757
15a201c8
GB
10758 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10759 return NULL;
10760
b9e7b9c3
UW
10761 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10762
10763 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10764 strlen (filename));
10765
10766 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10767 remote_errno, &attachment,
10768 &attachment_len);
10769
10770 if (len < 0)
10771 return NULL;
10772
10773 ret = xmalloc (len + 1);
10774
bc20a4af
PA
10775 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10776 (gdb_byte *) ret, len);
b9e7b9c3
UW
10777 if (read_len != len)
10778 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10779
10780 ret[len] = '\0';
10781 return ret;
10782}
10783
12e2a5fd 10784/* Implementation of to_fileio_fstat. */
0a93529c
GB
10785
10786static int
10787remote_hostio_fstat (struct target_ops *self,
10788 int fd, struct stat *st,
10789 int *remote_errno)
10790{
10791 struct remote_state *rs = get_remote_state ();
10792 char *p = rs->buf;
10793 int left = get_remote_packet_size ();
10794 int attachment_len, ret;
10795 char *attachment;
10796 struct fio_stat fst;
10797 int read_len;
10798
464b0089
GB
10799 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10800
10801 remote_buffer_add_int (&p, &left, fd);
10802
10803 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10804 remote_errno, &attachment,
10805 &attachment_len);
10806 if (ret < 0)
0a93529c 10807 {
464b0089
GB
10808 if (*remote_errno != FILEIO_ENOSYS)
10809 return ret;
10810
0a93529c
GB
10811 /* Strictly we should return -1, ENOSYS here, but when
10812 "set sysroot remote:" was implemented in August 2008
10813 BFD's need for a stat function was sidestepped with
10814 this hack. This was not remedied until March 2015
10815 so we retain the previous behavior to avoid breaking
10816 compatibility.
10817
10818 Note that the memset is a March 2015 addition; older
10819 GDBs set st_size *and nothing else* so the structure
10820 would have garbage in all other fields. This might
10821 break something but retaining the previous behavior
10822 here would be just too wrong. */
10823
10824 memset (st, 0, sizeof (struct stat));
10825 st->st_size = INT_MAX;
10826 return 0;
10827 }
10828
0a93529c
GB
10829 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10830 (gdb_byte *) &fst, sizeof (fst));
10831
10832 if (read_len != ret)
10833 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10834
10835 if (read_len != sizeof (fst))
10836 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10837 read_len, (int) sizeof (fst));
10838
10839 remote_fileio_to_host_stat (&fst, st);
10840
10841 return 0;
10842}
10843
12e2a5fd 10844/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
10845
10846static int
10847remote_filesystem_is_local (struct target_ops *self)
10848{
10849 /* Valgrind GDB presents itself as a remote target but works
10850 on the local filesystem: it does not implement remote get
10851 and users are not expected to set a sysroot. To handle
10852 this case we treat the remote filesystem as local if the
10853 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
10854 does not support vFile:open. */
a3be80c3 10855 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
10856 {
10857 enum packet_support ps = packet_support (PACKET_vFile_open);
10858
10859 if (ps == PACKET_SUPPORT_UNKNOWN)
10860 {
10861 int fd, remote_errno;
10862
10863 /* Try opening a file to probe support. The supplied
10864 filename is irrelevant, we only care about whether
10865 the stub recognizes the packet or not. */
07c138c8 10866 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 10867 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
10868 &remote_errno);
10869
10870 if (fd >= 0)
10871 remote_hostio_close (self, fd, &remote_errno);
10872
10873 ps = packet_support (PACKET_vFile_open);
10874 }
10875
10876 if (ps == PACKET_DISABLE)
10877 {
10878 static int warning_issued = 0;
10879
10880 if (!warning_issued)
10881 {
10882 warning (_("remote target does not support file"
10883 " transfer, attempting to access files"
10884 " from local filesystem."));
10885 warning_issued = 1;
10886 }
10887
10888 return 1;
10889 }
10890 }
10891
10892 return 0;
10893}
10894
a6b151f1
DJ
10895static int
10896remote_fileio_errno_to_host (int errnum)
10897{
10898 switch (errnum)
10899 {
10900 case FILEIO_EPERM:
10901 return EPERM;
10902 case FILEIO_ENOENT:
10903 return ENOENT;
10904 case FILEIO_EINTR:
10905 return EINTR;
10906 case FILEIO_EIO:
10907 return EIO;
10908 case FILEIO_EBADF:
10909 return EBADF;
10910 case FILEIO_EACCES:
10911 return EACCES;
10912 case FILEIO_EFAULT:
10913 return EFAULT;
10914 case FILEIO_EBUSY:
10915 return EBUSY;
10916 case FILEIO_EEXIST:
10917 return EEXIST;
10918 case FILEIO_ENODEV:
10919 return ENODEV;
10920 case FILEIO_ENOTDIR:
10921 return ENOTDIR;
10922 case FILEIO_EISDIR:
10923 return EISDIR;
10924 case FILEIO_EINVAL:
10925 return EINVAL;
10926 case FILEIO_ENFILE:
10927 return ENFILE;
10928 case FILEIO_EMFILE:
10929 return EMFILE;
10930 case FILEIO_EFBIG:
10931 return EFBIG;
10932 case FILEIO_ENOSPC:
10933 return ENOSPC;
10934 case FILEIO_ESPIPE:
10935 return ESPIPE;
10936 case FILEIO_EROFS:
10937 return EROFS;
10938 case FILEIO_ENOSYS:
10939 return ENOSYS;
10940 case FILEIO_ENAMETOOLONG:
10941 return ENAMETOOLONG;
10942 }
10943 return -1;
10944}
10945
10946static char *
10947remote_hostio_error (int errnum)
10948{
10949 int host_error = remote_fileio_errno_to_host (errnum);
10950
10951 if (host_error == -1)
10952 error (_("Unknown remote I/O error %d"), errnum);
10953 else
10954 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10955}
10956
a6b151f1
DJ
10957static void
10958remote_hostio_close_cleanup (void *opaque)
10959{
10960 int fd = *(int *) opaque;
10961 int remote_errno;
10962
df39ea25 10963 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
10964}
10965
10966void
10967remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10968{
10969 struct cleanup *back_to, *close_cleanup;
10970 int retcode, fd, remote_errno, bytes, io_size;
10971 FILE *file;
10972 gdb_byte *buffer;
10973 int bytes_in_buffer;
10974 int saw_eof;
10975 ULONGEST offset;
5d93a237 10976 struct remote_state *rs = get_remote_state ();
a6b151f1 10977
5d93a237 10978 if (!rs->remote_desc)
a6b151f1
DJ
10979 error (_("command can only be used with remote target"));
10980
614c279d 10981 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10982 if (file == NULL)
10983 perror_with_name (local_file);
7c8a8b04 10984 back_to = make_cleanup_fclose (file);
a6b151f1 10985
07c138c8 10986 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 10987 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 10988 | FILEIO_O_TRUNC),
4313b8c0 10989 0700, 0, &remote_errno);
a6b151f1
DJ
10990 if (fd == -1)
10991 remote_hostio_error (remote_errno);
10992
10993 /* Send up to this many bytes at once. They won't all fit in the
10994 remote packet limit, so we'll transfer slightly fewer. */
10995 io_size = get_remote_packet_size ();
10996 buffer = xmalloc (io_size);
10997 make_cleanup (xfree, buffer);
10998
10999 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11000
11001 bytes_in_buffer = 0;
11002 saw_eof = 0;
11003 offset = 0;
11004 while (bytes_in_buffer || !saw_eof)
11005 {
11006 if (!saw_eof)
11007 {
3e43a32a
MS
11008 bytes = fread (buffer + bytes_in_buffer, 1,
11009 io_size - bytes_in_buffer,
a6b151f1
DJ
11010 file);
11011 if (bytes == 0)
11012 {
11013 if (ferror (file))
11014 error (_("Error reading %s."), local_file);
11015 else
11016 {
11017 /* EOF. Unless there is something still in the
11018 buffer from the last iteration, we are done. */
11019 saw_eof = 1;
11020 if (bytes_in_buffer == 0)
11021 break;
11022 }
11023 }
11024 }
11025 else
11026 bytes = 0;
11027
11028 bytes += bytes_in_buffer;
11029 bytes_in_buffer = 0;
11030
0d866f62
TT
11031 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11032 fd, buffer, bytes,
3e43a32a 11033 offset, &remote_errno);
a6b151f1
DJ
11034
11035 if (retcode < 0)
11036 remote_hostio_error (remote_errno);
11037 else if (retcode == 0)
11038 error (_("Remote write of %d bytes returned 0!"), bytes);
11039 else if (retcode < bytes)
11040 {
11041 /* Short write. Save the rest of the read data for the next
11042 write. */
11043 bytes_in_buffer = bytes - retcode;
11044 memmove (buffer, buffer + retcode, bytes_in_buffer);
11045 }
11046
11047 offset += retcode;
11048 }
11049
11050 discard_cleanups (close_cleanup);
df39ea25 11051 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11052 remote_hostio_error (remote_errno);
11053
11054 if (from_tty)
11055 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11056 do_cleanups (back_to);
11057}
11058
11059void
11060remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11061{
11062 struct cleanup *back_to, *close_cleanup;
cea39f65 11063 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11064 FILE *file;
11065 gdb_byte *buffer;
11066 ULONGEST offset;
5d93a237 11067 struct remote_state *rs = get_remote_state ();
a6b151f1 11068
5d93a237 11069 if (!rs->remote_desc)
a6b151f1
DJ
11070 error (_("command can only be used with remote target"));
11071
07c138c8 11072 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11073 remote_file, FILEIO_O_RDONLY, 0, 0,
11074 &remote_errno);
a6b151f1
DJ
11075 if (fd == -1)
11076 remote_hostio_error (remote_errno);
11077
614c279d 11078 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11079 if (file == NULL)
11080 perror_with_name (local_file);
7c8a8b04 11081 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11082
11083 /* Send up to this many bytes at once. They won't all fit in the
11084 remote packet limit, so we'll transfer slightly fewer. */
11085 io_size = get_remote_packet_size ();
11086 buffer = xmalloc (io_size);
11087 make_cleanup (xfree, buffer);
11088
11089 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11090
11091 offset = 0;
11092 while (1)
11093 {
a3be983c
TT
11094 bytes = remote_hostio_pread (find_target_at (process_stratum),
11095 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11096 if (bytes == 0)
11097 /* Success, but no bytes, means end-of-file. */
11098 break;
11099 if (bytes == -1)
11100 remote_hostio_error (remote_errno);
11101
11102 offset += bytes;
11103
11104 bytes = fwrite (buffer, 1, bytes, file);
11105 if (bytes == 0)
11106 perror_with_name (local_file);
11107 }
11108
11109 discard_cleanups (close_cleanup);
df39ea25 11110 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11111 remote_hostio_error (remote_errno);
11112
11113 if (from_tty)
11114 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11115 do_cleanups (back_to);
11116}
11117
11118void
11119remote_file_delete (const char *remote_file, int from_tty)
11120{
11121 int retcode, remote_errno;
5d93a237 11122 struct remote_state *rs = get_remote_state ();
a6b151f1 11123
5d93a237 11124 if (!rs->remote_desc)
a6b151f1
DJ
11125 error (_("command can only be used with remote target"));
11126
dbbca37d 11127 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11128 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11129 if (retcode == -1)
11130 remote_hostio_error (remote_errno);
11131
11132 if (from_tty)
11133 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11134}
11135
11136static void
11137remote_put_command (char *args, int from_tty)
11138{
11139 struct cleanup *back_to;
11140 char **argv;
11141
d1a41061
PP
11142 if (args == NULL)
11143 error_no_arg (_("file to put"));
11144
11145 argv = gdb_buildargv (args);
a6b151f1
DJ
11146 back_to = make_cleanup_freeargv (argv);
11147 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11148 error (_("Invalid parameters to remote put"));
11149
11150 remote_file_put (argv[0], argv[1], from_tty);
11151
11152 do_cleanups (back_to);
11153}
11154
11155static void
11156remote_get_command (char *args, int from_tty)
11157{
11158 struct cleanup *back_to;
11159 char **argv;
11160
d1a41061
PP
11161 if (args == NULL)
11162 error_no_arg (_("file to get"));
11163
11164 argv = gdb_buildargv (args);
a6b151f1
DJ
11165 back_to = make_cleanup_freeargv (argv);
11166 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11167 error (_("Invalid parameters to remote get"));
11168
11169 remote_file_get (argv[0], argv[1], from_tty);
11170
11171 do_cleanups (back_to);
11172}
11173
11174static void
11175remote_delete_command (char *args, int from_tty)
11176{
11177 struct cleanup *back_to;
11178 char **argv;
11179
d1a41061
PP
11180 if (args == NULL)
11181 error_no_arg (_("file to delete"));
11182
11183 argv = gdb_buildargv (args);
a6b151f1
DJ
11184 back_to = make_cleanup_freeargv (argv);
11185 if (argv[0] == NULL || argv[1] != NULL)
11186 error (_("Invalid parameters to remote delete"));
11187
11188 remote_file_delete (argv[0], from_tty);
11189
11190 do_cleanups (back_to);
11191}
11192
11193static void
11194remote_command (char *args, int from_tty)
11195{
635c7e8a 11196 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11197}
11198
b2175913 11199static int
19db3e69 11200remote_can_execute_reverse (struct target_ops *self)
b2175913 11201{
4082afcc
PA
11202 if (packet_support (PACKET_bs) == PACKET_ENABLE
11203 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11204 return 1;
11205 else
11206 return 0;
b2175913
MS
11207}
11208
74531fed 11209static int
2a9a2795 11210remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11211{
11212 return 1;
11213}
11214
03583c20 11215static int
2bfc0540 11216remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11217{
11218 /* Only supported in extended mode. */
11219 return 0;
11220}
11221
8a305172 11222static int
86ce2668 11223remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11224{
11225 struct remote_state *rs = get_remote_state ();
a744cf53 11226
901f9912
UW
11227 /* Only extended-remote handles being attached to multiple
11228 processes, even though plain remote can use the multi-process
11229 thread id extensions, so that GDB knows the target process's
11230 PID. */
11231 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
11232}
11233
70221824 11234static int
782b2b07
SS
11235remote_supports_cond_tracepoints (void)
11236{
4082afcc 11237 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11238}
11239
3788aec7 11240static int
efcc2da7 11241remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11242{
4082afcc 11243 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11244}
11245
70221824 11246static int
7a697b8d
SS
11247remote_supports_fast_tracepoints (void)
11248{
4082afcc 11249 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11250}
11251
0fb4aa4b
PA
11252static int
11253remote_supports_static_tracepoints (void)
11254{
4082afcc 11255 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11256}
11257
1e4d1764
YQ
11258static int
11259remote_supports_install_in_trace (void)
11260{
4082afcc 11261 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11262}
11263
d248b706 11264static int
7d178d6a 11265remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11266{
4082afcc
PA
11267 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11268 == PACKET_ENABLE);
d248b706
KY
11269}
11270
3065dfb6 11271static int
6de37a3a 11272remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11273{
4082afcc 11274 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11275}
11276
d3ce09f5 11277static int
78eff0ec 11278remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11279{
4082afcc 11280 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11281}
11282
35b1e5cc 11283static void
ecae04e1 11284remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11285{
11286 putpkt ("QTinit");
11287 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11288 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11289 error (_("Target does not support this command."));
11290}
11291
11292static void free_actions_list (char **actions_list);
11293static void free_actions_list_cleanup_wrapper (void *);
11294static void
11295free_actions_list_cleanup_wrapper (void *al)
11296{
11297 free_actions_list (al);
11298}
11299
11300static void
11301free_actions_list (char **actions_list)
11302{
11303 int ndx;
11304
11305 if (actions_list == 0)
11306 return;
11307
11308 for (ndx = 0; actions_list[ndx]; ndx++)
11309 xfree (actions_list[ndx]);
11310
11311 xfree (actions_list);
11312}
11313
409873ef
SS
11314/* Recursive routine to walk through command list including loops, and
11315 download packets for each command. */
11316
11317static void
11318remote_download_command_source (int num, ULONGEST addr,
11319 struct command_line *cmds)
11320{
11321 struct remote_state *rs = get_remote_state ();
11322 struct command_line *cmd;
11323
11324 for (cmd = cmds; cmd; cmd = cmd->next)
11325 {
0df8b418 11326 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11327 strcpy (rs->buf, "QTDPsrc:");
11328 encode_source_string (num, addr, "cmd", cmd->line,
11329 rs->buf + strlen (rs->buf),
11330 rs->buf_size - strlen (rs->buf));
11331 putpkt (rs->buf);
11332 remote_get_noisy_reply (&target_buf, &target_buf_size);
11333 if (strcmp (target_buf, "OK"))
11334 warning (_("Target does not support source download."));
11335
11336 if (cmd->control_type == while_control
11337 || cmd->control_type == while_stepping_control)
11338 {
11339 remote_download_command_source (num, addr, *cmd->body_list);
11340
0df8b418 11341 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11342 strcpy (rs->buf, "QTDPsrc:");
11343 encode_source_string (num, addr, "cmd", "end",
11344 rs->buf + strlen (rs->buf),
11345 rs->buf_size - strlen (rs->buf));
11346 putpkt (rs->buf);
11347 remote_get_noisy_reply (&target_buf, &target_buf_size);
11348 if (strcmp (target_buf, "OK"))
11349 warning (_("Target does not support source download."));
11350 }
11351 }
11352}
11353
35b1e5cc 11354static void
548f7808 11355remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11356{
bba74b36 11357#define BUF_SIZE 2048
e8ba3115 11358
35b1e5cc 11359 CORE_ADDR tpaddr;
409873ef 11360 char addrbuf[40];
bba74b36 11361 char buf[BUF_SIZE];
35b1e5cc
SS
11362 char **tdp_actions;
11363 char **stepping_actions;
11364 int ndx;
11365 struct cleanup *old_chain = NULL;
11366 struct agent_expr *aexpr;
11367 struct cleanup *aexpr_chain = NULL;
11368 char *pkt;
e8ba3115 11369 struct breakpoint *b = loc->owner;
d9b3f62e 11370 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11371
dc673c81 11372 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11373 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11374 tdp_actions);
11375 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11376 stepping_actions);
11377
11378 tpaddr = loc->address;
11379 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11380 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11381 addrbuf, /* address */
11382 (b->enable_state == bp_enabled ? 'E' : 'D'),
11383 t->step_count, t->pass_count);
e8ba3115
YQ
11384 /* Fast tracepoints are mostly handled by the target, but we can
11385 tell the target how big of an instruction block should be moved
11386 around. */
11387 if (b->type == bp_fast_tracepoint)
11388 {
11389 /* Only test for support at download time; we may not know
11390 target capabilities at definition time. */
11391 if (remote_supports_fast_tracepoints ())
35b1e5cc 11392 {
6b940e6a
PL
11393 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11394 NULL))
bba74b36 11395 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11396 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11397 else
e8ba3115
YQ
11398 /* If it passed validation at definition but fails now,
11399 something is very wrong. */
11400 internal_error (__FILE__, __LINE__,
11401 _("Fast tracepoint not "
11402 "valid during download"));
35b1e5cc 11403 }
e8ba3115
YQ
11404 else
11405 /* Fast tracepoints are functionally identical to regular
11406 tracepoints, so don't take lack of support as a reason to
11407 give up on the trace run. */
11408 warning (_("Target does not support fast tracepoints, "
11409 "downloading %d as regular tracepoint"), b->number);
11410 }
11411 else if (b->type == bp_static_tracepoint)
11412 {
11413 /* Only test for support at download time; we may not know
11414 target capabilities at definition time. */
11415 if (remote_supports_static_tracepoints ())
0fb4aa4b 11416 {
e8ba3115 11417 struct static_tracepoint_marker marker;
0fb4aa4b 11418
e8ba3115
YQ
11419 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11420 strcat (buf, ":S");
0fb4aa4b 11421 else
e8ba3115 11422 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11423 }
e8ba3115
YQ
11424 else
11425 /* Fast tracepoints are functionally identical to regular
11426 tracepoints, so don't take lack of support as a reason
11427 to give up on the trace run. */
11428 error (_("Target does not support static tracepoints"));
11429 }
11430 /* If the tracepoint has a conditional, make it into an agent
11431 expression and append to the definition. */
11432 if (loc->cond)
11433 {
11434 /* Only test support at download time, we may not know target
11435 capabilities at definition time. */
11436 if (remote_supports_cond_tracepoints ())
35b1e5cc 11437 {
e8ba3115
YQ
11438 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11439 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11440 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11441 aexpr->len);
e8ba3115
YQ
11442 pkt = buf + strlen (buf);
11443 for (ndx = 0; ndx < aexpr->len; ++ndx)
11444 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11445 *pkt = '\0';
11446 do_cleanups (aexpr_chain);
35b1e5cc 11447 }
e8ba3115
YQ
11448 else
11449 warning (_("Target does not support conditional tracepoints, "
11450 "ignoring tp %d cond"), b->number);
11451 }
35b1e5cc 11452
d9b3f62e 11453 if (b->commands || *default_collect)
e8ba3115
YQ
11454 strcat (buf, "-");
11455 putpkt (buf);
11456 remote_get_noisy_reply (&target_buf, &target_buf_size);
11457 if (strcmp (target_buf, "OK"))
11458 error (_("Target does not support tracepoints."));
35b1e5cc 11459
e8ba3115
YQ
11460 /* do_single_steps (t); */
11461 if (tdp_actions)
11462 {
11463 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11464 {
e8ba3115 11465 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11466 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11467 b->number, addrbuf, /* address */
11468 tdp_actions[ndx],
11469 ((tdp_actions[ndx + 1] || stepping_actions)
11470 ? '-' : 0));
e8ba3115
YQ
11471 putpkt (buf);
11472 remote_get_noisy_reply (&target_buf,
11473 &target_buf_size);
11474 if (strcmp (target_buf, "OK"))
11475 error (_("Error on target while setting tracepoints."));
35b1e5cc 11476 }
e8ba3115
YQ
11477 }
11478 if (stepping_actions)
11479 {
11480 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11481 {
e8ba3115 11482 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11483 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11484 b->number, addrbuf, /* address */
11485 ((ndx == 0) ? "S" : ""),
11486 stepping_actions[ndx],
11487 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11488 putpkt (buf);
11489 remote_get_noisy_reply (&target_buf,
11490 &target_buf_size);
11491 if (strcmp (target_buf, "OK"))
11492 error (_("Error on target while setting tracepoints."));
35b1e5cc 11493 }
e8ba3115 11494 }
409873ef 11495
4082afcc 11496 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11497 {
f00aae0f 11498 if (b->location != NULL)
409873ef 11499 {
e8ba3115 11500 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11501 encode_source_string (b->number, loc->address, "at",
11502 event_location_to_string (b->location),
11503 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11504 putpkt (buf);
11505 remote_get_noisy_reply (&target_buf, &target_buf_size);
11506 if (strcmp (target_buf, "OK"))
11507 warning (_("Target does not support source download."));
409873ef 11508 }
e8ba3115
YQ
11509 if (b->cond_string)
11510 {
11511 strcpy (buf, "QTDPsrc:");
11512 encode_source_string (b->number, loc->address,
11513 "cond", b->cond_string, buf + strlen (buf),
11514 2048 - strlen (buf));
11515 putpkt (buf);
11516 remote_get_noisy_reply (&target_buf, &target_buf_size);
11517 if (strcmp (target_buf, "OK"))
11518 warning (_("Target does not support source download."));
11519 }
11520 remote_download_command_source (b->number, loc->address,
11521 breakpoint_commands (b));
35b1e5cc 11522 }
e8ba3115
YQ
11523
11524 do_cleanups (old_chain);
35b1e5cc
SS
11525}
11526
1e4d1764 11527static int
a52a8357 11528remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 11529{
1e51243a
PA
11530 struct remote_state *rs = get_remote_state ();
11531 struct trace_status *ts;
11532 int status;
11533
11534 /* Don't try to install tracepoints until we've relocated our
11535 symbols, and fetched and merged the target's tracepoint list with
11536 ours. */
11537 if (rs->starting_up)
11538 return 0;
11539
11540 ts = current_trace_status ();
8bd200f1 11541 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
11542
11543 if (status == -1 || !ts->running_known || !ts->running)
11544 return 0;
11545
11546 /* If we are in a tracing experiment, but remote stub doesn't support
11547 installing tracepoint in trace, we have to return. */
11548 if (!remote_supports_install_in_trace ())
11549 return 0;
11550
11551 return 1;
11552}
11553
11554
35b1e5cc 11555static void
559d2b81
TT
11556remote_download_trace_state_variable (struct target_ops *self,
11557 struct trace_state_variable *tsv)
35b1e5cc
SS
11558{
11559 struct remote_state *rs = get_remote_state ();
00bf0b85 11560 char *p;
35b1e5cc 11561
bba74b36
YQ
11562 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11563 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11564 tsv->builtin);
00bf0b85
SS
11565 p = rs->buf + strlen (rs->buf);
11566 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11567 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 11568 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 11569 *p++ = '\0';
35b1e5cc
SS
11570 putpkt (rs->buf);
11571 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11572 if (*target_buf == '\0')
11573 error (_("Target does not support this command."));
11574 if (strcmp (target_buf, "OK") != 0)
11575 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
11576}
11577
d248b706 11578static void
46670d57
TT
11579remote_enable_tracepoint (struct target_ops *self,
11580 struct bp_location *location)
d248b706
KY
11581{
11582 struct remote_state *rs = get_remote_state ();
11583 char addr_buf[40];
11584
11585 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11586 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11587 location->owner->number, addr_buf);
d248b706
KY
11588 putpkt (rs->buf);
11589 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11590 if (*rs->buf == '\0')
11591 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11592 if (strcmp (rs->buf, "OK") != 0)
11593 error (_("Error on target while enabling tracepoint."));
11594}
11595
11596static void
780b049c
TT
11597remote_disable_tracepoint (struct target_ops *self,
11598 struct bp_location *location)
d248b706
KY
11599{
11600 struct remote_state *rs = get_remote_state ();
11601 char addr_buf[40];
11602
11603 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11604 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11605 location->owner->number, addr_buf);
d248b706
KY
11606 putpkt (rs->buf);
11607 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11608 if (*rs->buf == '\0')
11609 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11610 if (strcmp (rs->buf, "OK") != 0)
11611 error (_("Error on target while disabling tracepoint."));
11612}
11613
35b1e5cc 11614static void
583f9a86 11615remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
11616{
11617 asection *s;
81b9b86e 11618 bfd *abfd = NULL;
35b1e5cc 11619 bfd_size_type size;
608bcef2 11620 bfd_vma vma;
35b1e5cc 11621 int anysecs = 0;
c2fa21f1 11622 int offset = 0;
35b1e5cc
SS
11623
11624 if (!exec_bfd)
11625 return; /* No information to give. */
11626
11627 strcpy (target_buf, "QTro");
9779ab84 11628 offset = strlen (target_buf);
35b1e5cc
SS
11629 for (s = exec_bfd->sections; s; s = s->next)
11630 {
11631 char tmp1[40], tmp2[40];
c2fa21f1 11632 int sec_length;
35b1e5cc
SS
11633
11634 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 11635 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
11636 (s->flags & SEC_READONLY) == 0)
11637 continue;
11638
11639 anysecs = 1;
81b9b86e 11640 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 11641 size = bfd_get_section_size (s);
608bcef2
HZ
11642 sprintf_vma (tmp1, vma);
11643 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
11644 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11645 if (offset + sec_length + 1 > target_buf_size)
11646 {
4082afcc 11647 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 11648 warning (_("\
c2fa21f1
HZ
11649Too many sections for read-only sections definition packet."));
11650 break;
11651 }
bba74b36
YQ
11652 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11653 tmp1, tmp2);
c2fa21f1 11654 offset += sec_length;
35b1e5cc
SS
11655 }
11656 if (anysecs)
11657 {
11658 putpkt (target_buf);
11659 getpkt (&target_buf, &target_buf_size, 0);
11660 }
11661}
11662
11663static void
e2d1aae3 11664remote_trace_start (struct target_ops *self)
35b1e5cc
SS
11665{
11666 putpkt ("QTStart");
11667 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11668 if (*target_buf == '\0')
11669 error (_("Target does not support this command."));
11670 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11671 error (_("Bogus reply from target: %s"), target_buf);
11672}
11673
11674static int
8bd200f1 11675remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 11676{
953b98d1 11677 /* Initialize it just to avoid a GCC false warning. */
f652de6f 11678 char *p = NULL;
0df8b418 11679 /* FIXME we need to get register block size some other way. */
00bf0b85 11680 extern int trace_regblock_size;
bd3eecc3
PA
11681 enum packet_result result;
11682
4082afcc 11683 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 11684 return -1;
a744cf53 11685
00bf0b85
SS
11686 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11687
049dc89b
JK
11688 putpkt ("qTStatus");
11689
492d29ea 11690 TRY
67f41397
JK
11691 {
11692 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11693 }
492d29ea 11694 CATCH (ex, RETURN_MASK_ERROR)
67f41397 11695 {
598d3636
JK
11696 if (ex.error != TARGET_CLOSE_ERROR)
11697 {
11698 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11699 return -1;
11700 }
11701 throw_exception (ex);
67f41397 11702 }
492d29ea 11703 END_CATCH
00bf0b85 11704
bd3eecc3
PA
11705 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11706
00bf0b85 11707 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 11708 if (result == PACKET_UNKNOWN)
00bf0b85 11709 return -1;
35b1e5cc 11710
00bf0b85 11711 /* We're working with a live target. */
f5911ea1 11712 ts->filename = NULL;
00bf0b85 11713
00bf0b85 11714 if (*p++ != 'T')
35b1e5cc
SS
11715 error (_("Bogus trace status reply from target: %s"), target_buf);
11716
84cebc4a
YQ
11717 /* Function 'parse_trace_status' sets default value of each field of
11718 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
11719 parse_trace_status (p, ts);
11720
11721 return ts->running;
35b1e5cc
SS
11722}
11723
70221824 11724static void
db90e85c 11725remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
11726 struct uploaded_tp *utp)
11727{
11728 struct remote_state *rs = get_remote_state ();
f196051f
SS
11729 char *reply;
11730 struct bp_location *loc;
11731 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 11732 size_t size = get_remote_packet_size ();
f196051f
SS
11733
11734 if (tp)
11735 {
11736 tp->base.hit_count = 0;
11737 tp->traceframe_usage = 0;
11738 for (loc = tp->base.loc; loc; loc = loc->next)
11739 {
11740 /* If the tracepoint was never downloaded, don't go asking for
11741 any status. */
11742 if (tp->number_on_target == 0)
11743 continue;
bba74b36
YQ
11744 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11745 phex_nz (loc->address, 0));
f196051f
SS
11746 putpkt (rs->buf);
11747 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11748 if (reply && *reply)
11749 {
11750 if (*reply == 'V')
11751 parse_tracepoint_status (reply + 1, bp, utp);
11752 }
11753 }
11754 }
11755 else if (utp)
11756 {
11757 utp->hit_count = 0;
11758 utp->traceframe_usage = 0;
bba74b36
YQ
11759 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11760 phex_nz (utp->addr, 0));
f196051f
SS
11761 putpkt (rs->buf);
11762 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11763 if (reply && *reply)
11764 {
11765 if (*reply == 'V')
11766 parse_tracepoint_status (reply + 1, bp, utp);
11767 }
11768 }
11769}
11770
35b1e5cc 11771static void
74499f1b 11772remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
11773{
11774 putpkt ("QTStop");
11775 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11776 if (*target_buf == '\0')
11777 error (_("Target does not support this command."));
11778 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11779 error (_("Bogus reply from target: %s"), target_buf);
11780}
11781
11782static int
bd4c6793
TT
11783remote_trace_find (struct target_ops *self,
11784 enum trace_find_type type, int num,
cc5925ad 11785 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
11786 int *tpp)
11787{
11788 struct remote_state *rs = get_remote_state ();
bba74b36 11789 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
11790 char *p, *reply;
11791 int target_frameno = -1, target_tracept = -1;
11792
e6e4e701
PA
11793 /* Lookups other than by absolute frame number depend on the current
11794 trace selected, so make sure it is correct on the remote end
11795 first. */
11796 if (type != tfind_number)
11797 set_remote_traceframe ();
11798
35b1e5cc
SS
11799 p = rs->buf;
11800 strcpy (p, "QTFrame:");
11801 p = strchr (p, '\0');
11802 switch (type)
11803 {
11804 case tfind_number:
bba74b36 11805 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
11806 break;
11807 case tfind_pc:
bba74b36 11808 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
11809 break;
11810 case tfind_tp:
bba74b36 11811 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
11812 break;
11813 case tfind_range:
bba74b36
YQ
11814 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11815 phex_nz (addr2, 0));
35b1e5cc
SS
11816 break;
11817 case tfind_outside:
bba74b36
YQ
11818 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11819 phex_nz (addr2, 0));
35b1e5cc
SS
11820 break;
11821 default:
9b20d036 11822 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
11823 }
11824
11825 putpkt (rs->buf);
2f65bcb7 11826 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
11827 if (*reply == '\0')
11828 error (_("Target does not support this command."));
35b1e5cc
SS
11829
11830 while (reply && *reply)
11831 switch (*reply)
11832 {
11833 case 'F':
f197e0f1
VP
11834 p = ++reply;
11835 target_frameno = (int) strtol (p, &reply, 16);
11836 if (reply == p)
11837 error (_("Unable to parse trace frame number"));
e6e4e701
PA
11838 /* Don't update our remote traceframe number cache on failure
11839 to select a remote traceframe. */
f197e0f1
VP
11840 if (target_frameno == -1)
11841 return -1;
35b1e5cc
SS
11842 break;
11843 case 'T':
f197e0f1
VP
11844 p = ++reply;
11845 target_tracept = (int) strtol (p, &reply, 16);
11846 if (reply == p)
11847 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
11848 break;
11849 case 'O': /* "OK"? */
11850 if (reply[1] == 'K' && reply[2] == '\0')
11851 reply += 2;
11852 else
11853 error (_("Bogus reply from target: %s"), reply);
11854 break;
11855 default:
11856 error (_("Bogus reply from target: %s"), reply);
11857 }
11858 if (tpp)
11859 *tpp = target_tracept;
e6e4e701 11860
262e1174 11861 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
11862 return target_frameno;
11863}
11864
11865static int
4011015b
TT
11866remote_get_trace_state_variable_value (struct target_ops *self,
11867 int tsvnum, LONGEST *val)
35b1e5cc
SS
11868{
11869 struct remote_state *rs = get_remote_state ();
11870 char *reply;
11871 ULONGEST uval;
11872
e6e4e701
PA
11873 set_remote_traceframe ();
11874
bba74b36 11875 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
11876 putpkt (rs->buf);
11877 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11878 if (reply && *reply)
11879 {
11880 if (*reply == 'V')
11881 {
11882 unpack_varlen_hex (reply + 1, &uval);
11883 *val = (LONGEST) uval;
11884 return 1;
11885 }
11886 }
11887 return 0;
11888}
11889
00bf0b85 11890static int
dc3decaf 11891remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
11892{
11893 struct remote_state *rs = get_remote_state ();
11894 char *p, *reply;
11895
11896 p = rs->buf;
11897 strcpy (p, "QTSave:");
11898 p += strlen (p);
11899 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11900 error (_("Remote file name too long for trace save packet"));
9f1b45b0 11901 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
11902 *p++ = '\0';
11903 putpkt (rs->buf);
ad91cd99 11904 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 11905 if (*reply == '\0')
ad91cd99
PA
11906 error (_("Target does not support this command."));
11907 if (strcmp (reply, "OK") != 0)
11908 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
11909 return 0;
11910}
11911
11912/* This is basically a memory transfer, but needs to be its own packet
11913 because we don't know how the target actually organizes its trace
11914 memory, plus we want to be able to ask for as much as possible, but
11915 not be unhappy if we don't get as much as we ask for. */
11916
11917static LONGEST
88ee6f45
TT
11918remote_get_raw_trace_data (struct target_ops *self,
11919 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
11920{
11921 struct remote_state *rs = get_remote_state ();
11922 char *reply;
11923 char *p;
11924 int rslt;
11925
11926 p = rs->buf;
11927 strcpy (p, "qTBuffer:");
11928 p += strlen (p);
11929 p += hexnumstr (p, offset);
11930 *p++ = ',';
11931 p += hexnumstr (p, len);
11932 *p++ = '\0';
11933
11934 putpkt (rs->buf);
11935 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11936 if (reply && *reply)
11937 {
11938 /* 'l' by itself means we're at the end of the buffer and
11939 there is nothing more to get. */
11940 if (*reply == 'l')
11941 return 0;
11942
11943 /* Convert the reply into binary. Limit the number of bytes to
11944 convert according to our passed-in buffer size, rather than
11945 what was returned in the packet; if the target is
11946 unexpectedly generous and gives us a bigger reply than we
11947 asked for, we don't want to crash. */
11948 rslt = hex2bin (target_buf, buf, len);
11949 return rslt;
11950 }
11951
11952 /* Something went wrong, flag as an error. */
11953 return -1;
11954}
11955
35b1e5cc 11956static void
37b25738 11957remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11958{
11959 struct remote_state *rs = get_remote_state ();
11960
4082afcc 11961 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 11962 {
ad91cd99
PA
11963 char *reply;
11964
bba74b36 11965 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11966 putpkt (rs->buf);
ad91cd99
PA
11967 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11968 if (*reply == '\0')
33da3f1c 11969 error (_("Target does not support this command."));
ad91cd99
PA
11970 if (strcmp (reply, "OK") != 0)
11971 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11972 }
11973 else if (val)
11974 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11975}
11976
dc146f7c
VP
11977static int
11978remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11979{
11980 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11981
fe978cb0
PA
11982 if (info && info->priv)
11983 return info->priv->core;
dc146f7c
VP
11984 return -1;
11985}
11986
4daf5ac0 11987static void
736d5b1f 11988remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11989{
11990 struct remote_state *rs = get_remote_state ();
ad91cd99 11991 char *reply;
4daf5ac0 11992
bba74b36 11993 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11994 putpkt (rs->buf);
ad91cd99
PA
11995 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11996 if (*reply == '\0')
4daf5ac0 11997 error (_("Target does not support this command."));
ad91cd99
PA
11998 if (strcmp (reply, "OK") != 0)
11999 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12000}
12001
b3b9301e 12002static struct traceframe_info *
a893e81f 12003remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12004{
12005 char *text;
12006
12007 text = target_read_stralloc (&current_target,
12008 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12009 if (text != NULL)
12010 {
12011 struct traceframe_info *info;
12012 struct cleanup *back_to = make_cleanup (xfree, text);
12013
12014 info = parse_traceframe_info (text);
12015 do_cleanups (back_to);
12016 return info;
12017 }
12018
12019 return NULL;
12020}
12021
405f8e94
SS
12022/* Handle the qTMinFTPILen packet. Returns the minimum length of
12023 instruction on which a fast tracepoint may be placed. Returns -1
12024 if the packet is not supported, and 0 if the minimum instruction
12025 length is unknown. */
12026
12027static int
0e67620a 12028remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12029{
12030 struct remote_state *rs = get_remote_state ();
12031 char *reply;
12032
e886a173
PA
12033 /* If we're not debugging a process yet, the IPA can't be
12034 loaded. */
12035 if (!target_has_execution)
12036 return 0;
12037
12038 /* Make sure the remote is pointing at the right process. */
12039 set_general_process ();
12040
bba74b36 12041 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12042 putpkt (rs->buf);
12043 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12044 if (*reply == '\0')
12045 return -1;
12046 else
12047 {
12048 ULONGEST min_insn_len;
12049
12050 unpack_varlen_hex (reply, &min_insn_len);
12051
12052 return (int) min_insn_len;
12053 }
12054}
12055
f6f899bf 12056static void
4da384be 12057remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12058{
4082afcc 12059 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12060 {
12061 struct remote_state *rs = get_remote_state ();
12062 char *buf = rs->buf;
12063 char *endbuf = rs->buf + get_remote_packet_size ();
12064 enum packet_result result;
12065
12066 gdb_assert (val >= 0 || val == -1);
12067 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12068 /* Send -1 as literal "-1" to avoid host size dependency. */
12069 if (val < 0)
12070 {
12071 *buf++ = '-';
12072 buf += hexnumstr (buf, (ULONGEST) -val);
12073 }
12074 else
12075 buf += hexnumstr (buf, (ULONGEST) val);
12076
12077 putpkt (rs->buf);
12078 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12079 result = packet_ok (rs->buf,
12080 &remote_protocol_packets[PACKET_QTBuffer_size]);
12081
12082 if (result != PACKET_OK)
12083 warning (_("Bogus reply from target: %s"), rs->buf);
12084 }
12085}
12086
f196051f 12087static int
d9e68a2c
TT
12088remote_set_trace_notes (struct target_ops *self,
12089 const char *user, const char *notes,
ca623f82 12090 const char *stop_notes)
f196051f
SS
12091{
12092 struct remote_state *rs = get_remote_state ();
12093 char *reply;
12094 char *buf = rs->buf;
12095 char *endbuf = rs->buf + get_remote_packet_size ();
12096 int nbytes;
12097
12098 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12099 if (user)
12100 {
12101 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12102 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12103 buf += 2 * nbytes;
12104 *buf++ = ';';
12105 }
12106 if (notes)
12107 {
12108 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12109 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12110 buf += 2 * nbytes;
12111 *buf++ = ';';
12112 }
12113 if (stop_notes)
12114 {
12115 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12116 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12117 buf += 2 * nbytes;
12118 *buf++ = ';';
12119 }
12120 /* Ensure the buffer is terminated. */
12121 *buf = '\0';
12122
12123 putpkt (rs->buf);
12124 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12125 if (*reply == '\0')
12126 return 0;
12127
12128 if (strcmp (reply, "OK") != 0)
12129 error (_("Bogus reply from target: %s"), reply);
12130
12131 return 1;
12132}
12133
d1feda86 12134static int
2c152180 12135remote_use_agent (struct target_ops *self, int use)
d1feda86 12136{
4082afcc 12137 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12138 {
12139 struct remote_state *rs = get_remote_state ();
12140
12141 /* If the stub supports QAgent. */
bba74b36 12142 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12143 putpkt (rs->buf);
12144 getpkt (&rs->buf, &rs->buf_size, 0);
12145
12146 if (strcmp (rs->buf, "OK") == 0)
12147 {
12148 use_agent = use;
12149 return 1;
12150 }
12151 }
12152
12153 return 0;
12154}
12155
12156static int
fe38f897 12157remote_can_use_agent (struct target_ops *self)
d1feda86 12158{
4082afcc 12159 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12160}
12161
9accd112
MM
12162struct btrace_target_info
12163{
12164 /* The ptid of the traced thread. */
12165 ptid_t ptid;
f4abbc16
MM
12166
12167 /* The obtained branch trace configuration. */
12168 struct btrace_config conf;
9accd112
MM
12169};
12170
f4abbc16
MM
12171/* Reset our idea of our target's btrace configuration. */
12172
12173static void
12174remote_btrace_reset (void)
12175{
12176 struct remote_state *rs = get_remote_state ();
12177
12178 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12179}
12180
9accd112
MM
12181/* Check whether the target supports branch tracing. */
12182
12183static int
043c3577 12184remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12185{
4082afcc 12186 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12187 return 0;
4082afcc 12188 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12189 return 0;
12190
043c3577
MM
12191 switch (format)
12192 {
12193 case BTRACE_FORMAT_NONE:
12194 return 0;
12195
12196 case BTRACE_FORMAT_BTS:
12197 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12198
12199 case BTRACE_FORMAT_PT:
12200 /* The trace is decoded on the host. Even if our target supports it,
12201 we still need to have libipt to decode the trace. */
12202#if defined (HAVE_LIBIPT)
12203 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12204#else /* !defined (HAVE_LIBIPT) */
12205 return 0;
12206#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12207 }
12208
12209 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12210}
12211
f4abbc16
MM
12212/* Synchronize the configuration with the target. */
12213
12214static void
12215btrace_sync_conf (const struct btrace_config *conf)
12216{
d33501a5
MM
12217 struct packet_config *packet;
12218 struct remote_state *rs;
12219 char *buf, *pos, *endbuf;
12220
12221 rs = get_remote_state ();
12222 buf = rs->buf;
12223 endbuf = buf + get_remote_packet_size ();
12224
12225 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12226 if (packet_config_support (packet) == PACKET_ENABLE
12227 && conf->bts.size != rs->btrace_config.bts.size)
12228 {
12229 pos = buf;
12230 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12231 conf->bts.size);
12232
12233 putpkt (buf);
12234 getpkt (&buf, &rs->buf_size, 0);
12235
12236 if (packet_ok (buf, packet) == PACKET_ERROR)
12237 {
12238 if (buf[0] == 'E' && buf[1] == '.')
12239 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12240 else
12241 error (_("Failed to configure the BTS buffer size."));
12242 }
12243
12244 rs->btrace_config.bts.size = conf->bts.size;
12245 }
b20a6524
MM
12246
12247 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12248 if (packet_config_support (packet) == PACKET_ENABLE
12249 && conf->pt.size != rs->btrace_config.pt.size)
12250 {
12251 pos = buf;
12252 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12253 conf->pt.size);
12254
12255 putpkt (buf);
12256 getpkt (&buf, &rs->buf_size, 0);
12257
12258 if (packet_ok (buf, packet) == PACKET_ERROR)
12259 {
12260 if (buf[0] == 'E' && buf[1] == '.')
12261 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12262 else
12263 error (_("Failed to configure the trace buffer size."));
12264 }
12265
12266 rs->btrace_config.pt.size = conf->pt.size;
12267 }
f4abbc16
MM
12268}
12269
12270/* Read the current thread's btrace configuration from the target and
12271 store it into CONF. */
12272
12273static void
12274btrace_read_config (struct btrace_config *conf)
12275{
12276 char *xml;
12277
12278 xml = target_read_stralloc (&current_target,
b20a6524 12279 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12280 if (xml != NULL)
12281 {
12282 struct cleanup *cleanup;
12283
12284 cleanup = make_cleanup (xfree, xml);
12285 parse_xml_btrace_conf (conf, xml);
12286 do_cleanups (cleanup);
12287 }
12288}
12289
9accd112
MM
12290/* Enable branch tracing. */
12291
12292static struct btrace_target_info *
f4abbc16
MM
12293remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12294 const struct btrace_config *conf)
9accd112
MM
12295{
12296 struct btrace_target_info *tinfo = NULL;
b20a6524 12297 struct packet_config *packet = NULL;
9accd112
MM
12298 struct remote_state *rs = get_remote_state ();
12299 char *buf = rs->buf;
12300 char *endbuf = rs->buf + get_remote_packet_size ();
12301
b20a6524
MM
12302 switch (conf->format)
12303 {
12304 case BTRACE_FORMAT_BTS:
12305 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12306 break;
12307
12308 case BTRACE_FORMAT_PT:
12309 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12310 break;
12311 }
12312
12313 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12314 error (_("Target does not support branch tracing."));
12315
f4abbc16
MM
12316 btrace_sync_conf (conf);
12317
9accd112
MM
12318 set_general_thread (ptid);
12319
12320 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12321 putpkt (rs->buf);
12322 getpkt (&rs->buf, &rs->buf_size, 0);
12323
12324 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12325 {
12326 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12327 error (_("Could not enable branch tracing for %s: %s"),
12328 target_pid_to_str (ptid), rs->buf + 2);
12329 else
12330 error (_("Could not enable branch tracing for %s."),
12331 target_pid_to_str (ptid));
12332 }
12333
12334 tinfo = xzalloc (sizeof (*tinfo));
12335 tinfo->ptid = ptid;
12336
f4abbc16
MM
12337 /* If we fail to read the configuration, we lose some information, but the
12338 tracing itself is not impacted. */
492d29ea
PA
12339 TRY
12340 {
12341 btrace_read_config (&tinfo->conf);
12342 }
12343 CATCH (err, RETURN_MASK_ERROR)
12344 {
12345 if (err.message != NULL)
12346 warning ("%s", err.message);
12347 }
12348 END_CATCH
f4abbc16 12349
9accd112
MM
12350 return tinfo;
12351}
12352
12353/* Disable branch tracing. */
12354
12355static void
25e95349
TT
12356remote_disable_btrace (struct target_ops *self,
12357 struct btrace_target_info *tinfo)
9accd112
MM
12358{
12359 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12360 struct remote_state *rs = get_remote_state ();
12361 char *buf = rs->buf;
12362 char *endbuf = rs->buf + get_remote_packet_size ();
12363
4082afcc 12364 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12365 error (_("Target does not support branch tracing."));
12366
12367 set_general_thread (tinfo->ptid);
12368
12369 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12370 putpkt (rs->buf);
12371 getpkt (&rs->buf, &rs->buf_size, 0);
12372
12373 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12374 {
12375 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12376 error (_("Could not disable branch tracing for %s: %s"),
12377 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12378 else
12379 error (_("Could not disable branch tracing for %s."),
12380 target_pid_to_str (tinfo->ptid));
12381 }
12382
12383 xfree (tinfo);
12384}
12385
12386/* Teardown branch tracing. */
12387
12388static void
1777056d
TT
12389remote_teardown_btrace (struct target_ops *self,
12390 struct btrace_target_info *tinfo)
9accd112
MM
12391{
12392 /* We must not talk to the target during teardown. */
12393 xfree (tinfo);
12394}
12395
12396/* Read the branch trace. */
12397
969c39fb 12398static enum btrace_error
39c49f83 12399remote_read_btrace (struct target_ops *self,
734b0e4b 12400 struct btrace_data *btrace,
969c39fb 12401 struct btrace_target_info *tinfo,
9accd112
MM
12402 enum btrace_read_type type)
12403{
12404 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12405 struct remote_state *rs = get_remote_state ();
969c39fb 12406 struct cleanup *cleanup;
9accd112
MM
12407 const char *annex;
12408 char *xml;
12409
4082afcc 12410 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12411 error (_("Target does not support branch tracing."));
12412
12413#if !defined(HAVE_LIBEXPAT)
12414 error (_("Cannot process branch tracing result. XML parsing not supported."));
12415#endif
12416
12417 switch (type)
12418 {
864089d2 12419 case BTRACE_READ_ALL:
9accd112
MM
12420 annex = "all";
12421 break;
864089d2 12422 case BTRACE_READ_NEW:
9accd112
MM
12423 annex = "new";
12424 break;
969c39fb
MM
12425 case BTRACE_READ_DELTA:
12426 annex = "delta";
12427 break;
9accd112
MM
12428 default:
12429 internal_error (__FILE__, __LINE__,
12430 _("Bad branch tracing read type: %u."),
12431 (unsigned int) type);
12432 }
12433
12434 xml = target_read_stralloc (&current_target,
b20a6524 12435 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12436 if (xml == NULL)
12437 return BTRACE_ERR_UNKNOWN;
9accd112 12438
969c39fb 12439 cleanup = make_cleanup (xfree, xml);
734b0e4b 12440 parse_xml_btrace (btrace, xml);
969c39fb 12441 do_cleanups (cleanup);
9accd112 12442
969c39fb 12443 return BTRACE_ERR_NONE;
9accd112
MM
12444}
12445
f4abbc16
MM
12446static const struct btrace_config *
12447remote_btrace_conf (struct target_ops *self,
12448 const struct btrace_target_info *tinfo)
12449{
12450 return &tinfo->conf;
12451}
12452
ced63ec0 12453static int
5436ff03 12454remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12455{
4082afcc
PA
12456 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12457 == PACKET_ENABLE);
ced63ec0
GB
12458}
12459
9dd130a0
TT
12460/* Implementation of to_load. */
12461
12462static void
9cbe5fff 12463remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12464{
12465 generic_load (name, from_tty);
12466}
12467
c78fa86a
GB
12468/* Accepts an integer PID; returns a string representing a file that
12469 can be opened on the remote side to get the symbols for the child
12470 process. Returns NULL if the operation is not supported. */
12471
12472static char *
12473remote_pid_to_exec_file (struct target_ops *self, int pid)
12474{
12475 static char *filename = NULL;
835205d0
GB
12476 struct inferior *inf;
12477 char *annex = NULL;
c78fa86a
GB
12478
12479 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12480 return NULL;
12481
12482 if (filename != NULL)
12483 xfree (filename);
12484
835205d0
GB
12485 inf = find_inferior_pid (pid);
12486 if (inf == NULL)
12487 internal_error (__FILE__, __LINE__,
12488 _("not currently attached to process %d"), pid);
12489
12490 if (!inf->fake_pid_p)
12491 {
12492 const int annex_size = 9;
12493
12494 annex = alloca (annex_size);
12495 xsnprintf (annex, annex_size, "%x", pid);
12496 }
12497
c78fa86a
GB
12498 filename = target_read_stralloc (&current_target,
12499 TARGET_OBJECT_EXEC_FILE, annex);
12500
12501 return filename;
12502}
12503
c906108c 12504static void
fba45db2 12505init_remote_ops (void)
c906108c 12506{
c5aa993b 12507 remote_ops.to_shortname = "remote";
c906108c 12508 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 12509 remote_ops.to_doc =
c906108c 12510 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
12511Specify the serial device it is connected to\n\
12512(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
12513 remote_ops.to_open = remote_open;
12514 remote_ops.to_close = remote_close;
c906108c 12515 remote_ops.to_detach = remote_detach;
6ad8ae5c 12516 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 12517 remote_ops.to_resume = remote_resume;
c906108c
SS
12518 remote_ops.to_wait = remote_wait;
12519 remote_ops.to_fetch_registers = remote_fetch_registers;
12520 remote_ops.to_store_registers = remote_store_registers;
12521 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 12522 remote_ops.to_files_info = remote_files_info;
c906108c
SS
12523 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12524 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
12525 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12526 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12527 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12528 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
12529 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12530 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
12531 remote_ops.to_watchpoint_addr_within_range =
12532 remote_watchpoint_addr_within_range;
3c3bea1c
GS
12533 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12534 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12535 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
12536 remote_ops.to_region_ok_for_hw_watchpoint
12537 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
12538 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12539 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 12540 remote_ops.to_kill = remote_kill;
9dd130a0 12541 remote_ops.to_load = remote_load;
c906108c 12542 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 12543 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 12544 remote_ops.to_program_signals = remote_program_signals;
c906108c 12545 remote_ops.to_thread_alive = remote_thread_alive;
e8032dde 12546 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 12547 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 12548 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 12549 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 12550 remote_ops.to_stop = remote_stop;
bfedc46a 12551 remote_ops.to_interrupt = remote_interrupt;
abc56d60 12552 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
4b8a223f 12553 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 12554 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 12555 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 12556 remote_ops.to_log_command = serial_log_command;
38691318 12557 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 12558 remote_ops.to_stratum = process_stratum;
c35b1492
PA
12559 remote_ops.to_has_all_memory = default_child_has_all_memory;
12560 remote_ops.to_has_memory = default_child_has_memory;
12561 remote_ops.to_has_stack = default_child_has_stack;
12562 remote_ops.to_has_registers = default_child_has_registers;
12563 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 12564 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 12565 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 12566 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 12567 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
12568 remote_ops.to_flash_erase = remote_flash_erase;
12569 remote_ops.to_flash_done = remote_flash_done;
29709017 12570 remote_ops.to_read_description = remote_read_description;
08388c79 12571 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
12572 remote_ops.to_can_async_p = remote_can_async_p;
12573 remote_ops.to_is_async_p = remote_is_async_p;
12574 remote_ops.to_async = remote_async;
75c99385
PA
12575 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12576 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 12577 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 12578 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
12579 remote_ops.to_supports_disable_randomization
12580 = remote_supports_disable_randomization;
4bd7dc42 12581 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
12582 remote_ops.to_fileio_open = remote_hostio_open;
12583 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12584 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 12585 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
12586 remote_ops.to_fileio_close = remote_hostio_close;
12587 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 12588 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 12589 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 12590 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 12591 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 12592 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
12593 remote_ops.to_trace_init = remote_trace_init;
12594 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 12595 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
12596 remote_ops.to_download_trace_state_variable
12597 = remote_download_trace_state_variable;
d248b706
KY
12598 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12599 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
12600 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12601 remote_ops.to_trace_start = remote_trace_start;
12602 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 12603 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
12604 remote_ops.to_trace_stop = remote_trace_stop;
12605 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
12606 remote_ops.to_get_trace_state_variable_value
12607 = remote_get_trace_state_variable_value;
00bf0b85
SS
12608 remote_ops.to_save_trace_data = remote_save_trace_data;
12609 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
12610 remote_ops.to_upload_trace_state_variables
12611 = remote_upload_trace_state_variables;
00bf0b85 12612 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 12613 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 12614 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 12615 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 12616 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 12617 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 12618 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 12619 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 12620 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 12621 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
12622 remote_ops.to_static_tracepoint_marker_at
12623 = remote_static_tracepoint_marker_at;
12624 remote_ops.to_static_tracepoint_markers_by_strid
12625 = remote_static_tracepoint_markers_by_strid;
b3b9301e 12626 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
12627 remote_ops.to_use_agent = remote_use_agent;
12628 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
12629 remote_ops.to_supports_btrace = remote_supports_btrace;
12630 remote_ops.to_enable_btrace = remote_enable_btrace;
12631 remote_ops.to_disable_btrace = remote_disable_btrace;
12632 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12633 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 12634 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
12635 remote_ops.to_augmented_libraries_svr4_read =
12636 remote_augmented_libraries_svr4_read;
c906108c
SS
12637}
12638
12639/* Set up the extended remote vector by making a copy of the standard
12640 remote vector and adding to it. */
12641
12642static void
fba45db2 12643init_extended_remote_ops (void)
c906108c
SS
12644{
12645 extended_remote_ops = remote_ops;
12646
0f71a2f6 12647 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 12648 extended_remote_ops.to_longname =
c906108c 12649 "Extended remote serial target in gdb-specific protocol";
c5aa993b 12650 extended_remote_ops.to_doc =
c906108c 12651 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
12652Specify the serial device it is connected to (e.g. /dev/ttya).";
12653 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
12654 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12655 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
12656 extended_remote_ops.to_detach = extended_remote_detach;
12657 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 12658 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 12659 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
12660 extended_remote_ops.to_supports_disable_randomization
12661 = extended_remote_supports_disable_randomization;
de0d863e 12662 extended_remote_ops.to_follow_fork = remote_follow_fork;
cbb8991c
DB
12663 extended_remote_ops.to_insert_fork_catchpoint
12664 = remote_insert_fork_catchpoint;
12665 extended_remote_ops.to_remove_fork_catchpoint
12666 = remote_remove_fork_catchpoint;
12667 extended_remote_ops.to_insert_vfork_catchpoint
12668 = remote_insert_vfork_catchpoint;
12669 extended_remote_ops.to_remove_vfork_catchpoint
12670 = remote_remove_vfork_catchpoint;
0f71a2f6
JM
12671}
12672
6426a772 12673static int
6a109b6b 12674remote_can_async_p (struct target_ops *ops)
6426a772 12675{
5d93a237
TT
12676 struct remote_state *rs = get_remote_state ();
12677
c6ebd6cf 12678 if (!target_async_permitted)
75c99385
PA
12679 /* We only enable async when the user specifically asks for it. */
12680 return 0;
12681
23860348 12682 /* We're async whenever the serial device is. */
5d93a237 12683 return serial_can_async_p (rs->remote_desc);
6426a772
JM
12684}
12685
12686static int
6a109b6b 12687remote_is_async_p (struct target_ops *ops)
6426a772 12688{
5d93a237
TT
12689 struct remote_state *rs = get_remote_state ();
12690
c6ebd6cf 12691 if (!target_async_permitted)
75c99385
PA
12692 /* We only enable async when the user specifically asks for it. */
12693 return 0;
12694
23860348 12695 /* We're async whenever the serial device is. */
5d93a237 12696 return serial_is_async_p (rs->remote_desc);
6426a772
JM
12697}
12698
2acceee2
JM
12699/* Pass the SERIAL event on and up to the client. One day this code
12700 will be able to delay notifying the client of an event until the
23860348 12701 point where an entire packet has been received. */
2acceee2 12702
2acceee2
JM
12703static serial_event_ftype remote_async_serial_handler;
12704
6426a772 12705static void
819cc324 12706remote_async_serial_handler (struct serial *scb, void *context)
6426a772 12707{
88b496c3
TT
12708 struct remote_state *rs = context;
12709
2acceee2
JM
12710 /* Don't propogate error information up to the client. Instead let
12711 the client find out about the error by querying the target. */
6a3753b3 12712 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
12713}
12714
74531fed
PA
12715static void
12716remote_async_inferior_event_handler (gdb_client_data data)
12717{
12718 inferior_event_handler (INF_REG_EVENT, NULL);
12719}
12720
2acceee2 12721static void
6a3753b3 12722remote_async (struct target_ops *ops, int enable)
2acceee2 12723{
5d93a237
TT
12724 struct remote_state *rs = get_remote_state ();
12725
6a3753b3 12726 if (enable)
2acceee2 12727 {
88b496c3 12728 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
12729
12730 /* If there are pending events in the stop reply queue tell the
12731 event loop to process them. */
12732 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12733 mark_async_event_handler (remote_async_inferior_event_token);
2acceee2
JM
12734 }
12735 else
b7d2e916
PA
12736 {
12737 serial_async (rs->remote_desc, NULL, NULL);
12738 clear_async_event_handler (remote_async_inferior_event_token);
12739 }
6426a772
JM
12740}
12741
5a2468f5 12742static void
c2d11a7d 12743set_remote_cmd (char *args, int from_tty)
5a2468f5 12744{
635c7e8a 12745 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
12746}
12747
d471ea57
AC
12748static void
12749show_remote_cmd (char *args, int from_tty)
12750{
37a105a1 12751 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 12752 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
12753 struct cleanup *showlist_chain;
12754 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 12755 struct ui_out *uiout = current_uiout;
37a105a1
DJ
12756
12757 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12758 for (; list != NULL; list = list->next)
12759 if (strcmp (list->name, "Z-packet") == 0)
12760 continue;
427c3a89
DJ
12761 else if (list->type == not_set_cmd)
12762 /* Alias commands are exactly like the original, except they
12763 don't have the normal type. */
12764 continue;
12765 else
37a105a1
DJ
12766 {
12767 struct cleanup *option_chain
12768 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 12769
37a105a1
DJ
12770 ui_out_field_string (uiout, "name", list->name);
12771 ui_out_text (uiout, ": ");
427c3a89 12772 if (list->type == show_cmd)
5b9afe8a 12773 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
12774 else
12775 cmd_func (list, NULL, from_tty);
37a105a1
DJ
12776 /* Close the tuple. */
12777 do_cleanups (option_chain);
12778 }
427c3a89
DJ
12779
12780 /* Close the tuple. */
12781 do_cleanups (showlist_chain);
d471ea57 12782}
5a2468f5 12783
0f71a2f6 12784
23860348 12785/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
12786static void
12787remote_new_objfile (struct objfile *objfile)
12788{
5d93a237
TT
12789 struct remote_state *rs = get_remote_state ();
12790
12791 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 12792 remote_check_symbols ();
dc8acb97
MS
12793}
12794
00bf0b85
SS
12795/* Pull all the tracepoints defined on the target and create local
12796 data structures representing them. We don't want to create real
12797 tracepoints yet, we don't want to mess up the user's existing
12798 collection. */
12799
12800static int
ab6617cc 12801remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 12802{
00bf0b85
SS
12803 struct remote_state *rs = get_remote_state ();
12804 char *p;
d5551862 12805
00bf0b85
SS
12806 /* Ask for a first packet of tracepoint definition. */
12807 putpkt ("qTfP");
12808 getpkt (&rs->buf, &rs->buf_size, 0);
12809 p = rs->buf;
12810 while (*p && *p != 'l')
d5551862 12811 {
00bf0b85
SS
12812 parse_tracepoint_definition (p, utpp);
12813 /* Ask for another packet of tracepoint definition. */
12814 putpkt ("qTsP");
12815 getpkt (&rs->buf, &rs->buf_size, 0);
12816 p = rs->buf;
d5551862 12817 }
00bf0b85 12818 return 0;
d5551862
SS
12819}
12820
00bf0b85 12821static int
181e3713
TT
12822remote_upload_trace_state_variables (struct target_ops *self,
12823 struct uploaded_tsv **utsvp)
d5551862 12824{
00bf0b85 12825 struct remote_state *rs = get_remote_state ();
d5551862 12826 char *p;
d5551862 12827
00bf0b85
SS
12828 /* Ask for a first packet of variable definition. */
12829 putpkt ("qTfV");
d5551862
SS
12830 getpkt (&rs->buf, &rs->buf_size, 0);
12831 p = rs->buf;
00bf0b85 12832 while (*p && *p != 'l')
d5551862 12833 {
00bf0b85
SS
12834 parse_tsv_definition (p, utsvp);
12835 /* Ask for another packet of variable definition. */
12836 putpkt ("qTsV");
d5551862
SS
12837 getpkt (&rs->buf, &rs->buf_size, 0);
12838 p = rs->buf;
12839 }
00bf0b85 12840 return 0;
d5551862
SS
12841}
12842
c1e36e3e
PA
12843/* The "set/show range-stepping" show hook. */
12844
12845static void
12846show_range_stepping (struct ui_file *file, int from_tty,
12847 struct cmd_list_element *c,
12848 const char *value)
12849{
12850 fprintf_filtered (file,
12851 _("Debugger's willingness to use range stepping "
12852 "is %s.\n"), value);
12853}
12854
12855/* The "set/show range-stepping" set hook. */
12856
12857static void
12858set_range_stepping (char *ignore_args, int from_tty,
12859 struct cmd_list_element *c)
12860{
5d93a237
TT
12861 struct remote_state *rs = get_remote_state ();
12862
c1e36e3e
PA
12863 /* Whene enabling, check whether range stepping is actually
12864 supported by the target, and warn if not. */
12865 if (use_range_stepping)
12866 {
5d93a237 12867 if (rs->remote_desc != NULL)
c1e36e3e 12868 {
4082afcc 12869 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
12870 remote_vcont_probe (rs);
12871
4082afcc 12872 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
12873 && rs->supports_vCont.r)
12874 return;
12875 }
12876
12877 warning (_("Range stepping is not supported by the current target"));
12878 }
12879}
12880
c906108c 12881void
fba45db2 12882_initialize_remote (void)
c906108c 12883{
ea9c271d 12884 struct remote_state *rs;
9a7071a8 12885 struct cmd_list_element *cmd;
6f937416 12886 const char *cmd_name;
ea9c271d 12887
0f71a2f6 12888 /* architecture specific data */
2bc416ba 12889 remote_gdbarch_data_handle =
23860348 12890 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
12891 remote_g_packet_data_handle =
12892 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 12893
ea9c271d
DJ
12894 /* Initialize the per-target state. At the moment there is only one
12895 of these, not one per target. Only one target is active at a
cf792862
TT
12896 time. */
12897 remote_state = new_remote_state ();
ea9c271d 12898
c906108c
SS
12899 init_remote_ops ();
12900 add_target (&remote_ops);
12901
12902 init_extended_remote_ops ();
12903 add_target (&extended_remote_ops);
cce74817 12904
dc8acb97 12905 /* Hook into new objfile notification. */
06d3b283 12906 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
12907 /* We're no longer interested in notification events of an inferior
12908 when it exits. */
12909 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 12910
b803fb0f 12911 /* Set up signal handlers. */
934b9bac 12912 async_sigint_remote_token =
b803fb0f 12913 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 12914 async_sigint_remote_twice_token =
6d549500 12915 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 12916
c906108c
SS
12917#if 0
12918 init_remote_threadtests ();
12919#endif
12920
722247f1 12921 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 12922 /* set/show remote ... */
d471ea57 12923
1bedd215 12924 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
12925Remote protocol specific variables\n\
12926Configure various remote-protocol specific variables such as\n\
1bedd215 12927the packets being used"),
cff3e48b 12928 &remote_set_cmdlist, "set remote ",
23860348 12929 0 /* allow-unknown */, &setlist);
1bedd215 12930 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
12931Remote protocol specific variables\n\
12932Configure various remote-protocol specific variables such as\n\
1bedd215 12933the packets being used"),
cff3e48b 12934 &remote_show_cmdlist, "show remote ",
23860348 12935 0 /* allow-unknown */, &showlist);
5a2468f5 12936
1a966eab
AC
12937 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12938Compare section data on target to the exec file.\n\
95cf3b38
DT
12939Argument is a single section name (default: all loaded sections).\n\
12940To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
12941 &cmdlist);
12942
1a966eab
AC
12943 add_cmd ("packet", class_maintenance, packet_command, _("\
12944Send an arbitrary packet to a remote target.\n\
c906108c
SS
12945 maintenance packet TEXT\n\
12946If GDB is talking to an inferior via the GDB serial protocol, then\n\
12947this command sends the string TEXT to the inferior, and displays the\n\
12948response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 12949terminating `#' character and checksum."),
c906108c
SS
12950 &maintenancelist);
12951
7915a72c
AC
12952 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12953Set whether to send break if interrupted."), _("\
12954Show whether to send break if interrupted."), _("\
12955If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 12956 set_remotebreak, show_remotebreak,
e707bbc2 12957 &setlist, &showlist);
9a7071a8
JB
12958 cmd_name = "remotebreak";
12959 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12960 deprecate_cmd (cmd, "set remote interrupt-sequence");
12961 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12962 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12963 deprecate_cmd (cmd, "show remote interrupt-sequence");
12964
12965 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
12966 interrupt_sequence_modes, &interrupt_sequence_mode,
12967 _("\
9a7071a8
JB
12968Set interrupt sequence to remote target."), _("\
12969Show interrupt sequence to remote target."), _("\
12970Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12971 NULL, show_interrupt_sequence,
12972 &remote_set_cmdlist,
12973 &remote_show_cmdlist);
12974
12975 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12976 &interrupt_on_connect, _("\
12977Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12978Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12979If set, interrupt sequence is sent to remote target."),
12980 NULL, NULL,
12981 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 12982
23860348 12983 /* Install commands for configuring memory read/write packets. */
11cf8741 12984
1a966eab
AC
12985 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12986Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 12987 &setlist);
1a966eab
AC
12988 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12989Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
12990 &showlist);
12991 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
12992 set_memory_write_packet_size, _("\
12993Set the maximum number of bytes per memory-write packet.\n\
12994Specify the number of bytes in a packet or 0 (zero) for the\n\
12995default packet size. The actual limit is further reduced\n\
12996dependent on the target. Specify ``fixed'' to disable the\n\
12997further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12998 &remote_set_cmdlist);
12999 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13000 set_memory_read_packet_size, _("\
13001Set the maximum number of bytes per memory-read packet.\n\
13002Specify the number of bytes in a packet or 0 (zero) for the\n\
13003default packet size. The actual limit is further reduced\n\
13004dependent on the target. Specify ``fixed'' to disable the\n\
13005further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13006 &remote_set_cmdlist);
13007 add_cmd ("memory-write-packet-size", no_class,
13008 show_memory_write_packet_size,
1a966eab 13009 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13010 &remote_show_cmdlist);
13011 add_cmd ("memory-read-packet-size", no_class,
13012 show_memory_read_packet_size,
1a966eab 13013 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13014 &remote_show_cmdlist);
c906108c 13015
b3f42336 13016 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13017 &remote_hw_watchpoint_limit, _("\
13018Set the maximum number of target hardware watchpoints."), _("\
13019Show the maximum number of target hardware watchpoints."), _("\
13020Specify a negative limit for unlimited."),
3e43a32a
MS
13021 NULL, NULL, /* FIXME: i18n: The maximum
13022 number of target hardware
13023 watchpoints is %s. */
b3f42336 13024 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13025 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13026 &remote_hw_watchpoint_length_limit, _("\
13027Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13028Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13029Specify a negative limit for unlimited."),
13030 NULL, NULL, /* FIXME: i18n: The maximum
13031 length (in bytes) of a target
13032 hardware watchpoint is %s. */
13033 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13034 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13035 &remote_hw_breakpoint_limit, _("\
13036Set the maximum number of target hardware breakpoints."), _("\
13037Show the maximum number of target hardware breakpoints."), _("\
13038Specify a negative limit for unlimited."),
3e43a32a
MS
13039 NULL, NULL, /* FIXME: i18n: The maximum
13040 number of target hardware
13041 breakpoints is %s. */
b3f42336 13042 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13043
1b493192
PA
13044 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13045 &remote_address_size, _("\
4d28ad1e
AC
13046Set the maximum size of the address (in bits) in a memory packet."), _("\
13047Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13048 NULL,
13049 NULL, /* FIXME: i18n: */
13050 &setlist, &showlist);
c906108c 13051
ca4f7f8b
PA
13052 init_all_packet_configs ();
13053
444abaca 13054 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13055 "X", "binary-download", 1);
0f71a2f6 13056
444abaca 13057 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13058 "vCont", "verbose-resume", 0);
506fb367 13059
89be2091
DJ
13060 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13061 "QPassSignals", "pass-signals", 0);
13062
9b224c5e
PA
13063 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13064 "QProgramSignals", "program-signals", 0);
13065
444abaca 13066 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13067 "qSymbol", "symbol-lookup", 0);
dc8acb97 13068
444abaca 13069 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13070 "P", "set-register", 1);
d471ea57 13071
444abaca 13072 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13073 "p", "fetch-register", 1);
b96ec7ac 13074
444abaca 13075 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13076 "Z0", "software-breakpoint", 0);
d471ea57 13077
444abaca 13078 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13079 "Z1", "hardware-breakpoint", 0);
d471ea57 13080
444abaca 13081 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13082 "Z2", "write-watchpoint", 0);
d471ea57 13083
444abaca 13084 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13085 "Z3", "read-watchpoint", 0);
d471ea57 13086
444abaca 13087 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13088 "Z4", "access-watchpoint", 0);
d471ea57 13089
0876f84a
DJ
13090 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13091 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13092
c78fa86a
GB
13093 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13094 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13095
23181151
DJ
13096 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13097 "qXfer:features:read", "target-features", 0);
13098
cfa9d6d9
DJ
13099 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13100 "qXfer:libraries:read", "library-info", 0);
13101
2268b414
JK
13102 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13103 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13104
fd79ecee
DJ
13105 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13106 "qXfer:memory-map:read", "memory-map", 0);
13107
0e7f50da
UW
13108 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13109 "qXfer:spu:read", "read-spu-object", 0);
13110
13111 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13112 "qXfer:spu:write", "write-spu-object", 0);
13113
07e059b5
VP
13114 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13115 "qXfer:osdata:read", "osdata", 0);
13116
dc146f7c
VP
13117 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13118 "qXfer:threads:read", "threads", 0);
13119
4aa995e1
PA
13120 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13121 "qXfer:siginfo:read", "read-siginfo-object", 0);
13122
13123 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13124 "qXfer:siginfo:write", "write-siginfo-object", 0);
13125
b3b9301e
PA
13126 add_packet_config_cmd
13127 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13128 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13129
169081d0
TG
13130 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13131 "qXfer:uib:read", "unwind-info-block", 0);
13132
444abaca 13133 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13134 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13135 0);
13136
711e434b
PM
13137 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13138 "qGetTIBAddr", "get-thread-information-block-address",
13139 0);
13140
40ab02ce
MS
13141 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13142 "bc", "reverse-continue", 0);
13143
13144 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13145 "bs", "reverse-step", 0);
13146
be2a5f71
DJ
13147 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13148 "qSupported", "supported-packets", 0);
13149
08388c79
DE
13150 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13151 "qSearch:memory", "search-memory", 0);
13152
bd3eecc3
PA
13153 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13154 "qTStatus", "trace-status", 0);
13155
15a201c8
GB
13156 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13157 "vFile:setfs", "hostio-setfs", 0);
13158
a6b151f1
DJ
13159 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13160 "vFile:open", "hostio-open", 0);
13161
13162 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13163 "vFile:pread", "hostio-pread", 0);
13164
13165 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13166 "vFile:pwrite", "hostio-pwrite", 0);
13167
13168 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13169 "vFile:close", "hostio-close", 0);
13170
13171 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13172 "vFile:unlink", "hostio-unlink", 0);
13173
b9e7b9c3
UW
13174 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13175 "vFile:readlink", "hostio-readlink", 0);
13176
0a93529c
GB
13177 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13178 "vFile:fstat", "hostio-fstat", 0);
13179
2d717e4f
DJ
13180 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13181 "vAttach", "attach", 0);
13182
13183 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13184 "vRun", "run", 0);
13185
a6f3e723
SL
13186 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13187 "QStartNoAckMode", "noack", 0);
13188
82f73884
PA
13189 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13190 "vKill", "kill", 0);
13191
0b16c5cf
PA
13192 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13193 "qAttached", "query-attached", 0);
13194
782b2b07 13195 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13196 "ConditionalTracepoints",
13197 "conditional-tracepoints", 0);
3788aec7
LM
13198
13199 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13200 "ConditionalBreakpoints",
13201 "conditional-breakpoints", 0);
13202
d3ce09f5
SS
13203 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13204 "BreakpointCommands",
13205 "breakpoint-commands", 0);
13206
7a697b8d
SS
13207 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13208 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13209
409873ef
SS
13210 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13211 "TracepointSource", "TracepointSource", 0);
13212
d914c394
SS
13213 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13214 "QAllow", "allow", 0);
13215
0fb4aa4b
PA
13216 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13217 "StaticTracepoints", "static-tracepoints", 0);
13218
1e4d1764
YQ
13219 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13220 "InstallInTrace", "install-in-trace", 0);
13221
0fb4aa4b
PA
13222 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13223 "qXfer:statictrace:read", "read-sdata-object", 0);
13224
78d85199
YQ
13225 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13226 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13227
03583c20
UW
13228 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13229 "QDisableRandomization", "disable-randomization", 0);
13230
d1feda86
YQ
13231 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13232 "QAgent", "agent", 0);
13233
f6f899bf
HAQ
13234 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13235 "QTBuffer:size", "trace-buffer-size", 0);
13236
9accd112
MM
13237 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13238 "Qbtrace:off", "disable-btrace", 0);
13239
13240 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13241 "Qbtrace:bts", "enable-btrace-bts", 0);
13242
13243 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13244 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13245
13246 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13247 "qXfer:btrace", "read-btrace", 0);
13248
f4abbc16
MM
13249 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13250 "qXfer:btrace-conf", "read-btrace-conf", 0);
13251
d33501a5
MM
13252 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13253 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13254
73b8c1fd
PA
13255 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13256 "multiprocess-feature", "multiprocess-feature", 0);
13257
f7e6eed5
PA
13258 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13259 "swbreak-feature", "swbreak-feature", 0);
13260
13261 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13262 "hwbreak-feature", "hwbreak-feature", 0);
13263
89245bc0
DB
13264 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13265 "fork-event-feature", "fork-event-feature", 0);
13266
13267 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13268 "vfork-event-feature", "vfork-event-feature", 0);
13269
b20a6524
MM
13270 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13271 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13272
0b736949
DB
13273 /* Assert that we've registered "set remote foo-packet" commands
13274 for all packet configs. */
ca4f7f8b
PA
13275 {
13276 int i;
13277
13278 for (i = 0; i < PACKET_MAX; i++)
13279 {
13280 /* Ideally all configs would have a command associated. Some
13281 still don't though. */
13282 int excepted;
13283
13284 switch (i)
13285 {
13286 case PACKET_QNonStop:
ca4f7f8b
PA
13287 case PACKET_EnableDisableTracepoints_feature:
13288 case PACKET_tracenz_feature:
13289 case PACKET_DisconnectedTracing_feature:
13290 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13291 case PACKET_qCRC:
13292 /* Additions to this list need to be well justified:
13293 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13294 excepted = 1;
13295 break;
13296 default:
13297 excepted = 0;
13298 break;
13299 }
13300
13301 /* This catches both forgetting to add a config command, and
13302 forgetting to remove a packet from the exception list. */
13303 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13304 }
13305 }
13306
37a105a1
DJ
13307 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13308 Z sub-packet has its own set and show commands, but users may
13309 have sets to this variable in their .gdbinit files (or in their
13310 documentation). */
e9e68a56 13311 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13312 &remote_Z_packet_detect, _("\
13313Set use of remote protocol `Z' packets"), _("\
13314Show use of remote protocol `Z' packets "), _("\
3b64bf98 13315When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13316packets."),
e9e68a56 13317 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13318 show_remote_protocol_Z_packet_cmd,
13319 /* FIXME: i18n: Use of remote protocol
13320 `Z' packets is %s. */
e9e68a56 13321 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13322
a6b151f1
DJ
13323 add_prefix_cmd ("remote", class_files, remote_command, _("\
13324Manipulate files on the remote system\n\
13325Transfer files to and from the remote target system."),
13326 &remote_cmdlist, "remote ",
13327 0 /* allow-unknown */, &cmdlist);
13328
13329 add_cmd ("put", class_files, remote_put_command,
13330 _("Copy a local file to the remote system."),
13331 &remote_cmdlist);
13332
13333 add_cmd ("get", class_files, remote_get_command,
13334 _("Copy a remote file to the local system."),
13335 &remote_cmdlist);
13336
13337 add_cmd ("delete", class_files, remote_delete_command,
13338 _("Delete a remote file."),
13339 &remote_cmdlist);
13340
2d717e4f
DJ
13341 remote_exec_file = xstrdup ("");
13342 add_setshow_string_noescape_cmd ("exec-file", class_files,
13343 &remote_exec_file, _("\
13344Set the remote pathname for \"run\""), _("\
13345Show the remote pathname for \"run\""), NULL, NULL, NULL,
13346 &remote_set_cmdlist, &remote_show_cmdlist);
13347
c1e36e3e
PA
13348 add_setshow_boolean_cmd ("range-stepping", class_run,
13349 &use_range_stepping, _("\
13350Enable or disable range stepping."), _("\
13351Show whether target-assisted range stepping is enabled."), _("\
13352If on, and the target supports it, when stepping a source line, GDB\n\
13353tells the target to step the corresponding range of addresses itself instead\n\
13354of issuing multiple single-steps. This speeds up source level\n\
13355stepping. If off, GDB always issues single-steps, even if range\n\
13356stepping is supported by the target. The default is on."),
13357 set_range_stepping,
13358 show_range_stepping,
13359 &setlist,
13360 &showlist);
13361
449092f6
CV
13362 /* Eventually initialize fileio. See fileio.c */
13363 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13364
ba348170 13365 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13366 special ptids with it set to != 0. */
ba348170
PA
13367 magic_null_ptid = ptid_build (42000, -1, 1);
13368 not_sent_ptid = ptid_build (42000, -2, 1);
13369 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13370
13371 target_buf_size = 2048;
13372 target_buf = xmalloc (target_buf_size);
c906108c 13373}
10760264 13374