Update gnulib to current upstream master
[deliverable/binutils-gdb.git] / gdb / remote.c
CommitLineData
c906108c 1/* Remote target communications for serial-line targets in custom GDB protocol
8926118c 2
32d0add0 3 Copyright (C) 1988-2015 Free Software Foundation, Inc.
c906108c 4
c5aa993b
JM
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
a9762ec7 9 the Free Software Foundation; either version 3 of the License, or
c5aa993b
JM
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
a9762ec7 18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
c5aa993b 19
23860348 20/* See the GDB User Guide for details of the GDB remote protocol. */
c5aa993b 21
c906108c 22#include "defs.h"
c906108c
SS
23#include <ctype.h>
24#include <fcntl.h>
c906108c 25#include "inferior.h"
45741a9c 26#include "infrun.h"
c906108c
SS
27#include "bfd.h"
28#include "symfile.h"
29#include "target.h"
c5aa993b 30/*#include "terminal.h" */
c906108c
SS
31#include "gdbcmd.h"
32#include "objfiles.h"
33#include "gdb-stabs.h"
34#include "gdbthread.h"
c2c6d25f 35#include "remote.h"
722247f1 36#include "remote-notif.h"
4e052eda 37#include "regcache.h"
fd0407d6 38#include "value.h"
6867ae3e 39#include "observer.h"
a77053c2 40#include "solib.h"
37a105a1
DJ
41#include "cli/cli-decode.h"
42#include "cli/cli-setshow.h"
424163ea 43#include "target-descriptions.h"
a4453b7e 44#include "gdb_bfd.h"
614c279d 45#include "filestuff.h"
9c3d6531 46#include "rsp-low.h"
6b940e6a 47#include "disasm.h"
f00aae0f 48#include "location.h"
c906108c 49
438e1e42 50#include "gdb_sys_time.h"
c906108c 51
43ff13b4 52#include "event-loop.h"
c2c6d25f 53#include "event-top.h"
2acceee2 54#include "inf-loop.h"
43ff13b4 55
c906108c
SS
56#include <signal.h>
57#include "serial.h"
58
6240bebf
MS
59#include "gdbcore.h" /* for exec_bfd */
60
449092f6 61#include "remote-fileio.h"
a6b151f1 62#include "gdb/fileio.h"
53ce3c39 63#include <sys/stat.h>
dc146f7c 64#include "xml-support.h"
449092f6 65
fd79ecee
DJ
66#include "memory-map.h"
67
35b1e5cc
SS
68#include "tracepoint.h"
69#include "ax.h"
70#include "ax-gdb.h"
d1feda86 71#include "agent.h"
9accd112 72#include "btrace.h"
35b1e5cc 73
0df8b418 74/* Temp hacks for tracepoint encoding migration. */
35b1e5cc
SS
75static char *target_buf;
76static long target_buf_size;
35b1e5cc 77
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
901f9912 4355 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4356
f7e6eed5
PA
4357 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4358 q = remote_query_supported_append (q, "swbreak+");
4359 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4360 q = remote_query_supported_append (q, "hwbreak+");
4361
c8d5aac9
L
4362 if (remote_support_xml)
4363 q = remote_query_supported_append (q, remote_support_xml);
4364
dde08ee1
PA
4365 q = remote_query_supported_append (q, "qRelocInsn+");
4366
89245bc0
DB
4367 if (rs->extended)
4368 {
4369 if (packet_set_cmd_state (PACKET_fork_event_feature)
4370 != AUTO_BOOLEAN_FALSE)
4371 q = remote_query_supported_append (q, "fork-events+");
4372 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4373 != AUTO_BOOLEAN_FALSE)
4374 q = remote_query_supported_append (q, "vfork-events+");
4375 }
4376
dde08ee1
PA
4377 q = reconcat (q, "qSupported:", q, (char *) NULL);
4378 putpkt (q);
82f73884 4379
94b0dee1
PA
4380 do_cleanups (old_chain);
4381
be2a5f71
DJ
4382 getpkt (&rs->buf, &rs->buf_size, 0);
4383
4384 /* If an error occured, warn, but do not return - just reset the
4385 buffer to empty and go on to disable features. */
4386 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4387 == PACKET_ERROR)
4388 {
4389 warning (_("Remote failure reply: %s"), rs->buf);
4390 rs->buf[0] = 0;
4391 }
4392 }
4393
4394 memset (seen, 0, sizeof (seen));
4395
4396 next = rs->buf;
4397 while (*next)
4398 {
4399 enum packet_support is_supported;
4400 char *p, *end, *name_end, *value;
4401
4402 /* First separate out this item from the rest of the packet. If
4403 there's another item after this, we overwrite the separator
4404 (terminated strings are much easier to work with). */
4405 p = next;
4406 end = strchr (p, ';');
4407 if (end == NULL)
4408 {
4409 end = p + strlen (p);
4410 next = end;
4411 }
4412 else
4413 {
89be2091
DJ
4414 *end = '\0';
4415 next = end + 1;
4416
be2a5f71
DJ
4417 if (end == p)
4418 {
4419 warning (_("empty item in \"qSupported\" response"));
4420 continue;
4421 }
be2a5f71
DJ
4422 }
4423
4424 name_end = strchr (p, '=');
4425 if (name_end)
4426 {
4427 /* This is a name=value entry. */
4428 is_supported = PACKET_ENABLE;
4429 value = name_end + 1;
4430 *name_end = '\0';
4431 }
4432 else
4433 {
4434 value = NULL;
4435 switch (end[-1])
4436 {
4437 case '+':
4438 is_supported = PACKET_ENABLE;
4439 break;
4440
4441 case '-':
4442 is_supported = PACKET_DISABLE;
4443 break;
4444
4445 case '?':
4446 is_supported = PACKET_SUPPORT_UNKNOWN;
4447 break;
4448
4449 default:
3e43a32a
MS
4450 warning (_("unrecognized item \"%s\" "
4451 "in \"qSupported\" response"), p);
be2a5f71
DJ
4452 continue;
4453 }
4454 end[-1] = '\0';
4455 }
4456
4457 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4458 if (strcmp (remote_protocol_features[i].name, p) == 0)
4459 {
4460 const struct protocol_feature *feature;
4461
4462 seen[i] = 1;
4463 feature = &remote_protocol_features[i];
4464 feature->func (feature, is_supported, value);
4465 break;
4466 }
4467 }
4468
4469 /* If we increased the packet size, make sure to increase the global
4470 buffer size also. We delay this until after parsing the entire
4471 qSupported packet, because this is the same buffer we were
4472 parsing. */
4473 if (rs->buf_size < rs->explicit_packet_size)
4474 {
4475 rs->buf_size = rs->explicit_packet_size;
4476 rs->buf = xrealloc (rs->buf, rs->buf_size);
4477 }
4478
4479 /* Handle the defaults for unmentioned features. */
4480 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4481 if (!seen[i])
4482 {
4483 const struct protocol_feature *feature;
4484
4485 feature = &remote_protocol_features[i];
4486 feature->func (feature, feature->default_support, NULL);
4487 }
4488}
4489
78a095c3
JK
4490/* Remove any of the remote.c targets from target stack. Upper targets depend
4491 on it so remove them first. */
4492
4493static void
4494remote_unpush_target (void)
4495{
4496 pop_all_targets_above (process_stratum - 1);
4497}
be2a5f71 4498
c906108c 4499static void
014f9477 4500remote_open_1 (const char *name, int from_tty,
3e43a32a 4501 struct target_ops *target, int extended_p)
c906108c 4502{
d01949b6 4503 struct remote_state *rs = get_remote_state ();
a6f3e723 4504
c906108c 4505 if (name == 0)
8a3fe4f8 4506 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4507 "serial device is attached to the remote system\n"
8a3fe4f8 4508 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4509
23860348 4510 /* See FIXME above. */
c6ebd6cf 4511 if (!target_async_permitted)
92d1e331 4512 wait_forever_enabled_p = 1;
6426a772 4513
2d717e4f 4514 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4515 Ask this question first, before target_preopen has a chance to kill
4516 anything. */
5d93a237 4517 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4518 {
78a095c3
JK
4519 if (from_tty
4520 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4521 error (_("Still connected."));
4522 }
4523
78a095c3 4524 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4525 target_preopen (from_tty);
4526
89be2091 4527 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4528 xfree (rs->last_pass_packet);
4529 rs->last_pass_packet = NULL;
89be2091 4530
9b224c5e
PA
4531 /* Make sure we send the program signals list the next time we
4532 resume. */
5e4a05c4
TT
4533 xfree (rs->last_program_signals_packet);
4534 rs->last_program_signals_packet = NULL;
9b224c5e 4535
ad9a8f3f 4536 remote_fileio_reset ();
1dd41f16
NS
4537 reopen_exec_file ();
4538 reread_symbols ();
4539
5d93a237
TT
4540 rs->remote_desc = remote_serial_open (name);
4541 if (!rs->remote_desc)
c906108c
SS
4542 perror_with_name (name);
4543
4544 if (baud_rate != -1)
4545 {
5d93a237 4546 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4547 {
9b74d5d3
KB
4548 /* The requested speed could not be set. Error out to
4549 top level after closing remote_desc. Take care to
4550 set remote_desc to NULL to avoid closing remote_desc
4551 more than once. */
5d93a237
TT
4552 serial_close (rs->remote_desc);
4553 rs->remote_desc = NULL;
c906108c
SS
4554 perror_with_name (name);
4555 }
4556 }
4557
236af5e3 4558 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4559 serial_raw (rs->remote_desc);
c906108c
SS
4560
4561 /* If there is something sitting in the buffer we might take it as a
4562 response to a command, which would be bad. */
5d93a237 4563 serial_flush_input (rs->remote_desc);
c906108c
SS
4564
4565 if (from_tty)
4566 {
4567 puts_filtered ("Remote debugging using ");
4568 puts_filtered (name);
4569 puts_filtered ("\n");
4570 }
23860348 4571 push_target (target); /* Switch to using remote target now. */
c906108c 4572
74531fed
PA
4573 /* Register extra event sources in the event loop. */
4574 remote_async_inferior_event_token
4575 = create_async_event_handler (remote_async_inferior_event_handler,
4576 NULL);
5965e028 4577 rs->notif_state = remote_notif_state_allocate ();
74531fed 4578
be2a5f71
DJ
4579 /* Reset the target state; these things will be queried either by
4580 remote_query_supported or as they are needed. */
ca4f7f8b 4581 reset_all_packet_configs_support ();
74531fed 4582 rs->cached_wait_status = 0;
be2a5f71 4583 rs->explicit_packet_size = 0;
a6f3e723 4584 rs->noack_mode = 0;
82f73884 4585 rs->extended = extended_p;
e24a49d8 4586 rs->waiting_for_stop_reply = 0;
3a29589a 4587 rs->ctrlc_pending_p = 0;
802188a7 4588
47f8a51d
TT
4589 rs->general_thread = not_sent_ptid;
4590 rs->continue_thread = not_sent_ptid;
262e1174 4591 rs->remote_traceframe_number = -1;
c906108c 4592
9d1f7ab2 4593 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4594 rs->use_threadinfo_query = 1;
4595 rs->use_threadextra_query = 1;
9d1f7ab2 4596
80152258
PA
4597 readahead_cache_invalidate ();
4598
c6ebd6cf 4599 if (target_async_permitted)
92d1e331 4600 {
23860348 4601 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4602 remote_async_terminal_ours_p = 1;
4603
4604 /* FIXME: cagney/1999-09-23: During the initial connection it is
4605 assumed that the target is already ready and able to respond to
0df8b418 4606 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4607 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4608 around this. Eventually a mechanism that allows
92d1e331 4609 wait_for_inferior() to expect/get timeouts will be
23860348 4610 implemented. */
92d1e331
DJ
4611 wait_forever_enabled_p = 0;
4612 }
4613
23860348 4614 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4615 no_shared_libraries (NULL, 0);
f78f6cf1 4616
74531fed
PA
4617 /* Start afresh. */
4618 init_thread_list ();
4619
36918e70 4620 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4621 target (we'd otherwise be in an inconsistent state) and then
4622 propogate the error on up the exception chain. This ensures that
4623 the caller doesn't stumble along blindly assuming that the
4624 function succeeded. The CLI doesn't have this problem but other
4625 UI's, such as MI do.
36918e70
AC
4626
4627 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4628 this function should return an error indication letting the
ce2826aa 4629 caller restore the previous state. Unfortunately the command
36918e70
AC
4630 ``target remote'' is directly wired to this function making that
4631 impossible. On a positive note, the CLI side of this problem has
4632 been fixed - the function set_cmd_context() makes it possible for
4633 all the ``target ....'' commands to share a common callback
4634 function. See cli-dump.c. */
109c3e39 4635 {
2d717e4f 4636
492d29ea 4637 TRY
04bd08de
TT
4638 {
4639 remote_start_remote (from_tty, target, extended_p);
4640 }
492d29ea 4641 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4642 {
c8d104ad
PA
4643 /* Pop the partially set up target - unless something else did
4644 already before throwing the exception. */
5d93a237 4645 if (rs->remote_desc != NULL)
78a095c3 4646 remote_unpush_target ();
c6ebd6cf 4647 if (target_async_permitted)
109c3e39
AC
4648 wait_forever_enabled_p = 1;
4649 throw_exception (ex);
4650 }
492d29ea 4651 END_CATCH
109c3e39 4652 }
c906108c 4653
f4abbc16
MM
4654 remote_btrace_reset ();
4655
c6ebd6cf 4656 if (target_async_permitted)
92d1e331 4657 wait_forever_enabled_p = 1;
43ff13b4
JM
4658}
4659
de0d863e
DB
4660/* Detach the specified process. */
4661
4662static void
4663remote_detach_pid (int pid)
4664{
4665 struct remote_state *rs = get_remote_state ();
4666
4667 if (remote_multi_process_p (rs))
4668 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4669 else
4670 strcpy (rs->buf, "D");
4671
4672 putpkt (rs->buf);
4673 getpkt (&rs->buf, &rs->buf_size, 0);
4674
4675 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4676 ;
4677 else if (rs->buf[0] == '\0')
4678 error (_("Remote doesn't know how to detach"));
4679 else
4680 error (_("Can't detach process."));
4681}
4682
4683/* This detaches a program to which we previously attached, using
4684 inferior_ptid to identify the process. After this is done, GDB
4685 can be used to debug some other program. We better not have left
4686 any breakpoints in the target program or it'll die when it hits
4687 one. */
c906108c
SS
4688
4689static void
de0d863e 4690remote_detach_1 (const char *args, int from_tty)
c906108c 4691{
82f73884 4692 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4693 struct remote_state *rs = get_remote_state ();
de0d863e
DB
4694 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4695 int is_fork_parent;
c906108c
SS
4696
4697 if (args)
8a3fe4f8 4698 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4699
2d717e4f
DJ
4700 if (!target_has_execution)
4701 error (_("No process to detach from."));
4702
7cee1e54
PA
4703 if (from_tty)
4704 {
4705 char *exec_file = get_exec_file (0);
4706 if (exec_file == NULL)
4707 exec_file = "";
4708 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4709 target_pid_to_str (pid_to_ptid (pid)));
4710 gdb_flush (gdb_stdout);
4711 }
4712
c906108c 4713 /* Tell the remote target to detach. */
de0d863e 4714 remote_detach_pid (pid);
82f73884 4715
de0d863e 4716 if (from_tty && !rs->extended)
7cee1e54 4717 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4718
de0d863e
DB
4719 /* Check to see if we are detaching a fork parent. Note that if we
4720 are detaching a fork child, tp == NULL. */
4721 is_fork_parent = (tp != NULL
4722 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4723
4724 /* If doing detach-on-fork, we don't mourn, because that will delete
4725 breakpoints that should be available for the followed inferior. */
4726 if (!is_fork_parent)
4727 target_mourn_inferior ();
4728 else
4729 {
4730 inferior_ptid = null_ptid;
4731 detach_inferior (pid);
4732 }
2d717e4f
DJ
4733}
4734
4735static void
52554a0e 4736remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4737{
de0d863e 4738 remote_detach_1 (args, from_tty);
2d717e4f
DJ
4739}
4740
4741static void
52554a0e 4742extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4743{
de0d863e
DB
4744 remote_detach_1 (args, from_tty);
4745}
4746
4747/* Target follow-fork function for remote targets. On entry, and
4748 at return, the current inferior is the fork parent.
4749
4750 Note that although this is currently only used for extended-remote,
4751 it is named remote_follow_fork in anticipation of using it for the
4752 remote target as well. */
4753
4754static int
4755remote_follow_fork (struct target_ops *ops, int follow_child,
4756 int detach_fork)
4757{
4758 struct remote_state *rs = get_remote_state ();
c269dbdb 4759 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 4760
c269dbdb
DB
4761 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4762 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
4763 {
4764 /* When following the parent and detaching the child, we detach
4765 the child here. For the case of following the child and
4766 detaching the parent, the detach is done in the target-
4767 independent follow fork code in infrun.c. We can't use
4768 target_detach when detaching an unfollowed child because
4769 the client side doesn't know anything about the child. */
4770 if (detach_fork && !follow_child)
4771 {
4772 /* Detach the fork child. */
4773 ptid_t child_ptid;
4774 pid_t child_pid;
4775
4776 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4777 child_pid = ptid_get_pid (child_ptid);
4778
4779 remote_detach_pid (child_pid);
4780 detach_inferior (child_pid);
4781 }
4782 }
4783 return 0;
c906108c
SS
4784}
4785
6ad8ae5c
DJ
4786/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4787
43ff13b4 4788static void
fee354ee 4789remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 4790{
43ff13b4 4791 if (args)
2d717e4f 4792 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4793
2d717e4f 4794 /* Make sure we unpush even the extended remote targets; mourn
20f796c9 4795 won't do it. So call remote_mourn directly instead of
2d717e4f 4796 target_mourn_inferior. */
20f796c9 4797 remote_mourn (target);
2d717e4f 4798
43ff13b4
JM
4799 if (from_tty)
4800 puts_filtered ("Ending remote debugging.\n");
4801}
4802
2d717e4f
DJ
4803/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4804 be chatty about it. */
4805
4806static void
20f796c9
GB
4807extended_remote_attach (struct target_ops *target, const char *args,
4808 int from_tty)
2d717e4f
DJ
4809{
4810 struct remote_state *rs = get_remote_state ();
be86555c 4811 int pid;
96ef3384 4812 char *wait_status = NULL;
2d717e4f 4813
74164c56 4814 pid = parse_pid_to_attach (args);
2d717e4f 4815
74164c56
JK
4816 /* Remote PID can be freely equal to getpid, do not check it here the same
4817 way as in other targets. */
2d717e4f 4818
4082afcc 4819 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
4820 error (_("This target does not support attaching to a process"));
4821
7cee1e54
PA
4822 if (from_tty)
4823 {
4824 char *exec_file = get_exec_file (0);
4825
4826 if (exec_file)
4827 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4828 target_pid_to_str (pid_to_ptid (pid)));
4829 else
4830 printf_unfiltered (_("Attaching to %s\n"),
4831 target_pid_to_str (pid_to_ptid (pid)));
4832
4833 gdb_flush (gdb_stdout);
4834 }
4835
bba74b36 4836 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4837 putpkt (rs->buf);
4838 getpkt (&rs->buf, &rs->buf_size, 0);
4839
4082afcc
PA
4840 switch (packet_ok (rs->buf,
4841 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 4842 {
4082afcc 4843 case PACKET_OK:
74531fed
PA
4844 if (!non_stop)
4845 {
4846 /* Save the reply for later. */
4847 wait_status = alloca (strlen (rs->buf) + 1);
4848 strcpy (wait_status, rs->buf);
4849 }
4850 else if (strcmp (rs->buf, "OK") != 0)
4851 error (_("Attaching to %s failed with: %s"),
4852 target_pid_to_str (pid_to_ptid (pid)),
4853 rs->buf);
4082afcc
PA
4854 break;
4855 case PACKET_UNKNOWN:
4856 error (_("This target does not support attaching to a process"));
4857 default:
4858 error (_("Attaching to %s failed"),
4859 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4860 }
2d717e4f 4861
1b6e6f5c 4862 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 4863
2d717e4f 4864 inferior_ptid = pid_to_ptid (pid);
79d7f229 4865
bad34192
PA
4866 if (non_stop)
4867 {
4868 struct thread_info *thread;
79d7f229 4869
bad34192 4870 /* Get list of threads. */
e8032dde 4871 remote_update_thread_list (target);
82f73884 4872
bad34192
PA
4873 thread = first_thread_of_process (pid);
4874 if (thread)
4875 inferior_ptid = thread->ptid;
4876 else
4877 inferior_ptid = pid_to_ptid (pid);
4878
4879 /* Invalidate our notion of the remote current thread. */
47f8a51d 4880 record_currthread (rs, minus_one_ptid);
bad34192 4881 }
74531fed 4882 else
bad34192
PA
4883 {
4884 /* Now, if we have thread information, update inferior_ptid. */
4885 inferior_ptid = remote_current_thread (inferior_ptid);
4886
4887 /* Add the main thread to the thread list. */
4888 add_thread_silent (inferior_ptid);
4889 }
c0a2216e 4890
96ef3384
UW
4891 /* Next, if the target can specify a description, read it. We do
4892 this before anything involving memory or registers. */
4893 target_find_description ();
4894
74531fed
PA
4895 if (!non_stop)
4896 {
4897 /* Use the previously fetched status. */
4898 gdb_assert (wait_status != NULL);
4899
4900 if (target_can_async_p ())
4901 {
722247f1
YQ
4902 struct notif_event *reply
4903 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4904
722247f1 4905 push_stop_reply ((struct stop_reply *) reply);
74531fed 4906
6a3753b3 4907 target_async (1);
74531fed
PA
4908 }
4909 else
4910 {
4911 gdb_assert (wait_status != NULL);
4912 strcpy (rs->buf, wait_status);
4913 rs->cached_wait_status = 1;
4914 }
4915 }
4916 else
4917 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4918}
4919
b9c1d481
AS
4920/* Implementation of the to_post_attach method. */
4921
4922static void
4923extended_remote_post_attach (struct target_ops *ops, int pid)
4924{
4925 /* In certain cases GDB might not have had the chance to start
4926 symbol lookup up until now. This could happen if the debugged
4927 binary is not using shared libraries, the vsyscall page is not
4928 present (on Linux) and the binary itself hadn't changed since the
4929 debugging process was started. */
4930 if (symfile_objfile != NULL)
4931 remote_check_symbols();
4932}
4933
c906108c 4934\f
506fb367
DJ
4935/* Check for the availability of vCont. This function should also check
4936 the response. */
c906108c
SS
4937
4938static void
6d820c5c 4939remote_vcont_probe (struct remote_state *rs)
c906108c 4940{
2e9f7625 4941 char *buf;
6d820c5c 4942
2e9f7625
DJ
4943 strcpy (rs->buf, "vCont?");
4944 putpkt (rs->buf);
6d820c5c 4945 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4946 buf = rs->buf;
c906108c 4947
506fb367 4948 /* Make sure that the features we assume are supported. */
61012eef 4949 if (startswith (buf, "vCont"))
506fb367
DJ
4950 {
4951 char *p = &buf[5];
4952 int support_s, support_S, support_c, support_C;
4953
4954 support_s = 0;
4955 support_S = 0;
4956 support_c = 0;
4957 support_C = 0;
d458bd84 4958 rs->supports_vCont.t = 0;
c1e36e3e 4959 rs->supports_vCont.r = 0;
506fb367
DJ
4960 while (p && *p == ';')
4961 {
4962 p++;
4963 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4964 support_s = 1;
4965 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4966 support_S = 1;
4967 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4968 support_c = 1;
4969 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4970 support_C = 1;
74531fed 4971 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4972 rs->supports_vCont.t = 1;
c1e36e3e
PA
4973 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4974 rs->supports_vCont.r = 1;
506fb367
DJ
4975
4976 p = strchr (p, ';');
4977 }
c906108c 4978
506fb367
DJ
4979 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4980 BUF will make packet_ok disable the packet. */
4981 if (!support_s || !support_S || !support_c || !support_C)
4982 buf[0] = 0;
4983 }
c906108c 4984
444abaca 4985 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4986}
c906108c 4987
0d8f58ca
PA
4988/* Helper function for building "vCont" resumptions. Write a
4989 resumption to P. ENDP points to one-passed-the-end of the buffer
4990 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4991 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4992 resumed thread should be single-stepped and/or signalled. If PTID
4993 equals minus_one_ptid, then all threads are resumed; if PTID
4994 represents a process, then all threads of the process are resumed;
4995 the thread to be stepped and/or signalled is given in the global
4996 INFERIOR_PTID. */
4997
4998static char *
4999append_resumption (char *p, char *endp,
2ea28649 5000 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
5001{
5002 struct remote_state *rs = get_remote_state ();
5003
a493e3e2 5004 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5005 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5006 else if (step
5007 /* GDB is willing to range step. */
5008 && use_range_stepping
5009 /* Target supports range stepping. */
5010 && rs->supports_vCont.r
5011 /* We don't currently support range stepping multiple
5012 threads with a wildcard (though the protocol allows it,
5013 so stubs shouldn't make an active effort to forbid
5014 it). */
5015 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5016 {
5017 struct thread_info *tp;
5018
5019 if (ptid_equal (ptid, minus_one_ptid))
5020 {
5021 /* If we don't know about the target thread's tid, then
5022 we're resuming magic_null_ptid (see caller). */
5023 tp = find_thread_ptid (magic_null_ptid);
5024 }
5025 else
5026 tp = find_thread_ptid (ptid);
5027 gdb_assert (tp != NULL);
5028
5029 if (tp->control.may_range_step)
5030 {
5031 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5032
5033 p += xsnprintf (p, endp - p, ";r%s,%s",
5034 phex_nz (tp->control.step_range_start,
5035 addr_size),
5036 phex_nz (tp->control.step_range_end,
5037 addr_size));
5038 }
5039 else
5040 p += xsnprintf (p, endp - p, ";s");
5041 }
0d8f58ca
PA
5042 else if (step)
5043 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5044 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5045 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5046 else
5047 p += xsnprintf (p, endp - p, ";c");
5048
5049 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5050 {
5051 ptid_t nptid;
5052
5053 /* All (-1) threads of process. */
ba348170 5054 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5055
5056 p += xsnprintf (p, endp - p, ":");
5057 p = write_ptid (p, endp, nptid);
5058 }
5059 else if (!ptid_equal (ptid, minus_one_ptid))
5060 {
5061 p += xsnprintf (p, endp - p, ":");
5062 p = write_ptid (p, endp, ptid);
5063 }
5064
5065 return p;
5066}
5067
e5ef252a
PA
5068/* Append a vCont continue-with-signal action for threads that have a
5069 non-zero stop signal. */
5070
5071static char *
5072append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5073{
5074 struct thread_info *thread;
5075
034f788c 5076 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5077 if (ptid_match (thread->ptid, ptid)
5078 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5079 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5080 {
5081 p = append_resumption (p, endp, thread->ptid,
5082 0, thread->suspend.stop_signal);
5083 thread->suspend.stop_signal = GDB_SIGNAL_0;
5084 }
5085
5086 return p;
5087}
5088
506fb367
DJ
5089/* Resume the remote inferior by using a "vCont" packet. The thread
5090 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5091 resumed thread should be single-stepped and/or signalled. If PTID
5092 equals minus_one_ptid, then all threads are resumed; the thread to
5093 be stepped and/or signalled is given in the global INFERIOR_PTID.
5094 This function returns non-zero iff it resumes the inferior.
44eaed12 5095
506fb367
DJ
5096 This function issues a strict subset of all possible vCont commands at the
5097 moment. */
44eaed12 5098
506fb367 5099static int
2ea28649 5100remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5101{
5102 struct remote_state *rs = get_remote_state ();
82f73884
PA
5103 char *p;
5104 char *endp;
44eaed12 5105
4082afcc 5106 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5107 remote_vcont_probe (rs);
44eaed12 5108
4082afcc 5109 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5110 return 0;
44eaed12 5111
82f73884
PA
5112 p = rs->buf;
5113 endp = rs->buf + get_remote_packet_size ();
5114
506fb367
DJ
5115 /* If we could generate a wider range of packets, we'd have to worry
5116 about overflowing BUF. Should there be a generic
5117 "multi-part-packet" packet? */
5118
0d8f58ca
PA
5119 p += xsnprintf (p, endp - p, "vCont");
5120
79d7f229 5121 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5122 {
79d7f229
PA
5123 /* MAGIC_NULL_PTID means that we don't have any active threads,
5124 so we don't have any TID numbers the inferior will
5125 understand. Make sure to only send forms that do not specify
5126 a TID. */
a9cbf802 5127 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5128 }
0d8f58ca 5129 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5130 {
0d8f58ca
PA
5131 /* Resume all threads (of all processes, or of a single
5132 process), with preference for INFERIOR_PTID. This assumes
5133 inferior_ptid belongs to the set of all threads we are about
5134 to resume. */
a493e3e2 5135 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5136 {
0d8f58ca
PA
5137 /* Step inferior_ptid, with or without signal. */
5138 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5139 }
0d8f58ca 5140
e5ef252a
PA
5141 /* Also pass down any pending signaled resumption for other
5142 threads not the current. */
5143 p = append_pending_thread_resumptions (p, endp, ptid);
5144
0d8f58ca 5145 /* And continue others without a signal. */
a493e3e2 5146 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5147 }
5148 else
506fb367
DJ
5149 {
5150 /* Scheduler locking; resume only PTID. */
a9cbf802 5151 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5152 }
c906108c 5153
82f73884
PA
5154 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5155 putpkt (rs->buf);
506fb367 5156
74531fed
PA
5157 if (non_stop)
5158 {
5159 /* In non-stop, the stub replies to vCont with "OK". The stop
5160 reply will be reported asynchronously by means of a `%Stop'
5161 notification. */
5162 getpkt (&rs->buf, &rs->buf_size, 0);
5163 if (strcmp (rs->buf, "OK") != 0)
5164 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5165 }
5166
506fb367 5167 return 1;
c906108c 5168}
43ff13b4 5169
506fb367
DJ
5170/* Tell the remote machine to resume. */
5171
43ff13b4 5172static void
28439f5e 5173remote_resume (struct target_ops *ops,
2ea28649 5174 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5175{
d01949b6 5176 struct remote_state *rs = get_remote_state ();
2e9f7625 5177 char *buf;
43ff13b4 5178
722247f1
YQ
5179 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5180 (explained in remote-notif.c:handle_notification) so
5181 remote_notif_process is not called. We need find a place where
5182 it is safe to start a 'vNotif' sequence. It is good to do it
5183 before resuming inferior, because inferior was stopped and no RSP
5184 traffic at that moment. */
5185 if (!non_stop)
5965e028 5186 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5187
b73be471 5188 rs->last_sent_signal = siggnal;
280ceea3 5189 rs->last_sent_step = step;
43ff13b4 5190
506fb367 5191 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5192 /* No reverse support (yet) for vCont. */
5193 if (execution_direction != EXEC_REVERSE)
5194 if (remote_vcont_resume (ptid, step, siggnal))
5195 goto done;
506fb367 5196
79d7f229
PA
5197 /* All other supported resume packets do use Hc, so set the continue
5198 thread. */
5199 if (ptid_equal (ptid, minus_one_ptid))
5200 set_continue_thread (any_thread_ptid);
506fb367 5201 else
79d7f229 5202 set_continue_thread (ptid);
506fb367 5203
2e9f7625 5204 buf = rs->buf;
b2175913
MS
5205 if (execution_direction == EXEC_REVERSE)
5206 {
5207 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5208 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5209 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5210 siggnal);
40ab02ce 5211
4082afcc 5212 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5213 error (_("Remote reverse-step not supported."));
4082afcc 5214 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5215 error (_("Remote reverse-continue not supported."));
40ab02ce 5216
b2175913
MS
5217 strcpy (buf, step ? "bs" : "bc");
5218 }
a493e3e2 5219 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5220 {
5221 buf[0] = step ? 'S' : 'C';
c5aa993b 5222 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5223 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5224 buf[3] = '\0';
5225 }
5226 else
c5aa993b 5227 strcpy (buf, step ? "s" : "c");
506fb367 5228
44eaed12 5229 putpkt (buf);
43ff13b4 5230
75c99385 5231 done:
2acceee2 5232 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5233 with the event loop. NOTE: this is the one place where all the
5234 execution commands end up. We could alternatively do this in each
23860348 5235 of the execution commands in infcmd.c. */
2acceee2
JM
5236 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5237 into infcmd.c in order to allow inferior function calls to work
23860348 5238 NOT asynchronously. */
362646f5 5239 if (target_can_async_p ())
6a3753b3 5240 target_async (1);
e24a49d8
PA
5241
5242 /* We've just told the target to resume. The remote server will
5243 wait for the inferior to stop, and then send a stop reply. In
5244 the mean time, we can't start another command/query ourselves
74531fed
PA
5245 because the stub wouldn't be ready to process it. This applies
5246 only to the base all-stop protocol, however. In non-stop (which
5247 only supports vCont), the stub replies with an "OK", and is
5248 immediate able to process further serial input. */
5249 if (!non_stop)
5250 rs->waiting_for_stop_reply = 1;
43ff13b4 5251}
c906108c 5252\f
43ff13b4
JM
5253
5254/* Set up the signal handler for SIGINT, while the target is
23860348 5255 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5256static void
934b9bac 5257async_initialize_sigint_signal_handler (void)
43ff13b4 5258{
934b9bac 5259 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5260}
5261
23860348 5262/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5263static void
934b9bac 5264async_handle_remote_sigint (int sig)
43ff13b4 5265{
934b9bac 5266 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5267 /* Note we need to go through gdb_call_async_signal_handler in order
5268 to wake up the event loop on Windows. */
5269 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5270}
5271
5272/* Signal handler for SIGINT, installed after SIGINT has already been
5273 sent once. It will take effect the second time that the user sends
23860348 5274 a ^C. */
43ff13b4 5275static void
934b9bac 5276async_handle_remote_sigint_twice (int sig)
43ff13b4 5277{
934b9bac 5278 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5279 /* See note in async_handle_remote_sigint. */
5280 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5281}
5282
6426a772 5283/* Perform the real interruption of the target execution, in response
23860348 5284 to a ^C. */
c5aa993b 5285static void
fba45db2 5286async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5287{
5288 if (remote_debug)
248fd3bf 5289 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5290
94cc34af 5291 target_stop (inferior_ptid);
43ff13b4
JM
5292}
5293
0df8b418 5294/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5295 up on the target alltogether. */
47e1ce27 5296static void
fba45db2 5297async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5298{
2df3850c 5299 if (remote_debug)
248fd3bf 5300 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5301
5302 interrupt_query ();
43ff13b4
JM
5303}
5304
5305/* Reinstall the usual SIGINT handlers, after the target has
23860348 5306 stopped. */
6426a772 5307static void
934b9bac 5308async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5309{
5310 signal (SIGINT, handle_sigint);
43ff13b4
JM
5311}
5312
c906108c
SS
5313/* Send ^C to target to halt it. Target will respond, and send us a
5314 packet. */
507f3c78 5315static void (*ofunc) (int);
c906108c 5316
bfedc46a
PA
5317/* The command line interface's interrupt routine. This function is installed
5318 as a signal handler for SIGINT. The first time a user requests an
5319 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5320 response from the target (it didn't stop when the user requested it),
23860348 5321 we ask the user if he'd like to detach from the target. */
bfedc46a 5322
c906108c 5323static void
934b9bac 5324sync_remote_interrupt (int signo)
c906108c 5325{
23860348 5326 /* If this doesn't work, try more severe steps. */
934b9bac 5327 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5328
934b9bac 5329 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5330}
5331
5332/* The user typed ^C twice. */
5333
5334static void
934b9bac 5335sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5336{
5337 signal (signo, ofunc);
934b9bac
JK
5338 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5339 signal (signo, sync_remote_interrupt);
c906108c 5340}
7a292a7a 5341
74531fed
PA
5342/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5343 thread, all threads of a remote process, or all threads of all
5344 processes. */
5345
5346static void
5347remote_stop_ns (ptid_t ptid)
5348{
5349 struct remote_state *rs = get_remote_state ();
5350 char *p = rs->buf;
5351 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5352
4082afcc 5353 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5354 remote_vcont_probe (rs);
5355
d458bd84 5356 if (!rs->supports_vCont.t)
74531fed
PA
5357 error (_("Remote server does not support stopping threads"));
5358
f91d3df5
PA
5359 if (ptid_equal (ptid, minus_one_ptid)
5360 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5361 p += xsnprintf (p, endp - p, "vCont;t");
5362 else
5363 {
5364 ptid_t nptid;
5365
74531fed
PA
5366 p += xsnprintf (p, endp - p, "vCont;t:");
5367
5368 if (ptid_is_pid (ptid))
5369 /* All (-1) threads of process. */
ba348170 5370 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5371 else
5372 {
5373 /* Small optimization: if we already have a stop reply for
5374 this thread, no use in telling the stub we want this
5375 stopped. */
5376 if (peek_stop_reply (ptid))
5377 return;
5378
5379 nptid = ptid;
5380 }
5381
a9cbf802 5382 write_ptid (p, endp, nptid);
74531fed
PA
5383 }
5384
5385 /* In non-stop, we get an immediate OK reply. The stop reply will
5386 come in asynchronously by notification. */
5387 putpkt (rs->buf);
5388 getpkt (&rs->buf, &rs->buf_size, 0);
5389 if (strcmp (rs->buf, "OK") != 0)
5390 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5391}
5392
bfedc46a
PA
5393/* All-stop version of target_interrupt. Sends a break or a ^C to
5394 interrupt the remote target. It is undefined which thread of which
5395 process reports the interrupt. */
74531fed
PA
5396
5397static void
bfedc46a 5398remote_interrupt_as (ptid_t ptid)
74531fed
PA
5399{
5400 struct remote_state *rs = get_remote_state ();
5401
3a29589a
DJ
5402 rs->ctrlc_pending_p = 1;
5403
74531fed
PA
5404 /* If the inferior is stopped already, but the core didn't know
5405 about it yet, just ignore the request. The cached wait status
5406 will be collected in remote_wait. */
5407 if (rs->cached_wait_status)
5408 return;
5409
9a7071a8
JB
5410 /* Send interrupt_sequence to remote target. */
5411 send_interrupt_sequence ();
74531fed
PA
5412}
5413
bfedc46a 5414/* Implement the to_stop function for the remote targets. */
74531fed 5415
c906108c 5416static void
1eab8a48 5417remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5418{
7a292a7a 5419 if (remote_debug)
0f71a2f6 5420 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5421
74531fed
PA
5422 if (non_stop)
5423 remote_stop_ns (ptid);
c906108c 5424 else
bfedc46a
PA
5425 {
5426 /* We don't currently have a way to transparently pause the
5427 remote target in all-stop mode. Interrupt it instead. */
5428 remote_interrupt_as (ptid);
5429 }
5430}
5431
5432/* Implement the to_interrupt function for the remote targets. */
5433
5434static void
5435remote_interrupt (struct target_ops *self, ptid_t ptid)
5436{
5437 if (remote_debug)
5438 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5439
5440 if (non_stop)
5441 {
5442 /* We don't currently have a way to ^C the remote target in
5443 non-stop mode. Stop it (with no signal) instead. */
5444 remote_stop_ns (ptid);
5445 }
5446 else
5447 remote_interrupt_as (ptid);
c906108c
SS
5448}
5449
5450/* Ask the user what to do when an interrupt is received. */
5451
5452static void
fba45db2 5453interrupt_query (void)
c906108c
SS
5454{
5455 target_terminal_ours ();
5456
d9d41e78 5457 if (target_is_async_p ())
c906108c 5458 {
74531fed 5459 signal (SIGINT, handle_sigint);
039e3c22 5460 quit ();
c906108c 5461 }
74531fed
PA
5462 else
5463 {
9e2f0ad4
HZ
5464 if (query (_("Interrupted while waiting for the program.\n\
5465Give up (and stop debugging it)? ")))
74531fed 5466 {
78a095c3 5467 remote_unpush_target ();
039e3c22 5468 quit ();
74531fed
PA
5469 }
5470 }
c906108c
SS
5471
5472 target_terminal_inferior ();
5473}
5474
6426a772
JM
5475/* Enable/disable target terminal ownership. Most targets can use
5476 terminal groups to control terminal ownership. Remote targets are
5477 different in that explicit transfer of ownership to/from GDB/target
23860348 5478 is required. */
6426a772
JM
5479
5480static void
d2f640d4 5481remote_terminal_inferior (struct target_ops *self)
6426a772 5482{
c6ebd6cf 5483 if (!target_async_permitted)
75c99385
PA
5484 /* Nothing to do. */
5485 return;
5486
d9d2d8b6
PA
5487 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5488 idempotent. The event-loop GDB talking to an asynchronous target
5489 with a synchronous command calls this function from both
5490 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5491 transfer the terminal to the target when it shouldn't this guard
5492 can go away. */
6426a772
JM
5493 if (!remote_async_terminal_ours_p)
5494 return;
5495 delete_file_handler (input_fd);
5496 remote_async_terminal_ours_p = 0;
934b9bac 5497 async_initialize_sigint_signal_handler ();
6426a772
JM
5498 /* NOTE: At this point we could also register our selves as the
5499 recipient of all input. Any characters typed could then be
23860348 5500 passed on down to the target. */
6426a772
JM
5501}
5502
5503static void
e3594fd1 5504remote_terminal_ours (struct target_ops *self)
6426a772 5505{
c6ebd6cf 5506 if (!target_async_permitted)
75c99385
PA
5507 /* Nothing to do. */
5508 return;
5509
5510 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5511 if (remote_async_terminal_ours_p)
5512 return;
934b9bac 5513 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5514 add_file_handler (input_fd, stdin_event_handler, 0);
5515 remote_async_terminal_ours_p = 1;
5516}
5517
176a6961 5518static void
917317f4 5519remote_console_output (char *msg)
c906108c
SS
5520{
5521 char *p;
5522
c5aa993b 5523 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5524 {
5525 char tb[2];
5526 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5527
c906108c
SS
5528 tb[0] = c;
5529 tb[1] = 0;
43ff13b4 5530 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5531 }
00db5b94
PA
5532 gdb_flush (gdb_stdtarg);
5533}
74531fed
PA
5534
5535typedef struct cached_reg
5536{
5537 int num;
5538 gdb_byte data[MAX_REGISTER_SIZE];
5539} cached_reg_t;
5540
5541DEF_VEC_O(cached_reg_t);
5542
722247f1 5543typedef struct stop_reply
74531fed 5544{
722247f1 5545 struct notif_event base;
74531fed 5546
722247f1 5547 /* The identifier of the thread about this event */
74531fed
PA
5548 ptid_t ptid;
5549
340e3c99 5550 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5551 connection, represented by a remote_state object, is closed,
5552 all the associated stop_reply events should be released. */
5553 struct remote_state *rs;
5554
74531fed
PA
5555 struct target_waitstatus ws;
5556
15148d6a
PA
5557 /* Expedited registers. This makes remote debugging a bit more
5558 efficient for those targets that provide critical registers as
5559 part of their normal status mechanism (as another roundtrip to
5560 fetch them is avoided). */
74531fed
PA
5561 VEC(cached_reg_t) *regcache;
5562
f7e6eed5
PA
5563 enum target_stop_reason stop_reason;
5564
74531fed
PA
5565 CORE_ADDR watch_data_address;
5566
dc146f7c 5567 int core;
722247f1 5568} *stop_reply_p;
a744cf53 5569
722247f1
YQ
5570DECLARE_QUEUE_P (stop_reply_p);
5571DEFINE_QUEUE_P (stop_reply_p);
5572/* The list of already fetched and acknowledged stop events. This
5573 queue is used for notification Stop, and other notifications
5574 don't need queue for their events, because the notification events
5575 of Stop can't be consumed immediately, so that events should be
5576 queued first, and be consumed by remote_wait_{ns,as} one per
5577 time. Other notifications can consume their events immediately,
5578 so queue is not needed for them. */
5579static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5580
5581static void
5582stop_reply_xfree (struct stop_reply *r)
5583{
f48ff2a7 5584 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5585}
5586
221e1a37
PA
5587/* Return the length of the stop reply queue. */
5588
5589static int
5590stop_reply_queue_length (void)
5591{
5592 return QUEUE_length (stop_reply_p, stop_reply_queue);
5593}
5594
722247f1
YQ
5595static void
5596remote_notif_stop_parse (struct notif_client *self, char *buf,
5597 struct notif_event *event)
5598{
5599 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5600}
5601
5602static void
5603remote_notif_stop_ack (struct notif_client *self, char *buf,
5604 struct notif_event *event)
5605{
5606 struct stop_reply *stop_reply = (struct stop_reply *) event;
5607
5608 /* acknowledge */
5609 putpkt ((char *) self->ack_command);
5610
5611 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5612 /* We got an unknown stop reply. */
5613 error (_("Unknown stop reply"));
5614
5615 push_stop_reply (stop_reply);
5616}
5617
5618static int
5619remote_notif_stop_can_get_pending_events (struct notif_client *self)
5620{
5621 /* We can't get pending events in remote_notif_process for
5622 notification stop, and we have to do this in remote_wait_ns
5623 instead. If we fetch all queued events from stub, remote stub
5624 may exit and we have no chance to process them back in
5625 remote_wait_ns. */
5626 mark_async_event_handler (remote_async_inferior_event_token);
5627 return 0;
5628}
5629
5630static void
5631stop_reply_dtr (struct notif_event *event)
5632{
5633 struct stop_reply *r = (struct stop_reply *) event;
5634
5635 VEC_free (cached_reg_t, r->regcache);
5636}
5637
5638static struct notif_event *
5639remote_notif_stop_alloc_reply (void)
5640{
5641 struct notif_event *r
70ba0933 5642 = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5643
5644 r->dtr = stop_reply_dtr;
5645
5646 return r;
5647}
5648
5649/* A client of notification Stop. */
5650
5651struct notif_client notif_client_stop =
5652{
5653 "Stop",
5654 "vStopped",
5655 remote_notif_stop_parse,
5656 remote_notif_stop_ack,
5657 remote_notif_stop_can_get_pending_events,
5658 remote_notif_stop_alloc_reply,
f48ff2a7 5659 REMOTE_NOTIF_STOP,
722247f1
YQ
5660};
5661
5662/* A parameter to pass data in and out. */
5663
5664struct queue_iter_param
5665{
5666 void *input;
5667 struct stop_reply *output;
5668};
5669
cbb8991c
DB
5670/* Determine if THREAD is a pending fork parent thread. ARG contains
5671 the pid of the process that owns the threads we want to check, or
5672 -1 if we want to check all threads. */
5673
5674static int
5675is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5676 ptid_t thread_ptid)
5677{
5678 if (ws->kind == TARGET_WAITKIND_FORKED
5679 || ws->kind == TARGET_WAITKIND_VFORKED)
5680 {
5681 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5682 return 1;
5683 }
5684
5685 return 0;
5686}
5687
5688/* Check whether EVENT is a fork event, and if it is, remove the
5689 fork child from the context list passed in DATA. */
5690
5691static int
5692remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5693 QUEUE_ITER (stop_reply_p) *iter,
5694 stop_reply_p event,
5695 void *data)
5696{
5697 struct queue_iter_param *param = data;
5698 struct threads_listing_context *context = param->input;
5699
5700 if (event->ws.kind == TARGET_WAITKIND_FORKED
5701 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5702 {
5703 threads_listing_context_remove (&event->ws, context);
5704 }
5705
5706 return 1;
5707}
5708
5709/* If CONTEXT contains any fork child threads that have not been
5710 reported yet, remove them from the CONTEXT list. If such a
5711 thread exists it is because we are stopped at a fork catchpoint
5712 and have not yet called follow_fork, which will set up the
5713 host-side data structures for the new process. */
5714
5715static void
5716remove_new_fork_children (struct threads_listing_context *context)
5717{
5718 struct thread_info * thread;
5719 int pid = -1;
5720 struct notif_client *notif = &notif_client_stop;
5721 struct queue_iter_param param;
5722
5723 /* For any threads stopped at a fork event, remove the corresponding
5724 fork child threads from the CONTEXT list. */
5725 ALL_NON_EXITED_THREADS (thread)
5726 {
5727 struct target_waitstatus *ws = &thread->pending_follow;
5728
5729 if (is_pending_fork_parent (ws, pid, thread->ptid))
5730 {
5731 threads_listing_context_remove (ws, context);
5732 }
5733 }
5734
5735 /* Check for any pending fork events (not reported or processed yet)
5736 in process PID and remove those fork child threads from the
5737 CONTEXT list as well. */
5738 remote_notif_get_pending_events (notif);
5739 param.input = context;
5740 param.output = NULL;
5741 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5742 remove_child_of_pending_fork, &param);
5743}
5744
f48ff2a7
YQ
5745/* Remove stop replies in the queue if its pid is equal to the given
5746 inferior's pid. */
722247f1
YQ
5747
5748static int
f48ff2a7
YQ
5749remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5750 QUEUE_ITER (stop_reply_p) *iter,
5751 stop_reply_p event,
5752 void *data)
722247f1
YQ
5753{
5754 struct queue_iter_param *param = data;
5755 struct inferior *inf = param->input;
5756
f48ff2a7 5757 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5758 {
5759 stop_reply_xfree (event);
5760 QUEUE_remove_elem (stop_reply_p, q, iter);
5761 }
5762
5763 return 1;
5764}
5765
f48ff2a7 5766/* Discard all pending stop replies of inferior INF. */
c906108c 5767
74531fed 5768static void
5f4cf0bb 5769discard_pending_stop_replies (struct inferior *inf)
c906108c 5770{
722247f1
YQ
5771 int i;
5772 struct queue_iter_param param;
f48ff2a7
YQ
5773 struct stop_reply *reply;
5774 struct remote_state *rs = get_remote_state ();
5775 struct remote_notif_state *rns = rs->notif_state;
5776
5777 /* This function can be notified when an inferior exists. When the
5778 target is not remote, the notification state is NULL. */
5779 if (rs->remote_desc == NULL)
5780 return;
5781
5782 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5783
74531fed 5784 /* Discard the in-flight notification. */
f48ff2a7 5785 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5786 {
722247f1 5787 stop_reply_xfree (reply);
f48ff2a7 5788 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5789 }
c906108c 5790
722247f1
YQ
5791 param.input = inf;
5792 param.output = NULL;
74531fed
PA
5793 /* Discard the stop replies we have already pulled with
5794 vStopped. */
722247f1 5795 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5796 remove_stop_reply_for_inferior, &param);
5797}
5798
bcc75809
YQ
5799/* If its remote state is equal to the given remote state,
5800 remove EVENT from the stop reply queue. */
5801
5802static int
5803remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5804 QUEUE_ITER (stop_reply_p) *iter,
5805 stop_reply_p event,
5806 void *data)
5807{
5808 struct queue_iter_param *param = data;
5809 struct remote_state *rs = param->input;
5810
5811 if (event->rs == rs)
5812 {
5813 stop_reply_xfree (event);
5814 QUEUE_remove_elem (stop_reply_p, q, iter);
5815 }
5816
5817 return 1;
5818}
5819
5820/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5821
5822static void
bcc75809 5823discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5824{
5825 struct queue_iter_param param;
5826
bcc75809 5827 param.input = rs;
f48ff2a7
YQ
5828 param.output = NULL;
5829 /* Discard the stop replies we have already pulled with
5830 vStopped. */
5831 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5832 remove_stop_reply_of_remote_state, &param);
722247f1 5833}
74531fed 5834
722247f1
YQ
5835/* A parameter to pass data in and out. */
5836
5837static int
5838remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5839 QUEUE_ITER (stop_reply_p) *iter,
5840 stop_reply_p event,
5841 void *data)
5842{
5843 struct queue_iter_param *param = data;
5844 ptid_t *ptid = param->input;
5845
5846 if (ptid_match (event->ptid, *ptid))
5847 {
5848 param->output = event;
5849 QUEUE_remove_elem (stop_reply_p, q, iter);
5850 return 0;
c8e38a49 5851 }
722247f1
YQ
5852
5853 return 1;
74531fed 5854}
43ff13b4 5855
722247f1
YQ
5856/* Remove the first reply in 'stop_reply_queue' which matches
5857 PTID. */
2e9f7625 5858
722247f1
YQ
5859static struct stop_reply *
5860remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5861{
722247f1
YQ
5862 struct queue_iter_param param;
5863
5864 param.input = &ptid;
5865 param.output = NULL;
5866
5867 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5868 remote_notif_remove_once_on_match, &param);
5869 if (notif_debug)
5870 fprintf_unfiltered (gdb_stdlog,
5871 "notif: discard queued event: 'Stop' in %s\n",
5872 target_pid_to_str (ptid));
a744cf53 5873
722247f1 5874 return param.output;
74531fed 5875}
75c99385 5876
74531fed
PA
5877/* Look for a queued stop reply belonging to PTID. If one is found,
5878 remove it from the queue, and return it. Returns NULL if none is
5879 found. If there are still queued events left to process, tell the
5880 event loop to get back to target_wait soon. */
e24a49d8 5881
74531fed
PA
5882static struct stop_reply *
5883queued_stop_reply (ptid_t ptid)
5884{
722247f1 5885 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5886
722247f1 5887 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5888 /* There's still at least an event left. */
5889 mark_async_event_handler (remote_async_inferior_event_token);
5890
722247f1 5891 return r;
74531fed
PA
5892}
5893
5894/* Push a fully parsed stop reply in the stop reply queue. Since we
5895 know that we now have at least one queued event left to pass to the
5896 core side, tell the event loop to get back to target_wait soon. */
5897
5898static void
5899push_stop_reply (struct stop_reply *new_event)
5900{
722247f1 5901 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5902
722247f1
YQ
5903 if (notif_debug)
5904 fprintf_unfiltered (gdb_stdlog,
5905 "notif: push 'Stop' %s to queue %d\n",
5906 target_pid_to_str (new_event->ptid),
5907 QUEUE_length (stop_reply_p,
5908 stop_reply_queue));
74531fed
PA
5909
5910 mark_async_event_handler (remote_async_inferior_event_token);
5911}
5912
722247f1
YQ
5913static int
5914stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5915 QUEUE_ITER (stop_reply_p) *iter,
5916 struct stop_reply *event,
5917 void *data)
5918{
5919 ptid_t *ptid = data;
5920
5921 return !(ptid_equal (*ptid, event->ptid)
5922 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5923}
5924
74531fed
PA
5925/* Returns true if we have a stop reply for PTID. */
5926
5927static int
5928peek_stop_reply (ptid_t ptid)
5929{
722247f1
YQ
5930 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5931 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5932}
5933
1f10ba14
PA
5934/* Skip PACKET until the next semi-colon (or end of string). */
5935
5936static char *
5937skip_to_semicolon (char *p)
5938{
5939 while (*p != '\0' && *p != ';')
5940 p++;
5941 return p;
5942}
5943
26d56a93
SL
5944/* Helper for remote_parse_stop_reply. Return nonzero if the substring
5945 starting with P and ending with PEND matches PREFIX. */
5946
5947static int
5948strprefix (const char *p, const char *pend, const char *prefix)
5949{
5950 for ( ; p < pend; p++, prefix++)
5951 if (*p != *prefix)
5952 return 0;
5953 return *prefix == '\0';
5954}
5955
74531fed
PA
5956/* Parse the stop reply in BUF. Either the function succeeds, and the
5957 result is stored in EVENT, or throws an error. */
5958
5959static void
5960remote_parse_stop_reply (char *buf, struct stop_reply *event)
5961{
5962 struct remote_arch_state *rsa = get_remote_arch_state ();
5963 ULONGEST addr;
5964 char *p;
5965
5966 event->ptid = null_ptid;
bcc75809 5967 event->rs = get_remote_state ();
74531fed
PA
5968 event->ws.kind = TARGET_WAITKIND_IGNORE;
5969 event->ws.value.integer = 0;
f7e6eed5 5970 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 5971 event->regcache = NULL;
dc146f7c 5972 event->core = -1;
74531fed
PA
5973
5974 switch (buf[0])
5975 {
5976 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5977 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5978 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5979 ss = signal number
5980 n... = register number
5981 r... = register contents
5982 */
5983
5984 p = &buf[3]; /* after Txx */
5985 while (*p)
5986 {
5987 char *p1;
cea39f65 5988 int fieldsize;
43ff13b4 5989
1f10ba14
PA
5990 p1 = strchr (p, ':');
5991 if (p1 == NULL)
5992 error (_("Malformed packet(a) (missing colon): %s\n\
5993Packet: '%s'\n"),
5994 p, buf);
5995 if (p == p1)
5996 error (_("Malformed packet(a) (missing register number): %s\n\
5997Packet: '%s'\n"),
5998 p, buf);
3c3bea1c 5999
1f10ba14
PA
6000 /* Some "registers" are actually extended stop information.
6001 Note if you're adding a new entry here: GDB 7.9 and
6002 earlier assume that all register "numbers" that start
6003 with an hex digit are real register numbers. Make sure
6004 the server only sends such a packet if it knows the
6005 client understands it. */
c8e38a49 6006
26d56a93 6007 if (strprefix (p, p1, "thread"))
1f10ba14 6008 event->ptid = read_ptid (++p1, &p);
26d56a93
SL
6009 else if (strprefix (p, p1, "watch")
6010 || strprefix (p, p1, "rwatch")
6011 || strprefix (p, p1, "awatch"))
cea39f65 6012 {
f7e6eed5 6013 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6014 p = unpack_varlen_hex (++p1, &addr);
6015 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6016 }
26d56a93 6017 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6018 {
6019 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6020
6021 /* Make sure the stub doesn't forget to indicate support
6022 with qSupported. */
6023 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6024 error (_("Unexpected swbreak stop reason"));
6025
6026 /* The value part is documented as "must be empty",
6027 though we ignore it, in case we ever decide to make
6028 use of it in a backward compatible way. */
6029 p = skip_to_semicolon (p1 + 1);
6030 }
26d56a93 6031 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6032 {
6033 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6034
6035 /* Make sure the stub doesn't forget to indicate support
6036 with qSupported. */
6037 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6038 error (_("Unexpected hwbreak stop reason"));
6039
6040 /* See above. */
6041 p = skip_to_semicolon (p1 + 1);
6042 }
26d56a93 6043 else if (strprefix (p, p1, "library"))
cea39f65 6044 {
1f10ba14
PA
6045 event->ws.kind = TARGET_WAITKIND_LOADED;
6046 p = skip_to_semicolon (p1 + 1);
6047 }
26d56a93 6048 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6049 {
6050 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6051 /* p1 will indicate "begin" or "end", but it makes
6052 no difference for now, so ignore it. */
6053 p = skip_to_semicolon (p1 + 1);
6054 }
26d56a93 6055 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6056 {
6057 ULONGEST c;
a744cf53 6058
1f10ba14
PA
6059 p = unpack_varlen_hex (++p1, &c);
6060 event->core = c;
cea39f65 6061 }
26d56a93 6062 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6063 {
6064 event->ws.value.related_pid = read_ptid (++p1, &p);
6065 event->ws.kind = TARGET_WAITKIND_FORKED;
6066 }
26d56a93 6067 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6068 {
6069 event->ws.value.related_pid = read_ptid (++p1, &p);
6070 event->ws.kind = TARGET_WAITKIND_VFORKED;
6071 }
26d56a93 6072 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6073 {
6074 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6075 p = skip_to_semicolon (p1 + 1);
6076 }
cea39f65
MS
6077 else
6078 {
1f10ba14
PA
6079 ULONGEST pnum;
6080 char *p_temp;
6081
6082 /* Maybe a real ``P'' register number. */
6083 p_temp = unpack_varlen_hex (p, &pnum);
6084 /* If the first invalid character is the colon, we got a
6085 register number. Otherwise, it's an unknown stop
6086 reason. */
6087 if (p_temp == p1)
6088 {
6089 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6090 cached_reg_t cached_reg;
43ff13b4 6091
1f10ba14
PA
6092 if (reg == NULL)
6093 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6094Packet: '%s'\n"),
1f10ba14 6095 hex_string (pnum), p, buf);
c8e38a49 6096
1f10ba14 6097 cached_reg.num = reg->regnum;
4100683b 6098
1f10ba14
PA
6099 p = p1 + 1;
6100 fieldsize = hex2bin (p, cached_reg.data,
6101 register_size (target_gdbarch (),
6102 reg->regnum));
6103 p += 2 * fieldsize;
6104 if (fieldsize < register_size (target_gdbarch (),
6105 reg->regnum))
6106 warning (_("Remote reply is too short: %s"), buf);
74531fed 6107
1f10ba14
PA
6108 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6109 }
6110 else
6111 {
6112 /* Not a number. Silently skip unknown optional
6113 info. */
6114 p = skip_to_semicolon (p1 + 1);
6115 }
cea39f65 6116 }
c8e38a49 6117
cea39f65
MS
6118 if (*p != ';')
6119 error (_("Remote register badly formatted: %s\nhere: %s"),
6120 buf, p);
6121 ++p;
6122 }
5b5596ff
PA
6123
6124 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6125 break;
6126
c8e38a49
PA
6127 /* fall through */
6128 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6129 {
6130 int sig;
6131
6132 event->ws.kind = TARGET_WAITKIND_STOPPED;
6133 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6134 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6135 event->ws.value.sig = (enum gdb_signal) sig;
6136 else
6137 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6138 }
c8e38a49
PA
6139 break;
6140 case 'W': /* Target exited. */
6141 case 'X':
6142 {
6143 char *p;
6144 int pid;
6145 ULONGEST value;
82f73884 6146
c8e38a49
PA
6147 /* GDB used to accept only 2 hex chars here. Stubs should
6148 only send more if they detect GDB supports multi-process
6149 support. */
6150 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6151
c8e38a49
PA
6152 if (buf[0] == 'W')
6153 {
6154 /* The remote process exited. */
74531fed
PA
6155 event->ws.kind = TARGET_WAITKIND_EXITED;
6156 event->ws.value.integer = value;
c8e38a49
PA
6157 }
6158 else
6159 {
6160 /* The remote process exited with a signal. */
74531fed 6161 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6162 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6163 event->ws.value.sig = (enum gdb_signal) value;
6164 else
6165 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6166 }
82f73884 6167
c8e38a49
PA
6168 /* If no process is specified, assume inferior_ptid. */
6169 pid = ptid_get_pid (inferior_ptid);
6170 if (*p == '\0')
6171 ;
6172 else if (*p == ';')
6173 {
6174 p++;
6175
0b24eb2d 6176 if (*p == '\0')
82f73884 6177 ;
61012eef 6178 else if (startswith (p, "process:"))
82f73884 6179 {
c8e38a49 6180 ULONGEST upid;
a744cf53 6181
c8e38a49
PA
6182 p += sizeof ("process:") - 1;
6183 unpack_varlen_hex (p, &upid);
6184 pid = upid;
82f73884
PA
6185 }
6186 else
6187 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6188 }
c8e38a49
PA
6189 else
6190 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6191 event->ptid = pid_to_ptid (pid);
6192 }
6193 break;
6194 }
6195
6196 if (non_stop && ptid_equal (event->ptid, null_ptid))
6197 error (_("No process or thread specified in stop reply: %s"), buf);
6198}
6199
722247f1
YQ
6200/* When the stub wants to tell GDB about a new notification reply, it
6201 sends a notification (%Stop, for example). Those can come it at
6202 any time, hence, we have to make sure that any pending
6203 putpkt/getpkt sequence we're making is finished, before querying
6204 the stub for more events with the corresponding ack command
6205 (vStopped, for example). E.g., if we started a vStopped sequence
6206 immediately upon receiving the notification, something like this
6207 could happen:
74531fed
PA
6208
6209 1.1) --> Hg 1
6210 1.2) <-- OK
6211 1.3) --> g
6212 1.4) <-- %Stop
6213 1.5) --> vStopped
6214 1.6) <-- (registers reply to step #1.3)
6215
6216 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6217 query.
6218
796cb314 6219 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6220 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6221 doing whatever we were doing:
6222
6223 2.1) --> Hg 1
6224 2.2) <-- OK
6225 2.3) --> g
6226 2.4) <-- %Stop
6227 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6228 2.5) <-- (registers reply to step #2.3)
6229
6230 Eventualy after step #2.5, we return to the event loop, which
6231 notices there's an event on the
6232 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6233 associated callback --- the function below. At this point, we're
6234 always safe to start a vStopped sequence. :
6235
6236 2.6) --> vStopped
6237 2.7) <-- T05 thread:2
6238 2.8) --> vStopped
6239 2.9) --> OK
6240*/
6241
722247f1
YQ
6242void
6243remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6244{
6245 struct remote_state *rs = get_remote_state ();
74531fed 6246
f48ff2a7 6247 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6248 {
722247f1
YQ
6249 if (notif_debug)
6250 fprintf_unfiltered (gdb_stdlog,
6251 "notif: process: '%s' ack pending event\n",
6252 nc->name);
74531fed 6253
722247f1 6254 /* acknowledge */
f48ff2a7
YQ
6255 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6256 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6257
6258 while (1)
6259 {
6260 getpkt (&rs->buf, &rs->buf_size, 0);
6261 if (strcmp (rs->buf, "OK") == 0)
6262 break;
6263 else
722247f1 6264 remote_notif_ack (nc, rs->buf);
74531fed
PA
6265 }
6266 }
722247f1
YQ
6267 else
6268 {
6269 if (notif_debug)
6270 fprintf_unfiltered (gdb_stdlog,
6271 "notif: process: '%s' no pending reply\n",
6272 nc->name);
6273 }
74531fed
PA
6274}
6275
74531fed
PA
6276/* Called when it is decided that STOP_REPLY holds the info of the
6277 event that is to be returned to the core. This function always
6278 destroys STOP_REPLY. */
6279
6280static ptid_t
6281process_stop_reply (struct stop_reply *stop_reply,
6282 struct target_waitstatus *status)
6283{
6284 ptid_t ptid;
6285
6286 *status = stop_reply->ws;
6287 ptid = stop_reply->ptid;
6288
6289 /* If no thread/process was reported by the stub, assume the current
6290 inferior. */
6291 if (ptid_equal (ptid, null_ptid))
6292 ptid = inferior_ptid;
6293
5f3563ea
PA
6294 if (status->kind != TARGET_WAITKIND_EXITED
6295 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 6296 {
ee154bee
TT
6297 struct remote_state *rs = get_remote_state ();
6298
5f3563ea
PA
6299 /* Expedited registers. */
6300 if (stop_reply->regcache)
6301 {
217f1f79 6302 struct regcache *regcache
f5656ead 6303 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6304 cached_reg_t *reg;
6305 int ix;
6306
6307 for (ix = 0;
6308 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6309 ix++)
217f1f79 6310 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6311 VEC_free (cached_reg_t, stop_reply->regcache);
6312 }
74531fed 6313
f7e6eed5 6314 rs->stop_reason = stop_reply->stop_reason;
ee154bee 6315 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
6316
6317 remote_notice_new_inferior (ptid, 0);
dc146f7c 6318 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
6319 }
6320
74531fed
PA
6321 stop_reply_xfree (stop_reply);
6322 return ptid;
6323}
6324
6325/* The non-stop mode version of target_wait. */
6326
6327static ptid_t
47608cb1 6328remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6329{
6330 struct remote_state *rs = get_remote_state ();
74531fed
PA
6331 struct stop_reply *stop_reply;
6332 int ret;
fee9eda9 6333 int is_notif = 0;
74531fed
PA
6334
6335 /* If in non-stop mode, get out of getpkt even if a
6336 notification is received. */
6337
6338 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6339 0 /* forever */, &is_notif);
74531fed
PA
6340 while (1)
6341 {
fee9eda9 6342 if (ret != -1 && !is_notif)
74531fed
PA
6343 switch (rs->buf[0])
6344 {
6345 case 'E': /* Error of some sort. */
6346 /* We're out of sync with the target now. Did it continue
6347 or not? We can't tell which thread it was in non-stop,
6348 so just ignore this. */
6349 warning (_("Remote failure reply: %s"), rs->buf);
6350 break;
6351 case 'O': /* Console output. */
6352 remote_console_output (rs->buf + 1);
6353 break;
6354 default:
6355 warning (_("Invalid remote reply: %s"), rs->buf);
6356 break;
6357 }
6358
6359 /* Acknowledge a pending stop reply that may have arrived in the
6360 mean time. */
f48ff2a7 6361 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6362 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6363
6364 /* If indeed we noticed a stop reply, we're done. */
6365 stop_reply = queued_stop_reply (ptid);
6366 if (stop_reply != NULL)
6367 return process_stop_reply (stop_reply, status);
6368
47608cb1 6369 /* Still no event. If we're just polling for an event, then
74531fed 6370 return to the event loop. */
47608cb1 6371 if (options & TARGET_WNOHANG)
74531fed
PA
6372 {
6373 status->kind = TARGET_WAITKIND_IGNORE;
6374 return minus_one_ptid;
6375 }
6376
47608cb1 6377 /* Otherwise do a blocking wait. */
74531fed 6378 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6379 1 /* forever */, &is_notif);
74531fed
PA
6380 }
6381}
6382
6383/* Wait until the remote machine stops, then return, storing status in
6384 STATUS just as `wait' would. */
6385
6386static ptid_t
47608cb1 6387remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6388{
6389 struct remote_state *rs = get_remote_state ();
74531fed 6390 ptid_t event_ptid = null_ptid;
cea39f65 6391 char *buf;
74531fed
PA
6392 struct stop_reply *stop_reply;
6393
47608cb1
PA
6394 again:
6395
74531fed
PA
6396 status->kind = TARGET_WAITKIND_IGNORE;
6397 status->value.integer = 0;
6398
6399 stop_reply = queued_stop_reply (ptid);
6400 if (stop_reply != NULL)
6401 return process_stop_reply (stop_reply, status);
6402
6403 if (rs->cached_wait_status)
6404 /* Use the cached wait status, but only once. */
6405 rs->cached_wait_status = 0;
6406 else
6407 {
6408 int ret;
722247f1 6409 int is_notif;
567420d1
PA
6410 int forever = ((options & TARGET_WNOHANG) == 0
6411 && wait_forever_enabled_p);
6412
6413 if (!rs->waiting_for_stop_reply)
6414 {
6415 status->kind = TARGET_WAITKIND_NO_RESUMED;
6416 return minus_one_ptid;
6417 }
74531fed
PA
6418
6419 if (!target_is_async_p ())
6420 {
934b9bac 6421 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6422 /* If the user hit C-c before this packet, or between packets,
6423 pretend that it was hit right here. */
522002f9 6424 if (check_quit_flag ())
74531fed 6425 {
522002f9 6426 clear_quit_flag ();
934b9bac 6427 sync_remote_interrupt (SIGINT);
74531fed
PA
6428 }
6429 }
6430
6431 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6432 _never_ wait for ever -> test on target_is_async_p().
6433 However, before we do that we need to ensure that the caller
6434 knows how to take the target into/out of async mode. */
722247f1 6435 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6436 forever, &is_notif);
722247f1 6437
5e1b953b
SDJ
6438 if (!target_is_async_p ())
6439 signal (SIGINT, ofunc);
6440
722247f1
YQ
6441 /* GDB gets a notification. Return to core as this event is
6442 not interesting. */
6443 if (ret != -1 && is_notif)
6444 return minus_one_ptid;
567420d1
PA
6445
6446 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6447 return minus_one_ptid;
74531fed
PA
6448 }
6449
6450 buf = rs->buf;
6451
f7e6eed5 6452 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed
PA
6453
6454 /* We got something. */
6455 rs->waiting_for_stop_reply = 0;
6456
3a29589a
DJ
6457 /* Assume that the target has acknowledged Ctrl-C unless we receive
6458 an 'F' or 'O' packet. */
6459 if (buf[0] != 'F' && buf[0] != 'O')
6460 rs->ctrlc_pending_p = 0;
6461
74531fed
PA
6462 switch (buf[0])
6463 {
6464 case 'E': /* Error of some sort. */
6465 /* We're out of sync with the target now. Did it continue or
6466 not? Not is more likely, so report a stop. */
6467 warning (_("Remote failure reply: %s"), buf);
6468 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6469 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6470 break;
6471 case 'F': /* File-I/O request. */
3a29589a
DJ
6472 remote_fileio_request (buf, rs->ctrlc_pending_p);
6473 rs->ctrlc_pending_p = 0;
74531fed
PA
6474 break;
6475 case 'T': case 'S': case 'X': case 'W':
6476 {
722247f1
YQ
6477 struct stop_reply *stop_reply
6478 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6479 rs->buf);
74531fed 6480
74531fed 6481 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6482 break;
6483 }
6484 case 'O': /* Console output. */
6485 remote_console_output (buf + 1);
e24a49d8 6486
c8e38a49
PA
6487 /* The target didn't really stop; keep waiting. */
6488 rs->waiting_for_stop_reply = 1;
e24a49d8 6489
c8e38a49
PA
6490 break;
6491 case '\0':
b73be471 6492 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6493 {
6494 /* Zero length reply means that we tried 'S' or 'C' and the
6495 remote system doesn't support it. */
6496 target_terminal_ours_for_output ();
6497 printf_filtered
6498 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6499 gdb_signal_to_name (rs->last_sent_signal));
6500 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6501 target_terminal_inferior ();
6502
280ceea3 6503 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6504 putpkt ((char *) buf);
6505
6506 /* We just told the target to resume, so a stop reply is in
6507 order. */
e24a49d8 6508 rs->waiting_for_stop_reply = 1;
c8e38a49 6509 break;
43ff13b4 6510 }
c8e38a49
PA
6511 /* else fallthrough */
6512 default:
6513 warning (_("Invalid remote reply: %s"), buf);
6514 /* Keep waiting. */
6515 rs->waiting_for_stop_reply = 1;
6516 break;
43ff13b4 6517 }
c8e38a49 6518
c8e38a49 6519 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6520 {
6521 /* Nothing interesting happened. If we're doing a non-blocking
6522 poll, we're done. Otherwise, go back to waiting. */
6523 if (options & TARGET_WNOHANG)
6524 return minus_one_ptid;
6525 else
6526 goto again;
6527 }
74531fed
PA
6528 else if (status->kind != TARGET_WAITKIND_EXITED
6529 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6530 {
6531 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6532 record_currthread (rs, event_ptid);
82f73884
PA
6533 else
6534 event_ptid = inferior_ptid;
43ff13b4 6535 }
74531fed
PA
6536 else
6537 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6538 record_currthread (rs, minus_one_ptid);
79d7f229 6539
82f73884 6540 return event_ptid;
43ff13b4
JM
6541}
6542
74531fed
PA
6543/* Wait until the remote machine stops, then return, storing status in
6544 STATUS just as `wait' would. */
6545
c8e38a49 6546static ptid_t
117de6a9 6547remote_wait (struct target_ops *ops,
47608cb1 6548 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6549{
6550 ptid_t event_ptid;
6551
74531fed 6552 if (non_stop)
47608cb1 6553 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6554 else
47608cb1 6555 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6556
d9d41e78 6557 if (target_is_async_p ())
c8e38a49 6558 {
74531fed
PA
6559 /* If there are are events left in the queue tell the event loop
6560 to return here. */
722247f1 6561 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6562 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6563 }
c8e38a49
PA
6564
6565 return event_ptid;
6566}
6567
74ca34ce 6568/* Fetch a single register using a 'p' packet. */
c906108c 6569
b96ec7ac 6570static int
56be3814 6571fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6572{
6573 struct remote_state *rs = get_remote_state ();
2e9f7625 6574 char *buf, *p;
b96ec7ac
AC
6575 char regp[MAX_REGISTER_SIZE];
6576 int i;
6577
4082afcc 6578 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6579 return 0;
6580
6581 if (reg->pnum == -1)
6582 return 0;
6583
2e9f7625 6584 p = rs->buf;
fcad0fa4 6585 *p++ = 'p';
74ca34ce 6586 p += hexnumstr (p, reg->pnum);
fcad0fa4 6587 *p++ = '\0';
1f4437a4
MS
6588 putpkt (rs->buf);
6589 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6590
2e9f7625
DJ
6591 buf = rs->buf;
6592
74ca34ce
DJ
6593 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6594 {
6595 case PACKET_OK:
6596 break;
6597 case PACKET_UNKNOWN:
6598 return 0;
6599 case PACKET_ERROR:
27a9c0bf
MS
6600 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6601 gdbarch_register_name (get_regcache_arch (regcache),
6602 reg->regnum),
6603 buf);
74ca34ce 6604 }
3f9a994c
JB
6605
6606 /* If this register is unfetchable, tell the regcache. */
6607 if (buf[0] == 'x')
8480adf2 6608 {
56be3814 6609 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6610 return 1;
b96ec7ac 6611 }
b96ec7ac 6612
3f9a994c
JB
6613 /* Otherwise, parse and supply the value. */
6614 p = buf;
6615 i = 0;
6616 while (p[0] != 0)
6617 {
6618 if (p[1] == 0)
74ca34ce 6619 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6620
6621 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6622 p += 2;
6623 }
56be3814 6624 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6625 return 1;
b96ec7ac
AC
6626}
6627
74ca34ce
DJ
6628/* Fetch the registers included in the target's 'g' packet. */
6629
29709017
DJ
6630static int
6631send_g_packet (void)
c906108c 6632{
d01949b6 6633 struct remote_state *rs = get_remote_state ();
cea39f65 6634 int buf_len;
c906108c 6635
bba74b36 6636 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6637 remote_send (&rs->buf, &rs->buf_size);
c906108c 6638
29709017
DJ
6639 /* We can get out of synch in various cases. If the first character
6640 in the buffer is not a hex character, assume that has happened
6641 and try to fetch another packet to read. */
6642 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6643 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6644 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6645 && rs->buf[0] != 'x') /* New: unavailable register value. */
6646 {
6647 if (remote_debug)
6648 fprintf_unfiltered (gdb_stdlog,
6649 "Bad register packet; fetching a new packet\n");
6650 getpkt (&rs->buf, &rs->buf_size, 0);
6651 }
6652
74ca34ce
DJ
6653 buf_len = strlen (rs->buf);
6654
6655 /* Sanity check the received packet. */
6656 if (buf_len % 2 != 0)
6657 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6658
6659 return buf_len / 2;
6660}
6661
6662static void
56be3814 6663process_g_packet (struct regcache *regcache)
29709017 6664{
4a22f64d 6665 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6666 struct remote_state *rs = get_remote_state ();
6667 struct remote_arch_state *rsa = get_remote_arch_state ();
6668 int i, buf_len;
6669 char *p;
6670 char *regs;
6671
6672 buf_len = strlen (rs->buf);
6673
6674 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6675 if (buf_len > 2 * rsa->sizeof_g_packet)
6676 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6677
6678 /* Save the size of the packet sent to us by the target. It is used
6679 as a heuristic when determining the max size of packets that the
6680 target can safely receive. */
6681 if (rsa->actual_register_packet_size == 0)
6682 rsa->actual_register_packet_size = buf_len;
6683
6684 /* If this is smaller than we guessed the 'g' packet would be,
6685 update our records. A 'g' reply that doesn't include a register's
6686 value implies either that the register is not available, or that
6687 the 'p' packet must be used. */
6688 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6689 {
74ca34ce
DJ
6690 rsa->sizeof_g_packet = buf_len / 2;
6691
4a22f64d 6692 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6693 {
74ca34ce
DJ
6694 if (rsa->regs[i].pnum == -1)
6695 continue;
6696
6697 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6698 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6699 else
74ca34ce 6700 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6701 }
74ca34ce 6702 }
b323314b 6703
74ca34ce 6704 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6705
6706 /* Unimplemented registers read as all bits zero. */
ea9c271d 6707 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6708
c906108c
SS
6709 /* Reply describes registers byte by byte, each byte encoded as two
6710 hex characters. Suck them all up, then supply them to the
6711 register cacheing/storage mechanism. */
6712
74ca34ce 6713 p = rs->buf;
ea9c271d 6714 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6715 {
74ca34ce
DJ
6716 if (p[0] == 0 || p[1] == 0)
6717 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6718 internal_error (__FILE__, __LINE__,
9b20d036 6719 _("unexpected end of 'g' packet reply"));
74ca34ce 6720
c906108c 6721 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6722 regs[i] = 0; /* 'x' */
c906108c
SS
6723 else
6724 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6725 p += 2;
6726 }
6727
a744cf53
MS
6728 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6729 {
6730 struct packet_reg *r = &rsa->regs[i];
6731
6732 if (r->in_g_packet)
6733 {
6734 if (r->offset * 2 >= strlen (rs->buf))
6735 /* This shouldn't happen - we adjusted in_g_packet above. */
6736 internal_error (__FILE__, __LINE__,
9b20d036 6737 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6738 else if (rs->buf[r->offset * 2] == 'x')
6739 {
6740 gdb_assert (r->offset * 2 < strlen (rs->buf));
6741 /* The register isn't available, mark it as such (at
6742 the same time setting the value to zero). */
6743 regcache_raw_supply (regcache, r->regnum, NULL);
6744 }
6745 else
6746 regcache_raw_supply (regcache, r->regnum,
6747 regs + r->offset);
6748 }
6749 }
c906108c
SS
6750}
6751
29709017 6752static void
56be3814 6753fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6754{
6755 send_g_packet ();
56be3814 6756 process_g_packet (regcache);
29709017
DJ
6757}
6758
e6e4e701
PA
6759/* Make the remote selected traceframe match GDB's selected
6760 traceframe. */
6761
6762static void
6763set_remote_traceframe (void)
6764{
6765 int newnum;
262e1174 6766 struct remote_state *rs = get_remote_state ();
e6e4e701 6767
262e1174 6768 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6769 return;
6770
6771 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6772 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6773
6774 newnum = target_trace_find (tfind_number,
6775 get_traceframe_number (), 0, 0, NULL);
6776
6777 /* Should not happen. If it does, all bets are off. */
6778 if (newnum != get_traceframe_number ())
6779 warning (_("could not set remote traceframe"));
6780}
6781
74ca34ce 6782static void
28439f5e
PA
6783remote_fetch_registers (struct target_ops *ops,
6784 struct regcache *regcache, int regnum)
74ca34ce 6785{
74ca34ce
DJ
6786 struct remote_arch_state *rsa = get_remote_arch_state ();
6787 int i;
6788
e6e4e701 6789 set_remote_traceframe ();
79d7f229 6790 set_general_thread (inferior_ptid);
74ca34ce
DJ
6791
6792 if (regnum >= 0)
6793 {
6794 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6795
74ca34ce
DJ
6796 gdb_assert (reg != NULL);
6797
6798 /* If this register might be in the 'g' packet, try that first -
6799 we are likely to read more than one register. If this is the
6800 first 'g' packet, we might be overly optimistic about its
6801 contents, so fall back to 'p'. */
6802 if (reg->in_g_packet)
6803 {
56be3814 6804 fetch_registers_using_g (regcache);
74ca34ce
DJ
6805 if (reg->in_g_packet)
6806 return;
6807 }
6808
56be3814 6809 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6810 return;
6811
6812 /* This register is not available. */
56be3814 6813 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6814
6815 return;
6816 }
6817
56be3814 6818 fetch_registers_using_g (regcache);
74ca34ce 6819
4a22f64d 6820 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6821 if (!rsa->regs[i].in_g_packet)
56be3814 6822 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6823 {
6824 /* This register is not available. */
56be3814 6825 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6826 }
6827}
6828
c906108c
SS
6829/* Prepare to store registers. Since we may send them all (using a
6830 'G' request), we have to read out the ones we don't want to change
6831 first. */
6832
c5aa993b 6833static void
f32dbf8c 6834remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6835{
ea9c271d 6836 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6837 int i;
cfd77fa1 6838 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6839
c906108c 6840 /* Make sure the entire registers array is valid. */
4082afcc 6841 switch (packet_support (PACKET_P))
5a2468f5
JM
6842 {
6843 case PACKET_DISABLE:
6844 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6845 /* Make sure all the necessary registers are cached. */
4a22f64d 6846 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6847 if (rsa->regs[i].in_g_packet)
316f2060 6848 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6849 break;
6850 case PACKET_ENABLE:
6851 break;
6852 }
6853}
6854
ad10f812 6855/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6856 packet was not recognized. */
5a2468f5
JM
6857
6858static int
1f4437a4
MS
6859store_register_using_P (const struct regcache *regcache,
6860 struct packet_reg *reg)
5a2468f5 6861{
4a22f64d 6862 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6863 struct remote_state *rs = get_remote_state ();
5a2468f5 6864 /* Try storing a single register. */
6d820c5c 6865 char *buf = rs->buf;
cfd77fa1 6866 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6867 char *p;
5a2468f5 6868
4082afcc 6869 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
6870 return 0;
6871
6872 if (reg->pnum == -1)
6873 return 0;
6874
ea9c271d 6875 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6876 p = buf + strlen (buf);
56be3814 6877 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6878 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6879 putpkt (rs->buf);
6880 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6881
74ca34ce
DJ
6882 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6883 {
6884 case PACKET_OK:
6885 return 1;
6886 case PACKET_ERROR:
27a9c0bf
MS
6887 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6888 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6889 case PACKET_UNKNOWN:
6890 return 0;
6891 default:
6892 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6893 }
c906108c
SS
6894}
6895
23860348
MS
6896/* Store register REGNUM, or all registers if REGNUM == -1, from the
6897 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6898
6899static void
56be3814 6900store_registers_using_G (const struct regcache *regcache)
c906108c 6901{
d01949b6 6902 struct remote_state *rs = get_remote_state ();
ea9c271d 6903 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6904 gdb_byte *regs;
c906108c
SS
6905 char *p;
6906
193cb69f
AC
6907 /* Extract all the registers in the regcache copying them into a
6908 local buffer. */
6909 {
b323314b 6910 int i;
a744cf53 6911
ea9c271d
DJ
6912 regs = alloca (rsa->sizeof_g_packet);
6913 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6914 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6915 {
ea9c271d 6916 struct packet_reg *r = &rsa->regs[i];
a744cf53 6917
b323314b 6918 if (r->in_g_packet)
56be3814 6919 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6920 }
6921 }
c906108c
SS
6922
6923 /* Command describes registers byte by byte,
6924 each byte encoded as two hex characters. */
6d820c5c 6925 p = rs->buf;
193cb69f 6926 *p++ = 'G';
74ca34ce
DJ
6927 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6928 updated. */
6929 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6930 putpkt (rs->buf);
6931 getpkt (&rs->buf, &rs->buf_size, 0);
6932 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6933 error (_("Could not write registers; remote failure reply '%s'"),
6934 rs->buf);
c906108c 6935}
74ca34ce
DJ
6936
6937/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6938 of the register cache buffer. FIXME: ignores errors. */
6939
6940static void
28439f5e
PA
6941remote_store_registers (struct target_ops *ops,
6942 struct regcache *regcache, int regnum)
74ca34ce 6943{
74ca34ce
DJ
6944 struct remote_arch_state *rsa = get_remote_arch_state ();
6945 int i;
6946
e6e4e701 6947 set_remote_traceframe ();
79d7f229 6948 set_general_thread (inferior_ptid);
74ca34ce
DJ
6949
6950 if (regnum >= 0)
6951 {
6952 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6953
74ca34ce
DJ
6954 gdb_assert (reg != NULL);
6955
6956 /* Always prefer to store registers using the 'P' packet if
6957 possible; we often change only a small number of registers.
6958 Sometimes we change a larger number; we'd need help from a
6959 higher layer to know to use 'G'. */
56be3814 6960 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6961 return;
6962
6963 /* For now, don't complain if we have no way to write the
6964 register. GDB loses track of unavailable registers too
6965 easily. Some day, this may be an error. We don't have
0df8b418 6966 any way to read the register, either... */
74ca34ce
DJ
6967 if (!reg->in_g_packet)
6968 return;
6969
56be3814 6970 store_registers_using_G (regcache);
74ca34ce
DJ
6971 return;
6972 }
6973
56be3814 6974 store_registers_using_G (regcache);
74ca34ce 6975
4a22f64d 6976 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6977 if (!rsa->regs[i].in_g_packet)
56be3814 6978 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6979 /* See above for why we do not issue an error here. */
6980 continue;
6981}
c906108c
SS
6982\f
6983
6984/* Return the number of hex digits in num. */
6985
6986static int
fba45db2 6987hexnumlen (ULONGEST num)
c906108c
SS
6988{
6989 int i;
6990
6991 for (i = 0; num != 0; i++)
6992 num >>= 4;
6993
6994 return max (i, 1);
6995}
6996
2df3850c 6997/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
6998
6999static int
fba45db2 7000hexnumstr (char *buf, ULONGEST num)
c906108c 7001{
c906108c 7002 int len = hexnumlen (num);
a744cf53 7003
2df3850c
JM
7004 return hexnumnstr (buf, num, len);
7005}
7006
c906108c 7007
2df3850c 7008/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7009
2df3850c 7010static int
fba45db2 7011hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7012{
7013 int i;
7014
7015 buf[width] = '\0';
7016
7017 for (i = width - 1; i >= 0; i--)
c906108c 7018 {
c5aa993b 7019 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7020 num >>= 4;
7021 }
7022
2df3850c 7023 return width;
c906108c
SS
7024}
7025
23860348 7026/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7027
7028static CORE_ADDR
fba45db2 7029remote_address_masked (CORE_ADDR addr)
c906108c 7030{
883b9c6c 7031 unsigned int address_size = remote_address_size;
a744cf53 7032
911c95a5
UW
7033 /* If "remoteaddresssize" was not set, default to target address size. */
7034 if (!address_size)
f5656ead 7035 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7036
7037 if (address_size > 0
7038 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7039 {
7040 /* Only create a mask when that mask can safely be constructed
23860348 7041 in a ULONGEST variable. */
c906108c 7042 ULONGEST mask = 1;
a744cf53 7043
911c95a5 7044 mask = (mask << address_size) - 1;
c906108c
SS
7045 addr &= mask;
7046 }
7047 return addr;
7048}
7049
7050/* Determine whether the remote target supports binary downloading.
7051 This is accomplished by sending a no-op memory write of zero length
7052 to the target at the specified address. It does not suffice to send
23860348
MS
7053 the whole packet, since many stubs strip the eighth bit and
7054 subsequently compute a wrong checksum, which causes real havoc with
7055 remote_write_bytes.
7a292a7a 7056
96baa820 7057 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7058 clean. In cases like this, the user should clear "remote
23860348 7059 X-packet". */
96baa820 7060
c906108c 7061static void
fba45db2 7062check_binary_download (CORE_ADDR addr)
c906108c 7063{
d01949b6 7064 struct remote_state *rs = get_remote_state ();
24b06219 7065
4082afcc 7066 switch (packet_support (PACKET_X))
c906108c 7067 {
96baa820
JM
7068 case PACKET_DISABLE:
7069 break;
7070 case PACKET_ENABLE:
7071 break;
7072 case PACKET_SUPPORT_UNKNOWN:
7073 {
96baa820 7074 char *p;
802188a7 7075
2e9f7625 7076 p = rs->buf;
96baa820
JM
7077 *p++ = 'X';
7078 p += hexnumstr (p, (ULONGEST) addr);
7079 *p++ = ',';
7080 p += hexnumstr (p, (ULONGEST) 0);
7081 *p++ = ':';
7082 *p = '\0';
802188a7 7083
2e9f7625 7084 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7085 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7086
2e9f7625 7087 if (rs->buf[0] == '\0')
96baa820
JM
7088 {
7089 if (remote_debug)
7090 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7091 "binary downloading NOT "
7092 "supported by target\n");
444abaca 7093 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7094 }
7095 else
7096 {
7097 if (remote_debug)
7098 fprintf_unfiltered (gdb_stdlog,
64b9b334 7099 "binary downloading supported by target\n");
444abaca 7100 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7101 }
7102 break;
7103 }
c906108c
SS
7104 }
7105}
7106
124e13d9
SM
7107/* Helper function to resize the payload in order to try to get a good
7108 alignment. We try to write an amount of data such that the next write will
7109 start on an address aligned on REMOTE_ALIGN_WRITES. */
7110
7111static int
7112align_for_efficient_write (int todo, CORE_ADDR memaddr)
7113{
7114 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7115}
7116
c906108c
SS
7117/* Write memory data directly to the remote machine.
7118 This does not inform the data cache; the data cache uses this.
a76d924d 7119 HEADER is the starting part of the packet.
c906108c
SS
7120 MEMADDR is the address in the remote memory space.
7121 MYADDR is the address of the buffer in our space.
124e13d9
SM
7122 LEN_UNITS is the number of addressable units to write.
7123 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7124 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7125 should send data as binary ('X'), or hex-encoded ('M').
7126
7127 The function creates packet of the form
7128 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7129
124e13d9 7130 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7131
7132 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7133 are omitted.
7134
9b409511 7135 Return the transferred status, error or OK (an
124e13d9
SM
7136 'enum target_xfer_status' value). Save the number of addressable units
7137 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7138
7139 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7140 exchange between gdb and the stub could look like (?? in place of the
7141 checksum):
7142
7143 -> $m1000,4#??
7144 <- aaaabbbbccccdddd
7145
7146 -> $M1000,3:eeeeffffeeee#??
7147 <- OK
7148
7149 -> $m1000,4#??
7150 <- eeeeffffeeeedddd */
c906108c 7151
9b409511 7152static enum target_xfer_status
a76d924d 7153remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7154 const gdb_byte *myaddr, ULONGEST len_units,
7155 int unit_size, ULONGEST *xfered_len_units,
7156 char packet_format, int use_length)
c906108c 7157{
6d820c5c 7158 struct remote_state *rs = get_remote_state ();
cfd77fa1 7159 char *p;
a76d924d
DJ
7160 char *plen = NULL;
7161 int plenlen = 0;
124e13d9
SM
7162 int todo_units;
7163 int units_written;
7164 int payload_capacity_bytes;
7165 int payload_length_bytes;
a76d924d
DJ
7166
7167 if (packet_format != 'X' && packet_format != 'M')
7168 internal_error (__FILE__, __LINE__,
9b20d036 7169 _("remote_write_bytes_aux: bad packet format"));
c906108c 7170
124e13d9 7171 if (len_units == 0)
9b409511 7172 return TARGET_XFER_EOF;
b2182ed2 7173
124e13d9 7174 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7175
6d820c5c
DJ
7176 /* The packet buffer will be large enough for the payload;
7177 get_memory_packet_size ensures this. */
a76d924d 7178 rs->buf[0] = '\0';
c906108c 7179
a257b5bb 7180 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7181 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7182
124e13d9 7183 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7184 if (!use_length)
0df8b418 7185 /* The comma won't be used. */
124e13d9
SM
7186 payload_capacity_bytes += 1;
7187 payload_capacity_bytes -= strlen (header);
7188 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7189
a76d924d 7190 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7191
a76d924d
DJ
7192 strcat (rs->buf, header);
7193 p = rs->buf + strlen (header);
7194
7195 /* Compute a best guess of the number of bytes actually transfered. */
7196 if (packet_format == 'X')
c906108c 7197 {
23860348 7198 /* Best guess at number of bytes that will fit. */
124e13d9 7199 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7200 if (use_length)
124e13d9
SM
7201 payload_capacity_bytes -= hexnumlen (todo_units);
7202 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7203 }
7204 else
7205 {
124e13d9
SM
7206 /* Number of bytes that will fit. */
7207 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7208 if (use_length)
124e13d9
SM
7209 payload_capacity_bytes -= hexnumlen (todo_units);
7210 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7211 }
a76d924d 7212
124e13d9 7213 if (todo_units <= 0)
3de11b2e 7214 internal_error (__FILE__, __LINE__,
405f8e94 7215 _("minimum packet size too small to write data"));
802188a7 7216
6765f3e5
DJ
7217 /* If we already need another packet, then try to align the end
7218 of this packet to a useful boundary. */
124e13d9
SM
7219 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7220 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7221
a257b5bb 7222 /* Append "<memaddr>". */
917317f4
JM
7223 memaddr = remote_address_masked (memaddr);
7224 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7225
a76d924d
DJ
7226 if (use_length)
7227 {
7228 /* Append ",". */
7229 *p++ = ',';
802188a7 7230
124e13d9
SM
7231 /* Append the length and retain its location and size. It may need to be
7232 adjusted once the packet body has been created. */
a76d924d 7233 plen = p;
124e13d9 7234 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7235 p += plenlen;
7236 }
a257b5bb
AC
7237
7238 /* Append ":". */
917317f4
JM
7239 *p++ = ':';
7240 *p = '\0';
802188a7 7241
a257b5bb 7242 /* Append the packet body. */
a76d924d 7243 if (packet_format == 'X')
917317f4 7244 {
917317f4
JM
7245 /* Binary mode. Send target system values byte by byte, in
7246 increasing byte addresses. Only escape certain critical
7247 characters. */
124e13d9
SM
7248 payload_length_bytes =
7249 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7250 &units_written, payload_capacity_bytes);
6765f3e5 7251
124e13d9 7252 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7253 a second try to keep the end of the packet aligned. Don't do
7254 this if the packet is tiny. */
124e13d9 7255 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7256 {
124e13d9
SM
7257 int new_todo_units;
7258
7259 new_todo_units = align_for_efficient_write (units_written, memaddr);
7260
7261 if (new_todo_units != units_written)
7262 payload_length_bytes =
7263 remote_escape_output (myaddr, new_todo_units, unit_size,
7264 (gdb_byte *) p, &units_written,
7265 payload_capacity_bytes);
6765f3e5
DJ
7266 }
7267
124e13d9
SM
7268 p += payload_length_bytes;
7269 if (use_length && units_written < todo_units)
c906108c 7270 {
802188a7 7271 /* Escape chars have filled up the buffer prematurely,
124e13d9 7272 and we have actually sent fewer units than planned.
917317f4
JM
7273 Fix-up the length field of the packet. Use the same
7274 number of characters as before. */
124e13d9
SM
7275 plen += hexnumnstr (plen, (ULONGEST) units_written,
7276 plenlen);
917317f4 7277 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7278 }
a76d924d
DJ
7279 }
7280 else
7281 {
917317f4
JM
7282 /* Normal mode: Send target system values byte by byte, in
7283 increasing byte addresses. Each byte is encoded as a two hex
7284 value. */
124e13d9
SM
7285 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7286 units_written = todo_units;
c906108c 7287 }
802188a7 7288
2e9f7625 7289 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7290 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7291
2e9f7625 7292 if (rs->buf[0] == 'E')
00d84524 7293 return TARGET_XFER_E_IO;
802188a7 7294
124e13d9
SM
7295 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7296 send fewer units than we'd planned. */
7297 *xfered_len_units = (ULONGEST) units_written;
9b409511 7298 return TARGET_XFER_OK;
c906108c
SS
7299}
7300
a76d924d
DJ
7301/* Write memory data directly to the remote machine.
7302 This does not inform the data cache; the data cache uses this.
7303 MEMADDR is the address in the remote memory space.
7304 MYADDR is the address of the buffer in our space.
7305 LEN is the number of bytes.
7306
9b409511
YQ
7307 Return the transferred status, error or OK (an
7308 'enum target_xfer_status' value). Save the number of bytes
7309 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7310
9b409511
YQ
7311static enum target_xfer_status
7312remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7313 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7314{
7315 char *packet_format = 0;
7316
7317 /* Check whether the target supports binary download. */
7318 check_binary_download (memaddr);
7319
4082afcc 7320 switch (packet_support (PACKET_X))
a76d924d
DJ
7321 {
7322 case PACKET_ENABLE:
7323 packet_format = "X";
7324 break;
7325 case PACKET_DISABLE:
7326 packet_format = "M";
7327 break;
7328 case PACKET_SUPPORT_UNKNOWN:
7329 internal_error (__FILE__, __LINE__,
7330 _("remote_write_bytes: bad internal state"));
7331 default:
7332 internal_error (__FILE__, __LINE__, _("bad switch"));
7333 }
7334
7335 return remote_write_bytes_aux (packet_format,
124e13d9 7336 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7337 packet_format[0], 1);
a76d924d
DJ
7338}
7339
9217e74e
YQ
7340/* Read memory data directly from the remote machine.
7341 This does not use the data cache; the data cache uses this.
7342 MEMADDR is the address in the remote memory space.
7343 MYADDR is the address of the buffer in our space.
124e13d9
SM
7344 LEN_UNITS is the number of addressable memory units to read..
7345 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7346
7347 Return the transferred status, error or OK (an
7348 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7349 transferred in *XFERED_LEN_UNITS.
7350
7351 See the comment of remote_write_bytes_aux for an example of
7352 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7353
7354static enum target_xfer_status
124e13d9
SM
7355remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7356 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7357{
7358 struct remote_state *rs = get_remote_state ();
124e13d9 7359 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7360 char *p;
124e13d9
SM
7361 int todo_units;
7362 int decoded_bytes;
9217e74e 7363
124e13d9 7364 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7365 /* The packet buffer will be large enough for the payload;
7366 get_memory_packet_size ensures this. */
7367
124e13d9
SM
7368 /* Number of units that will fit. */
7369 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7370
7371 /* Construct "m"<memaddr>","<len>". */
7372 memaddr = remote_address_masked (memaddr);
7373 p = rs->buf;
7374 *p++ = 'm';
7375 p += hexnumstr (p, (ULONGEST) memaddr);
7376 *p++ = ',';
124e13d9 7377 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7378 *p = '\0';
7379 putpkt (rs->buf);
7380 getpkt (&rs->buf, &rs->buf_size, 0);
7381 if (rs->buf[0] == 'E'
7382 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7383 && rs->buf[3] == '\0')
7384 return TARGET_XFER_E_IO;
7385 /* Reply describes memory byte by byte, each byte encoded as two hex
7386 characters. */
7387 p = rs->buf;
124e13d9 7388 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7389 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7390 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7391 return TARGET_XFER_OK;
7392}
7393
b55fbac4
YQ
7394/* Using the set of read-only target sections of remote, read live
7395 read-only memory.
8acf9577
YQ
7396
7397 For interface/parameters/return description see target.h,
7398 to_xfer_partial. */
7399
7400static enum target_xfer_status
b55fbac4
YQ
7401remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7402 ULONGEST memaddr, ULONGEST len,
124e13d9 7403 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7404{
7405 struct target_section *secp;
7406 struct target_section_table *table;
7407
7408 secp = target_section_by_addr (ops, memaddr);
7409 if (secp != NULL
7410 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7411 secp->the_bfd_section)
7412 & SEC_READONLY))
7413 {
7414 struct target_section *p;
7415 ULONGEST memend = memaddr + len;
7416
7417 table = target_get_section_table (ops);
7418
7419 for (p = table->sections; p < table->sections_end; p++)
7420 {
7421 if (memaddr >= p->addr)
7422 {
7423 if (memend <= p->endaddr)
7424 {
7425 /* Entire transfer is within this section. */
124e13d9 7426 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7427 xfered_len);
8acf9577
YQ
7428 }
7429 else if (memaddr >= p->endaddr)
7430 {
7431 /* This section ends before the transfer starts. */
7432 continue;
7433 }
7434 else
7435 {
7436 /* This section overlaps the transfer. Just do half. */
7437 len = p->endaddr - memaddr;
124e13d9 7438 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7439 xfered_len);
8acf9577
YQ
7440 }
7441 }
7442 }
7443 }
7444
7445 return TARGET_XFER_EOF;
7446}
7447
9217e74e
YQ
7448/* Similar to remote_read_bytes_1, but it reads from the remote stub
7449 first if the requested memory is unavailable in traceframe.
7450 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7451
9b409511 7452static enum target_xfer_status
8acf9577 7453remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7454 gdb_byte *myaddr, ULONGEST len, int unit_size,
7455 ULONGEST *xfered_len)
c906108c 7456{
6b6aa828 7457 if (len == 0)
96c4f946 7458 return TARGET_XFER_EOF;
b2182ed2 7459
8acf9577
YQ
7460 if (get_traceframe_number () != -1)
7461 {
7462 VEC(mem_range_s) *available;
7463
7464 /* If we fail to get the set of available memory, then the
7465 target does not support querying traceframe info, and so we
7466 attempt reading from the traceframe anyway (assuming the
7467 target implements the old QTro packet then). */
7468 if (traceframe_available_memory (&available, memaddr, len))
7469 {
7470 struct cleanup *old_chain;
7471
7472 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7473
7474 if (VEC_empty (mem_range_s, available)
7475 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7476 {
7477 enum target_xfer_status res;
7478
7479 /* Don't read into the traceframe's available
7480 memory. */
7481 if (!VEC_empty (mem_range_s, available))
7482 {
7483 LONGEST oldlen = len;
7484
7485 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7486 gdb_assert (len <= oldlen);
7487 }
7488
7489 do_cleanups (old_chain);
7490
7491 /* This goes through the topmost target again. */
b55fbac4 7492 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7493 len, unit_size, xfered_len);
8acf9577
YQ
7494 if (res == TARGET_XFER_OK)
7495 return TARGET_XFER_OK;
7496 else
7497 {
7498 /* No use trying further, we know some memory starting
7499 at MEMADDR isn't available. */
7500 *xfered_len = len;
7501 return TARGET_XFER_UNAVAILABLE;
7502 }
7503 }
7504
7505 /* Don't try to read more than how much is available, in
7506 case the target implements the deprecated QTro packet to
7507 cater for older GDBs (the target's knowledge of read-only
7508 sections may be outdated by now). */
7509 len = VEC_index (mem_range_s, available, 0)->length;
7510
7511 do_cleanups (old_chain);
7512 }
7513 }
7514
124e13d9 7515 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7516}
74531fed 7517
c906108c 7518\f
c906108c 7519
a76d924d
DJ
7520/* Sends a packet with content determined by the printf format string
7521 FORMAT and the remaining arguments, then gets the reply. Returns
7522 whether the packet was a success, a failure, or unknown. */
7523
77b64a49
PA
7524static enum packet_result remote_send_printf (const char *format, ...)
7525 ATTRIBUTE_PRINTF (1, 2);
7526
2c0b251b 7527static enum packet_result
a76d924d
DJ
7528remote_send_printf (const char *format, ...)
7529{
7530 struct remote_state *rs = get_remote_state ();
7531 int max_size = get_remote_packet_size ();
a76d924d 7532 va_list ap;
a744cf53 7533
a76d924d
DJ
7534 va_start (ap, format);
7535
7536 rs->buf[0] = '\0';
7537 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7538 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7539
7540 if (putpkt (rs->buf) < 0)
7541 error (_("Communication problem with target."));
7542
7543 rs->buf[0] = '\0';
7544 getpkt (&rs->buf, &rs->buf_size, 0);
7545
7546 return packet_check_result (rs->buf);
7547}
7548
7549static void
7550restore_remote_timeout (void *p)
7551{
7552 int value = *(int *)p;
a744cf53 7553
a76d924d
DJ
7554 remote_timeout = value;
7555}
7556
7557/* Flash writing can take quite some time. We'll set
7558 effectively infinite timeout for flash operations.
7559 In future, we'll need to decide on a better approach. */
7560static const int remote_flash_timeout = 1000;
7561
7562static void
7563remote_flash_erase (struct target_ops *ops,
7564 ULONGEST address, LONGEST length)
7565{
f5656ead 7566 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7567 int saved_remote_timeout = remote_timeout;
7568 enum packet_result ret;
a76d924d
DJ
7569 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7570 &saved_remote_timeout);
a744cf53 7571
a76d924d
DJ
7572 remote_timeout = remote_flash_timeout;
7573
7574 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7575 phex (address, addr_size),
a76d924d
DJ
7576 phex (length, 4));
7577 switch (ret)
7578 {
7579 case PACKET_UNKNOWN:
7580 error (_("Remote target does not support flash erase"));
7581 case PACKET_ERROR:
7582 error (_("Error erasing flash with vFlashErase packet"));
7583 default:
7584 break;
7585 }
7586
7587 do_cleanups (back_to);
7588}
7589
9b409511
YQ
7590static enum target_xfer_status
7591remote_flash_write (struct target_ops *ops, ULONGEST address,
7592 ULONGEST length, ULONGEST *xfered_len,
7593 const gdb_byte *data)
a76d924d
DJ
7594{
7595 int saved_remote_timeout = remote_timeout;
9b409511 7596 enum target_xfer_status ret;
a76d924d 7597 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7598 &saved_remote_timeout);
a76d924d
DJ
7599
7600 remote_timeout = remote_flash_timeout;
124e13d9 7601 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 7602 xfered_len,'X', 0);
a76d924d
DJ
7603 do_cleanups (back_to);
7604
7605 return ret;
7606}
7607
7608static void
7609remote_flash_done (struct target_ops *ops)
7610{
7611 int saved_remote_timeout = remote_timeout;
7612 int ret;
7613 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7614 &saved_remote_timeout);
7615
7616 remote_timeout = remote_flash_timeout;
7617 ret = remote_send_printf ("vFlashDone");
7618 do_cleanups (back_to);
7619
7620 switch (ret)
7621 {
7622 case PACKET_UNKNOWN:
7623 error (_("Remote target does not support vFlashDone"));
7624 case PACKET_ERROR:
7625 error (_("Error finishing flash operation"));
7626 default:
7627 break;
7628 }
7629}
7630
c906108c 7631static void
fba45db2 7632remote_files_info (struct target_ops *ignore)
c906108c
SS
7633{
7634 puts_filtered ("Debugging a target over a serial line.\n");
7635}
7636\f
7637/* Stuff for dealing with the packets which are part of this protocol.
7638 See comment at top of file for details. */
7639
1927e618
PA
7640/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7641 error to higher layers. Called when a serial error is detected.
7642 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7643 the system error message for errno at function entry and final dot
7644 for output compatibility with throw_perror_with_name. */
1927e618
PA
7645
7646static void
7647unpush_and_perror (const char *string)
7648{
d6cb50a2 7649 int saved_errno = errno;
1927e618
PA
7650
7651 remote_unpush_target ();
d6cb50a2
JK
7652 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7653 safe_strerror (saved_errno));
1927e618
PA
7654}
7655
0876f84a 7656/* Read a single character from the remote end. */
c906108c
SS
7657
7658static int
fba45db2 7659readchar (int timeout)
c906108c
SS
7660{
7661 int ch;
5d93a237 7662 struct remote_state *rs = get_remote_state ();
c906108c 7663
5d93a237 7664 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7665
2acceee2 7666 if (ch >= 0)
0876f84a 7667 return ch;
2acceee2
JM
7668
7669 switch ((enum serial_rc) ch)
c906108c
SS
7670 {
7671 case SERIAL_EOF:
78a095c3 7672 remote_unpush_target ();
598d3636 7673 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7674 /* no return */
c906108c 7675 case SERIAL_ERROR:
1927e618
PA
7676 unpush_and_perror (_("Remote communication error. "
7677 "Target disconnected."));
2acceee2 7678 /* no return */
c906108c 7679 case SERIAL_TIMEOUT:
2acceee2 7680 break;
c906108c 7681 }
2acceee2 7682 return ch;
c906108c
SS
7683}
7684
c33e31fd
PA
7685/* Wrapper for serial_write that closes the target and throws if
7686 writing fails. */
7687
7688static void
7689remote_serial_write (const char *str, int len)
7690{
5d93a237
TT
7691 struct remote_state *rs = get_remote_state ();
7692
7693 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7694 {
1927e618
PA
7695 unpush_and_perror (_("Remote communication error. "
7696 "Target disconnected."));
c33e31fd
PA
7697 }
7698}
7699
6d820c5c
DJ
7700/* Send the command in *BUF to the remote machine, and read the reply
7701 into *BUF. Report an error if we get an error reply. Resize
7702 *BUF using xrealloc if necessary to hold the result, and update
7703 *SIZEOF_BUF. */
c906108c
SS
7704
7705static void
6d820c5c
DJ
7706remote_send (char **buf,
7707 long *sizeof_buf)
c906108c 7708{
6d820c5c 7709 putpkt (*buf);
c2d11a7d 7710 getpkt (buf, sizeof_buf, 0);
c906108c 7711
6d820c5c
DJ
7712 if ((*buf)[0] == 'E')
7713 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7714}
7715
6e5abd65
PA
7716/* Return a pointer to an xmalloc'ed string representing an escaped
7717 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7718 etc. The caller is responsible for releasing the returned
7719 memory. */
7720
7721static char *
7722escape_buffer (const char *buf, int n)
7723{
7724 struct cleanup *old_chain;
7725 struct ui_file *stb;
7726 char *str;
6e5abd65
PA
7727
7728 stb = mem_fileopen ();
7729 old_chain = make_cleanup_ui_file_delete (stb);
7730
6ef284bd 7731 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 7732 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7733 do_cleanups (old_chain);
7734 return str;
7735}
7736
c906108c
SS
7737/* Display a null-terminated packet on stdout, for debugging, using C
7738 string notation. */
7739
7740static void
baa336ce 7741print_packet (const char *buf)
c906108c
SS
7742{
7743 puts_filtered ("\"");
43e526b9 7744 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7745 puts_filtered ("\"");
7746}
7747
7748int
baa336ce 7749putpkt (const char *buf)
c906108c
SS
7750{
7751 return putpkt_binary (buf, strlen (buf));
7752}
7753
7754/* Send a packet to the remote machine, with error checking. The data
23860348 7755 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7756 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7757 and for a possible /0 if we are debugging (remote_debug) and want
7758 to print the sent packet as a string. */
c906108c
SS
7759
7760static int
baa336ce 7761putpkt_binary (const char *buf, int cnt)
c906108c 7762{
2d717e4f 7763 struct remote_state *rs = get_remote_state ();
c906108c
SS
7764 int i;
7765 unsigned char csum = 0;
11cf8741 7766 char *buf2 = alloca (cnt + 6);
085dd6e6 7767
c906108c
SS
7768 int ch;
7769 int tcount = 0;
7770 char *p;
dd61ec5c 7771 char *message;
c906108c 7772
e24a49d8
PA
7773 /* Catch cases like trying to read memory or listing threads while
7774 we're waiting for a stop reply. The remote server wouldn't be
7775 ready to handle this request, so we'd hang and timeout. We don't
7776 have to worry about this in synchronous mode, because in that
7777 case it's not possible to issue a command while the target is
74531fed
PA
7778 running. This is not a problem in non-stop mode, because in that
7779 case, the stub is always ready to process serial input. */
d9d41e78 7780 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
9597b22a
DE
7781 {
7782 error (_("Cannot execute this command while the target is running.\n"
7783 "Use the \"interrupt\" command to stop the target\n"
7784 "and then try again."));
7785 }
e24a49d8 7786
2d717e4f
DJ
7787 /* We're sending out a new packet. Make sure we don't look at a
7788 stale cached response. */
7789 rs->cached_wait_status = 0;
7790
c906108c
SS
7791 /* Copy the packet into buffer BUF2, encapsulating it
7792 and giving it a checksum. */
7793
c906108c
SS
7794 p = buf2;
7795 *p++ = '$';
7796
7797 for (i = 0; i < cnt; i++)
7798 {
7799 csum += buf[i];
7800 *p++ = buf[i];
7801 }
7802 *p++ = '#';
7803 *p++ = tohex ((csum >> 4) & 0xf);
7804 *p++ = tohex (csum & 0xf);
7805
7806 /* Send it over and over until we get a positive ack. */
7807
7808 while (1)
7809 {
7810 int started_error_output = 0;
7811
7812 if (remote_debug)
7813 {
6e5abd65
PA
7814 struct cleanup *old_chain;
7815 char *str;
7816
c906108c 7817 *p = '\0';
6e5abd65
PA
7818 str = escape_buffer (buf2, p - buf2);
7819 old_chain = make_cleanup (xfree, str);
7820 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7821 gdb_flush (gdb_stdlog);
6e5abd65 7822 do_cleanups (old_chain);
c906108c 7823 }
c33e31fd 7824 remote_serial_write (buf2, p - buf2);
c906108c 7825
a6f3e723
SL
7826 /* If this is a no acks version of the remote protocol, send the
7827 packet and move on. */
7828 if (rs->noack_mode)
7829 break;
7830
74531fed
PA
7831 /* Read until either a timeout occurs (-2) or '+' is read.
7832 Handle any notification that arrives in the mean time. */
c906108c
SS
7833 while (1)
7834 {
7835 ch = readchar (remote_timeout);
7836
c5aa993b 7837 if (remote_debug)
c906108c
SS
7838 {
7839 switch (ch)
7840 {
7841 case '+':
1216fa2c 7842 case '-':
c906108c
SS
7843 case SERIAL_TIMEOUT:
7844 case '$':
74531fed 7845 case '%':
c906108c
SS
7846 if (started_error_output)
7847 {
7848 putchar_unfiltered ('\n');
7849 started_error_output = 0;
7850 }
7851 }
7852 }
7853
7854 switch (ch)
7855 {
7856 case '+':
7857 if (remote_debug)
0f71a2f6 7858 fprintf_unfiltered (gdb_stdlog, "Ack\n");
c906108c 7859 return 1;
1216fa2c
AC
7860 case '-':
7861 if (remote_debug)
7862 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7863 /* FALLTHROUGH */
c906108c 7864 case SERIAL_TIMEOUT:
c5aa993b 7865 tcount++;
c906108c
SS
7866 if (tcount > 3)
7867 return 0;
23860348 7868 break; /* Retransmit buffer. */
c906108c
SS
7869 case '$':
7870 {
40e3f985 7871 if (remote_debug)
2bc416ba 7872 fprintf_unfiltered (gdb_stdlog,
23860348 7873 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7874 /* It's probably an old response sent because an ACK
7875 was lost. Gobble up the packet and ack it so it
7876 doesn't get retransmitted when we resend this
7877 packet. */
6d820c5c 7878 skip_frame ();
c33e31fd 7879 remote_serial_write ("+", 1);
23860348 7880 continue; /* Now, go look for +. */
c906108c 7881 }
74531fed
PA
7882
7883 case '%':
7884 {
7885 int val;
7886
7887 /* If we got a notification, handle it, and go back to looking
7888 for an ack. */
7889 /* We've found the start of a notification. Now
7890 collect the data. */
7891 val = read_frame (&rs->buf, &rs->buf_size);
7892 if (val >= 0)
7893 {
7894 if (remote_debug)
7895 {
6e5abd65
PA
7896 struct cleanup *old_chain;
7897 char *str;
7898
7899 str = escape_buffer (rs->buf, val);
7900 old_chain = make_cleanup (xfree, str);
7901 fprintf_unfiltered (gdb_stdlog,
7902 " Notification received: %s\n",
7903 str);
7904 do_cleanups (old_chain);
74531fed 7905 }
5965e028 7906 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7907 /* We're in sync now, rewait for the ack. */
7908 tcount = 0;
7909 }
7910 else
7911 {
7912 if (remote_debug)
7913 {
7914 if (!started_error_output)
7915 {
7916 started_error_output = 1;
7917 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7918 }
7919 fputc_unfiltered (ch & 0177, gdb_stdlog);
7920 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7921 }
7922 }
7923 continue;
7924 }
7925 /* fall-through */
c906108c
SS
7926 default:
7927 if (remote_debug)
7928 {
7929 if (!started_error_output)
7930 {
7931 started_error_output = 1;
0f71a2f6 7932 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7933 }
0f71a2f6 7934 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7935 }
7936 continue;
7937 }
23860348 7938 break; /* Here to retransmit. */
c906108c
SS
7939 }
7940
7941#if 0
7942 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7943 able to get out next time we call QUIT, without anything as
7944 violent as interrupt_query. If we want to provide a way out of
7945 here without getting to the next QUIT, it should be based on
7946 hitting ^C twice as in remote_wait. */
c906108c
SS
7947 if (quit_flag)
7948 {
7949 quit_flag = 0;
7950 interrupt_query ();
7951 }
7952#endif
7953 }
a6f3e723 7954 return 0;
c906108c
SS
7955}
7956
6d820c5c
DJ
7957/* Come here after finding the start of a frame when we expected an
7958 ack. Do our best to discard the rest of this packet. */
7959
7960static void
7961skip_frame (void)
7962{
7963 int c;
7964
7965 while (1)
7966 {
7967 c = readchar (remote_timeout);
7968 switch (c)
7969 {
7970 case SERIAL_TIMEOUT:
7971 /* Nothing we can do. */
7972 return;
7973 case '#':
7974 /* Discard the two bytes of checksum and stop. */
7975 c = readchar (remote_timeout);
7976 if (c >= 0)
7977 c = readchar (remote_timeout);
7978
7979 return;
7980 case '*': /* Run length encoding. */
7981 /* Discard the repeat count. */
7982 c = readchar (remote_timeout);
7983 if (c < 0)
7984 return;
7985 break;
7986 default:
7987 /* A regular character. */
7988 break;
7989 }
7990 }
7991}
7992
c906108c 7993/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
7994 into *BUF, verifying the checksum, length, and handling run-length
7995 compression. NUL terminate the buffer. If there is not enough room,
7996 expand *BUF using xrealloc.
c906108c 7997
c2d11a7d
JM
7998 Returns -1 on error, number of characters in buffer (ignoring the
7999 trailing NULL) on success. (could be extended to return one of the
23860348 8000 SERIAL status indications). */
c2d11a7d
JM
8001
8002static long
6d820c5c
DJ
8003read_frame (char **buf_p,
8004 long *sizeof_buf)
c906108c
SS
8005{
8006 unsigned char csum;
c2d11a7d 8007 long bc;
c906108c 8008 int c;
6d820c5c 8009 char *buf = *buf_p;
a6f3e723 8010 struct remote_state *rs = get_remote_state ();
c906108c
SS
8011
8012 csum = 0;
c2d11a7d 8013 bc = 0;
c906108c
SS
8014
8015 while (1)
8016 {
8017 c = readchar (remote_timeout);
c906108c
SS
8018 switch (c)
8019 {
8020 case SERIAL_TIMEOUT:
8021 if (remote_debug)
0f71a2f6 8022 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8023 return -1;
c906108c
SS
8024 case '$':
8025 if (remote_debug)
0f71a2f6
JM
8026 fputs_filtered ("Saw new packet start in middle of old one\n",
8027 gdb_stdlog);
23860348 8028 return -1; /* Start a new packet, count retries. */
c906108c
SS
8029 case '#':
8030 {
8031 unsigned char pktcsum;
e1b09194
AC
8032 int check_0 = 0;
8033 int check_1 = 0;
c906108c 8034
c2d11a7d 8035 buf[bc] = '\0';
c906108c 8036
e1b09194
AC
8037 check_0 = readchar (remote_timeout);
8038 if (check_0 >= 0)
8039 check_1 = readchar (remote_timeout);
802188a7 8040
e1b09194
AC
8041 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8042 {
8043 if (remote_debug)
2bc416ba 8044 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8045 gdb_stdlog);
e1b09194
AC
8046 return -1;
8047 }
8048 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8049 {
8050 if (remote_debug)
2bc416ba 8051 fputs_filtered ("Communication error in checksum\n",
23860348 8052 gdb_stdlog);
40e3f985
FN
8053 return -1;
8054 }
c906108c 8055
a6f3e723
SL
8056 /* Don't recompute the checksum; with no ack packets we
8057 don't have any way to indicate a packet retransmission
8058 is necessary. */
8059 if (rs->noack_mode)
8060 return bc;
8061
e1b09194 8062 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8063 if (csum == pktcsum)
c2d11a7d 8064 return bc;
c906108c 8065
c5aa993b 8066 if (remote_debug)
c906108c 8067 {
6e5abd65
PA
8068 struct cleanup *old_chain;
8069 char *str;
8070
8071 str = escape_buffer (buf, bc);
8072 old_chain = make_cleanup (xfree, str);
8073 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8074 "Bad checksum, sentsum=0x%x, "
8075 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8076 pktcsum, csum, str);
8077 do_cleanups (old_chain);
c906108c 8078 }
c2d11a7d 8079 /* Number of characters in buffer ignoring trailing
23860348 8080 NULL. */
c2d11a7d 8081 return -1;
c906108c 8082 }
23860348 8083 case '*': /* Run length encoding. */
c2c6d25f
JM
8084 {
8085 int repeat;
c906108c 8086
a744cf53 8087 csum += c;
b4501125
AC
8088 c = readchar (remote_timeout);
8089 csum += c;
23860348 8090 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8091
23860348 8092 /* The character before ``*'' is repeated. */
c2d11a7d 8093
6d820c5c 8094 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8095 {
6d820c5c
DJ
8096 if (bc + repeat - 1 >= *sizeof_buf - 1)
8097 {
8098 /* Make some more room in the buffer. */
8099 *sizeof_buf += repeat;
8100 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8101 buf = *buf_p;
8102 }
8103
c2d11a7d
JM
8104 memset (&buf[bc], buf[bc - 1], repeat);
8105 bc += repeat;
c2c6d25f
JM
8106 continue;
8107 }
8108
c2d11a7d 8109 buf[bc] = '\0';
6d820c5c 8110 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8111 return -1;
c2c6d25f 8112 }
c906108c 8113 default:
6d820c5c 8114 if (bc >= *sizeof_buf - 1)
c906108c 8115 {
6d820c5c
DJ
8116 /* Make some more room in the buffer. */
8117 *sizeof_buf *= 2;
8118 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8119 buf = *buf_p;
c906108c
SS
8120 }
8121
6d820c5c
DJ
8122 buf[bc++] = c;
8123 csum += c;
8124 continue;
c906108c
SS
8125 }
8126 }
8127}
8128
8129/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8130 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8131 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8132 rather than timing out; this is used (in synchronous mode) to wait
8133 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8134/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8135 don't have to change all the calls to getpkt to deal with the
8136 return value, because at the moment I don't know what the right
23860348 8137 thing to do it for those. */
c906108c 8138void
6d820c5c
DJ
8139getpkt (char **buf,
8140 long *sizeof_buf,
c2d11a7d 8141 int forever)
d9fcf2fb
JM
8142{
8143 int timed_out;
8144
8145 timed_out = getpkt_sane (buf, sizeof_buf, forever);
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. If FOREVER ==
8154 0, this function is allowed to time out gracefully and return an
74531fed
PA
8155 indication of this to the caller. Otherwise return the number of
8156 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8157 enough reason to return to the caller. *IS_NOTIF is an output
8158 boolean that indicates whether *BUF holds a notification or not
8159 (a regular packet). */
74531fed 8160
3172dc30 8161static int
74531fed 8162getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8163 int expecting_notif, int *is_notif)
c906108c 8164{
2d717e4f 8165 struct remote_state *rs = get_remote_state ();
c906108c
SS
8166 int c;
8167 int tries;
8168 int timeout;
df4b58fe 8169 int val = -1;
c906108c 8170
2d717e4f
DJ
8171 /* We're reading a new response. Make sure we don't look at a
8172 previously cached response. */
8173 rs->cached_wait_status = 0;
8174
6d820c5c 8175 strcpy (*buf, "timeout");
c906108c
SS
8176
8177 if (forever)
74531fed
PA
8178 timeout = watchdog > 0 ? watchdog : -1;
8179 else if (expecting_notif)
8180 timeout = 0; /* There should already be a char in the buffer. If
8181 not, bail out. */
c906108c
SS
8182 else
8183 timeout = remote_timeout;
8184
8185#define MAX_TRIES 3
8186
74531fed
PA
8187 /* Process any number of notifications, and then return when
8188 we get a packet. */
8189 for (;;)
c906108c 8190 {
d9c43928 8191 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8192 times. */
8193 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8194 {
74531fed
PA
8195 /* This can loop forever if the remote side sends us
8196 characters continuously, but if it pauses, we'll get
8197 SERIAL_TIMEOUT from readchar because of timeout. Then
8198 we'll count that as a retry.
8199
8200 Note that even when forever is set, we will only wait
8201 forever prior to the start of a packet. After that, we
8202 expect characters to arrive at a brisk pace. They should
8203 show up within remote_timeout intervals. */
8204 do
8205 c = readchar (timeout);
8206 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8207
8208 if (c == SERIAL_TIMEOUT)
8209 {
74531fed
PA
8210 if (expecting_notif)
8211 return -1; /* Don't complain, it's normal to not get
8212 anything in this case. */
8213
23860348 8214 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8215 {
2acceee2 8216 QUIT;
78a095c3 8217 remote_unpush_target ();
598d3636
JK
8218 throw_error (TARGET_CLOSE_ERROR,
8219 _("Watchdog timeout has expired. "
8220 "Target detached."));
c906108c 8221 }
c906108c 8222 if (remote_debug)
0f71a2f6 8223 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8224 }
74531fed
PA
8225 else
8226 {
8227 /* We've found the start of a packet or notification.
8228 Now collect the data. */
8229 val = read_frame (buf, sizeof_buf);
8230 if (val >= 0)
8231 break;
8232 }
8233
c33e31fd 8234 remote_serial_write ("-", 1);
c906108c 8235 }
c906108c 8236
74531fed
PA
8237 if (tries > MAX_TRIES)
8238 {
8239 /* We have tried hard enough, and just can't receive the
8240 packet/notification. Give up. */
8241 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8242
74531fed
PA
8243 /* Skip the ack char if we're in no-ack mode. */
8244 if (!rs->noack_mode)
c33e31fd 8245 remote_serial_write ("+", 1);
74531fed
PA
8246 return -1;
8247 }
c906108c 8248
74531fed
PA
8249 /* If we got an ordinary packet, return that to our caller. */
8250 if (c == '$')
c906108c
SS
8251 {
8252 if (remote_debug)
43e526b9 8253 {
6e5abd65
PA
8254 struct cleanup *old_chain;
8255 char *str;
8256
8257 str = escape_buffer (*buf, val);
8258 old_chain = make_cleanup (xfree, str);
8259 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8260 do_cleanups (old_chain);
43e526b9 8261 }
a6f3e723
SL
8262
8263 /* Skip the ack char if we're in no-ack mode. */
8264 if (!rs->noack_mode)
c33e31fd 8265 remote_serial_write ("+", 1);
fee9eda9
YQ
8266 if (is_notif != NULL)
8267 *is_notif = 0;
0876f84a 8268 return val;
c906108c
SS
8269 }
8270
74531fed
PA
8271 /* If we got a notification, handle it, and go back to looking
8272 for a packet. */
8273 else
8274 {
8275 gdb_assert (c == '%');
8276
8277 if (remote_debug)
8278 {
6e5abd65
PA
8279 struct cleanup *old_chain;
8280 char *str;
8281
8282 str = escape_buffer (*buf, val);
8283 old_chain = make_cleanup (xfree, str);
8284 fprintf_unfiltered (gdb_stdlog,
8285 " Notification received: %s\n",
8286 str);
8287 do_cleanups (old_chain);
74531fed 8288 }
fee9eda9
YQ
8289 if (is_notif != NULL)
8290 *is_notif = 1;
c906108c 8291
5965e028 8292 handle_notification (rs->notif_state, *buf);
c906108c 8293
74531fed 8294 /* Notifications require no acknowledgement. */
a6f3e723 8295
74531fed 8296 if (expecting_notif)
fee9eda9 8297 return val;
74531fed
PA
8298 }
8299 }
8300}
8301
8302static int
8303getpkt_sane (char **buf, long *sizeof_buf, int forever)
8304{
fee9eda9 8305 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8306}
8307
8308static int
fee9eda9
YQ
8309getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8310 int *is_notif)
74531fed 8311{
fee9eda9
YQ
8312 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8313 is_notif);
c906108c 8314}
74531fed 8315
cbb8991c
DB
8316/* Check whether EVENT is a fork event for the process specified
8317 by the pid passed in DATA, and if it is, kill the fork child. */
8318
8319static int
8320kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8321 QUEUE_ITER (stop_reply_p) *iter,
8322 stop_reply_p event,
8323 void *data)
8324{
8325 struct queue_iter_param *param = data;
8326 int parent_pid = *(int *) param->input;
8327
8328 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8329 {
8330 struct remote_state *rs = get_remote_state ();
8331 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8332 int res;
8333
8334 res = remote_vkill (child_pid, rs);
8335 if (res != 0)
8336 error (_("Can't kill fork child process %d"), child_pid);
8337 }
8338
8339 return 1;
8340}
8341
8342/* Kill any new fork children of process PID that haven't been
8343 processed by follow_fork. */
8344
8345static void
8346kill_new_fork_children (int pid, struct remote_state *rs)
8347{
8348 struct thread_info *thread;
8349 struct notif_client *notif = &notif_client_stop;
8350 struct queue_iter_param param;
8351
8352 /* Kill the fork child threads of any threads in process PID
8353 that are stopped at a fork event. */
8354 ALL_NON_EXITED_THREADS (thread)
8355 {
8356 struct target_waitstatus *ws = &thread->pending_follow;
8357
8358 if (is_pending_fork_parent (ws, pid, thread->ptid))
8359 {
8360 struct remote_state *rs = get_remote_state ();
8361 int child_pid = ptid_get_pid (ws->value.related_pid);
8362 int res;
8363
8364 res = remote_vkill (child_pid, rs);
8365 if (res != 0)
8366 error (_("Can't kill fork child process %d"), child_pid);
8367 }
8368 }
8369
8370 /* Check for any pending fork events (not reported or processed yet)
8371 in process PID and kill those fork child threads as well. */
8372 remote_notif_get_pending_events (notif);
8373 param.input = &pid;
8374 param.output = NULL;
8375 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8376 kill_child_of_pending_fork, &param);
8377}
8378
c906108c
SS
8379\f
8380static void
7d85a9c0 8381remote_kill (struct target_ops *ops)
43ff13b4 8382{
0fdf84ca
PA
8383
8384 /* Catch errors so the user can quit from gdb even when we
23860348 8385 aren't on speaking terms with the remote system. */
492d29ea 8386 TRY
0fdf84ca
PA
8387 {
8388 putpkt ("k");
8389 }
492d29ea 8390 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
8391 {
8392 if (ex.error == TARGET_CLOSE_ERROR)
8393 {
8394 /* If we got an (EOF) error that caused the target
8395 to go away, then we're done, that's what we wanted.
8396 "k" is susceptible to cause a premature EOF, given
8397 that the remote server isn't actually required to
8398 reply to "k", and it can happen that it doesn't
8399 even get to reply ACK to the "k". */
8400 return;
8401 }
8402
8403 /* Otherwise, something went wrong. We didn't actually kill
8404 the target. Just propagate the exception, and let the
8405 user or higher layers decide what to do. */
8406 throw_exception (ex);
8407 }
492d29ea 8408 END_CATCH
43ff13b4 8409
0fdf84ca
PA
8410 /* We've killed the remote end, we get to mourn it. Since this is
8411 target remote, single-process, mourning the inferior also
8412 unpushes remote_ops. */
43ff13b4
JM
8413 target_mourn_inferior ();
8414}
8415
82f73884
PA
8416static int
8417remote_vkill (int pid, struct remote_state *rs)
8418{
4082afcc 8419 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8420 return -1;
8421
8422 /* Tell the remote target to detach. */
bba74b36 8423 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8424 putpkt (rs->buf);
8425 getpkt (&rs->buf, &rs->buf_size, 0);
8426
4082afcc
PA
8427 switch (packet_ok (rs->buf,
8428 &remote_protocol_packets[PACKET_vKill]))
8429 {
8430 case PACKET_OK:
8431 return 0;
8432 case PACKET_ERROR:
8433 return 1;
8434 case PACKET_UNKNOWN:
8435 return -1;
8436 default:
8437 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8438 }
82f73884
PA
8439}
8440
8441static void
7d85a9c0 8442extended_remote_kill (struct target_ops *ops)
82f73884
PA
8443{
8444 int res;
8445 int pid = ptid_get_pid (inferior_ptid);
8446 struct remote_state *rs = get_remote_state ();
8447
cbb8991c
DB
8448 /* If we're stopped while forking and we haven't followed yet, kill the
8449 child task. We need to do this before killing the parent task
8450 because if this is a vfork then the parent will be sleeping. */
8451 kill_new_fork_children (pid, rs);
8452
82f73884 8453 res = remote_vkill (pid, rs);
901f9912 8454 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
8455 {
8456 /* Don't try 'k' on a multi-process aware stub -- it has no way
8457 to specify the pid. */
8458
8459 putpkt ("k");
8460#if 0
8461 getpkt (&rs->buf, &rs->buf_size, 0);
8462 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8463 res = 1;
8464#else
8465 /* Don't wait for it to die. I'm not really sure it matters whether
8466 we do or not. For the existing stubs, kill is a noop. */
8467 res = 0;
8468#endif
8469 }
8470
8471 if (res != 0)
8472 error (_("Can't kill process"));
8473
82f73884
PA
8474 target_mourn_inferior ();
8475}
8476
c906108c 8477static void
20f796c9 8478remote_mourn (struct target_ops *target)
c906108c
SS
8479{
8480 unpush_target (target);
ce5ce7ed 8481
8a2492ee
PA
8482 /* remote_close takes care of doing most of the clean up. */
8483 generic_mourn_inferior ();
c906108c
SS
8484}
8485
2d717e4f 8486static void
20f796c9 8487extended_remote_mourn (struct target_ops *target)
2d717e4f
DJ
8488{
8489 struct remote_state *rs = get_remote_state ();
c906108c 8490
e24a49d8
PA
8491 /* In case we got here due to an error, but we're going to stay
8492 connected. */
8493 rs->waiting_for_stop_reply = 0;
8494
dc1981d7
PA
8495 /* If the current general thread belonged to the process we just
8496 detached from or has exited, the remote side current general
8497 thread becomes undefined. Considering a case like this:
8498
8499 - We just got here due to a detach.
8500 - The process that we're detaching from happens to immediately
8501 report a global breakpoint being hit in non-stop mode, in the
8502 same thread we had selected before.
8503 - GDB attaches to this process again.
8504 - This event happens to be the next event we handle.
8505
8506 GDB would consider that the current general thread didn't need to
8507 be set on the stub side (with Hg), since for all it knew,
8508 GENERAL_THREAD hadn't changed.
8509
8510 Notice that although in all-stop mode, the remote server always
8511 sets the current thread to the thread reporting the stop event,
8512 that doesn't happen in non-stop mode; in non-stop, the stub *must
8513 not* change the current thread when reporting a breakpoint hit,
8514 due to the decoupling of event reporting and event handling.
8515
8516 To keep things simple, we always invalidate our notion of the
8517 current thread. */
47f8a51d 8518 record_currthread (rs, minus_one_ptid);
dc1981d7 8519
2d717e4f
DJ
8520 /* Unlike "target remote", we do not want to unpush the target; then
8521 the next time the user says "run", we won't be connected. */
8522
48aa3c27
PA
8523 /* Call common code to mark the inferior as not running. */
8524 generic_mourn_inferior ();
8525
d729566a 8526 if (!have_inferiors ())
2d717e4f 8527 {
82f73884
PA
8528 if (!remote_multi_process_p (rs))
8529 {
8530 /* Check whether the target is running now - some remote stubs
8531 automatically restart after kill. */
8532 putpkt ("?");
8533 getpkt (&rs->buf, &rs->buf_size, 0);
8534
8535 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8536 {
3e43a32a
MS
8537 /* Assume that the target has been restarted. Set
8538 inferior_ptid so that bits of core GDB realizes
8539 there's something here, e.g., so that the user can
8540 say "kill" again. */
82f73884
PA
8541 inferior_ptid = magic_null_ptid;
8542 }
82f73884 8543 }
2d717e4f
DJ
8544 }
8545}
c906108c 8546
03583c20 8547static int
2bfc0540 8548extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8549{
4082afcc 8550 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8551}
8552
8553static void
8554extended_remote_disable_randomization (int val)
8555{
8556 struct remote_state *rs = get_remote_state ();
8557 char *reply;
8558
bba74b36
YQ
8559 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8560 val);
03583c20
UW
8561 putpkt (rs->buf);
8562 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8563 if (*reply == '\0')
8564 error (_("Target does not support QDisableRandomization."));
8565 if (strcmp (reply, "OK") != 0)
8566 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8567}
8568
2d717e4f
DJ
8569static int
8570extended_remote_run (char *args)
8571{
8572 struct remote_state *rs = get_remote_state ();
2d717e4f 8573 int len;
c906108c 8574
2d717e4f
DJ
8575 /* If the user has disabled vRun support, or we have detected that
8576 support is not available, do not try it. */
4082afcc 8577 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8578 return -1;
424163ea 8579
2d717e4f
DJ
8580 strcpy (rs->buf, "vRun;");
8581 len = strlen (rs->buf);
c906108c 8582
2d717e4f
DJ
8583 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8584 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8585 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8586 strlen (remote_exec_file));
2d717e4f 8587
d1a41061 8588 gdb_assert (args != NULL);
2d717e4f
DJ
8589 if (*args)
8590 {
8591 struct cleanup *back_to;
8592 int i;
8593 char **argv;
8594
d1a41061 8595 argv = gdb_buildargv (args);
6e366df1 8596 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
8597 for (i = 0; argv[i] != NULL; i++)
8598 {
8599 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8600 error (_("Argument list too long for run packet"));
8601 rs->buf[len++] = ';';
9f1b45b0
TT
8602 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8603 strlen (argv[i]));
2d717e4f
DJ
8604 }
8605 do_cleanups (back_to);
8606 }
8607
8608 rs->buf[len++] = '\0';
8609
8610 putpkt (rs->buf);
8611 getpkt (&rs->buf, &rs->buf_size, 0);
8612
4082afcc 8613 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 8614 {
4082afcc 8615 case PACKET_OK:
3405876a 8616 /* We have a wait response. All is well. */
2d717e4f 8617 return 0;
4082afcc
PA
8618 case PACKET_UNKNOWN:
8619 return -1;
8620 case PACKET_ERROR:
2d717e4f
DJ
8621 if (remote_exec_file[0] == '\0')
8622 error (_("Running the default executable on the remote target failed; "
8623 "try \"set remote exec-file\"?"));
8624 else
8625 error (_("Running \"%s\" on the remote target failed"),
8626 remote_exec_file);
4082afcc
PA
8627 default:
8628 gdb_assert_not_reached (_("bad switch"));
2d717e4f 8629 }
c906108c
SS
8630}
8631
2d717e4f
DJ
8632/* In the extended protocol we want to be able to do things like
8633 "run" and have them basically work as expected. So we need
8634 a special create_inferior function. We support changing the
8635 executable file and the command line arguments, but not the
8636 environment. */
8637
43ff13b4 8638static void
77a19445
TT
8639extended_remote_create_inferior (struct target_ops *ops,
8640 char *exec_file, char *args,
8641 char **env, int from_tty)
43ff13b4 8642{
3405876a
PA
8643 int run_worked;
8644 char *stop_reply;
8645 struct remote_state *rs = get_remote_state ();
8646
43ff13b4 8647 /* If running asynchronously, register the target file descriptor
23860348 8648 with the event loop. */
75c99385 8649 if (target_can_async_p ())
6a3753b3 8650 target_async (1);
43ff13b4 8651
03583c20 8652 /* Disable address space randomization if requested (and supported). */
2bfc0540 8653 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
8654 extended_remote_disable_randomization (disable_randomization);
8655
43ff13b4 8656 /* Now restart the remote server. */
3405876a
PA
8657 run_worked = extended_remote_run (args) != -1;
8658 if (!run_worked)
2d717e4f
DJ
8659 {
8660 /* vRun was not supported. Fail if we need it to do what the
8661 user requested. */
8662 if (remote_exec_file[0])
8663 error (_("Remote target does not support \"set remote exec-file\""));
8664 if (args[0])
8665 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 8666
2d717e4f
DJ
8667 /* Fall back to "R". */
8668 extended_remote_restart ();
8669 }
424163ea 8670
6c95b8df
PA
8671 if (!have_inferiors ())
8672 {
8673 /* Clean up from the last time we ran, before we mark the target
8674 running again. This will mark breakpoints uninserted, and
8675 get_offsets may insert breakpoints. */
8676 init_thread_list ();
8677 init_wait_for_inferior ();
8678 }
45280a52 8679
3405876a
PA
8680 /* vRun's success return is a stop reply. */
8681 stop_reply = run_worked ? rs->buf : NULL;
8682 add_current_inferior_and_thread (stop_reply);
c0a2216e 8683
2d717e4f
DJ
8684 /* Get updated offsets, if the stub uses qOffsets. */
8685 get_offsets ();
2d717e4f 8686}
c906108c 8687\f
c5aa993b 8688
b775012e
LM
8689/* Given a location's target info BP_TGT and the packet buffer BUF, output
8690 the list of conditions (in agent expression bytecode format), if any, the
8691 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8692 started from BUF and ended at BUF_END. */
b775012e
LM
8693
8694static int
8695remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8696 struct bp_target_info *bp_tgt, char *buf,
8697 char *buf_end)
b775012e
LM
8698{
8699 struct agent_expr *aexpr = NULL;
8700 int i, ix;
8701 char *pkt;
8702 char *buf_start = buf;
8703
8704 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8705 return 0;
8706
8707 buf += strlen (buf);
bba74b36 8708 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8709 buf++;
8710
8711 /* Send conditions to the target and free the vector. */
8712 for (ix = 0;
8713 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8714 ix++)
8715 {
bba74b36 8716 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8717 buf += strlen (buf);
8718 for (i = 0; i < aexpr->len; ++i)
8719 buf = pack_hex_byte (buf, aexpr->buf[i]);
8720 *buf = '\0';
8721 }
b775012e
LM
8722 return 0;
8723}
8724
d3ce09f5
SS
8725static void
8726remote_add_target_side_commands (struct gdbarch *gdbarch,
8727 struct bp_target_info *bp_tgt, char *buf)
8728{
8729 struct agent_expr *aexpr = NULL;
8730 int i, ix;
8731
8732 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8733 return;
8734
8735 buf += strlen (buf);
8736
8737 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8738 buf += strlen (buf);
8739
8740 /* Concatenate all the agent expressions that are commands into the
8741 cmds parameter. */
8742 for (ix = 0;
8743 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8744 ix++)
8745 {
8746 sprintf (buf, "X%x,", aexpr->len);
8747 buf += strlen (buf);
8748 for (i = 0; i < aexpr->len; ++i)
8749 buf = pack_hex_byte (buf, aexpr->buf[i]);
8750 *buf = '\0';
8751 }
d3ce09f5
SS
8752}
8753
8181d85f
DJ
8754/* Insert a breakpoint. On targets that have software breakpoint
8755 support, we ask the remote target to do the work; on targets
8756 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8757
8758static int
3db08215
MM
8759remote_insert_breakpoint (struct target_ops *ops,
8760 struct gdbarch *gdbarch,
a6d9a66e 8761 struct bp_target_info *bp_tgt)
c906108c 8762{
d471ea57
AC
8763 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8764 If it succeeds, then set the support to PACKET_ENABLE. If it
8765 fails, and the user has explicitly requested the Z support then
23860348 8766 report an error, otherwise, mark it disabled and go on. */
802188a7 8767
4082afcc 8768 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8769 {
0d5ed153 8770 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8771 struct remote_state *rs;
bba74b36 8772 char *p, *endbuf;
7c0f6dcc 8773 int bpsize;
b775012e 8774 struct condition_list *cond = NULL;
4fff2411 8775
28439a30
PA
8776 /* Make sure the remote is pointing at the right process, if
8777 necessary. */
8778 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8779 set_general_process ();
8780
a1dcb23a 8781 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8782
8783 rs = get_remote_state ();
8784 p = rs->buf;
bba74b36 8785 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8786
96baa820
JM
8787 *(p++) = 'Z';
8788 *(p++) = '0';
8789 *(p++) = ',';
7c0f6dcc 8790 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8791 p += hexnumstr (p, addr);
bba74b36 8792 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8793
efcc2da7 8794 if (remote_supports_cond_breakpoints (ops))
bba74b36 8795 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8796
78eff0ec 8797 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8798 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8799
6d820c5c
DJ
8800 putpkt (rs->buf);
8801 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8802
6d820c5c 8803 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8804 {
d471ea57
AC
8805 case PACKET_ERROR:
8806 return -1;
8807 case PACKET_OK:
7c0f6dcc
JL
8808 bp_tgt->placed_address = addr;
8809 bp_tgt->placed_size = bpsize;
d471ea57
AC
8810 return 0;
8811 case PACKET_UNKNOWN:
8812 break;
96baa820
JM
8813 }
8814 }
c906108c 8815
0000e5cc
PA
8816 /* If this breakpoint has target-side commands but this stub doesn't
8817 support Z0 packets, throw error. */
8818 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8819 throw_error (NOT_SUPPORTED_ERROR, _("\
8820Target doesn't support breakpoints that have target side commands."));
8821
3db08215 8822 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8823}
8824
8825static int
3db08215
MM
8826remote_remove_breakpoint (struct target_ops *ops,
8827 struct gdbarch *gdbarch,
a6d9a66e 8828 struct bp_target_info *bp_tgt)
c906108c 8829{
8181d85f 8830 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8831 struct remote_state *rs = get_remote_state ();
96baa820 8832
4082afcc 8833 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8834 {
6d820c5c 8835 char *p = rs->buf;
bba74b36 8836 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8837
28439a30
PA
8838 /* Make sure the remote is pointing at the right process, if
8839 necessary. */
8840 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8841 set_general_process ();
8842
96baa820
JM
8843 *(p++) = 'z';
8844 *(p++) = '0';
8845 *(p++) = ',';
8846
8181d85f
DJ
8847 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8848 p += hexnumstr (p, addr);
bba74b36 8849 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8850
6d820c5c
DJ
8851 putpkt (rs->buf);
8852 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8853
6d820c5c 8854 return (rs->buf[0] == 'E');
96baa820
JM
8855 }
8856
3db08215 8857 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8858}
8859
f486487f 8860static enum Z_packet_type
d471ea57
AC
8861watchpoint_to_Z_packet (int type)
8862{
8863 switch (type)
8864 {
8865 case hw_write:
bb858e6a 8866 return Z_PACKET_WRITE_WP;
d471ea57
AC
8867 break;
8868 case hw_read:
bb858e6a 8869 return Z_PACKET_READ_WP;
d471ea57
AC
8870 break;
8871 case hw_access:
bb858e6a 8872 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8873 break;
8874 default:
8e65ff28 8875 internal_error (__FILE__, __LINE__,
e2e0b3e5 8876 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8877 }
8878}
8879
3c3bea1c 8880static int
f486487f
SM
8881remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8882 enum target_hw_bp_type type, struct expression *cond)
96baa820 8883{
d01949b6 8884 struct remote_state *rs = get_remote_state ();
bba74b36 8885 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8886 char *p;
d471ea57 8887 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8888
4082afcc 8889 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 8890 return 1;
802188a7 8891
28439a30
PA
8892 /* Make sure the remote is pointing at the right process, if
8893 necessary. */
8894 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8895 set_general_process ();
8896
bba74b36 8897 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8898 p = strchr (rs->buf, '\0');
96baa820
JM
8899 addr = remote_address_masked (addr);
8900 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8901 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8902
6d820c5c
DJ
8903 putpkt (rs->buf);
8904 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8905
6d820c5c 8906 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8907 {
8908 case PACKET_ERROR:
d471ea57 8909 return -1;
85d721b8
PA
8910 case PACKET_UNKNOWN:
8911 return 1;
d471ea57
AC
8912 case PACKET_OK:
8913 return 0;
8914 }
8e65ff28 8915 internal_error (__FILE__, __LINE__,
e2e0b3e5 8916 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8917}
8918
283002cf
MR
8919static int
8920remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8921 CORE_ADDR start, int length)
8922{
8923 CORE_ADDR diff = remote_address_masked (addr - start);
8924
8925 return diff < length;
8926}
8927
d471ea57 8928
3c3bea1c 8929static int
f486487f
SM
8930remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8931 enum target_hw_bp_type type, struct expression *cond)
96baa820 8932{
d01949b6 8933 struct remote_state *rs = get_remote_state ();
bba74b36 8934 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8935 char *p;
d471ea57
AC
8936 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8937
4082afcc 8938 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 8939 return -1;
802188a7 8940
28439a30
PA
8941 /* Make sure the remote is pointing at the right process, if
8942 necessary. */
8943 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8944 set_general_process ();
8945
bba74b36 8946 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8947 p = strchr (rs->buf, '\0');
96baa820
JM
8948 addr = remote_address_masked (addr);
8949 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8950 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8951 putpkt (rs->buf);
8952 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8953
6d820c5c 8954 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8955 {
8956 case PACKET_ERROR:
8957 case PACKET_UNKNOWN:
8958 return -1;
8959 case PACKET_OK:
8960 return 0;
8961 }
8e65ff28 8962 internal_error (__FILE__, __LINE__,
e2e0b3e5 8963 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8964}
8965
3c3bea1c 8966
501eef12 8967int remote_hw_watchpoint_limit = -1;
480a3f21 8968int remote_hw_watchpoint_length_limit = -1;
501eef12 8969int remote_hw_breakpoint_limit = -1;
d471ea57 8970
480a3f21 8971static int
31568a15
TT
8972remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8973 CORE_ADDR addr, int len)
480a3f21
PW
8974{
8975 if (remote_hw_watchpoint_length_limit == 0)
8976 return 0;
8977 else if (remote_hw_watchpoint_length_limit < 0)
8978 return 1;
8979 else if (len <= remote_hw_watchpoint_length_limit)
8980 return 1;
8981 else
8982 return 0;
8983}
8984
b9362cc7 8985static int
5461485a 8986remote_check_watch_resources (struct target_ops *self,
f486487f 8987 enum bptype type, int cnt, int ot)
96baa820 8988{
3c3bea1c
GS
8989 if (type == bp_hardware_breakpoint)
8990 {
8991 if (remote_hw_breakpoint_limit == 0)
8992 return 0;
501eef12
AC
8993 else if (remote_hw_breakpoint_limit < 0)
8994 return 1;
3c3bea1c
GS
8995 else if (cnt <= remote_hw_breakpoint_limit)
8996 return 1;
8997 }
8998 else
8999 {
9000 if (remote_hw_watchpoint_limit == 0)
9001 return 0;
501eef12
AC
9002 else if (remote_hw_watchpoint_limit < 0)
9003 return 1;
3c3bea1c
GS
9004 else if (ot)
9005 return -1;
9006 else if (cnt <= remote_hw_watchpoint_limit)
9007 return 1;
9008 }
9009 return -1;
9010}
9011
f7e6eed5
PA
9012/* The to_stopped_by_sw_breakpoint method of target remote. */
9013
9014static int
9015remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9016{
9017 struct remote_state *rs = get_remote_state ();
9018
9019 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
9020}
9021
9022/* The to_supports_stopped_by_sw_breakpoint method of target
9023 remote. */
9024
9025static int
9026remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9027{
9028 struct remote_state *rs = get_remote_state ();
9029
9030 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9031}
9032
9033/* The to_stopped_by_hw_breakpoint method of target remote. */
9034
9035static int
9036remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9037{
9038 struct remote_state *rs = get_remote_state ();
9039
9040 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9041}
9042
9043/* The to_supports_stopped_by_hw_breakpoint method of target
9044 remote. */
9045
9046static int
9047remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9048{
9049 struct remote_state *rs = get_remote_state ();
9050
9051 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9052}
9053
b9362cc7 9054static int
6a109b6b 9055remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9056{
ee154bee
TT
9057 struct remote_state *rs = get_remote_state ();
9058
f7e6eed5 9059 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
3c3bea1c
GS
9060}
9061
4aa7a7f5
JJ
9062static int
9063remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9064{
ee154bee 9065 struct remote_state *rs = get_remote_state ();
4aa7a7f5 9066 int rc = 0;
a744cf53 9067
6a109b6b 9068 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 9069 {
ee154bee 9070 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
9071 rc = 1;
9072 }
9073
9074 return rc;
3c3bea1c
GS
9075}
9076
9077
9078static int
23a26771 9079remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9080 struct bp_target_info *bp_tgt)
3c3bea1c 9081{
0d5ed153 9082 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9083 struct remote_state *rs;
bba74b36 9084 char *p, *endbuf;
dd61ec5c 9085 char *message;
0d5ed153 9086 int bpsize;
802188a7 9087
c8189ed1 9088 /* The length field should be set to the size of a breakpoint
8181d85f 9089 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9090
0d5ed153 9091 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9092
4082afcc 9093 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9094 return -1;
2bc416ba 9095
28439a30
PA
9096 /* Make sure the remote is pointing at the right process, if
9097 necessary. */
9098 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9099 set_general_process ();
9100
4fff2411
JZ
9101 rs = get_remote_state ();
9102 p = rs->buf;
bba74b36 9103 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9104
96baa820
JM
9105 *(p++) = 'Z';
9106 *(p++) = '1';
9107 *(p++) = ',';
802188a7 9108
0d5ed153 9109 addr = remote_address_masked (addr);
96baa820 9110 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9111 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9112
efcc2da7 9113 if (remote_supports_cond_breakpoints (self))
bba74b36 9114 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9115
78eff0ec 9116 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9117 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9118
6d820c5c
DJ
9119 putpkt (rs->buf);
9120 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9121
6d820c5c 9122 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9123 {
9124 case PACKET_ERROR:
dd61ec5c
MW
9125 if (rs->buf[1] == '.')
9126 {
9127 message = strchr (rs->buf + 2, '.');
9128 if (message)
0316657e 9129 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9130 }
9131 return -1;
d471ea57
AC
9132 case PACKET_UNKNOWN:
9133 return -1;
9134 case PACKET_OK:
0d5ed153
MR
9135 bp_tgt->placed_address = addr;
9136 bp_tgt->placed_size = bpsize;
d471ea57
AC
9137 return 0;
9138 }
8e65ff28 9139 internal_error (__FILE__, __LINE__,
e2e0b3e5 9140 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9141}
9142
d471ea57 9143
802188a7 9144static int
a64dc96c 9145remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9146 struct bp_target_info *bp_tgt)
96baa820 9147{
8181d85f 9148 CORE_ADDR addr;
d01949b6 9149 struct remote_state *rs = get_remote_state ();
6d820c5c 9150 char *p = rs->buf;
bba74b36 9151 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9152
4082afcc 9153 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9154 return -1;
802188a7 9155
28439a30
PA
9156 /* Make sure the remote is pointing at the right process, if
9157 necessary. */
9158 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9159 set_general_process ();
9160
96baa820
JM
9161 *(p++) = 'z';
9162 *(p++) = '1';
9163 *(p++) = ',';
802188a7 9164
8181d85f 9165 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9166 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9167 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9168
6d820c5c
DJ
9169 putpkt (rs->buf);
9170 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9171
6d820c5c 9172 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9173 {
9174 case PACKET_ERROR:
9175 case PACKET_UNKNOWN:
9176 return -1;
9177 case PACKET_OK:
9178 return 0;
9179 }
8e65ff28 9180 internal_error (__FILE__, __LINE__,
e2e0b3e5 9181 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9182}
96baa820 9183
4a5e7a5b
PA
9184/* Verify memory using the "qCRC:" request. */
9185
9186static int
9187remote_verify_memory (struct target_ops *ops,
9188 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9189{
9190 struct remote_state *rs = get_remote_state ();
9191 unsigned long host_crc, target_crc;
9192 char *tmp;
9193
936d2992
PA
9194 /* It doesn't make sense to use qCRC if the remote target is
9195 connected but not running. */
9196 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9197 {
9198 enum packet_result result;
28439a30 9199
936d2992
PA
9200 /* Make sure the remote is pointing at the right process. */
9201 set_general_process ();
4a5e7a5b 9202
936d2992
PA
9203 /* FIXME: assumes lma can fit into long. */
9204 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9205 (long) lma, (long) size);
9206 putpkt (rs->buf);
4a5e7a5b 9207
936d2992
PA
9208 /* Be clever; compute the host_crc before waiting for target
9209 reply. */
9210 host_crc = xcrc32 (data, size, 0xffffffff);
9211
9212 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9213
936d2992
PA
9214 result = packet_ok (rs->buf,
9215 &remote_protocol_packets[PACKET_qCRC]);
9216 if (result == PACKET_ERROR)
9217 return -1;
9218 else if (result == PACKET_OK)
9219 {
9220 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9221 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9222
936d2992
PA
9223 return (host_crc == target_crc);
9224 }
9225 }
4a5e7a5b 9226
936d2992 9227 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9228}
9229
c906108c
SS
9230/* compare-sections command
9231
9232 With no arguments, compares each loadable section in the exec bfd
9233 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9234 Useful for verifying the image on the target against the exec file. */
e514a9d6 9235
c906108c 9236static void
fba45db2 9237compare_sections_command (char *args, int from_tty)
c906108c
SS
9238{
9239 asection *s;
c906108c 9240 struct cleanup *old_chain;
948f8e3d 9241 gdb_byte *sectdata;
ce359b09 9242 const char *sectname;
c906108c
SS
9243 bfd_size_type size;
9244 bfd_vma lma;
9245 int matched = 0;
9246 int mismatched = 0;
4a5e7a5b 9247 int res;
95cf3b38 9248 int read_only = 0;
c906108c
SS
9249
9250 if (!exec_bfd)
8a3fe4f8 9251 error (_("command cannot be used without an exec file"));
c906108c 9252
28439a30
PA
9253 /* Make sure the remote is pointing at the right process. */
9254 set_general_process ();
9255
95cf3b38
DT
9256 if (args != NULL && strcmp (args, "-r") == 0)
9257 {
9258 read_only = 1;
9259 args = NULL;
9260 }
9261
c5aa993b 9262 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9263 {
9264 if (!(s->flags & SEC_LOAD))
0df8b418 9265 continue; /* Skip non-loadable section. */
c906108c 9266
95cf3b38
DT
9267 if (read_only && (s->flags & SEC_READONLY) == 0)
9268 continue; /* Skip writeable sections */
9269
2c500098 9270 size = bfd_get_section_size (s);
c906108c 9271 if (size == 0)
0df8b418 9272 continue; /* Skip zero-length section. */
c906108c 9273
ce359b09 9274 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9275 if (args && strcmp (args, sectname) != 0)
0df8b418 9276 continue; /* Not the section selected by user. */
c906108c 9277
0df8b418 9278 matched = 1; /* Do this section. */
c906108c 9279 lma = s->lma;
c906108c 9280
c906108c 9281 sectdata = xmalloc (size);
b8c9b27d 9282 old_chain = make_cleanup (xfree, sectdata);
c906108c 9283 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9284
4a5e7a5b
PA
9285 res = target_verify_memory (sectdata, lma, size);
9286
9287 if (res == -1)
5af949e3 9288 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9289 paddress (target_gdbarch (), lma),
9290 paddress (target_gdbarch (), lma + size));
c906108c 9291
5af949e3 9292 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9293 paddress (target_gdbarch (), lma),
9294 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9295 if (res)
c906108c
SS
9296 printf_filtered ("matched.\n");
9297 else
c5aa993b
JM
9298 {
9299 printf_filtered ("MIS-MATCHED!\n");
9300 mismatched++;
9301 }
c906108c
SS
9302
9303 do_cleanups (old_chain);
9304 }
9305 if (mismatched > 0)
936d2992 9306 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9307the loaded file\n"));
c906108c 9308 if (args && !matched)
a3f17187 9309 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9310}
9311
0e7f50da
UW
9312/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9313 into remote target. The number of bytes written to the remote
9314 target is returned, or -1 for error. */
9315
9b409511 9316static enum target_xfer_status
0e7f50da
UW
9317remote_write_qxfer (struct target_ops *ops, const char *object_name,
9318 const char *annex, const gdb_byte *writebuf,
9b409511 9319 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9320 struct packet_config *packet)
9321{
9322 int i, buf_len;
9323 ULONGEST n;
0e7f50da
UW
9324 struct remote_state *rs = get_remote_state ();
9325 int max_size = get_memory_write_packet_size ();
9326
9327 if (packet->support == PACKET_DISABLE)
2ed4b548 9328 return TARGET_XFER_E_IO;
0e7f50da
UW
9329
9330 /* Insert header. */
9331 i = snprintf (rs->buf, max_size,
9332 "qXfer:%s:write:%s:%s:",
9333 object_name, annex ? annex : "",
9334 phex_nz (offset, sizeof offset));
9335 max_size -= (i + 1);
9336
9337 /* Escape as much data as fits into rs->buf. */
9338 buf_len = remote_escape_output
124e13d9 9339 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9340
9341 if (putpkt_binary (rs->buf, i + buf_len) < 0
9342 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9343 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9344 return TARGET_XFER_E_IO;
0e7f50da
UW
9345
9346 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9347
9348 *xfered_len = n;
9349 return TARGET_XFER_OK;
0e7f50da
UW
9350}
9351
0876f84a
DJ
9352/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9353 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9354 number of bytes read is returned, or 0 for EOF, or -1 for error.
9355 The number of bytes read may be less than LEN without indicating an
9356 EOF. PACKET is checked and updated to indicate whether the remote
9357 target supports this object. */
9358
9b409511 9359static enum target_xfer_status
0876f84a
DJ
9360remote_read_qxfer (struct target_ops *ops, const char *object_name,
9361 const char *annex,
9362 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9363 ULONGEST *xfered_len,
0876f84a
DJ
9364 struct packet_config *packet)
9365{
0876f84a 9366 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9367 LONGEST i, n, packet_len;
9368
9369 if (packet->support == PACKET_DISABLE)
2ed4b548 9370 return TARGET_XFER_E_IO;
0876f84a
DJ
9371
9372 /* Check whether we've cached an end-of-object packet that matches
9373 this request. */
8e88304f 9374 if (rs->finished_object)
0876f84a 9375 {
8e88304f
TT
9376 if (strcmp (object_name, rs->finished_object) == 0
9377 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9378 && offset == rs->finished_offset)
9b409511
YQ
9379 return TARGET_XFER_EOF;
9380
0876f84a
DJ
9381
9382 /* Otherwise, we're now reading something different. Discard
9383 the cache. */
8e88304f
TT
9384 xfree (rs->finished_object);
9385 xfree (rs->finished_annex);
9386 rs->finished_object = NULL;
9387 rs->finished_annex = NULL;
0876f84a
DJ
9388 }
9389
9390 /* Request only enough to fit in a single packet. The actual data
9391 may not, since we don't know how much of it will need to be escaped;
9392 the target is free to respond with slightly less data. We subtract
9393 five to account for the response type and the protocol frame. */
9394 n = min (get_remote_packet_size () - 5, len);
9395 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9396 object_name, annex ? annex : "",
9397 phex_nz (offset, sizeof offset),
9398 phex_nz (n, sizeof n));
9399 i = putpkt (rs->buf);
9400 if (i < 0)
2ed4b548 9401 return TARGET_XFER_E_IO;
0876f84a
DJ
9402
9403 rs->buf[0] = '\0';
9404 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9405 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9406 return TARGET_XFER_E_IO;
0876f84a
DJ
9407
9408 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9409 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9410
9411 /* 'm' means there is (or at least might be) more data after this
9412 batch. That does not make sense unless there's at least one byte
9413 of data in this reply. */
9414 if (rs->buf[0] == 'm' && packet_len == 1)
9415 error (_("Remote qXfer reply contained no data."));
9416
9417 /* Got some data. */
bc20a4af
PA
9418 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9419 packet_len - 1, readbuf, n);
0876f84a
DJ
9420
9421 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9422 or possibly empty. If we have the final block of a non-empty
9423 object, record this fact to bypass a subsequent partial read. */
9424 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9425 {
8e88304f
TT
9426 rs->finished_object = xstrdup (object_name);
9427 rs->finished_annex = xstrdup (annex ? annex : "");
9428 rs->finished_offset = offset + i;
0876f84a
DJ
9429 }
9430
9b409511
YQ
9431 if (i == 0)
9432 return TARGET_XFER_EOF;
9433 else
9434 {
9435 *xfered_len = i;
9436 return TARGET_XFER_OK;
9437 }
0876f84a
DJ
9438}
9439
9b409511 9440static enum target_xfer_status
4b8a223f 9441remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9442 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9443 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9444 ULONGEST *xfered_len)
c906108c 9445{
82f73884 9446 struct remote_state *rs;
c906108c 9447 int i;
6d820c5c 9448 char *p2;
1e3ff5ad 9449 char query_type;
124e13d9 9450 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9451
e6e4e701 9452 set_remote_traceframe ();
82f73884
PA
9453 set_general_thread (inferior_ptid);
9454
9455 rs = get_remote_state ();
9456
b2182ed2 9457 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9458 if (object == TARGET_OBJECT_MEMORY)
9459 {
2d717e4f
DJ
9460 /* If the remote target is connected but not running, we should
9461 pass this request down to a lower stratum (e.g. the executable
9462 file). */
9463 if (!target_has_execution)
9b409511 9464 return TARGET_XFER_EOF;
2d717e4f 9465
21e3b9b9 9466 if (writebuf != NULL)
124e13d9
SM
9467 return remote_write_bytes (offset, writebuf, len, unit_size,
9468 xfered_len);
21e3b9b9 9469 else
124e13d9
SM
9470 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9471 xfered_len);
21e3b9b9
DJ
9472 }
9473
0df8b418 9474 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9475 if (object == TARGET_OBJECT_SPU)
9476 {
9477 if (readbuf)
9478 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9479 xfered_len, &remote_protocol_packets
9480 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9481 else
9482 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9483 xfered_len, &remote_protocol_packets
9484 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9485 }
9486
4aa995e1
PA
9487 /* Handle extra signal info using qxfer packets. */
9488 if (object == TARGET_OBJECT_SIGNAL_INFO)
9489 {
9490 if (readbuf)
9491 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 9492 xfered_len, &remote_protocol_packets
4aa995e1
PA
9493 [PACKET_qXfer_siginfo_read]);
9494 else
3e43a32a 9495 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 9496 writebuf, offset, len, xfered_len,
4aa995e1
PA
9497 &remote_protocol_packets
9498 [PACKET_qXfer_siginfo_write]);
9499 }
9500
0fb4aa4b
PA
9501 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9502 {
9503 if (readbuf)
3e43a32a 9504 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 9505 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
9506 &remote_protocol_packets
9507 [PACKET_qXfer_statictrace_read]);
9508 else
2ed4b548 9509 return TARGET_XFER_E_IO;
0fb4aa4b
PA
9510 }
9511
a76d924d
DJ
9512 /* Only handle flash writes. */
9513 if (writebuf != NULL)
9514 {
9515 LONGEST xfered;
9516
9517 switch (object)
9518 {
9519 case TARGET_OBJECT_FLASH:
9b409511
YQ
9520 return remote_flash_write (ops, offset, len, xfered_len,
9521 writebuf);
a76d924d
DJ
9522
9523 default:
2ed4b548 9524 return TARGET_XFER_E_IO;
a76d924d
DJ
9525 }
9526 }
4b8a223f 9527
1e3ff5ad
AC
9528 /* Map pre-existing objects onto letters. DO NOT do this for new
9529 objects!!! Instead specify new query packets. */
9530 switch (object)
c906108c 9531 {
1e3ff5ad
AC
9532 case TARGET_OBJECT_AVR:
9533 query_type = 'R';
9534 break;
802188a7
RM
9535
9536 case TARGET_OBJECT_AUXV:
0876f84a
DJ
9537 gdb_assert (annex == NULL);
9538 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9539 xfered_len,
0876f84a 9540 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9541
23181151
DJ
9542 case TARGET_OBJECT_AVAILABLE_FEATURES:
9543 return remote_read_qxfer
9b409511 9544 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9545 &remote_protocol_packets[PACKET_qXfer_features]);
9546
cfa9d6d9
DJ
9547 case TARGET_OBJECT_LIBRARIES:
9548 return remote_read_qxfer
9b409511 9549 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9550 &remote_protocol_packets[PACKET_qXfer_libraries]);
9551
2268b414
JK
9552 case TARGET_OBJECT_LIBRARIES_SVR4:
9553 return remote_read_qxfer
9b409511 9554 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9555 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9556
fd79ecee
DJ
9557 case TARGET_OBJECT_MEMORY_MAP:
9558 gdb_assert (annex == NULL);
9559 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9560 xfered_len,
fd79ecee
DJ
9561 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9562
07e059b5
VP
9563 case TARGET_OBJECT_OSDATA:
9564 /* Should only get here if we're connected. */
5d93a237 9565 gdb_assert (rs->remote_desc);
07e059b5 9566 return remote_read_qxfer
9b409511 9567 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9568 &remote_protocol_packets[PACKET_qXfer_osdata]);
9569
dc146f7c
VP
9570 case TARGET_OBJECT_THREADS:
9571 gdb_assert (annex == NULL);
9572 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9573 xfered_len,
dc146f7c
VP
9574 &remote_protocol_packets[PACKET_qXfer_threads]);
9575
b3b9301e
PA
9576 case TARGET_OBJECT_TRACEFRAME_INFO:
9577 gdb_assert (annex == NULL);
9578 return remote_read_qxfer
9b409511 9579 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9580 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9581
9582 case TARGET_OBJECT_FDPIC:
9583 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9584 xfered_len,
78d85199 9585 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9586
9587 case TARGET_OBJECT_OPENVMS_UIB:
9588 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 9589 xfered_len,
169081d0
TG
9590 &remote_protocol_packets[PACKET_qXfer_uib]);
9591
9accd112
MM
9592 case TARGET_OBJECT_BTRACE:
9593 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 9594 xfered_len,
9accd112
MM
9595 &remote_protocol_packets[PACKET_qXfer_btrace]);
9596
f4abbc16
MM
9597 case TARGET_OBJECT_BTRACE_CONF:
9598 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9599 len, xfered_len,
9600 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9601
c78fa86a
GB
9602 case TARGET_OBJECT_EXEC_FILE:
9603 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9604 len, xfered_len,
9605 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9606
1e3ff5ad 9607 default:
2ed4b548 9608 return TARGET_XFER_E_IO;
c906108c
SS
9609 }
9610
0df8b418 9611 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 9612 large enough let the caller deal with it. */
ea9c271d 9613 if (len < get_remote_packet_size ())
2ed4b548 9614 return TARGET_XFER_E_IO;
ea9c271d 9615 len = get_remote_packet_size ();
1e3ff5ad 9616
23860348 9617 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 9618 if (!rs->remote_desc)
8a3fe4f8 9619 error (_("remote query is only available after target open"));
c906108c 9620
1e3ff5ad 9621 gdb_assert (annex != NULL);
4b8a223f 9622 gdb_assert (readbuf != NULL);
c906108c 9623
6d820c5c 9624 p2 = rs->buf;
c906108c
SS
9625 *p2++ = 'q';
9626 *p2++ = query_type;
9627
23860348
MS
9628 /* We used one buffer char for the remote protocol q command and
9629 another for the query type. As the remote protocol encapsulation
9630 uses 4 chars plus one extra in case we are debugging
9631 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9632 string. */
c906108c 9633 i = 0;
ea9c271d 9634 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 9635 {
1e3ff5ad
AC
9636 /* Bad caller may have sent forbidden characters. */
9637 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9638 *p2++ = annex[i];
c906108c
SS
9639 i++;
9640 }
1e3ff5ad
AC
9641 *p2 = '\0';
9642 gdb_assert (annex[i] == '\0');
c906108c 9643
6d820c5c 9644 i = putpkt (rs->buf);
c5aa993b 9645 if (i < 0)
2ed4b548 9646 return TARGET_XFER_E_IO;
c906108c 9647
6d820c5c
DJ
9648 getpkt (&rs->buf, &rs->buf_size, 0);
9649 strcpy ((char *) readbuf, rs->buf);
c906108c 9650
9b409511
YQ
9651 *xfered_len = strlen ((char *) readbuf);
9652 return TARGET_XFER_OK;
c906108c
SS
9653}
9654
08388c79
DE
9655static int
9656remote_search_memory (struct target_ops* ops,
9657 CORE_ADDR start_addr, ULONGEST search_space_len,
9658 const gdb_byte *pattern, ULONGEST pattern_len,
9659 CORE_ADDR *found_addrp)
9660{
f5656ead 9661 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
9662 struct remote_state *rs = get_remote_state ();
9663 int max_size = get_memory_write_packet_size ();
9664 struct packet_config *packet =
9665 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
9666 /* Number of packet bytes used to encode the pattern;
9667 this could be more than PATTERN_LEN due to escape characters. */
08388c79 9668 int escaped_pattern_len;
0df8b418 9669 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
9670 int used_pattern_len;
9671 int i;
9672 int found;
9673 ULONGEST found_addr;
9674
9675 /* Don't go to the target if we don't have to.
9676 This is done before checking packet->support to avoid the possibility that
9677 a success for this edge case means the facility works in general. */
9678 if (pattern_len > search_space_len)
9679 return 0;
9680 if (pattern_len == 0)
9681 {
9682 *found_addrp = start_addr;
9683 return 1;
9684 }
9685
9686 /* If we already know the packet isn't supported, fall back to the simple
9687 way of searching memory. */
9688
4082afcc 9689 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
9690 {
9691 /* Target doesn't provided special support, fall back and use the
9692 standard support (copy memory and do the search here). */
9693 return simple_search_memory (ops, start_addr, search_space_len,
9694 pattern, pattern_len, found_addrp);
9695 }
9696
28439a30
PA
9697 /* Make sure the remote is pointing at the right process. */
9698 set_general_process ();
9699
08388c79
DE
9700 /* Insert header. */
9701 i = snprintf (rs->buf, max_size,
9702 "qSearch:memory:%s;%s;",
5af949e3 9703 phex_nz (start_addr, addr_size),
08388c79
DE
9704 phex_nz (search_space_len, sizeof (search_space_len)));
9705 max_size -= (i + 1);
9706
9707 /* Escape as much data as fits into rs->buf. */
9708 escaped_pattern_len =
124e13d9 9709 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
9710 &used_pattern_len, max_size);
9711
9712 /* Bail if the pattern is too large. */
9713 if (used_pattern_len != pattern_len)
9b20d036 9714 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
9715
9716 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9717 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9718 || packet_ok (rs->buf, packet) != PACKET_OK)
9719 {
9720 /* The request may not have worked because the command is not
9721 supported. If so, fall back to the simple way. */
9722 if (packet->support == PACKET_DISABLE)
9723 {
9724 return simple_search_memory (ops, start_addr, search_space_len,
9725 pattern, pattern_len, found_addrp);
9726 }
9727 return -1;
9728 }
9729
9730 if (rs->buf[0] == '0')
9731 found = 0;
9732 else if (rs->buf[0] == '1')
9733 {
9734 found = 1;
9735 if (rs->buf[1] != ',')
10e0fa18 9736 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9737 unpack_varlen_hex (rs->buf + 2, &found_addr);
9738 *found_addrp = found_addr;
9739 }
9740 else
10e0fa18 9741 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9742
9743 return found;
9744}
9745
96baa820 9746static void
a30bf1f1 9747remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 9748 struct ui_file *outbuf)
96baa820 9749{
d01949b6 9750 struct remote_state *rs = get_remote_state ();
2e9f7625 9751 char *p = rs->buf;
96baa820 9752
5d93a237 9753 if (!rs->remote_desc)
8a3fe4f8 9754 error (_("remote rcmd is only available after target open"));
96baa820 9755
23860348 9756 /* Send a NULL command across as an empty command. */
7be570e7
JM
9757 if (command == NULL)
9758 command = "";
9759
23860348 9760 /* The query prefix. */
2e9f7625
DJ
9761 strcpy (rs->buf, "qRcmd,");
9762 p = strchr (rs->buf, '\0');
96baa820 9763
3e43a32a
MS
9764 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9765 > get_remote_packet_size ())
8a3fe4f8 9766 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9767
23860348 9768 /* Encode the actual command. */
a30bf1f1 9769 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 9770
6d820c5c 9771 if (putpkt (rs->buf) < 0)
8a3fe4f8 9772 error (_("Communication problem with target."));
96baa820
JM
9773
9774 /* get/display the response */
9775 while (1)
9776 {
2e9f7625
DJ
9777 char *buf;
9778
00bf0b85 9779 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9780 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9781 rs->buf[0] = '\0';
5b37825d
PW
9782 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9783 {
9784 /* Timeout. Continue to (try to) read responses.
9785 This is better than stopping with an error, assuming the stub
9786 is still executing the (long) monitor command.
9787 If needed, the user can interrupt gdb using C-c, obtaining
9788 an effect similar to stop on timeout. */
9789 continue;
9790 }
2e9f7625 9791 buf = rs->buf;
96baa820 9792 if (buf[0] == '\0')
8a3fe4f8 9793 error (_("Target does not support this command."));
96baa820
JM
9794 if (buf[0] == 'O' && buf[1] != 'K')
9795 {
23860348 9796 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9797 continue;
9798 }
9799 if (strcmp (buf, "OK") == 0)
9800 break;
7be570e7
JM
9801 if (strlen (buf) == 3 && buf[0] == 'E'
9802 && isdigit (buf[1]) && isdigit (buf[2]))
9803 {
8a3fe4f8 9804 error (_("Protocol error with Rcmd"));
7be570e7 9805 }
96baa820
JM
9806 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9807 {
9808 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9809
96baa820
JM
9810 fputc_unfiltered (c, outbuf);
9811 }
9812 break;
9813 }
9814}
9815
fd79ecee
DJ
9816static VEC(mem_region_s) *
9817remote_memory_map (struct target_ops *ops)
9818{
9819 VEC(mem_region_s) *result = NULL;
9820 char *text = target_read_stralloc (&current_target,
9821 TARGET_OBJECT_MEMORY_MAP, NULL);
9822
9823 if (text)
9824 {
9825 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9826
fd79ecee
DJ
9827 result = parse_memory_map (text);
9828 do_cleanups (back_to);
9829 }
9830
9831 return result;
9832}
9833
c906108c 9834static void
fba45db2 9835packet_command (char *args, int from_tty)
c906108c 9836{
d01949b6 9837 struct remote_state *rs = get_remote_state ();
c906108c 9838
5d93a237 9839 if (!rs->remote_desc)
8a3fe4f8 9840 error (_("command can only be used with remote target"));
c906108c 9841
c5aa993b 9842 if (!args)
8a3fe4f8 9843 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9844
9845 puts_filtered ("sending: ");
9846 print_packet (args);
9847 puts_filtered ("\n");
9848 putpkt (args);
9849
6d820c5c 9850 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9851 puts_filtered ("received: ");
6d820c5c 9852 print_packet (rs->buf);
c906108c
SS
9853 puts_filtered ("\n");
9854}
9855
9856#if 0
23860348 9857/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9858
a14ed312 9859static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9860
a14ed312 9861static void threadset_test_cmd (char *cmd, int tty);
c906108c 9862
a14ed312 9863static void threadalive_test (char *cmd, int tty);
c906108c 9864
a14ed312 9865static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9866
23860348 9867int get_and_display_threadinfo (threadref *ref);
c906108c 9868
a14ed312 9869static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9870
23860348 9871static int thread_display_step (threadref *ref, void *context);
c906108c 9872
a14ed312 9873static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9874
a14ed312 9875static void init_remote_threadtests (void);
c906108c 9876
23860348 9877#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9878
9879static void
fba45db2 9880threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9881{
9882 int sample_thread = SAMPLE_THREAD;
9883
a3f17187 9884 printf_filtered (_("Remote threadset test\n"));
79d7f229 9885 set_general_thread (sample_thread);
c906108c
SS
9886}
9887
9888
9889static void
fba45db2 9890threadalive_test (char *cmd, int tty)
c906108c
SS
9891{
9892 int sample_thread = SAMPLE_THREAD;
79d7f229 9893 int pid = ptid_get_pid (inferior_ptid);
ba348170 9894 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 9895
79d7f229 9896 if (remote_thread_alive (ptid))
c906108c
SS
9897 printf_filtered ("PASS: Thread alive test\n");
9898 else
9899 printf_filtered ("FAIL: Thread alive test\n");
9900}
9901
23860348 9902void output_threadid (char *title, threadref *ref);
c906108c
SS
9903
9904void
fba45db2 9905output_threadid (char *title, threadref *ref)
c906108c
SS
9906{
9907 char hexid[20];
9908
23860348 9909 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9910 hexid[16] = 0;
9911 printf_filtered ("%s %s\n", title, (&hexid[0]));
9912}
9913
9914static void
fba45db2 9915threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9916{
9917 int startflag = 1;
9918 threadref nextthread;
9919 int done, result_count;
9920 threadref threadlist[3];
9921
9922 printf_filtered ("Remote Threadlist test\n");
9923 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9924 &result_count, &threadlist[0]))
9925 printf_filtered ("FAIL: threadlist test\n");
9926 else
9927 {
9928 threadref *scan = threadlist;
9929 threadref *limit = scan + result_count;
9930
9931 while (scan < limit)
9932 output_threadid (" thread ", scan++);
9933 }
9934}
9935
9936void
fba45db2 9937display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9938{
9939 output_threadid ("Threadid: ", &info->threadid);
9940 printf_filtered ("Name: %s\n ", info->shortname);
9941 printf_filtered ("State: %s\n", info->display);
9942 printf_filtered ("other: %s\n\n", info->more_display);
9943}
9944
9945int
fba45db2 9946get_and_display_threadinfo (threadref *ref)
c906108c
SS
9947{
9948 int result;
9949 int set;
9950 struct gdb_ext_thread_info threadinfo;
9951
9952 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9953 | TAG_MOREDISPLAY | TAG_DISPLAY;
9954 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9955 display_thread_info (&threadinfo);
9956 return result;
9957}
9958
9959static void
fba45db2 9960threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9961{
9962 int athread = SAMPLE_THREAD;
9963 threadref thread;
9964 int set;
9965
9966 int_to_threadref (&thread, athread);
9967 printf_filtered ("Remote Threadinfo test\n");
9968 if (!get_and_display_threadinfo (&thread))
9969 printf_filtered ("FAIL cannot get thread info\n");
9970}
9971
9972static int
fba45db2 9973thread_display_step (threadref *ref, void *context)
c906108c
SS
9974{
9975 /* output_threadid(" threadstep ",ref); *//* simple test */
9976 return get_and_display_threadinfo (ref);
9977}
9978
9979static void
fba45db2 9980threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
9981{
9982 printf_filtered ("Remote Threadlist update test\n");
9983 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9984}
9985
9986static void
9987init_remote_threadtests (void)
9988{
3e43a32a
MS
9989 add_com ("tlist", class_obscure, threadlist_test_cmd,
9990 _("Fetch and print the remote list of "
9991 "thread identifiers, one pkt only"));
c906108c 9992 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 9993 _("Fetch and display info about one thread"));
c906108c 9994 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 9995 _("Test setting to a different thread"));
c906108c 9996 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 9997 _("Iterate through updating all remote thread info"));
c906108c 9998 add_com ("talive", class_obscure, threadalive_test,
1bedd215 9999 _(" Remote thread alive test "));
c906108c
SS
10000}
10001
10002#endif /* 0 */
10003
f3fb8c85
MS
10004/* Convert a thread ID to a string. Returns the string in a static
10005 buffer. */
10006
10007static char *
117de6a9 10008remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10009{
79d7f229 10010 static char buf[64];
82f73884 10011 struct remote_state *rs = get_remote_state ();
f3fb8c85 10012
7cee1e54
PA
10013 if (ptid_equal (ptid, null_ptid))
10014 return normal_pid_to_str (ptid);
10015 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10016 {
10017 /* Printing an inferior target id. */
10018
10019 /* When multi-process extensions are off, there's no way in the
10020 remote protocol to know the remote process id, if there's any
10021 at all. There's one exception --- when we're connected with
10022 target extended-remote, and we manually attached to a process
10023 with "attach PID". We don't record anywhere a flag that
10024 allows us to distinguish that case from the case of
10025 connecting with extended-remote and the stub already being
10026 attached to a process, and reporting yes to qAttached, hence
10027 no smart special casing here. */
10028 if (!remote_multi_process_p (rs))
10029 {
10030 xsnprintf (buf, sizeof buf, "Remote target");
10031 return buf;
10032 }
10033
10034 return normal_pid_to_str (ptid);
82f73884 10035 }
ecd0ada5 10036 else
79d7f229 10037 {
ecd0ada5
PA
10038 if (ptid_equal (magic_null_ptid, ptid))
10039 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 10040 else if (rs->extended && remote_multi_process_p (rs))
de0d863e
DB
10041 if (ptid_get_lwp (ptid) == 0)
10042 return normal_pid_to_str (ptid);
10043 else
10044 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10045 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10046 else
10047 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10048 ptid_get_lwp (ptid));
79d7f229
PA
10049 return buf;
10050 }
f3fb8c85
MS
10051}
10052
38691318
KB
10053/* Get the address of the thread local variable in OBJFILE which is
10054 stored at OFFSET within the thread local storage for thread PTID. */
10055
10056static CORE_ADDR
117de6a9
PA
10057remote_get_thread_local_address (struct target_ops *ops,
10058 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10059{
4082afcc 10060 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10061 {
10062 struct remote_state *rs = get_remote_state ();
6d820c5c 10063 char *p = rs->buf;
82f73884 10064 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10065 enum packet_result result;
38691318
KB
10066
10067 strcpy (p, "qGetTLSAddr:");
10068 p += strlen (p);
82f73884 10069 p = write_ptid (p, endp, ptid);
38691318
KB
10070 *p++ = ',';
10071 p += hexnumstr (p, offset);
10072 *p++ = ',';
10073 p += hexnumstr (p, lm);
10074 *p++ = '\0';
10075
6d820c5c
DJ
10076 putpkt (rs->buf);
10077 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10078 result = packet_ok (rs->buf,
10079 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10080 if (result == PACKET_OK)
38691318
KB
10081 {
10082 ULONGEST result;
10083
6d820c5c 10084 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10085 return result;
10086 }
571dd617 10087 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10088 throw_error (TLS_GENERIC_ERROR,
10089 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10090 else
109c3e39
AC
10091 throw_error (TLS_GENERIC_ERROR,
10092 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10093 }
10094 else
109c3e39
AC
10095 throw_error (TLS_GENERIC_ERROR,
10096 _("TLS not supported or disabled on this target"));
38691318
KB
10097 /* Not reached. */
10098 return 0;
10099}
10100
711e434b
PM
10101/* Provide thread local base, i.e. Thread Information Block address.
10102 Returns 1 if ptid is found and thread_local_base is non zero. */
10103
70221824 10104static int
bd7ae0f5 10105remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10106{
4082afcc 10107 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10108 {
10109 struct remote_state *rs = get_remote_state ();
10110 char *p = rs->buf;
10111 char *endp = rs->buf + get_remote_packet_size ();
10112 enum packet_result result;
10113
10114 strcpy (p, "qGetTIBAddr:");
10115 p += strlen (p);
10116 p = write_ptid (p, endp, ptid);
10117 *p++ = '\0';
10118
10119 putpkt (rs->buf);
10120 getpkt (&rs->buf, &rs->buf_size, 0);
10121 result = packet_ok (rs->buf,
10122 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10123 if (result == PACKET_OK)
10124 {
10125 ULONGEST result;
10126
10127 unpack_varlen_hex (rs->buf, &result);
10128 if (addr)
10129 *addr = (CORE_ADDR) result;
10130 return 1;
10131 }
10132 else if (result == PACKET_UNKNOWN)
10133 error (_("Remote target doesn't support qGetTIBAddr packet"));
10134 else
10135 error (_("Remote target failed to process qGetTIBAddr request"));
10136 }
10137 else
10138 error (_("qGetTIBAddr not supported or disabled on this target"));
10139 /* Not reached. */
10140 return 0;
10141}
10142
29709017
DJ
10143/* Support for inferring a target description based on the current
10144 architecture and the size of a 'g' packet. While the 'g' packet
10145 can have any size (since optional registers can be left off the
10146 end), some sizes are easily recognizable given knowledge of the
10147 approximate architecture. */
10148
10149struct remote_g_packet_guess
10150{
10151 int bytes;
10152 const struct target_desc *tdesc;
10153};
10154typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10155DEF_VEC_O(remote_g_packet_guess_s);
10156
10157struct remote_g_packet_data
10158{
10159 VEC(remote_g_packet_guess_s) *guesses;
10160};
10161
10162static struct gdbarch_data *remote_g_packet_data_handle;
10163
10164static void *
10165remote_g_packet_data_init (struct obstack *obstack)
10166{
10167 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10168}
10169
10170void
10171register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10172 const struct target_desc *tdesc)
10173{
10174 struct remote_g_packet_data *data
10175 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
10176 struct remote_g_packet_guess new_guess, *guess;
10177 int ix;
10178
10179 gdb_assert (tdesc != NULL);
10180
10181 for (ix = 0;
10182 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10183 ix++)
10184 if (guess->bytes == bytes)
10185 internal_error (__FILE__, __LINE__,
9b20d036 10186 _("Duplicate g packet description added for size %d"),
29709017
DJ
10187 bytes);
10188
10189 new_guess.bytes = bytes;
10190 new_guess.tdesc = tdesc;
10191 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10192}
10193
d962ef82
DJ
10194/* Return 1 if remote_read_description would do anything on this target
10195 and architecture, 0 otherwise. */
10196
10197static int
10198remote_read_description_p (struct target_ops *target)
10199{
10200 struct remote_g_packet_data *data
f5656ead 10201 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
10202
10203 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10204 return 1;
10205
10206 return 0;
10207}
10208
29709017
DJ
10209static const struct target_desc *
10210remote_read_description (struct target_ops *target)
10211{
10212 struct remote_g_packet_data *data
f5656ead 10213 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 10214
d962ef82
DJ
10215 /* Do not try this during initial connection, when we do not know
10216 whether there is a running but stopped thread. */
10217 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10218 return target->beneath->to_read_description (target->beneath);
d962ef82 10219
29709017
DJ
10220 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10221 {
10222 struct remote_g_packet_guess *guess;
10223 int ix;
10224 int bytes = send_g_packet ();
10225
10226 for (ix = 0;
10227 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10228 ix++)
10229 if (guess->bytes == bytes)
10230 return guess->tdesc;
10231
10232 /* We discard the g packet. A minor optimization would be to
10233 hold on to it, and fill the register cache once we have selected
10234 an architecture, but it's too tricky to do safely. */
10235 }
10236
2117c711 10237 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10238}
10239
a6b151f1
DJ
10240/* Remote file transfer support. This is host-initiated I/O, not
10241 target-initiated; for target-initiated, see remote-fileio.c. */
10242
10243/* If *LEFT is at least the length of STRING, copy STRING to
10244 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10245 decrease *LEFT. Otherwise raise an error. */
10246
10247static void
10248remote_buffer_add_string (char **buffer, int *left, char *string)
10249{
10250 int len = strlen (string);
10251
10252 if (len > *left)
10253 error (_("Packet too long for target."));
10254
10255 memcpy (*buffer, string, len);
10256 *buffer += len;
10257 *left -= len;
10258
10259 /* NUL-terminate the buffer as a convenience, if there is
10260 room. */
10261 if (*left)
10262 **buffer = '\0';
10263}
10264
10265/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10266 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10267 decrease *LEFT. Otherwise raise an error. */
10268
10269static void
10270remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10271 int len)
10272{
10273 if (2 * len > *left)
10274 error (_("Packet too long for target."));
10275
10276 bin2hex (bytes, *buffer, len);
10277 *buffer += 2 * len;
10278 *left -= 2 * len;
10279
10280 /* NUL-terminate the buffer as a convenience, if there is
10281 room. */
10282 if (*left)
10283 **buffer = '\0';
10284}
10285
10286/* If *LEFT is large enough, convert VALUE to hex and add it to
10287 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10288 decrease *LEFT. Otherwise raise an error. */
10289
10290static void
10291remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10292{
10293 int len = hexnumlen (value);
10294
10295 if (len > *left)
10296 error (_("Packet too long for target."));
10297
10298 hexnumstr (*buffer, value);
10299 *buffer += len;
10300 *left -= len;
10301
10302 /* NUL-terminate the buffer as a convenience, if there is
10303 room. */
10304 if (*left)
10305 **buffer = '\0';
10306}
10307
10308/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10309 value, *REMOTE_ERRNO to the remote error number or zero if none
10310 was included, and *ATTACHMENT to point to the start of the annex
10311 if any. The length of the packet isn't needed here; there may
10312 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10313
10314 Return 0 if the packet could be parsed, -1 if it could not. If
10315 -1 is returned, the other variables may not be initialized. */
10316
10317static int
10318remote_hostio_parse_result (char *buffer, int *retcode,
10319 int *remote_errno, char **attachment)
10320{
10321 char *p, *p2;
10322
10323 *remote_errno = 0;
10324 *attachment = NULL;
10325
10326 if (buffer[0] != 'F')
10327 return -1;
10328
10329 errno = 0;
10330 *retcode = strtol (&buffer[1], &p, 16);
10331 if (errno != 0 || p == &buffer[1])
10332 return -1;
10333
10334 /* Check for ",errno". */
10335 if (*p == ',')
10336 {
10337 errno = 0;
10338 *remote_errno = strtol (p + 1, &p2, 16);
10339 if (errno != 0 || p + 1 == p2)
10340 return -1;
10341 p = p2;
10342 }
10343
10344 /* Check for ";attachment". If there is no attachment, the
10345 packet should end here. */
10346 if (*p == ';')
10347 {
10348 *attachment = p + 1;
10349 return 0;
10350 }
10351 else if (*p == '\0')
10352 return 0;
10353 else
10354 return -1;
10355}
10356
10357/* Send a prepared I/O packet to the target and read its response.
10358 The prepared packet is in the global RS->BUF before this function
10359 is called, and the answer is there when we return.
10360
10361 COMMAND_BYTES is the length of the request to send, which may include
10362 binary data. WHICH_PACKET is the packet configuration to check
10363 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10364 is set to the error number and -1 is returned. Otherwise the value
10365 returned by the function is returned.
10366
10367 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10368 attachment is expected; an error will be reported if there's a
10369 mismatch. If one is found, *ATTACHMENT will be set to point into
10370 the packet buffer and *ATTACHMENT_LEN will be set to the
10371 attachment's length. */
10372
10373static int
10374remote_hostio_send_command (int command_bytes, int which_packet,
10375 int *remote_errno, char **attachment,
10376 int *attachment_len)
10377{
10378 struct remote_state *rs = get_remote_state ();
10379 int ret, bytes_read;
10380 char *attachment_tmp;
10381
5d93a237 10382 if (!rs->remote_desc
4082afcc 10383 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10384 {
10385 *remote_errno = FILEIO_ENOSYS;
10386 return -1;
10387 }
10388
10389 putpkt_binary (rs->buf, command_bytes);
10390 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10391
10392 /* If it timed out, something is wrong. Don't try to parse the
10393 buffer. */
10394 if (bytes_read < 0)
10395 {
10396 *remote_errno = FILEIO_EINVAL;
10397 return -1;
10398 }
10399
10400 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10401 {
10402 case PACKET_ERROR:
10403 *remote_errno = FILEIO_EINVAL;
10404 return -1;
10405 case PACKET_UNKNOWN:
10406 *remote_errno = FILEIO_ENOSYS;
10407 return -1;
10408 case PACKET_OK:
10409 break;
10410 }
10411
10412 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10413 &attachment_tmp))
10414 {
10415 *remote_errno = FILEIO_EINVAL;
10416 return -1;
10417 }
10418
10419 /* Make sure we saw an attachment if and only if we expected one. */
10420 if ((attachment_tmp == NULL && attachment != NULL)
10421 || (attachment_tmp != NULL && attachment == NULL))
10422 {
10423 *remote_errno = FILEIO_EINVAL;
10424 return -1;
10425 }
10426
10427 /* If an attachment was found, it must point into the packet buffer;
10428 work out how many bytes there were. */
10429 if (attachment_tmp != NULL)
10430 {
10431 *attachment = attachment_tmp;
10432 *attachment_len = bytes_read - (*attachment - rs->buf);
10433 }
10434
10435 return ret;
10436}
10437
80152258
PA
10438/* Invalidate the readahead cache. */
10439
10440static void
10441readahead_cache_invalidate (void)
10442{
10443 struct remote_state *rs = get_remote_state ();
10444
10445 rs->readahead_cache.fd = -1;
10446}
10447
10448/* Invalidate the readahead cache if it is holding data for FD. */
10449
10450static void
10451readahead_cache_invalidate_fd (int fd)
10452{
10453 struct remote_state *rs = get_remote_state ();
10454
10455 if (rs->readahead_cache.fd == fd)
10456 rs->readahead_cache.fd = -1;
10457}
10458
15a201c8
GB
10459/* Set the filesystem remote_hostio functions that take FILENAME
10460 arguments will use. Return 0 on success, or -1 if an error
10461 occurs (and set *REMOTE_ERRNO). */
10462
10463static int
10464remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10465{
10466 struct remote_state *rs = get_remote_state ();
10467 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10468 char *p = rs->buf;
10469 int left = get_remote_packet_size () - 1;
10470 char arg[9];
10471 int ret;
10472
10473 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10474 return 0;
10475
10476 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10477 return 0;
10478
10479 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10480
10481 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10482 remote_buffer_add_string (&p, &left, arg);
10483
10484 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10485 remote_errno, NULL, NULL);
10486
10487 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10488 return 0;
10489
10490 if (ret == 0)
10491 rs->fs_pid = required_pid;
10492
10493 return ret;
10494}
10495
12e2a5fd 10496/* Implementation of to_fileio_open. */
a6b151f1
DJ
10497
10498static int
cd897586 10499remote_hostio_open (struct target_ops *self,
07c138c8 10500 struct inferior *inf, const char *filename,
4313b8c0
GB
10501 int flags, int mode, int warn_if_slow,
10502 int *remote_errno)
a6b151f1
DJ
10503{
10504 struct remote_state *rs = get_remote_state ();
10505 char *p = rs->buf;
10506 int left = get_remote_packet_size () - 1;
10507
4313b8c0
GB
10508 if (warn_if_slow)
10509 {
10510 static int warning_issued = 0;
10511
10512 printf_unfiltered (_("Reading %s from remote target...\n"),
10513 filename);
10514
10515 if (!warning_issued)
10516 {
10517 warning (_("File transfers from remote targets can be slow."
10518 " Use \"set sysroot\" to access files locally"
10519 " instead."));
10520 warning_issued = 1;
10521 }
10522 }
10523
15a201c8
GB
10524 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10525 return -1;
10526
a6b151f1
DJ
10527 remote_buffer_add_string (&p, &left, "vFile:open:");
10528
10529 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10530 strlen (filename));
10531 remote_buffer_add_string (&p, &left, ",");
10532
10533 remote_buffer_add_int (&p, &left, flags);
10534 remote_buffer_add_string (&p, &left, ",");
10535
10536 remote_buffer_add_int (&p, &left, mode);
10537
10538 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10539 remote_errno, NULL, NULL);
10540}
10541
12e2a5fd 10542/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
10543
10544static int
0d866f62
TT
10545remote_hostio_pwrite (struct target_ops *self,
10546 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
10547 ULONGEST offset, int *remote_errno)
10548{
10549 struct remote_state *rs = get_remote_state ();
10550 char *p = rs->buf;
10551 int left = get_remote_packet_size ();
10552 int out_len;
10553
80152258
PA
10554 readahead_cache_invalidate_fd (fd);
10555
a6b151f1
DJ
10556 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10557
10558 remote_buffer_add_int (&p, &left, fd);
10559 remote_buffer_add_string (&p, &left, ",");
10560
10561 remote_buffer_add_int (&p, &left, offset);
10562 remote_buffer_add_string (&p, &left, ",");
10563
124e13d9 10564 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
10565 get_remote_packet_size () - (p - rs->buf));
10566
10567 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10568 remote_errno, NULL, NULL);
10569}
10570
80152258
PA
10571/* Helper for the implementation of to_fileio_pread. Read the file
10572 from the remote side with vFile:pread. */
a6b151f1
DJ
10573
10574static int
80152258
PA
10575remote_hostio_pread_vFile (struct target_ops *self,
10576 int fd, gdb_byte *read_buf, int len,
10577 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
10578{
10579 struct remote_state *rs = get_remote_state ();
10580 char *p = rs->buf;
10581 char *attachment;
10582 int left = get_remote_packet_size ();
10583 int ret, attachment_len;
10584 int read_len;
10585
10586 remote_buffer_add_string (&p, &left, "vFile:pread:");
10587
10588 remote_buffer_add_int (&p, &left, fd);
10589 remote_buffer_add_string (&p, &left, ",");
10590
10591 remote_buffer_add_int (&p, &left, len);
10592 remote_buffer_add_string (&p, &left, ",");
10593
10594 remote_buffer_add_int (&p, &left, offset);
10595
10596 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10597 remote_errno, &attachment,
10598 &attachment_len);
10599
10600 if (ret < 0)
10601 return ret;
10602
bc20a4af 10603 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
10604 read_buf, len);
10605 if (read_len != ret)
10606 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10607
10608 return ret;
10609}
10610
80152258
PA
10611/* Serve pread from the readahead cache. Returns number of bytes
10612 read, or 0 if the request can't be served from the cache. */
10613
10614static int
10615remote_hostio_pread_from_cache (struct remote_state *rs,
10616 int fd, gdb_byte *read_buf, size_t len,
10617 ULONGEST offset)
10618{
10619 struct readahead_cache *cache = &rs->readahead_cache;
10620
10621 if (cache->fd == fd
10622 && cache->offset <= offset
10623 && offset < cache->offset + cache->bufsize)
10624 {
10625 ULONGEST max = cache->offset + cache->bufsize;
10626
10627 if (offset + len > max)
10628 len = max - offset;
10629
10630 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10631 return len;
10632 }
10633
10634 return 0;
10635}
10636
10637/* Implementation of to_fileio_pread. */
10638
10639static int
10640remote_hostio_pread (struct target_ops *self,
10641 int fd, gdb_byte *read_buf, int len,
10642 ULONGEST offset, int *remote_errno)
10643{
10644 int ret;
10645 struct remote_state *rs = get_remote_state ();
10646 struct readahead_cache *cache = &rs->readahead_cache;
10647
10648 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10649 if (ret > 0)
10650 {
10651 cache->hit_count++;
10652
10653 if (remote_debug)
10654 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10655 pulongest (cache->hit_count));
10656 return ret;
10657 }
10658
10659 cache->miss_count++;
10660 if (remote_debug)
10661 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10662 pulongest (cache->miss_count));
10663
10664 cache->fd = fd;
10665 cache->offset = offset;
10666 cache->bufsize = get_remote_packet_size ();
10667 cache->buf = xrealloc (cache->buf, cache->bufsize);
10668
10669 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10670 cache->offset, remote_errno);
10671 if (ret <= 0)
10672 {
10673 readahead_cache_invalidate_fd (fd);
10674 return ret;
10675 }
10676
10677 cache->bufsize = ret;
10678 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10679}
10680
12e2a5fd 10681/* Implementation of to_fileio_close. */
a6b151f1
DJ
10682
10683static int
df39ea25 10684remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
10685{
10686 struct remote_state *rs = get_remote_state ();
10687 char *p = rs->buf;
10688 int left = get_remote_packet_size () - 1;
10689
80152258
PA
10690 readahead_cache_invalidate_fd (fd);
10691
a6b151f1
DJ
10692 remote_buffer_add_string (&p, &left, "vFile:close:");
10693
10694 remote_buffer_add_int (&p, &left, fd);
10695
10696 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10697 remote_errno, NULL, NULL);
10698}
10699
12e2a5fd 10700/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
10701
10702static int
dbbca37d 10703remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
10704 struct inferior *inf, const char *filename,
10705 int *remote_errno)
a6b151f1
DJ
10706{
10707 struct remote_state *rs = get_remote_state ();
10708 char *p = rs->buf;
10709 int left = get_remote_packet_size () - 1;
10710
15a201c8
GB
10711 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10712 return -1;
10713
a6b151f1
DJ
10714 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10715
10716 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10717 strlen (filename));
10718
10719 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10720 remote_errno, NULL, NULL);
10721}
10722
12e2a5fd 10723/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
10724
10725static char *
fab5aa7c 10726remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
10727 struct inferior *inf, const char *filename,
10728 int *remote_errno)
b9e7b9c3
UW
10729{
10730 struct remote_state *rs = get_remote_state ();
10731 char *p = rs->buf;
10732 char *attachment;
10733 int left = get_remote_packet_size ();
10734 int len, attachment_len;
10735 int read_len;
10736 char *ret;
10737
15a201c8
GB
10738 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10739 return NULL;
10740
b9e7b9c3
UW
10741 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10742
10743 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10744 strlen (filename));
10745
10746 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10747 remote_errno, &attachment,
10748 &attachment_len);
10749
10750 if (len < 0)
10751 return NULL;
10752
10753 ret = xmalloc (len + 1);
10754
bc20a4af
PA
10755 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10756 (gdb_byte *) ret, len);
b9e7b9c3
UW
10757 if (read_len != len)
10758 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10759
10760 ret[len] = '\0';
10761 return ret;
10762}
10763
12e2a5fd 10764/* Implementation of to_fileio_fstat. */
0a93529c
GB
10765
10766static int
10767remote_hostio_fstat (struct target_ops *self,
10768 int fd, struct stat *st,
10769 int *remote_errno)
10770{
10771 struct remote_state *rs = get_remote_state ();
10772 char *p = rs->buf;
10773 int left = get_remote_packet_size ();
10774 int attachment_len, ret;
10775 char *attachment;
10776 struct fio_stat fst;
10777 int read_len;
10778
464b0089
GB
10779 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10780
10781 remote_buffer_add_int (&p, &left, fd);
10782
10783 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10784 remote_errno, &attachment,
10785 &attachment_len);
10786 if (ret < 0)
0a93529c 10787 {
464b0089
GB
10788 if (*remote_errno != FILEIO_ENOSYS)
10789 return ret;
10790
0a93529c
GB
10791 /* Strictly we should return -1, ENOSYS here, but when
10792 "set sysroot remote:" was implemented in August 2008
10793 BFD's need for a stat function was sidestepped with
10794 this hack. This was not remedied until March 2015
10795 so we retain the previous behavior to avoid breaking
10796 compatibility.
10797
10798 Note that the memset is a March 2015 addition; older
10799 GDBs set st_size *and nothing else* so the structure
10800 would have garbage in all other fields. This might
10801 break something but retaining the previous behavior
10802 here would be just too wrong. */
10803
10804 memset (st, 0, sizeof (struct stat));
10805 st->st_size = INT_MAX;
10806 return 0;
10807 }
10808
0a93529c
GB
10809 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10810 (gdb_byte *) &fst, sizeof (fst));
10811
10812 if (read_len != ret)
10813 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10814
10815 if (read_len != sizeof (fst))
10816 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10817 read_len, (int) sizeof (fst));
10818
10819 remote_fileio_to_host_stat (&fst, st);
10820
10821 return 0;
10822}
10823
12e2a5fd 10824/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
10825
10826static int
10827remote_filesystem_is_local (struct target_ops *self)
10828{
10829 /* Valgrind GDB presents itself as a remote target but works
10830 on the local filesystem: it does not implement remote get
10831 and users are not expected to set a sysroot. To handle
10832 this case we treat the remote filesystem as local if the
10833 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
10834 does not support vFile:open. */
a3be80c3 10835 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
10836 {
10837 enum packet_support ps = packet_support (PACKET_vFile_open);
10838
10839 if (ps == PACKET_SUPPORT_UNKNOWN)
10840 {
10841 int fd, remote_errno;
10842
10843 /* Try opening a file to probe support. The supplied
10844 filename is irrelevant, we only care about whether
10845 the stub recognizes the packet or not. */
07c138c8 10846 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 10847 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
10848 &remote_errno);
10849
10850 if (fd >= 0)
10851 remote_hostio_close (self, fd, &remote_errno);
10852
10853 ps = packet_support (PACKET_vFile_open);
10854 }
10855
10856 if (ps == PACKET_DISABLE)
10857 {
10858 static int warning_issued = 0;
10859
10860 if (!warning_issued)
10861 {
10862 warning (_("remote target does not support file"
10863 " transfer, attempting to access files"
10864 " from local filesystem."));
10865 warning_issued = 1;
10866 }
10867
10868 return 1;
10869 }
10870 }
10871
10872 return 0;
10873}
10874
a6b151f1
DJ
10875static int
10876remote_fileio_errno_to_host (int errnum)
10877{
10878 switch (errnum)
10879 {
10880 case FILEIO_EPERM:
10881 return EPERM;
10882 case FILEIO_ENOENT:
10883 return ENOENT;
10884 case FILEIO_EINTR:
10885 return EINTR;
10886 case FILEIO_EIO:
10887 return EIO;
10888 case FILEIO_EBADF:
10889 return EBADF;
10890 case FILEIO_EACCES:
10891 return EACCES;
10892 case FILEIO_EFAULT:
10893 return EFAULT;
10894 case FILEIO_EBUSY:
10895 return EBUSY;
10896 case FILEIO_EEXIST:
10897 return EEXIST;
10898 case FILEIO_ENODEV:
10899 return ENODEV;
10900 case FILEIO_ENOTDIR:
10901 return ENOTDIR;
10902 case FILEIO_EISDIR:
10903 return EISDIR;
10904 case FILEIO_EINVAL:
10905 return EINVAL;
10906 case FILEIO_ENFILE:
10907 return ENFILE;
10908 case FILEIO_EMFILE:
10909 return EMFILE;
10910 case FILEIO_EFBIG:
10911 return EFBIG;
10912 case FILEIO_ENOSPC:
10913 return ENOSPC;
10914 case FILEIO_ESPIPE:
10915 return ESPIPE;
10916 case FILEIO_EROFS:
10917 return EROFS;
10918 case FILEIO_ENOSYS:
10919 return ENOSYS;
10920 case FILEIO_ENAMETOOLONG:
10921 return ENAMETOOLONG;
10922 }
10923 return -1;
10924}
10925
10926static char *
10927remote_hostio_error (int errnum)
10928{
10929 int host_error = remote_fileio_errno_to_host (errnum);
10930
10931 if (host_error == -1)
10932 error (_("Unknown remote I/O error %d"), errnum);
10933 else
10934 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10935}
10936
a6b151f1
DJ
10937static void
10938remote_hostio_close_cleanup (void *opaque)
10939{
10940 int fd = *(int *) opaque;
10941 int remote_errno;
10942
df39ea25 10943 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
10944}
10945
10946void
10947remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10948{
10949 struct cleanup *back_to, *close_cleanup;
10950 int retcode, fd, remote_errno, bytes, io_size;
10951 FILE *file;
10952 gdb_byte *buffer;
10953 int bytes_in_buffer;
10954 int saw_eof;
10955 ULONGEST offset;
5d93a237 10956 struct remote_state *rs = get_remote_state ();
a6b151f1 10957
5d93a237 10958 if (!rs->remote_desc)
a6b151f1
DJ
10959 error (_("command can only be used with remote target"));
10960
614c279d 10961 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10962 if (file == NULL)
10963 perror_with_name (local_file);
7c8a8b04 10964 back_to = make_cleanup_fclose (file);
a6b151f1 10965
07c138c8 10966 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 10967 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 10968 | FILEIO_O_TRUNC),
4313b8c0 10969 0700, 0, &remote_errno);
a6b151f1
DJ
10970 if (fd == -1)
10971 remote_hostio_error (remote_errno);
10972
10973 /* Send up to this many bytes at once. They won't all fit in the
10974 remote packet limit, so we'll transfer slightly fewer. */
10975 io_size = get_remote_packet_size ();
10976 buffer = xmalloc (io_size);
10977 make_cleanup (xfree, buffer);
10978
10979 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10980
10981 bytes_in_buffer = 0;
10982 saw_eof = 0;
10983 offset = 0;
10984 while (bytes_in_buffer || !saw_eof)
10985 {
10986 if (!saw_eof)
10987 {
3e43a32a
MS
10988 bytes = fread (buffer + bytes_in_buffer, 1,
10989 io_size - bytes_in_buffer,
a6b151f1
DJ
10990 file);
10991 if (bytes == 0)
10992 {
10993 if (ferror (file))
10994 error (_("Error reading %s."), local_file);
10995 else
10996 {
10997 /* EOF. Unless there is something still in the
10998 buffer from the last iteration, we are done. */
10999 saw_eof = 1;
11000 if (bytes_in_buffer == 0)
11001 break;
11002 }
11003 }
11004 }
11005 else
11006 bytes = 0;
11007
11008 bytes += bytes_in_buffer;
11009 bytes_in_buffer = 0;
11010
0d866f62
TT
11011 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11012 fd, buffer, bytes,
3e43a32a 11013 offset, &remote_errno);
a6b151f1
DJ
11014
11015 if (retcode < 0)
11016 remote_hostio_error (remote_errno);
11017 else if (retcode == 0)
11018 error (_("Remote write of %d bytes returned 0!"), bytes);
11019 else if (retcode < bytes)
11020 {
11021 /* Short write. Save the rest of the read data for the next
11022 write. */
11023 bytes_in_buffer = bytes - retcode;
11024 memmove (buffer, buffer + retcode, bytes_in_buffer);
11025 }
11026
11027 offset += retcode;
11028 }
11029
11030 discard_cleanups (close_cleanup);
df39ea25 11031 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11032 remote_hostio_error (remote_errno);
11033
11034 if (from_tty)
11035 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11036 do_cleanups (back_to);
11037}
11038
11039void
11040remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11041{
11042 struct cleanup *back_to, *close_cleanup;
cea39f65 11043 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11044 FILE *file;
11045 gdb_byte *buffer;
11046 ULONGEST offset;
5d93a237 11047 struct remote_state *rs = get_remote_state ();
a6b151f1 11048
5d93a237 11049 if (!rs->remote_desc)
a6b151f1
DJ
11050 error (_("command can only be used with remote target"));
11051
07c138c8 11052 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11053 remote_file, FILEIO_O_RDONLY, 0, 0,
11054 &remote_errno);
a6b151f1
DJ
11055 if (fd == -1)
11056 remote_hostio_error (remote_errno);
11057
614c279d 11058 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11059 if (file == NULL)
11060 perror_with_name (local_file);
7c8a8b04 11061 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11062
11063 /* Send up to this many bytes at once. They won't all fit in the
11064 remote packet limit, so we'll transfer slightly fewer. */
11065 io_size = get_remote_packet_size ();
11066 buffer = xmalloc (io_size);
11067 make_cleanup (xfree, buffer);
11068
11069 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11070
11071 offset = 0;
11072 while (1)
11073 {
a3be983c
TT
11074 bytes = remote_hostio_pread (find_target_at (process_stratum),
11075 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11076 if (bytes == 0)
11077 /* Success, but no bytes, means end-of-file. */
11078 break;
11079 if (bytes == -1)
11080 remote_hostio_error (remote_errno);
11081
11082 offset += bytes;
11083
11084 bytes = fwrite (buffer, 1, bytes, file);
11085 if (bytes == 0)
11086 perror_with_name (local_file);
11087 }
11088
11089 discard_cleanups (close_cleanup);
df39ea25 11090 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11091 remote_hostio_error (remote_errno);
11092
11093 if (from_tty)
11094 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11095 do_cleanups (back_to);
11096}
11097
11098void
11099remote_file_delete (const char *remote_file, int from_tty)
11100{
11101 int retcode, remote_errno;
5d93a237 11102 struct remote_state *rs = get_remote_state ();
a6b151f1 11103
5d93a237 11104 if (!rs->remote_desc)
a6b151f1
DJ
11105 error (_("command can only be used with remote target"));
11106
dbbca37d 11107 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11108 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11109 if (retcode == -1)
11110 remote_hostio_error (remote_errno);
11111
11112 if (from_tty)
11113 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11114}
11115
11116static void
11117remote_put_command (char *args, int from_tty)
11118{
11119 struct cleanup *back_to;
11120 char **argv;
11121
d1a41061
PP
11122 if (args == NULL)
11123 error_no_arg (_("file to put"));
11124
11125 argv = gdb_buildargv (args);
a6b151f1
DJ
11126 back_to = make_cleanup_freeargv (argv);
11127 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11128 error (_("Invalid parameters to remote put"));
11129
11130 remote_file_put (argv[0], argv[1], from_tty);
11131
11132 do_cleanups (back_to);
11133}
11134
11135static void
11136remote_get_command (char *args, int from_tty)
11137{
11138 struct cleanup *back_to;
11139 char **argv;
11140
d1a41061
PP
11141 if (args == NULL)
11142 error_no_arg (_("file to get"));
11143
11144 argv = gdb_buildargv (args);
a6b151f1
DJ
11145 back_to = make_cleanup_freeargv (argv);
11146 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11147 error (_("Invalid parameters to remote get"));
11148
11149 remote_file_get (argv[0], argv[1], from_tty);
11150
11151 do_cleanups (back_to);
11152}
11153
11154static void
11155remote_delete_command (char *args, int from_tty)
11156{
11157 struct cleanup *back_to;
11158 char **argv;
11159
d1a41061
PP
11160 if (args == NULL)
11161 error_no_arg (_("file to delete"));
11162
11163 argv = gdb_buildargv (args);
a6b151f1
DJ
11164 back_to = make_cleanup_freeargv (argv);
11165 if (argv[0] == NULL || argv[1] != NULL)
11166 error (_("Invalid parameters to remote delete"));
11167
11168 remote_file_delete (argv[0], from_tty);
11169
11170 do_cleanups (back_to);
11171}
11172
11173static void
11174remote_command (char *args, int from_tty)
11175{
635c7e8a 11176 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11177}
11178
b2175913 11179static int
19db3e69 11180remote_can_execute_reverse (struct target_ops *self)
b2175913 11181{
4082afcc
PA
11182 if (packet_support (PACKET_bs) == PACKET_ENABLE
11183 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11184 return 1;
11185 else
11186 return 0;
b2175913
MS
11187}
11188
74531fed 11189static int
2a9a2795 11190remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11191{
11192 return 1;
11193}
11194
03583c20 11195static int
2bfc0540 11196remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11197{
11198 /* Only supported in extended mode. */
11199 return 0;
11200}
11201
8a305172 11202static int
86ce2668 11203remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11204{
11205 struct remote_state *rs = get_remote_state ();
a744cf53 11206
901f9912
UW
11207 /* Only extended-remote handles being attached to multiple
11208 processes, even though plain remote can use the multi-process
11209 thread id extensions, so that GDB knows the target process's
11210 PID. */
11211 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
11212}
11213
70221824 11214static int
782b2b07
SS
11215remote_supports_cond_tracepoints (void)
11216{
4082afcc 11217 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11218}
11219
3788aec7 11220static int
efcc2da7 11221remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11222{
4082afcc 11223 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11224}
11225
70221824 11226static int
7a697b8d
SS
11227remote_supports_fast_tracepoints (void)
11228{
4082afcc 11229 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11230}
11231
0fb4aa4b
PA
11232static int
11233remote_supports_static_tracepoints (void)
11234{
4082afcc 11235 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11236}
11237
1e4d1764
YQ
11238static int
11239remote_supports_install_in_trace (void)
11240{
4082afcc 11241 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11242}
11243
d248b706 11244static int
7d178d6a 11245remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11246{
4082afcc
PA
11247 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11248 == PACKET_ENABLE);
d248b706
KY
11249}
11250
3065dfb6 11251static int
6de37a3a 11252remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11253{
4082afcc 11254 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11255}
11256
d3ce09f5 11257static int
78eff0ec 11258remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11259{
4082afcc 11260 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11261}
11262
35b1e5cc 11263static void
ecae04e1 11264remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11265{
11266 putpkt ("QTinit");
11267 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11268 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11269 error (_("Target does not support this command."));
11270}
11271
11272static void free_actions_list (char **actions_list);
11273static void free_actions_list_cleanup_wrapper (void *);
11274static void
11275free_actions_list_cleanup_wrapper (void *al)
11276{
11277 free_actions_list (al);
11278}
11279
11280static void
11281free_actions_list (char **actions_list)
11282{
11283 int ndx;
11284
11285 if (actions_list == 0)
11286 return;
11287
11288 for (ndx = 0; actions_list[ndx]; ndx++)
11289 xfree (actions_list[ndx]);
11290
11291 xfree (actions_list);
11292}
11293
409873ef
SS
11294/* Recursive routine to walk through command list including loops, and
11295 download packets for each command. */
11296
11297static void
11298remote_download_command_source (int num, ULONGEST addr,
11299 struct command_line *cmds)
11300{
11301 struct remote_state *rs = get_remote_state ();
11302 struct command_line *cmd;
11303
11304 for (cmd = cmds; cmd; cmd = cmd->next)
11305 {
0df8b418 11306 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11307 strcpy (rs->buf, "QTDPsrc:");
11308 encode_source_string (num, addr, "cmd", cmd->line,
11309 rs->buf + strlen (rs->buf),
11310 rs->buf_size - strlen (rs->buf));
11311 putpkt (rs->buf);
11312 remote_get_noisy_reply (&target_buf, &target_buf_size);
11313 if (strcmp (target_buf, "OK"))
11314 warning (_("Target does not support source download."));
11315
11316 if (cmd->control_type == while_control
11317 || cmd->control_type == while_stepping_control)
11318 {
11319 remote_download_command_source (num, addr, *cmd->body_list);
11320
0df8b418 11321 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11322 strcpy (rs->buf, "QTDPsrc:");
11323 encode_source_string (num, addr, "cmd", "end",
11324 rs->buf + strlen (rs->buf),
11325 rs->buf_size - strlen (rs->buf));
11326 putpkt (rs->buf);
11327 remote_get_noisy_reply (&target_buf, &target_buf_size);
11328 if (strcmp (target_buf, "OK"))
11329 warning (_("Target does not support source download."));
11330 }
11331 }
11332}
11333
35b1e5cc 11334static void
548f7808 11335remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11336{
bba74b36 11337#define BUF_SIZE 2048
e8ba3115 11338
35b1e5cc 11339 CORE_ADDR tpaddr;
409873ef 11340 char addrbuf[40];
bba74b36 11341 char buf[BUF_SIZE];
35b1e5cc
SS
11342 char **tdp_actions;
11343 char **stepping_actions;
11344 int ndx;
11345 struct cleanup *old_chain = NULL;
11346 struct agent_expr *aexpr;
11347 struct cleanup *aexpr_chain = NULL;
11348 char *pkt;
e8ba3115 11349 struct breakpoint *b = loc->owner;
d9b3f62e 11350 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11351
dc673c81 11352 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11353 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11354 tdp_actions);
11355 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11356 stepping_actions);
11357
11358 tpaddr = loc->address;
11359 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11360 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11361 addrbuf, /* address */
11362 (b->enable_state == bp_enabled ? 'E' : 'D'),
11363 t->step_count, t->pass_count);
e8ba3115
YQ
11364 /* Fast tracepoints are mostly handled by the target, but we can
11365 tell the target how big of an instruction block should be moved
11366 around. */
11367 if (b->type == bp_fast_tracepoint)
11368 {
11369 /* Only test for support at download time; we may not know
11370 target capabilities at definition time. */
11371 if (remote_supports_fast_tracepoints ())
35b1e5cc 11372 {
6b940e6a
PL
11373 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11374 NULL))
bba74b36 11375 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11376 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11377 else
e8ba3115
YQ
11378 /* If it passed validation at definition but fails now,
11379 something is very wrong. */
11380 internal_error (__FILE__, __LINE__,
11381 _("Fast tracepoint not "
11382 "valid during download"));
35b1e5cc 11383 }
e8ba3115
YQ
11384 else
11385 /* Fast tracepoints are functionally identical to regular
11386 tracepoints, so don't take lack of support as a reason to
11387 give up on the trace run. */
11388 warning (_("Target does not support fast tracepoints, "
11389 "downloading %d as regular tracepoint"), b->number);
11390 }
11391 else if (b->type == bp_static_tracepoint)
11392 {
11393 /* Only test for support at download time; we may not know
11394 target capabilities at definition time. */
11395 if (remote_supports_static_tracepoints ())
0fb4aa4b 11396 {
e8ba3115 11397 struct static_tracepoint_marker marker;
0fb4aa4b 11398
e8ba3115
YQ
11399 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11400 strcat (buf, ":S");
0fb4aa4b 11401 else
e8ba3115 11402 error (_("Static tracepoint not valid during download"));
0fb4aa4b 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
11407 to give up on the trace run. */
11408 error (_("Target does not support static tracepoints"));
11409 }
11410 /* If the tracepoint has a conditional, make it into an agent
11411 expression and append to the definition. */
11412 if (loc->cond)
11413 {
11414 /* Only test support at download time, we may not know target
11415 capabilities at definition time. */
11416 if (remote_supports_cond_tracepoints ())
35b1e5cc 11417 {
e8ba3115
YQ
11418 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11419 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11420 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11421 aexpr->len);
e8ba3115
YQ
11422 pkt = buf + strlen (buf);
11423 for (ndx = 0; ndx < aexpr->len; ++ndx)
11424 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11425 *pkt = '\0';
11426 do_cleanups (aexpr_chain);
35b1e5cc 11427 }
e8ba3115
YQ
11428 else
11429 warning (_("Target does not support conditional tracepoints, "
11430 "ignoring tp %d cond"), b->number);
11431 }
35b1e5cc 11432
d9b3f62e 11433 if (b->commands || *default_collect)
e8ba3115
YQ
11434 strcat (buf, "-");
11435 putpkt (buf);
11436 remote_get_noisy_reply (&target_buf, &target_buf_size);
11437 if (strcmp (target_buf, "OK"))
11438 error (_("Target does not support tracepoints."));
35b1e5cc 11439
e8ba3115
YQ
11440 /* do_single_steps (t); */
11441 if (tdp_actions)
11442 {
11443 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11444 {
e8ba3115 11445 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11446 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11447 b->number, addrbuf, /* address */
11448 tdp_actions[ndx],
11449 ((tdp_actions[ndx + 1] || stepping_actions)
11450 ? '-' : 0));
e8ba3115
YQ
11451 putpkt (buf);
11452 remote_get_noisy_reply (&target_buf,
11453 &target_buf_size);
11454 if (strcmp (target_buf, "OK"))
11455 error (_("Error on target while setting tracepoints."));
35b1e5cc 11456 }
e8ba3115
YQ
11457 }
11458 if (stepping_actions)
11459 {
11460 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11461 {
e8ba3115 11462 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11463 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11464 b->number, addrbuf, /* address */
11465 ((ndx == 0) ? "S" : ""),
11466 stepping_actions[ndx],
11467 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11468 putpkt (buf);
11469 remote_get_noisy_reply (&target_buf,
11470 &target_buf_size);
11471 if (strcmp (target_buf, "OK"))
11472 error (_("Error on target while setting tracepoints."));
35b1e5cc 11473 }
e8ba3115 11474 }
409873ef 11475
4082afcc 11476 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11477 {
f00aae0f 11478 if (b->location != NULL)
409873ef 11479 {
e8ba3115 11480 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11481 encode_source_string (b->number, loc->address, "at",
11482 event_location_to_string (b->location),
11483 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11484 putpkt (buf);
11485 remote_get_noisy_reply (&target_buf, &target_buf_size);
11486 if (strcmp (target_buf, "OK"))
11487 warning (_("Target does not support source download."));
409873ef 11488 }
e8ba3115
YQ
11489 if (b->cond_string)
11490 {
11491 strcpy (buf, "QTDPsrc:");
11492 encode_source_string (b->number, loc->address,
11493 "cond", b->cond_string, buf + strlen (buf),
11494 2048 - strlen (buf));
11495 putpkt (buf);
11496 remote_get_noisy_reply (&target_buf, &target_buf_size);
11497 if (strcmp (target_buf, "OK"))
11498 warning (_("Target does not support source download."));
11499 }
11500 remote_download_command_source (b->number, loc->address,
11501 breakpoint_commands (b));
35b1e5cc 11502 }
e8ba3115
YQ
11503
11504 do_cleanups (old_chain);
35b1e5cc
SS
11505}
11506
1e4d1764 11507static int
a52a8357 11508remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 11509{
1e51243a
PA
11510 struct remote_state *rs = get_remote_state ();
11511 struct trace_status *ts;
11512 int status;
11513
11514 /* Don't try to install tracepoints until we've relocated our
11515 symbols, and fetched and merged the target's tracepoint list with
11516 ours. */
11517 if (rs->starting_up)
11518 return 0;
11519
11520 ts = current_trace_status ();
8bd200f1 11521 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
11522
11523 if (status == -1 || !ts->running_known || !ts->running)
11524 return 0;
11525
11526 /* If we are in a tracing experiment, but remote stub doesn't support
11527 installing tracepoint in trace, we have to return. */
11528 if (!remote_supports_install_in_trace ())
11529 return 0;
11530
11531 return 1;
11532}
11533
11534
35b1e5cc 11535static void
559d2b81
TT
11536remote_download_trace_state_variable (struct target_ops *self,
11537 struct trace_state_variable *tsv)
35b1e5cc
SS
11538{
11539 struct remote_state *rs = get_remote_state ();
00bf0b85 11540 char *p;
35b1e5cc 11541
bba74b36
YQ
11542 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11543 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11544 tsv->builtin);
00bf0b85
SS
11545 p = rs->buf + strlen (rs->buf);
11546 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11547 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 11548 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 11549 *p++ = '\0';
35b1e5cc
SS
11550 putpkt (rs->buf);
11551 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11552 if (*target_buf == '\0')
11553 error (_("Target does not support this command."));
11554 if (strcmp (target_buf, "OK") != 0)
11555 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
11556}
11557
d248b706 11558static void
46670d57
TT
11559remote_enable_tracepoint (struct target_ops *self,
11560 struct bp_location *location)
d248b706
KY
11561{
11562 struct remote_state *rs = get_remote_state ();
11563 char addr_buf[40];
11564
11565 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11566 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11567 location->owner->number, addr_buf);
d248b706
KY
11568 putpkt (rs->buf);
11569 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11570 if (*rs->buf == '\0')
11571 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11572 if (strcmp (rs->buf, "OK") != 0)
11573 error (_("Error on target while enabling tracepoint."));
11574}
11575
11576static void
780b049c
TT
11577remote_disable_tracepoint (struct target_ops *self,
11578 struct bp_location *location)
d248b706
KY
11579{
11580 struct remote_state *rs = get_remote_state ();
11581 char addr_buf[40];
11582
11583 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11584 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11585 location->owner->number, addr_buf);
d248b706
KY
11586 putpkt (rs->buf);
11587 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11588 if (*rs->buf == '\0')
11589 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11590 if (strcmp (rs->buf, "OK") != 0)
11591 error (_("Error on target while disabling tracepoint."));
11592}
11593
35b1e5cc 11594static void
583f9a86 11595remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
11596{
11597 asection *s;
81b9b86e 11598 bfd *abfd = NULL;
35b1e5cc 11599 bfd_size_type size;
608bcef2 11600 bfd_vma vma;
35b1e5cc 11601 int anysecs = 0;
c2fa21f1 11602 int offset = 0;
35b1e5cc
SS
11603
11604 if (!exec_bfd)
11605 return; /* No information to give. */
11606
11607 strcpy (target_buf, "QTro");
9779ab84 11608 offset = strlen (target_buf);
35b1e5cc
SS
11609 for (s = exec_bfd->sections; s; s = s->next)
11610 {
11611 char tmp1[40], tmp2[40];
c2fa21f1 11612 int sec_length;
35b1e5cc
SS
11613
11614 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 11615 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
11616 (s->flags & SEC_READONLY) == 0)
11617 continue;
11618
11619 anysecs = 1;
81b9b86e 11620 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 11621 size = bfd_get_section_size (s);
608bcef2
HZ
11622 sprintf_vma (tmp1, vma);
11623 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
11624 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11625 if (offset + sec_length + 1 > target_buf_size)
11626 {
4082afcc 11627 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 11628 warning (_("\
c2fa21f1
HZ
11629Too many sections for read-only sections definition packet."));
11630 break;
11631 }
bba74b36
YQ
11632 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11633 tmp1, tmp2);
c2fa21f1 11634 offset += sec_length;
35b1e5cc
SS
11635 }
11636 if (anysecs)
11637 {
11638 putpkt (target_buf);
11639 getpkt (&target_buf, &target_buf_size, 0);
11640 }
11641}
11642
11643static void
e2d1aae3 11644remote_trace_start (struct target_ops *self)
35b1e5cc
SS
11645{
11646 putpkt ("QTStart");
11647 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11648 if (*target_buf == '\0')
11649 error (_("Target does not support this command."));
11650 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11651 error (_("Bogus reply from target: %s"), target_buf);
11652}
11653
11654static int
8bd200f1 11655remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 11656{
953b98d1 11657 /* Initialize it just to avoid a GCC false warning. */
f652de6f 11658 char *p = NULL;
0df8b418 11659 /* FIXME we need to get register block size some other way. */
00bf0b85 11660 extern int trace_regblock_size;
bd3eecc3
PA
11661 enum packet_result result;
11662
4082afcc 11663 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 11664 return -1;
a744cf53 11665
00bf0b85
SS
11666 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11667
049dc89b
JK
11668 putpkt ("qTStatus");
11669
492d29ea 11670 TRY
67f41397
JK
11671 {
11672 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11673 }
492d29ea 11674 CATCH (ex, RETURN_MASK_ERROR)
67f41397 11675 {
598d3636
JK
11676 if (ex.error != TARGET_CLOSE_ERROR)
11677 {
11678 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11679 return -1;
11680 }
11681 throw_exception (ex);
67f41397 11682 }
492d29ea 11683 END_CATCH
00bf0b85 11684
bd3eecc3
PA
11685 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11686
00bf0b85 11687 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 11688 if (result == PACKET_UNKNOWN)
00bf0b85 11689 return -1;
35b1e5cc 11690
00bf0b85 11691 /* We're working with a live target. */
f5911ea1 11692 ts->filename = NULL;
00bf0b85 11693
00bf0b85 11694 if (*p++ != 'T')
35b1e5cc
SS
11695 error (_("Bogus trace status reply from target: %s"), target_buf);
11696
84cebc4a
YQ
11697 /* Function 'parse_trace_status' sets default value of each field of
11698 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
11699 parse_trace_status (p, ts);
11700
11701 return ts->running;
35b1e5cc
SS
11702}
11703
70221824 11704static void
db90e85c 11705remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
11706 struct uploaded_tp *utp)
11707{
11708 struct remote_state *rs = get_remote_state ();
f196051f
SS
11709 char *reply;
11710 struct bp_location *loc;
11711 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 11712 size_t size = get_remote_packet_size ();
f196051f
SS
11713
11714 if (tp)
11715 {
11716 tp->base.hit_count = 0;
11717 tp->traceframe_usage = 0;
11718 for (loc = tp->base.loc; loc; loc = loc->next)
11719 {
11720 /* If the tracepoint was never downloaded, don't go asking for
11721 any status. */
11722 if (tp->number_on_target == 0)
11723 continue;
bba74b36
YQ
11724 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11725 phex_nz (loc->address, 0));
f196051f
SS
11726 putpkt (rs->buf);
11727 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11728 if (reply && *reply)
11729 {
11730 if (*reply == 'V')
11731 parse_tracepoint_status (reply + 1, bp, utp);
11732 }
11733 }
11734 }
11735 else if (utp)
11736 {
11737 utp->hit_count = 0;
11738 utp->traceframe_usage = 0;
bba74b36
YQ
11739 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11740 phex_nz (utp->addr, 0));
f196051f
SS
11741 putpkt (rs->buf);
11742 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11743 if (reply && *reply)
11744 {
11745 if (*reply == 'V')
11746 parse_tracepoint_status (reply + 1, bp, utp);
11747 }
11748 }
11749}
11750
35b1e5cc 11751static void
74499f1b 11752remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
11753{
11754 putpkt ("QTStop");
11755 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11756 if (*target_buf == '\0')
11757 error (_("Target does not support this command."));
11758 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11759 error (_("Bogus reply from target: %s"), target_buf);
11760}
11761
11762static int
bd4c6793
TT
11763remote_trace_find (struct target_ops *self,
11764 enum trace_find_type type, int num,
cc5925ad 11765 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
11766 int *tpp)
11767{
11768 struct remote_state *rs = get_remote_state ();
bba74b36 11769 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
11770 char *p, *reply;
11771 int target_frameno = -1, target_tracept = -1;
11772
e6e4e701
PA
11773 /* Lookups other than by absolute frame number depend on the current
11774 trace selected, so make sure it is correct on the remote end
11775 first. */
11776 if (type != tfind_number)
11777 set_remote_traceframe ();
11778
35b1e5cc
SS
11779 p = rs->buf;
11780 strcpy (p, "QTFrame:");
11781 p = strchr (p, '\0');
11782 switch (type)
11783 {
11784 case tfind_number:
bba74b36 11785 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
11786 break;
11787 case tfind_pc:
bba74b36 11788 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
11789 break;
11790 case tfind_tp:
bba74b36 11791 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
11792 break;
11793 case tfind_range:
bba74b36
YQ
11794 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11795 phex_nz (addr2, 0));
35b1e5cc
SS
11796 break;
11797 case tfind_outside:
bba74b36
YQ
11798 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11799 phex_nz (addr2, 0));
35b1e5cc
SS
11800 break;
11801 default:
9b20d036 11802 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
11803 }
11804
11805 putpkt (rs->buf);
2f65bcb7 11806 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
11807 if (*reply == '\0')
11808 error (_("Target does not support this command."));
35b1e5cc
SS
11809
11810 while (reply && *reply)
11811 switch (*reply)
11812 {
11813 case 'F':
f197e0f1
VP
11814 p = ++reply;
11815 target_frameno = (int) strtol (p, &reply, 16);
11816 if (reply == p)
11817 error (_("Unable to parse trace frame number"));
e6e4e701
PA
11818 /* Don't update our remote traceframe number cache on failure
11819 to select a remote traceframe. */
f197e0f1
VP
11820 if (target_frameno == -1)
11821 return -1;
35b1e5cc
SS
11822 break;
11823 case 'T':
f197e0f1
VP
11824 p = ++reply;
11825 target_tracept = (int) strtol (p, &reply, 16);
11826 if (reply == p)
11827 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
11828 break;
11829 case 'O': /* "OK"? */
11830 if (reply[1] == 'K' && reply[2] == '\0')
11831 reply += 2;
11832 else
11833 error (_("Bogus reply from target: %s"), reply);
11834 break;
11835 default:
11836 error (_("Bogus reply from target: %s"), reply);
11837 }
11838 if (tpp)
11839 *tpp = target_tracept;
e6e4e701 11840
262e1174 11841 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
11842 return target_frameno;
11843}
11844
11845static int
4011015b
TT
11846remote_get_trace_state_variable_value (struct target_ops *self,
11847 int tsvnum, LONGEST *val)
35b1e5cc
SS
11848{
11849 struct remote_state *rs = get_remote_state ();
11850 char *reply;
11851 ULONGEST uval;
11852
e6e4e701
PA
11853 set_remote_traceframe ();
11854
bba74b36 11855 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
11856 putpkt (rs->buf);
11857 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11858 if (reply && *reply)
11859 {
11860 if (*reply == 'V')
11861 {
11862 unpack_varlen_hex (reply + 1, &uval);
11863 *val = (LONGEST) uval;
11864 return 1;
11865 }
11866 }
11867 return 0;
11868}
11869
00bf0b85 11870static int
dc3decaf 11871remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
11872{
11873 struct remote_state *rs = get_remote_state ();
11874 char *p, *reply;
11875
11876 p = rs->buf;
11877 strcpy (p, "QTSave:");
11878 p += strlen (p);
11879 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11880 error (_("Remote file name too long for trace save packet"));
9f1b45b0 11881 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
11882 *p++ = '\0';
11883 putpkt (rs->buf);
ad91cd99 11884 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 11885 if (*reply == '\0')
ad91cd99
PA
11886 error (_("Target does not support this command."));
11887 if (strcmp (reply, "OK") != 0)
11888 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
11889 return 0;
11890}
11891
11892/* This is basically a memory transfer, but needs to be its own packet
11893 because we don't know how the target actually organizes its trace
11894 memory, plus we want to be able to ask for as much as possible, but
11895 not be unhappy if we don't get as much as we ask for. */
11896
11897static LONGEST
88ee6f45
TT
11898remote_get_raw_trace_data (struct target_ops *self,
11899 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
11900{
11901 struct remote_state *rs = get_remote_state ();
11902 char *reply;
11903 char *p;
11904 int rslt;
11905
11906 p = rs->buf;
11907 strcpy (p, "qTBuffer:");
11908 p += strlen (p);
11909 p += hexnumstr (p, offset);
11910 *p++ = ',';
11911 p += hexnumstr (p, len);
11912 *p++ = '\0';
11913
11914 putpkt (rs->buf);
11915 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11916 if (reply && *reply)
11917 {
11918 /* 'l' by itself means we're at the end of the buffer and
11919 there is nothing more to get. */
11920 if (*reply == 'l')
11921 return 0;
11922
11923 /* Convert the reply into binary. Limit the number of bytes to
11924 convert according to our passed-in buffer size, rather than
11925 what was returned in the packet; if the target is
11926 unexpectedly generous and gives us a bigger reply than we
11927 asked for, we don't want to crash. */
11928 rslt = hex2bin (target_buf, buf, len);
11929 return rslt;
11930 }
11931
11932 /* Something went wrong, flag as an error. */
11933 return -1;
11934}
11935
35b1e5cc 11936static void
37b25738 11937remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11938{
11939 struct remote_state *rs = get_remote_state ();
11940
4082afcc 11941 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 11942 {
ad91cd99
PA
11943 char *reply;
11944
bba74b36 11945 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11946 putpkt (rs->buf);
ad91cd99
PA
11947 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11948 if (*reply == '\0')
33da3f1c 11949 error (_("Target does not support this command."));
ad91cd99
PA
11950 if (strcmp (reply, "OK") != 0)
11951 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11952 }
11953 else if (val)
11954 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11955}
11956
dc146f7c
VP
11957static int
11958remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11959{
11960 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11961
fe978cb0
PA
11962 if (info && info->priv)
11963 return info->priv->core;
dc146f7c
VP
11964 return -1;
11965}
11966
4daf5ac0 11967static void
736d5b1f 11968remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11969{
11970 struct remote_state *rs = get_remote_state ();
ad91cd99 11971 char *reply;
4daf5ac0 11972
bba74b36 11973 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11974 putpkt (rs->buf);
ad91cd99
PA
11975 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11976 if (*reply == '\0')
4daf5ac0 11977 error (_("Target does not support this command."));
ad91cd99
PA
11978 if (strcmp (reply, "OK") != 0)
11979 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
11980}
11981
b3b9301e 11982static struct traceframe_info *
a893e81f 11983remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
11984{
11985 char *text;
11986
11987 text = target_read_stralloc (&current_target,
11988 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11989 if (text != NULL)
11990 {
11991 struct traceframe_info *info;
11992 struct cleanup *back_to = make_cleanup (xfree, text);
11993
11994 info = parse_traceframe_info (text);
11995 do_cleanups (back_to);
11996 return info;
11997 }
11998
11999 return NULL;
12000}
12001
405f8e94
SS
12002/* Handle the qTMinFTPILen packet. Returns the minimum length of
12003 instruction on which a fast tracepoint may be placed. Returns -1
12004 if the packet is not supported, and 0 if the minimum instruction
12005 length is unknown. */
12006
12007static int
0e67620a 12008remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12009{
12010 struct remote_state *rs = get_remote_state ();
12011 char *reply;
12012
e886a173
PA
12013 /* If we're not debugging a process yet, the IPA can't be
12014 loaded. */
12015 if (!target_has_execution)
12016 return 0;
12017
12018 /* Make sure the remote is pointing at the right process. */
12019 set_general_process ();
12020
bba74b36 12021 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12022 putpkt (rs->buf);
12023 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12024 if (*reply == '\0')
12025 return -1;
12026 else
12027 {
12028 ULONGEST min_insn_len;
12029
12030 unpack_varlen_hex (reply, &min_insn_len);
12031
12032 return (int) min_insn_len;
12033 }
12034}
12035
f6f899bf 12036static void
4da384be 12037remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12038{
4082afcc 12039 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12040 {
12041 struct remote_state *rs = get_remote_state ();
12042 char *buf = rs->buf;
12043 char *endbuf = rs->buf + get_remote_packet_size ();
12044 enum packet_result result;
12045
12046 gdb_assert (val >= 0 || val == -1);
12047 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12048 /* Send -1 as literal "-1" to avoid host size dependency. */
12049 if (val < 0)
12050 {
12051 *buf++ = '-';
12052 buf += hexnumstr (buf, (ULONGEST) -val);
12053 }
12054 else
12055 buf += hexnumstr (buf, (ULONGEST) val);
12056
12057 putpkt (rs->buf);
12058 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12059 result = packet_ok (rs->buf,
12060 &remote_protocol_packets[PACKET_QTBuffer_size]);
12061
12062 if (result != PACKET_OK)
12063 warning (_("Bogus reply from target: %s"), rs->buf);
12064 }
12065}
12066
f196051f 12067static int
d9e68a2c
TT
12068remote_set_trace_notes (struct target_ops *self,
12069 const char *user, const char *notes,
ca623f82 12070 const char *stop_notes)
f196051f
SS
12071{
12072 struct remote_state *rs = get_remote_state ();
12073 char *reply;
12074 char *buf = rs->buf;
12075 char *endbuf = rs->buf + get_remote_packet_size ();
12076 int nbytes;
12077
12078 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12079 if (user)
12080 {
12081 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12082 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12083 buf += 2 * nbytes;
12084 *buf++ = ';';
12085 }
12086 if (notes)
12087 {
12088 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12089 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12090 buf += 2 * nbytes;
12091 *buf++ = ';';
12092 }
12093 if (stop_notes)
12094 {
12095 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12096 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12097 buf += 2 * nbytes;
12098 *buf++ = ';';
12099 }
12100 /* Ensure the buffer is terminated. */
12101 *buf = '\0';
12102
12103 putpkt (rs->buf);
12104 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12105 if (*reply == '\0')
12106 return 0;
12107
12108 if (strcmp (reply, "OK") != 0)
12109 error (_("Bogus reply from target: %s"), reply);
12110
12111 return 1;
12112}
12113
d1feda86 12114static int
2c152180 12115remote_use_agent (struct target_ops *self, int use)
d1feda86 12116{
4082afcc 12117 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12118 {
12119 struct remote_state *rs = get_remote_state ();
12120
12121 /* If the stub supports QAgent. */
bba74b36 12122 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12123 putpkt (rs->buf);
12124 getpkt (&rs->buf, &rs->buf_size, 0);
12125
12126 if (strcmp (rs->buf, "OK") == 0)
12127 {
12128 use_agent = use;
12129 return 1;
12130 }
12131 }
12132
12133 return 0;
12134}
12135
12136static int
fe38f897 12137remote_can_use_agent (struct target_ops *self)
d1feda86 12138{
4082afcc 12139 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12140}
12141
9accd112
MM
12142struct btrace_target_info
12143{
12144 /* The ptid of the traced thread. */
12145 ptid_t ptid;
f4abbc16
MM
12146
12147 /* The obtained branch trace configuration. */
12148 struct btrace_config conf;
9accd112
MM
12149};
12150
f4abbc16
MM
12151/* Reset our idea of our target's btrace configuration. */
12152
12153static void
12154remote_btrace_reset (void)
12155{
12156 struct remote_state *rs = get_remote_state ();
12157
12158 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12159}
12160
9accd112
MM
12161/* Check whether the target supports branch tracing. */
12162
12163static int
043c3577 12164remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12165{
4082afcc 12166 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12167 return 0;
4082afcc 12168 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12169 return 0;
12170
043c3577
MM
12171 switch (format)
12172 {
12173 case BTRACE_FORMAT_NONE:
12174 return 0;
12175
12176 case BTRACE_FORMAT_BTS:
12177 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12178
12179 case BTRACE_FORMAT_PT:
12180 /* The trace is decoded on the host. Even if our target supports it,
12181 we still need to have libipt to decode the trace. */
12182#if defined (HAVE_LIBIPT)
12183 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12184#else /* !defined (HAVE_LIBIPT) */
12185 return 0;
12186#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12187 }
12188
12189 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12190}
12191
f4abbc16
MM
12192/* Synchronize the configuration with the target. */
12193
12194static void
12195btrace_sync_conf (const struct btrace_config *conf)
12196{
d33501a5
MM
12197 struct packet_config *packet;
12198 struct remote_state *rs;
12199 char *buf, *pos, *endbuf;
12200
12201 rs = get_remote_state ();
12202 buf = rs->buf;
12203 endbuf = buf + get_remote_packet_size ();
12204
12205 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12206 if (packet_config_support (packet) == PACKET_ENABLE
12207 && conf->bts.size != rs->btrace_config.bts.size)
12208 {
12209 pos = buf;
12210 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12211 conf->bts.size);
12212
12213 putpkt (buf);
12214 getpkt (&buf, &rs->buf_size, 0);
12215
12216 if (packet_ok (buf, packet) == PACKET_ERROR)
12217 {
12218 if (buf[0] == 'E' && buf[1] == '.')
12219 error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
12220 else
12221 error (_("Failed to configure the BTS buffer size."));
12222 }
12223
12224 rs->btrace_config.bts.size = conf->bts.size;
12225 }
b20a6524
MM
12226
12227 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12228 if (packet_config_support (packet) == PACKET_ENABLE
12229 && conf->pt.size != rs->btrace_config.pt.size)
12230 {
12231 pos = buf;
12232 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12233 conf->pt.size);
12234
12235 putpkt (buf);
12236 getpkt (&buf, &rs->buf_size, 0);
12237
12238 if (packet_ok (buf, packet) == PACKET_ERROR)
12239 {
12240 if (buf[0] == 'E' && buf[1] == '.')
12241 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12242 else
12243 error (_("Failed to configure the trace buffer size."));
12244 }
12245
12246 rs->btrace_config.pt.size = conf->pt.size;
12247 }
f4abbc16
MM
12248}
12249
12250/* Read the current thread's btrace configuration from the target and
12251 store it into CONF. */
12252
12253static void
12254btrace_read_config (struct btrace_config *conf)
12255{
12256 char *xml;
12257
12258 xml = target_read_stralloc (&current_target,
b20a6524 12259 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12260 if (xml != NULL)
12261 {
12262 struct cleanup *cleanup;
12263
12264 cleanup = make_cleanup (xfree, xml);
12265 parse_xml_btrace_conf (conf, xml);
12266 do_cleanups (cleanup);
12267 }
12268}
12269
9accd112
MM
12270/* Enable branch tracing. */
12271
12272static struct btrace_target_info *
f4abbc16
MM
12273remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12274 const struct btrace_config *conf)
9accd112
MM
12275{
12276 struct btrace_target_info *tinfo = NULL;
b20a6524 12277 struct packet_config *packet = NULL;
9accd112
MM
12278 struct remote_state *rs = get_remote_state ();
12279 char *buf = rs->buf;
12280 char *endbuf = rs->buf + get_remote_packet_size ();
12281
b20a6524
MM
12282 switch (conf->format)
12283 {
12284 case BTRACE_FORMAT_BTS:
12285 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12286 break;
12287
12288 case BTRACE_FORMAT_PT:
12289 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12290 break;
12291 }
12292
12293 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12294 error (_("Target does not support branch tracing."));
12295
f4abbc16
MM
12296 btrace_sync_conf (conf);
12297
9accd112
MM
12298 set_general_thread (ptid);
12299
12300 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12301 putpkt (rs->buf);
12302 getpkt (&rs->buf, &rs->buf_size, 0);
12303
12304 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12305 {
12306 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12307 error (_("Could not enable branch tracing for %s: %s"),
12308 target_pid_to_str (ptid), rs->buf + 2);
12309 else
12310 error (_("Could not enable branch tracing for %s."),
12311 target_pid_to_str (ptid));
12312 }
12313
12314 tinfo = xzalloc (sizeof (*tinfo));
12315 tinfo->ptid = ptid;
12316
f4abbc16
MM
12317 /* If we fail to read the configuration, we lose some information, but the
12318 tracing itself is not impacted. */
492d29ea
PA
12319 TRY
12320 {
12321 btrace_read_config (&tinfo->conf);
12322 }
12323 CATCH (err, RETURN_MASK_ERROR)
12324 {
12325 if (err.message != NULL)
12326 warning ("%s", err.message);
12327 }
12328 END_CATCH
f4abbc16 12329
9accd112
MM
12330 return tinfo;
12331}
12332
12333/* Disable branch tracing. */
12334
12335static void
25e95349
TT
12336remote_disable_btrace (struct target_ops *self,
12337 struct btrace_target_info *tinfo)
9accd112
MM
12338{
12339 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12340 struct remote_state *rs = get_remote_state ();
12341 char *buf = rs->buf;
12342 char *endbuf = rs->buf + get_remote_packet_size ();
12343
4082afcc 12344 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12345 error (_("Target does not support branch tracing."));
12346
12347 set_general_thread (tinfo->ptid);
12348
12349 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12350 putpkt (rs->buf);
12351 getpkt (&rs->buf, &rs->buf_size, 0);
12352
12353 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12354 {
12355 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12356 error (_("Could not disable branch tracing for %s: %s"),
12357 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12358 else
12359 error (_("Could not disable branch tracing for %s."),
12360 target_pid_to_str (tinfo->ptid));
12361 }
12362
12363 xfree (tinfo);
12364}
12365
12366/* Teardown branch tracing. */
12367
12368static void
1777056d
TT
12369remote_teardown_btrace (struct target_ops *self,
12370 struct btrace_target_info *tinfo)
9accd112
MM
12371{
12372 /* We must not talk to the target during teardown. */
12373 xfree (tinfo);
12374}
12375
12376/* Read the branch trace. */
12377
969c39fb 12378static enum btrace_error
39c49f83 12379remote_read_btrace (struct target_ops *self,
734b0e4b 12380 struct btrace_data *btrace,
969c39fb 12381 struct btrace_target_info *tinfo,
9accd112
MM
12382 enum btrace_read_type type)
12383{
12384 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12385 struct remote_state *rs = get_remote_state ();
969c39fb 12386 struct cleanup *cleanup;
9accd112
MM
12387 const char *annex;
12388 char *xml;
12389
4082afcc 12390 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12391 error (_("Target does not support branch tracing."));
12392
12393#if !defined(HAVE_LIBEXPAT)
12394 error (_("Cannot process branch tracing result. XML parsing not supported."));
12395#endif
12396
12397 switch (type)
12398 {
864089d2 12399 case BTRACE_READ_ALL:
9accd112
MM
12400 annex = "all";
12401 break;
864089d2 12402 case BTRACE_READ_NEW:
9accd112
MM
12403 annex = "new";
12404 break;
969c39fb
MM
12405 case BTRACE_READ_DELTA:
12406 annex = "delta";
12407 break;
9accd112
MM
12408 default:
12409 internal_error (__FILE__, __LINE__,
12410 _("Bad branch tracing read type: %u."),
12411 (unsigned int) type);
12412 }
12413
12414 xml = target_read_stralloc (&current_target,
b20a6524 12415 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12416 if (xml == NULL)
12417 return BTRACE_ERR_UNKNOWN;
9accd112 12418
969c39fb 12419 cleanup = make_cleanup (xfree, xml);
734b0e4b 12420 parse_xml_btrace (btrace, xml);
969c39fb 12421 do_cleanups (cleanup);
9accd112 12422
969c39fb 12423 return BTRACE_ERR_NONE;
9accd112
MM
12424}
12425
f4abbc16
MM
12426static const struct btrace_config *
12427remote_btrace_conf (struct target_ops *self,
12428 const struct btrace_target_info *tinfo)
12429{
12430 return &tinfo->conf;
12431}
12432
ced63ec0 12433static int
5436ff03 12434remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12435{
4082afcc
PA
12436 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12437 == PACKET_ENABLE);
ced63ec0
GB
12438}
12439
9dd130a0
TT
12440/* Implementation of to_load. */
12441
12442static void
9cbe5fff 12443remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12444{
12445 generic_load (name, from_tty);
12446}
12447
c78fa86a
GB
12448/* Accepts an integer PID; returns a string representing a file that
12449 can be opened on the remote side to get the symbols for the child
12450 process. Returns NULL if the operation is not supported. */
12451
12452static char *
12453remote_pid_to_exec_file (struct target_ops *self, int pid)
12454{
12455 static char *filename = NULL;
835205d0
GB
12456 struct inferior *inf;
12457 char *annex = NULL;
c78fa86a
GB
12458
12459 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12460 return NULL;
12461
12462 if (filename != NULL)
12463 xfree (filename);
12464
835205d0
GB
12465 inf = find_inferior_pid (pid);
12466 if (inf == NULL)
12467 internal_error (__FILE__, __LINE__,
12468 _("not currently attached to process %d"), pid);
12469
12470 if (!inf->fake_pid_p)
12471 {
12472 const int annex_size = 9;
12473
12474 annex = alloca (annex_size);
12475 xsnprintf (annex, annex_size, "%x", pid);
12476 }
12477
c78fa86a
GB
12478 filename = target_read_stralloc (&current_target,
12479 TARGET_OBJECT_EXEC_FILE, annex);
12480
12481 return filename;
12482}
12483
c906108c 12484static void
fba45db2 12485init_remote_ops (void)
c906108c 12486{
c5aa993b 12487 remote_ops.to_shortname = "remote";
c906108c 12488 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 12489 remote_ops.to_doc =
c906108c 12490 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
12491Specify the serial device it is connected to\n\
12492(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
12493 remote_ops.to_open = remote_open;
12494 remote_ops.to_close = remote_close;
c906108c 12495 remote_ops.to_detach = remote_detach;
6ad8ae5c 12496 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 12497 remote_ops.to_resume = remote_resume;
c906108c
SS
12498 remote_ops.to_wait = remote_wait;
12499 remote_ops.to_fetch_registers = remote_fetch_registers;
12500 remote_ops.to_store_registers = remote_store_registers;
12501 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 12502 remote_ops.to_files_info = remote_files_info;
c906108c
SS
12503 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12504 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
12505 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12506 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12507 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12508 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
12509 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12510 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
12511 remote_ops.to_watchpoint_addr_within_range =
12512 remote_watchpoint_addr_within_range;
3c3bea1c
GS
12513 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12514 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12515 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
12516 remote_ops.to_region_ok_for_hw_watchpoint
12517 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
12518 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12519 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 12520 remote_ops.to_kill = remote_kill;
9dd130a0 12521 remote_ops.to_load = remote_load;
c906108c 12522 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 12523 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 12524 remote_ops.to_program_signals = remote_program_signals;
c906108c 12525 remote_ops.to_thread_alive = remote_thread_alive;
e8032dde 12526 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 12527 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 12528 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 12529 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 12530 remote_ops.to_stop = remote_stop;
bfedc46a 12531 remote_ops.to_interrupt = remote_interrupt;
4b8a223f 12532 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 12533 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 12534 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 12535 remote_ops.to_log_command = serial_log_command;
38691318 12536 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 12537 remote_ops.to_stratum = process_stratum;
c35b1492
PA
12538 remote_ops.to_has_all_memory = default_child_has_all_memory;
12539 remote_ops.to_has_memory = default_child_has_memory;
12540 remote_ops.to_has_stack = default_child_has_stack;
12541 remote_ops.to_has_registers = default_child_has_registers;
12542 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 12543 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 12544 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 12545 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 12546 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
12547 remote_ops.to_flash_erase = remote_flash_erase;
12548 remote_ops.to_flash_done = remote_flash_done;
29709017 12549 remote_ops.to_read_description = remote_read_description;
08388c79 12550 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
12551 remote_ops.to_can_async_p = remote_can_async_p;
12552 remote_ops.to_is_async_p = remote_is_async_p;
12553 remote_ops.to_async = remote_async;
75c99385
PA
12554 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12555 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 12556 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 12557 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
12558 remote_ops.to_supports_disable_randomization
12559 = remote_supports_disable_randomization;
4bd7dc42 12560 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
12561 remote_ops.to_fileio_open = remote_hostio_open;
12562 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12563 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 12564 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
12565 remote_ops.to_fileio_close = remote_hostio_close;
12566 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 12567 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 12568 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 12569 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 12570 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 12571 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
12572 remote_ops.to_trace_init = remote_trace_init;
12573 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 12574 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
12575 remote_ops.to_download_trace_state_variable
12576 = remote_download_trace_state_variable;
d248b706
KY
12577 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12578 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
12579 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12580 remote_ops.to_trace_start = remote_trace_start;
12581 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 12582 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
12583 remote_ops.to_trace_stop = remote_trace_stop;
12584 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
12585 remote_ops.to_get_trace_state_variable_value
12586 = remote_get_trace_state_variable_value;
00bf0b85
SS
12587 remote_ops.to_save_trace_data = remote_save_trace_data;
12588 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
12589 remote_ops.to_upload_trace_state_variables
12590 = remote_upload_trace_state_variables;
00bf0b85 12591 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 12592 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 12593 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 12594 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 12595 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 12596 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 12597 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 12598 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 12599 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 12600 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
12601 remote_ops.to_static_tracepoint_marker_at
12602 = remote_static_tracepoint_marker_at;
12603 remote_ops.to_static_tracepoint_markers_by_strid
12604 = remote_static_tracepoint_markers_by_strid;
b3b9301e 12605 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
12606 remote_ops.to_use_agent = remote_use_agent;
12607 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
12608 remote_ops.to_supports_btrace = remote_supports_btrace;
12609 remote_ops.to_enable_btrace = remote_enable_btrace;
12610 remote_ops.to_disable_btrace = remote_disable_btrace;
12611 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12612 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 12613 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
12614 remote_ops.to_augmented_libraries_svr4_read =
12615 remote_augmented_libraries_svr4_read;
c906108c
SS
12616}
12617
12618/* Set up the extended remote vector by making a copy of the standard
12619 remote vector and adding to it. */
12620
12621static void
fba45db2 12622init_extended_remote_ops (void)
c906108c
SS
12623{
12624 extended_remote_ops = remote_ops;
12625
0f71a2f6 12626 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 12627 extended_remote_ops.to_longname =
c906108c 12628 "Extended remote serial target in gdb-specific protocol";
c5aa993b 12629 extended_remote_ops.to_doc =
c906108c 12630 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
12631Specify the serial device it is connected to (e.g. /dev/ttya).";
12632 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
12633 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12634 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
12635 extended_remote_ops.to_detach = extended_remote_detach;
12636 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 12637 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 12638 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
12639 extended_remote_ops.to_supports_disable_randomization
12640 = extended_remote_supports_disable_randomization;
de0d863e 12641 extended_remote_ops.to_follow_fork = remote_follow_fork;
cbb8991c
DB
12642 extended_remote_ops.to_insert_fork_catchpoint
12643 = remote_insert_fork_catchpoint;
12644 extended_remote_ops.to_remove_fork_catchpoint
12645 = remote_remove_fork_catchpoint;
12646 extended_remote_ops.to_insert_vfork_catchpoint
12647 = remote_insert_vfork_catchpoint;
12648 extended_remote_ops.to_remove_vfork_catchpoint
12649 = remote_remove_vfork_catchpoint;
0f71a2f6
JM
12650}
12651
6426a772 12652static int
6a109b6b 12653remote_can_async_p (struct target_ops *ops)
6426a772 12654{
5d93a237
TT
12655 struct remote_state *rs = get_remote_state ();
12656
c6ebd6cf 12657 if (!target_async_permitted)
75c99385
PA
12658 /* We only enable async when the user specifically asks for it. */
12659 return 0;
12660
23860348 12661 /* We're async whenever the serial device is. */
5d93a237 12662 return serial_can_async_p (rs->remote_desc);
6426a772
JM
12663}
12664
12665static int
6a109b6b 12666remote_is_async_p (struct target_ops *ops)
6426a772 12667{
5d93a237
TT
12668 struct remote_state *rs = get_remote_state ();
12669
c6ebd6cf 12670 if (!target_async_permitted)
75c99385
PA
12671 /* We only enable async when the user specifically asks for it. */
12672 return 0;
12673
23860348 12674 /* We're async whenever the serial device is. */
5d93a237 12675 return serial_is_async_p (rs->remote_desc);
6426a772
JM
12676}
12677
2acceee2
JM
12678/* Pass the SERIAL event on and up to the client. One day this code
12679 will be able to delay notifying the client of an event until the
23860348 12680 point where an entire packet has been received. */
2acceee2 12681
2acceee2
JM
12682static serial_event_ftype remote_async_serial_handler;
12683
6426a772 12684static void
819cc324 12685remote_async_serial_handler (struct serial *scb, void *context)
6426a772 12686{
88b496c3
TT
12687 struct remote_state *rs = context;
12688
2acceee2
JM
12689 /* Don't propogate error information up to the client. Instead let
12690 the client find out about the error by querying the target. */
6a3753b3 12691 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
12692}
12693
74531fed
PA
12694static void
12695remote_async_inferior_event_handler (gdb_client_data data)
12696{
12697 inferior_event_handler (INF_REG_EVENT, NULL);
12698}
12699
2acceee2 12700static void
6a3753b3 12701remote_async (struct target_ops *ops, int enable)
2acceee2 12702{
5d93a237
TT
12703 struct remote_state *rs = get_remote_state ();
12704
6a3753b3 12705 if (enable)
2acceee2 12706 {
88b496c3 12707 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
12708
12709 /* If there are pending events in the stop reply queue tell the
12710 event loop to process them. */
12711 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12712 mark_async_event_handler (remote_async_inferior_event_token);
2acceee2
JM
12713 }
12714 else
b7d2e916
PA
12715 {
12716 serial_async (rs->remote_desc, NULL, NULL);
12717 clear_async_event_handler (remote_async_inferior_event_token);
12718 }
6426a772
JM
12719}
12720
5a2468f5 12721static void
c2d11a7d 12722set_remote_cmd (char *args, int from_tty)
5a2468f5 12723{
635c7e8a 12724 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
12725}
12726
d471ea57
AC
12727static void
12728show_remote_cmd (char *args, int from_tty)
12729{
37a105a1 12730 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 12731 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
12732 struct cleanup *showlist_chain;
12733 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 12734 struct ui_out *uiout = current_uiout;
37a105a1
DJ
12735
12736 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12737 for (; list != NULL; list = list->next)
12738 if (strcmp (list->name, "Z-packet") == 0)
12739 continue;
427c3a89
DJ
12740 else if (list->type == not_set_cmd)
12741 /* Alias commands are exactly like the original, except they
12742 don't have the normal type. */
12743 continue;
12744 else
37a105a1
DJ
12745 {
12746 struct cleanup *option_chain
12747 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 12748
37a105a1
DJ
12749 ui_out_field_string (uiout, "name", list->name);
12750 ui_out_text (uiout, ": ");
427c3a89 12751 if (list->type == show_cmd)
5b9afe8a 12752 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
12753 else
12754 cmd_func (list, NULL, from_tty);
37a105a1
DJ
12755 /* Close the tuple. */
12756 do_cleanups (option_chain);
12757 }
427c3a89
DJ
12758
12759 /* Close the tuple. */
12760 do_cleanups (showlist_chain);
d471ea57 12761}
5a2468f5 12762
0f71a2f6 12763
23860348 12764/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
12765static void
12766remote_new_objfile (struct objfile *objfile)
12767{
5d93a237
TT
12768 struct remote_state *rs = get_remote_state ();
12769
12770 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 12771 remote_check_symbols ();
dc8acb97
MS
12772}
12773
00bf0b85
SS
12774/* Pull all the tracepoints defined on the target and create local
12775 data structures representing them. We don't want to create real
12776 tracepoints yet, we don't want to mess up the user's existing
12777 collection. */
12778
12779static int
ab6617cc 12780remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 12781{
00bf0b85
SS
12782 struct remote_state *rs = get_remote_state ();
12783 char *p;
d5551862 12784
00bf0b85
SS
12785 /* Ask for a first packet of tracepoint definition. */
12786 putpkt ("qTfP");
12787 getpkt (&rs->buf, &rs->buf_size, 0);
12788 p = rs->buf;
12789 while (*p && *p != 'l')
d5551862 12790 {
00bf0b85
SS
12791 parse_tracepoint_definition (p, utpp);
12792 /* Ask for another packet of tracepoint definition. */
12793 putpkt ("qTsP");
12794 getpkt (&rs->buf, &rs->buf_size, 0);
12795 p = rs->buf;
d5551862 12796 }
00bf0b85 12797 return 0;
d5551862
SS
12798}
12799
00bf0b85 12800static int
181e3713
TT
12801remote_upload_trace_state_variables (struct target_ops *self,
12802 struct uploaded_tsv **utsvp)
d5551862 12803{
00bf0b85 12804 struct remote_state *rs = get_remote_state ();
d5551862 12805 char *p;
d5551862 12806
00bf0b85
SS
12807 /* Ask for a first packet of variable definition. */
12808 putpkt ("qTfV");
d5551862
SS
12809 getpkt (&rs->buf, &rs->buf_size, 0);
12810 p = rs->buf;
00bf0b85 12811 while (*p && *p != 'l')
d5551862 12812 {
00bf0b85
SS
12813 parse_tsv_definition (p, utsvp);
12814 /* Ask for another packet of variable definition. */
12815 putpkt ("qTsV");
d5551862
SS
12816 getpkt (&rs->buf, &rs->buf_size, 0);
12817 p = rs->buf;
12818 }
00bf0b85 12819 return 0;
d5551862
SS
12820}
12821
c1e36e3e
PA
12822/* The "set/show range-stepping" show hook. */
12823
12824static void
12825show_range_stepping (struct ui_file *file, int from_tty,
12826 struct cmd_list_element *c,
12827 const char *value)
12828{
12829 fprintf_filtered (file,
12830 _("Debugger's willingness to use range stepping "
12831 "is %s.\n"), value);
12832}
12833
12834/* The "set/show range-stepping" set hook. */
12835
12836static void
12837set_range_stepping (char *ignore_args, int from_tty,
12838 struct cmd_list_element *c)
12839{
5d93a237
TT
12840 struct remote_state *rs = get_remote_state ();
12841
c1e36e3e
PA
12842 /* Whene enabling, check whether range stepping is actually
12843 supported by the target, and warn if not. */
12844 if (use_range_stepping)
12845 {
5d93a237 12846 if (rs->remote_desc != NULL)
c1e36e3e 12847 {
4082afcc 12848 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
12849 remote_vcont_probe (rs);
12850
4082afcc 12851 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
12852 && rs->supports_vCont.r)
12853 return;
12854 }
12855
12856 warning (_("Range stepping is not supported by the current target"));
12857 }
12858}
12859
c906108c 12860void
fba45db2 12861_initialize_remote (void)
c906108c 12862{
ea9c271d 12863 struct remote_state *rs;
9a7071a8 12864 struct cmd_list_element *cmd;
6f937416 12865 const char *cmd_name;
ea9c271d 12866
0f71a2f6 12867 /* architecture specific data */
2bc416ba 12868 remote_gdbarch_data_handle =
23860348 12869 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
12870 remote_g_packet_data_handle =
12871 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 12872
ea9c271d
DJ
12873 /* Initialize the per-target state. At the moment there is only one
12874 of these, not one per target. Only one target is active at a
cf792862
TT
12875 time. */
12876 remote_state = new_remote_state ();
ea9c271d 12877
c906108c
SS
12878 init_remote_ops ();
12879 add_target (&remote_ops);
12880
12881 init_extended_remote_ops ();
12882 add_target (&extended_remote_ops);
cce74817 12883
dc8acb97 12884 /* Hook into new objfile notification. */
06d3b283 12885 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
12886 /* We're no longer interested in notification events of an inferior
12887 when it exits. */
12888 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 12889
b803fb0f 12890 /* Set up signal handlers. */
934b9bac 12891 async_sigint_remote_token =
b803fb0f 12892 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 12893 async_sigint_remote_twice_token =
6d549500 12894 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 12895
c906108c
SS
12896#if 0
12897 init_remote_threadtests ();
12898#endif
12899
722247f1 12900 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 12901 /* set/show remote ... */
d471ea57 12902
1bedd215 12903 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
12904Remote protocol specific variables\n\
12905Configure various remote-protocol specific variables such as\n\
1bedd215 12906the packets being used"),
cff3e48b 12907 &remote_set_cmdlist, "set remote ",
23860348 12908 0 /* allow-unknown */, &setlist);
1bedd215 12909 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
12910Remote protocol specific variables\n\
12911Configure various remote-protocol specific variables such as\n\
1bedd215 12912the packets being used"),
cff3e48b 12913 &remote_show_cmdlist, "show remote ",
23860348 12914 0 /* allow-unknown */, &showlist);
5a2468f5 12915
1a966eab
AC
12916 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12917Compare section data on target to the exec file.\n\
95cf3b38
DT
12918Argument is a single section name (default: all loaded sections).\n\
12919To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
12920 &cmdlist);
12921
1a966eab
AC
12922 add_cmd ("packet", class_maintenance, packet_command, _("\
12923Send an arbitrary packet to a remote target.\n\
c906108c
SS
12924 maintenance packet TEXT\n\
12925If GDB is talking to an inferior via the GDB serial protocol, then\n\
12926this command sends the string TEXT to the inferior, and displays the\n\
12927response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 12928terminating `#' character and checksum."),
c906108c
SS
12929 &maintenancelist);
12930
7915a72c
AC
12931 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12932Set whether to send break if interrupted."), _("\
12933Show whether to send break if interrupted."), _("\
12934If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 12935 set_remotebreak, show_remotebreak,
e707bbc2 12936 &setlist, &showlist);
9a7071a8
JB
12937 cmd_name = "remotebreak";
12938 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12939 deprecate_cmd (cmd, "set remote interrupt-sequence");
12940 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12941 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12942 deprecate_cmd (cmd, "show remote interrupt-sequence");
12943
12944 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
12945 interrupt_sequence_modes, &interrupt_sequence_mode,
12946 _("\
9a7071a8
JB
12947Set interrupt sequence to remote target."), _("\
12948Show interrupt sequence to remote target."), _("\
12949Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12950 NULL, show_interrupt_sequence,
12951 &remote_set_cmdlist,
12952 &remote_show_cmdlist);
12953
12954 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12955 &interrupt_on_connect, _("\
12956Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12957Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12958If set, interrupt sequence is sent to remote target."),
12959 NULL, NULL,
12960 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 12961
23860348 12962 /* Install commands for configuring memory read/write packets. */
11cf8741 12963
1a966eab
AC
12964 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12965Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 12966 &setlist);
1a966eab
AC
12967 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12968Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
12969 &showlist);
12970 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
12971 set_memory_write_packet_size, _("\
12972Set the maximum number of bytes per memory-write packet.\n\
12973Specify the number of bytes in a packet or 0 (zero) for the\n\
12974default packet size. The actual limit is further reduced\n\
12975dependent on the target. Specify ``fixed'' to disable the\n\
12976further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12977 &remote_set_cmdlist);
12978 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
12979 set_memory_read_packet_size, _("\
12980Set the maximum number of bytes per memory-read packet.\n\
12981Specify the number of bytes in a packet or 0 (zero) for the\n\
12982default packet size. The actual limit is further reduced\n\
12983dependent on the target. Specify ``fixed'' to disable the\n\
12984further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
12985 &remote_set_cmdlist);
12986 add_cmd ("memory-write-packet-size", no_class,
12987 show_memory_write_packet_size,
1a966eab 12988 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
12989 &remote_show_cmdlist);
12990 add_cmd ("memory-read-packet-size", no_class,
12991 show_memory_read_packet_size,
1a966eab 12992 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 12993 &remote_show_cmdlist);
c906108c 12994
b3f42336 12995 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
12996 &remote_hw_watchpoint_limit, _("\
12997Set the maximum number of target hardware watchpoints."), _("\
12998Show the maximum number of target hardware watchpoints."), _("\
12999Specify a negative limit for unlimited."),
3e43a32a
MS
13000 NULL, NULL, /* FIXME: i18n: The maximum
13001 number of target hardware
13002 watchpoints is %s. */
b3f42336 13003 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13004 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13005 &remote_hw_watchpoint_length_limit, _("\
13006Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13007Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13008Specify a negative limit for unlimited."),
13009 NULL, NULL, /* FIXME: i18n: The maximum
13010 length (in bytes) of a target
13011 hardware watchpoint is %s. */
13012 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13013 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13014 &remote_hw_breakpoint_limit, _("\
13015Set the maximum number of target hardware breakpoints."), _("\
13016Show the maximum number of target hardware breakpoints."), _("\
13017Specify a negative limit for unlimited."),
3e43a32a
MS
13018 NULL, NULL, /* FIXME: i18n: The maximum
13019 number of target hardware
13020 breakpoints is %s. */
b3f42336 13021 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13022
1b493192
PA
13023 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13024 &remote_address_size, _("\
4d28ad1e
AC
13025Set the maximum size of the address (in bits) in a memory packet."), _("\
13026Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13027 NULL,
13028 NULL, /* FIXME: i18n: */
13029 &setlist, &showlist);
c906108c 13030
ca4f7f8b
PA
13031 init_all_packet_configs ();
13032
444abaca 13033 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13034 "X", "binary-download", 1);
0f71a2f6 13035
444abaca 13036 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13037 "vCont", "verbose-resume", 0);
506fb367 13038
89be2091
DJ
13039 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13040 "QPassSignals", "pass-signals", 0);
13041
9b224c5e
PA
13042 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13043 "QProgramSignals", "program-signals", 0);
13044
444abaca 13045 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13046 "qSymbol", "symbol-lookup", 0);
dc8acb97 13047
444abaca 13048 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13049 "P", "set-register", 1);
d471ea57 13050
444abaca 13051 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13052 "p", "fetch-register", 1);
b96ec7ac 13053
444abaca 13054 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13055 "Z0", "software-breakpoint", 0);
d471ea57 13056
444abaca 13057 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13058 "Z1", "hardware-breakpoint", 0);
d471ea57 13059
444abaca 13060 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13061 "Z2", "write-watchpoint", 0);
d471ea57 13062
444abaca 13063 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13064 "Z3", "read-watchpoint", 0);
d471ea57 13065
444abaca 13066 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13067 "Z4", "access-watchpoint", 0);
d471ea57 13068
0876f84a
DJ
13069 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13070 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13071
c78fa86a
GB
13072 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13073 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13074
23181151
DJ
13075 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13076 "qXfer:features:read", "target-features", 0);
13077
cfa9d6d9
DJ
13078 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13079 "qXfer:libraries:read", "library-info", 0);
13080
2268b414
JK
13081 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13082 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13083
fd79ecee
DJ
13084 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13085 "qXfer:memory-map:read", "memory-map", 0);
13086
0e7f50da
UW
13087 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13088 "qXfer:spu:read", "read-spu-object", 0);
13089
13090 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13091 "qXfer:spu:write", "write-spu-object", 0);
13092
07e059b5
VP
13093 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13094 "qXfer:osdata:read", "osdata", 0);
13095
dc146f7c
VP
13096 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13097 "qXfer:threads:read", "threads", 0);
13098
4aa995e1
PA
13099 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13100 "qXfer:siginfo:read", "read-siginfo-object", 0);
13101
13102 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13103 "qXfer:siginfo:write", "write-siginfo-object", 0);
13104
b3b9301e
PA
13105 add_packet_config_cmd
13106 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13107 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13108
169081d0
TG
13109 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13110 "qXfer:uib:read", "unwind-info-block", 0);
13111
444abaca 13112 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13113 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13114 0);
13115
711e434b
PM
13116 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13117 "qGetTIBAddr", "get-thread-information-block-address",
13118 0);
13119
40ab02ce
MS
13120 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13121 "bc", "reverse-continue", 0);
13122
13123 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13124 "bs", "reverse-step", 0);
13125
be2a5f71
DJ
13126 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13127 "qSupported", "supported-packets", 0);
13128
08388c79
DE
13129 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13130 "qSearch:memory", "search-memory", 0);
13131
bd3eecc3
PA
13132 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13133 "qTStatus", "trace-status", 0);
13134
15a201c8
GB
13135 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13136 "vFile:setfs", "hostio-setfs", 0);
13137
a6b151f1
DJ
13138 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13139 "vFile:open", "hostio-open", 0);
13140
13141 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13142 "vFile:pread", "hostio-pread", 0);
13143
13144 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13145 "vFile:pwrite", "hostio-pwrite", 0);
13146
13147 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13148 "vFile:close", "hostio-close", 0);
13149
13150 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13151 "vFile:unlink", "hostio-unlink", 0);
13152
b9e7b9c3
UW
13153 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13154 "vFile:readlink", "hostio-readlink", 0);
13155
0a93529c
GB
13156 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13157 "vFile:fstat", "hostio-fstat", 0);
13158
2d717e4f
DJ
13159 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13160 "vAttach", "attach", 0);
13161
13162 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13163 "vRun", "run", 0);
13164
a6f3e723
SL
13165 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13166 "QStartNoAckMode", "noack", 0);
13167
82f73884
PA
13168 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13169 "vKill", "kill", 0);
13170
0b16c5cf
PA
13171 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13172 "qAttached", "query-attached", 0);
13173
782b2b07 13174 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13175 "ConditionalTracepoints",
13176 "conditional-tracepoints", 0);
3788aec7
LM
13177
13178 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13179 "ConditionalBreakpoints",
13180 "conditional-breakpoints", 0);
13181
d3ce09f5
SS
13182 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13183 "BreakpointCommands",
13184 "breakpoint-commands", 0);
13185
7a697b8d
SS
13186 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13187 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13188
409873ef
SS
13189 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13190 "TracepointSource", "TracepointSource", 0);
13191
d914c394
SS
13192 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13193 "QAllow", "allow", 0);
13194
0fb4aa4b
PA
13195 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13196 "StaticTracepoints", "static-tracepoints", 0);
13197
1e4d1764
YQ
13198 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13199 "InstallInTrace", "install-in-trace", 0);
13200
0fb4aa4b
PA
13201 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13202 "qXfer:statictrace:read", "read-sdata-object", 0);
13203
78d85199
YQ
13204 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13205 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13206
03583c20
UW
13207 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13208 "QDisableRandomization", "disable-randomization", 0);
13209
d1feda86
YQ
13210 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13211 "QAgent", "agent", 0);
13212
f6f899bf
HAQ
13213 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13214 "QTBuffer:size", "trace-buffer-size", 0);
13215
9accd112
MM
13216 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13217 "Qbtrace:off", "disable-btrace", 0);
13218
13219 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13220 "Qbtrace:bts", "enable-btrace-bts", 0);
13221
13222 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13223 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13224
13225 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13226 "qXfer:btrace", "read-btrace", 0);
13227
f4abbc16
MM
13228 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13229 "qXfer:btrace-conf", "read-btrace-conf", 0);
13230
d33501a5
MM
13231 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13232 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13233
f7e6eed5
PA
13234 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13235 "swbreak-feature", "swbreak-feature", 0);
13236
13237 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13238 "hwbreak-feature", "hwbreak-feature", 0);
13239
89245bc0
DB
13240 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13241 "fork-event-feature", "fork-event-feature", 0);
13242
13243 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13244 "vfork-event-feature", "vfork-event-feature", 0);
13245
b20a6524
MM
13246 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13247 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13248
0b736949
DB
13249 /* Assert that we've registered "set remote foo-packet" commands
13250 for all packet configs. */
ca4f7f8b
PA
13251 {
13252 int i;
13253
13254 for (i = 0; i < PACKET_MAX; i++)
13255 {
13256 /* Ideally all configs would have a command associated. Some
13257 still don't though. */
13258 int excepted;
13259
13260 switch (i)
13261 {
13262 case PACKET_QNonStop:
13263 case PACKET_multiprocess_feature:
13264 case PACKET_EnableDisableTracepoints_feature:
13265 case PACKET_tracenz_feature:
13266 case PACKET_DisconnectedTracing_feature:
13267 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13268 case PACKET_qCRC:
13269 /* Additions to this list need to be well justified:
13270 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13271 excepted = 1;
13272 break;
13273 default:
13274 excepted = 0;
13275 break;
13276 }
13277
13278 /* This catches both forgetting to add a config command, and
13279 forgetting to remove a packet from the exception list. */
13280 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13281 }
13282 }
13283
37a105a1
DJ
13284 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13285 Z sub-packet has its own set and show commands, but users may
13286 have sets to this variable in their .gdbinit files (or in their
13287 documentation). */
e9e68a56 13288 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13289 &remote_Z_packet_detect, _("\
13290Set use of remote protocol `Z' packets"), _("\
13291Show use of remote protocol `Z' packets "), _("\
3b64bf98 13292When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13293packets."),
e9e68a56 13294 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13295 show_remote_protocol_Z_packet_cmd,
13296 /* FIXME: i18n: Use of remote protocol
13297 `Z' packets is %s. */
e9e68a56 13298 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13299
a6b151f1
DJ
13300 add_prefix_cmd ("remote", class_files, remote_command, _("\
13301Manipulate files on the remote system\n\
13302Transfer files to and from the remote target system."),
13303 &remote_cmdlist, "remote ",
13304 0 /* allow-unknown */, &cmdlist);
13305
13306 add_cmd ("put", class_files, remote_put_command,
13307 _("Copy a local file to the remote system."),
13308 &remote_cmdlist);
13309
13310 add_cmd ("get", class_files, remote_get_command,
13311 _("Copy a remote file to the local system."),
13312 &remote_cmdlist);
13313
13314 add_cmd ("delete", class_files, remote_delete_command,
13315 _("Delete a remote file."),
13316 &remote_cmdlist);
13317
2d717e4f
DJ
13318 remote_exec_file = xstrdup ("");
13319 add_setshow_string_noescape_cmd ("exec-file", class_files,
13320 &remote_exec_file, _("\
13321Set the remote pathname for \"run\""), _("\
13322Show the remote pathname for \"run\""), NULL, NULL, NULL,
13323 &remote_set_cmdlist, &remote_show_cmdlist);
13324
c1e36e3e
PA
13325 add_setshow_boolean_cmd ("range-stepping", class_run,
13326 &use_range_stepping, _("\
13327Enable or disable range stepping."), _("\
13328Show whether target-assisted range stepping is enabled."), _("\
13329If on, and the target supports it, when stepping a source line, GDB\n\
13330tells the target to step the corresponding range of addresses itself instead\n\
13331of issuing multiple single-steps. This speeds up source level\n\
13332stepping. If off, GDB always issues single-steps, even if range\n\
13333stepping is supported by the target. The default is on."),
13334 set_range_stepping,
13335 show_range_stepping,
13336 &setlist,
13337 &showlist);
13338
449092f6
CV
13339 /* Eventually initialize fileio. See fileio.c */
13340 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13341
ba348170 13342 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13343 special ptids with it set to != 0. */
ba348170
PA
13344 magic_null_ptid = ptid_build (42000, -1, 1);
13345 not_sent_ptid = ptid_build (42000, -2, 1);
13346 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13347
13348 target_buf_size = 2048;
13349 target_buf = xmalloc (target_buf_size);
c906108c 13350}
10760264 13351
This page took 3.973249 seconds and 4 git commands to generate.