Add "ld -r" tests for PR ld/15323
[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{
17d8546e 603 gdb_assert (target_gdbarch () != NULL);
f5656ead 604 return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
d01949b6
AC
605}
606
0b83947e
DJ
607/* Fetch the global remote target state. */
608
609static struct remote_state *
610get_remote_state (void)
611{
612 /* Make sure that the remote architecture state has been
613 initialized, because doing so might reallocate rs->buf. Any
614 function which calls getpkt also needs to be mindful of changes
615 to rs->buf, but this call limits the number of places which run
616 into trouble. */
617 get_remote_arch_state ();
618
619 return get_remote_state_raw ();
620}
621
74ca34ce
DJ
622static int
623compare_pnums (const void *lhs_, const void *rhs_)
624{
625 const struct packet_reg * const *lhs = lhs_;
626 const struct packet_reg * const *rhs = rhs_;
627
628 if ((*lhs)->pnum < (*rhs)->pnum)
629 return -1;
630 else if ((*lhs)->pnum == (*rhs)->pnum)
631 return 0;
632 else
633 return 1;
634}
635
c21236dc
PA
636static int
637map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
d01949b6 638{
74ca34ce 639 int regnum, num_remote_regs, offset;
74ca34ce 640 struct packet_reg **remote_regs;
ea9c271d 641
4a22f64d 642 for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
ad10f812 643 {
c21236dc 644 struct packet_reg *r = &regs[regnum];
baef701f 645
4a22f64d 646 if (register_size (gdbarch, regnum) == 0)
baef701f
DJ
647 /* Do not try to fetch zero-sized (placeholder) registers. */
648 r->pnum = -1;
649 else
650 r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
651
b323314b 652 r->regnum = regnum;
74ca34ce
DJ
653 }
654
655 /* Define the g/G packet format as the contents of each register
656 with a remote protocol number, in order of ascending protocol
657 number. */
658
4a22f64d 659 remote_regs = alloca (gdbarch_num_regs (gdbarch)
c21236dc 660 * sizeof (struct packet_reg *));
f57d151a 661 for (num_remote_regs = 0, regnum = 0;
4a22f64d 662 regnum < gdbarch_num_regs (gdbarch);
f57d151a 663 regnum++)
c21236dc
PA
664 if (regs[regnum].pnum != -1)
665 remote_regs[num_remote_regs++] = &regs[regnum];
7d58c67d 666
74ca34ce
DJ
667 qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
668 compare_pnums);
669
670 for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
671 {
672 remote_regs[regnum]->in_g_packet = 1;
673 remote_regs[regnum]->offset = offset;
4a22f64d 674 offset += register_size (gdbarch, remote_regs[regnum]->regnum);
ad10f812
AC
675 }
676
c21236dc
PA
677 return offset;
678}
679
680/* Given the architecture described by GDBARCH, return the remote
681 protocol register's number and the register's offset in the g/G
682 packets of GDB register REGNUM, in PNUM and POFFSET respectively.
683 If the target does not have a mapping for REGNUM, return false,
684 otherwise, return true. */
685
686int
687remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
688 int *pnum, int *poffset)
689{
690 int sizeof_g_packet;
691 struct packet_reg *regs;
692 struct cleanup *old_chain;
693
694 gdb_assert (regnum < gdbarch_num_regs (gdbarch));
695
696 regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
697 old_chain = make_cleanup (xfree, regs);
698
699 sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
700
701 *pnum = regs[regnum].pnum;
702 *poffset = regs[regnum].offset;
703
704 do_cleanups (old_chain);
705
706 return *pnum != -1;
707}
708
709static void *
710init_remote_state (struct gdbarch *gdbarch)
711{
712 struct remote_state *rs = get_remote_state_raw ();
713 struct remote_arch_state *rsa;
714
715 rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
716
717 /* Use the architecture to build a regnum<->pnum table, which will be
718 1:1 unless a feature set specifies otherwise. */
719 rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
720 gdbarch_num_regs (gdbarch),
721 struct packet_reg);
722
74ca34ce
DJ
723 /* Record the maximum possible size of the g packet - it may turn out
724 to be smaller. */
c21236dc 725 rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
74ca34ce 726
0df8b418 727 /* Default maximum number of characters in a packet body. Many
d01949b6
AC
728 remote stubs have a hardwired buffer size of 400 bytes
729 (c.f. BUFMAX in m68k-stub.c and i386-stub.c). BUFMAX-1 is used
730 as the maximum packet-size to ensure that the packet and an extra
731 NUL character can always fit in the buffer. This stops GDB
732 trashing stubs that try to squeeze an extra NUL into what is
ea9c271d
DJ
733 already a full buffer (As of 1999-12-04 that was most stubs). */
734 rsa->remote_packet_size = 400 - 1;
d01949b6 735
ea9c271d
DJ
736 /* This one is filled in when a ``g'' packet is received. */
737 rsa->actual_register_packet_size = 0;
738
739 /* Should rsa->sizeof_g_packet needs more space than the
0df8b418
MS
740 default, adjust the size accordingly. Remember that each byte is
741 encoded as two characters. 32 is the overhead for the packet
742 header / footer. NOTE: cagney/1999-10-26: I suspect that 8
d01949b6 743 (``$NN:G...#NN'') is a better guess, the below has been padded a
23860348 744 little. */
ea9c271d
DJ
745 if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
746 rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
802188a7 747
ea9c271d
DJ
748 /* Make sure that the packet buffer is plenty big enough for
749 this architecture. */
750 if (rs->buf_size < rsa->remote_packet_size)
751 {
752 rs->buf_size = 2 * rsa->remote_packet_size;
7fca722e 753 rs->buf = xrealloc (rs->buf, rs->buf_size);
ea9c271d 754 }
6d820c5c 755
ea9c271d
DJ
756 return rsa;
757}
758
759/* Return the current allowed size of a remote packet. This is
760 inferred from the current architecture, and should be used to
761 limit the length of outgoing packets. */
762static long
763get_remote_packet_size (void)
764{
be2a5f71 765 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
766 struct remote_arch_state *rsa = get_remote_arch_state ();
767
be2a5f71
DJ
768 if (rs->explicit_packet_size)
769 return rs->explicit_packet_size;
770
ea9c271d 771 return rsa->remote_packet_size;
d01949b6
AC
772}
773
ad10f812 774static struct packet_reg *
ea9c271d 775packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
ad10f812 776{
f5656ead 777 if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
b323314b
AC
778 return NULL;
779 else
ad10f812 780 {
ea9c271d 781 struct packet_reg *r = &rsa->regs[regnum];
a744cf53 782
b323314b
AC
783 gdb_assert (r->regnum == regnum);
784 return r;
ad10f812 785 }
ad10f812
AC
786}
787
788static struct packet_reg *
ea9c271d 789packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
ad10f812 790{
b323314b 791 int i;
a744cf53 792
f5656ead 793 for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
ad10f812 794 {
ea9c271d 795 struct packet_reg *r = &rsa->regs[i];
a744cf53 796
b323314b
AC
797 if (r->pnum == pnum)
798 return r;
ad10f812
AC
799 }
800 return NULL;
d01949b6
AC
801}
802
c906108c
SS
803static struct target_ops remote_ops;
804
805static struct target_ops extended_remote_ops;
806
6426a772
JM
807/* FIXME: cagney/1999-09-23: Even though getpkt was called with
808 ``forever'' still use the normal timeout mechanism. This is
809 currently used by the ASYNC code to guarentee that target reads
810 during the initial connect always time-out. Once getpkt has been
811 modified to return a timeout indication and, in turn
812 remote_wait()/wait_for_inferior() have gained a timeout parameter
23860348 813 this can go away. */
6426a772
JM
814static int wait_forever_enabled_p = 1;
815
9a7071a8
JB
816/* Allow the user to specify what sequence to send to the remote
817 when he requests a program interruption: Although ^C is usually
818 what remote systems expect (this is the default, here), it is
819 sometimes preferable to send a break. On other systems such
820 as the Linux kernel, a break followed by g, which is Magic SysRq g
821 is required in order to interrupt the execution. */
822const char interrupt_sequence_control_c[] = "Ctrl-C";
823const char interrupt_sequence_break[] = "BREAK";
824const char interrupt_sequence_break_g[] = "BREAK-g";
40478521 825static const char *const interrupt_sequence_modes[] =
9a7071a8
JB
826 {
827 interrupt_sequence_control_c,
828 interrupt_sequence_break,
829 interrupt_sequence_break_g,
830 NULL
831 };
832static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
833
834static void
835show_interrupt_sequence (struct ui_file *file, int from_tty,
836 struct cmd_list_element *c,
837 const char *value)
838{
839 if (interrupt_sequence_mode == interrupt_sequence_control_c)
840 fprintf_filtered (file,
841 _("Send the ASCII ETX character (Ctrl-c) "
842 "to the remote target to interrupt the "
843 "execution of the program.\n"));
844 else if (interrupt_sequence_mode == interrupt_sequence_break)
845 fprintf_filtered (file,
846 _("send a break signal to the remote target "
847 "to interrupt the execution of the program.\n"));
848 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
849 fprintf_filtered (file,
850 _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
851 "the remote target to interrupt the execution "
852 "of Linux kernel.\n"));
853 else
854 internal_error (__FILE__, __LINE__,
855 _("Invalid value for interrupt_sequence_mode: %s."),
856 interrupt_sequence_mode);
857}
6426a772 858
9a7071a8
JB
859/* This boolean variable specifies whether interrupt_sequence is sent
860 to the remote target when gdb connects to it.
861 This is mostly needed when you debug the Linux kernel: The Linux kernel
862 expects BREAK g which is Magic SysRq g for connecting gdb. */
863static int interrupt_on_connect = 0;
c906108c 864
9a7071a8
JB
865/* This variable is used to implement the "set/show remotebreak" commands.
866 Since these commands are now deprecated in favor of "set/show remote
867 interrupt-sequence", it no longer has any effect on the code. */
c906108c
SS
868static int remote_break;
869
9a7071a8
JB
870static void
871set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
872{
873 if (remote_break)
874 interrupt_sequence_mode = interrupt_sequence_break;
875 else
876 interrupt_sequence_mode = interrupt_sequence_control_c;
877}
878
879static void
880show_remotebreak (struct ui_file *file, int from_tty,
881 struct cmd_list_element *c,
882 const char *value)
883{
884}
885
c906108c
SS
886/* This variable sets the number of bits in an address that are to be
887 sent in a memory ("M" or "m") packet. Normally, after stripping
0df8b418 888 leading zeros, the entire address would be sent. This variable
c906108c
SS
889 restricts the address to REMOTE_ADDRESS_SIZE bits. HISTORY: The
890 initial implementation of remote.c restricted the address sent in
891 memory packets to ``host::sizeof long'' bytes - (typically 32
892 bits). Consequently, for 64 bit targets, the upper 32 bits of an
893 address was never sent. Since fixing this bug may cause a break in
894 some remote targets this variable is principly provided to
23860348 895 facilitate backward compatibility. */
c906108c 896
883b9c6c 897static unsigned int remote_address_size;
c906108c 898
75c99385
PA
899/* Temporary to track who currently owns the terminal. See
900 remote_terminal_* for more details. */
6426a772
JM
901
902static int remote_async_terminal_ours_p;
903
2d717e4f
DJ
904/* The executable file to use for "run" on the remote side. */
905
906static char *remote_exec_file = "";
907
11cf8741 908\f
11cf8741 909/* User configurable variables for the number of characters in a
ea9c271d
DJ
910 memory read/write packet. MIN (rsa->remote_packet_size,
911 rsa->sizeof_g_packet) is the default. Some targets need smaller
24b06219 912 values (fifo overruns, et.al.) and some users need larger values
ad10f812
AC
913 (speed up transfers). The variables ``preferred_*'' (the user
914 request), ``current_*'' (what was actually set) and ``forced_*''
23860348 915 (Positive - a soft limit, negative - a hard limit). */
11cf8741
JM
916
917struct memory_packet_config
918{
919 char *name;
920 long size;
921 int fixed_p;
922};
923
a5c0808e
PA
924/* The default max memory-write-packet-size. The 16k is historical.
925 (It came from older GDB's using alloca for buffers and the
926 knowledge (folklore?) that some hosts don't cope very well with
927 large alloca calls.) */
928#define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
929
930/* The minimum remote packet size for memory transfers. Ensures we
931 can write at least one byte. */
932#define MIN_MEMORY_PACKET_SIZE 20
933
11cf8741
JM
934/* Compute the current size of a read/write packet. Since this makes
935 use of ``actual_register_packet_size'' the computation is dynamic. */
936
937static long
938get_memory_packet_size (struct memory_packet_config *config)
939{
d01949b6 940 struct remote_state *rs = get_remote_state ();
ea9c271d
DJ
941 struct remote_arch_state *rsa = get_remote_arch_state ();
942
11cf8741
JM
943 long what_they_get;
944 if (config->fixed_p)
945 {
946 if (config->size <= 0)
a5c0808e 947 what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
11cf8741
JM
948 else
949 what_they_get = config->size;
950 }
951 else
952 {
ea9c271d 953 what_they_get = get_remote_packet_size ();
23860348 954 /* Limit the packet to the size specified by the user. */
11cf8741
JM
955 if (config->size > 0
956 && what_they_get > config->size)
957 what_they_get = config->size;
be2a5f71
DJ
958
959 /* Limit it to the size of the targets ``g'' response unless we have
960 permission from the stub to use a larger packet size. */
961 if (rs->explicit_packet_size == 0
962 && rsa->actual_register_packet_size > 0
963 && what_they_get > rsa->actual_register_packet_size)
964 what_they_get = rsa->actual_register_packet_size;
11cf8741 965 }
a5c0808e
PA
966 if (what_they_get < MIN_MEMORY_PACKET_SIZE)
967 what_they_get = MIN_MEMORY_PACKET_SIZE;
6d820c5c
DJ
968
969 /* Make sure there is room in the global buffer for this packet
970 (including its trailing NUL byte). */
971 if (rs->buf_size < what_they_get + 1)
972 {
973 rs->buf_size = 2 * what_they_get;
974 rs->buf = xrealloc (rs->buf, 2 * what_they_get);
975 }
976
11cf8741
JM
977 return what_they_get;
978}
979
0df8b418 980/* Update the size of a read/write packet. If they user wants
23860348 981 something really big then do a sanity check. */
11cf8741
JM
982
983static void
984set_memory_packet_size (char *args, struct memory_packet_config *config)
985{
986 int fixed_p = config->fixed_p;
987 long size = config->size;
a744cf53 988
11cf8741 989 if (args == NULL)
8a3fe4f8 990 error (_("Argument required (integer, `fixed' or `limited')."));
11cf8741
JM
991 else if (strcmp (args, "hard") == 0
992 || strcmp (args, "fixed") == 0)
993 fixed_p = 1;
994 else if (strcmp (args, "soft") == 0
995 || strcmp (args, "limit") == 0)
996 fixed_p = 0;
997 else
998 {
999 char *end;
a744cf53 1000
11cf8741
JM
1001 size = strtoul (args, &end, 0);
1002 if (args == end)
8a3fe4f8 1003 error (_("Invalid %s (bad syntax)."), config->name);
a5c0808e
PA
1004
1005 /* Instead of explicitly capping the size of a packet to or
1006 disallowing it, the user is allowed to set the size to
1007 something arbitrarily large. */
11cf8741 1008 }
a5c0808e
PA
1009
1010 /* So that the query shows the correct value. */
1011 if (size <= 0)
1012 size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1013
23860348 1014 /* Extra checks? */
11cf8741
JM
1015 if (fixed_p && !config->fixed_p)
1016 {
e2e0b3e5
AC
1017 if (! query (_("The target may not be able to correctly handle a %s\n"
1018 "of %ld bytes. Change the packet size? "),
11cf8741 1019 config->name, size))
8a3fe4f8 1020 error (_("Packet size not changed."));
11cf8741 1021 }
23860348 1022 /* Update the config. */
11cf8741
JM
1023 config->fixed_p = fixed_p;
1024 config->size = size;
1025}
1026
1027static void
1028show_memory_packet_size (struct memory_packet_config *config)
1029{
a3f17187 1030 printf_filtered (_("The %s is %ld. "), config->name, config->size);
11cf8741 1031 if (config->fixed_p)
a3f17187 1032 printf_filtered (_("Packets are fixed at %ld bytes.\n"),
11cf8741
JM
1033 get_memory_packet_size (config));
1034 else
a3f17187 1035 printf_filtered (_("Packets are limited to %ld bytes.\n"),
11cf8741
JM
1036 get_memory_packet_size (config));
1037}
1038
1039static struct memory_packet_config memory_write_packet_config =
1040{
1041 "memory-write-packet-size",
1042};
1043
1044static void
1045set_memory_write_packet_size (char *args, int from_tty)
1046{
1047 set_memory_packet_size (args, &memory_write_packet_config);
1048}
1049
1050static void
1051show_memory_write_packet_size (char *args, int from_tty)
1052{
1053 show_memory_packet_size (&memory_write_packet_config);
1054}
1055
1056static long
1057get_memory_write_packet_size (void)
1058{
1059 return get_memory_packet_size (&memory_write_packet_config);
1060}
1061
1062static struct memory_packet_config memory_read_packet_config =
1063{
1064 "memory-read-packet-size",
1065};
1066
1067static void
1068set_memory_read_packet_size (char *args, int from_tty)
1069{
1070 set_memory_packet_size (args, &memory_read_packet_config);
1071}
1072
1073static void
1074show_memory_read_packet_size (char *args, int from_tty)
1075{
1076 show_memory_packet_size (&memory_read_packet_config);
1077}
1078
1079static long
1080get_memory_read_packet_size (void)
1081{
1082 long size = get_memory_packet_size (&memory_read_packet_config);
a744cf53 1083
11cf8741
JM
1084 /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1085 extra buffer size argument before the memory read size can be
ea9c271d
DJ
1086 increased beyond this. */
1087 if (size > get_remote_packet_size ())
1088 size = get_remote_packet_size ();
11cf8741
JM
1089 return size;
1090}
1091
11cf8741 1092\f
5a2468f5 1093/* Generic configuration support for packets the stub optionally
0df8b418 1094 supports. Allows the user to specify the use of the packet as well
23860348 1095 as allowing GDB to auto-detect support in the remote stub. */
5a2468f5
JM
1096
1097enum packet_support
1098 {
1099 PACKET_SUPPORT_UNKNOWN = 0,
1100 PACKET_ENABLE,
1101 PACKET_DISABLE
1102 };
1103
5a2468f5
JM
1104struct packet_config
1105 {
bb572ddd
DJ
1106 const char *name;
1107 const char *title;
4082afcc
PA
1108
1109 /* If auto, GDB auto-detects support for this packet or feature,
1110 either through qSupported, or by trying the packet and looking
1111 at the response. If true, GDB assumes the target supports this
ca4f7f8b
PA
1112 packet. If false, the packet is disabled. Configs that don't
1113 have an associated command always have this set to auto. */
7f19b9a2 1114 enum auto_boolean detect;
4082afcc
PA
1115
1116 /* Does the target support this packet? */
5a2468f5
JM
1117 enum packet_support support;
1118 };
1119
d471ea57 1120/* Analyze a packet's return value and update the packet config
23860348 1121 accordingly. */
d471ea57
AC
1122
1123enum packet_result
1124{
1125 PACKET_ERROR,
1126 PACKET_OK,
1127 PACKET_UNKNOWN
1128};
1129
4082afcc
PA
1130static enum packet_support packet_config_support (struct packet_config *config);
1131static enum packet_support packet_support (int packet);
5a2468f5
JM
1132
1133static void
fba45db2 1134show_packet_config_cmd (struct packet_config *config)
5a2468f5
JM
1135{
1136 char *support = "internal-error";
a744cf53 1137
4082afcc 1138 switch (packet_config_support (config))
5a2468f5
JM
1139 {
1140 case PACKET_ENABLE:
1141 support = "enabled";
1142 break;
1143 case PACKET_DISABLE:
1144 support = "disabled";
1145 break;
1146 case PACKET_SUPPORT_UNKNOWN:
1147 support = "unknown";
1148 break;
1149 }
1150 switch (config->detect)
1151 {
7f19b9a2 1152 case AUTO_BOOLEAN_AUTO:
3e43a32a
MS
1153 printf_filtered (_("Support for the `%s' packet "
1154 "is auto-detected, currently %s.\n"),
37a105a1 1155 config->name, support);
5a2468f5 1156 break;
7f19b9a2
AC
1157 case AUTO_BOOLEAN_TRUE:
1158 case AUTO_BOOLEAN_FALSE:
37a105a1
DJ
1159 printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1160 config->name, support);
8e248173 1161 break;
5a2468f5
JM
1162 }
1163}
1164
1165static void
bb572ddd
DJ
1166add_packet_config_cmd (struct packet_config *config, const char *name,
1167 const char *title, int legacy)
d471ea57 1168{
5a2468f5
JM
1169 char *set_doc;
1170 char *show_doc;
d471ea57 1171 char *cmd_name;
3ed07be4 1172
5a2468f5
JM
1173 config->name = name;
1174 config->title = title;
b435e160
AC
1175 set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1176 name, title);
3e43a32a
MS
1177 show_doc = xstrprintf ("Show current use of remote "
1178 "protocol `%s' (%s) packet",
b435e160 1179 name, title);
d471ea57 1180 /* set/show TITLE-packet {auto,on,off} */
b435e160 1181 cmd_name = xstrprintf ("%s-packet", title);
e9e68a56 1182 add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
3e43a32a
MS
1183 &config->detect, set_doc,
1184 show_doc, NULL, /* help_doc */
4082afcc 1185 NULL,
bb572ddd
DJ
1186 show_remote_protocol_packet_cmd,
1187 &remote_set_cmdlist, &remote_show_cmdlist);
1eefb858
TT
1188 /* The command code copies the documentation strings. */
1189 xfree (set_doc);
1190 xfree (show_doc);
23860348 1191 /* set/show remote NAME-packet {auto,on,off} -- legacy. */
d471ea57
AC
1192 if (legacy)
1193 {
1194 char *legacy_name;
a744cf53 1195
b435e160 1196 legacy_name = xstrprintf ("%s-packet", name);
d471ea57 1197 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1198 &remote_set_cmdlist);
d471ea57 1199 add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
bb572ddd 1200 &remote_show_cmdlist);
d471ea57 1201 }
5a2468f5
JM
1202}
1203
d471ea57 1204static enum packet_result
a76d924d 1205packet_check_result (const char *buf)
5a2468f5 1206{
d471ea57 1207 if (buf[0] != '\0')
5a2468f5 1208 {
d471ea57 1209 /* The stub recognized the packet request. Check that the
23860348 1210 operation succeeded. */
a76d924d
DJ
1211 if (buf[0] == 'E'
1212 && isxdigit (buf[1]) && isxdigit (buf[2])
1213 && buf[3] == '\0')
1214 /* "Enn" - definitly an error. */
1215 return PACKET_ERROR;
1216
1217 /* Always treat "E." as an error. This will be used for
1218 more verbose error messages, such as E.memtypes. */
1219 if (buf[0] == 'E' && buf[1] == '.')
1220 return PACKET_ERROR;
1221
1222 /* The packet may or may not be OK. Just assume it is. */
1223 return PACKET_OK;
1224 }
1225 else
1226 /* The stub does not support the packet. */
1227 return PACKET_UNKNOWN;
1228}
1229
1230static enum packet_result
1231packet_ok (const char *buf, struct packet_config *config)
1232{
1233 enum packet_result result;
1234
4082afcc
PA
1235 if (config->detect != AUTO_BOOLEAN_TRUE
1236 && config->support == PACKET_DISABLE)
1237 internal_error (__FILE__, __LINE__,
1238 _("packet_ok: attempt to use a disabled packet"));
1239
a76d924d
DJ
1240 result = packet_check_result (buf);
1241 switch (result)
1242 {
1243 case PACKET_OK:
1244 case PACKET_ERROR:
1245 /* The stub recognized the packet request. */
4082afcc 1246 if (config->support == PACKET_SUPPORT_UNKNOWN)
d471ea57 1247 {
d471ea57
AC
1248 if (remote_debug)
1249 fprintf_unfiltered (gdb_stdlog,
4082afcc
PA
1250 "Packet %s (%s) is supported\n",
1251 config->name, config->title);
d471ea57 1252 config->support = PACKET_ENABLE;
d471ea57 1253 }
a76d924d
DJ
1254 break;
1255 case PACKET_UNKNOWN:
23860348 1256 /* The stub does not support the packet. */
4082afcc
PA
1257 if (config->detect == AUTO_BOOLEAN_AUTO
1258 && config->support == PACKET_ENABLE)
d471ea57 1259 {
4082afcc
PA
1260 /* If the stub previously indicated that the packet was
1261 supported then there is a protocol error. */
1262 error (_("Protocol error: %s (%s) conflicting enabled responses."),
1263 config->name, config->title);
1264 }
1265 else if (config->detect == AUTO_BOOLEAN_TRUE)
1266 {
1267 /* The user set it wrong. */
1268 error (_("Enabled packet %s (%s) not recognized by stub"),
1269 config->name, config->title);
d471ea57 1270 }
4082afcc
PA
1271
1272 if (remote_debug)
1273 fprintf_unfiltered (gdb_stdlog,
1274 "Packet %s (%s) is NOT supported\n",
1275 config->name, config->title);
1276 config->support = PACKET_DISABLE;
a76d924d 1277 break;
5a2468f5 1278 }
a76d924d
DJ
1279
1280 return result;
5a2468f5
JM
1281}
1282
444abaca
DJ
1283enum {
1284 PACKET_vCont = 0,
1285 PACKET_X,
1286 PACKET_qSymbol,
1287 PACKET_P,
1288 PACKET_p,
1289 PACKET_Z0,
1290 PACKET_Z1,
1291 PACKET_Z2,
1292 PACKET_Z3,
1293 PACKET_Z4,
15a201c8 1294 PACKET_vFile_setfs,
a6b151f1
DJ
1295 PACKET_vFile_open,
1296 PACKET_vFile_pread,
1297 PACKET_vFile_pwrite,
1298 PACKET_vFile_close,
1299 PACKET_vFile_unlink,
b9e7b9c3 1300 PACKET_vFile_readlink,
0a93529c 1301 PACKET_vFile_fstat,
0876f84a 1302 PACKET_qXfer_auxv,
23181151 1303 PACKET_qXfer_features,
c78fa86a 1304 PACKET_qXfer_exec_file,
cfa9d6d9 1305 PACKET_qXfer_libraries,
2268b414 1306 PACKET_qXfer_libraries_svr4,
fd79ecee 1307 PACKET_qXfer_memory_map,
0e7f50da
UW
1308 PACKET_qXfer_spu_read,
1309 PACKET_qXfer_spu_write,
07e059b5 1310 PACKET_qXfer_osdata,
dc146f7c 1311 PACKET_qXfer_threads,
0fb4aa4b 1312 PACKET_qXfer_statictrace_read,
b3b9301e 1313 PACKET_qXfer_traceframe_info,
169081d0 1314 PACKET_qXfer_uib,
711e434b 1315 PACKET_qGetTIBAddr,
444abaca 1316 PACKET_qGetTLSAddr,
be2a5f71 1317 PACKET_qSupported,
bd3eecc3 1318 PACKET_qTStatus,
89be2091 1319 PACKET_QPassSignals,
9b224c5e 1320 PACKET_QProgramSignals,
936d2992 1321 PACKET_qCRC,
08388c79 1322 PACKET_qSearch_memory,
2d717e4f
DJ
1323 PACKET_vAttach,
1324 PACKET_vRun,
a6f3e723 1325 PACKET_QStartNoAckMode,
82f73884 1326 PACKET_vKill,
4aa995e1
PA
1327 PACKET_qXfer_siginfo_read,
1328 PACKET_qXfer_siginfo_write,
0b16c5cf 1329 PACKET_qAttached,
4082afcc
PA
1330
1331 /* Support for conditional tracepoints. */
782b2b07 1332 PACKET_ConditionalTracepoints,
4082afcc
PA
1333
1334 /* Support for target-side breakpoint conditions. */
3788aec7 1335 PACKET_ConditionalBreakpoints,
4082afcc
PA
1336
1337 /* Support for target-side breakpoint commands. */
d3ce09f5 1338 PACKET_BreakpointCommands,
4082afcc
PA
1339
1340 /* Support for fast tracepoints. */
7a697b8d 1341 PACKET_FastTracepoints,
4082afcc
PA
1342
1343 /* Support for static tracepoints. */
0fb4aa4b 1344 PACKET_StaticTracepoints,
4082afcc
PA
1345
1346 /* Support for installing tracepoints while a trace experiment is
1347 running. */
1e4d1764 1348 PACKET_InstallInTrace,
4082afcc 1349
40ab02ce
MS
1350 PACKET_bc,
1351 PACKET_bs,
409873ef 1352 PACKET_TracepointSource,
d914c394 1353 PACKET_QAllow,
78d85199 1354 PACKET_qXfer_fdpic,
03583c20 1355 PACKET_QDisableRandomization,
d1feda86 1356 PACKET_QAgent,
f6f899bf 1357 PACKET_QTBuffer_size,
9accd112
MM
1358 PACKET_Qbtrace_off,
1359 PACKET_Qbtrace_bts,
b20a6524 1360 PACKET_Qbtrace_pt,
9accd112 1361 PACKET_qXfer_btrace,
4082afcc
PA
1362
1363 /* Support for the QNonStop packet. */
1364 PACKET_QNonStop,
1365
1366 /* Support for multi-process extensions. */
1367 PACKET_multiprocess_feature,
1368
1369 /* Support for enabling and disabling tracepoints while a trace
1370 experiment is running. */
1371 PACKET_EnableDisableTracepoints_feature,
1372
1373 /* Support for collecting strings using the tracenz bytecode. */
1374 PACKET_tracenz_feature,
1375
1376 /* Support for continuing to run a trace experiment while GDB is
1377 disconnected. */
1378 PACKET_DisconnectedTracing_feature,
1379
1380 /* Support for qXfer:libraries-svr4:read with a non-empty annex. */
1381 PACKET_augmented_libraries_svr4_read_feature,
1382
f4abbc16
MM
1383 /* Support for the qXfer:btrace-conf:read packet. */
1384 PACKET_qXfer_btrace_conf,
1385
d33501a5
MM
1386 /* Support for the Qbtrace-conf:bts:size packet. */
1387 PACKET_Qbtrace_conf_bts_size,
1388
f7e6eed5
PA
1389 /* Support for swbreak+ feature. */
1390 PACKET_swbreak_feature,
1391
1392 /* Support for hwbreak+ feature. */
1393 PACKET_hwbreak_feature,
1394
89245bc0
DB
1395 /* Support for fork events. */
1396 PACKET_fork_event_feature,
1397
1398 /* Support for vfork events. */
1399 PACKET_vfork_event_feature,
1400
b20a6524
MM
1401 /* Support for the Qbtrace-conf:pt:size packet. */
1402 PACKET_Qbtrace_conf_pt_size,
1403
444abaca
DJ
1404 PACKET_MAX
1405};
506fb367 1406
444abaca 1407static struct packet_config remote_protocol_packets[PACKET_MAX];
dc8acb97 1408
f7e6eed5
PA
1409/* Returns the packet's corresponding "set remote foo-packet" command
1410 state. See struct packet_config for more details. */
1411
1412static enum auto_boolean
1413packet_set_cmd_state (int packet)
1414{
1415 return remote_protocol_packets[packet].detect;
1416}
1417
4082afcc
PA
1418/* Returns whether a given packet or feature is supported. This takes
1419 into account the state of the corresponding "set remote foo-packet"
1420 command, which may be used to bypass auto-detection. */
dc8acb97 1421
4082afcc
PA
1422static enum packet_support
1423packet_config_support (struct packet_config *config)
1424{
1425 switch (config->detect)
444abaca 1426 {
4082afcc
PA
1427 case AUTO_BOOLEAN_TRUE:
1428 return PACKET_ENABLE;
1429 case AUTO_BOOLEAN_FALSE:
1430 return PACKET_DISABLE;
1431 case AUTO_BOOLEAN_AUTO:
1432 return config->support;
1433 default:
1434 gdb_assert_not_reached (_("bad switch"));
444abaca 1435 }
4082afcc
PA
1436}
1437
1438/* Same as packet_config_support, but takes the packet's enum value as
1439 argument. */
1440
1441static enum packet_support
1442packet_support (int packet)
1443{
1444 struct packet_config *config = &remote_protocol_packets[packet];
1445
1446 return packet_config_support (config);
dc8acb97
MS
1447}
1448
5a2468f5 1449static void
444abaca
DJ
1450show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1451 struct cmd_list_element *c,
1452 const char *value)
5a2468f5 1453{
444abaca 1454 struct packet_config *packet;
5a2468f5 1455
444abaca
DJ
1456 for (packet = remote_protocol_packets;
1457 packet < &remote_protocol_packets[PACKET_MAX];
1458 packet++)
1459 {
1460 if (&packet->detect == c->var)
1461 {
1462 show_packet_config_cmd (packet);
1463 return;
1464 }
1465 }
9b20d036 1466 internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
444abaca 1467 c->name);
5a2468f5
JM
1468}
1469
d471ea57
AC
1470/* Should we try one of the 'Z' requests? */
1471
1472enum Z_packet_type
1473{
1474 Z_PACKET_SOFTWARE_BP,
1475 Z_PACKET_HARDWARE_BP,
1476 Z_PACKET_WRITE_WP,
1477 Z_PACKET_READ_WP,
1478 Z_PACKET_ACCESS_WP,
1479 NR_Z_PACKET_TYPES
1480};
96baa820 1481
d471ea57 1482/* For compatibility with older distributions. Provide a ``set remote
23860348 1483 Z-packet ...'' command that updates all the Z packet types. */
d471ea57 1484
7f19b9a2 1485static enum auto_boolean remote_Z_packet_detect;
96baa820
JM
1486
1487static void
fba45db2
KB
1488set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1489 struct cmd_list_element *c)
96baa820 1490{
d471ea57 1491 int i;
a744cf53 1492
d471ea57 1493 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
4082afcc 1494 remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
96baa820
JM
1495}
1496
1497static void
08546159
AC
1498show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1499 struct cmd_list_element *c,
1500 const char *value)
96baa820 1501{
d471ea57 1502 int i;
a744cf53 1503
d471ea57
AC
1504 for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1505 {
444abaca 1506 show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
d471ea57 1507 }
96baa820
JM
1508}
1509
4082afcc
PA
1510/* Returns true if the multi-process extensions are in effect. */
1511
1512static int
1513remote_multi_process_p (struct remote_state *rs)
1514{
1515 return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1516}
1517
de0d863e
DB
1518/* Returns true if fork events are supported. */
1519
1520static int
1521remote_fork_event_p (struct remote_state *rs)
1522{
1523 return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1524}
1525
c269dbdb
DB
1526/* Returns true if vfork events are supported. */
1527
1528static int
1529remote_vfork_event_p (struct remote_state *rs)
1530{
1531 return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1532}
1533
cbb8991c
DB
1534/* Insert fork catchpoint target routine. If fork events are enabled
1535 then return success, nothing more to do. */
1536
1537static int
1538remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1539{
1540 struct remote_state *rs = get_remote_state ();
1541
1542 return !remote_fork_event_p (rs);
1543}
1544
1545/* Remove fork catchpoint target routine. Nothing to do, just
1546 return success. */
1547
1548static int
1549remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1550{
1551 return 0;
1552}
1553
1554/* Insert vfork catchpoint target routine. If vfork events are enabled
1555 then return success, nothing more to do. */
1556
1557static int
1558remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1559{
1560 struct remote_state *rs = get_remote_state ();
1561
1562 return !remote_vfork_event_p (rs);
1563}
1564
1565/* Remove vfork catchpoint target routine. Nothing to do, just
1566 return success. */
1567
1568static int
1569remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1570{
1571 return 0;
1572}
1573
23860348 1574/* Tokens for use by the asynchronous signal handlers for SIGINT. */
934b9bac
JK
1575static struct async_signal_handler *async_sigint_remote_twice_token;
1576static struct async_signal_handler *async_sigint_remote_token;
43ff13b4 1577
74531fed
PA
1578\f
1579/* Asynchronous signal handle registered as event loop source for
1580 when we have pending events ready to be passed to the core. */
1581
1582static struct async_event_handler *remote_async_inferior_event_token;
1583
c906108c
SS
1584\f
1585
79d7f229
PA
1586static ptid_t magic_null_ptid;
1587static ptid_t not_sent_ptid;
1588static ptid_t any_thread_ptid;
1589
0b16c5cf
PA
1590/* Find out if the stub attached to PID (and hence GDB should offer to
1591 detach instead of killing it when bailing out). */
1592
1593static int
1594remote_query_attached (int pid)
1595{
1596 struct remote_state *rs = get_remote_state ();
bba74b36 1597 size_t size = get_remote_packet_size ();
0b16c5cf 1598
4082afcc 1599 if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
0b16c5cf
PA
1600 return 0;
1601
1602 if (remote_multi_process_p (rs))
bba74b36 1603 xsnprintf (rs->buf, size, "qAttached:%x", pid);
0b16c5cf 1604 else
bba74b36 1605 xsnprintf (rs->buf, size, "qAttached");
0b16c5cf
PA
1606
1607 putpkt (rs->buf);
1608 getpkt (&rs->buf, &rs->buf_size, 0);
1609
1610 switch (packet_ok (rs->buf,
1554e9be 1611 &remote_protocol_packets[PACKET_qAttached]))
0b16c5cf
PA
1612 {
1613 case PACKET_OK:
1614 if (strcmp (rs->buf, "1") == 0)
1615 return 1;
1616 break;
1617 case PACKET_ERROR:
1618 warning (_("Remote failure reply: %s"), rs->buf);
1619 break;
1620 case PACKET_UNKNOWN:
1621 break;
1622 }
1623
1624 return 0;
1625}
1626
49c62f2e
PA
1627/* Add PID to GDB's inferior table. If FAKE_PID_P is true, then PID
1628 has been invented by GDB, instead of reported by the target. Since
1629 we can be connected to a remote system before before knowing about
1630 any inferior, mark the target with execution when we find the first
1631 inferior. If ATTACHED is 1, then we had just attached to this
1632 inferior. If it is 0, then we just created this inferior. If it
1633 is -1, then try querying the remote stub to find out if it had
1b6e6f5c
GB
1634 attached to the inferior or not. If TRY_OPEN_EXEC is true then
1635 attempt to open this inferior's executable as the main executable
1636 if no main executable is open already. */
1941c569
PA
1637
1638static struct inferior *
1b6e6f5c
GB
1639remote_add_inferior (int fake_pid_p, int pid, int attached,
1640 int try_open_exec)
1941c569 1641{
1941c569
PA
1642 struct inferior *inf;
1643
0b16c5cf
PA
1644 /* Check whether this process we're learning about is to be
1645 considered attached, or if is to be considered to have been
1646 spawned by the stub. */
1647 if (attached == -1)
1648 attached = remote_query_attached (pid);
1649
f5656ead 1650 if (gdbarch_has_global_solist (target_gdbarch ()))
6c95b8df
PA
1651 {
1652 /* If the target shares code across all inferiors, then every
1653 attach adds a new inferior. */
1654 inf = add_inferior (pid);
1655
1656 /* ... and every inferior is bound to the same program space.
1657 However, each inferior may still have its own address
1658 space. */
1659 inf->aspace = maybe_new_address_space ();
1660 inf->pspace = current_program_space;
1661 }
1662 else
1663 {
1664 /* In the traditional debugging scenario, there's a 1-1 match
1665 between program/address spaces. We simply bind the inferior
1666 to the program space's address space. */
1667 inf = current_inferior ();
1668 inferior_appeared (inf, pid);
1669 }
1941c569 1670
0b16c5cf 1671 inf->attach_flag = attached;
49c62f2e 1672 inf->fake_pid_p = fake_pid_p;
0b16c5cf 1673
1b6e6f5c
GB
1674 /* If no main executable is currently open then attempt to
1675 open the file that was executed to create this inferior. */
835205d0 1676 if (try_open_exec && get_exec_file (0) == NULL)
1b6e6f5c
GB
1677 exec_file_locate_attach (pid, 1);
1678
1941c569
PA
1679 return inf;
1680}
1681
1682/* Add thread PTID to GDB's thread list. Tag it as executing/running
1683 according to RUNNING. */
1684
c906108c 1685static void
1941c569 1686remote_add_thread (ptid_t ptid, int running)
c906108c 1687{
b7ea362b
PA
1688 struct remote_state *rs = get_remote_state ();
1689
1690 /* GDB historically didn't pull threads in the initial connection
1691 setup. If the remote target doesn't even have a concept of
1692 threads (e.g., a bare-metal target), even if internally we
1693 consider that a single-threaded target, mentioning a new thread
1694 might be confusing to the user. Be silent then, preserving the
1695 age old behavior. */
1696 if (rs->starting_up)
1697 add_thread_silent (ptid);
1698 else
1699 add_thread (ptid);
1941c569
PA
1700
1701 set_executing (ptid, running);
1702 set_running (ptid, running);
1703}
1704
1705/* Come here when we learn about a thread id from the remote target.
1706 It may be the first time we hear about such thread, so take the
1707 opportunity to add it to GDB's thread list. In case this is the
1708 first time we're noticing its corresponding inferior, add it to
1709 GDB's inferior list as well. */
1710
1711static void
1712remote_notice_new_inferior (ptid_t currthread, int running)
1713{
c906108c
SS
1714 /* If this is a new thread, add it to GDB's thread list.
1715 If we leave it up to WFI to do this, bad things will happen. */
82f73884
PA
1716
1717 if (in_thread_list (currthread) && is_exited (currthread))
1718 {
1719 /* We're seeing an event on a thread id we knew had exited.
1720 This has to be a new thread reusing the old id. Add it. */
1941c569 1721 remote_add_thread (currthread, running);
82f73884
PA
1722 return;
1723 }
1724
79d7f229 1725 if (!in_thread_list (currthread))
c0a2216e 1726 {
1941c569 1727 struct inferior *inf = NULL;
bad34192 1728 int pid = ptid_get_pid (currthread);
1941c569 1729
bad34192
PA
1730 if (ptid_is_pid (inferior_ptid)
1731 && pid == ptid_get_pid (inferior_ptid))
c0a2216e
PA
1732 {
1733 /* inferior_ptid has no thread member yet. This can happen
1734 with the vAttach -> remote_wait,"TAAthread:" path if the
1735 stub doesn't support qC. This is the first stop reported
1736 after an attach, so this is the main thread. Update the
1737 ptid in the thread list. */
bad34192
PA
1738 if (in_thread_list (pid_to_ptid (pid)))
1739 thread_change_ptid (inferior_ptid, currthread);
1740 else
1741 {
1742 remote_add_thread (currthread, running);
1743 inferior_ptid = currthread;
1744 }
dc146f7c 1745 return;
c0a2216e 1746 }
82f73884
PA
1747
1748 if (ptid_equal (magic_null_ptid, inferior_ptid))
c0a2216e
PA
1749 {
1750 /* inferior_ptid is not set yet. This can happen with the
1751 vRun -> remote_wait,"TAAthread:" path if the stub
1752 doesn't support qC. This is the first stop reported
1753 after an attach, so this is the main thread. Update the
1754 ptid in the thread list. */
dc146f7c 1755 thread_change_ptid (inferior_ptid, currthread);
82f73884 1756 return;
c0a2216e 1757 }
82f73884 1758
29c87f7f
PA
1759 /* When connecting to a target remote, or to a target
1760 extended-remote which already was debugging an inferior, we
1761 may not know about it yet. Add it before adding its child
1762 thread, so notifications are emitted in a sensible order. */
1763 if (!in_inferior_list (ptid_get_pid (currthread)))
49c62f2e
PA
1764 {
1765 struct remote_state *rs = get_remote_state ();
1766 int fake_pid_p = !remote_multi_process_p (rs);
1767
1768 inf = remote_add_inferior (fake_pid_p,
1b6e6f5c 1769 ptid_get_pid (currthread), -1, 1);
49c62f2e 1770 }
29c87f7f 1771
82f73884 1772 /* This is really a new thread. Add it. */
1941c569
PA
1773 remote_add_thread (currthread, running);
1774
1775 /* If we found a new inferior, let the common code do whatever
1776 it needs to with it (e.g., read shared libraries, insert
b7ea362b
PA
1777 breakpoints), unless we're just setting up an all-stop
1778 connection. */
1941c569 1779 if (inf != NULL)
b7ea362b
PA
1780 {
1781 struct remote_state *rs = get_remote_state ();
1782
1783 if (non_stop || !rs->starting_up)
1784 notice_new_inferior (currthread, running, 0);
1785 }
c0a2216e 1786 }
c906108c
SS
1787}
1788
dc146f7c
VP
1789/* Return the private thread data, creating it if necessary. */
1790
70221824 1791static struct private_thread_info *
dc146f7c
VP
1792demand_private_info (ptid_t ptid)
1793{
1794 struct thread_info *info = find_thread_ptid (ptid);
1795
1796 gdb_assert (info);
1797
fe978cb0 1798 if (!info->priv)
dc146f7c 1799 {
8d749320 1800 info->priv = XNEW (struct private_thread_info);
dc146f7c 1801 info->private_dtor = free_private_thread_info;
fe978cb0
PA
1802 info->priv->core = -1;
1803 info->priv->extra = 0;
dc146f7c
VP
1804 }
1805
fe978cb0 1806 return info->priv;
dc146f7c
VP
1807}
1808
74531fed
PA
1809/* Call this function as a result of
1810 1) A halt indication (T packet) containing a thread id
1811 2) A direct query of currthread
0df8b418 1812 3) Successful execution of set thread */
74531fed
PA
1813
1814static void
47f8a51d 1815record_currthread (struct remote_state *rs, ptid_t currthread)
74531fed 1816{
47f8a51d 1817 rs->general_thread = currthread;
74531fed
PA
1818}
1819
89be2091
DJ
1820/* If 'QPassSignals' is supported, tell the remote stub what signals
1821 it can simply pass through to the inferior without reporting. */
1822
1823static void
94bedb42
TT
1824remote_pass_signals (struct target_ops *self,
1825 int numsigs, unsigned char *pass_signals)
89be2091 1826{
4082afcc 1827 if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
89be2091
DJ
1828 {
1829 char *pass_packet, *p;
89be2091 1830 int count = 0, i;
747dc59d 1831 struct remote_state *rs = get_remote_state ();
89be2091
DJ
1832
1833 gdb_assert (numsigs < 256);
1834 for (i = 0; i < numsigs; i++)
1835 {
2455069d 1836 if (pass_signals[i])
89be2091
DJ
1837 count++;
1838 }
1839 pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1840 strcpy (pass_packet, "QPassSignals:");
1841 p = pass_packet + strlen (pass_packet);
1842 for (i = 0; i < numsigs; i++)
1843 {
2455069d 1844 if (pass_signals[i])
89be2091
DJ
1845 {
1846 if (i >= 16)
1847 *p++ = tohex (i >> 4);
1848 *p++ = tohex (i & 15);
1849 if (count)
1850 *p++ = ';';
1851 else
1852 break;
1853 count--;
1854 }
1855 }
1856 *p = 0;
747dc59d 1857 if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
89be2091 1858 {
89be2091
DJ
1859 putpkt (pass_packet);
1860 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1861 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
747dc59d
TT
1862 if (rs->last_pass_packet)
1863 xfree (rs->last_pass_packet);
1864 rs->last_pass_packet = pass_packet;
89be2091
DJ
1865 }
1866 else
1867 xfree (pass_packet);
1868 }
1869}
1870
9b224c5e
PA
1871/* If 'QProgramSignals' is supported, tell the remote stub what
1872 signals it should pass through to the inferior when detaching. */
1873
1874static void
daf5e9b6
TT
1875remote_program_signals (struct target_ops *self,
1876 int numsigs, unsigned char *signals)
9b224c5e 1877{
4082afcc 1878 if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
9b224c5e
PA
1879 {
1880 char *packet, *p;
1881 int count = 0, i;
5e4a05c4 1882 struct remote_state *rs = get_remote_state ();
9b224c5e
PA
1883
1884 gdb_assert (numsigs < 256);
1885 for (i = 0; i < numsigs; i++)
1886 {
1887 if (signals[i])
1888 count++;
1889 }
1890 packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1891 strcpy (packet, "QProgramSignals:");
1892 p = packet + strlen (packet);
1893 for (i = 0; i < numsigs; i++)
1894 {
1895 if (signal_pass_state (i))
1896 {
1897 if (i >= 16)
1898 *p++ = tohex (i >> 4);
1899 *p++ = tohex (i & 15);
1900 if (count)
1901 *p++ = ';';
1902 else
1903 break;
1904 count--;
1905 }
1906 }
1907 *p = 0;
5e4a05c4
TT
1908 if (!rs->last_program_signals_packet
1909 || strcmp (rs->last_program_signals_packet, packet) != 0)
9b224c5e 1910 {
9b224c5e
PA
1911 putpkt (packet);
1912 getpkt (&rs->buf, &rs->buf_size, 0);
8dc5b319 1913 packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
5e4a05c4
TT
1914 xfree (rs->last_program_signals_packet);
1915 rs->last_program_signals_packet = packet;
9b224c5e
PA
1916 }
1917 else
1918 xfree (packet);
1919 }
1920}
1921
79d7f229
PA
1922/* If PTID is MAGIC_NULL_PTID, don't set any thread. If PTID is
1923 MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1924 thread. If GEN is set, set the general thread, if not, then set
1925 the step/continue thread. */
c906108c 1926static void
79d7f229 1927set_thread (struct ptid ptid, int gen)
c906108c 1928{
d01949b6 1929 struct remote_state *rs = get_remote_state ();
47f8a51d 1930 ptid_t state = gen ? rs->general_thread : rs->continue_thread;
6d820c5c 1931 char *buf = rs->buf;
79d7f229 1932 char *endbuf = rs->buf + get_remote_packet_size ();
c906108c 1933
79d7f229 1934 if (ptid_equal (state, ptid))
c906108c
SS
1935 return;
1936
79d7f229
PA
1937 *buf++ = 'H';
1938 *buf++ = gen ? 'g' : 'c';
1939 if (ptid_equal (ptid, magic_null_ptid))
1940 xsnprintf (buf, endbuf - buf, "0");
1941 else if (ptid_equal (ptid, any_thread_ptid))
1942 xsnprintf (buf, endbuf - buf, "0");
1943 else if (ptid_equal (ptid, minus_one_ptid))
1944 xsnprintf (buf, endbuf - buf, "-1");
1945 else
82f73884 1946 write_ptid (buf, endbuf, ptid);
79d7f229 1947 putpkt (rs->buf);
6d820c5c 1948 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 1949 if (gen)
47f8a51d 1950 rs->general_thread = ptid;
c906108c 1951 else
47f8a51d 1952 rs->continue_thread = ptid;
c906108c 1953}
79d7f229
PA
1954
1955static void
1956set_general_thread (struct ptid ptid)
1957{
1958 set_thread (ptid, 1);
1959}
1960
1961static void
1962set_continue_thread (struct ptid ptid)
1963{
1964 set_thread (ptid, 0);
1965}
1966
3c9c4b83
PA
1967/* Change the remote current process. Which thread within the process
1968 ends up selected isn't important, as long as it is the same process
1969 as what INFERIOR_PTID points to.
1970
1971 This comes from that fact that there is no explicit notion of
1972 "selected process" in the protocol. The selected process for
1973 general operations is the process the selected general thread
1974 belongs to. */
1975
1976static void
1977set_general_process (void)
1978{
1979 struct remote_state *rs = get_remote_state ();
1980
1981 /* If the remote can't handle multiple processes, don't bother. */
901f9912 1982 if (!rs->extended || !remote_multi_process_p (rs))
3c9c4b83
PA
1983 return;
1984
1985 /* We only need to change the remote current thread if it's pointing
1986 at some other process. */
47f8a51d 1987 if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
3c9c4b83
PA
1988 set_general_thread (inferior_ptid);
1989}
1990
c906108c 1991\f
7d1a114c
PA
1992/* Return nonzero if this is the main thread that we made up ourselves
1993 to model non-threaded targets as single-threaded. */
c906108c
SS
1994
1995static int
7d1a114c 1996remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
c906108c 1997{
6d820c5c 1998 struct remote_state *rs = get_remote_state ();
82f73884 1999 char *p, *endp;
c906108c 2000
c0a2216e
PA
2001 if (ptid_equal (ptid, magic_null_ptid))
2002 /* The main thread is always alive. */
2003 return 1;
2004
ba348170 2005 if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
c0a2216e
PA
2006 /* The main thread is always alive. This can happen after a
2007 vAttach, if the remote side doesn't support
2008 multi-threading. */
2009 return 1;
2010
7d1a114c
PA
2011 return 0;
2012}
2013
2014/* Return nonzero if the thread PTID is still alive on the remote
2015 system. */
2016
2017static int
2018remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2019{
2020 struct remote_state *rs = get_remote_state ();
2021 char *p, *endp;
2022
2023 /* Check if this is a thread that we made up ourselves to model
2024 non-threaded targets as single-threaded. */
2025 if (remote_thread_always_alive (ops, ptid))
2026 return 1;
2027
82f73884
PA
2028 p = rs->buf;
2029 endp = rs->buf + get_remote_packet_size ();
2030
2031 *p++ = 'T';
2032 write_ptid (p, endp, ptid);
2033
2e9f7625 2034 putpkt (rs->buf);
6d820c5c 2035 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2036 return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
c906108c
SS
2037}
2038
2039/* About these extended threadlist and threadinfo packets. They are
2040 variable length packets but, the fields within them are often fixed
2041 length. They are redundent enough to send over UDP as is the
2042 remote protocol in general. There is a matching unit test module
2043 in libstub. */
2044
23860348 2045/* WARNING: This threadref data structure comes from the remote O.S.,
0df8b418 2046 libstub protocol encoding, and remote.c. It is not particularly
23860348 2047 changable. */
cce74817
JM
2048
2049/* Right now, the internal structure is int. We want it to be bigger.
0df8b418 2050 Plan to fix this. */
cce74817 2051
23860348 2052typedef int gdb_threadref; /* Internal GDB thread reference. */
cce74817 2053
9d1f7ab2 2054/* gdb_ext_thread_info is an internal GDB data structure which is
cfde0993 2055 equivalent to the reply of the remote threadinfo packet. */
cce74817
JM
2056
2057struct gdb_ext_thread_info
c5aa993b 2058 {
23860348 2059 threadref threadid; /* External form of thread reference. */
2bc416ba 2060 int active; /* Has state interesting to GDB?
23860348 2061 regs, stack. */
2bc416ba 2062 char display[256]; /* Brief state display, name,
cedea757 2063 blocked/suspended. */
23860348 2064 char shortname[32]; /* To be used to name threads. */
2bc416ba 2065 char more_display[256]; /* Long info, statistics, queue depth,
23860348 2066 whatever. */
c5aa993b 2067 };
cce74817
JM
2068
2069/* The volume of remote transfers can be limited by submitting
2070 a mask containing bits specifying the desired information.
2071 Use a union of these values as the 'selection' parameter to
0df8b418 2072 get_thread_info. FIXME: Make these TAG names more thread specific. */
cce74817
JM
2073
2074#define TAG_THREADID 1
2075#define TAG_EXISTS 2
2076#define TAG_DISPLAY 4
2077#define TAG_THREADNAME 8
c5aa993b 2078#define TAG_MOREDISPLAY 16
cce74817 2079
23860348 2080#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
c906108c 2081
a14ed312 2082static char *unpack_nibble (char *buf, int *val);
cce74817 2083
a14ed312 2084static char *unpack_byte (char *buf, int *value);
cce74817 2085
a14ed312 2086static char *pack_int (char *buf, int value);
cce74817 2087
a14ed312 2088static char *unpack_int (char *buf, int *value);
cce74817 2089
a14ed312 2090static char *unpack_string (char *src, char *dest, int length);
cce74817 2091
23860348 2092static char *pack_threadid (char *pkt, threadref *id);
cce74817 2093
23860348 2094static char *unpack_threadid (char *inbuf, threadref *id);
cce74817 2095
23860348 2096void int_to_threadref (threadref *id, int value);
cce74817 2097
23860348 2098static int threadref_to_int (threadref *ref);
cce74817 2099
23860348 2100static void copy_threadref (threadref *dest, threadref *src);
cce74817 2101
23860348 2102static int threadmatch (threadref *dest, threadref *src);
cce74817 2103
2bc416ba 2104static char *pack_threadinfo_request (char *pkt, int mode,
23860348 2105 threadref *id);
cce74817 2106
a14ed312 2107static int remote_unpack_thread_info_response (char *pkt,
23860348 2108 threadref *expectedref,
a14ed312
KB
2109 struct gdb_ext_thread_info
2110 *info);
cce74817
JM
2111
2112
2bc416ba 2113static int remote_get_threadinfo (threadref *threadid,
23860348 2114 int fieldset, /*TAG mask */
a14ed312 2115 struct gdb_ext_thread_info *info);
cce74817 2116
a14ed312
KB
2117static char *pack_threadlist_request (char *pkt, int startflag,
2118 int threadcount,
23860348 2119 threadref *nextthread);
cce74817 2120
a14ed312
KB
2121static int parse_threadlist_response (char *pkt,
2122 int result_limit,
23860348 2123 threadref *original_echo,
2bc416ba 2124 threadref *resultlist,
23860348 2125 int *doneflag);
cce74817 2126
a14ed312 2127static int remote_get_threadlist (int startflag,
23860348 2128 threadref *nextthread,
a14ed312
KB
2129 int result_limit,
2130 int *done,
2bc416ba 2131 int *result_count,
23860348 2132 threadref *threadlist);
cce74817 2133
23860348 2134typedef int (*rmt_thread_action) (threadref *ref, void *context);
cce74817 2135
a14ed312
KB
2136static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2137 void *context, int looplimit);
cce74817 2138
23860348 2139static int remote_newthread_step (threadref *ref, void *context);
cce74817 2140
82f73884
PA
2141
2142/* Write a PTID to BUF. ENDBUF points to one-passed-the-end of the
2143 buffer we're allowed to write to. Returns
2144 BUF+CHARACTERS_WRITTEN. */
2145
2146static char *
2147write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2148{
2149 int pid, tid;
2150 struct remote_state *rs = get_remote_state ();
2151
2152 if (remote_multi_process_p (rs))
2153 {
2154 pid = ptid_get_pid (ptid);
2155 if (pid < 0)
2156 buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2157 else
2158 buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2159 }
ba348170 2160 tid = ptid_get_lwp (ptid);
82f73884
PA
2161 if (tid < 0)
2162 buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2163 else
2164 buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2165
2166 return buf;
2167}
2168
2169/* Extract a PTID from BUF. If non-null, OBUF is set to the to one
2170 passed the last parsed char. Returns null_ptid on error. */
2171
2172static ptid_t
2173read_ptid (char *buf, char **obuf)
2174{
2175 char *p = buf;
2176 char *pp;
2177 ULONGEST pid = 0, tid = 0;
82f73884
PA
2178
2179 if (*p == 'p')
2180 {
2181 /* Multi-process ptid. */
2182 pp = unpack_varlen_hex (p + 1, &pid);
2183 if (*pp != '.')
b37520b6 2184 error (_("invalid remote ptid: %s"), p);
82f73884
PA
2185
2186 p = pp;
2187 pp = unpack_varlen_hex (p + 1, &tid);
2188 if (obuf)
2189 *obuf = pp;
ba348170 2190 return ptid_build (pid, tid, 0);
82f73884
PA
2191 }
2192
2193 /* No multi-process. Just a tid. */
2194 pp = unpack_varlen_hex (p, &tid);
2195
c9f35b34
KB
2196 /* Return null_ptid when no thread id is found. */
2197 if (p == pp)
2198 {
2199 if (obuf)
2200 *obuf = pp;
2201 return null_ptid;
2202 }
2203
82f73884 2204 /* Since the stub is not sending a process id, then default to
ca19bf23
PA
2205 what's in inferior_ptid, unless it's null at this point. If so,
2206 then since there's no way to know the pid of the reported
2207 threads, use the magic number. */
2208 if (ptid_equal (inferior_ptid, null_ptid))
2209 pid = ptid_get_pid (magic_null_ptid);
2210 else
2211 pid = ptid_get_pid (inferior_ptid);
82f73884
PA
2212
2213 if (obuf)
2214 *obuf = pp;
ba348170 2215 return ptid_build (pid, tid, 0);
82f73884
PA
2216}
2217
c906108c 2218static int
fba45db2 2219stubhex (int ch)
c906108c
SS
2220{
2221 if (ch >= 'a' && ch <= 'f')
2222 return ch - 'a' + 10;
2223 if (ch >= '0' && ch <= '9')
2224 return ch - '0';
2225 if (ch >= 'A' && ch <= 'F')
2226 return ch - 'A' + 10;
2227 return -1;
2228}
2229
2230static int
fba45db2 2231stub_unpack_int (char *buff, int fieldlength)
c906108c
SS
2232{
2233 int nibble;
2234 int retval = 0;
2235
2236 while (fieldlength)
2237 {
2238 nibble = stubhex (*buff++);
2239 retval |= nibble;
2240 fieldlength--;
2241 if (fieldlength)
2242 retval = retval << 4;
2243 }
2244 return retval;
2245}
2246
c906108c 2247static char *
fba45db2 2248unpack_nibble (char *buf, int *val)
c906108c 2249{
b7589f7d 2250 *val = fromhex (*buf++);
c906108c
SS
2251 return buf;
2252}
2253
c906108c 2254static char *
fba45db2 2255unpack_byte (char *buf, int *value)
c906108c
SS
2256{
2257 *value = stub_unpack_int (buf, 2);
2258 return buf + 2;
2259}
2260
2261static char *
fba45db2 2262pack_int (char *buf, int value)
c906108c
SS
2263{
2264 buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2265 buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2266 buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2267 buf = pack_hex_byte (buf, (value & 0xff));
2268 return buf;
2269}
2270
2271static char *
fba45db2 2272unpack_int (char *buf, int *value)
c906108c
SS
2273{
2274 *value = stub_unpack_int (buf, 8);
2275 return buf + 8;
2276}
2277
23860348 2278#if 0 /* Currently unused, uncomment when needed. */
a14ed312 2279static char *pack_string (char *pkt, char *string);
c906108c
SS
2280
2281static char *
fba45db2 2282pack_string (char *pkt, char *string)
c906108c
SS
2283{
2284 char ch;
2285 int len;
2286
2287 len = strlen (string);
2288 if (len > 200)
23860348 2289 len = 200; /* Bigger than most GDB packets, junk??? */
c906108c
SS
2290 pkt = pack_hex_byte (pkt, len);
2291 while (len-- > 0)
2292 {
2293 ch = *string++;
2294 if ((ch == '\0') || (ch == '#'))
23860348 2295 ch = '*'; /* Protect encapsulation. */
c906108c
SS
2296 *pkt++ = ch;
2297 }
2298 return pkt;
2299}
2300#endif /* 0 (unused) */
2301
2302static char *
fba45db2 2303unpack_string (char *src, char *dest, int length)
c906108c
SS
2304{
2305 while (length--)
2306 *dest++ = *src++;
2307 *dest = '\0';
2308 return src;
2309}
2310
2311static char *
fba45db2 2312pack_threadid (char *pkt, threadref *id)
c906108c
SS
2313{
2314 char *limit;
2315 unsigned char *altid;
2316
2317 altid = (unsigned char *) id;
2318 limit = pkt + BUF_THREAD_ID_SIZE;
2319 while (pkt < limit)
2320 pkt = pack_hex_byte (pkt, *altid++);
2321 return pkt;
2322}
2323
2324
2325static char *
fba45db2 2326unpack_threadid (char *inbuf, threadref *id)
c906108c
SS
2327{
2328 char *altref;
2329 char *limit = inbuf + BUF_THREAD_ID_SIZE;
2330 int x, y;
2331
2332 altref = (char *) id;
2333
2334 while (inbuf < limit)
2335 {
2336 x = stubhex (*inbuf++);
2337 y = stubhex (*inbuf++);
2338 *altref++ = (x << 4) | y;
2339 }
2340 return inbuf;
2341}
2342
2343/* Externally, threadrefs are 64 bits but internally, they are still
0df8b418 2344 ints. This is due to a mismatch of specifications. We would like
c906108c
SS
2345 to use 64bit thread references internally. This is an adapter
2346 function. */
2347
2348void
fba45db2 2349int_to_threadref (threadref *id, int value)
c906108c
SS
2350{
2351 unsigned char *scan;
2352
2353 scan = (unsigned char *) id;
2354 {
2355 int i = 4;
2356 while (i--)
2357 *scan++ = 0;
2358 }
2359 *scan++ = (value >> 24) & 0xff;
2360 *scan++ = (value >> 16) & 0xff;
2361 *scan++ = (value >> 8) & 0xff;
2362 *scan++ = (value & 0xff);
2363}
2364
2365static int
fba45db2 2366threadref_to_int (threadref *ref)
c906108c
SS
2367{
2368 int i, value = 0;
2369 unsigned char *scan;
2370
cfd77fa1 2371 scan = *ref;
c906108c
SS
2372 scan += 4;
2373 i = 4;
2374 while (i-- > 0)
2375 value = (value << 8) | ((*scan++) & 0xff);
2376 return value;
2377}
2378
2379static void
fba45db2 2380copy_threadref (threadref *dest, threadref *src)
c906108c
SS
2381{
2382 int i;
2383 unsigned char *csrc, *cdest;
2384
2385 csrc = (unsigned char *) src;
2386 cdest = (unsigned char *) dest;
2387 i = 8;
2388 while (i--)
2389 *cdest++ = *csrc++;
2390}
2391
2392static int
fba45db2 2393threadmatch (threadref *dest, threadref *src)
c906108c 2394{
23860348 2395 /* Things are broken right now, so just assume we got a match. */
c906108c
SS
2396#if 0
2397 unsigned char *srcp, *destp;
2398 int i, result;
2399 srcp = (char *) src;
2400 destp = (char *) dest;
2401
2402 result = 1;
2403 while (i-- > 0)
2404 result &= (*srcp++ == *destp++) ? 1 : 0;
2405 return result;
2406#endif
2407 return 1;
2408}
2409
2410/*
c5aa993b
JM
2411 threadid:1, # always request threadid
2412 context_exists:2,
2413 display:4,
2414 unique_name:8,
2415 more_display:16
2416 */
c906108c
SS
2417
2418/* Encoding: 'Q':8,'P':8,mask:32,threadid:64 */
2419
2420static char *
fba45db2 2421pack_threadinfo_request (char *pkt, int mode, threadref *id)
c906108c 2422{
23860348
MS
2423 *pkt++ = 'q'; /* Info Query */
2424 *pkt++ = 'P'; /* process or thread info */
2425 pkt = pack_int (pkt, mode); /* mode */
c906108c 2426 pkt = pack_threadid (pkt, id); /* threadid */
23860348 2427 *pkt = '\0'; /* terminate */
c906108c
SS
2428 return pkt;
2429}
2430
23860348 2431/* These values tag the fields in a thread info response packet. */
c906108c 2432/* Tagging the fields allows us to request specific fields and to
23860348 2433 add more fields as time goes by. */
c906108c 2434
23860348 2435#define TAG_THREADID 1 /* Echo the thread identifier. */
c5aa993b 2436#define TAG_EXISTS 2 /* Is this process defined enough to
23860348 2437 fetch registers and its stack? */
c5aa993b 2438#define TAG_DISPLAY 4 /* A short thing maybe to put on a window */
23860348 2439#define TAG_THREADNAME 8 /* string, maps 1-to-1 with a thread is. */
802188a7 2440#define TAG_MOREDISPLAY 16 /* Whatever the kernel wants to say about
23860348 2441 the process. */
c906108c
SS
2442
2443static int
fba45db2
KB
2444remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2445 struct gdb_ext_thread_info *info)
c906108c 2446{
d01949b6 2447 struct remote_state *rs = get_remote_state ();
c906108c 2448 int mask, length;
cfd77fa1 2449 int tag;
c906108c 2450 threadref ref;
6d820c5c 2451 char *limit = pkt + rs->buf_size; /* Plausible parsing limit. */
c906108c
SS
2452 int retval = 1;
2453
23860348 2454 /* info->threadid = 0; FIXME: implement zero_threadref. */
c906108c
SS
2455 info->active = 0;
2456 info->display[0] = '\0';
2457 info->shortname[0] = '\0';
2458 info->more_display[0] = '\0';
2459
23860348
MS
2460 /* Assume the characters indicating the packet type have been
2461 stripped. */
c906108c
SS
2462 pkt = unpack_int (pkt, &mask); /* arg mask */
2463 pkt = unpack_threadid (pkt, &ref);
2464
2465 if (mask == 0)
8a3fe4f8 2466 warning (_("Incomplete response to threadinfo request."));
c906108c 2467 if (!threadmatch (&ref, expectedref))
23860348 2468 { /* This is an answer to a different request. */
8a3fe4f8 2469 warning (_("ERROR RMT Thread info mismatch."));
c906108c
SS
2470 return 0;
2471 }
2472 copy_threadref (&info->threadid, &ref);
2473
23860348 2474 /* Loop on tagged fields , try to bail if somthing goes wrong. */
c906108c 2475
23860348
MS
2476 /* Packets are terminated with nulls. */
2477 while ((pkt < limit) && mask && *pkt)
c906108c
SS
2478 {
2479 pkt = unpack_int (pkt, &tag); /* tag */
23860348
MS
2480 pkt = unpack_byte (pkt, &length); /* length */
2481 if (!(tag & mask)) /* Tags out of synch with mask. */
c906108c 2482 {
8a3fe4f8 2483 warning (_("ERROR RMT: threadinfo tag mismatch."));
c906108c
SS
2484 retval = 0;
2485 break;
2486 }
2487 if (tag == TAG_THREADID)
2488 {
2489 if (length != 16)
2490 {
8a3fe4f8 2491 warning (_("ERROR RMT: length of threadid is not 16."));
c906108c
SS
2492 retval = 0;
2493 break;
2494 }
2495 pkt = unpack_threadid (pkt, &ref);
2496 mask = mask & ~TAG_THREADID;
2497 continue;
2498 }
2499 if (tag == TAG_EXISTS)
2500 {
2501 info->active = stub_unpack_int (pkt, length);
2502 pkt += length;
2503 mask = mask & ~(TAG_EXISTS);
2504 if (length > 8)
2505 {
8a3fe4f8 2506 warning (_("ERROR RMT: 'exists' length too long."));
c906108c
SS
2507 retval = 0;
2508 break;
2509 }
2510 continue;
2511 }
2512 if (tag == TAG_THREADNAME)
2513 {
2514 pkt = unpack_string (pkt, &info->shortname[0], length);
2515 mask = mask & ~TAG_THREADNAME;
2516 continue;
2517 }
2518 if (tag == TAG_DISPLAY)
2519 {
2520 pkt = unpack_string (pkt, &info->display[0], length);
2521 mask = mask & ~TAG_DISPLAY;
2522 continue;
2523 }
2524 if (tag == TAG_MOREDISPLAY)
2525 {
2526 pkt = unpack_string (pkt, &info->more_display[0], length);
2527 mask = mask & ~TAG_MOREDISPLAY;
2528 continue;
2529 }
8a3fe4f8 2530 warning (_("ERROR RMT: unknown thread info tag."));
23860348 2531 break; /* Not a tag we know about. */
c906108c
SS
2532 }
2533 return retval;
2534}
2535
2536static int
fba45db2
KB
2537remote_get_threadinfo (threadref *threadid, int fieldset, /* TAG mask */
2538 struct gdb_ext_thread_info *info)
c906108c 2539{
d01949b6 2540 struct remote_state *rs = get_remote_state ();
c906108c 2541 int result;
c906108c 2542
2e9f7625
DJ
2543 pack_threadinfo_request (rs->buf, fieldset, threadid);
2544 putpkt (rs->buf);
6d820c5c 2545 getpkt (&rs->buf, &rs->buf_size, 0);
3084dd77
PA
2546
2547 if (rs->buf[0] == '\0')
2548 return 0;
2549
2e9f7625 2550 result = remote_unpack_thread_info_response (rs->buf + 2,
23860348 2551 threadid, info);
c906108c
SS
2552 return result;
2553}
2554
c906108c
SS
2555/* Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32 */
2556
2557static char *
fba45db2
KB
2558pack_threadlist_request (char *pkt, int startflag, int threadcount,
2559 threadref *nextthread)
c906108c
SS
2560{
2561 *pkt++ = 'q'; /* info query packet */
2562 *pkt++ = 'L'; /* Process LIST or threadLIST request */
23860348 2563 pkt = pack_nibble (pkt, startflag); /* initflag 1 bytes */
c906108c
SS
2564 pkt = pack_hex_byte (pkt, threadcount); /* threadcount 2 bytes */
2565 pkt = pack_threadid (pkt, nextthread); /* 64 bit thread identifier */
2566 *pkt = '\0';
2567 return pkt;
2568}
2569
2570/* Encoding: 'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2571
2572static int
fba45db2
KB
2573parse_threadlist_response (char *pkt, int result_limit,
2574 threadref *original_echo, threadref *resultlist,
2575 int *doneflag)
c906108c 2576{
d01949b6 2577 struct remote_state *rs = get_remote_state ();
c906108c
SS
2578 char *limit;
2579 int count, resultcount, done;
2580
2581 resultcount = 0;
2582 /* Assume the 'q' and 'M chars have been stripped. */
6d820c5c 2583 limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
23860348 2584 /* done parse past here */
c906108c
SS
2585 pkt = unpack_byte (pkt, &count); /* count field */
2586 pkt = unpack_nibble (pkt, &done);
2587 /* The first threadid is the argument threadid. */
2588 pkt = unpack_threadid (pkt, original_echo); /* should match query packet */
2589 while ((count-- > 0) && (pkt < limit))
2590 {
2591 pkt = unpack_threadid (pkt, resultlist++);
2592 if (resultcount++ >= result_limit)
2593 break;
2594 }
2595 if (doneflag)
2596 *doneflag = done;
2597 return resultcount;
2598}
2599
6dc54d91
PA
2600/* Fetch the next batch of threads from the remote. Returns -1 if the
2601 qL packet is not supported, 0 on error and 1 on success. */
2602
c906108c 2603static int
fba45db2
KB
2604remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2605 int *done, int *result_count, threadref *threadlist)
c906108c 2606{
d01949b6 2607 struct remote_state *rs = get_remote_state ();
c906108c
SS
2608 int result = 1;
2609
23860348 2610 /* Trancate result limit to be smaller than the packet size. */
3e43a32a
MS
2611 if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2612 >= get_remote_packet_size ())
ea9c271d 2613 result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
c906108c 2614
6d820c5c
DJ
2615 pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2616 putpkt (rs->buf);
2617 getpkt (&rs->buf, &rs->buf_size, 0);
d8f2712d 2618 if (*rs->buf == '\0')
6dc54d91
PA
2619 {
2620 /* Packet not supported. */
2621 return -1;
2622 }
2623
2624 *result_count =
2625 parse_threadlist_response (rs->buf + 2, result_limit,
2626 &rs->echo_nextthread, threadlist, done);
c906108c 2627
0d031856 2628 if (!threadmatch (&rs->echo_nextthread, nextthread))
c906108c 2629 {
23860348
MS
2630 /* FIXME: This is a good reason to drop the packet. */
2631 /* Possably, there is a duplicate response. */
c906108c
SS
2632 /* Possabilities :
2633 retransmit immediatly - race conditions
2634 retransmit after timeout - yes
2635 exit
2636 wait for packet, then exit
2637 */
8a3fe4f8 2638 warning (_("HMM: threadlist did not echo arg thread, dropping it."));
23860348 2639 return 0; /* I choose simply exiting. */
c906108c
SS
2640 }
2641 if (*result_count <= 0)
2642 {
2643 if (*done != 1)
2644 {
8a3fe4f8 2645 warning (_("RMT ERROR : failed to get remote thread list."));
c906108c
SS
2646 result = 0;
2647 }
2648 return result; /* break; */
2649 }
2650 if (*result_count > result_limit)
2651 {
2652 *result_count = 0;
8a3fe4f8 2653 warning (_("RMT ERROR: threadlist response longer than requested."));
c906108c
SS
2654 return 0;
2655 }
2656 return result;
2657}
2658
6dc54d91
PA
2659/* Fetch the list of remote threads, with the qL packet, and call
2660 STEPFUNCTION for each thread found. Stops iterating and returns 1
2661 if STEPFUNCTION returns true. Stops iterating and returns 0 if the
2662 STEPFUNCTION returns false. If the packet is not supported,
2663 returns -1. */
c906108c 2664
c906108c 2665static int
fba45db2
KB
2666remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2667 int looplimit)
c906108c 2668{
0d031856 2669 struct remote_state *rs = get_remote_state ();
c906108c
SS
2670 int done, i, result_count;
2671 int startflag = 1;
2672 int result = 1;
2673 int loopcount = 0;
c906108c
SS
2674
2675 done = 0;
2676 while (!done)
2677 {
2678 if (loopcount++ > looplimit)
2679 {
2680 result = 0;
8a3fe4f8 2681 warning (_("Remote fetch threadlist -infinite loop-."));
c906108c
SS
2682 break;
2683 }
6dc54d91
PA
2684 result = remote_get_threadlist (startflag, &rs->nextthread,
2685 MAXTHREADLISTRESULTS,
2686 &done, &result_count,
2687 rs->resultthreadlist);
2688 if (result <= 0)
2689 break;
23860348 2690 /* Clear for later iterations. */
c906108c
SS
2691 startflag = 0;
2692 /* Setup to resume next batch of thread references, set nextthread. */
2693 if (result_count >= 1)
0d031856
TT
2694 copy_threadref (&rs->nextthread,
2695 &rs->resultthreadlist[result_count - 1]);
c906108c
SS
2696 i = 0;
2697 while (result_count--)
6dc54d91
PA
2698 {
2699 if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2700 {
2701 result = 0;
2702 break;
2703 }
2704 }
c906108c
SS
2705 }
2706 return result;
2707}
2708
6dc54d91
PA
2709/* A thread found on the remote target. */
2710
2711typedef struct thread_item
2712{
2713 /* The thread's PTID. */
2714 ptid_t ptid;
2715
2716 /* The thread's extra info. May be NULL. */
2717 char *extra;
2718
2719 /* The core the thread was running on. -1 if not known. */
2720 int core;
2721} thread_item_t;
2722DEF_VEC_O(thread_item_t);
2723
2724/* Context passed around to the various methods listing remote
2725 threads. As new threads are found, they're added to the ITEMS
2726 vector. */
2727
2728struct threads_listing_context
2729{
2730 /* The threads found on the remote target. */
2731 VEC (thread_item_t) *items;
2732};
2733
80134cf5
PA
2734/* Discard the contents of the constructed thread listing context. */
2735
2736static void
2737clear_threads_listing_context (void *p)
2738{
2739 struct threads_listing_context *context = p;
2740 int i;
2741 struct thread_item *item;
2742
2743 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2744 xfree (item->extra);
2745
2746 VEC_free (thread_item_t, context->items);
2747}
2748
cbb8991c
DB
2749/* Remove the thread specified as the related_pid field of WS
2750 from the CONTEXT list. */
2751
2752static void
2753threads_listing_context_remove (struct target_waitstatus *ws,
2754 struct threads_listing_context *context)
2755{
2756 struct thread_item *item;
2757 int i;
2758 ptid_t child_ptid = ws->value.related_pid;
2759
2760 for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2761 {
2762 if (ptid_equal (item->ptid, child_ptid))
2763 {
2764 VEC_ordered_remove (thread_item_t, context->items, i);
2765 break;
2766 }
2767 }
2768}
2769
c906108c 2770static int
6dc54d91 2771remote_newthread_step (threadref *ref, void *data)
c906108c 2772{
6dc54d91
PA
2773 struct threads_listing_context *context = data;
2774 struct thread_item item;
79d7f229 2775 int pid = ptid_get_pid (inferior_ptid);
39f77062 2776
6dc54d91
PA
2777 item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2778 item.core = -1;
2779 item.extra = NULL;
2780
2781 VEC_safe_push (thread_item_t, context->items, &item);
2782
c906108c
SS
2783 return 1; /* continue iterator */
2784}
2785
2786#define CRAZY_MAX_THREADS 1000
2787
39f77062
KB
2788static ptid_t
2789remote_current_thread (ptid_t oldpid)
c906108c 2790{
d01949b6 2791 struct remote_state *rs = get_remote_state ();
c906108c
SS
2792
2793 putpkt ("qC");
6d820c5c 2794 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2795 if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
c9f35b34
KB
2796 {
2797 char *obuf;
2798 ptid_t result;
2799
2800 result = read_ptid (&rs->buf[2], &obuf);
2801 if (*obuf != '\0' && remote_debug)
2802 fprintf_unfiltered (gdb_stdlog,
2803 "warning: garbage in qC reply\n");
2804
2805 return result;
2806 }
c906108c
SS
2807 else
2808 return oldpid;
2809}
2810
6dc54d91 2811/* List remote threads using the deprecated qL packet. */
cce74817 2812
6dc54d91
PA
2813static int
2814remote_get_threads_with_ql (struct target_ops *ops,
2815 struct threads_listing_context *context)
c906108c 2816{
6dc54d91
PA
2817 if (remote_threadlist_iterator (remote_newthread_step, context,
2818 CRAZY_MAX_THREADS) >= 0)
2819 return 1;
2820
2821 return 0;
c906108c
SS
2822}
2823
dc146f7c
VP
2824#if defined(HAVE_LIBEXPAT)
2825
dc146f7c
VP
2826static void
2827start_thread (struct gdb_xml_parser *parser,
2828 const struct gdb_xml_element *element,
2829 void *user_data, VEC(gdb_xml_value_s) *attributes)
2830{
6dc54d91 2831 struct threads_listing_context *data = user_data;
dc146f7c
VP
2832
2833 struct thread_item item;
2834 char *id;
3d2c1d41 2835 struct gdb_xml_value *attr;
dc146f7c 2836
3d2c1d41 2837 id = xml_find_attribute (attributes, "id")->value;
dc146f7c
VP
2838 item.ptid = read_ptid (id, NULL);
2839
3d2c1d41
PA
2840 attr = xml_find_attribute (attributes, "core");
2841 if (attr != NULL)
2842 item.core = *(ULONGEST *) attr->value;
dc146f7c
VP
2843 else
2844 item.core = -1;
2845
2846 item.extra = 0;
2847
2848 VEC_safe_push (thread_item_t, data->items, &item);
2849}
2850
2851static void
2852end_thread (struct gdb_xml_parser *parser,
2853 const struct gdb_xml_element *element,
2854 void *user_data, const char *body_text)
2855{
6dc54d91 2856 struct threads_listing_context *data = user_data;
dc146f7c
VP
2857
2858 if (body_text && *body_text)
2ae2a0b7 2859 VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
dc146f7c
VP
2860}
2861
2862const struct gdb_xml_attribute thread_attributes[] = {
2863 { "id", GDB_XML_AF_NONE, NULL, NULL },
2864 { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2865 { NULL, GDB_XML_AF_NONE, NULL, NULL }
2866};
2867
2868const struct gdb_xml_element thread_children[] = {
2869 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2870};
2871
2872const struct gdb_xml_element threads_children[] = {
2873 { "thread", thread_attributes, thread_children,
2874 GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2875 start_thread, end_thread },
2876 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2877};
2878
2879const struct gdb_xml_element threads_elements[] = {
2880 { "threads", NULL, threads_children,
2881 GDB_XML_EF_NONE, NULL, NULL },
2882 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2883};
2884
2885#endif
2886
6dc54d91 2887/* List remote threads using qXfer:threads:read. */
9d1f7ab2 2888
6dc54d91
PA
2889static int
2890remote_get_threads_with_qxfer (struct target_ops *ops,
2891 struct threads_listing_context *context)
0f71a2f6 2892{
dc146f7c 2893#if defined(HAVE_LIBEXPAT)
4082afcc 2894 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c 2895 {
6dc54d91 2896 char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
dc146f7c 2897 struct cleanup *back_to = make_cleanup (xfree, xml);
efc0eabd 2898
6dc54d91 2899 if (xml != NULL && *xml != '\0')
dc146f7c 2900 {
6dc54d91
PA
2901 gdb_xml_parse_quick (_("threads"), "threads.dtd",
2902 threads_elements, xml, context);
dc146f7c
VP
2903 }
2904
2905 do_cleanups (back_to);
6dc54d91 2906 return 1;
dc146f7c
VP
2907 }
2908#endif
2909
6dc54d91
PA
2910 return 0;
2911}
2912
2913/* List remote threads using qfThreadInfo/qsThreadInfo. */
2914
2915static int
2916remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2917 struct threads_listing_context *context)
2918{
2919 struct remote_state *rs = get_remote_state ();
2920
b80fafe3 2921 if (rs->use_threadinfo_query)
9d1f7ab2 2922 {
6dc54d91
PA
2923 char *bufp;
2924
9d1f7ab2 2925 putpkt ("qfThreadInfo");
6d820c5c 2926 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 2927 bufp = rs->buf;
9d1f7ab2 2928 if (bufp[0] != '\0') /* q packet recognized */
802188a7 2929 {
9d1f7ab2
MS
2930 while (*bufp++ == 'm') /* reply contains one or more TID */
2931 {
2932 do
2933 {
6dc54d91
PA
2934 struct thread_item item;
2935
2936 item.ptid = read_ptid (bufp, &bufp);
2937 item.core = -1;
2938 item.extra = NULL;
2939
2940 VEC_safe_push (thread_item_t, context->items, &item);
9d1f7ab2
MS
2941 }
2942 while (*bufp++ == ','); /* comma-separated list */
2943 putpkt ("qsThreadInfo");
6d820c5c 2944 getpkt (&rs->buf, &rs->buf_size, 0);
6dc54d91 2945 bufp = rs->buf;
9d1f7ab2 2946 }
6dc54d91
PA
2947 return 1;
2948 }
2949 else
2950 {
2951 /* Packet not recognized. */
2952 rs->use_threadinfo_query = 0;
9d1f7ab2
MS
2953 }
2954 }
2955
6dc54d91
PA
2956 return 0;
2957}
2958
e8032dde 2959/* Implement the to_update_thread_list function for the remote
6dc54d91
PA
2960 targets. */
2961
2962static void
e8032dde 2963remote_update_thread_list (struct target_ops *ops)
6dc54d91
PA
2964{
2965 struct remote_state *rs = get_remote_state ();
2966 struct threads_listing_context context;
2967 struct cleanup *old_chain;
ab970af1 2968 int got_list = 0;
e8032dde 2969
6dc54d91
PA
2970 context.items = NULL;
2971 old_chain = make_cleanup (clear_threads_listing_context, &context);
2972
2973 /* We have a few different mechanisms to fetch the thread list. Try
2974 them all, starting with the most preferred one first, falling
2975 back to older methods. */
2976 if (remote_get_threads_with_qxfer (ops, &context)
2977 || remote_get_threads_with_qthreadinfo (ops, &context)
2978 || remote_get_threads_with_ql (ops, &context))
2979 {
2980 int i;
2981 struct thread_item *item;
ab970af1
PA
2982 struct thread_info *tp, *tmp;
2983
2984 got_list = 1;
2985
7d1a114c
PA
2986 if (VEC_empty (thread_item_t, context.items)
2987 && remote_thread_always_alive (ops, inferior_ptid))
2988 {
2989 /* Some targets don't really support threads, but still
2990 reply an (empty) thread list in response to the thread
2991 listing packets, instead of replying "packet not
2992 supported". Exit early so we don't delete the main
2993 thread. */
2994 do_cleanups (old_chain);
2995 return;
2996 }
2997
ab970af1
PA
2998 /* CONTEXT now holds the current thread list on the remote
2999 target end. Delete GDB-side threads no longer found on the
3000 target. */
8a06aea7 3001 ALL_THREADS_SAFE (tp, tmp)
cbb8991c 3002 {
ab970af1
PA
3003 for (i = 0;
3004 VEC_iterate (thread_item_t, context.items, i, item);
3005 ++i)
3006 {
3007 if (ptid_equal (item->ptid, tp->ptid))
3008 break;
3009 }
3010
3011 if (i == VEC_length (thread_item_t, context.items))
3012 {
3013 /* Not found. */
3014 delete_thread (tp->ptid);
3015 }
cbb8991c
DB
3016 }
3017
3018 /* Remove any unreported fork child threads from CONTEXT so
3019 that we don't interfere with follow fork, which is where
3020 creation of such threads is handled. */
3021 remove_new_fork_children (&context);
74531fed 3022
ab970af1 3023 /* And now add threads we don't know about yet to our list. */
6dc54d91
PA
3024 for (i = 0;
3025 VEC_iterate (thread_item_t, context.items, i, item);
3026 ++i)
3027 {
3028 if (!ptid_equal (item->ptid, null_ptid))
3029 {
3030 struct private_thread_info *info;
3031 /* In non-stop mode, we assume new found threads are
3032 running until proven otherwise with a stop reply. In
3033 all-stop, we can only get here if all threads are
3034 stopped. */
3035 int running = non_stop ? 1 : 0;
3036
3037 remote_notice_new_inferior (item->ptid, running);
3038
3039 info = demand_private_info (item->ptid);
3040 info->core = item->core;
3041 info->extra = item->extra;
3042 item->extra = NULL;
3043 }
3044 }
3045 }
3046
ab970af1
PA
3047 if (!got_list)
3048 {
3049 /* If no thread listing method is supported, then query whether
3050 each known thread is alive, one by one, with the T packet.
3051 If the target doesn't support threads at all, then this is a
3052 no-op. See remote_thread_alive. */
3053 prune_threads ();
3054 }
3055
6dc54d91 3056 do_cleanups (old_chain);
9d1f7ab2
MS
3057}
3058
802188a7 3059/*
9d1f7ab2
MS
3060 * Collect a descriptive string about the given thread.
3061 * The target may say anything it wants to about the thread
3062 * (typically info about its blocked / runnable state, name, etc.).
3063 * This string will appear in the info threads display.
802188a7 3064 *
9d1f7ab2
MS
3065 * Optional: targets are not required to implement this function.
3066 */
3067
3068static char *
c15906d8 3069remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
9d1f7ab2 3070{
d01949b6 3071 struct remote_state *rs = get_remote_state ();
9d1f7ab2
MS
3072 int result;
3073 int set;
3074 threadref id;
3075 struct gdb_ext_thread_info threadinfo;
23860348 3076 static char display_buf[100]; /* arbitrary... */
9d1f7ab2
MS
3077 int n = 0; /* position in display_buf */
3078
5d93a237 3079 if (rs->remote_desc == 0) /* paranoia */
8e65ff28 3080 internal_error (__FILE__, __LINE__,
e2e0b3e5 3081 _("remote_threads_extra_info"));
9d1f7ab2 3082
60e569b9 3083 if (ptid_equal (tp->ptid, magic_null_ptid)
ba348170 3084 || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
60e569b9
PA
3085 /* This is the main thread which was added by GDB. The remote
3086 server doesn't know about it. */
3087 return NULL;
3088
4082afcc 3089 if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
dc146f7c
VP
3090 {
3091 struct thread_info *info = find_thread_ptid (tp->ptid);
a744cf53 3092
fe978cb0
PA
3093 if (info && info->priv)
3094 return info->priv->extra;
dc146f7c
VP
3095 else
3096 return NULL;
3097 }
3098
b80fafe3 3099 if (rs->use_threadextra_query)
9d1f7ab2 3100 {
82f73884
PA
3101 char *b = rs->buf;
3102 char *endb = rs->buf + get_remote_packet_size ();
3103
3104 xsnprintf (b, endb - b, "qThreadExtraInfo,");
3105 b += strlen (b);
3106 write_ptid (b, endb, tp->ptid);
3107
2e9f7625 3108 putpkt (rs->buf);
6d820c5c 3109 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3110 if (rs->buf[0] != 0)
9d1f7ab2 3111 {
2e9f7625
DJ
3112 n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3113 result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
30559e10 3114 display_buf [result] = '\0';
9d1f7ab2
MS
3115 return display_buf;
3116 }
0f71a2f6 3117 }
9d1f7ab2
MS
3118
3119 /* If the above query fails, fall back to the old method. */
b80fafe3 3120 rs->use_threadextra_query = 0;
9d1f7ab2
MS
3121 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3122 | TAG_MOREDISPLAY | TAG_DISPLAY;
ba348170 3123 int_to_threadref (&id, ptid_get_lwp (tp->ptid));
9d1f7ab2
MS
3124 if (remote_get_threadinfo (&id, set, &threadinfo))
3125 if (threadinfo.active)
0f71a2f6 3126 {
9d1f7ab2 3127 if (*threadinfo.shortname)
2bc416ba 3128 n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
ecbc58df 3129 " Name: %s,", threadinfo.shortname);
9d1f7ab2 3130 if (*threadinfo.display)
2bc416ba 3131 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3132 " State: %s,", threadinfo.display);
9d1f7ab2 3133 if (*threadinfo.more_display)
2bc416ba 3134 n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
ecbc58df 3135 " Priority: %s", threadinfo.more_display);
9d1f7ab2
MS
3136
3137 if (n > 0)
c5aa993b 3138 {
23860348 3139 /* For purely cosmetic reasons, clear up trailing commas. */
9d1f7ab2
MS
3140 if (',' == display_buf[n-1])
3141 display_buf[n-1] = ' ';
3142 return display_buf;
c5aa993b 3143 }
0f71a2f6 3144 }
9d1f7ab2 3145 return NULL;
0f71a2f6 3146}
c906108c 3147\f
c5aa993b 3148
0fb4aa4b 3149static int
61fc905d 3150remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
0fb4aa4b
PA
3151 struct static_tracepoint_marker *marker)
3152{
3153 struct remote_state *rs = get_remote_state ();
3154 char *p = rs->buf;
3155
bba74b36 3156 xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
0fb4aa4b
PA
3157 p += strlen (p);
3158 p += hexnumstr (p, addr);
3159 putpkt (rs->buf);
3160 getpkt (&rs->buf, &rs->buf_size, 0);
3161 p = rs->buf;
3162
3163 if (*p == 'E')
3164 error (_("Remote failure reply: %s"), p);
3165
3166 if (*p++ == 'm')
3167 {
3168 parse_static_tracepoint_marker_definition (p, &p, marker);
3169 return 1;
3170 }
3171
3172 return 0;
3173}
3174
0fb4aa4b 3175static VEC(static_tracepoint_marker_p) *
c686c57f
TT
3176remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3177 const char *strid)
0fb4aa4b
PA
3178{
3179 struct remote_state *rs = get_remote_state ();
3180 VEC(static_tracepoint_marker_p) *markers = NULL;
3181 struct static_tracepoint_marker *marker = NULL;
3182 struct cleanup *old_chain;
3183 char *p;
3184
3185 /* Ask for a first packet of static tracepoint marker
3186 definition. */
3187 putpkt ("qTfSTM");
3188 getpkt (&rs->buf, &rs->buf_size, 0);
3189 p = rs->buf;
3190 if (*p == 'E')
3191 error (_("Remote failure reply: %s"), p);
3192
3193 old_chain = make_cleanup (free_current_marker, &marker);
3194
3195 while (*p++ == 'm')
3196 {
3197 if (marker == NULL)
3198 marker = XCNEW (struct static_tracepoint_marker);
3199
3200 do
3201 {
3202 parse_static_tracepoint_marker_definition (p, &p, marker);
3203
3204 if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3205 {
3206 VEC_safe_push (static_tracepoint_marker_p,
3207 markers, marker);
3208 marker = NULL;
3209 }
3210 else
3211 {
3212 release_static_tracepoint_marker (marker);
3213 memset (marker, 0, sizeof (*marker));
3214 }
3215 }
3216 while (*p++ == ','); /* comma-separated list */
3217 /* Ask for another packet of static tracepoint definition. */
3218 putpkt ("qTsSTM");
3219 getpkt (&rs->buf, &rs->buf_size, 0);
3220 p = rs->buf;
3221 }
3222
3223 do_cleanups (old_chain);
3224 return markers;
3225}
3226
3227\f
10760264
JB
3228/* Implement the to_get_ada_task_ptid function for the remote targets. */
3229
3230static ptid_t
1e6b91a4 3231remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
10760264 3232{
ba348170 3233 return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
10760264
JB
3234}
3235\f
3236
24b06219 3237/* Restart the remote side; this is an extended protocol operation. */
c906108c
SS
3238
3239static void
fba45db2 3240extended_remote_restart (void)
c906108c 3241{
d01949b6 3242 struct remote_state *rs = get_remote_state ();
c906108c
SS
3243
3244 /* Send the restart command; for reasons I don't understand the
3245 remote side really expects a number after the "R". */
ea9c271d 3246 xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
6d820c5c 3247 putpkt (rs->buf);
c906108c 3248
ad9a8f3f 3249 remote_fileio_reset ();
c906108c
SS
3250}
3251\f
3252/* Clean up connection to a remote debugger. */
3253
c906108c 3254static void
de90e03d 3255remote_close (struct target_ops *self)
c906108c 3256{
5d93a237
TT
3257 struct remote_state *rs = get_remote_state ();
3258
3259 if (rs->remote_desc == NULL)
d3fd5342
PA
3260 return; /* already closed */
3261
3262 /* Make sure we leave stdin registered in the event loop, and we
3263 don't leave the async SIGINT signal handler installed. */
e3594fd1 3264 remote_terminal_ours (self);
ce5ce7ed 3265
5d93a237
TT
3266 serial_close (rs->remote_desc);
3267 rs->remote_desc = NULL;
ce5ce7ed
PA
3268
3269 /* We don't have a connection to the remote stub anymore. Get rid
f67fd822
PM
3270 of all the inferiors and their threads we were controlling.
3271 Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3272 will be unable to find the thread corresponding to (pid, 0, 0). */
0f2caa1b 3273 inferior_ptid = null_ptid;
f67fd822 3274 discard_all_inferiors ();
ce5ce7ed 3275
f48ff2a7
YQ
3276 /* We are closing the remote target, so we should discard
3277 everything of this target. */
bcc75809 3278 discard_pending_stop_replies_in_queue (rs);
74531fed
PA
3279
3280 if (remote_async_inferior_event_token)
3281 delete_async_event_handler (&remote_async_inferior_event_token);
722247f1 3282
5965e028 3283 remote_notif_state_xfree (rs->notif_state);
aef525cb
YQ
3284
3285 trace_reset_local_state ();
c906108c
SS
3286}
3287
23860348 3288/* Query the remote side for the text, data and bss offsets. */
c906108c
SS
3289
3290static void
fba45db2 3291get_offsets (void)
c906108c 3292{
d01949b6 3293 struct remote_state *rs = get_remote_state ();
2e9f7625 3294 char *buf;
085dd6e6 3295 char *ptr;
31d99776
DJ
3296 int lose, num_segments = 0, do_sections, do_segments;
3297 CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
c906108c 3298 struct section_offsets *offs;
31d99776
DJ
3299 struct symfile_segment_data *data;
3300
3301 if (symfile_objfile == NULL)
3302 return;
c906108c
SS
3303
3304 putpkt ("qOffsets");
6d820c5c 3305 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 3306 buf = rs->buf;
c906108c
SS
3307
3308 if (buf[0] == '\000')
3309 return; /* Return silently. Stub doesn't support
23860348 3310 this command. */
c906108c
SS
3311 if (buf[0] == 'E')
3312 {
8a3fe4f8 3313 warning (_("Remote failure reply: %s"), buf);
c906108c
SS
3314 return;
3315 }
3316
3317 /* Pick up each field in turn. This used to be done with scanf, but
3318 scanf will make trouble if CORE_ADDR size doesn't match
3319 conversion directives correctly. The following code will work
3320 with any size of CORE_ADDR. */
3321 text_addr = data_addr = bss_addr = 0;
3322 ptr = buf;
3323 lose = 0;
3324
61012eef 3325 if (startswith (ptr, "Text="))
c906108c
SS
3326 {
3327 ptr += 5;
3328 /* Don't use strtol, could lose on big values. */
3329 while (*ptr && *ptr != ';')
3330 text_addr = (text_addr << 4) + fromhex (*ptr++);
c906108c 3331
61012eef 3332 if (startswith (ptr, ";Data="))
31d99776
DJ
3333 {
3334 ptr += 6;
3335 while (*ptr && *ptr != ';')
3336 data_addr = (data_addr << 4) + fromhex (*ptr++);
3337 }
3338 else
3339 lose = 1;
3340
61012eef 3341 if (!lose && startswith (ptr, ";Bss="))
31d99776
DJ
3342 {
3343 ptr += 5;
3344 while (*ptr && *ptr != ';')
3345 bss_addr = (bss_addr << 4) + fromhex (*ptr++);
c906108c 3346
31d99776
DJ
3347 if (bss_addr != data_addr)
3348 warning (_("Target reported unsupported offsets: %s"), buf);
3349 }
3350 else
3351 lose = 1;
3352 }
61012eef 3353 else if (startswith (ptr, "TextSeg="))
c906108c 3354 {
31d99776
DJ
3355 ptr += 8;
3356 /* Don't use strtol, could lose on big values. */
c906108c 3357 while (*ptr && *ptr != ';')
31d99776
DJ
3358 text_addr = (text_addr << 4) + fromhex (*ptr++);
3359 num_segments = 1;
3360
61012eef 3361 if (startswith (ptr, ";DataSeg="))
31d99776
DJ
3362 {
3363 ptr += 9;
3364 while (*ptr && *ptr != ';')
3365 data_addr = (data_addr << 4) + fromhex (*ptr++);
3366 num_segments++;
3367 }
c906108c
SS
3368 }
3369 else
3370 lose = 1;
3371
3372 if (lose)
8a3fe4f8 3373 error (_("Malformed response to offset query, %s"), buf);
31d99776
DJ
3374 else if (*ptr != '\0')
3375 warning (_("Target reported unsupported offsets: %s"), buf);
c906108c 3376
802188a7 3377 offs = ((struct section_offsets *)
a39a16c4 3378 alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
802188a7 3379 memcpy (offs, symfile_objfile->section_offsets,
a39a16c4 3380 SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
c906108c 3381
31d99776
DJ
3382 data = get_symfile_segment_data (symfile_objfile->obfd);
3383 do_segments = (data != NULL);
3384 do_sections = num_segments == 0;
c906108c 3385
28c32713 3386 if (num_segments > 0)
31d99776 3387 {
31d99776
DJ
3388 segments[0] = text_addr;
3389 segments[1] = data_addr;
3390 }
28c32713
JB
3391 /* If we have two segments, we can still try to relocate everything
3392 by assuming that the .text and .data offsets apply to the whole
3393 text and data segments. Convert the offsets given in the packet
3394 to base addresses for symfile_map_offsets_to_segments. */
3395 else if (data && data->num_segments == 2)
3396 {
3397 segments[0] = data->segment_bases[0] + text_addr;
3398 segments[1] = data->segment_bases[1] + data_addr;
3399 num_segments = 2;
3400 }
8d385431
DJ
3401 /* If the object file has only one segment, assume that it is text
3402 rather than data; main programs with no writable data are rare,
3403 but programs with no code are useless. Of course the code might
3404 have ended up in the data segment... to detect that we would need
3405 the permissions here. */
3406 else if (data && data->num_segments == 1)
3407 {
3408 segments[0] = data->segment_bases[0] + text_addr;
3409 num_segments = 1;
3410 }
28c32713
JB
3411 /* There's no way to relocate by segment. */
3412 else
3413 do_segments = 0;
31d99776
DJ
3414
3415 if (do_segments)
3416 {
3417 int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3418 offs, num_segments, segments);
3419
3420 if (ret == 0 && !do_sections)
3e43a32a
MS
3421 error (_("Can not handle qOffsets TextSeg "
3422 "response with this symbol file"));
31d99776
DJ
3423
3424 if (ret > 0)
3425 do_sections = 0;
3426 }
c906108c 3427
9ef895d6
DJ
3428 if (data)
3429 free_symfile_segment_data (data);
31d99776
DJ
3430
3431 if (do_sections)
3432 {
3433 offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3434
3e43a32a
MS
3435 /* This is a temporary kludge to force data and bss to use the
3436 same offsets because that's what nlmconv does now. The real
3437 solution requires changes to the stub and remote.c that I
3438 don't have time to do right now. */
31d99776
DJ
3439
3440 offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3441 offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3442 }
c906108c
SS
3443
3444 objfile_relocate (symfile_objfile, offs);
3445}
3446
9a7071a8
JB
3447/* Send interrupt_sequence to remote target. */
3448static void
eeae04df 3449send_interrupt_sequence (void)
9a7071a8 3450{
5d93a237
TT
3451 struct remote_state *rs = get_remote_state ();
3452
9a7071a8 3453 if (interrupt_sequence_mode == interrupt_sequence_control_c)
c33e31fd 3454 remote_serial_write ("\x03", 1);
9a7071a8 3455 else if (interrupt_sequence_mode == interrupt_sequence_break)
5d93a237 3456 serial_send_break (rs->remote_desc);
9a7071a8
JB
3457 else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3458 {
5d93a237 3459 serial_send_break (rs->remote_desc);
c33e31fd 3460 remote_serial_write ("g", 1);
9a7071a8
JB
3461 }
3462 else
3463 internal_error (__FILE__, __LINE__,
3464 _("Invalid value for interrupt_sequence_mode: %s."),
3465 interrupt_sequence_mode);
3466}
3467
3405876a
PA
3468
3469/* If STOP_REPLY is a T stop reply, look for the "thread" register,
3470 and extract the PTID. Returns NULL_PTID if not found. */
3471
3472static ptid_t
3473stop_reply_extract_thread (char *stop_reply)
3474{
3475 if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3476 {
3477 char *p;
3478
3479 /* Txx r:val ; r:val (...) */
3480 p = &stop_reply[3];
3481
3482 /* Look for "register" named "thread". */
3483 while (*p != '\0')
3484 {
3485 char *p1;
3486
3487 p1 = strchr (p, ':');
3488 if (p1 == NULL)
3489 return null_ptid;
3490
3491 if (strncmp (p, "thread", p1 - p) == 0)
3492 return read_ptid (++p1, &p);
3493
3494 p1 = strchr (p, ';');
3495 if (p1 == NULL)
3496 return null_ptid;
3497 p1++;
3498
3499 p = p1;
3500 }
3501 }
3502
3503 return null_ptid;
3504}
3505
b7ea362b
PA
3506/* Determine the remote side's current thread. If we have a stop
3507 reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3508 "thread" register we can extract the current thread from. If not,
3509 ask the remote which is the current thread with qC. The former
3510 method avoids a roundtrip. */
3511
3512static ptid_t
3513get_current_thread (char *wait_status)
3514{
6a49a997 3515 ptid_t ptid = null_ptid;
b7ea362b
PA
3516
3517 /* Note we don't use remote_parse_stop_reply as that makes use of
3518 the target architecture, which we haven't yet fully determined at
3519 this point. */
3520 if (wait_status != NULL)
3521 ptid = stop_reply_extract_thread (wait_status);
3522 if (ptid_equal (ptid, null_ptid))
3523 ptid = remote_current_thread (inferior_ptid);
3524
3525 return ptid;
3526}
3527
49c62f2e
PA
3528/* Query the remote target for which is the current thread/process,
3529 add it to our tables, and update INFERIOR_PTID. The caller is
3530 responsible for setting the state such that the remote end is ready
3405876a
PA
3531 to return the current thread.
3532
3533 This function is called after handling the '?' or 'vRun' packets,
3534 whose response is a stop reply from which we can also try
3535 extracting the thread. If the target doesn't support the explicit
3536 qC query, we infer the current thread from that stop reply, passed
3537 in in WAIT_STATUS, which may be NULL. */
49c62f2e
PA
3538
3539static void
3405876a 3540add_current_inferior_and_thread (char *wait_status)
49c62f2e
PA
3541{
3542 struct remote_state *rs = get_remote_state ();
3543 int fake_pid_p = 0;
6a49a997 3544 ptid_t ptid;
49c62f2e
PA
3545
3546 inferior_ptid = null_ptid;
3547
b7ea362b
PA
3548 /* Now, if we have thread information, update inferior_ptid. */
3549 ptid = get_current_thread (wait_status);
3405876a 3550
49c62f2e
PA
3551 if (!ptid_equal (ptid, null_ptid))
3552 {
3553 if (!remote_multi_process_p (rs))
3554 fake_pid_p = 1;
3555
3556 inferior_ptid = ptid;
3557 }
3558 else
3559 {
3560 /* Without this, some commands which require an active target
3561 (such as kill) won't work. This variable serves (at least)
3562 double duty as both the pid of the target process (if it has
3563 such), and as a flag indicating that a target is active. */
3564 inferior_ptid = magic_null_ptid;
3565 fake_pid_p = 1;
3566 }
3567
1b6e6f5c 3568 remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
49c62f2e
PA
3569
3570 /* Add the main thread. */
3571 add_thread_silent (inferior_ptid);
3572}
3573
221e1a37
PA
3574/* Process all initial stop replies the remote side sent in response
3575 to the ? packet. These indicate threads that were already stopped
3576 on initial connection. We mark these threads as stopped and print
3577 their current frame before giving the user the prompt. */
3578
3579static void
3580process_initial_stop_replies (void)
3581{
3582 int pending_stop_replies = stop_reply_queue_length ();
3583
3584 /* Consume the initial pending events. */
3585 while (pending_stop_replies-- > 0)
3586 {
3587 ptid_t waiton_ptid = minus_one_ptid;
3588 ptid_t event_ptid;
3589 struct target_waitstatus ws;
3590 int ignore_event = 0;
3591
3592 memset (&ws, 0, sizeof (ws));
3593 event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3594 if (remote_debug)
3595 print_target_wait_results (waiton_ptid, event_ptid, &ws);
3596
3597 switch (ws.kind)
3598 {
3599 case TARGET_WAITKIND_IGNORE:
3600 case TARGET_WAITKIND_NO_RESUMED:
3601 case TARGET_WAITKIND_SIGNALLED:
3602 case TARGET_WAITKIND_EXITED:
3603 /* We shouldn't see these, but if we do, just ignore. */
3604 if (remote_debug)
3605 fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3606 ignore_event = 1;
3607 break;
3608
3609 case TARGET_WAITKIND_EXECD:
3610 xfree (ws.value.execd_pathname);
3611 break;
3612 default:
3613 break;
3614 }
3615
3616 if (ignore_event)
3617 continue;
3618
3619 switch_to_thread (event_ptid);
3620 set_executing (event_ptid, 0);
3621 set_running (event_ptid, 0);
3622
3623 stop_pc = get_frame_pc (get_current_frame ());
3624 set_current_sal_from_frame (get_current_frame ());
3625
3626 if (ws.kind == TARGET_WAITKIND_STOPPED)
3627 {
3628 enum gdb_signal sig = ws.value.sig;
3629
3630 /* Stubs traditionally report SIGTRAP as initial signal,
3631 instead of signal 0. Suppress it. */
3632 if (sig == GDB_SIGNAL_TRAP)
3633 sig = GDB_SIGNAL_0;
3634 inferior_thread ()->suspend.stop_signal = sig;
3635
3636 if (signal_print_state (sig))
3637 observer_notify_signal_received (sig);
3638 }
3639
243a9253 3640 print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
221e1a37
PA
3641 observer_notify_normal_stop (NULL, 1);
3642 }
3643}
3644
9cbc821d 3645static void
04bd08de 3646remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
c906108c 3647{
c8d104ad
PA
3648 struct remote_state *rs = get_remote_state ();
3649 struct packet_config *noack_config;
2d717e4f 3650 char *wait_status = NULL;
8621d6a9 3651
23860348 3652 immediate_quit++; /* Allow user to interrupt it. */
522002f9 3653 QUIT;
c906108c 3654
9a7071a8
JB
3655 if (interrupt_on_connect)
3656 send_interrupt_sequence ();
3657
57e12211 3658 /* Ack any packet which the remote side has already sent. */
5d93a237 3659 serial_write (rs->remote_desc, "+", 1);
57e12211 3660
1e51243a
PA
3661 /* Signal other parts that we're going through the initial setup,
3662 and so things may not be stable yet. */
3663 rs->starting_up = 1;
3664
c8d104ad
PA
3665 /* The first packet we send to the target is the optional "supported
3666 packets" request. If the target can answer this, it will tell us
3667 which later probes to skip. */
3668 remote_query_supported ();
3669
d914c394 3670 /* If the stub wants to get a QAllow, compose one and send it. */
4082afcc 3671 if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
c378d69d 3672 remote_set_permissions (target);
d914c394 3673
c8d104ad
PA
3674 /* Next, we possibly activate noack mode.
3675
3676 If the QStartNoAckMode packet configuration is set to AUTO,
3677 enable noack mode if the stub reported a wish for it with
3678 qSupported.
3679
3680 If set to TRUE, then enable noack mode even if the stub didn't
3681 report it in qSupported. If the stub doesn't reply OK, the
3682 session ends with an error.
3683
3684 If FALSE, then don't activate noack mode, regardless of what the
3685 stub claimed should be the default with qSupported. */
3686
3687 noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4082afcc 3688 if (packet_config_support (noack_config) != PACKET_DISABLE)
c8d104ad
PA
3689 {
3690 putpkt ("QStartNoAckMode");
3691 getpkt (&rs->buf, &rs->buf_size, 0);
3692 if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3693 rs->noack_mode = 1;
3694 }
3695
04bd08de 3696 if (extended_p)
5fe04517
PA
3697 {
3698 /* Tell the remote that we are using the extended protocol. */
3699 putpkt ("!");
3700 getpkt (&rs->buf, &rs->buf_size, 0);
3701 }
3702
9b224c5e
PA
3703 /* Let the target know which signals it is allowed to pass down to
3704 the program. */
3705 update_signals_program_target ();
3706
d962ef82
DJ
3707 /* Next, if the target can specify a description, read it. We do
3708 this before anything involving memory or registers. */
3709 target_find_description ();
3710
6c95b8df
PA
3711 /* Next, now that we know something about the target, update the
3712 address spaces in the program spaces. */
3713 update_address_spaces ();
3714
50c71eaf
PA
3715 /* On OSs where the list of libraries is global to all
3716 processes, we fetch them early. */
f5656ead 3717 if (gdbarch_has_global_solist (target_gdbarch ()))
04bd08de 3718 solib_add (NULL, from_tty, target, auto_solib_add);
50c71eaf 3719
74531fed
PA
3720 if (non_stop)
3721 {
4082afcc 3722 if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3e43a32a
MS
3723 error (_("Non-stop mode requested, but remote "
3724 "does not support non-stop"));
74531fed
PA
3725
3726 putpkt ("QNonStop:1");
3727 getpkt (&rs->buf, &rs->buf_size, 0);
3728
3729 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3730 error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
74531fed
PA
3731
3732 /* Find about threads and processes the stub is already
3733 controlling. We default to adding them in the running state.
3734 The '?' query below will then tell us about which threads are
3735 stopped. */
e8032dde 3736 remote_update_thread_list (target);
74531fed 3737 }
4082afcc 3738 else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
74531fed
PA
3739 {
3740 /* Don't assume that the stub can operate in all-stop mode.
e6f3fa52 3741 Request it explicitly. */
74531fed
PA
3742 putpkt ("QNonStop:0");
3743 getpkt (&rs->buf, &rs->buf_size, 0);
3744
3745 if (strcmp (rs->buf, "OK") != 0)
9b20d036 3746 error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
74531fed
PA
3747 }
3748
a0743c90
YQ
3749 /* Upload TSVs regardless of whether the target is running or not. The
3750 remote stub, such as GDBserver, may have some predefined or builtin
3751 TSVs, even if the target is not running. */
8bd200f1 3752 if (remote_get_trace_status (target, current_trace_status ()) != -1)
a0743c90
YQ
3753 {
3754 struct uploaded_tsv *uploaded_tsvs = NULL;
3755
181e3713 3756 remote_upload_trace_state_variables (target, &uploaded_tsvs);
a0743c90
YQ
3757 merge_uploaded_trace_state_variables (&uploaded_tsvs);
3758 }
3759
2d717e4f
DJ
3760 /* Check whether the target is running now. */
3761 putpkt ("?");
3762 getpkt (&rs->buf, &rs->buf_size, 0);
3763
74531fed 3764 if (!non_stop)
2d717e4f 3765 {
e714e1bf
UW
3766 ptid_t ptid;
3767 int fake_pid_p = 0;
3768 struct inferior *inf;
3769
74531fed 3770 if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2d717e4f 3771 {
04bd08de 3772 if (!extended_p)
74531fed 3773 error (_("The target is not running (try extended-remote?)"));
c35b1492
PA
3774
3775 /* We're connected, but not running. Drop out before we
3776 call start_remote. */
e278ad5b 3777 rs->starting_up = 0;
c35b1492 3778 return;
2d717e4f
DJ
3779 }
3780 else
74531fed 3781 {
74531fed
PA
3782 /* Save the reply for later. */
3783 wait_status = alloca (strlen (rs->buf) + 1);
3784 strcpy (wait_status, rs->buf);
3785 }
3786
b7ea362b 3787 /* Fetch thread list. */
e8032dde 3788 target_update_thread_list ();
b7ea362b 3789
74531fed
PA
3790 /* Let the stub know that we want it to return the thread. */
3791 set_continue_thread (minus_one_ptid);
3792
b7ea362b
PA
3793 if (thread_count () == 0)
3794 {
3795 /* Target has no concept of threads at all. GDB treats
3796 non-threaded target as single-threaded; add a main
3797 thread. */
3798 add_current_inferior_and_thread (wait_status);
3799 }
3800 else
3801 {
3802 /* We have thread information; select the thread the target
3803 says should be current. If we're reconnecting to a
3804 multi-threaded program, this will ideally be the thread
3805 that last reported an event before GDB disconnected. */
3806 inferior_ptid = get_current_thread (wait_status);
3807 if (ptid_equal (inferior_ptid, null_ptid))
3808 {
3809 /* Odd... The target was able to list threads, but not
3810 tell us which thread was current (no "thread"
3811 register in T stop reply?). Just pick the first
3812 thread in the thread list then. */
c9f35b34
KB
3813
3814 if (remote_debug)
3815 fprintf_unfiltered (gdb_stdlog,
3816 "warning: couldn't determine remote "
3817 "current thread; picking first in list.\n");
3818
b7ea362b
PA
3819 inferior_ptid = thread_list->ptid;
3820 }
3821 }
74531fed 3822
6e586cc5
YQ
3823 /* init_wait_for_inferior should be called before get_offsets in order
3824 to manage `inserted' flag in bp loc in a correct state.
3825 breakpoint_init_inferior, called from init_wait_for_inferior, set
3826 `inserted' flag to 0, while before breakpoint_re_set, called from
3827 start_remote, set `inserted' flag to 1. In the initialization of
3828 inferior, breakpoint_init_inferior should be called first, and then
3829 breakpoint_re_set can be called. If this order is broken, state of
3830 `inserted' flag is wrong, and cause some problems on breakpoint
3831 manipulation. */
3832 init_wait_for_inferior ();
3833
74531fed
PA
3834 get_offsets (); /* Get text, data & bss offsets. */
3835
d962ef82
DJ
3836 /* If we could not find a description using qXfer, and we know
3837 how to do it some other way, try again. This is not
3838 supported for non-stop; it could be, but it is tricky if
3839 there are no stopped threads when we connect. */
04bd08de 3840 if (remote_read_description_p (target)
f5656ead 3841 && gdbarch_target_desc (target_gdbarch ()) == NULL)
d962ef82
DJ
3842 {
3843 target_clear_description ();
3844 target_find_description ();
3845 }
3846
74531fed
PA
3847 /* Use the previously fetched status. */
3848 gdb_assert (wait_status != NULL);
3849 strcpy (rs->buf, wait_status);
3850 rs->cached_wait_status = 1;
3851
3852 immediate_quit--;
04bd08de 3853 start_remote (from_tty); /* Initialize gdb process mechanisms. */
2d717e4f
DJ
3854 }
3855 else
3856 {
221e1a37
PA
3857 ptid_t current_ptid;
3858
68c97600
PA
3859 /* Clear WFI global state. Do this before finding about new
3860 threads and inferiors, and setting the current inferior.
3861 Otherwise we would clear the proceed status of the current
3862 inferior when we want its stop_soon state to be preserved
3863 (see notice_new_inferior). */
3864 init_wait_for_inferior ();
3865
74531fed
PA
3866 /* In non-stop, we will either get an "OK", meaning that there
3867 are no stopped threads at this time; or, a regular stop
3868 reply. In the latter case, there may be more than one thread
3869 stopped --- we pull them all out using the vStopped
3870 mechanism. */
3871 if (strcmp (rs->buf, "OK") != 0)
3872 {
722247f1 3873 struct notif_client *notif = &notif_client_stop;
2d717e4f 3874
722247f1
YQ
3875 /* remote_notif_get_pending_replies acks this one, and gets
3876 the rest out. */
f48ff2a7 3877 rs->notif_state->pending_event[notif_client_stop.id]
722247f1
YQ
3878 = remote_notif_parse (notif, rs->buf);
3879 remote_notif_get_pending_events (notif);
74531fed 3880 }
2d717e4f 3881
74531fed
PA
3882 if (thread_count () == 0)
3883 {
04bd08de 3884 if (!extended_p)
74531fed 3885 error (_("The target is not running (try extended-remote?)"));
82f73884 3886
c35b1492
PA
3887 /* We're connected, but not running. Drop out before we
3888 call start_remote. */
e278ad5b 3889 rs->starting_up = 0;
c35b1492
PA
3890 return;
3891 }
74531fed
PA
3892
3893 /* Let the stub know that we want it to return the thread. */
c0a2216e 3894
74531fed
PA
3895 /* Force the stub to choose a thread. */
3896 set_general_thread (null_ptid);
c906108c 3897
74531fed 3898 /* Query it. */
221e1a37 3899 current_ptid = remote_current_thread (minus_one_ptid);
74531fed
PA
3900 if (ptid_equal (inferior_ptid, minus_one_ptid))
3901 error (_("remote didn't report the current thread in non-stop mode"));
c906108c 3902
221e1a37 3903 inferior_ptid = current_ptid;
74531fed
PA
3904 get_offsets (); /* Get text, data & bss offsets. */
3905
3906 /* In non-stop mode, any cached wait status will be stored in
3907 the stop reply queue. */
3908 gdb_assert (wait_status == NULL);
f0223081 3909
2455069d 3910 /* Report all signals during attach/startup. */
94bedb42 3911 remote_pass_signals (target, 0, NULL);
221e1a37
PA
3912
3913 /* If there are already stopped threads, mark them stopped and
3914 report their stops before giving the prompt to the user. */
3915 process_initial_stop_replies ();
3916
3917 switch_to_thread (current_ptid);
3918
3919 if (target_can_async_p ())
3920 target_async (1);
74531fed 3921 }
c8d104ad 3922
c8d104ad
PA
3923 /* If we connected to a live target, do some additional setup. */
3924 if (target_has_execution)
3925 {
f4ccffad 3926 if (symfile_objfile) /* No use without a symbol-file. */
36d25514 3927 remote_check_symbols ();
c8d104ad 3928 }
50c71eaf 3929
d5551862
SS
3930 /* Possibly the target has been engaged in a trace run started
3931 previously; find out where things are at. */
8bd200f1 3932 if (remote_get_trace_status (target, current_trace_status ()) != -1)
d5551862 3933 {
00bf0b85 3934 struct uploaded_tp *uploaded_tps = NULL;
00bf0b85 3935
00bf0b85
SS
3936 if (current_trace_status ()->running)
3937 printf_filtered (_("Trace is already running on the target.\n"));
3938
ab6617cc 3939 remote_upload_tracepoints (target, &uploaded_tps);
00bf0b85
SS
3940
3941 merge_uploaded_tracepoints (&uploaded_tps);
d5551862
SS
3942 }
3943
1e51243a
PA
3944 /* The thread and inferior lists are now synchronized with the
3945 target, our symbols have been relocated, and we're merged the
3946 target's tracepoints with ours. We're done with basic start
3947 up. */
3948 rs->starting_up = 0;
3949
a25a5a45
PA
3950 /* Maybe breakpoints are global and need to be inserted now. */
3951 if (breakpoints_should_be_inserted_now ())
50c71eaf 3952 insert_breakpoints ();
c906108c
SS
3953}
3954
3955/* Open a connection to a remote debugger.
3956 NAME is the filename used for communication. */
3957
3958static void
014f9477 3959remote_open (const char *name, int from_tty)
c906108c 3960{
75c99385 3961 remote_open_1 (name, from_tty, &remote_ops, 0);
43ff13b4
JM
3962}
3963
c906108c
SS
3964/* Open a connection to a remote debugger using the extended
3965 remote gdb protocol. NAME is the filename used for communication. */
3966
3967static void
014f9477 3968extended_remote_open (const char *name, int from_tty)
c906108c 3969{
75c99385 3970 remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
43ff13b4
JM
3971}
3972
ca4f7f8b
PA
3973/* Reset all packets back to "unknown support". Called when opening a
3974 new connection to a remote target. */
c906108c 3975
d471ea57 3976static void
ca4f7f8b 3977reset_all_packet_configs_support (void)
d471ea57
AC
3978{
3979 int i;
a744cf53 3980
444abaca 3981 for (i = 0; i < PACKET_MAX; i++)
4082afcc 3982 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
d471ea57
AC
3983}
3984
ca4f7f8b
PA
3985/* Initialize all packet configs. */
3986
3987static void
3988init_all_packet_configs (void)
3989{
3990 int i;
3991
3992 for (i = 0; i < PACKET_MAX; i++)
3993 {
3994 remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3995 remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3996 }
3997}
3998
23860348 3999/* Symbol look-up. */
dc8acb97
MS
4000
4001static void
36d25514 4002remote_check_symbols (void)
dc8acb97 4003{
d01949b6 4004 struct remote_state *rs = get_remote_state ();
dc8acb97 4005 char *msg, *reply, *tmp;
3b7344d5 4006 struct bound_minimal_symbol sym;
dc8acb97 4007 int end;
a5c0808e 4008 struct cleanup *old_chain;
dc8acb97 4009
63154eca
PA
4010 /* The remote side has no concept of inferiors that aren't running
4011 yet, it only knows about running processes. If we're connected
4012 but our current inferior is not running, we should not invite the
4013 remote target to request symbol lookups related to its
4014 (unrelated) current process. */
4015 if (!target_has_execution)
4016 return;
4017
4082afcc 4018 if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
dc8acb97
MS
4019 return;
4020
63154eca
PA
4021 /* Make sure the remote is pointing at the right process. Note
4022 there's no way to select "no process". */
3c9c4b83
PA
4023 set_general_process ();
4024
6d820c5c
DJ
4025 /* Allocate a message buffer. We can't reuse the input buffer in RS,
4026 because we need both at the same time. */
a5c0808e
PA
4027 msg = xmalloc (get_remote_packet_size ());
4028 old_chain = make_cleanup (xfree, msg);
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 4065 }
a5c0808e
PA
4066
4067 do_cleanups (old_chain);
dc8acb97
MS
4068}
4069
9db8d71f 4070static struct serial *
baa336ce 4071remote_serial_open (const char *name)
9db8d71f
DJ
4072{
4073 static int udp_warning = 0;
4074
4075 /* FIXME: Parsing NAME here is a hack. But we want to warn here instead
4076 of in ser-tcp.c, because it is the remote protocol assuming that the
4077 serial connection is reliable and not the serial connection promising
4078 to be. */
61012eef 4079 if (!udp_warning && startswith (name, "udp:"))
9db8d71f 4080 {
3e43a32a
MS
4081 warning (_("The remote protocol may be unreliable over UDP.\n"
4082 "Some events may be lost, rendering further debugging "
4083 "impossible."));
9db8d71f
DJ
4084 udp_warning = 1;
4085 }
4086
4087 return serial_open (name);
4088}
4089
d914c394
SS
4090/* Inform the target of our permission settings. The permission flags
4091 work without this, but if the target knows the settings, it can do
4092 a couple things. First, it can add its own check, to catch cases
4093 that somehow manage to get by the permissions checks in target
4094 methods. Second, if the target is wired to disallow particular
4095 settings (for instance, a system in the field that is not set up to
4096 be able to stop at a breakpoint), it can object to any unavailable
4097 permissions. */
4098
4099void
c378d69d 4100remote_set_permissions (struct target_ops *self)
d914c394
SS
4101{
4102 struct remote_state *rs = get_remote_state ();
4103
bba74b36
YQ
4104 xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4105 "WriteReg:%x;WriteMem:%x;"
4106 "InsertBreak:%x;InsertTrace:%x;"
4107 "InsertFastTrace:%x;Stop:%x",
4108 may_write_registers, may_write_memory,
4109 may_insert_breakpoints, may_insert_tracepoints,
4110 may_insert_fast_tracepoints, may_stop);
d914c394
SS
4111 putpkt (rs->buf);
4112 getpkt (&rs->buf, &rs->buf_size, 0);
4113
4114 /* If the target didn't like the packet, warn the user. Do not try
4115 to undo the user's settings, that would just be maddening. */
4116 if (strcmp (rs->buf, "OK") != 0)
7ea6d463 4117 warning (_("Remote refused setting permissions with: %s"), rs->buf);
d914c394
SS
4118}
4119
be2a5f71
DJ
4120/* This type describes each known response to the qSupported
4121 packet. */
4122struct protocol_feature
4123{
4124 /* The name of this protocol feature. */
4125 const char *name;
4126
4127 /* The default for this protocol feature. */
4128 enum packet_support default_support;
4129
4130 /* The function to call when this feature is reported, or after
4131 qSupported processing if the feature is not supported.
4132 The first argument points to this structure. The second
4133 argument indicates whether the packet requested support be
4134 enabled, disabled, or probed (or the default, if this function
4135 is being called at the end of processing and this feature was
4136 not reported). The third argument may be NULL; if not NULL, it
4137 is a NUL-terminated string taken from the packet following
4138 this feature's name and an equals sign. */
4139 void (*func) (const struct protocol_feature *, enum packet_support,
4140 const char *);
4141
4142 /* The corresponding packet for this feature. Only used if
4143 FUNC is remote_supported_packet. */
4144 int packet;
4145};
4146
be2a5f71
DJ
4147static void
4148remote_supported_packet (const struct protocol_feature *feature,
4149 enum packet_support support,
4150 const char *argument)
4151{
4152 if (argument)
4153 {
4154 warning (_("Remote qSupported response supplied an unexpected value for"
4155 " \"%s\"."), feature->name);
4156 return;
4157 }
4158
4082afcc 4159 remote_protocol_packets[feature->packet].support = support;
be2a5f71 4160}
be2a5f71
DJ
4161
4162static void
4163remote_packet_size (const struct protocol_feature *feature,
4164 enum packet_support support, const char *value)
4165{
4166 struct remote_state *rs = get_remote_state ();
4167
4168 int packet_size;
4169 char *value_end;
4170
4171 if (support != PACKET_ENABLE)
4172 return;
4173
4174 if (value == NULL || *value == '\0')
4175 {
4176 warning (_("Remote target reported \"%s\" without a size."),
4177 feature->name);
4178 return;
4179 }
4180
4181 errno = 0;
4182 packet_size = strtol (value, &value_end, 16);
4183 if (errno != 0 || *value_end != '\0' || packet_size < 0)
4184 {
4185 warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4186 feature->name, value);
4187 return;
4188 }
4189
be2a5f71
DJ
4190 /* Record the new maximum packet size. */
4191 rs->explicit_packet_size = packet_size;
4192}
4193
dc473cfb 4194static const struct protocol_feature remote_protocol_features[] = {
0876f84a 4195 { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
40e57cf2 4196 { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
fd79ecee 4197 PACKET_qXfer_auxv },
c78fa86a
GB
4198 { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4199 PACKET_qXfer_exec_file },
23181151
DJ
4200 { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4201 PACKET_qXfer_features },
cfa9d6d9
DJ
4202 { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4203 PACKET_qXfer_libraries },
2268b414
JK
4204 { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4205 PACKET_qXfer_libraries_svr4 },
ced63ec0 4206 { "augmented-libraries-svr4-read", PACKET_DISABLE,
4082afcc 4207 remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
fd79ecee 4208 { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
89be2091 4209 PACKET_qXfer_memory_map },
4de6483e
UW
4210 { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4211 PACKET_qXfer_spu_read },
4212 { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4213 PACKET_qXfer_spu_write },
07e059b5
VP
4214 { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4215 PACKET_qXfer_osdata },
dc146f7c
VP
4216 { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4217 PACKET_qXfer_threads },
b3b9301e
PA
4218 { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4219 PACKET_qXfer_traceframe_info },
89be2091
DJ
4220 { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4221 PACKET_QPassSignals },
9b224c5e
PA
4222 { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4223 PACKET_QProgramSignals },
a6f3e723
SL
4224 { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4225 PACKET_QStartNoAckMode },
4082afcc
PA
4226 { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4227 PACKET_multiprocess_feature },
4228 { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4aa995e1
PA
4229 { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4230 PACKET_qXfer_siginfo_read },
4231 { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4232 PACKET_qXfer_siginfo_write },
4082afcc 4233 { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
782b2b07 4234 PACKET_ConditionalTracepoints },
4082afcc 4235 { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
3788aec7 4236 PACKET_ConditionalBreakpoints },
4082afcc 4237 { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
d3ce09f5 4238 PACKET_BreakpointCommands },
4082afcc 4239 { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
7a697b8d 4240 PACKET_FastTracepoints },
4082afcc 4241 { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
0fb4aa4b 4242 PACKET_StaticTracepoints },
4082afcc 4243 {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
1e4d1764 4244 PACKET_InstallInTrace},
4082afcc
PA
4245 { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4246 PACKET_DisconnectedTracing_feature },
40ab02ce
MS
4247 { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4248 PACKET_bc },
4249 { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4250 PACKET_bs },
409873ef
SS
4251 { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4252 PACKET_TracepointSource },
d914c394
SS
4253 { "QAllow", PACKET_DISABLE, remote_supported_packet,
4254 PACKET_QAllow },
4082afcc
PA
4255 { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4256 PACKET_EnableDisableTracepoints_feature },
78d85199
YQ
4257 { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4258 PACKET_qXfer_fdpic },
169081d0
TG
4259 { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4260 PACKET_qXfer_uib },
03583c20
UW
4261 { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4262 PACKET_QDisableRandomization },
d1feda86 4263 { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
f6f899bf
HAQ
4264 { "QTBuffer:size", PACKET_DISABLE,
4265 remote_supported_packet, PACKET_QTBuffer_size},
4082afcc 4266 { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
9accd112
MM
4267 { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4268 { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
b20a6524 4269 { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
9accd112 4270 { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
f4abbc16
MM
4271 PACKET_qXfer_btrace },
4272 { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
d33501a5
MM
4273 PACKET_qXfer_btrace_conf },
4274 { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
f7e6eed5
PA
4275 PACKET_Qbtrace_conf_bts_size },
4276 { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
0a93529c 4277 { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
89245bc0
DB
4278 { "fork-events", PACKET_DISABLE, remote_supported_packet,
4279 PACKET_fork_event_feature },
4280 { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4281 PACKET_vfork_event_feature },
b20a6524
MM
4282 { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4283 PACKET_Qbtrace_conf_pt_size }
be2a5f71
DJ
4284};
4285
c8d5aac9
L
4286static char *remote_support_xml;
4287
4288/* Register string appended to "xmlRegisters=" in qSupported query. */
4289
4290void
6e39997a 4291register_remote_support_xml (const char *xml)
c8d5aac9
L
4292{
4293#if defined(HAVE_LIBEXPAT)
4294 if (remote_support_xml == NULL)
c4f7c687 4295 remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
c8d5aac9
L
4296 else
4297 {
4298 char *copy = xstrdup (remote_support_xml + 13);
4299 char *p = strtok (copy, ",");
4300
4301 do
4302 {
4303 if (strcmp (p, xml) == 0)
4304 {
4305 /* already there */
4306 xfree (copy);
4307 return;
4308 }
4309 }
4310 while ((p = strtok (NULL, ",")) != NULL);
4311 xfree (copy);
4312
94b0dee1
PA
4313 remote_support_xml = reconcat (remote_support_xml,
4314 remote_support_xml, ",", xml,
4315 (char *) NULL);
c8d5aac9
L
4316 }
4317#endif
4318}
4319
4320static char *
4321remote_query_supported_append (char *msg, const char *append)
4322{
4323 if (msg)
94b0dee1 4324 return reconcat (msg, msg, ";", append, (char *) NULL);
c8d5aac9
L
4325 else
4326 return xstrdup (append);
4327}
4328
be2a5f71
DJ
4329static void
4330remote_query_supported (void)
4331{
4332 struct remote_state *rs = get_remote_state ();
4333 char *next;
4334 int i;
4335 unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4336
4337 /* The packet support flags are handled differently for this packet
4338 than for most others. We treat an error, a disabled packet, and
4339 an empty response identically: any features which must be reported
4340 to be used will be automatically disabled. An empty buffer
4341 accomplishes this, since that is also the representation for a list
4342 containing no features. */
4343
4344 rs->buf[0] = 0;
4082afcc 4345 if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
be2a5f71 4346 {
c8d5aac9 4347 char *q = NULL;
94b0dee1 4348 struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
c8d5aac9 4349
73b8c1fd
PA
4350 if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4351 q = remote_query_supported_append (q, "multiprocess+");
c8d5aac9 4352
f7e6eed5
PA
4353 if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4354 q = remote_query_supported_append (q, "swbreak+");
4355 if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4356 q = remote_query_supported_append (q, "hwbreak+");
4357
c8d5aac9
L
4358 if (remote_support_xml)
4359 q = remote_query_supported_append (q, remote_support_xml);
4360
dde08ee1
PA
4361 q = remote_query_supported_append (q, "qRelocInsn+");
4362
89245bc0
DB
4363 if (rs->extended)
4364 {
4365 if (packet_set_cmd_state (PACKET_fork_event_feature)
4366 != AUTO_BOOLEAN_FALSE)
4367 q = remote_query_supported_append (q, "fork-events+");
4368 if (packet_set_cmd_state (PACKET_vfork_event_feature)
4369 != AUTO_BOOLEAN_FALSE)
4370 q = remote_query_supported_append (q, "vfork-events+");
4371 }
4372
dde08ee1
PA
4373 q = reconcat (q, "qSupported:", q, (char *) NULL);
4374 putpkt (q);
82f73884 4375
94b0dee1
PA
4376 do_cleanups (old_chain);
4377
be2a5f71
DJ
4378 getpkt (&rs->buf, &rs->buf_size, 0);
4379
4380 /* If an error occured, warn, but do not return - just reset the
4381 buffer to empty and go on to disable features. */
4382 if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4383 == PACKET_ERROR)
4384 {
4385 warning (_("Remote failure reply: %s"), rs->buf);
4386 rs->buf[0] = 0;
4387 }
4388 }
4389
4390 memset (seen, 0, sizeof (seen));
4391
4392 next = rs->buf;
4393 while (*next)
4394 {
4395 enum packet_support is_supported;
4396 char *p, *end, *name_end, *value;
4397
4398 /* First separate out this item from the rest of the packet. If
4399 there's another item after this, we overwrite the separator
4400 (terminated strings are much easier to work with). */
4401 p = next;
4402 end = strchr (p, ';');
4403 if (end == NULL)
4404 {
4405 end = p + strlen (p);
4406 next = end;
4407 }
4408 else
4409 {
89be2091
DJ
4410 *end = '\0';
4411 next = end + 1;
4412
be2a5f71
DJ
4413 if (end == p)
4414 {
4415 warning (_("empty item in \"qSupported\" response"));
4416 continue;
4417 }
be2a5f71
DJ
4418 }
4419
4420 name_end = strchr (p, '=');
4421 if (name_end)
4422 {
4423 /* This is a name=value entry. */
4424 is_supported = PACKET_ENABLE;
4425 value = name_end + 1;
4426 *name_end = '\0';
4427 }
4428 else
4429 {
4430 value = NULL;
4431 switch (end[-1])
4432 {
4433 case '+':
4434 is_supported = PACKET_ENABLE;
4435 break;
4436
4437 case '-':
4438 is_supported = PACKET_DISABLE;
4439 break;
4440
4441 case '?':
4442 is_supported = PACKET_SUPPORT_UNKNOWN;
4443 break;
4444
4445 default:
3e43a32a
MS
4446 warning (_("unrecognized item \"%s\" "
4447 "in \"qSupported\" response"), p);
be2a5f71
DJ
4448 continue;
4449 }
4450 end[-1] = '\0';
4451 }
4452
4453 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4454 if (strcmp (remote_protocol_features[i].name, p) == 0)
4455 {
4456 const struct protocol_feature *feature;
4457
4458 seen[i] = 1;
4459 feature = &remote_protocol_features[i];
4460 feature->func (feature, is_supported, value);
4461 break;
4462 }
4463 }
4464
4465 /* If we increased the packet size, make sure to increase the global
4466 buffer size also. We delay this until after parsing the entire
4467 qSupported packet, because this is the same buffer we were
4468 parsing. */
4469 if (rs->buf_size < rs->explicit_packet_size)
4470 {
4471 rs->buf_size = rs->explicit_packet_size;
4472 rs->buf = xrealloc (rs->buf, rs->buf_size);
4473 }
4474
4475 /* Handle the defaults for unmentioned features. */
4476 for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4477 if (!seen[i])
4478 {
4479 const struct protocol_feature *feature;
4480
4481 feature = &remote_protocol_features[i];
4482 feature->func (feature, feature->default_support, NULL);
4483 }
4484}
4485
78a095c3
JK
4486/* Remove any of the remote.c targets from target stack. Upper targets depend
4487 on it so remove them first. */
4488
4489static void
4490remote_unpush_target (void)
4491{
4492 pop_all_targets_above (process_stratum - 1);
4493}
be2a5f71 4494
c906108c 4495static void
014f9477 4496remote_open_1 (const char *name, int from_tty,
3e43a32a 4497 struct target_ops *target, int extended_p)
c906108c 4498{
d01949b6 4499 struct remote_state *rs = get_remote_state ();
a6f3e723 4500
c906108c 4501 if (name == 0)
8a3fe4f8 4502 error (_("To open a remote debug connection, you need to specify what\n"
22e04375 4503 "serial device is attached to the remote system\n"
8a3fe4f8 4504 "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
c906108c 4505
23860348 4506 /* See FIXME above. */
c6ebd6cf 4507 if (!target_async_permitted)
92d1e331 4508 wait_forever_enabled_p = 1;
6426a772 4509
2d717e4f 4510 /* If we're connected to a running target, target_preopen will kill it.
78a095c3
JK
4511 Ask this question first, before target_preopen has a chance to kill
4512 anything. */
5d93a237 4513 if (rs->remote_desc != NULL && !have_inferiors ())
2d717e4f 4514 {
78a095c3
JK
4515 if (from_tty
4516 && !query (_("Already connected to a remote target. Disconnect? ")))
2d717e4f
DJ
4517 error (_("Still connected."));
4518 }
4519
78a095c3 4520 /* Here the possibly existing remote target gets unpushed. */
c906108c
SS
4521 target_preopen (from_tty);
4522
89be2091 4523 /* Make sure we send the passed signals list the next time we resume. */
747dc59d
TT
4524 xfree (rs->last_pass_packet);
4525 rs->last_pass_packet = NULL;
89be2091 4526
9b224c5e
PA
4527 /* Make sure we send the program signals list the next time we
4528 resume. */
5e4a05c4
TT
4529 xfree (rs->last_program_signals_packet);
4530 rs->last_program_signals_packet = NULL;
9b224c5e 4531
ad9a8f3f 4532 remote_fileio_reset ();
1dd41f16
NS
4533 reopen_exec_file ();
4534 reread_symbols ();
4535
5d93a237
TT
4536 rs->remote_desc = remote_serial_open (name);
4537 if (!rs->remote_desc)
c906108c
SS
4538 perror_with_name (name);
4539
4540 if (baud_rate != -1)
4541 {
5d93a237 4542 if (serial_setbaudrate (rs->remote_desc, baud_rate))
c906108c 4543 {
9b74d5d3
KB
4544 /* The requested speed could not be set. Error out to
4545 top level after closing remote_desc. Take care to
4546 set remote_desc to NULL to avoid closing remote_desc
4547 more than once. */
5d93a237
TT
4548 serial_close (rs->remote_desc);
4549 rs->remote_desc = NULL;
c906108c
SS
4550 perror_with_name (name);
4551 }
4552 }
4553
236af5e3 4554 serial_setparity (rs->remote_desc, serial_parity);
5d93a237 4555 serial_raw (rs->remote_desc);
c906108c
SS
4556
4557 /* If there is something sitting in the buffer we might take it as a
4558 response to a command, which would be bad. */
5d93a237 4559 serial_flush_input (rs->remote_desc);
c906108c
SS
4560
4561 if (from_tty)
4562 {
4563 puts_filtered ("Remote debugging using ");
4564 puts_filtered (name);
4565 puts_filtered ("\n");
4566 }
23860348 4567 push_target (target); /* Switch to using remote target now. */
c906108c 4568
74531fed
PA
4569 /* Register extra event sources in the event loop. */
4570 remote_async_inferior_event_token
4571 = create_async_event_handler (remote_async_inferior_event_handler,
4572 NULL);
5965e028 4573 rs->notif_state = remote_notif_state_allocate ();
74531fed 4574
be2a5f71
DJ
4575 /* Reset the target state; these things will be queried either by
4576 remote_query_supported or as they are needed. */
ca4f7f8b 4577 reset_all_packet_configs_support ();
74531fed 4578 rs->cached_wait_status = 0;
be2a5f71 4579 rs->explicit_packet_size = 0;
a6f3e723 4580 rs->noack_mode = 0;
82f73884 4581 rs->extended = extended_p;
e24a49d8 4582 rs->waiting_for_stop_reply = 0;
3a29589a 4583 rs->ctrlc_pending_p = 0;
802188a7 4584
47f8a51d
TT
4585 rs->general_thread = not_sent_ptid;
4586 rs->continue_thread = not_sent_ptid;
262e1174 4587 rs->remote_traceframe_number = -1;
c906108c 4588
9d1f7ab2 4589 /* Probe for ability to use "ThreadInfo" query, as required. */
b80fafe3
TT
4590 rs->use_threadinfo_query = 1;
4591 rs->use_threadextra_query = 1;
9d1f7ab2 4592
80152258
PA
4593 readahead_cache_invalidate ();
4594
c6ebd6cf 4595 if (target_async_permitted)
92d1e331 4596 {
23860348 4597 /* With this target we start out by owning the terminal. */
92d1e331
DJ
4598 remote_async_terminal_ours_p = 1;
4599
4600 /* FIXME: cagney/1999-09-23: During the initial connection it is
4601 assumed that the target is already ready and able to respond to
0df8b418 4602 requests. Unfortunately remote_start_remote() eventually calls
92d1e331 4603 wait_for_inferior() with no timeout. wait_forever_enabled_p gets
0df8b418 4604 around this. Eventually a mechanism that allows
92d1e331 4605 wait_for_inferior() to expect/get timeouts will be
23860348 4606 implemented. */
92d1e331
DJ
4607 wait_forever_enabled_p = 0;
4608 }
4609
23860348 4610 /* First delete any symbols previously loaded from shared libraries. */
f78f6cf1 4611 no_shared_libraries (NULL, 0);
f78f6cf1 4612
74531fed
PA
4613 /* Start afresh. */
4614 init_thread_list ();
4615
36918e70 4616 /* Start the remote connection. If error() or QUIT, discard this
165b8e33
AC
4617 target (we'd otherwise be in an inconsistent state) and then
4618 propogate the error on up the exception chain. This ensures that
4619 the caller doesn't stumble along blindly assuming that the
4620 function succeeded. The CLI doesn't have this problem but other
4621 UI's, such as MI do.
36918e70
AC
4622
4623 FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4624 this function should return an error indication letting the
ce2826aa 4625 caller restore the previous state. Unfortunately the command
36918e70
AC
4626 ``target remote'' is directly wired to this function making that
4627 impossible. On a positive note, the CLI side of this problem has
4628 been fixed - the function set_cmd_context() makes it possible for
4629 all the ``target ....'' commands to share a common callback
4630 function. See cli-dump.c. */
109c3e39 4631 {
2d717e4f 4632
492d29ea 4633 TRY
04bd08de
TT
4634 {
4635 remote_start_remote (from_tty, target, extended_p);
4636 }
492d29ea 4637 CATCH (ex, RETURN_MASK_ALL)
109c3e39 4638 {
c8d104ad
PA
4639 /* Pop the partially set up target - unless something else did
4640 already before throwing the exception. */
5d93a237 4641 if (rs->remote_desc != NULL)
78a095c3 4642 remote_unpush_target ();
c6ebd6cf 4643 if (target_async_permitted)
109c3e39
AC
4644 wait_forever_enabled_p = 1;
4645 throw_exception (ex);
4646 }
492d29ea 4647 END_CATCH
109c3e39 4648 }
c906108c 4649
f4abbc16
MM
4650 remote_btrace_reset ();
4651
c6ebd6cf 4652 if (target_async_permitted)
92d1e331 4653 wait_forever_enabled_p = 1;
43ff13b4
JM
4654}
4655
de0d863e
DB
4656/* Detach the specified process. */
4657
4658static void
4659remote_detach_pid (int pid)
4660{
4661 struct remote_state *rs = get_remote_state ();
4662
4663 if (remote_multi_process_p (rs))
4664 xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4665 else
4666 strcpy (rs->buf, "D");
4667
4668 putpkt (rs->buf);
4669 getpkt (&rs->buf, &rs->buf_size, 0);
4670
4671 if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4672 ;
4673 else if (rs->buf[0] == '\0')
4674 error (_("Remote doesn't know how to detach"));
4675 else
4676 error (_("Can't detach process."));
4677}
4678
4679/* This detaches a program to which we previously attached, using
4680 inferior_ptid to identify the process. After this is done, GDB
4681 can be used to debug some other program. We better not have left
4682 any breakpoints in the target program or it'll die when it hits
4683 one. */
c906108c
SS
4684
4685static void
de0d863e 4686remote_detach_1 (const char *args, int from_tty)
c906108c 4687{
82f73884 4688 int pid = ptid_get_pid (inferior_ptid);
d01949b6 4689 struct remote_state *rs = get_remote_state ();
de0d863e
DB
4690 struct thread_info *tp = find_thread_ptid (inferior_ptid);
4691 int is_fork_parent;
c906108c
SS
4692
4693 if (args)
8a3fe4f8 4694 error (_("Argument given to \"detach\" when remotely debugging."));
c906108c 4695
2d717e4f
DJ
4696 if (!target_has_execution)
4697 error (_("No process to detach from."));
4698
7cee1e54
PA
4699 if (from_tty)
4700 {
4701 char *exec_file = get_exec_file (0);
4702 if (exec_file == NULL)
4703 exec_file = "";
4704 printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4705 target_pid_to_str (pid_to_ptid (pid)));
4706 gdb_flush (gdb_stdout);
4707 }
4708
c906108c 4709 /* Tell the remote target to detach. */
de0d863e 4710 remote_detach_pid (pid);
82f73884 4711
de0d863e 4712 if (from_tty && !rs->extended)
7cee1e54 4713 puts_filtered (_("Ending remote debugging.\n"));
82f73884 4714
de0d863e
DB
4715 /* Check to see if we are detaching a fork parent. Note that if we
4716 are detaching a fork child, tp == NULL. */
4717 is_fork_parent = (tp != NULL
4718 && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4719
4720 /* If doing detach-on-fork, we don't mourn, because that will delete
4721 breakpoints that should be available for the followed inferior. */
4722 if (!is_fork_parent)
4723 target_mourn_inferior ();
4724 else
4725 {
4726 inferior_ptid = null_ptid;
4727 detach_inferior (pid);
4728 }
2d717e4f
DJ
4729}
4730
4731static void
52554a0e 4732remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4733{
de0d863e 4734 remote_detach_1 (args, from_tty);
2d717e4f
DJ
4735}
4736
4737static void
52554a0e 4738extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
2d717e4f 4739{
de0d863e
DB
4740 remote_detach_1 (args, from_tty);
4741}
4742
4743/* Target follow-fork function for remote targets. On entry, and
4744 at return, the current inferior is the fork parent.
4745
4746 Note that although this is currently only used for extended-remote,
4747 it is named remote_follow_fork in anticipation of using it for the
4748 remote target as well. */
4749
4750static int
4751remote_follow_fork (struct target_ops *ops, int follow_child,
4752 int detach_fork)
4753{
4754 struct remote_state *rs = get_remote_state ();
c269dbdb 4755 enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
de0d863e 4756
c269dbdb
DB
4757 if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4758 || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
de0d863e
DB
4759 {
4760 /* When following the parent and detaching the child, we detach
4761 the child here. For the case of following the child and
4762 detaching the parent, the detach is done in the target-
4763 independent follow fork code in infrun.c. We can't use
4764 target_detach when detaching an unfollowed child because
4765 the client side doesn't know anything about the child. */
4766 if (detach_fork && !follow_child)
4767 {
4768 /* Detach the fork child. */
4769 ptid_t child_ptid;
4770 pid_t child_pid;
4771
4772 child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4773 child_pid = ptid_get_pid (child_ptid);
4774
4775 remote_detach_pid (child_pid);
4776 detach_inferior (child_pid);
4777 }
4778 }
4779 return 0;
c906108c
SS
4780}
4781
6ad8ae5c
DJ
4782/* Same as remote_detach, but don't send the "D" packet; just disconnect. */
4783
43ff13b4 4784static void
fee354ee 4785remote_disconnect (struct target_ops *target, const char *args, int from_tty)
43ff13b4 4786{
43ff13b4 4787 if (args)
2d717e4f 4788 error (_("Argument given to \"disconnect\" when remotely debugging."));
43ff13b4 4789
2d717e4f 4790 /* Make sure we unpush even the extended remote targets; mourn
20f796c9 4791 won't do it. So call remote_mourn directly instead of
2d717e4f 4792 target_mourn_inferior. */
20f796c9 4793 remote_mourn (target);
2d717e4f 4794
43ff13b4
JM
4795 if (from_tty)
4796 puts_filtered ("Ending remote debugging.\n");
4797}
4798
2d717e4f
DJ
4799/* Attach to the process specified by ARGS. If FROM_TTY is non-zero,
4800 be chatty about it. */
4801
4802static void
20f796c9
GB
4803extended_remote_attach (struct target_ops *target, const char *args,
4804 int from_tty)
2d717e4f
DJ
4805{
4806 struct remote_state *rs = get_remote_state ();
be86555c 4807 int pid;
96ef3384 4808 char *wait_status = NULL;
2d717e4f 4809
74164c56 4810 pid = parse_pid_to_attach (args);
2d717e4f 4811
74164c56
JK
4812 /* Remote PID can be freely equal to getpid, do not check it here the same
4813 way as in other targets. */
2d717e4f 4814
4082afcc 4815 if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
2d717e4f
DJ
4816 error (_("This target does not support attaching to a process"));
4817
7cee1e54
PA
4818 if (from_tty)
4819 {
4820 char *exec_file = get_exec_file (0);
4821
4822 if (exec_file)
4823 printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4824 target_pid_to_str (pid_to_ptid (pid)));
4825 else
4826 printf_unfiltered (_("Attaching to %s\n"),
4827 target_pid_to_str (pid_to_ptid (pid)));
4828
4829 gdb_flush (gdb_stdout);
4830 }
4831
bba74b36 4832 xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
2d717e4f
DJ
4833 putpkt (rs->buf);
4834 getpkt (&rs->buf, &rs->buf_size, 0);
4835
4082afcc
PA
4836 switch (packet_ok (rs->buf,
4837 &remote_protocol_packets[PACKET_vAttach]))
2d717e4f 4838 {
4082afcc 4839 case PACKET_OK:
74531fed
PA
4840 if (!non_stop)
4841 {
4842 /* Save the reply for later. */
4843 wait_status = alloca (strlen (rs->buf) + 1);
4844 strcpy (wait_status, rs->buf);
4845 }
4846 else if (strcmp (rs->buf, "OK") != 0)
4847 error (_("Attaching to %s failed with: %s"),
4848 target_pid_to_str (pid_to_ptid (pid)),
4849 rs->buf);
4082afcc
PA
4850 break;
4851 case PACKET_UNKNOWN:
4852 error (_("This target does not support attaching to a process"));
4853 default:
4854 error (_("Attaching to %s failed"),
4855 target_pid_to_str (pid_to_ptid (pid)));
2d717e4f 4856 }
2d717e4f 4857
1b6e6f5c 4858 set_current_inferior (remote_add_inferior (0, pid, 1, 0));
bad34192 4859
2d717e4f 4860 inferior_ptid = pid_to_ptid (pid);
79d7f229 4861
bad34192
PA
4862 if (non_stop)
4863 {
4864 struct thread_info *thread;
79d7f229 4865
bad34192 4866 /* Get list of threads. */
e8032dde 4867 remote_update_thread_list (target);
82f73884 4868
bad34192
PA
4869 thread = first_thread_of_process (pid);
4870 if (thread)
4871 inferior_ptid = thread->ptid;
4872 else
4873 inferior_ptid = pid_to_ptid (pid);
4874
4875 /* Invalidate our notion of the remote current thread. */
47f8a51d 4876 record_currthread (rs, minus_one_ptid);
bad34192 4877 }
74531fed 4878 else
bad34192
PA
4879 {
4880 /* Now, if we have thread information, update inferior_ptid. */
4881 inferior_ptid = remote_current_thread (inferior_ptid);
4882
4883 /* Add the main thread to the thread list. */
4884 add_thread_silent (inferior_ptid);
4885 }
c0a2216e 4886
96ef3384
UW
4887 /* Next, if the target can specify a description, read it. We do
4888 this before anything involving memory or registers. */
4889 target_find_description ();
4890
74531fed
PA
4891 if (!non_stop)
4892 {
4893 /* Use the previously fetched status. */
4894 gdb_assert (wait_status != NULL);
4895
4896 if (target_can_async_p ())
4897 {
722247f1
YQ
4898 struct notif_event *reply
4899 = remote_notif_parse (&notif_client_stop, wait_status);
74531fed 4900
722247f1 4901 push_stop_reply ((struct stop_reply *) reply);
74531fed 4902
6a3753b3 4903 target_async (1);
74531fed
PA
4904 }
4905 else
4906 {
4907 gdb_assert (wait_status != NULL);
4908 strcpy (rs->buf, wait_status);
4909 rs->cached_wait_status = 1;
4910 }
4911 }
4912 else
4913 gdb_assert (wait_status == NULL);
2d717e4f
DJ
4914}
4915
b9c1d481
AS
4916/* Implementation of the to_post_attach method. */
4917
4918static void
4919extended_remote_post_attach (struct target_ops *ops, int pid)
4920{
4921 /* In certain cases GDB might not have had the chance to start
4922 symbol lookup up until now. This could happen if the debugged
4923 binary is not using shared libraries, the vsyscall page is not
4924 present (on Linux) and the binary itself hadn't changed since the
4925 debugging process was started. */
4926 if (symfile_objfile != NULL)
4927 remote_check_symbols();
4928}
4929
c906108c 4930\f
506fb367
DJ
4931/* Check for the availability of vCont. This function should also check
4932 the response. */
c906108c
SS
4933
4934static void
6d820c5c 4935remote_vcont_probe (struct remote_state *rs)
c906108c 4936{
2e9f7625 4937 char *buf;
6d820c5c 4938
2e9f7625
DJ
4939 strcpy (rs->buf, "vCont?");
4940 putpkt (rs->buf);
6d820c5c 4941 getpkt (&rs->buf, &rs->buf_size, 0);
2e9f7625 4942 buf = rs->buf;
c906108c 4943
506fb367 4944 /* Make sure that the features we assume are supported. */
61012eef 4945 if (startswith (buf, "vCont"))
506fb367
DJ
4946 {
4947 char *p = &buf[5];
4948 int support_s, support_S, support_c, support_C;
4949
4950 support_s = 0;
4951 support_S = 0;
4952 support_c = 0;
4953 support_C = 0;
d458bd84 4954 rs->supports_vCont.t = 0;
c1e36e3e 4955 rs->supports_vCont.r = 0;
506fb367
DJ
4956 while (p && *p == ';')
4957 {
4958 p++;
4959 if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4960 support_s = 1;
4961 else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4962 support_S = 1;
4963 else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4964 support_c = 1;
4965 else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4966 support_C = 1;
74531fed 4967 else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
d458bd84 4968 rs->supports_vCont.t = 1;
c1e36e3e
PA
4969 else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4970 rs->supports_vCont.r = 1;
506fb367
DJ
4971
4972 p = strchr (p, ';');
4973 }
c906108c 4974
506fb367
DJ
4975 /* If s, S, c, and C are not all supported, we can't use vCont. Clearing
4976 BUF will make packet_ok disable the packet. */
4977 if (!support_s || !support_S || !support_c || !support_C)
4978 buf[0] = 0;
4979 }
c906108c 4980
444abaca 4981 packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
506fb367 4982}
c906108c 4983
0d8f58ca
PA
4984/* Helper function for building "vCont" resumptions. Write a
4985 resumption to P. ENDP points to one-passed-the-end of the buffer
4986 we're allowed to write to. Returns BUF+CHARACTERS_WRITTEN. The
4987 thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4988 resumed thread should be single-stepped and/or signalled. If PTID
4989 equals minus_one_ptid, then all threads are resumed; if PTID
4990 represents a process, then all threads of the process are resumed;
4991 the thread to be stepped and/or signalled is given in the global
4992 INFERIOR_PTID. */
4993
4994static char *
4995append_resumption (char *p, char *endp,
2ea28649 4996 ptid_t ptid, int step, enum gdb_signal siggnal)
0d8f58ca
PA
4997{
4998 struct remote_state *rs = get_remote_state ();
4999
a493e3e2 5000 if (step && siggnal != GDB_SIGNAL_0)
0d8f58ca 5001 p += xsnprintf (p, endp - p, ";S%02x", siggnal);
c1e36e3e
PA
5002 else if (step
5003 /* GDB is willing to range step. */
5004 && use_range_stepping
5005 /* Target supports range stepping. */
5006 && rs->supports_vCont.r
5007 /* We don't currently support range stepping multiple
5008 threads with a wildcard (though the protocol allows it,
5009 so stubs shouldn't make an active effort to forbid
5010 it). */
5011 && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5012 {
5013 struct thread_info *tp;
5014
5015 if (ptid_equal (ptid, minus_one_ptid))
5016 {
5017 /* If we don't know about the target thread's tid, then
5018 we're resuming magic_null_ptid (see caller). */
5019 tp = find_thread_ptid (magic_null_ptid);
5020 }
5021 else
5022 tp = find_thread_ptid (ptid);
5023 gdb_assert (tp != NULL);
5024
5025 if (tp->control.may_range_step)
5026 {
5027 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5028
5029 p += xsnprintf (p, endp - p, ";r%s,%s",
5030 phex_nz (tp->control.step_range_start,
5031 addr_size),
5032 phex_nz (tp->control.step_range_end,
5033 addr_size));
5034 }
5035 else
5036 p += xsnprintf (p, endp - p, ";s");
5037 }
0d8f58ca
PA
5038 else if (step)
5039 p += xsnprintf (p, endp - p, ";s");
a493e3e2 5040 else if (siggnal != GDB_SIGNAL_0)
0d8f58ca
PA
5041 p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5042 else
5043 p += xsnprintf (p, endp - p, ";c");
5044
5045 if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5046 {
5047 ptid_t nptid;
5048
5049 /* All (-1) threads of process. */
ba348170 5050 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
0d8f58ca
PA
5051
5052 p += xsnprintf (p, endp - p, ":");
5053 p = write_ptid (p, endp, nptid);
5054 }
5055 else if (!ptid_equal (ptid, minus_one_ptid))
5056 {
5057 p += xsnprintf (p, endp - p, ":");
5058 p = write_ptid (p, endp, ptid);
5059 }
5060
5061 return p;
5062}
5063
e5ef252a
PA
5064/* Append a vCont continue-with-signal action for threads that have a
5065 non-zero stop signal. */
5066
5067static char *
5068append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5069{
5070 struct thread_info *thread;
5071
034f788c 5072 ALL_NON_EXITED_THREADS (thread)
e5ef252a
PA
5073 if (ptid_match (thread->ptid, ptid)
5074 && !ptid_equal (inferior_ptid, thread->ptid)
70509625 5075 && thread->suspend.stop_signal != GDB_SIGNAL_0)
e5ef252a
PA
5076 {
5077 p = append_resumption (p, endp, thread->ptid,
5078 0, thread->suspend.stop_signal);
5079 thread->suspend.stop_signal = GDB_SIGNAL_0;
5080 }
5081
5082 return p;
5083}
5084
506fb367
DJ
5085/* Resume the remote inferior by using a "vCont" packet. The thread
5086 to be resumed is PTID; STEP and SIGGNAL indicate whether the
79d7f229
PA
5087 resumed thread should be single-stepped and/or signalled. If PTID
5088 equals minus_one_ptid, then all threads are resumed; the thread to
5089 be stepped and/or signalled is given in the global INFERIOR_PTID.
5090 This function returns non-zero iff it resumes the inferior.
44eaed12 5091
506fb367
DJ
5092 This function issues a strict subset of all possible vCont commands at the
5093 moment. */
44eaed12 5094
506fb367 5095static int
2ea28649 5096remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
506fb367
DJ
5097{
5098 struct remote_state *rs = get_remote_state ();
82f73884
PA
5099 char *p;
5100 char *endp;
44eaed12 5101
4082afcc 5102 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6d820c5c 5103 remote_vcont_probe (rs);
44eaed12 5104
4082afcc 5105 if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6d820c5c 5106 return 0;
44eaed12 5107
82f73884
PA
5108 p = rs->buf;
5109 endp = rs->buf + get_remote_packet_size ();
5110
506fb367
DJ
5111 /* If we could generate a wider range of packets, we'd have to worry
5112 about overflowing BUF. Should there be a generic
5113 "multi-part-packet" packet? */
5114
0d8f58ca
PA
5115 p += xsnprintf (p, endp - p, "vCont");
5116
79d7f229 5117 if (ptid_equal (ptid, magic_null_ptid))
c906108c 5118 {
79d7f229
PA
5119 /* MAGIC_NULL_PTID means that we don't have any active threads,
5120 so we don't have any TID numbers the inferior will
5121 understand. Make sure to only send forms that do not specify
5122 a TID. */
a9cbf802 5123 append_resumption (p, endp, minus_one_ptid, step, siggnal);
506fb367 5124 }
0d8f58ca 5125 else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
506fb367 5126 {
0d8f58ca
PA
5127 /* Resume all threads (of all processes, or of a single
5128 process), with preference for INFERIOR_PTID. This assumes
5129 inferior_ptid belongs to the set of all threads we are about
5130 to resume. */
a493e3e2 5131 if (step || siggnal != GDB_SIGNAL_0)
82f73884 5132 {
0d8f58ca
PA
5133 /* Step inferior_ptid, with or without signal. */
5134 p = append_resumption (p, endp, inferior_ptid, step, siggnal);
82f73884 5135 }
0d8f58ca 5136
e5ef252a
PA
5137 /* Also pass down any pending signaled resumption for other
5138 threads not the current. */
5139 p = append_pending_thread_resumptions (p, endp, ptid);
5140
0d8f58ca 5141 /* And continue others without a signal. */
a493e3e2 5142 append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
c906108c
SS
5143 }
5144 else
506fb367
DJ
5145 {
5146 /* Scheduler locking; resume only PTID. */
a9cbf802 5147 append_resumption (p, endp, ptid, step, siggnal);
506fb367 5148 }
c906108c 5149
82f73884
PA
5150 gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5151 putpkt (rs->buf);
506fb367 5152
74531fed
PA
5153 if (non_stop)
5154 {
5155 /* In non-stop, the stub replies to vCont with "OK". The stop
5156 reply will be reported asynchronously by means of a `%Stop'
5157 notification. */
5158 getpkt (&rs->buf, &rs->buf_size, 0);
5159 if (strcmp (rs->buf, "OK") != 0)
5160 error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5161 }
5162
506fb367 5163 return 1;
c906108c 5164}
43ff13b4 5165
506fb367
DJ
5166/* Tell the remote machine to resume. */
5167
43ff13b4 5168static void
28439f5e 5169remote_resume (struct target_ops *ops,
2ea28649 5170 ptid_t ptid, int step, enum gdb_signal siggnal)
43ff13b4 5171{
d01949b6 5172 struct remote_state *rs = get_remote_state ();
2e9f7625 5173 char *buf;
43ff13b4 5174
722247f1
YQ
5175 /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5176 (explained in remote-notif.c:handle_notification) so
5177 remote_notif_process is not called. We need find a place where
5178 it is safe to start a 'vNotif' sequence. It is good to do it
5179 before resuming inferior, because inferior was stopped and no RSP
5180 traffic at that moment. */
5181 if (!non_stop)
5965e028 5182 remote_notif_process (rs->notif_state, &notif_client_stop);
722247f1 5183
b73be471 5184 rs->last_sent_signal = siggnal;
280ceea3 5185 rs->last_sent_step = step;
43ff13b4 5186
506fb367 5187 /* The vCont packet doesn't need to specify threads via Hc. */
40ab02ce
MS
5188 /* No reverse support (yet) for vCont. */
5189 if (execution_direction != EXEC_REVERSE)
5190 if (remote_vcont_resume (ptid, step, siggnal))
5191 goto done;
506fb367 5192
79d7f229
PA
5193 /* All other supported resume packets do use Hc, so set the continue
5194 thread. */
5195 if (ptid_equal (ptid, minus_one_ptid))
5196 set_continue_thread (any_thread_ptid);
506fb367 5197 else
79d7f229 5198 set_continue_thread (ptid);
506fb367 5199
2e9f7625 5200 buf = rs->buf;
b2175913
MS
5201 if (execution_direction == EXEC_REVERSE)
5202 {
5203 /* We don't pass signals to the target in reverse exec mode. */
a493e3e2 5204 if (info_verbose && siggnal != GDB_SIGNAL_0)
7ea6d463 5205 warning (_(" - Can't pass signal %d to target in reverse: ignored."),
b2175913 5206 siggnal);
40ab02ce 5207
4082afcc 5208 if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
40ab02ce 5209 error (_("Remote reverse-step not supported."));
4082afcc 5210 if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
08c93ed9 5211 error (_("Remote reverse-continue not supported."));
40ab02ce 5212
b2175913
MS
5213 strcpy (buf, step ? "bs" : "bc");
5214 }
a493e3e2 5215 else if (siggnal != GDB_SIGNAL_0)
43ff13b4
JM
5216 {
5217 buf[0] = step ? 'S' : 'C';
c5aa993b 5218 buf[1] = tohex (((int) siggnal >> 4) & 0xf);
506fb367 5219 buf[2] = tohex (((int) siggnal) & 0xf);
43ff13b4
JM
5220 buf[3] = '\0';
5221 }
5222 else
c5aa993b 5223 strcpy (buf, step ? "s" : "c");
506fb367 5224
44eaed12 5225 putpkt (buf);
43ff13b4 5226
75c99385 5227 done:
2acceee2 5228 /* We are about to start executing the inferior, let's register it
0df8b418
MS
5229 with the event loop. NOTE: this is the one place where all the
5230 execution commands end up. We could alternatively do this in each
23860348 5231 of the execution commands in infcmd.c. */
2acceee2
JM
5232 /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5233 into infcmd.c in order to allow inferior function calls to work
23860348 5234 NOT asynchronously. */
362646f5 5235 if (target_can_async_p ())
6a3753b3 5236 target_async (1);
e24a49d8
PA
5237
5238 /* We've just told the target to resume. The remote server will
5239 wait for the inferior to stop, and then send a stop reply. In
5240 the mean time, we can't start another command/query ourselves
74531fed
PA
5241 because the stub wouldn't be ready to process it. This applies
5242 only to the base all-stop protocol, however. In non-stop (which
5243 only supports vCont), the stub replies with an "OK", and is
5244 immediate able to process further serial input. */
5245 if (!non_stop)
5246 rs->waiting_for_stop_reply = 1;
43ff13b4 5247}
c906108c 5248\f
43ff13b4
JM
5249
5250/* Set up the signal handler for SIGINT, while the target is
23860348 5251 executing, ovewriting the 'regular' SIGINT signal handler. */
43ff13b4 5252static void
934b9bac 5253async_initialize_sigint_signal_handler (void)
43ff13b4 5254{
934b9bac 5255 signal (SIGINT, async_handle_remote_sigint);
43ff13b4
JM
5256}
5257
23860348 5258/* Signal handler for SIGINT, while the target is executing. */
43ff13b4 5259static void
934b9bac 5260async_handle_remote_sigint (int sig)
43ff13b4 5261{
934b9bac 5262 signal (sig, async_handle_remote_sigint_twice);
b2ee242b
PA
5263 /* Note we need to go through gdb_call_async_signal_handler in order
5264 to wake up the event loop on Windows. */
5265 gdb_call_async_signal_handler (async_sigint_remote_token, 0);
43ff13b4
JM
5266}
5267
5268/* Signal handler for SIGINT, installed after SIGINT has already been
5269 sent once. It will take effect the second time that the user sends
23860348 5270 a ^C. */
43ff13b4 5271static void
934b9bac 5272async_handle_remote_sigint_twice (int sig)
43ff13b4 5273{
934b9bac 5274 signal (sig, async_handle_remote_sigint);
b2ee242b
PA
5275 /* See note in async_handle_remote_sigint. */
5276 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
43ff13b4
JM
5277}
5278
abc56d60
PA
5279/* Implementation of to_check_pending_interrupt. */
5280
5281static void
5282remote_check_pending_interrupt (struct target_ops *self)
5283{
5284 struct async_signal_handler *token = async_sigint_remote_twice_token;
5285
5286 if (async_signal_handler_is_marked (token))
5287 {
5288 clear_async_signal_handler (token);
5289 call_async_signal_handler (token);
5290 }
5291}
5292
6426a772 5293/* Perform the real interruption of the target execution, in response
23860348 5294 to a ^C. */
c5aa993b 5295static void
fba45db2 5296async_remote_interrupt (gdb_client_data arg)
43ff13b4
JM
5297{
5298 if (remote_debug)
248fd3bf 5299 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
43ff13b4 5300
94cc34af 5301 target_stop (inferior_ptid);
43ff13b4
JM
5302}
5303
0df8b418 5304/* Perform interrupt, if the first attempt did not succeed. Just give
23860348 5305 up on the target alltogether. */
47e1ce27 5306static void
fba45db2 5307async_remote_interrupt_twice (gdb_client_data arg)
43ff13b4 5308{
2df3850c 5309 if (remote_debug)
248fd3bf 5310 fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
b803fb0f
DJ
5311
5312 interrupt_query ();
43ff13b4
JM
5313}
5314
5315/* Reinstall the usual SIGINT handlers, after the target has
23860348 5316 stopped. */
6426a772 5317static void
934b9bac 5318async_cleanup_sigint_signal_handler (void *dummy)
43ff13b4
JM
5319{
5320 signal (SIGINT, handle_sigint);
43ff13b4
JM
5321}
5322
c906108c
SS
5323/* Send ^C to target to halt it. Target will respond, and send us a
5324 packet. */
507f3c78 5325static void (*ofunc) (int);
c906108c 5326
bfedc46a
PA
5327/* The command line interface's interrupt routine. This function is installed
5328 as a signal handler for SIGINT. The first time a user requests an
5329 interrupt, we call remote_interrupt to send a break or ^C. If there is no
7a292a7a 5330 response from the target (it didn't stop when the user requested it),
23860348 5331 we ask the user if he'd like to detach from the target. */
bfedc46a 5332
c906108c 5333static void
934b9bac 5334sync_remote_interrupt (int signo)
c906108c 5335{
23860348 5336 /* If this doesn't work, try more severe steps. */
934b9bac 5337 signal (signo, sync_remote_interrupt_twice);
7a292a7a 5338
934b9bac 5339 gdb_call_async_signal_handler (async_sigint_remote_token, 1);
7a292a7a
SS
5340}
5341
5342/* The user typed ^C twice. */
5343
5344static void
934b9bac 5345sync_remote_interrupt_twice (int signo)
7a292a7a
SS
5346{
5347 signal (signo, ofunc);
934b9bac
JK
5348 gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5349 signal (signo, sync_remote_interrupt);
c906108c 5350}
7a292a7a 5351
74531fed
PA
5352/* Non-stop version of target_stop. Uses `vCont;t' to stop a remote
5353 thread, all threads of a remote process, or all threads of all
5354 processes. */
5355
5356static void
5357remote_stop_ns (ptid_t ptid)
5358{
5359 struct remote_state *rs = get_remote_state ();
5360 char *p = rs->buf;
5361 char *endp = rs->buf + get_remote_packet_size ();
74531fed 5362
4082afcc 5363 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
74531fed
PA
5364 remote_vcont_probe (rs);
5365
d458bd84 5366 if (!rs->supports_vCont.t)
74531fed
PA
5367 error (_("Remote server does not support stopping threads"));
5368
f91d3df5
PA
5369 if (ptid_equal (ptid, minus_one_ptid)
5370 || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
74531fed
PA
5371 p += xsnprintf (p, endp - p, "vCont;t");
5372 else
5373 {
5374 ptid_t nptid;
5375
74531fed
PA
5376 p += xsnprintf (p, endp - p, "vCont;t:");
5377
5378 if (ptid_is_pid (ptid))
5379 /* All (-1) threads of process. */
ba348170 5380 nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
74531fed
PA
5381 else
5382 {
5383 /* Small optimization: if we already have a stop reply for
5384 this thread, no use in telling the stub we want this
5385 stopped. */
5386 if (peek_stop_reply (ptid))
5387 return;
5388
5389 nptid = ptid;
5390 }
5391
a9cbf802 5392 write_ptid (p, endp, nptid);
74531fed
PA
5393 }
5394
5395 /* In non-stop, we get an immediate OK reply. The stop reply will
5396 come in asynchronously by notification. */
5397 putpkt (rs->buf);
5398 getpkt (&rs->buf, &rs->buf_size, 0);
5399 if (strcmp (rs->buf, "OK") != 0)
5400 error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5401}
5402
bfedc46a
PA
5403/* All-stop version of target_interrupt. Sends a break or a ^C to
5404 interrupt the remote target. It is undefined which thread of which
5405 process reports the interrupt. */
74531fed
PA
5406
5407static void
bfedc46a 5408remote_interrupt_as (ptid_t ptid)
74531fed
PA
5409{
5410 struct remote_state *rs = get_remote_state ();
5411
3a29589a
DJ
5412 rs->ctrlc_pending_p = 1;
5413
74531fed
PA
5414 /* If the inferior is stopped already, but the core didn't know
5415 about it yet, just ignore the request. The cached wait status
5416 will be collected in remote_wait. */
5417 if (rs->cached_wait_status)
5418 return;
5419
9a7071a8
JB
5420 /* Send interrupt_sequence to remote target. */
5421 send_interrupt_sequence ();
74531fed
PA
5422}
5423
bfedc46a 5424/* Implement the to_stop function for the remote targets. */
74531fed 5425
c906108c 5426static void
1eab8a48 5427remote_stop (struct target_ops *self, ptid_t ptid)
c906108c 5428{
7a292a7a 5429 if (remote_debug)
0f71a2f6 5430 fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
c906108c 5431
74531fed
PA
5432 if (non_stop)
5433 remote_stop_ns (ptid);
c906108c 5434 else
bfedc46a
PA
5435 {
5436 /* We don't currently have a way to transparently pause the
5437 remote target in all-stop mode. Interrupt it instead. */
5438 remote_interrupt_as (ptid);
5439 }
5440}
5441
5442/* Implement the to_interrupt function for the remote targets. */
5443
5444static void
5445remote_interrupt (struct target_ops *self, ptid_t ptid)
5446{
5447 if (remote_debug)
5448 fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
5449
5450 if (non_stop)
5451 {
5452 /* We don't currently have a way to ^C the remote target in
5453 non-stop mode. Stop it (with no signal) instead. */
5454 remote_stop_ns (ptid);
5455 }
5456 else
5457 remote_interrupt_as (ptid);
c906108c
SS
5458}
5459
5460/* Ask the user what to do when an interrupt is received. */
5461
5462static void
fba45db2 5463interrupt_query (void)
c906108c 5464{
abc56d60
PA
5465 struct remote_state *rs = get_remote_state ();
5466 struct cleanup *old_chain;
5467
5468 old_chain = make_cleanup_restore_target_terminal ();
c906108c
SS
5469 target_terminal_ours ();
5470
abc56d60 5471 if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
74531fed 5472 {
abc56d60
PA
5473 if (query (_("The target is not responding to interrupt requests.\n"
5474 "Stop debugging it? ")))
74531fed 5475 {
78a095c3 5476 remote_unpush_target ();
abc56d60 5477 throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
74531fed
PA
5478 }
5479 }
abc56d60
PA
5480 else
5481 {
5482 if (query (_("Interrupted while waiting for the program.\n"
5483 "Give up waiting? ")))
5484 quit ();
5485 }
c906108c 5486
abc56d60 5487 do_cleanups (old_chain);
c906108c
SS
5488}
5489
6426a772
JM
5490/* Enable/disable target terminal ownership. Most targets can use
5491 terminal groups to control terminal ownership. Remote targets are
5492 different in that explicit transfer of ownership to/from GDB/target
23860348 5493 is required. */
6426a772
JM
5494
5495static void
d2f640d4 5496remote_terminal_inferior (struct target_ops *self)
6426a772 5497{
c6ebd6cf 5498 if (!target_async_permitted)
75c99385
PA
5499 /* Nothing to do. */
5500 return;
5501
d9d2d8b6
PA
5502 /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5503 idempotent. The event-loop GDB talking to an asynchronous target
5504 with a synchronous command calls this function from both
5505 event-top.c and infrun.c/infcmd.c. Once GDB stops trying to
5506 transfer the terminal to the target when it shouldn't this guard
5507 can go away. */
6426a772
JM
5508 if (!remote_async_terminal_ours_p)
5509 return;
5510 delete_file_handler (input_fd);
5511 remote_async_terminal_ours_p = 0;
934b9bac 5512 async_initialize_sigint_signal_handler ();
6426a772
JM
5513 /* NOTE: At this point we could also register our selves as the
5514 recipient of all input. Any characters typed could then be
23860348 5515 passed on down to the target. */
6426a772
JM
5516}
5517
5518static void
e3594fd1 5519remote_terminal_ours (struct target_ops *self)
6426a772 5520{
c6ebd6cf 5521 if (!target_async_permitted)
75c99385
PA
5522 /* Nothing to do. */
5523 return;
5524
5525 /* See FIXME in remote_terminal_inferior. */
6426a772
JM
5526 if (remote_async_terminal_ours_p)
5527 return;
934b9bac 5528 async_cleanup_sigint_signal_handler (NULL);
6426a772
JM
5529 add_file_handler (input_fd, stdin_event_handler, 0);
5530 remote_async_terminal_ours_p = 1;
5531}
5532
176a6961 5533static void
917317f4 5534remote_console_output (char *msg)
c906108c
SS
5535{
5536 char *p;
5537
c5aa993b 5538 for (p = msg; p[0] && p[1]; p += 2)
c906108c
SS
5539 {
5540 char tb[2];
5541 char c = fromhex (p[0]) * 16 + fromhex (p[1]);
a744cf53 5542
c906108c
SS
5543 tb[0] = c;
5544 tb[1] = 0;
43ff13b4 5545 fputs_unfiltered (tb, gdb_stdtarg);
c906108c 5546 }
00db5b94
PA
5547 gdb_flush (gdb_stdtarg);
5548}
74531fed
PA
5549
5550typedef struct cached_reg
5551{
5552 int num;
5553 gdb_byte data[MAX_REGISTER_SIZE];
5554} cached_reg_t;
5555
5556DEF_VEC_O(cached_reg_t);
5557
722247f1 5558typedef struct stop_reply
74531fed 5559{
722247f1 5560 struct notif_event base;
74531fed 5561
722247f1 5562 /* The identifier of the thread about this event */
74531fed
PA
5563 ptid_t ptid;
5564
340e3c99 5565 /* The remote state this event is associated with. When the remote
bcc75809
YQ
5566 connection, represented by a remote_state object, is closed,
5567 all the associated stop_reply events should be released. */
5568 struct remote_state *rs;
5569
74531fed
PA
5570 struct target_waitstatus ws;
5571
15148d6a
PA
5572 /* Expedited registers. This makes remote debugging a bit more
5573 efficient for those targets that provide critical registers as
5574 part of their normal status mechanism (as another roundtrip to
5575 fetch them is avoided). */
74531fed
PA
5576 VEC(cached_reg_t) *regcache;
5577
f7e6eed5
PA
5578 enum target_stop_reason stop_reason;
5579
74531fed
PA
5580 CORE_ADDR watch_data_address;
5581
dc146f7c 5582 int core;
722247f1 5583} *stop_reply_p;
a744cf53 5584
722247f1
YQ
5585DECLARE_QUEUE_P (stop_reply_p);
5586DEFINE_QUEUE_P (stop_reply_p);
5587/* The list of already fetched and acknowledged stop events. This
5588 queue is used for notification Stop, and other notifications
5589 don't need queue for their events, because the notification events
5590 of Stop can't be consumed immediately, so that events should be
5591 queued first, and be consumed by remote_wait_{ns,as} one per
5592 time. Other notifications can consume their events immediately,
5593 so queue is not needed for them. */
5594static QUEUE (stop_reply_p) *stop_reply_queue;
74531fed
PA
5595
5596static void
5597stop_reply_xfree (struct stop_reply *r)
5598{
f48ff2a7 5599 notif_event_xfree ((struct notif_event *) r);
c906108c
SS
5600}
5601
221e1a37
PA
5602/* Return the length of the stop reply queue. */
5603
5604static int
5605stop_reply_queue_length (void)
5606{
5607 return QUEUE_length (stop_reply_p, stop_reply_queue);
5608}
5609
722247f1
YQ
5610static void
5611remote_notif_stop_parse (struct notif_client *self, char *buf,
5612 struct notif_event *event)
5613{
5614 remote_parse_stop_reply (buf, (struct stop_reply *) event);
5615}
5616
5617static void
5618remote_notif_stop_ack (struct notif_client *self, char *buf,
5619 struct notif_event *event)
5620{
5621 struct stop_reply *stop_reply = (struct stop_reply *) event;
5622
5623 /* acknowledge */
5624 putpkt ((char *) self->ack_command);
5625
5626 if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5627 /* We got an unknown stop reply. */
5628 error (_("Unknown stop reply"));
5629
5630 push_stop_reply (stop_reply);
5631}
5632
5633static int
5634remote_notif_stop_can_get_pending_events (struct notif_client *self)
5635{
5636 /* We can't get pending events in remote_notif_process for
5637 notification stop, and we have to do this in remote_wait_ns
5638 instead. If we fetch all queued events from stub, remote stub
5639 may exit and we have no chance to process them back in
5640 remote_wait_ns. */
5641 mark_async_event_handler (remote_async_inferior_event_token);
5642 return 0;
5643}
5644
5645static void
5646stop_reply_dtr (struct notif_event *event)
5647{
5648 struct stop_reply *r = (struct stop_reply *) event;
5649
5650 VEC_free (cached_reg_t, r->regcache);
5651}
5652
5653static struct notif_event *
5654remote_notif_stop_alloc_reply (void)
5655{
8d749320
SM
5656 /* We cast to a pointer to the "base class". */
5657 struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
722247f1
YQ
5658
5659 r->dtr = stop_reply_dtr;
5660
5661 return r;
5662}
5663
5664/* A client of notification Stop. */
5665
5666struct notif_client notif_client_stop =
5667{
5668 "Stop",
5669 "vStopped",
5670 remote_notif_stop_parse,
5671 remote_notif_stop_ack,
5672 remote_notif_stop_can_get_pending_events,
5673 remote_notif_stop_alloc_reply,
f48ff2a7 5674 REMOTE_NOTIF_STOP,
722247f1
YQ
5675};
5676
5677/* A parameter to pass data in and out. */
5678
5679struct queue_iter_param
5680{
5681 void *input;
5682 struct stop_reply *output;
5683};
5684
cbb8991c
DB
5685/* Determine if THREAD is a pending fork parent thread. ARG contains
5686 the pid of the process that owns the threads we want to check, or
5687 -1 if we want to check all threads. */
5688
5689static int
5690is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5691 ptid_t thread_ptid)
5692{
5693 if (ws->kind == TARGET_WAITKIND_FORKED
5694 || ws->kind == TARGET_WAITKIND_VFORKED)
5695 {
5696 if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5697 return 1;
5698 }
5699
5700 return 0;
5701}
5702
5703/* Check whether EVENT is a fork event, and if it is, remove the
5704 fork child from the context list passed in DATA. */
5705
5706static int
5707remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5708 QUEUE_ITER (stop_reply_p) *iter,
5709 stop_reply_p event,
5710 void *data)
5711{
5712 struct queue_iter_param *param = data;
5713 struct threads_listing_context *context = param->input;
5714
5715 if (event->ws.kind == TARGET_WAITKIND_FORKED
5716 || event->ws.kind == TARGET_WAITKIND_VFORKED)
5717 {
5718 threads_listing_context_remove (&event->ws, context);
5719 }
5720
5721 return 1;
5722}
5723
5724/* If CONTEXT contains any fork child threads that have not been
5725 reported yet, remove them from the CONTEXT list. If such a
5726 thread exists it is because we are stopped at a fork catchpoint
5727 and have not yet called follow_fork, which will set up the
5728 host-side data structures for the new process. */
5729
5730static void
5731remove_new_fork_children (struct threads_listing_context *context)
5732{
5733 struct thread_info * thread;
5734 int pid = -1;
5735 struct notif_client *notif = &notif_client_stop;
5736 struct queue_iter_param param;
5737
5738 /* For any threads stopped at a fork event, remove the corresponding
5739 fork child threads from the CONTEXT list. */
5740 ALL_NON_EXITED_THREADS (thread)
5741 {
5742 struct target_waitstatus *ws = &thread->pending_follow;
5743
5744 if (is_pending_fork_parent (ws, pid, thread->ptid))
5745 {
5746 threads_listing_context_remove (ws, context);
5747 }
5748 }
5749
5750 /* Check for any pending fork events (not reported or processed yet)
5751 in process PID and remove those fork child threads from the
5752 CONTEXT list as well. */
5753 remote_notif_get_pending_events (notif);
5754 param.input = context;
5755 param.output = NULL;
5756 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5757 remove_child_of_pending_fork, &param);
5758}
5759
f48ff2a7
YQ
5760/* Remove stop replies in the queue if its pid is equal to the given
5761 inferior's pid. */
722247f1
YQ
5762
5763static int
f48ff2a7
YQ
5764remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5765 QUEUE_ITER (stop_reply_p) *iter,
5766 stop_reply_p event,
5767 void *data)
722247f1
YQ
5768{
5769 struct queue_iter_param *param = data;
5770 struct inferior *inf = param->input;
5771
f48ff2a7 5772 if (ptid_get_pid (event->ptid) == inf->pid)
722247f1
YQ
5773 {
5774 stop_reply_xfree (event);
5775 QUEUE_remove_elem (stop_reply_p, q, iter);
5776 }
5777
5778 return 1;
5779}
5780
f48ff2a7 5781/* Discard all pending stop replies of inferior INF. */
c906108c 5782
74531fed 5783static void
5f4cf0bb 5784discard_pending_stop_replies (struct inferior *inf)
c906108c 5785{
722247f1
YQ
5786 int i;
5787 struct queue_iter_param param;
f48ff2a7
YQ
5788 struct stop_reply *reply;
5789 struct remote_state *rs = get_remote_state ();
5790 struct remote_notif_state *rns = rs->notif_state;
5791
5792 /* This function can be notified when an inferior exists. When the
5793 target is not remote, the notification state is NULL. */
5794 if (rs->remote_desc == NULL)
5795 return;
5796
5797 reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
c906108c 5798
74531fed 5799 /* Discard the in-flight notification. */
f48ff2a7 5800 if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
74531fed 5801 {
722247f1 5802 stop_reply_xfree (reply);
f48ff2a7 5803 rns->pending_event[notif_client_stop.id] = NULL;
74531fed 5804 }
c906108c 5805
722247f1
YQ
5806 param.input = inf;
5807 param.output = NULL;
74531fed
PA
5808 /* Discard the stop replies we have already pulled with
5809 vStopped. */
722247f1 5810 QUEUE_iterate (stop_reply_p, stop_reply_queue,
f48ff2a7
YQ
5811 remove_stop_reply_for_inferior, &param);
5812}
5813
bcc75809
YQ
5814/* If its remote state is equal to the given remote state,
5815 remove EVENT from the stop reply queue. */
5816
5817static int
5818remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5819 QUEUE_ITER (stop_reply_p) *iter,
5820 stop_reply_p event,
5821 void *data)
5822{
5823 struct queue_iter_param *param = data;
5824 struct remote_state *rs = param->input;
5825
5826 if (event->rs == rs)
5827 {
5828 stop_reply_xfree (event);
5829 QUEUE_remove_elem (stop_reply_p, q, iter);
5830 }
5831
5832 return 1;
5833}
5834
5835/* Discard the stop replies for RS in stop_reply_queue. */
f48ff2a7
YQ
5836
5837static void
bcc75809 5838discard_pending_stop_replies_in_queue (struct remote_state *rs)
f48ff2a7
YQ
5839{
5840 struct queue_iter_param param;
5841
bcc75809 5842 param.input = rs;
f48ff2a7
YQ
5843 param.output = NULL;
5844 /* Discard the stop replies we have already pulled with
5845 vStopped. */
5846 QUEUE_iterate (stop_reply_p, stop_reply_queue,
bcc75809 5847 remove_stop_reply_of_remote_state, &param);
722247f1 5848}
74531fed 5849
722247f1
YQ
5850/* A parameter to pass data in and out. */
5851
5852static int
5853remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5854 QUEUE_ITER (stop_reply_p) *iter,
5855 stop_reply_p event,
5856 void *data)
5857{
5858 struct queue_iter_param *param = data;
5859 ptid_t *ptid = param->input;
5860
5861 if (ptid_match (event->ptid, *ptid))
5862 {
5863 param->output = event;
5864 QUEUE_remove_elem (stop_reply_p, q, iter);
5865 return 0;
c8e38a49 5866 }
722247f1
YQ
5867
5868 return 1;
74531fed 5869}
43ff13b4 5870
722247f1
YQ
5871/* Remove the first reply in 'stop_reply_queue' which matches
5872 PTID. */
2e9f7625 5873
722247f1
YQ
5874static struct stop_reply *
5875remote_notif_remove_queued_reply (ptid_t ptid)
74531fed 5876{
722247f1
YQ
5877 struct queue_iter_param param;
5878
5879 param.input = &ptid;
5880 param.output = NULL;
5881
5882 QUEUE_iterate (stop_reply_p, stop_reply_queue,
5883 remote_notif_remove_once_on_match, &param);
5884 if (notif_debug)
5885 fprintf_unfiltered (gdb_stdlog,
5886 "notif: discard queued event: 'Stop' in %s\n",
5887 target_pid_to_str (ptid));
a744cf53 5888
722247f1 5889 return param.output;
74531fed 5890}
75c99385 5891
74531fed
PA
5892/* Look for a queued stop reply belonging to PTID. If one is found,
5893 remove it from the queue, and return it. Returns NULL if none is
5894 found. If there are still queued events left to process, tell the
5895 event loop to get back to target_wait soon. */
e24a49d8 5896
74531fed
PA
5897static struct stop_reply *
5898queued_stop_reply (ptid_t ptid)
5899{
722247f1 5900 struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
74531fed 5901
722247f1 5902 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed
PA
5903 /* There's still at least an event left. */
5904 mark_async_event_handler (remote_async_inferior_event_token);
5905
722247f1 5906 return r;
74531fed
PA
5907}
5908
5909/* Push a fully parsed stop reply in the stop reply queue. Since we
5910 know that we now have at least one queued event left to pass to the
5911 core side, tell the event loop to get back to target_wait soon. */
5912
5913static void
5914push_stop_reply (struct stop_reply *new_event)
5915{
722247f1 5916 QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
74531fed 5917
722247f1
YQ
5918 if (notif_debug)
5919 fprintf_unfiltered (gdb_stdlog,
5920 "notif: push 'Stop' %s to queue %d\n",
5921 target_pid_to_str (new_event->ptid),
5922 QUEUE_length (stop_reply_p,
5923 stop_reply_queue));
74531fed
PA
5924
5925 mark_async_event_handler (remote_async_inferior_event_token);
5926}
5927
722247f1
YQ
5928static int
5929stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5930 QUEUE_ITER (stop_reply_p) *iter,
5931 struct stop_reply *event,
5932 void *data)
5933{
5934 ptid_t *ptid = data;
5935
5936 return !(ptid_equal (*ptid, event->ptid)
5937 && event->ws.kind == TARGET_WAITKIND_STOPPED);
5938}
5939
74531fed
PA
5940/* Returns true if we have a stop reply for PTID. */
5941
5942static int
5943peek_stop_reply (ptid_t ptid)
5944{
722247f1
YQ
5945 return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5946 stop_reply_match_ptid_and_ws, &ptid);
74531fed
PA
5947}
5948
1f10ba14
PA
5949/* Skip PACKET until the next semi-colon (or end of string). */
5950
5951static char *
5952skip_to_semicolon (char *p)
5953{
5954 while (*p != '\0' && *p != ';')
5955 p++;
5956 return p;
5957}
5958
26d56a93
SL
5959/* Helper for remote_parse_stop_reply. Return nonzero if the substring
5960 starting with P and ending with PEND matches PREFIX. */
5961
5962static int
5963strprefix (const char *p, const char *pend, const char *prefix)
5964{
5965 for ( ; p < pend; p++, prefix++)
5966 if (*p != *prefix)
5967 return 0;
5968 return *prefix == '\0';
5969}
5970
74531fed
PA
5971/* Parse the stop reply in BUF. Either the function succeeds, and the
5972 result is stored in EVENT, or throws an error. */
5973
5974static void
5975remote_parse_stop_reply (char *buf, struct stop_reply *event)
5976{
5977 struct remote_arch_state *rsa = get_remote_arch_state ();
5978 ULONGEST addr;
5979 char *p;
5980
5981 event->ptid = null_ptid;
bcc75809 5982 event->rs = get_remote_state ();
74531fed
PA
5983 event->ws.kind = TARGET_WAITKIND_IGNORE;
5984 event->ws.value.integer = 0;
f7e6eed5 5985 event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed 5986 event->regcache = NULL;
dc146f7c 5987 event->core = -1;
74531fed
PA
5988
5989 switch (buf[0])
5990 {
5991 case 'T': /* Status with PC, SP, FP, ... */
cea39f65
MS
5992 /* Expedited reply, containing Signal, {regno, reg} repeat. */
5993 /* format is: 'Tssn...:r...;n...:r...;n...:r...;#cc', where
5994 ss = signal number
5995 n... = register number
5996 r... = register contents
5997 */
5998
5999 p = &buf[3]; /* after Txx */
6000 while (*p)
6001 {
6002 char *p1;
cea39f65 6003 int fieldsize;
43ff13b4 6004
1f10ba14
PA
6005 p1 = strchr (p, ':');
6006 if (p1 == NULL)
6007 error (_("Malformed packet(a) (missing colon): %s\n\
6008Packet: '%s'\n"),
6009 p, buf);
6010 if (p == p1)
6011 error (_("Malformed packet(a) (missing register number): %s\n\
6012Packet: '%s'\n"),
6013 p, buf);
3c3bea1c 6014
1f10ba14
PA
6015 /* Some "registers" are actually extended stop information.
6016 Note if you're adding a new entry here: GDB 7.9 and
6017 earlier assume that all register "numbers" that start
6018 with an hex digit are real register numbers. Make sure
6019 the server only sends such a packet if it knows the
6020 client understands it. */
c8e38a49 6021
26d56a93 6022 if (strprefix (p, p1, "thread"))
1f10ba14 6023 event->ptid = read_ptid (++p1, &p);
26d56a93
SL
6024 else if (strprefix (p, p1, "watch")
6025 || strprefix (p, p1, "rwatch")
6026 || strprefix (p, p1, "awatch"))
cea39f65 6027 {
f7e6eed5 6028 event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
1f10ba14
PA
6029 p = unpack_varlen_hex (++p1, &addr);
6030 event->watch_data_address = (CORE_ADDR) addr;
cea39f65 6031 }
26d56a93 6032 else if (strprefix (p, p1, "swbreak"))
f7e6eed5
PA
6033 {
6034 event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6035
6036 /* Make sure the stub doesn't forget to indicate support
6037 with qSupported. */
6038 if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6039 error (_("Unexpected swbreak stop reason"));
6040
6041 /* The value part is documented as "must be empty",
6042 though we ignore it, in case we ever decide to make
6043 use of it in a backward compatible way. */
6044 p = skip_to_semicolon (p1 + 1);
6045 }
26d56a93 6046 else if (strprefix (p, p1, "hwbreak"))
f7e6eed5
PA
6047 {
6048 event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6049
6050 /* Make sure the stub doesn't forget to indicate support
6051 with qSupported. */
6052 if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6053 error (_("Unexpected hwbreak stop reason"));
6054
6055 /* See above. */
6056 p = skip_to_semicolon (p1 + 1);
6057 }
26d56a93 6058 else if (strprefix (p, p1, "library"))
cea39f65 6059 {
1f10ba14
PA
6060 event->ws.kind = TARGET_WAITKIND_LOADED;
6061 p = skip_to_semicolon (p1 + 1);
6062 }
26d56a93 6063 else if (strprefix (p, p1, "replaylog"))
1f10ba14
PA
6064 {
6065 event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6066 /* p1 will indicate "begin" or "end", but it makes
6067 no difference for now, so ignore it. */
6068 p = skip_to_semicolon (p1 + 1);
6069 }
26d56a93 6070 else if (strprefix (p, p1, "core"))
1f10ba14
PA
6071 {
6072 ULONGEST c;
a744cf53 6073
1f10ba14
PA
6074 p = unpack_varlen_hex (++p1, &c);
6075 event->core = c;
cea39f65 6076 }
26d56a93 6077 else if (strprefix (p, p1, "fork"))
de0d863e
DB
6078 {
6079 event->ws.value.related_pid = read_ptid (++p1, &p);
6080 event->ws.kind = TARGET_WAITKIND_FORKED;
6081 }
26d56a93 6082 else if (strprefix (p, p1, "vfork"))
c269dbdb
DB
6083 {
6084 event->ws.value.related_pid = read_ptid (++p1, &p);
6085 event->ws.kind = TARGET_WAITKIND_VFORKED;
6086 }
26d56a93 6087 else if (strprefix (p, p1, "vforkdone"))
c269dbdb
DB
6088 {
6089 event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6090 p = skip_to_semicolon (p1 + 1);
6091 }
cea39f65
MS
6092 else
6093 {
1f10ba14
PA
6094 ULONGEST pnum;
6095 char *p_temp;
6096
6097 /* Maybe a real ``P'' register number. */
6098 p_temp = unpack_varlen_hex (p, &pnum);
6099 /* If the first invalid character is the colon, we got a
6100 register number. Otherwise, it's an unknown stop
6101 reason. */
6102 if (p_temp == p1)
6103 {
6104 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
6105 cached_reg_t cached_reg;
43ff13b4 6106
1f10ba14
PA
6107 if (reg == NULL)
6108 error (_("Remote sent bad register number %s: %s\n\
8a3fe4f8 6109Packet: '%s'\n"),
1f10ba14 6110 hex_string (pnum), p, buf);
c8e38a49 6111
1f10ba14 6112 cached_reg.num = reg->regnum;
4100683b 6113
1f10ba14
PA
6114 p = p1 + 1;
6115 fieldsize = hex2bin (p, cached_reg.data,
6116 register_size (target_gdbarch (),
6117 reg->regnum));
6118 p += 2 * fieldsize;
6119 if (fieldsize < register_size (target_gdbarch (),
6120 reg->regnum))
6121 warning (_("Remote reply is too short: %s"), buf);
74531fed 6122
1f10ba14
PA
6123 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6124 }
6125 else
6126 {
6127 /* Not a number. Silently skip unknown optional
6128 info. */
6129 p = skip_to_semicolon (p1 + 1);
6130 }
cea39f65 6131 }
c8e38a49 6132
cea39f65
MS
6133 if (*p != ';')
6134 error (_("Remote register badly formatted: %s\nhere: %s"),
6135 buf, p);
6136 ++p;
6137 }
5b5596ff
PA
6138
6139 if (event->ws.kind != TARGET_WAITKIND_IGNORE)
6140 break;
6141
c8e38a49
PA
6142 /* fall through */
6143 case 'S': /* Old style status, just signal only. */
3a09da41
PA
6144 {
6145 int sig;
6146
6147 event->ws.kind = TARGET_WAITKIND_STOPPED;
6148 sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
6149 if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
6150 event->ws.value.sig = (enum gdb_signal) sig;
6151 else
6152 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
6153 }
c8e38a49
PA
6154 break;
6155 case 'W': /* Target exited. */
6156 case 'X':
6157 {
6158 char *p;
6159 int pid;
6160 ULONGEST value;
82f73884 6161
c8e38a49
PA
6162 /* GDB used to accept only 2 hex chars here. Stubs should
6163 only send more if they detect GDB supports multi-process
6164 support. */
6165 p = unpack_varlen_hex (&buf[1], &value);
82f73884 6166
c8e38a49
PA
6167 if (buf[0] == 'W')
6168 {
6169 /* The remote process exited. */
74531fed
PA
6170 event->ws.kind = TARGET_WAITKIND_EXITED;
6171 event->ws.value.integer = value;
c8e38a49
PA
6172 }
6173 else
6174 {
6175 /* The remote process exited with a signal. */
74531fed 6176 event->ws.kind = TARGET_WAITKIND_SIGNALLED;
3a09da41
PA
6177 if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
6178 event->ws.value.sig = (enum gdb_signal) value;
6179 else
6180 event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
c8e38a49 6181 }
82f73884 6182
c8e38a49
PA
6183 /* If no process is specified, assume inferior_ptid. */
6184 pid = ptid_get_pid (inferior_ptid);
6185 if (*p == '\0')
6186 ;
6187 else if (*p == ';')
6188 {
6189 p++;
6190
0b24eb2d 6191 if (*p == '\0')
82f73884 6192 ;
61012eef 6193 else if (startswith (p, "process:"))
82f73884 6194 {
c8e38a49 6195 ULONGEST upid;
a744cf53 6196
c8e38a49
PA
6197 p += sizeof ("process:") - 1;
6198 unpack_varlen_hex (p, &upid);
6199 pid = upid;
82f73884
PA
6200 }
6201 else
6202 error (_("unknown stop reply packet: %s"), buf);
43ff13b4 6203 }
c8e38a49
PA
6204 else
6205 error (_("unknown stop reply packet: %s"), buf);
74531fed
PA
6206 event->ptid = pid_to_ptid (pid);
6207 }
6208 break;
6209 }
6210
6211 if (non_stop && ptid_equal (event->ptid, null_ptid))
6212 error (_("No process or thread specified in stop reply: %s"), buf);
6213}
6214
722247f1
YQ
6215/* When the stub wants to tell GDB about a new notification reply, it
6216 sends a notification (%Stop, for example). Those can come it at
6217 any time, hence, we have to make sure that any pending
6218 putpkt/getpkt sequence we're making is finished, before querying
6219 the stub for more events with the corresponding ack command
6220 (vStopped, for example). E.g., if we started a vStopped sequence
6221 immediately upon receiving the notification, something like this
6222 could happen:
74531fed
PA
6223
6224 1.1) --> Hg 1
6225 1.2) <-- OK
6226 1.3) --> g
6227 1.4) <-- %Stop
6228 1.5) --> vStopped
6229 1.6) <-- (registers reply to step #1.3)
6230
6231 Obviously, the reply in step #1.6 would be unexpected to a vStopped
6232 query.
6233
796cb314 6234 To solve this, whenever we parse a %Stop notification successfully,
74531fed
PA
6235 we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6236 doing whatever we were doing:
6237
6238 2.1) --> Hg 1
6239 2.2) <-- OK
6240 2.3) --> g
6241 2.4) <-- %Stop
6242 <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6243 2.5) <-- (registers reply to step #2.3)
6244
6245 Eventualy after step #2.5, we return to the event loop, which
6246 notices there's an event on the
6247 REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6248 associated callback --- the function below. At this point, we're
6249 always safe to start a vStopped sequence. :
6250
6251 2.6) --> vStopped
6252 2.7) <-- T05 thread:2
6253 2.8) --> vStopped
6254 2.9) --> OK
6255*/
6256
722247f1
YQ
6257void
6258remote_notif_get_pending_events (struct notif_client *nc)
74531fed
PA
6259{
6260 struct remote_state *rs = get_remote_state ();
74531fed 6261
f48ff2a7 6262 if (rs->notif_state->pending_event[nc->id] != NULL)
74531fed 6263 {
722247f1
YQ
6264 if (notif_debug)
6265 fprintf_unfiltered (gdb_stdlog,
6266 "notif: process: '%s' ack pending event\n",
6267 nc->name);
74531fed 6268
722247f1 6269 /* acknowledge */
f48ff2a7
YQ
6270 nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6271 rs->notif_state->pending_event[nc->id] = NULL;
74531fed
PA
6272
6273 while (1)
6274 {
6275 getpkt (&rs->buf, &rs->buf_size, 0);
6276 if (strcmp (rs->buf, "OK") == 0)
6277 break;
6278 else
722247f1 6279 remote_notif_ack (nc, rs->buf);
74531fed
PA
6280 }
6281 }
722247f1
YQ
6282 else
6283 {
6284 if (notif_debug)
6285 fprintf_unfiltered (gdb_stdlog,
6286 "notif: process: '%s' no pending reply\n",
6287 nc->name);
6288 }
74531fed
PA
6289}
6290
74531fed
PA
6291/* Called when it is decided that STOP_REPLY holds the info of the
6292 event that is to be returned to the core. This function always
6293 destroys STOP_REPLY. */
6294
6295static ptid_t
6296process_stop_reply (struct stop_reply *stop_reply,
6297 struct target_waitstatus *status)
6298{
6299 ptid_t ptid;
6300
6301 *status = stop_reply->ws;
6302 ptid = stop_reply->ptid;
6303
6304 /* If no thread/process was reported by the stub, assume the current
6305 inferior. */
6306 if (ptid_equal (ptid, null_ptid))
6307 ptid = inferior_ptid;
6308
5f3563ea
PA
6309 if (status->kind != TARGET_WAITKIND_EXITED
6310 && status->kind != TARGET_WAITKIND_SIGNALLED)
74531fed 6311 {
ee154bee
TT
6312 struct remote_state *rs = get_remote_state ();
6313
5f3563ea
PA
6314 /* Expedited registers. */
6315 if (stop_reply->regcache)
6316 {
217f1f79 6317 struct regcache *regcache
f5656ead 6318 = get_thread_arch_regcache (ptid, target_gdbarch ());
5f3563ea
PA
6319 cached_reg_t *reg;
6320 int ix;
6321
6322 for (ix = 0;
6323 VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6324 ix++)
217f1f79 6325 regcache_raw_supply (regcache, reg->num, reg->data);
5f3563ea
PA
6326 VEC_free (cached_reg_t, stop_reply->regcache);
6327 }
74531fed 6328
f7e6eed5 6329 rs->stop_reason = stop_reply->stop_reason;
ee154bee 6330 rs->remote_watch_data_address = stop_reply->watch_data_address;
1941c569
PA
6331
6332 remote_notice_new_inferior (ptid, 0);
dc146f7c 6333 demand_private_info (ptid)->core = stop_reply->core;
74531fed
PA
6334 }
6335
74531fed
PA
6336 stop_reply_xfree (stop_reply);
6337 return ptid;
6338}
6339
6340/* The non-stop mode version of target_wait. */
6341
6342static ptid_t
47608cb1 6343remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6344{
6345 struct remote_state *rs = get_remote_state ();
74531fed
PA
6346 struct stop_reply *stop_reply;
6347 int ret;
fee9eda9 6348 int is_notif = 0;
74531fed
PA
6349
6350 /* If in non-stop mode, get out of getpkt even if a
6351 notification is received. */
6352
6353 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6354 0 /* forever */, &is_notif);
74531fed
PA
6355 while (1)
6356 {
fee9eda9 6357 if (ret != -1 && !is_notif)
74531fed
PA
6358 switch (rs->buf[0])
6359 {
6360 case 'E': /* Error of some sort. */
6361 /* We're out of sync with the target now. Did it continue
6362 or not? We can't tell which thread it was in non-stop,
6363 so just ignore this. */
6364 warning (_("Remote failure reply: %s"), rs->buf);
6365 break;
6366 case 'O': /* Console output. */
6367 remote_console_output (rs->buf + 1);
6368 break;
6369 default:
6370 warning (_("Invalid remote reply: %s"), rs->buf);
6371 break;
6372 }
6373
6374 /* Acknowledge a pending stop reply that may have arrived in the
6375 mean time. */
f48ff2a7 6376 if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
722247f1 6377 remote_notif_get_pending_events (&notif_client_stop);
74531fed
PA
6378
6379 /* If indeed we noticed a stop reply, we're done. */
6380 stop_reply = queued_stop_reply (ptid);
6381 if (stop_reply != NULL)
6382 return process_stop_reply (stop_reply, status);
6383
47608cb1 6384 /* Still no event. If we're just polling for an event, then
74531fed 6385 return to the event loop. */
47608cb1 6386 if (options & TARGET_WNOHANG)
74531fed
PA
6387 {
6388 status->kind = TARGET_WAITKIND_IGNORE;
6389 return minus_one_ptid;
6390 }
6391
47608cb1 6392 /* Otherwise do a blocking wait. */
74531fed 6393 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
fee9eda9 6394 1 /* forever */, &is_notif);
74531fed
PA
6395 }
6396}
6397
6398/* Wait until the remote machine stops, then return, storing status in
6399 STATUS just as `wait' would. */
6400
6401static ptid_t
47608cb1 6402remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
74531fed
PA
6403{
6404 struct remote_state *rs = get_remote_state ();
74531fed 6405 ptid_t event_ptid = null_ptid;
cea39f65 6406 char *buf;
74531fed
PA
6407 struct stop_reply *stop_reply;
6408
47608cb1
PA
6409 again:
6410
74531fed
PA
6411 status->kind = TARGET_WAITKIND_IGNORE;
6412 status->value.integer = 0;
6413
6414 stop_reply = queued_stop_reply (ptid);
6415 if (stop_reply != NULL)
6416 return process_stop_reply (stop_reply, status);
6417
6418 if (rs->cached_wait_status)
6419 /* Use the cached wait status, but only once. */
6420 rs->cached_wait_status = 0;
6421 else
6422 {
6423 int ret;
722247f1 6424 int is_notif;
567420d1
PA
6425 int forever = ((options & TARGET_WNOHANG) == 0
6426 && wait_forever_enabled_p);
6427
6428 if (!rs->waiting_for_stop_reply)
6429 {
6430 status->kind = TARGET_WAITKIND_NO_RESUMED;
6431 return minus_one_ptid;
6432 }
74531fed
PA
6433
6434 if (!target_is_async_p ())
6435 {
934b9bac 6436 ofunc = signal (SIGINT, sync_remote_interrupt);
74531fed
PA
6437 /* If the user hit C-c before this packet, or between packets,
6438 pretend that it was hit right here. */
522002f9 6439 if (check_quit_flag ())
74531fed 6440 {
522002f9 6441 clear_quit_flag ();
934b9bac 6442 sync_remote_interrupt (SIGINT);
74531fed
PA
6443 }
6444 }
6445
6446 /* FIXME: cagney/1999-09-27: If we're in async mode we should
6447 _never_ wait for ever -> test on target_is_async_p().
6448 However, before we do that we need to ensure that the caller
6449 knows how to take the target into/out of async mode. */
722247f1 6450 ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
567420d1 6451 forever, &is_notif);
722247f1 6452
5e1b953b
SDJ
6453 if (!target_is_async_p ())
6454 signal (SIGINT, ofunc);
6455
722247f1
YQ
6456 /* GDB gets a notification. Return to core as this event is
6457 not interesting. */
6458 if (ret != -1 && is_notif)
6459 return minus_one_ptid;
567420d1
PA
6460
6461 if (ret == -1 && (options & TARGET_WNOHANG) != 0)
6462 return minus_one_ptid;
74531fed
PA
6463 }
6464
6465 buf = rs->buf;
6466
f7e6eed5 6467 rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
74531fed
PA
6468
6469 /* We got something. */
6470 rs->waiting_for_stop_reply = 0;
6471
3a29589a
DJ
6472 /* Assume that the target has acknowledged Ctrl-C unless we receive
6473 an 'F' or 'O' packet. */
6474 if (buf[0] != 'F' && buf[0] != 'O')
6475 rs->ctrlc_pending_p = 0;
6476
74531fed
PA
6477 switch (buf[0])
6478 {
6479 case 'E': /* Error of some sort. */
6480 /* We're out of sync with the target now. Did it continue or
6481 not? Not is more likely, so report a stop. */
6482 warning (_("Remote failure reply: %s"), buf);
6483 status->kind = TARGET_WAITKIND_STOPPED;
a493e3e2 6484 status->value.sig = GDB_SIGNAL_0;
74531fed
PA
6485 break;
6486 case 'F': /* File-I/O request. */
3a29589a
DJ
6487 remote_fileio_request (buf, rs->ctrlc_pending_p);
6488 rs->ctrlc_pending_p = 0;
74531fed
PA
6489 break;
6490 case 'T': case 'S': case 'X': case 'W':
6491 {
722247f1
YQ
6492 struct stop_reply *stop_reply
6493 = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6494 rs->buf);
74531fed 6495
74531fed 6496 event_ptid = process_stop_reply (stop_reply, status);
c8e38a49
PA
6497 break;
6498 }
6499 case 'O': /* Console output. */
6500 remote_console_output (buf + 1);
e24a49d8 6501
c8e38a49
PA
6502 /* The target didn't really stop; keep waiting. */
6503 rs->waiting_for_stop_reply = 1;
e24a49d8 6504
c8e38a49
PA
6505 break;
6506 case '\0':
b73be471 6507 if (rs->last_sent_signal != GDB_SIGNAL_0)
c8e38a49
PA
6508 {
6509 /* Zero length reply means that we tried 'S' or 'C' and the
6510 remote system doesn't support it. */
6511 target_terminal_ours_for_output ();
6512 printf_filtered
6513 ("Can't send signals to this remote system. %s not sent.\n",
b73be471
TT
6514 gdb_signal_to_name (rs->last_sent_signal));
6515 rs->last_sent_signal = GDB_SIGNAL_0;
c8e38a49
PA
6516 target_terminal_inferior ();
6517
280ceea3 6518 strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
c8e38a49
PA
6519 putpkt ((char *) buf);
6520
6521 /* We just told the target to resume, so a stop reply is in
6522 order. */
e24a49d8 6523 rs->waiting_for_stop_reply = 1;
c8e38a49 6524 break;
43ff13b4 6525 }
c8e38a49
PA
6526 /* else fallthrough */
6527 default:
6528 warning (_("Invalid remote reply: %s"), buf);
6529 /* Keep waiting. */
6530 rs->waiting_for_stop_reply = 1;
6531 break;
43ff13b4 6532 }
c8e38a49 6533
c8e38a49 6534 if (status->kind == TARGET_WAITKIND_IGNORE)
47608cb1
PA
6535 {
6536 /* Nothing interesting happened. If we're doing a non-blocking
6537 poll, we're done. Otherwise, go back to waiting. */
6538 if (options & TARGET_WNOHANG)
6539 return minus_one_ptid;
6540 else
6541 goto again;
6542 }
74531fed
PA
6543 else if (status->kind != TARGET_WAITKIND_EXITED
6544 && status->kind != TARGET_WAITKIND_SIGNALLED)
82f73884
PA
6545 {
6546 if (!ptid_equal (event_ptid, null_ptid))
47f8a51d 6547 record_currthread (rs, event_ptid);
82f73884
PA
6548 else
6549 event_ptid = inferior_ptid;
43ff13b4 6550 }
74531fed
PA
6551 else
6552 /* A process exit. Invalidate our notion of current thread. */
47f8a51d 6553 record_currthread (rs, minus_one_ptid);
79d7f229 6554
82f73884 6555 return event_ptid;
43ff13b4
JM
6556}
6557
74531fed
PA
6558/* Wait until the remote machine stops, then return, storing status in
6559 STATUS just as `wait' would. */
6560
c8e38a49 6561static ptid_t
117de6a9 6562remote_wait (struct target_ops *ops,
47608cb1 6563 ptid_t ptid, struct target_waitstatus *status, int options)
c8e38a49
PA
6564{
6565 ptid_t event_ptid;
6566
74531fed 6567 if (non_stop)
47608cb1 6568 event_ptid = remote_wait_ns (ptid, status, options);
74531fed 6569 else
47608cb1 6570 event_ptid = remote_wait_as (ptid, status, options);
c8e38a49 6571
d9d41e78 6572 if (target_is_async_p ())
c8e38a49 6573 {
74531fed
PA
6574 /* If there are are events left in the queue tell the event loop
6575 to return here. */
722247f1 6576 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
74531fed 6577 mark_async_event_handler (remote_async_inferior_event_token);
c8e38a49 6578 }
c8e38a49
PA
6579
6580 return event_ptid;
6581}
6582
74ca34ce 6583/* Fetch a single register using a 'p' packet. */
c906108c 6584
b96ec7ac 6585static int
56be3814 6586fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
b96ec7ac
AC
6587{
6588 struct remote_state *rs = get_remote_state ();
2e9f7625 6589 char *buf, *p;
b96ec7ac
AC
6590 char regp[MAX_REGISTER_SIZE];
6591 int i;
6592
4082afcc 6593 if (packet_support (PACKET_p) == PACKET_DISABLE)
74ca34ce
DJ
6594 return 0;
6595
6596 if (reg->pnum == -1)
6597 return 0;
6598
2e9f7625 6599 p = rs->buf;
fcad0fa4 6600 *p++ = 'p';
74ca34ce 6601 p += hexnumstr (p, reg->pnum);
fcad0fa4 6602 *p++ = '\0';
1f4437a4
MS
6603 putpkt (rs->buf);
6604 getpkt (&rs->buf, &rs->buf_size, 0);
3f9a994c 6605
2e9f7625
DJ
6606 buf = rs->buf;
6607
74ca34ce
DJ
6608 switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6609 {
6610 case PACKET_OK:
6611 break;
6612 case PACKET_UNKNOWN:
6613 return 0;
6614 case PACKET_ERROR:
27a9c0bf
MS
6615 error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6616 gdbarch_register_name (get_regcache_arch (regcache),
6617 reg->regnum),
6618 buf);
74ca34ce 6619 }
3f9a994c
JB
6620
6621 /* If this register is unfetchable, tell the regcache. */
6622 if (buf[0] == 'x')
8480adf2 6623 {
56be3814 6624 regcache_raw_supply (regcache, reg->regnum, NULL);
8480adf2 6625 return 1;
b96ec7ac 6626 }
b96ec7ac 6627
3f9a994c
JB
6628 /* Otherwise, parse and supply the value. */
6629 p = buf;
6630 i = 0;
6631 while (p[0] != 0)
6632 {
6633 if (p[1] == 0)
74ca34ce 6634 error (_("fetch_register_using_p: early buf termination"));
3f9a994c
JB
6635
6636 regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6637 p += 2;
6638 }
56be3814 6639 regcache_raw_supply (regcache, reg->regnum, regp);
3f9a994c 6640 return 1;
b96ec7ac
AC
6641}
6642
74ca34ce
DJ
6643/* Fetch the registers included in the target's 'g' packet. */
6644
29709017
DJ
6645static int
6646send_g_packet (void)
c906108c 6647{
d01949b6 6648 struct remote_state *rs = get_remote_state ();
cea39f65 6649 int buf_len;
c906108c 6650
bba74b36 6651 xsnprintf (rs->buf, get_remote_packet_size (), "g");
74ca34ce 6652 remote_send (&rs->buf, &rs->buf_size);
c906108c 6653
29709017
DJ
6654 /* We can get out of synch in various cases. If the first character
6655 in the buffer is not a hex character, assume that has happened
6656 and try to fetch another packet to read. */
6657 while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6658 && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6659 && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6660 && rs->buf[0] != 'x') /* New: unavailable register value. */
6661 {
6662 if (remote_debug)
6663 fprintf_unfiltered (gdb_stdlog,
6664 "Bad register packet; fetching a new packet\n");
6665 getpkt (&rs->buf, &rs->buf_size, 0);
6666 }
6667
74ca34ce
DJ
6668 buf_len = strlen (rs->buf);
6669
6670 /* Sanity check the received packet. */
6671 if (buf_len % 2 != 0)
6672 error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
29709017
DJ
6673
6674 return buf_len / 2;
6675}
6676
6677static void
56be3814 6678process_g_packet (struct regcache *regcache)
29709017 6679{
4a22f64d 6680 struct gdbarch *gdbarch = get_regcache_arch (regcache);
29709017
DJ
6681 struct remote_state *rs = get_remote_state ();
6682 struct remote_arch_state *rsa = get_remote_arch_state ();
6683 int i, buf_len;
6684 char *p;
6685 char *regs;
6686
6687 buf_len = strlen (rs->buf);
6688
6689 /* Further sanity checks, with knowledge of the architecture. */
74ca34ce
DJ
6690 if (buf_len > 2 * rsa->sizeof_g_packet)
6691 error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6692
6693 /* Save the size of the packet sent to us by the target. It is used
6694 as a heuristic when determining the max size of packets that the
6695 target can safely receive. */
6696 if (rsa->actual_register_packet_size == 0)
6697 rsa->actual_register_packet_size = buf_len;
6698
6699 /* If this is smaller than we guessed the 'g' packet would be,
6700 update our records. A 'g' reply that doesn't include a register's
6701 value implies either that the register is not available, or that
6702 the 'p' packet must be used. */
6703 if (buf_len < 2 * rsa->sizeof_g_packet)
b323314b 6704 {
74ca34ce
DJ
6705 rsa->sizeof_g_packet = buf_len / 2;
6706
4a22f64d 6707 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
b96ec7ac 6708 {
74ca34ce
DJ
6709 if (rsa->regs[i].pnum == -1)
6710 continue;
6711
6712 if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6713 rsa->regs[i].in_g_packet = 0;
b96ec7ac 6714 else
74ca34ce 6715 rsa->regs[i].in_g_packet = 1;
b96ec7ac 6716 }
74ca34ce 6717 }
b323314b 6718
74ca34ce 6719 regs = alloca (rsa->sizeof_g_packet);
c906108c
SS
6720
6721 /* Unimplemented registers read as all bits zero. */
ea9c271d 6722 memset (regs, 0, rsa->sizeof_g_packet);
c906108c 6723
c906108c
SS
6724 /* Reply describes registers byte by byte, each byte encoded as two
6725 hex characters. Suck them all up, then supply them to the
6726 register cacheing/storage mechanism. */
6727
74ca34ce 6728 p = rs->buf;
ea9c271d 6729 for (i = 0; i < rsa->sizeof_g_packet; i++)
c906108c 6730 {
74ca34ce
DJ
6731 if (p[0] == 0 || p[1] == 0)
6732 /* This shouldn't happen - we adjusted sizeof_g_packet above. */
6733 internal_error (__FILE__, __LINE__,
9b20d036 6734 _("unexpected end of 'g' packet reply"));
74ca34ce 6735
c906108c 6736 if (p[0] == 'x' && p[1] == 'x')
c5aa993b 6737 regs[i] = 0; /* 'x' */
c906108c
SS
6738 else
6739 regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6740 p += 2;
6741 }
6742
a744cf53
MS
6743 for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6744 {
6745 struct packet_reg *r = &rsa->regs[i];
6746
6747 if (r->in_g_packet)
6748 {
6749 if (r->offset * 2 >= strlen (rs->buf))
6750 /* This shouldn't happen - we adjusted in_g_packet above. */
6751 internal_error (__FILE__, __LINE__,
9b20d036 6752 _("unexpected end of 'g' packet reply"));
a744cf53
MS
6753 else if (rs->buf[r->offset * 2] == 'x')
6754 {
6755 gdb_assert (r->offset * 2 < strlen (rs->buf));
6756 /* The register isn't available, mark it as such (at
6757 the same time setting the value to zero). */
6758 regcache_raw_supply (regcache, r->regnum, NULL);
6759 }
6760 else
6761 regcache_raw_supply (regcache, r->regnum,
6762 regs + r->offset);
6763 }
6764 }
c906108c
SS
6765}
6766
29709017 6767static void
56be3814 6768fetch_registers_using_g (struct regcache *regcache)
29709017
DJ
6769{
6770 send_g_packet ();
56be3814 6771 process_g_packet (regcache);
29709017
DJ
6772}
6773
e6e4e701
PA
6774/* Make the remote selected traceframe match GDB's selected
6775 traceframe. */
6776
6777static void
6778set_remote_traceframe (void)
6779{
6780 int newnum;
262e1174 6781 struct remote_state *rs = get_remote_state ();
e6e4e701 6782
262e1174 6783 if (rs->remote_traceframe_number == get_traceframe_number ())
e6e4e701
PA
6784 return;
6785
6786 /* Avoid recursion, remote_trace_find calls us again. */
262e1174 6787 rs->remote_traceframe_number = get_traceframe_number ();
e6e4e701
PA
6788
6789 newnum = target_trace_find (tfind_number,
6790 get_traceframe_number (), 0, 0, NULL);
6791
6792 /* Should not happen. If it does, all bets are off. */
6793 if (newnum != get_traceframe_number ())
6794 warning (_("could not set remote traceframe"));
6795}
6796
74ca34ce 6797static void
28439f5e
PA
6798remote_fetch_registers (struct target_ops *ops,
6799 struct regcache *regcache, int regnum)
74ca34ce 6800{
74ca34ce
DJ
6801 struct remote_arch_state *rsa = get_remote_arch_state ();
6802 int i;
6803
e6e4e701 6804 set_remote_traceframe ();
79d7f229 6805 set_general_thread (inferior_ptid);
74ca34ce
DJ
6806
6807 if (regnum >= 0)
6808 {
6809 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6810
74ca34ce
DJ
6811 gdb_assert (reg != NULL);
6812
6813 /* If this register might be in the 'g' packet, try that first -
6814 we are likely to read more than one register. If this is the
6815 first 'g' packet, we might be overly optimistic about its
6816 contents, so fall back to 'p'. */
6817 if (reg->in_g_packet)
6818 {
56be3814 6819 fetch_registers_using_g (regcache);
74ca34ce
DJ
6820 if (reg->in_g_packet)
6821 return;
6822 }
6823
56be3814 6824 if (fetch_register_using_p (regcache, reg))
74ca34ce
DJ
6825 return;
6826
6827 /* This register is not available. */
56be3814 6828 regcache_raw_supply (regcache, reg->regnum, NULL);
74ca34ce
DJ
6829
6830 return;
6831 }
6832
56be3814 6833 fetch_registers_using_g (regcache);
74ca34ce 6834
4a22f64d 6835 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6836 if (!rsa->regs[i].in_g_packet)
56be3814 6837 if (!fetch_register_using_p (regcache, &rsa->regs[i]))
74ca34ce
DJ
6838 {
6839 /* This register is not available. */
56be3814 6840 regcache_raw_supply (regcache, i, NULL);
74ca34ce
DJ
6841 }
6842}
6843
c906108c
SS
6844/* Prepare to store registers. Since we may send them all (using a
6845 'G' request), we have to read out the ones we don't want to change
6846 first. */
6847
c5aa993b 6848static void
f32dbf8c 6849remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
c906108c 6850{
ea9c271d 6851 struct remote_arch_state *rsa = get_remote_arch_state ();
cf0e1e0d 6852 int i;
cfd77fa1 6853 gdb_byte buf[MAX_REGISTER_SIZE];
cf0e1e0d 6854
c906108c 6855 /* Make sure the entire registers array is valid. */
4082afcc 6856 switch (packet_support (PACKET_P))
5a2468f5
JM
6857 {
6858 case PACKET_DISABLE:
6859 case PACKET_SUPPORT_UNKNOWN:
cf0e1e0d 6860 /* Make sure all the necessary registers are cached. */
4a22f64d 6861 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
ea9c271d 6862 if (rsa->regs[i].in_g_packet)
316f2060 6863 regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5a2468f5
JM
6864 break;
6865 case PACKET_ENABLE:
6866 break;
6867 }
6868}
6869
ad10f812 6870/* Helper: Attempt to store REGNUM using the P packet. Return fail IFF
23860348 6871 packet was not recognized. */
5a2468f5
JM
6872
6873static int
1f4437a4
MS
6874store_register_using_P (const struct regcache *regcache,
6875 struct packet_reg *reg)
5a2468f5 6876{
4a22f64d 6877 struct gdbarch *gdbarch = get_regcache_arch (regcache);
d01949b6 6878 struct remote_state *rs = get_remote_state ();
5a2468f5 6879 /* Try storing a single register. */
6d820c5c 6880 char *buf = rs->buf;
cfd77fa1 6881 gdb_byte regp[MAX_REGISTER_SIZE];
5a2468f5 6882 char *p;
5a2468f5 6883
4082afcc 6884 if (packet_support (PACKET_P) == PACKET_DISABLE)
74ca34ce
DJ
6885 return 0;
6886
6887 if (reg->pnum == -1)
6888 return 0;
6889
ea9c271d 6890 xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5a2468f5 6891 p = buf + strlen (buf);
56be3814 6892 regcache_raw_collect (regcache, reg->regnum, regp);
4a22f64d 6893 bin2hex (regp, p, register_size (gdbarch, reg->regnum));
1f4437a4
MS
6894 putpkt (rs->buf);
6895 getpkt (&rs->buf, &rs->buf_size, 0);
5a2468f5 6896
74ca34ce
DJ
6897 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6898 {
6899 case PACKET_OK:
6900 return 1;
6901 case PACKET_ERROR:
27a9c0bf
MS
6902 error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6903 gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
74ca34ce
DJ
6904 case PACKET_UNKNOWN:
6905 return 0;
6906 default:
6907 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6908 }
c906108c
SS
6909}
6910
23860348
MS
6911/* Store register REGNUM, or all registers if REGNUM == -1, from the
6912 contents of the register cache buffer. FIXME: ignores errors. */
c906108c
SS
6913
6914static void
56be3814 6915store_registers_using_G (const struct regcache *regcache)
c906108c 6916{
d01949b6 6917 struct remote_state *rs = get_remote_state ();
ea9c271d 6918 struct remote_arch_state *rsa = get_remote_arch_state ();
cfd77fa1 6919 gdb_byte *regs;
c906108c
SS
6920 char *p;
6921
193cb69f
AC
6922 /* Extract all the registers in the regcache copying them into a
6923 local buffer. */
6924 {
b323314b 6925 int i;
a744cf53 6926
ea9c271d
DJ
6927 regs = alloca (rsa->sizeof_g_packet);
6928 memset (regs, 0, rsa->sizeof_g_packet);
4a22f64d 6929 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
193cb69f 6930 {
ea9c271d 6931 struct packet_reg *r = &rsa->regs[i];
a744cf53 6932
b323314b 6933 if (r->in_g_packet)
56be3814 6934 regcache_raw_collect (regcache, r->regnum, regs + r->offset);
193cb69f
AC
6935 }
6936 }
c906108c
SS
6937
6938 /* Command describes registers byte by byte,
6939 each byte encoded as two hex characters. */
6d820c5c 6940 p = rs->buf;
193cb69f 6941 *p++ = 'G';
74ca34ce
DJ
6942 /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6943 updated. */
6944 bin2hex (regs, p, rsa->sizeof_g_packet);
1f4437a4
MS
6945 putpkt (rs->buf);
6946 getpkt (&rs->buf, &rs->buf_size, 0);
6947 if (packet_check_result (rs->buf) == PACKET_ERROR)
27a9c0bf
MS
6948 error (_("Could not write registers; remote failure reply '%s'"),
6949 rs->buf);
c906108c 6950}
74ca34ce
DJ
6951
6952/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6953 of the register cache buffer. FIXME: ignores errors. */
6954
6955static void
28439f5e
PA
6956remote_store_registers (struct target_ops *ops,
6957 struct regcache *regcache, int regnum)
74ca34ce 6958{
74ca34ce
DJ
6959 struct remote_arch_state *rsa = get_remote_arch_state ();
6960 int i;
6961
e6e4e701 6962 set_remote_traceframe ();
79d7f229 6963 set_general_thread (inferior_ptid);
74ca34ce
DJ
6964
6965 if (regnum >= 0)
6966 {
6967 struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
a744cf53 6968
74ca34ce
DJ
6969 gdb_assert (reg != NULL);
6970
6971 /* Always prefer to store registers using the 'P' packet if
6972 possible; we often change only a small number of registers.
6973 Sometimes we change a larger number; we'd need help from a
6974 higher layer to know to use 'G'. */
56be3814 6975 if (store_register_using_P (regcache, reg))
74ca34ce
DJ
6976 return;
6977
6978 /* For now, don't complain if we have no way to write the
6979 register. GDB loses track of unavailable registers too
6980 easily. Some day, this may be an error. We don't have
0df8b418 6981 any way to read the register, either... */
74ca34ce
DJ
6982 if (!reg->in_g_packet)
6983 return;
6984
56be3814 6985 store_registers_using_G (regcache);
74ca34ce
DJ
6986 return;
6987 }
6988
56be3814 6989 store_registers_using_G (regcache);
74ca34ce 6990
4a22f64d 6991 for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
74ca34ce 6992 if (!rsa->regs[i].in_g_packet)
56be3814 6993 if (!store_register_using_P (regcache, &rsa->regs[i]))
74ca34ce
DJ
6994 /* See above for why we do not issue an error here. */
6995 continue;
6996}
c906108c
SS
6997\f
6998
6999/* Return the number of hex digits in num. */
7000
7001static int
fba45db2 7002hexnumlen (ULONGEST num)
c906108c
SS
7003{
7004 int i;
7005
7006 for (i = 0; num != 0; i++)
7007 num >>= 4;
7008
7009 return max (i, 1);
7010}
7011
2df3850c 7012/* Set BUF to the minimum number of hex digits representing NUM. */
c906108c
SS
7013
7014static int
fba45db2 7015hexnumstr (char *buf, ULONGEST num)
c906108c 7016{
c906108c 7017 int len = hexnumlen (num);
a744cf53 7018
2df3850c
JM
7019 return hexnumnstr (buf, num, len);
7020}
7021
c906108c 7022
2df3850c 7023/* Set BUF to the hex digits representing NUM, padded to WIDTH characters. */
c906108c 7024
2df3850c 7025static int
fba45db2 7026hexnumnstr (char *buf, ULONGEST num, int width)
2df3850c
JM
7027{
7028 int i;
7029
7030 buf[width] = '\0';
7031
7032 for (i = width - 1; i >= 0; i--)
c906108c 7033 {
c5aa993b 7034 buf[i] = "0123456789abcdef"[(num & 0xf)];
c906108c
SS
7035 num >>= 4;
7036 }
7037
2df3850c 7038 return width;
c906108c
SS
7039}
7040
23860348 7041/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
c906108c
SS
7042
7043static CORE_ADDR
fba45db2 7044remote_address_masked (CORE_ADDR addr)
c906108c 7045{
883b9c6c 7046 unsigned int address_size = remote_address_size;
a744cf53 7047
911c95a5
UW
7048 /* If "remoteaddresssize" was not set, default to target address size. */
7049 if (!address_size)
f5656ead 7050 address_size = gdbarch_addr_bit (target_gdbarch ());
911c95a5
UW
7051
7052 if (address_size > 0
7053 && address_size < (sizeof (ULONGEST) * 8))
c906108c
SS
7054 {
7055 /* Only create a mask when that mask can safely be constructed
23860348 7056 in a ULONGEST variable. */
c906108c 7057 ULONGEST mask = 1;
a744cf53 7058
911c95a5 7059 mask = (mask << address_size) - 1;
c906108c
SS
7060 addr &= mask;
7061 }
7062 return addr;
7063}
7064
7065/* Determine whether the remote target supports binary downloading.
7066 This is accomplished by sending a no-op memory write of zero length
7067 to the target at the specified address. It does not suffice to send
23860348
MS
7068 the whole packet, since many stubs strip the eighth bit and
7069 subsequently compute a wrong checksum, which causes real havoc with
7070 remote_write_bytes.
7a292a7a 7071
96baa820 7072 NOTE: This can still lose if the serial line is not eight-bit
0df8b418 7073 clean. In cases like this, the user should clear "remote
23860348 7074 X-packet". */
96baa820 7075
c906108c 7076static void
fba45db2 7077check_binary_download (CORE_ADDR addr)
c906108c 7078{
d01949b6 7079 struct remote_state *rs = get_remote_state ();
24b06219 7080
4082afcc 7081 switch (packet_support (PACKET_X))
c906108c 7082 {
96baa820
JM
7083 case PACKET_DISABLE:
7084 break;
7085 case PACKET_ENABLE:
7086 break;
7087 case PACKET_SUPPORT_UNKNOWN:
7088 {
96baa820 7089 char *p;
802188a7 7090
2e9f7625 7091 p = rs->buf;
96baa820
JM
7092 *p++ = 'X';
7093 p += hexnumstr (p, (ULONGEST) addr);
7094 *p++ = ',';
7095 p += hexnumstr (p, (ULONGEST) 0);
7096 *p++ = ':';
7097 *p = '\0';
802188a7 7098
2e9f7625 7099 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7100 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 7101
2e9f7625 7102 if (rs->buf[0] == '\0')
96baa820
JM
7103 {
7104 if (remote_debug)
7105 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
7106 "binary downloading NOT "
7107 "supported by target\n");
444abaca 7108 remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
96baa820
JM
7109 }
7110 else
7111 {
7112 if (remote_debug)
7113 fprintf_unfiltered (gdb_stdlog,
64b9b334 7114 "binary downloading supported by target\n");
444abaca 7115 remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
96baa820
JM
7116 }
7117 break;
7118 }
c906108c
SS
7119 }
7120}
7121
124e13d9
SM
7122/* Helper function to resize the payload in order to try to get a good
7123 alignment. We try to write an amount of data such that the next write will
7124 start on an address aligned on REMOTE_ALIGN_WRITES. */
7125
7126static int
7127align_for_efficient_write (int todo, CORE_ADDR memaddr)
7128{
7129 return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7130}
7131
c906108c
SS
7132/* Write memory data directly to the remote machine.
7133 This does not inform the data cache; the data cache uses this.
a76d924d 7134 HEADER is the starting part of the packet.
c906108c
SS
7135 MEMADDR is the address in the remote memory space.
7136 MYADDR is the address of the buffer in our space.
124e13d9
SM
7137 LEN_UNITS is the number of addressable units to write.
7138 UNIT_SIZE is the length in bytes of an addressable unit.
a76d924d
DJ
7139 PACKET_FORMAT should be either 'X' or 'M', and indicates if we
7140 should send data as binary ('X'), or hex-encoded ('M').
7141
7142 The function creates packet of the form
7143 <HEADER><ADDRESS>,<LENGTH>:<DATA>
7144
124e13d9 7145 where encoding of <DATA> is terminated by PACKET_FORMAT.
a76d924d
DJ
7146
7147 If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
7148 are omitted.
7149
9b409511 7150 Return the transferred status, error or OK (an
124e13d9
SM
7151 'enum target_xfer_status' value). Save the number of addressable units
7152 transferred in *XFERED_LEN_UNITS. Only transfer a single packet.
7153
7154 On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
7155 exchange between gdb and the stub could look like (?? in place of the
7156 checksum):
7157
7158 -> $m1000,4#??
7159 <- aaaabbbbccccdddd
7160
7161 -> $M1000,3:eeeeffffeeee#??
7162 <- OK
7163
7164 -> $m1000,4#??
7165 <- eeeeffffeeeedddd */
c906108c 7166
9b409511 7167static enum target_xfer_status
a76d924d 7168remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
124e13d9
SM
7169 const gdb_byte *myaddr, ULONGEST len_units,
7170 int unit_size, ULONGEST *xfered_len_units,
7171 char packet_format, int use_length)
c906108c 7172{
6d820c5c 7173 struct remote_state *rs = get_remote_state ();
cfd77fa1 7174 char *p;
a76d924d
DJ
7175 char *plen = NULL;
7176 int plenlen = 0;
124e13d9
SM
7177 int todo_units;
7178 int units_written;
7179 int payload_capacity_bytes;
7180 int payload_length_bytes;
a76d924d
DJ
7181
7182 if (packet_format != 'X' && packet_format != 'M')
7183 internal_error (__FILE__, __LINE__,
9b20d036 7184 _("remote_write_bytes_aux: bad packet format"));
c906108c 7185
124e13d9 7186 if (len_units == 0)
9b409511 7187 return TARGET_XFER_EOF;
b2182ed2 7188
124e13d9 7189 payload_capacity_bytes = get_memory_write_packet_size ();
2bc416ba 7190
6d820c5c
DJ
7191 /* The packet buffer will be large enough for the payload;
7192 get_memory_packet_size ensures this. */
a76d924d 7193 rs->buf[0] = '\0';
c906108c 7194
a257b5bb 7195 /* Compute the size of the actual payload by subtracting out the
0df8b418
MS
7196 packet header and footer overhead: "$M<memaddr>,<len>:...#nn". */
7197
124e13d9 7198 payload_capacity_bytes -= strlen ("$,:#NN");
a76d924d 7199 if (!use_length)
0df8b418 7200 /* The comma won't be used. */
124e13d9
SM
7201 payload_capacity_bytes += 1;
7202 payload_capacity_bytes -= strlen (header);
7203 payload_capacity_bytes -= hexnumlen (memaddr);
c906108c 7204
a76d924d 7205 /* Construct the packet excluding the data: "<header><memaddr>,<len>:". */
917317f4 7206
a76d924d
DJ
7207 strcat (rs->buf, header);
7208 p = rs->buf + strlen (header);
7209
7210 /* Compute a best guess of the number of bytes actually transfered. */
7211 if (packet_format == 'X')
c906108c 7212 {
23860348 7213 /* Best guess at number of bytes that will fit. */
124e13d9 7214 todo_units = min (len_units, payload_capacity_bytes / unit_size);
a76d924d 7215 if (use_length)
124e13d9
SM
7216 payload_capacity_bytes -= hexnumlen (todo_units);
7217 todo_units = min (todo_units, payload_capacity_bytes / unit_size);
a76d924d
DJ
7218 }
7219 else
7220 {
124e13d9
SM
7221 /* Number of bytes that will fit. */
7222 todo_units = min (len_units, (payload_capacity_bytes / unit_size) / 2);
a76d924d 7223 if (use_length)
124e13d9
SM
7224 payload_capacity_bytes -= hexnumlen (todo_units);
7225 todo_units = min (todo_units, (payload_capacity_bytes / unit_size) / 2);
917317f4 7226 }
a76d924d 7227
124e13d9 7228 if (todo_units <= 0)
3de11b2e 7229 internal_error (__FILE__, __LINE__,
405f8e94 7230 _("minimum packet size too small to write data"));
802188a7 7231
6765f3e5
DJ
7232 /* If we already need another packet, then try to align the end
7233 of this packet to a useful boundary. */
124e13d9
SM
7234 if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
7235 todo_units = align_for_efficient_write (todo_units, memaddr);
6765f3e5 7236
a257b5bb 7237 /* Append "<memaddr>". */
917317f4
JM
7238 memaddr = remote_address_masked (memaddr);
7239 p += hexnumstr (p, (ULONGEST) memaddr);
a257b5bb 7240
a76d924d
DJ
7241 if (use_length)
7242 {
7243 /* Append ",". */
7244 *p++ = ',';
802188a7 7245
124e13d9
SM
7246 /* Append the length and retain its location and size. It may need to be
7247 adjusted once the packet body has been created. */
a76d924d 7248 plen = p;
124e13d9 7249 plenlen = hexnumstr (p, (ULONGEST) todo_units);
a76d924d
DJ
7250 p += plenlen;
7251 }
a257b5bb
AC
7252
7253 /* Append ":". */
917317f4
JM
7254 *p++ = ':';
7255 *p = '\0';
802188a7 7256
a257b5bb 7257 /* Append the packet body. */
a76d924d 7258 if (packet_format == 'X')
917317f4 7259 {
917317f4
JM
7260 /* Binary mode. Send target system values byte by byte, in
7261 increasing byte addresses. Only escape certain critical
7262 characters. */
124e13d9
SM
7263 payload_length_bytes =
7264 remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
7265 &units_written, payload_capacity_bytes);
6765f3e5 7266
124e13d9 7267 /* If not all TODO units fit, then we'll need another packet. Make
9b7194bc
DJ
7268 a second try to keep the end of the packet aligned. Don't do
7269 this if the packet is tiny. */
124e13d9 7270 if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
6765f3e5 7271 {
124e13d9
SM
7272 int new_todo_units;
7273
7274 new_todo_units = align_for_efficient_write (units_written, memaddr);
7275
7276 if (new_todo_units != units_written)
7277 payload_length_bytes =
7278 remote_escape_output (myaddr, new_todo_units, unit_size,
7279 (gdb_byte *) p, &units_written,
7280 payload_capacity_bytes);
6765f3e5
DJ
7281 }
7282
124e13d9
SM
7283 p += payload_length_bytes;
7284 if (use_length && units_written < todo_units)
c906108c 7285 {
802188a7 7286 /* Escape chars have filled up the buffer prematurely,
124e13d9 7287 and we have actually sent fewer units than planned.
917317f4
JM
7288 Fix-up the length field of the packet. Use the same
7289 number of characters as before. */
124e13d9
SM
7290 plen += hexnumnstr (plen, (ULONGEST) units_written,
7291 plenlen);
917317f4 7292 *plen = ':'; /* overwrite \0 from hexnumnstr() */
c906108c 7293 }
a76d924d
DJ
7294 }
7295 else
7296 {
917317f4
JM
7297 /* Normal mode: Send target system values byte by byte, in
7298 increasing byte addresses. Each byte is encoded as a two hex
7299 value. */
124e13d9
SM
7300 p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
7301 units_written = todo_units;
c906108c 7302 }
802188a7 7303
2e9f7625 7304 putpkt_binary (rs->buf, (int) (p - rs->buf));
6d820c5c 7305 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 7306
2e9f7625 7307 if (rs->buf[0] == 'E')
00d84524 7308 return TARGET_XFER_E_IO;
802188a7 7309
124e13d9
SM
7310 /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
7311 send fewer units than we'd planned. */
7312 *xfered_len_units = (ULONGEST) units_written;
9b409511 7313 return TARGET_XFER_OK;
c906108c
SS
7314}
7315
a76d924d
DJ
7316/* Write memory data directly to the remote machine.
7317 This does not inform the data cache; the data cache uses this.
7318 MEMADDR is the address in the remote memory space.
7319 MYADDR is the address of the buffer in our space.
7320 LEN is the number of bytes.
7321
9b409511
YQ
7322 Return the transferred status, error or OK (an
7323 'enum target_xfer_status' value). Save the number of bytes
7324 transferred in *XFERED_LEN. Only transfer a single packet. */
a76d924d 7325
9b409511
YQ
7326static enum target_xfer_status
7327remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
124e13d9 7328 int unit_size, ULONGEST *xfered_len)
a76d924d
DJ
7329{
7330 char *packet_format = 0;
7331
7332 /* Check whether the target supports binary download. */
7333 check_binary_download (memaddr);
7334
4082afcc 7335 switch (packet_support (PACKET_X))
a76d924d
DJ
7336 {
7337 case PACKET_ENABLE:
7338 packet_format = "X";
7339 break;
7340 case PACKET_DISABLE:
7341 packet_format = "M";
7342 break;
7343 case PACKET_SUPPORT_UNKNOWN:
7344 internal_error (__FILE__, __LINE__,
7345 _("remote_write_bytes: bad internal state"));
7346 default:
7347 internal_error (__FILE__, __LINE__, _("bad switch"));
7348 }
7349
7350 return remote_write_bytes_aux (packet_format,
124e13d9 7351 memaddr, myaddr, len, unit_size, xfered_len,
9b409511 7352 packet_format[0], 1);
a76d924d
DJ
7353}
7354
9217e74e
YQ
7355/* Read memory data directly from the remote machine.
7356 This does not use the data cache; the data cache uses this.
7357 MEMADDR is the address in the remote memory space.
7358 MYADDR is the address of the buffer in our space.
124e13d9
SM
7359 LEN_UNITS is the number of addressable memory units to read..
7360 UNIT_SIZE is the length in bytes of an addressable unit.
9217e74e
YQ
7361
7362 Return the transferred status, error or OK (an
7363 'enum target_xfer_status' value). Save the number of bytes
124e13d9
SM
7364 transferred in *XFERED_LEN_UNITS.
7365
7366 See the comment of remote_write_bytes_aux for an example of
7367 memory read/write exchange between gdb and the stub. */
9217e74e
YQ
7368
7369static enum target_xfer_status
124e13d9
SM
7370remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
7371 int unit_size, ULONGEST *xfered_len_units)
9217e74e
YQ
7372{
7373 struct remote_state *rs = get_remote_state ();
124e13d9 7374 int buf_size_bytes; /* Max size of packet output buffer. */
9217e74e 7375 char *p;
124e13d9
SM
7376 int todo_units;
7377 int decoded_bytes;
9217e74e 7378
124e13d9 7379 buf_size_bytes = get_memory_read_packet_size ();
9217e74e
YQ
7380 /* The packet buffer will be large enough for the payload;
7381 get_memory_packet_size ensures this. */
7382
124e13d9
SM
7383 /* Number of units that will fit. */
7384 todo_units = min (len_units, (buf_size_bytes / unit_size) / 2);
9217e74e
YQ
7385
7386 /* Construct "m"<memaddr>","<len>". */
7387 memaddr = remote_address_masked (memaddr);
7388 p = rs->buf;
7389 *p++ = 'm';
7390 p += hexnumstr (p, (ULONGEST) memaddr);
7391 *p++ = ',';
124e13d9 7392 p += hexnumstr (p, (ULONGEST) todo_units);
9217e74e
YQ
7393 *p = '\0';
7394 putpkt (rs->buf);
7395 getpkt (&rs->buf, &rs->buf_size, 0);
7396 if (rs->buf[0] == 'E'
7397 && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7398 && rs->buf[3] == '\0')
7399 return TARGET_XFER_E_IO;
7400 /* Reply describes memory byte by byte, each byte encoded as two hex
7401 characters. */
7402 p = rs->buf;
124e13d9 7403 decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
9217e74e 7404 /* Return what we have. Let higher layers handle partial reads. */
124e13d9 7405 *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
9217e74e
YQ
7406 return TARGET_XFER_OK;
7407}
7408
b55fbac4
YQ
7409/* Using the set of read-only target sections of remote, read live
7410 read-only memory.
8acf9577
YQ
7411
7412 For interface/parameters/return description see target.h,
7413 to_xfer_partial. */
7414
7415static enum target_xfer_status
b55fbac4
YQ
7416remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7417 ULONGEST memaddr, ULONGEST len,
124e13d9 7418 int unit_size, ULONGEST *xfered_len)
8acf9577
YQ
7419{
7420 struct target_section *secp;
7421 struct target_section_table *table;
7422
7423 secp = target_section_by_addr (ops, memaddr);
7424 if (secp != NULL
7425 && (bfd_get_section_flags (secp->the_bfd_section->owner,
7426 secp->the_bfd_section)
7427 & SEC_READONLY))
7428 {
7429 struct target_section *p;
7430 ULONGEST memend = memaddr + len;
7431
7432 table = target_get_section_table (ops);
7433
7434 for (p = table->sections; p < table->sections_end; p++)
7435 {
7436 if (memaddr >= p->addr)
7437 {
7438 if (memend <= p->endaddr)
7439 {
7440 /* Entire transfer is within this section. */
124e13d9 7441 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7442 xfered_len);
8acf9577
YQ
7443 }
7444 else if (memaddr >= p->endaddr)
7445 {
7446 /* This section ends before the transfer starts. */
7447 continue;
7448 }
7449 else
7450 {
7451 /* This section overlaps the transfer. Just do half. */
7452 len = p->endaddr - memaddr;
124e13d9 7453 return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
b55fbac4 7454 xfered_len);
8acf9577
YQ
7455 }
7456 }
7457 }
7458 }
7459
7460 return TARGET_XFER_EOF;
7461}
7462
9217e74e
YQ
7463/* Similar to remote_read_bytes_1, but it reads from the remote stub
7464 first if the requested memory is unavailable in traceframe.
7465 Otherwise, fall back to remote_read_bytes_1. */
c906108c 7466
9b409511 7467static enum target_xfer_status
8acf9577 7468remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
124e13d9
SM
7469 gdb_byte *myaddr, ULONGEST len, int unit_size,
7470 ULONGEST *xfered_len)
c906108c 7471{
6b6aa828 7472 if (len == 0)
96c4f946 7473 return TARGET_XFER_EOF;
b2182ed2 7474
8acf9577
YQ
7475 if (get_traceframe_number () != -1)
7476 {
7477 VEC(mem_range_s) *available;
7478
7479 /* If we fail to get the set of available memory, then the
7480 target does not support querying traceframe info, and so we
7481 attempt reading from the traceframe anyway (assuming the
7482 target implements the old QTro packet then). */
7483 if (traceframe_available_memory (&available, memaddr, len))
7484 {
7485 struct cleanup *old_chain;
7486
7487 old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7488
7489 if (VEC_empty (mem_range_s, available)
7490 || VEC_index (mem_range_s, available, 0)->start != memaddr)
7491 {
7492 enum target_xfer_status res;
7493
7494 /* Don't read into the traceframe's available
7495 memory. */
7496 if (!VEC_empty (mem_range_s, available))
7497 {
7498 LONGEST oldlen = len;
7499
7500 len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7501 gdb_assert (len <= oldlen);
7502 }
7503
7504 do_cleanups (old_chain);
7505
7506 /* This goes through the topmost target again. */
b55fbac4 7507 res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
124e13d9 7508 len, unit_size, xfered_len);
8acf9577
YQ
7509 if (res == TARGET_XFER_OK)
7510 return TARGET_XFER_OK;
7511 else
7512 {
7513 /* No use trying further, we know some memory starting
7514 at MEMADDR isn't available. */
7515 *xfered_len = len;
7516 return TARGET_XFER_UNAVAILABLE;
7517 }
7518 }
7519
7520 /* Don't try to read more than how much is available, in
7521 case the target implements the deprecated QTro packet to
7522 cater for older GDBs (the target's knowledge of read-only
7523 sections may be outdated by now). */
7524 len = VEC_index (mem_range_s, available, 0)->length;
7525
7526 do_cleanups (old_chain);
7527 }
7528 }
7529
124e13d9 7530 return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
c906108c 7531}
74531fed 7532
c906108c 7533\f
c906108c 7534
a76d924d
DJ
7535/* Sends a packet with content determined by the printf format string
7536 FORMAT and the remaining arguments, then gets the reply. Returns
7537 whether the packet was a success, a failure, or unknown. */
7538
77b64a49
PA
7539static enum packet_result remote_send_printf (const char *format, ...)
7540 ATTRIBUTE_PRINTF (1, 2);
7541
2c0b251b 7542static enum packet_result
a76d924d
DJ
7543remote_send_printf (const char *format, ...)
7544{
7545 struct remote_state *rs = get_remote_state ();
7546 int max_size = get_remote_packet_size ();
a76d924d 7547 va_list ap;
a744cf53 7548
a76d924d
DJ
7549 va_start (ap, format);
7550
7551 rs->buf[0] = '\0';
7552 if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9b20d036 7553 internal_error (__FILE__, __LINE__, _("Too long remote packet."));
a76d924d
DJ
7554
7555 if (putpkt (rs->buf) < 0)
7556 error (_("Communication problem with target."));
7557
7558 rs->buf[0] = '\0';
7559 getpkt (&rs->buf, &rs->buf_size, 0);
7560
7561 return packet_check_result (rs->buf);
7562}
7563
7564static void
7565restore_remote_timeout (void *p)
7566{
7567 int value = *(int *)p;
a744cf53 7568
a76d924d
DJ
7569 remote_timeout = value;
7570}
7571
7572/* Flash writing can take quite some time. We'll set
7573 effectively infinite timeout for flash operations.
7574 In future, we'll need to decide on a better approach. */
7575static const int remote_flash_timeout = 1000;
7576
7577static void
7578remote_flash_erase (struct target_ops *ops,
7579 ULONGEST address, LONGEST length)
7580{
f5656ead 7581 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
a76d924d
DJ
7582 int saved_remote_timeout = remote_timeout;
7583 enum packet_result ret;
a76d924d
DJ
7584 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7585 &saved_remote_timeout);
a744cf53 7586
a76d924d
DJ
7587 remote_timeout = remote_flash_timeout;
7588
7589 ret = remote_send_printf ("vFlashErase:%s,%s",
5af949e3 7590 phex (address, addr_size),
a76d924d
DJ
7591 phex (length, 4));
7592 switch (ret)
7593 {
7594 case PACKET_UNKNOWN:
7595 error (_("Remote target does not support flash erase"));
7596 case PACKET_ERROR:
7597 error (_("Error erasing flash with vFlashErase packet"));
7598 default:
7599 break;
7600 }
7601
7602 do_cleanups (back_to);
7603}
7604
9b409511
YQ
7605static enum target_xfer_status
7606remote_flash_write (struct target_ops *ops, ULONGEST address,
7607 ULONGEST length, ULONGEST *xfered_len,
7608 const gdb_byte *data)
a76d924d
DJ
7609{
7610 int saved_remote_timeout = remote_timeout;
9b409511 7611 enum target_xfer_status ret;
a76d924d 7612 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
9b409511 7613 &saved_remote_timeout);
a76d924d
DJ
7614
7615 remote_timeout = remote_flash_timeout;
124e13d9 7616 ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9b409511 7617 xfered_len,'X', 0);
a76d924d
DJ
7618 do_cleanups (back_to);
7619
7620 return ret;
7621}
7622
7623static void
7624remote_flash_done (struct target_ops *ops)
7625{
7626 int saved_remote_timeout = remote_timeout;
7627 int ret;
7628 struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7629 &saved_remote_timeout);
7630
7631 remote_timeout = remote_flash_timeout;
7632 ret = remote_send_printf ("vFlashDone");
7633 do_cleanups (back_to);
7634
7635 switch (ret)
7636 {
7637 case PACKET_UNKNOWN:
7638 error (_("Remote target does not support vFlashDone"));
7639 case PACKET_ERROR:
7640 error (_("Error finishing flash operation"));
7641 default:
7642 break;
7643 }
7644}
7645
c906108c 7646static void
fba45db2 7647remote_files_info (struct target_ops *ignore)
c906108c
SS
7648{
7649 puts_filtered ("Debugging a target over a serial line.\n");
7650}
7651\f
7652/* Stuff for dealing with the packets which are part of this protocol.
7653 See comment at top of file for details. */
7654
1927e618
PA
7655/* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7656 error to higher layers. Called when a serial error is detected.
7657 The exception message is STRING, followed by a colon and a blank,
d6cb50a2
JK
7658 the system error message for errno at function entry and final dot
7659 for output compatibility with throw_perror_with_name. */
1927e618
PA
7660
7661static void
7662unpush_and_perror (const char *string)
7663{
d6cb50a2 7664 int saved_errno = errno;
1927e618
PA
7665
7666 remote_unpush_target ();
d6cb50a2
JK
7667 throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7668 safe_strerror (saved_errno));
1927e618
PA
7669}
7670
0876f84a 7671/* Read a single character from the remote end. */
c906108c
SS
7672
7673static int
fba45db2 7674readchar (int timeout)
c906108c
SS
7675{
7676 int ch;
5d93a237 7677 struct remote_state *rs = get_remote_state ();
c906108c 7678
5d93a237 7679 ch = serial_readchar (rs->remote_desc, timeout);
c906108c 7680
2acceee2 7681 if (ch >= 0)
0876f84a 7682 return ch;
2acceee2
JM
7683
7684 switch ((enum serial_rc) ch)
c906108c
SS
7685 {
7686 case SERIAL_EOF:
78a095c3 7687 remote_unpush_target ();
598d3636 7688 throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
2acceee2 7689 /* no return */
c906108c 7690 case SERIAL_ERROR:
1927e618
PA
7691 unpush_and_perror (_("Remote communication error. "
7692 "Target disconnected."));
2acceee2 7693 /* no return */
c906108c 7694 case SERIAL_TIMEOUT:
2acceee2 7695 break;
c906108c 7696 }
2acceee2 7697 return ch;
c906108c
SS
7698}
7699
c33e31fd
PA
7700/* Wrapper for serial_write that closes the target and throws if
7701 writing fails. */
7702
7703static void
7704remote_serial_write (const char *str, int len)
7705{
5d93a237
TT
7706 struct remote_state *rs = get_remote_state ();
7707
7708 if (serial_write (rs->remote_desc, str, len))
c33e31fd 7709 {
1927e618
PA
7710 unpush_and_perror (_("Remote communication error. "
7711 "Target disconnected."));
c33e31fd
PA
7712 }
7713}
7714
6d820c5c
DJ
7715/* Send the command in *BUF to the remote machine, and read the reply
7716 into *BUF. Report an error if we get an error reply. Resize
7717 *BUF using xrealloc if necessary to hold the result, and update
7718 *SIZEOF_BUF. */
c906108c
SS
7719
7720static void
6d820c5c
DJ
7721remote_send (char **buf,
7722 long *sizeof_buf)
c906108c 7723{
6d820c5c 7724 putpkt (*buf);
c2d11a7d 7725 getpkt (buf, sizeof_buf, 0);
c906108c 7726
6d820c5c
DJ
7727 if ((*buf)[0] == 'E')
7728 error (_("Remote failure reply: %s"), *buf);
c906108c
SS
7729}
7730
6e5abd65
PA
7731/* Return a pointer to an xmalloc'ed string representing an escaped
7732 version of BUF, of len N. E.g. \n is converted to \\n, \t to \\t,
7733 etc. The caller is responsible for releasing the returned
7734 memory. */
7735
7736static char *
7737escape_buffer (const char *buf, int n)
7738{
7739 struct cleanup *old_chain;
7740 struct ui_file *stb;
7741 char *str;
6e5abd65
PA
7742
7743 stb = mem_fileopen ();
7744 old_chain = make_cleanup_ui_file_delete (stb);
7745
6ef284bd 7746 fputstrn_unfiltered (buf, n, '\\', stb);
759ef836 7747 str = ui_file_xstrdup (stb, NULL);
6e5abd65
PA
7748 do_cleanups (old_chain);
7749 return str;
7750}
7751
c906108c
SS
7752/* Display a null-terminated packet on stdout, for debugging, using C
7753 string notation. */
7754
7755static void
baa336ce 7756print_packet (const char *buf)
c906108c
SS
7757{
7758 puts_filtered ("\"");
43e526b9 7759 fputstr_filtered (buf, '"', gdb_stdout);
c906108c
SS
7760 puts_filtered ("\"");
7761}
7762
7763int
baa336ce 7764putpkt (const char *buf)
c906108c
SS
7765{
7766 return putpkt_binary (buf, strlen (buf));
7767}
7768
7769/* Send a packet to the remote machine, with error checking. The data
23860348 7770 of the packet is in BUF. The string in BUF can be at most
ea9c271d 7771 get_remote_packet_size () - 5 to account for the $, # and checksum,
23860348
MS
7772 and for a possible /0 if we are debugging (remote_debug) and want
7773 to print the sent packet as a string. */
c906108c
SS
7774
7775static int
baa336ce 7776putpkt_binary (const char *buf, int cnt)
c906108c 7777{
2d717e4f 7778 struct remote_state *rs = get_remote_state ();
c906108c
SS
7779 int i;
7780 unsigned char csum = 0;
a5c0808e
PA
7781 char *buf2 = xmalloc (cnt + 6);
7782 struct cleanup *old_chain = make_cleanup (xfree, buf2);
085dd6e6 7783
c906108c
SS
7784 int ch;
7785 int tcount = 0;
7786 char *p;
dd61ec5c 7787 char *message;
c906108c 7788
e24a49d8
PA
7789 /* Catch cases like trying to read memory or listing threads while
7790 we're waiting for a stop reply. The remote server wouldn't be
7791 ready to handle this request, so we'd hang and timeout. We don't
7792 have to worry about this in synchronous mode, because in that
7793 case it's not possible to issue a command while the target is
74531fed
PA
7794 running. This is not a problem in non-stop mode, because in that
7795 case, the stub is always ready to process serial input. */
d9d41e78 7796 if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
9597b22a
DE
7797 {
7798 error (_("Cannot execute this command while the target is running.\n"
7799 "Use the \"interrupt\" command to stop the target\n"
7800 "and then try again."));
7801 }
e24a49d8 7802
2d717e4f
DJ
7803 /* We're sending out a new packet. Make sure we don't look at a
7804 stale cached response. */
7805 rs->cached_wait_status = 0;
7806
c906108c
SS
7807 /* Copy the packet into buffer BUF2, encapsulating it
7808 and giving it a checksum. */
7809
c906108c
SS
7810 p = buf2;
7811 *p++ = '$';
7812
7813 for (i = 0; i < cnt; i++)
7814 {
7815 csum += buf[i];
7816 *p++ = buf[i];
7817 }
7818 *p++ = '#';
7819 *p++ = tohex ((csum >> 4) & 0xf);
7820 *p++ = tohex (csum & 0xf);
7821
7822 /* Send it over and over until we get a positive ack. */
7823
7824 while (1)
7825 {
7826 int started_error_output = 0;
7827
7828 if (remote_debug)
7829 {
6e5abd65
PA
7830 struct cleanup *old_chain;
7831 char *str;
7832
c906108c 7833 *p = '\0';
6e5abd65
PA
7834 str = escape_buffer (buf2, p - buf2);
7835 old_chain = make_cleanup (xfree, str);
7836 fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
0f71a2f6 7837 gdb_flush (gdb_stdlog);
6e5abd65 7838 do_cleanups (old_chain);
c906108c 7839 }
c33e31fd 7840 remote_serial_write (buf2, p - buf2);
c906108c 7841
a6f3e723
SL
7842 /* If this is a no acks version of the remote protocol, send the
7843 packet and move on. */
7844 if (rs->noack_mode)
7845 break;
7846
74531fed
PA
7847 /* Read until either a timeout occurs (-2) or '+' is read.
7848 Handle any notification that arrives in the mean time. */
c906108c
SS
7849 while (1)
7850 {
7851 ch = readchar (remote_timeout);
7852
c5aa993b 7853 if (remote_debug)
c906108c
SS
7854 {
7855 switch (ch)
7856 {
7857 case '+':
1216fa2c 7858 case '-':
c906108c
SS
7859 case SERIAL_TIMEOUT:
7860 case '$':
74531fed 7861 case '%':
c906108c
SS
7862 if (started_error_output)
7863 {
7864 putchar_unfiltered ('\n');
7865 started_error_output = 0;
7866 }
7867 }
7868 }
7869
7870 switch (ch)
7871 {
7872 case '+':
7873 if (remote_debug)
0f71a2f6 7874 fprintf_unfiltered (gdb_stdlog, "Ack\n");
a5c0808e 7875 do_cleanups (old_chain);
c906108c 7876 return 1;
1216fa2c
AC
7877 case '-':
7878 if (remote_debug)
7879 fprintf_unfiltered (gdb_stdlog, "Nak\n");
a17d146e 7880 /* FALLTHROUGH */
c906108c 7881 case SERIAL_TIMEOUT:
c5aa993b 7882 tcount++;
c906108c 7883 if (tcount > 3)
a5c0808e
PA
7884 {
7885 do_cleanups (old_chain);
7886 return 0;
7887 }
23860348 7888 break; /* Retransmit buffer. */
c906108c
SS
7889 case '$':
7890 {
40e3f985 7891 if (remote_debug)
2bc416ba 7892 fprintf_unfiltered (gdb_stdlog,
23860348 7893 "Packet instead of Ack, ignoring it\n");
d6f7abdf
AC
7894 /* It's probably an old response sent because an ACK
7895 was lost. Gobble up the packet and ack it so it
7896 doesn't get retransmitted when we resend this
7897 packet. */
6d820c5c 7898 skip_frame ();
c33e31fd 7899 remote_serial_write ("+", 1);
23860348 7900 continue; /* Now, go look for +. */
c906108c 7901 }
74531fed
PA
7902
7903 case '%':
7904 {
7905 int val;
7906
7907 /* If we got a notification, handle it, and go back to looking
7908 for an ack. */
7909 /* We've found the start of a notification. Now
7910 collect the data. */
7911 val = read_frame (&rs->buf, &rs->buf_size);
7912 if (val >= 0)
7913 {
7914 if (remote_debug)
7915 {
6e5abd65
PA
7916 struct cleanup *old_chain;
7917 char *str;
7918
7919 str = escape_buffer (rs->buf, val);
7920 old_chain = make_cleanup (xfree, str);
7921 fprintf_unfiltered (gdb_stdlog,
7922 " Notification received: %s\n",
7923 str);
7924 do_cleanups (old_chain);
74531fed 7925 }
5965e028 7926 handle_notification (rs->notif_state, rs->buf);
74531fed
PA
7927 /* We're in sync now, rewait for the ack. */
7928 tcount = 0;
7929 }
7930 else
7931 {
7932 if (remote_debug)
7933 {
7934 if (!started_error_output)
7935 {
7936 started_error_output = 1;
7937 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7938 }
7939 fputc_unfiltered (ch & 0177, gdb_stdlog);
7940 fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7941 }
7942 }
7943 continue;
7944 }
7945 /* fall-through */
c906108c
SS
7946 default:
7947 if (remote_debug)
7948 {
7949 if (!started_error_output)
7950 {
7951 started_error_output = 1;
0f71a2f6 7952 fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
c906108c 7953 }
0f71a2f6 7954 fputc_unfiltered (ch & 0177, gdb_stdlog);
c906108c
SS
7955 }
7956 continue;
7957 }
23860348 7958 break; /* Here to retransmit. */
c906108c
SS
7959 }
7960
7961#if 0
7962 /* This is wrong. If doing a long backtrace, the user should be
c5aa993b
JM
7963 able to get out next time we call QUIT, without anything as
7964 violent as interrupt_query. If we want to provide a way out of
7965 here without getting to the next QUIT, it should be based on
7966 hitting ^C twice as in remote_wait. */
c906108c
SS
7967 if (quit_flag)
7968 {
7969 quit_flag = 0;
7970 interrupt_query ();
7971 }
7972#endif
7973 }
a5c0808e
PA
7974
7975 do_cleanups (old_chain);
a6f3e723 7976 return 0;
c906108c
SS
7977}
7978
6d820c5c
DJ
7979/* Come here after finding the start of a frame when we expected an
7980 ack. Do our best to discard the rest of this packet. */
7981
7982static void
7983skip_frame (void)
7984{
7985 int c;
7986
7987 while (1)
7988 {
7989 c = readchar (remote_timeout);
7990 switch (c)
7991 {
7992 case SERIAL_TIMEOUT:
7993 /* Nothing we can do. */
7994 return;
7995 case '#':
7996 /* Discard the two bytes of checksum and stop. */
7997 c = readchar (remote_timeout);
7998 if (c >= 0)
7999 c = readchar (remote_timeout);
8000
8001 return;
8002 case '*': /* Run length encoding. */
8003 /* Discard the repeat count. */
8004 c = readchar (remote_timeout);
8005 if (c < 0)
8006 return;
8007 break;
8008 default:
8009 /* A regular character. */
8010 break;
8011 }
8012 }
8013}
8014
c906108c 8015/* Come here after finding the start of the frame. Collect the rest
6d820c5c
DJ
8016 into *BUF, verifying the checksum, length, and handling run-length
8017 compression. NUL terminate the buffer. If there is not enough room,
8018 expand *BUF using xrealloc.
c906108c 8019
c2d11a7d
JM
8020 Returns -1 on error, number of characters in buffer (ignoring the
8021 trailing NULL) on success. (could be extended to return one of the
23860348 8022 SERIAL status indications). */
c2d11a7d
JM
8023
8024static long
6d820c5c
DJ
8025read_frame (char **buf_p,
8026 long *sizeof_buf)
c906108c
SS
8027{
8028 unsigned char csum;
c2d11a7d 8029 long bc;
c906108c 8030 int c;
6d820c5c 8031 char *buf = *buf_p;
a6f3e723 8032 struct remote_state *rs = get_remote_state ();
c906108c
SS
8033
8034 csum = 0;
c2d11a7d 8035 bc = 0;
c906108c
SS
8036
8037 while (1)
8038 {
8039 c = readchar (remote_timeout);
c906108c
SS
8040 switch (c)
8041 {
8042 case SERIAL_TIMEOUT:
8043 if (remote_debug)
0f71a2f6 8044 fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
c2d11a7d 8045 return -1;
c906108c
SS
8046 case '$':
8047 if (remote_debug)
0f71a2f6
JM
8048 fputs_filtered ("Saw new packet start in middle of old one\n",
8049 gdb_stdlog);
23860348 8050 return -1; /* Start a new packet, count retries. */
c906108c
SS
8051 case '#':
8052 {
8053 unsigned char pktcsum;
e1b09194
AC
8054 int check_0 = 0;
8055 int check_1 = 0;
c906108c 8056
c2d11a7d 8057 buf[bc] = '\0';
c906108c 8058
e1b09194
AC
8059 check_0 = readchar (remote_timeout);
8060 if (check_0 >= 0)
8061 check_1 = readchar (remote_timeout);
802188a7 8062
e1b09194
AC
8063 if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8064 {
8065 if (remote_debug)
2bc416ba 8066 fputs_filtered ("Timeout in checksum, retrying\n",
23860348 8067 gdb_stdlog);
e1b09194
AC
8068 return -1;
8069 }
8070 else if (check_0 < 0 || check_1 < 0)
40e3f985
FN
8071 {
8072 if (remote_debug)
2bc416ba 8073 fputs_filtered ("Communication error in checksum\n",
23860348 8074 gdb_stdlog);
40e3f985
FN
8075 return -1;
8076 }
c906108c 8077
a6f3e723
SL
8078 /* Don't recompute the checksum; with no ack packets we
8079 don't have any way to indicate a packet retransmission
8080 is necessary. */
8081 if (rs->noack_mode)
8082 return bc;
8083
e1b09194 8084 pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
c906108c 8085 if (csum == pktcsum)
c2d11a7d 8086 return bc;
c906108c 8087
c5aa993b 8088 if (remote_debug)
c906108c 8089 {
6e5abd65
PA
8090 struct cleanup *old_chain;
8091 char *str;
8092
8093 str = escape_buffer (buf, bc);
8094 old_chain = make_cleanup (xfree, str);
8095 fprintf_unfiltered (gdb_stdlog,
3e43a32a
MS
8096 "Bad checksum, sentsum=0x%x, "
8097 "csum=0x%x, buf=%s\n",
6e5abd65
PA
8098 pktcsum, csum, str);
8099 do_cleanups (old_chain);
c906108c 8100 }
c2d11a7d 8101 /* Number of characters in buffer ignoring trailing
23860348 8102 NULL. */
c2d11a7d 8103 return -1;
c906108c 8104 }
23860348 8105 case '*': /* Run length encoding. */
c2c6d25f
JM
8106 {
8107 int repeat;
c906108c 8108
a744cf53 8109 csum += c;
b4501125
AC
8110 c = readchar (remote_timeout);
8111 csum += c;
23860348 8112 repeat = c - ' ' + 3; /* Compute repeat count. */
c906108c 8113
23860348 8114 /* The character before ``*'' is repeated. */
c2d11a7d 8115
6d820c5c 8116 if (repeat > 0 && repeat <= 255 && bc > 0)
c2c6d25f 8117 {
6d820c5c
DJ
8118 if (bc + repeat - 1 >= *sizeof_buf - 1)
8119 {
8120 /* Make some more room in the buffer. */
8121 *sizeof_buf += repeat;
8122 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8123 buf = *buf_p;
8124 }
8125
c2d11a7d
JM
8126 memset (&buf[bc], buf[bc - 1], repeat);
8127 bc += repeat;
c2c6d25f
JM
8128 continue;
8129 }
8130
c2d11a7d 8131 buf[bc] = '\0';
6d820c5c 8132 printf_filtered (_("Invalid run length encoding: %s\n"), buf);
c2d11a7d 8133 return -1;
c2c6d25f 8134 }
c906108c 8135 default:
6d820c5c 8136 if (bc >= *sizeof_buf - 1)
c906108c 8137 {
6d820c5c
DJ
8138 /* Make some more room in the buffer. */
8139 *sizeof_buf *= 2;
8140 *buf_p = xrealloc (*buf_p, *sizeof_buf);
8141 buf = *buf_p;
c906108c
SS
8142 }
8143
6d820c5c
DJ
8144 buf[bc++] = c;
8145 csum += c;
8146 continue;
c906108c
SS
8147 }
8148 }
8149}
8150
8151/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8152 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8153 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8154 rather than timing out; this is used (in synchronous mode) to wait
8155 for a target that is is executing user code to stop. */
d9fcf2fb
JM
8156/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
8157 don't have to change all the calls to getpkt to deal with the
8158 return value, because at the moment I don't know what the right
23860348 8159 thing to do it for those. */
c906108c 8160void
6d820c5c
DJ
8161getpkt (char **buf,
8162 long *sizeof_buf,
c2d11a7d 8163 int forever)
d9fcf2fb
JM
8164{
8165 int timed_out;
8166
8167 timed_out = getpkt_sane (buf, sizeof_buf, forever);
8168}
8169
8170
8171/* Read a packet from the remote machine, with error checking, and
6d820c5c
DJ
8172 store it in *BUF. Resize *BUF using xrealloc if necessary to hold
8173 the result, and update *SIZEOF_BUF. If FOREVER, wait forever
8174 rather than timing out; this is used (in synchronous mode) to wait
8175 for a target that is is executing user code to stop. If FOREVER ==
8176 0, this function is allowed to time out gracefully and return an
74531fed
PA
8177 indication of this to the caller. Otherwise return the number of
8178 bytes read. If EXPECTING_NOTIF, consider receiving a notification
fee9eda9
YQ
8179 enough reason to return to the caller. *IS_NOTIF is an output
8180 boolean that indicates whether *BUF holds a notification or not
8181 (a regular packet). */
74531fed 8182
3172dc30 8183static int
74531fed 8184getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
fee9eda9 8185 int expecting_notif, int *is_notif)
c906108c 8186{
2d717e4f 8187 struct remote_state *rs = get_remote_state ();
c906108c
SS
8188 int c;
8189 int tries;
8190 int timeout;
df4b58fe 8191 int val = -1;
c906108c 8192
2d717e4f
DJ
8193 /* We're reading a new response. Make sure we don't look at a
8194 previously cached response. */
8195 rs->cached_wait_status = 0;
8196
6d820c5c 8197 strcpy (*buf, "timeout");
c906108c
SS
8198
8199 if (forever)
74531fed
PA
8200 timeout = watchdog > 0 ? watchdog : -1;
8201 else if (expecting_notif)
8202 timeout = 0; /* There should already be a char in the buffer. If
8203 not, bail out. */
c906108c
SS
8204 else
8205 timeout = remote_timeout;
8206
8207#define MAX_TRIES 3
8208
74531fed
PA
8209 /* Process any number of notifications, and then return when
8210 we get a packet. */
8211 for (;;)
c906108c 8212 {
d9c43928 8213 /* If we get a timeout or bad checksum, retry up to MAX_TRIES
74531fed
PA
8214 times. */
8215 for (tries = 1; tries <= MAX_TRIES; tries++)
c906108c 8216 {
74531fed
PA
8217 /* This can loop forever if the remote side sends us
8218 characters continuously, but if it pauses, we'll get
8219 SERIAL_TIMEOUT from readchar because of timeout. Then
8220 we'll count that as a retry.
8221
8222 Note that even when forever is set, we will only wait
8223 forever prior to the start of a packet. After that, we
8224 expect characters to arrive at a brisk pace. They should
8225 show up within remote_timeout intervals. */
8226 do
8227 c = readchar (timeout);
8228 while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
c906108c
SS
8229
8230 if (c == SERIAL_TIMEOUT)
8231 {
74531fed
PA
8232 if (expecting_notif)
8233 return -1; /* Don't complain, it's normal to not get
8234 anything in this case. */
8235
23860348 8236 if (forever) /* Watchdog went off? Kill the target. */
c906108c 8237 {
2acceee2 8238 QUIT;
78a095c3 8239 remote_unpush_target ();
598d3636
JK
8240 throw_error (TARGET_CLOSE_ERROR,
8241 _("Watchdog timeout has expired. "
8242 "Target detached."));
c906108c 8243 }
c906108c 8244 if (remote_debug)
0f71a2f6 8245 fputs_filtered ("Timed out.\n", gdb_stdlog);
c906108c 8246 }
74531fed
PA
8247 else
8248 {
8249 /* We've found the start of a packet or notification.
8250 Now collect the data. */
8251 val = read_frame (buf, sizeof_buf);
8252 if (val >= 0)
8253 break;
8254 }
8255
c33e31fd 8256 remote_serial_write ("-", 1);
c906108c 8257 }
c906108c 8258
74531fed
PA
8259 if (tries > MAX_TRIES)
8260 {
8261 /* We have tried hard enough, and just can't receive the
8262 packet/notification. Give up. */
8263 printf_unfiltered (_("Ignoring packet error, continuing...\n"));
c906108c 8264
74531fed
PA
8265 /* Skip the ack char if we're in no-ack mode. */
8266 if (!rs->noack_mode)
c33e31fd 8267 remote_serial_write ("+", 1);
74531fed
PA
8268 return -1;
8269 }
c906108c 8270
74531fed
PA
8271 /* If we got an ordinary packet, return that to our caller. */
8272 if (c == '$')
c906108c
SS
8273 {
8274 if (remote_debug)
43e526b9 8275 {
6e5abd65
PA
8276 struct cleanup *old_chain;
8277 char *str;
8278
8279 str = escape_buffer (*buf, val);
8280 old_chain = make_cleanup (xfree, str);
8281 fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8282 do_cleanups (old_chain);
43e526b9 8283 }
a6f3e723
SL
8284
8285 /* Skip the ack char if we're in no-ack mode. */
8286 if (!rs->noack_mode)
c33e31fd 8287 remote_serial_write ("+", 1);
fee9eda9
YQ
8288 if (is_notif != NULL)
8289 *is_notif = 0;
0876f84a 8290 return val;
c906108c
SS
8291 }
8292
74531fed
PA
8293 /* If we got a notification, handle it, and go back to looking
8294 for a packet. */
8295 else
8296 {
8297 gdb_assert (c == '%');
8298
8299 if (remote_debug)
8300 {
6e5abd65
PA
8301 struct cleanup *old_chain;
8302 char *str;
8303
8304 str = escape_buffer (*buf, val);
8305 old_chain = make_cleanup (xfree, str);
8306 fprintf_unfiltered (gdb_stdlog,
8307 " Notification received: %s\n",
8308 str);
8309 do_cleanups (old_chain);
74531fed 8310 }
fee9eda9
YQ
8311 if (is_notif != NULL)
8312 *is_notif = 1;
c906108c 8313
5965e028 8314 handle_notification (rs->notif_state, *buf);
c906108c 8315
74531fed 8316 /* Notifications require no acknowledgement. */
a6f3e723 8317
74531fed 8318 if (expecting_notif)
fee9eda9 8319 return val;
74531fed
PA
8320 }
8321 }
8322}
8323
8324static int
8325getpkt_sane (char **buf, long *sizeof_buf, int forever)
8326{
fee9eda9 8327 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
74531fed
PA
8328}
8329
8330static int
fee9eda9
YQ
8331getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8332 int *is_notif)
74531fed 8333{
fee9eda9
YQ
8334 return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8335 is_notif);
c906108c 8336}
74531fed 8337
cbb8991c
DB
8338/* Check whether EVENT is a fork event for the process specified
8339 by the pid passed in DATA, and if it is, kill the fork child. */
8340
8341static int
8342kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8343 QUEUE_ITER (stop_reply_p) *iter,
8344 stop_reply_p event,
8345 void *data)
8346{
8347 struct queue_iter_param *param = data;
8348 int parent_pid = *(int *) param->input;
8349
8350 if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8351 {
8352 struct remote_state *rs = get_remote_state ();
8353 int child_pid = ptid_get_pid (event->ws.value.related_pid);
8354 int res;
8355
8356 res = remote_vkill (child_pid, rs);
8357 if (res != 0)
8358 error (_("Can't kill fork child process %d"), child_pid);
8359 }
8360
8361 return 1;
8362}
8363
8364/* Kill any new fork children of process PID that haven't been
8365 processed by follow_fork. */
8366
8367static void
8368kill_new_fork_children (int pid, struct remote_state *rs)
8369{
8370 struct thread_info *thread;
8371 struct notif_client *notif = &notif_client_stop;
8372 struct queue_iter_param param;
8373
8374 /* Kill the fork child threads of any threads in process PID
8375 that are stopped at a fork event. */
8376 ALL_NON_EXITED_THREADS (thread)
8377 {
8378 struct target_waitstatus *ws = &thread->pending_follow;
8379
8380 if (is_pending_fork_parent (ws, pid, thread->ptid))
8381 {
8382 struct remote_state *rs = get_remote_state ();
8383 int child_pid = ptid_get_pid (ws->value.related_pid);
8384 int res;
8385
8386 res = remote_vkill (child_pid, rs);
8387 if (res != 0)
8388 error (_("Can't kill fork child process %d"), child_pid);
8389 }
8390 }
8391
8392 /* Check for any pending fork events (not reported or processed yet)
8393 in process PID and kill those fork child threads as well. */
8394 remote_notif_get_pending_events (notif);
8395 param.input = &pid;
8396 param.output = NULL;
8397 QUEUE_iterate (stop_reply_p, stop_reply_queue,
8398 kill_child_of_pending_fork, &param);
8399}
8400
c906108c
SS
8401\f
8402static void
7d85a9c0 8403remote_kill (struct target_ops *ops)
43ff13b4 8404{
0fdf84ca
PA
8405
8406 /* Catch errors so the user can quit from gdb even when we
23860348 8407 aren't on speaking terms with the remote system. */
492d29ea 8408 TRY
0fdf84ca
PA
8409 {
8410 putpkt ("k");
8411 }
492d29ea 8412 CATCH (ex, RETURN_MASK_ERROR)
0fdf84ca
PA
8413 {
8414 if (ex.error == TARGET_CLOSE_ERROR)
8415 {
8416 /* If we got an (EOF) error that caused the target
8417 to go away, then we're done, that's what we wanted.
8418 "k" is susceptible to cause a premature EOF, given
8419 that the remote server isn't actually required to
8420 reply to "k", and it can happen that it doesn't
8421 even get to reply ACK to the "k". */
8422 return;
8423 }
8424
8425 /* Otherwise, something went wrong. We didn't actually kill
8426 the target. Just propagate the exception, and let the
8427 user or higher layers decide what to do. */
8428 throw_exception (ex);
8429 }
492d29ea 8430 END_CATCH
43ff13b4 8431
0fdf84ca
PA
8432 /* We've killed the remote end, we get to mourn it. Since this is
8433 target remote, single-process, mourning the inferior also
8434 unpushes remote_ops. */
43ff13b4
JM
8435 target_mourn_inferior ();
8436}
8437
82f73884
PA
8438static int
8439remote_vkill (int pid, struct remote_state *rs)
8440{
4082afcc 8441 if (packet_support (PACKET_vKill) == PACKET_DISABLE)
82f73884
PA
8442 return -1;
8443
8444 /* Tell the remote target to detach. */
bba74b36 8445 xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
82f73884
PA
8446 putpkt (rs->buf);
8447 getpkt (&rs->buf, &rs->buf_size, 0);
8448
4082afcc
PA
8449 switch (packet_ok (rs->buf,
8450 &remote_protocol_packets[PACKET_vKill]))
8451 {
8452 case PACKET_OK:
8453 return 0;
8454 case PACKET_ERROR:
8455 return 1;
8456 case PACKET_UNKNOWN:
8457 return -1;
8458 default:
8459 internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8460 }
82f73884
PA
8461}
8462
8463static void
7d85a9c0 8464extended_remote_kill (struct target_ops *ops)
82f73884
PA
8465{
8466 int res;
8467 int pid = ptid_get_pid (inferior_ptid);
8468 struct remote_state *rs = get_remote_state ();
8469
cbb8991c
DB
8470 /* If we're stopped while forking and we haven't followed yet, kill the
8471 child task. We need to do this before killing the parent task
8472 because if this is a vfork then the parent will be sleeping. */
8473 kill_new_fork_children (pid, rs);
8474
82f73884 8475 res = remote_vkill (pid, rs);
901f9912 8476 if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
82f73884
PA
8477 {
8478 /* Don't try 'k' on a multi-process aware stub -- it has no way
8479 to specify the pid. */
8480
8481 putpkt ("k");
8482#if 0
8483 getpkt (&rs->buf, &rs->buf_size, 0);
8484 if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8485 res = 1;
8486#else
8487 /* Don't wait for it to die. I'm not really sure it matters whether
8488 we do or not. For the existing stubs, kill is a noop. */
8489 res = 0;
8490#endif
8491 }
8492
8493 if (res != 0)
8494 error (_("Can't kill process"));
8495
82f73884
PA
8496 target_mourn_inferior ();
8497}
8498
c906108c 8499static void
20f796c9 8500remote_mourn (struct target_ops *target)
c906108c
SS
8501{
8502 unpush_target (target);
ce5ce7ed 8503
8a2492ee
PA
8504 /* remote_close takes care of doing most of the clean up. */
8505 generic_mourn_inferior ();
c906108c
SS
8506}
8507
2d717e4f 8508static void
20f796c9 8509extended_remote_mourn (struct target_ops *target)
2d717e4f
DJ
8510{
8511 struct remote_state *rs = get_remote_state ();
c906108c 8512
e24a49d8
PA
8513 /* In case we got here due to an error, but we're going to stay
8514 connected. */
8515 rs->waiting_for_stop_reply = 0;
8516
dc1981d7
PA
8517 /* If the current general thread belonged to the process we just
8518 detached from or has exited, the remote side current general
8519 thread becomes undefined. Considering a case like this:
8520
8521 - We just got here due to a detach.
8522 - The process that we're detaching from happens to immediately
8523 report a global breakpoint being hit in non-stop mode, in the
8524 same thread we had selected before.
8525 - GDB attaches to this process again.
8526 - This event happens to be the next event we handle.
8527
8528 GDB would consider that the current general thread didn't need to
8529 be set on the stub side (with Hg), since for all it knew,
8530 GENERAL_THREAD hadn't changed.
8531
8532 Notice that although in all-stop mode, the remote server always
8533 sets the current thread to the thread reporting the stop event,
8534 that doesn't happen in non-stop mode; in non-stop, the stub *must
8535 not* change the current thread when reporting a breakpoint hit,
8536 due to the decoupling of event reporting and event handling.
8537
8538 To keep things simple, we always invalidate our notion of the
8539 current thread. */
47f8a51d 8540 record_currthread (rs, minus_one_ptid);
dc1981d7 8541
2d717e4f
DJ
8542 /* Unlike "target remote", we do not want to unpush the target; then
8543 the next time the user says "run", we won't be connected. */
8544
48aa3c27
PA
8545 /* Call common code to mark the inferior as not running. */
8546 generic_mourn_inferior ();
8547
d729566a 8548 if (!have_inferiors ())
2d717e4f 8549 {
82f73884
PA
8550 if (!remote_multi_process_p (rs))
8551 {
8552 /* Check whether the target is running now - some remote stubs
8553 automatically restart after kill. */
8554 putpkt ("?");
8555 getpkt (&rs->buf, &rs->buf_size, 0);
8556
8557 if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8558 {
3e43a32a
MS
8559 /* Assume that the target has been restarted. Set
8560 inferior_ptid so that bits of core GDB realizes
8561 there's something here, e.g., so that the user can
8562 say "kill" again. */
82f73884
PA
8563 inferior_ptid = magic_null_ptid;
8564 }
82f73884 8565 }
2d717e4f
DJ
8566 }
8567}
c906108c 8568
03583c20 8569static int
2bfc0540 8570extended_remote_supports_disable_randomization (struct target_ops *self)
03583c20 8571{
4082afcc 8572 return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
03583c20
UW
8573}
8574
8575static void
8576extended_remote_disable_randomization (int val)
8577{
8578 struct remote_state *rs = get_remote_state ();
8579 char *reply;
8580
bba74b36
YQ
8581 xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8582 val);
03583c20
UW
8583 putpkt (rs->buf);
8584 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8585 if (*reply == '\0')
8586 error (_("Target does not support QDisableRandomization."));
8587 if (strcmp (reply, "OK") != 0)
8588 error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8589}
8590
2d717e4f
DJ
8591static int
8592extended_remote_run (char *args)
8593{
8594 struct remote_state *rs = get_remote_state ();
2d717e4f 8595 int len;
c906108c 8596
2d717e4f
DJ
8597 /* If the user has disabled vRun support, or we have detected that
8598 support is not available, do not try it. */
4082afcc 8599 if (packet_support (PACKET_vRun) == PACKET_DISABLE)
2d717e4f 8600 return -1;
424163ea 8601
2d717e4f
DJ
8602 strcpy (rs->buf, "vRun;");
8603 len = strlen (rs->buf);
c906108c 8604
2d717e4f
DJ
8605 if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8606 error (_("Remote file name too long for run packet"));
9f1b45b0
TT
8607 len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8608 strlen (remote_exec_file));
2d717e4f 8609
d1a41061 8610 gdb_assert (args != NULL);
2d717e4f
DJ
8611 if (*args)
8612 {
8613 struct cleanup *back_to;
8614 int i;
8615 char **argv;
8616
d1a41061 8617 argv = gdb_buildargv (args);
6e366df1 8618 back_to = make_cleanup_freeargv (argv);
2d717e4f
DJ
8619 for (i = 0; argv[i] != NULL; i++)
8620 {
8621 if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8622 error (_("Argument list too long for run packet"));
8623 rs->buf[len++] = ';';
9f1b45b0
TT
8624 len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8625 strlen (argv[i]));
2d717e4f
DJ
8626 }
8627 do_cleanups (back_to);
8628 }
8629
8630 rs->buf[len++] = '\0';
8631
8632 putpkt (rs->buf);
8633 getpkt (&rs->buf, &rs->buf_size, 0);
8634
4082afcc 8635 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
2d717e4f 8636 {
4082afcc 8637 case PACKET_OK:
3405876a 8638 /* We have a wait response. All is well. */
2d717e4f 8639 return 0;
4082afcc
PA
8640 case PACKET_UNKNOWN:
8641 return -1;
8642 case PACKET_ERROR:
2d717e4f
DJ
8643 if (remote_exec_file[0] == '\0')
8644 error (_("Running the default executable on the remote target failed; "
8645 "try \"set remote exec-file\"?"));
8646 else
8647 error (_("Running \"%s\" on the remote target failed"),
8648 remote_exec_file);
4082afcc
PA
8649 default:
8650 gdb_assert_not_reached (_("bad switch"));
2d717e4f 8651 }
c906108c
SS
8652}
8653
2d717e4f
DJ
8654/* In the extended protocol we want to be able to do things like
8655 "run" and have them basically work as expected. So we need
8656 a special create_inferior function. We support changing the
8657 executable file and the command line arguments, but not the
8658 environment. */
8659
43ff13b4 8660static void
77a19445
TT
8661extended_remote_create_inferior (struct target_ops *ops,
8662 char *exec_file, char *args,
8663 char **env, int from_tty)
43ff13b4 8664{
3405876a
PA
8665 int run_worked;
8666 char *stop_reply;
8667 struct remote_state *rs = get_remote_state ();
8668
43ff13b4 8669 /* If running asynchronously, register the target file descriptor
23860348 8670 with the event loop. */
75c99385 8671 if (target_can_async_p ())
6a3753b3 8672 target_async (1);
43ff13b4 8673
03583c20 8674 /* Disable address space randomization if requested (and supported). */
2bfc0540 8675 if (extended_remote_supports_disable_randomization (ops))
03583c20
UW
8676 extended_remote_disable_randomization (disable_randomization);
8677
43ff13b4 8678 /* Now restart the remote server. */
3405876a
PA
8679 run_worked = extended_remote_run (args) != -1;
8680 if (!run_worked)
2d717e4f
DJ
8681 {
8682 /* vRun was not supported. Fail if we need it to do what the
8683 user requested. */
8684 if (remote_exec_file[0])
8685 error (_("Remote target does not support \"set remote exec-file\""));
8686 if (args[0])
8687 error (_("Remote target does not support \"set args\" or run <ARGS>"));
43ff13b4 8688
2d717e4f
DJ
8689 /* Fall back to "R". */
8690 extended_remote_restart ();
8691 }
424163ea 8692
6c95b8df
PA
8693 if (!have_inferiors ())
8694 {
8695 /* Clean up from the last time we ran, before we mark the target
8696 running again. This will mark breakpoints uninserted, and
8697 get_offsets may insert breakpoints. */
8698 init_thread_list ();
8699 init_wait_for_inferior ();
8700 }
45280a52 8701
3405876a
PA
8702 /* vRun's success return is a stop reply. */
8703 stop_reply = run_worked ? rs->buf : NULL;
8704 add_current_inferior_and_thread (stop_reply);
c0a2216e 8705
2d717e4f
DJ
8706 /* Get updated offsets, if the stub uses qOffsets. */
8707 get_offsets ();
2d717e4f 8708}
c906108c 8709\f
c5aa993b 8710
b775012e
LM
8711/* Given a location's target info BP_TGT and the packet buffer BUF, output
8712 the list of conditions (in agent expression bytecode format), if any, the
8713 target needs to evaluate. The output is placed into the packet buffer
bba74b36 8714 started from BUF and ended at BUF_END. */
b775012e
LM
8715
8716static int
8717remote_add_target_side_condition (struct gdbarch *gdbarch,
bba74b36
YQ
8718 struct bp_target_info *bp_tgt, char *buf,
8719 char *buf_end)
b775012e
LM
8720{
8721 struct agent_expr *aexpr = NULL;
8722 int i, ix;
8723 char *pkt;
8724 char *buf_start = buf;
8725
8726 if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8727 return 0;
8728
8729 buf += strlen (buf);
bba74b36 8730 xsnprintf (buf, buf_end - buf, "%s", ";");
b775012e
LM
8731 buf++;
8732
8733 /* Send conditions to the target and free the vector. */
8734 for (ix = 0;
8735 VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8736 ix++)
8737 {
bba74b36 8738 xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
b775012e
LM
8739 buf += strlen (buf);
8740 for (i = 0; i < aexpr->len; ++i)
8741 buf = pack_hex_byte (buf, aexpr->buf[i]);
8742 *buf = '\0';
8743 }
b775012e
LM
8744 return 0;
8745}
8746
d3ce09f5
SS
8747static void
8748remote_add_target_side_commands (struct gdbarch *gdbarch,
8749 struct bp_target_info *bp_tgt, char *buf)
8750{
8751 struct agent_expr *aexpr = NULL;
8752 int i, ix;
8753
8754 if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8755 return;
8756
8757 buf += strlen (buf);
8758
8759 sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8760 buf += strlen (buf);
8761
8762 /* Concatenate all the agent expressions that are commands into the
8763 cmds parameter. */
8764 for (ix = 0;
8765 VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8766 ix++)
8767 {
8768 sprintf (buf, "X%x,", aexpr->len);
8769 buf += strlen (buf);
8770 for (i = 0; i < aexpr->len; ++i)
8771 buf = pack_hex_byte (buf, aexpr->buf[i]);
8772 *buf = '\0';
8773 }
d3ce09f5
SS
8774}
8775
8181d85f
DJ
8776/* Insert a breakpoint. On targets that have software breakpoint
8777 support, we ask the remote target to do the work; on targets
8778 which don't, we insert a traditional memory breakpoint. */
c906108c
SS
8779
8780static int
3db08215
MM
8781remote_insert_breakpoint (struct target_ops *ops,
8782 struct gdbarch *gdbarch,
a6d9a66e 8783 struct bp_target_info *bp_tgt)
c906108c 8784{
d471ea57
AC
8785 /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8786 If it succeeds, then set the support to PACKET_ENABLE. If it
8787 fails, and the user has explicitly requested the Z support then
23860348 8788 report an error, otherwise, mark it disabled and go on. */
802188a7 8789
4082afcc 8790 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8791 {
0d5ed153 8792 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 8793 struct remote_state *rs;
bba74b36 8794 char *p, *endbuf;
7c0f6dcc 8795 int bpsize;
b775012e 8796 struct condition_list *cond = NULL;
4fff2411 8797
28439a30
PA
8798 /* Make sure the remote is pointing at the right process, if
8799 necessary. */
8800 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8801 set_general_process ();
8802
a1dcb23a 8803 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
4fff2411
JZ
8804
8805 rs = get_remote_state ();
8806 p = rs->buf;
bba74b36 8807 endbuf = rs->buf + get_remote_packet_size ();
802188a7 8808
96baa820
JM
8809 *(p++) = 'Z';
8810 *(p++) = '0';
8811 *(p++) = ',';
7c0f6dcc 8812 addr = (ULONGEST) remote_address_masked (addr);
8181d85f 8813 p += hexnumstr (p, addr);
bba74b36 8814 xsnprintf (p, endbuf - p, ",%d", bpsize);
802188a7 8815
efcc2da7 8816 if (remote_supports_cond_breakpoints (ops))
bba74b36 8817 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 8818
78eff0ec 8819 if (remote_can_run_breakpoint_commands (ops))
d3ce09f5
SS
8820 remote_add_target_side_commands (gdbarch, bp_tgt, p);
8821
6d820c5c
DJ
8822 putpkt (rs->buf);
8823 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8824
6d820c5c 8825 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
96baa820 8826 {
d471ea57
AC
8827 case PACKET_ERROR:
8828 return -1;
8829 case PACKET_OK:
7c0f6dcc
JL
8830 bp_tgt->placed_address = addr;
8831 bp_tgt->placed_size = bpsize;
d471ea57
AC
8832 return 0;
8833 case PACKET_UNKNOWN:
8834 break;
96baa820
JM
8835 }
8836 }
c906108c 8837
0000e5cc
PA
8838 /* If this breakpoint has target-side commands but this stub doesn't
8839 support Z0 packets, throw error. */
8840 if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8841 throw_error (NOT_SUPPORTED_ERROR, _("\
8842Target doesn't support breakpoints that have target side commands."));
8843
3db08215 8844 return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8845}
8846
8847static int
3db08215
MM
8848remote_remove_breakpoint (struct target_ops *ops,
8849 struct gdbarch *gdbarch,
a6d9a66e 8850 struct bp_target_info *bp_tgt)
c906108c 8851{
8181d85f 8852 CORE_ADDR addr = bp_tgt->placed_address;
d01949b6 8853 struct remote_state *rs = get_remote_state ();
96baa820 8854
4082afcc 8855 if (packet_support (PACKET_Z0) != PACKET_DISABLE)
96baa820 8856 {
6d820c5c 8857 char *p = rs->buf;
bba74b36 8858 char *endbuf = rs->buf + get_remote_packet_size ();
802188a7 8859
28439a30
PA
8860 /* Make sure the remote is pointing at the right process, if
8861 necessary. */
8862 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8863 set_general_process ();
8864
96baa820
JM
8865 *(p++) = 'z';
8866 *(p++) = '0';
8867 *(p++) = ',';
8868
8181d85f
DJ
8869 addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8870 p += hexnumstr (p, addr);
bba74b36 8871 xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
802188a7 8872
6d820c5c
DJ
8873 putpkt (rs->buf);
8874 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8875
6d820c5c 8876 return (rs->buf[0] == 'E');
96baa820
JM
8877 }
8878
3db08215 8879 return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
c906108c
SS
8880}
8881
f486487f 8882static enum Z_packet_type
d471ea57
AC
8883watchpoint_to_Z_packet (int type)
8884{
8885 switch (type)
8886 {
8887 case hw_write:
bb858e6a 8888 return Z_PACKET_WRITE_WP;
d471ea57
AC
8889 break;
8890 case hw_read:
bb858e6a 8891 return Z_PACKET_READ_WP;
d471ea57
AC
8892 break;
8893 case hw_access:
bb858e6a 8894 return Z_PACKET_ACCESS_WP;
d471ea57
AC
8895 break;
8896 default:
8e65ff28 8897 internal_error (__FILE__, __LINE__,
e2e0b3e5 8898 _("hw_bp_to_z: bad watchpoint type %d"), type);
d471ea57
AC
8899 }
8900}
8901
3c3bea1c 8902static int
f486487f
SM
8903remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8904 enum target_hw_bp_type type, struct expression *cond)
96baa820 8905{
d01949b6 8906 struct remote_state *rs = get_remote_state ();
bba74b36 8907 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8908 char *p;
d471ea57 8909 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
96baa820 8910
4082afcc 8911 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
85d721b8 8912 return 1;
802188a7 8913
28439a30
PA
8914 /* Make sure the remote is pointing at the right process, if
8915 necessary. */
8916 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8917 set_general_process ();
8918
bba74b36 8919 xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
6d820c5c 8920 p = strchr (rs->buf, '\0');
96baa820
JM
8921 addr = remote_address_masked (addr);
8922 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8923 xsnprintf (p, endbuf - p, ",%x", len);
802188a7 8924
6d820c5c
DJ
8925 putpkt (rs->buf);
8926 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8927
6d820c5c 8928 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8929 {
8930 case PACKET_ERROR:
d471ea57 8931 return -1;
85d721b8
PA
8932 case PACKET_UNKNOWN:
8933 return 1;
d471ea57
AC
8934 case PACKET_OK:
8935 return 0;
8936 }
8e65ff28 8937 internal_error (__FILE__, __LINE__,
e2e0b3e5 8938 _("remote_insert_watchpoint: reached end of function"));
96baa820
JM
8939}
8940
283002cf
MR
8941static int
8942remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8943 CORE_ADDR start, int length)
8944{
8945 CORE_ADDR diff = remote_address_masked (addr - start);
8946
8947 return diff < length;
8948}
8949
d471ea57 8950
3c3bea1c 8951static int
f486487f
SM
8952remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
8953 enum target_hw_bp_type type, struct expression *cond)
96baa820 8954{
d01949b6 8955 struct remote_state *rs = get_remote_state ();
bba74b36 8956 char *endbuf = rs->buf + get_remote_packet_size ();
e514a9d6 8957 char *p;
d471ea57
AC
8958 enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8959
4082afcc 8960 if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
5cffb350 8961 return -1;
802188a7 8962
28439a30
PA
8963 /* Make sure the remote is pointing at the right process, if
8964 necessary. */
8965 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8966 set_general_process ();
8967
bba74b36 8968 xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
6d820c5c 8969 p = strchr (rs->buf, '\0');
96baa820
JM
8970 addr = remote_address_masked (addr);
8971 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 8972 xsnprintf (p, endbuf - p, ",%x", len);
6d820c5c
DJ
8973 putpkt (rs->buf);
8974 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 8975
6d820c5c 8976 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
d471ea57
AC
8977 {
8978 case PACKET_ERROR:
8979 case PACKET_UNKNOWN:
8980 return -1;
8981 case PACKET_OK:
8982 return 0;
8983 }
8e65ff28 8984 internal_error (__FILE__, __LINE__,
e2e0b3e5 8985 _("remote_remove_watchpoint: reached end of function"));
96baa820
JM
8986}
8987
3c3bea1c 8988
501eef12 8989int remote_hw_watchpoint_limit = -1;
480a3f21 8990int remote_hw_watchpoint_length_limit = -1;
501eef12 8991int remote_hw_breakpoint_limit = -1;
d471ea57 8992
480a3f21 8993static int
31568a15
TT
8994remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8995 CORE_ADDR addr, int len)
480a3f21
PW
8996{
8997 if (remote_hw_watchpoint_length_limit == 0)
8998 return 0;
8999 else if (remote_hw_watchpoint_length_limit < 0)
9000 return 1;
9001 else if (len <= remote_hw_watchpoint_length_limit)
9002 return 1;
9003 else
9004 return 0;
9005}
9006
b9362cc7 9007static int
5461485a 9008remote_check_watch_resources (struct target_ops *self,
f486487f 9009 enum bptype type, int cnt, int ot)
96baa820 9010{
3c3bea1c
GS
9011 if (type == bp_hardware_breakpoint)
9012 {
9013 if (remote_hw_breakpoint_limit == 0)
9014 return 0;
501eef12
AC
9015 else if (remote_hw_breakpoint_limit < 0)
9016 return 1;
3c3bea1c
GS
9017 else if (cnt <= remote_hw_breakpoint_limit)
9018 return 1;
9019 }
9020 else
9021 {
9022 if (remote_hw_watchpoint_limit == 0)
9023 return 0;
501eef12
AC
9024 else if (remote_hw_watchpoint_limit < 0)
9025 return 1;
3c3bea1c
GS
9026 else if (ot)
9027 return -1;
9028 else if (cnt <= remote_hw_watchpoint_limit)
9029 return 1;
9030 }
9031 return -1;
9032}
9033
f7e6eed5
PA
9034/* The to_stopped_by_sw_breakpoint method of target remote. */
9035
9036static int
9037remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9038{
9039 struct remote_state *rs = get_remote_state ();
9040
9041 return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
9042}
9043
9044/* The to_supports_stopped_by_sw_breakpoint method of target
9045 remote. */
9046
9047static int
9048remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
9049{
9050 struct remote_state *rs = get_remote_state ();
9051
9052 return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
9053}
9054
9055/* The to_stopped_by_hw_breakpoint method of target remote. */
9056
9057static int
9058remote_stopped_by_hw_breakpoint (struct target_ops *ops)
9059{
9060 struct remote_state *rs = get_remote_state ();
9061
9062 return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
9063}
9064
9065/* The to_supports_stopped_by_hw_breakpoint method of target
9066 remote. */
9067
9068static int
9069remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
9070{
9071 struct remote_state *rs = get_remote_state ();
9072
9073 return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
9074}
9075
b9362cc7 9076static int
6a109b6b 9077remote_stopped_by_watchpoint (struct target_ops *ops)
3c3bea1c 9078{
ee154bee
TT
9079 struct remote_state *rs = get_remote_state ();
9080
f7e6eed5 9081 return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
3c3bea1c
GS
9082}
9083
4aa7a7f5
JJ
9084static int
9085remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
3c3bea1c 9086{
ee154bee 9087 struct remote_state *rs = get_remote_state ();
4aa7a7f5 9088 int rc = 0;
a744cf53 9089
6a109b6b 9090 if (remote_stopped_by_watchpoint (target))
4aa7a7f5 9091 {
ee154bee 9092 *addr_p = rs->remote_watch_data_address;
4aa7a7f5
JJ
9093 rc = 1;
9094 }
9095
9096 return rc;
3c3bea1c
GS
9097}
9098
9099
9100static int
23a26771 9101remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9102 struct bp_target_info *bp_tgt)
3c3bea1c 9103{
0d5ed153 9104 CORE_ADDR addr = bp_tgt->reqstd_address;
4fff2411 9105 struct remote_state *rs;
bba74b36 9106 char *p, *endbuf;
dd61ec5c 9107 char *message;
0d5ed153 9108 int bpsize;
802188a7 9109
c8189ed1 9110 /* The length field should be set to the size of a breakpoint
8181d85f 9111 instruction, even though we aren't inserting one ourselves. */
c8189ed1 9112
0d5ed153 9113 gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
3c3bea1c 9114
4082afcc 9115 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9116 return -1;
2bc416ba 9117
28439a30
PA
9118 /* Make sure the remote is pointing at the right process, if
9119 necessary. */
9120 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9121 set_general_process ();
9122
4fff2411
JZ
9123 rs = get_remote_state ();
9124 p = rs->buf;
bba74b36 9125 endbuf = rs->buf + get_remote_packet_size ();
4fff2411 9126
96baa820
JM
9127 *(p++) = 'Z';
9128 *(p++) = '1';
9129 *(p++) = ',';
802188a7 9130
0d5ed153 9131 addr = remote_address_masked (addr);
96baa820 9132 p += hexnumstr (p, (ULONGEST) addr);
0d5ed153 9133 xsnprintf (p, endbuf - p, ",%x", bpsize);
96baa820 9134
efcc2da7 9135 if (remote_supports_cond_breakpoints (self))
bba74b36 9136 remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
b775012e 9137
78eff0ec 9138 if (remote_can_run_breakpoint_commands (self))
d3ce09f5
SS
9139 remote_add_target_side_commands (gdbarch, bp_tgt, p);
9140
6d820c5c
DJ
9141 putpkt (rs->buf);
9142 getpkt (&rs->buf, &rs->buf_size, 0);
96baa820 9143
6d820c5c 9144 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9145 {
9146 case PACKET_ERROR:
dd61ec5c
MW
9147 if (rs->buf[1] == '.')
9148 {
9149 message = strchr (rs->buf + 2, '.');
9150 if (message)
0316657e 9151 error (_("Remote failure reply: %s"), message + 1);
dd61ec5c
MW
9152 }
9153 return -1;
d471ea57
AC
9154 case PACKET_UNKNOWN:
9155 return -1;
9156 case PACKET_OK:
0d5ed153
MR
9157 bp_tgt->placed_address = addr;
9158 bp_tgt->placed_size = bpsize;
d471ea57
AC
9159 return 0;
9160 }
8e65ff28 9161 internal_error (__FILE__, __LINE__,
e2e0b3e5 9162 _("remote_insert_hw_breakpoint: reached end of function"));
96baa820
JM
9163}
9164
d471ea57 9165
802188a7 9166static int
a64dc96c 9167remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
a6d9a66e 9168 struct bp_target_info *bp_tgt)
96baa820 9169{
8181d85f 9170 CORE_ADDR addr;
d01949b6 9171 struct remote_state *rs = get_remote_state ();
6d820c5c 9172 char *p = rs->buf;
bba74b36 9173 char *endbuf = rs->buf + get_remote_packet_size ();
c8189ed1 9174
4082afcc 9175 if (packet_support (PACKET_Z1) == PACKET_DISABLE)
5cffb350 9176 return -1;
802188a7 9177
28439a30
PA
9178 /* Make sure the remote is pointing at the right process, if
9179 necessary. */
9180 if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9181 set_general_process ();
9182
96baa820
JM
9183 *(p++) = 'z';
9184 *(p++) = '1';
9185 *(p++) = ',';
802188a7 9186
8181d85f 9187 addr = remote_address_masked (bp_tgt->placed_address);
96baa820 9188 p += hexnumstr (p, (ULONGEST) addr);
bba74b36 9189 xsnprintf (p, endbuf - p, ",%x", bp_tgt->placed_size);
96baa820 9190
6d820c5c
DJ
9191 putpkt (rs->buf);
9192 getpkt (&rs->buf, &rs->buf_size, 0);
802188a7 9193
6d820c5c 9194 switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
d471ea57
AC
9195 {
9196 case PACKET_ERROR:
9197 case PACKET_UNKNOWN:
9198 return -1;
9199 case PACKET_OK:
9200 return 0;
9201 }
8e65ff28 9202 internal_error (__FILE__, __LINE__,
e2e0b3e5 9203 _("remote_remove_hw_breakpoint: reached end of function"));
96baa820 9204}
96baa820 9205
4a5e7a5b
PA
9206/* Verify memory using the "qCRC:" request. */
9207
9208static int
9209remote_verify_memory (struct target_ops *ops,
9210 const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
9211{
9212 struct remote_state *rs = get_remote_state ();
9213 unsigned long host_crc, target_crc;
9214 char *tmp;
9215
936d2992
PA
9216 /* It doesn't make sense to use qCRC if the remote target is
9217 connected but not running. */
9218 if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
9219 {
9220 enum packet_result result;
28439a30 9221
936d2992
PA
9222 /* Make sure the remote is pointing at the right process. */
9223 set_general_process ();
4a5e7a5b 9224
936d2992
PA
9225 /* FIXME: assumes lma can fit into long. */
9226 xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
9227 (long) lma, (long) size);
9228 putpkt (rs->buf);
4a5e7a5b 9229
936d2992
PA
9230 /* Be clever; compute the host_crc before waiting for target
9231 reply. */
9232 host_crc = xcrc32 (data, size, 0xffffffff);
9233
9234 getpkt (&rs->buf, &rs->buf_size, 0);
4a5e7a5b 9235
936d2992
PA
9236 result = packet_ok (rs->buf,
9237 &remote_protocol_packets[PACKET_qCRC]);
9238 if (result == PACKET_ERROR)
9239 return -1;
9240 else if (result == PACKET_OK)
9241 {
9242 for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9243 target_crc = target_crc * 16 + fromhex (*tmp);
4a5e7a5b 9244
936d2992
PA
9245 return (host_crc == target_crc);
9246 }
9247 }
4a5e7a5b 9248
936d2992 9249 return simple_verify_memory (ops, data, lma, size);
4a5e7a5b
PA
9250}
9251
c906108c
SS
9252/* compare-sections command
9253
9254 With no arguments, compares each loadable section in the exec bfd
9255 with the same memory range on the target, and reports mismatches.
4a5e7a5b 9256 Useful for verifying the image on the target against the exec file. */
e514a9d6 9257
c906108c 9258static void
fba45db2 9259compare_sections_command (char *args, int from_tty)
c906108c
SS
9260{
9261 asection *s;
c906108c 9262 struct cleanup *old_chain;
948f8e3d 9263 gdb_byte *sectdata;
ce359b09 9264 const char *sectname;
c906108c
SS
9265 bfd_size_type size;
9266 bfd_vma lma;
9267 int matched = 0;
9268 int mismatched = 0;
4a5e7a5b 9269 int res;
95cf3b38 9270 int read_only = 0;
c906108c
SS
9271
9272 if (!exec_bfd)
8a3fe4f8 9273 error (_("command cannot be used without an exec file"));
c906108c 9274
28439a30
PA
9275 /* Make sure the remote is pointing at the right process. */
9276 set_general_process ();
9277
95cf3b38
DT
9278 if (args != NULL && strcmp (args, "-r") == 0)
9279 {
9280 read_only = 1;
9281 args = NULL;
9282 }
9283
c5aa993b 9284 for (s = exec_bfd->sections; s; s = s->next)
c906108c
SS
9285 {
9286 if (!(s->flags & SEC_LOAD))
0df8b418 9287 continue; /* Skip non-loadable section. */
c906108c 9288
95cf3b38
DT
9289 if (read_only && (s->flags & SEC_READONLY) == 0)
9290 continue; /* Skip writeable sections */
9291
2c500098 9292 size = bfd_get_section_size (s);
c906108c 9293 if (size == 0)
0df8b418 9294 continue; /* Skip zero-length section. */
c906108c 9295
ce359b09 9296 sectname = bfd_get_section_name (exec_bfd, s);
c906108c 9297 if (args && strcmp (args, sectname) != 0)
0df8b418 9298 continue; /* Not the section selected by user. */
c906108c 9299
0df8b418 9300 matched = 1; /* Do this section. */
c906108c 9301 lma = s->lma;
c906108c 9302
c906108c 9303 sectdata = xmalloc (size);
b8c9b27d 9304 old_chain = make_cleanup (xfree, sectdata);
c906108c 9305 bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
c906108c 9306
4a5e7a5b
PA
9307 res = target_verify_memory (sectdata, lma, size);
9308
9309 if (res == -1)
5af949e3 9310 error (_("target memory fault, section %s, range %s -- %s"), sectname,
f5656ead
TT
9311 paddress (target_gdbarch (), lma),
9312 paddress (target_gdbarch (), lma + size));
c906108c 9313
5af949e3 9314 printf_filtered ("Section %s, range %s -- %s: ", sectname,
f5656ead
TT
9315 paddress (target_gdbarch (), lma),
9316 paddress (target_gdbarch (), lma + size));
4a5e7a5b 9317 if (res)
c906108c
SS
9318 printf_filtered ("matched.\n");
9319 else
c5aa993b
JM
9320 {
9321 printf_filtered ("MIS-MATCHED!\n");
9322 mismatched++;
9323 }
c906108c
SS
9324
9325 do_cleanups (old_chain);
9326 }
9327 if (mismatched > 0)
936d2992 9328 warning (_("One or more sections of the target image does not match\n\
8a3fe4f8 9329the loaded file\n"));
c906108c 9330 if (args && !matched)
a3f17187 9331 printf_filtered (_("No loaded section named '%s'.\n"), args);
c906108c
SS
9332}
9333
0e7f50da
UW
9334/* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9335 into remote target. The number of bytes written to the remote
9336 target is returned, or -1 for error. */
9337
9b409511 9338static enum target_xfer_status
0e7f50da
UW
9339remote_write_qxfer (struct target_ops *ops, const char *object_name,
9340 const char *annex, const gdb_byte *writebuf,
9b409511 9341 ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
0e7f50da
UW
9342 struct packet_config *packet)
9343{
9344 int i, buf_len;
9345 ULONGEST n;
0e7f50da
UW
9346 struct remote_state *rs = get_remote_state ();
9347 int max_size = get_memory_write_packet_size ();
9348
9349 if (packet->support == PACKET_DISABLE)
2ed4b548 9350 return TARGET_XFER_E_IO;
0e7f50da
UW
9351
9352 /* Insert header. */
9353 i = snprintf (rs->buf, max_size,
9354 "qXfer:%s:write:%s:%s:",
9355 object_name, annex ? annex : "",
9356 phex_nz (offset, sizeof offset));
9357 max_size -= (i + 1);
9358
9359 /* Escape as much data as fits into rs->buf. */
9360 buf_len = remote_escape_output
124e13d9 9361 (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
0e7f50da
UW
9362
9363 if (putpkt_binary (rs->buf, i + buf_len) < 0
9364 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9365 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9366 return TARGET_XFER_E_IO;
0e7f50da
UW
9367
9368 unpack_varlen_hex (rs->buf, &n);
9b409511
YQ
9369
9370 *xfered_len = n;
9371 return TARGET_XFER_OK;
0e7f50da
UW
9372}
9373
0876f84a
DJ
9374/* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9375 Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9376 number of bytes read is returned, or 0 for EOF, or -1 for error.
9377 The number of bytes read may be less than LEN without indicating an
9378 EOF. PACKET is checked and updated to indicate whether the remote
9379 target supports this object. */
9380
9b409511 9381static enum target_xfer_status
0876f84a
DJ
9382remote_read_qxfer (struct target_ops *ops, const char *object_name,
9383 const char *annex,
9384 gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9b409511 9385 ULONGEST *xfered_len,
0876f84a
DJ
9386 struct packet_config *packet)
9387{
0876f84a 9388 struct remote_state *rs = get_remote_state ();
0876f84a
DJ
9389 LONGEST i, n, packet_len;
9390
9391 if (packet->support == PACKET_DISABLE)
2ed4b548 9392 return TARGET_XFER_E_IO;
0876f84a
DJ
9393
9394 /* Check whether we've cached an end-of-object packet that matches
9395 this request. */
8e88304f 9396 if (rs->finished_object)
0876f84a 9397 {
8e88304f
TT
9398 if (strcmp (object_name, rs->finished_object) == 0
9399 && strcmp (annex ? annex : "", rs->finished_annex) == 0
9400 && offset == rs->finished_offset)
9b409511
YQ
9401 return TARGET_XFER_EOF;
9402
0876f84a
DJ
9403
9404 /* Otherwise, we're now reading something different. Discard
9405 the cache. */
8e88304f
TT
9406 xfree (rs->finished_object);
9407 xfree (rs->finished_annex);
9408 rs->finished_object = NULL;
9409 rs->finished_annex = NULL;
0876f84a
DJ
9410 }
9411
9412 /* Request only enough to fit in a single packet. The actual data
9413 may not, since we don't know how much of it will need to be escaped;
9414 the target is free to respond with slightly less data. We subtract
9415 five to account for the response type and the protocol frame. */
9416 n = min (get_remote_packet_size () - 5, len);
9417 snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9418 object_name, annex ? annex : "",
9419 phex_nz (offset, sizeof offset),
9420 phex_nz (n, sizeof n));
9421 i = putpkt (rs->buf);
9422 if (i < 0)
2ed4b548 9423 return TARGET_XFER_E_IO;
0876f84a
DJ
9424
9425 rs->buf[0] = '\0';
9426 packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9427 if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
2ed4b548 9428 return TARGET_XFER_E_IO;
0876f84a
DJ
9429
9430 if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9431 error (_("Unknown remote qXfer reply: %s"), rs->buf);
9432
9433 /* 'm' means there is (or at least might be) more data after this
9434 batch. That does not make sense unless there's at least one byte
9435 of data in this reply. */
9436 if (rs->buf[0] == 'm' && packet_len == 1)
9437 error (_("Remote qXfer reply contained no data."));
9438
9439 /* Got some data. */
bc20a4af
PA
9440 i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9441 packet_len - 1, readbuf, n);
0876f84a
DJ
9442
9443 /* 'l' is an EOF marker, possibly including a final block of data,
0e7f50da
UW
9444 or possibly empty. If we have the final block of a non-empty
9445 object, record this fact to bypass a subsequent partial read. */
9446 if (rs->buf[0] == 'l' && offset + i > 0)
0876f84a 9447 {
8e88304f
TT
9448 rs->finished_object = xstrdup (object_name);
9449 rs->finished_annex = xstrdup (annex ? annex : "");
9450 rs->finished_offset = offset + i;
0876f84a
DJ
9451 }
9452
9b409511
YQ
9453 if (i == 0)
9454 return TARGET_XFER_EOF;
9455 else
9456 {
9457 *xfered_len = i;
9458 return TARGET_XFER_OK;
9459 }
0876f84a
DJ
9460}
9461
9b409511 9462static enum target_xfer_status
4b8a223f 9463remote_xfer_partial (struct target_ops *ops, enum target_object object,
961cb7b5 9464 const char *annex, gdb_byte *readbuf,
9b409511
YQ
9465 const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9466 ULONGEST *xfered_len)
c906108c 9467{
82f73884 9468 struct remote_state *rs;
c906108c 9469 int i;
6d820c5c 9470 char *p2;
1e3ff5ad 9471 char query_type;
124e13d9 9472 int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
c906108c 9473
e6e4e701 9474 set_remote_traceframe ();
82f73884
PA
9475 set_general_thread (inferior_ptid);
9476
9477 rs = get_remote_state ();
9478
b2182ed2 9479 /* Handle memory using the standard memory routines. */
21e3b9b9
DJ
9480 if (object == TARGET_OBJECT_MEMORY)
9481 {
2d717e4f
DJ
9482 /* If the remote target is connected but not running, we should
9483 pass this request down to a lower stratum (e.g. the executable
9484 file). */
9485 if (!target_has_execution)
9b409511 9486 return TARGET_XFER_EOF;
2d717e4f 9487
21e3b9b9 9488 if (writebuf != NULL)
124e13d9
SM
9489 return remote_write_bytes (offset, writebuf, len, unit_size,
9490 xfered_len);
21e3b9b9 9491 else
124e13d9
SM
9492 return remote_read_bytes (ops, offset, readbuf, len, unit_size,
9493 xfered_len);
21e3b9b9
DJ
9494 }
9495
0df8b418 9496 /* Handle SPU memory using qxfer packets. */
0e7f50da
UW
9497 if (object == TARGET_OBJECT_SPU)
9498 {
9499 if (readbuf)
9500 return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9b409511
YQ
9501 xfered_len, &remote_protocol_packets
9502 [PACKET_qXfer_spu_read]);
0e7f50da
UW
9503 else
9504 return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9b409511
YQ
9505 xfered_len, &remote_protocol_packets
9506 [PACKET_qXfer_spu_write]);
0e7f50da
UW
9507 }
9508
4aa995e1
PA
9509 /* Handle extra signal info using qxfer packets. */
9510 if (object == TARGET_OBJECT_SIGNAL_INFO)
9511 {
9512 if (readbuf)
9513 return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9b409511 9514 xfered_len, &remote_protocol_packets
4aa995e1
PA
9515 [PACKET_qXfer_siginfo_read]);
9516 else
3e43a32a 9517 return remote_write_qxfer (ops, "siginfo", annex,
9b409511 9518 writebuf, offset, len, xfered_len,
4aa995e1
PA
9519 &remote_protocol_packets
9520 [PACKET_qXfer_siginfo_write]);
9521 }
9522
0fb4aa4b
PA
9523 if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9524 {
9525 if (readbuf)
3e43a32a 9526 return remote_read_qxfer (ops, "statictrace", annex,
9b409511 9527 readbuf, offset, len, xfered_len,
0fb4aa4b
PA
9528 &remote_protocol_packets
9529 [PACKET_qXfer_statictrace_read]);
9530 else
2ed4b548 9531 return TARGET_XFER_E_IO;
0fb4aa4b
PA
9532 }
9533
a76d924d
DJ
9534 /* Only handle flash writes. */
9535 if (writebuf != NULL)
9536 {
9537 LONGEST xfered;
9538
9539 switch (object)
9540 {
9541 case TARGET_OBJECT_FLASH:
9b409511
YQ
9542 return remote_flash_write (ops, offset, len, xfered_len,
9543 writebuf);
a76d924d
DJ
9544
9545 default:
2ed4b548 9546 return TARGET_XFER_E_IO;
a76d924d
DJ
9547 }
9548 }
4b8a223f 9549
1e3ff5ad
AC
9550 /* Map pre-existing objects onto letters. DO NOT do this for new
9551 objects!!! Instead specify new query packets. */
9552 switch (object)
c906108c 9553 {
1e3ff5ad
AC
9554 case TARGET_OBJECT_AVR:
9555 query_type = 'R';
9556 break;
802188a7
RM
9557
9558 case TARGET_OBJECT_AUXV:
0876f84a
DJ
9559 gdb_assert (annex == NULL);
9560 return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9b409511 9561 xfered_len,
0876f84a 9562 &remote_protocol_packets[PACKET_qXfer_auxv]);
802188a7 9563
23181151
DJ
9564 case TARGET_OBJECT_AVAILABLE_FEATURES:
9565 return remote_read_qxfer
9b409511 9566 (ops, "features", annex, readbuf, offset, len, xfered_len,
23181151
DJ
9567 &remote_protocol_packets[PACKET_qXfer_features]);
9568
cfa9d6d9
DJ
9569 case TARGET_OBJECT_LIBRARIES:
9570 return remote_read_qxfer
9b409511 9571 (ops, "libraries", annex, readbuf, offset, len, xfered_len,
cfa9d6d9
DJ
9572 &remote_protocol_packets[PACKET_qXfer_libraries]);
9573
2268b414
JK
9574 case TARGET_OBJECT_LIBRARIES_SVR4:
9575 return remote_read_qxfer
9b409511 9576 (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
2268b414
JK
9577 &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9578
fd79ecee
DJ
9579 case TARGET_OBJECT_MEMORY_MAP:
9580 gdb_assert (annex == NULL);
9581 return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9b409511 9582 xfered_len,
fd79ecee
DJ
9583 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9584
07e059b5
VP
9585 case TARGET_OBJECT_OSDATA:
9586 /* Should only get here if we're connected. */
5d93a237 9587 gdb_assert (rs->remote_desc);
07e059b5 9588 return remote_read_qxfer
9b409511 9589 (ops, "osdata", annex, readbuf, offset, len, xfered_len,
07e059b5
VP
9590 &remote_protocol_packets[PACKET_qXfer_osdata]);
9591
dc146f7c
VP
9592 case TARGET_OBJECT_THREADS:
9593 gdb_assert (annex == NULL);
9594 return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9b409511 9595 xfered_len,
dc146f7c
VP
9596 &remote_protocol_packets[PACKET_qXfer_threads]);
9597
b3b9301e
PA
9598 case TARGET_OBJECT_TRACEFRAME_INFO:
9599 gdb_assert (annex == NULL);
9600 return remote_read_qxfer
9b409511 9601 (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
b3b9301e 9602 &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
78d85199
YQ
9603
9604 case TARGET_OBJECT_FDPIC:
9605 return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9b409511 9606 xfered_len,
78d85199 9607 &remote_protocol_packets[PACKET_qXfer_fdpic]);
169081d0
TG
9608
9609 case TARGET_OBJECT_OPENVMS_UIB:
9610 return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9b409511 9611 xfered_len,
169081d0
TG
9612 &remote_protocol_packets[PACKET_qXfer_uib]);
9613
9accd112
MM
9614 case TARGET_OBJECT_BTRACE:
9615 return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9b409511 9616 xfered_len,
9accd112
MM
9617 &remote_protocol_packets[PACKET_qXfer_btrace]);
9618
f4abbc16
MM
9619 case TARGET_OBJECT_BTRACE_CONF:
9620 return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9621 len, xfered_len,
9622 &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9623
c78fa86a
GB
9624 case TARGET_OBJECT_EXEC_FILE:
9625 return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9626 len, xfered_len,
9627 &remote_protocol_packets[PACKET_qXfer_exec_file]);
9628
1e3ff5ad 9629 default:
2ed4b548 9630 return TARGET_XFER_E_IO;
c906108c
SS
9631 }
9632
0df8b418 9633 /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
24b06219 9634 large enough let the caller deal with it. */
ea9c271d 9635 if (len < get_remote_packet_size ())
2ed4b548 9636 return TARGET_XFER_E_IO;
ea9c271d 9637 len = get_remote_packet_size ();
1e3ff5ad 9638
23860348 9639 /* Except for querying the minimum buffer size, target must be open. */
5d93a237 9640 if (!rs->remote_desc)
8a3fe4f8 9641 error (_("remote query is only available after target open"));
c906108c 9642
1e3ff5ad 9643 gdb_assert (annex != NULL);
4b8a223f 9644 gdb_assert (readbuf != NULL);
c906108c 9645
6d820c5c 9646 p2 = rs->buf;
c906108c
SS
9647 *p2++ = 'q';
9648 *p2++ = query_type;
9649
23860348
MS
9650 /* We used one buffer char for the remote protocol q command and
9651 another for the query type. As the remote protocol encapsulation
9652 uses 4 chars plus one extra in case we are debugging
9653 (remote_debug), we have PBUFZIZ - 7 left to pack the query
9654 string. */
c906108c 9655 i = 0;
ea9c271d 9656 while (annex[i] && (i < (get_remote_packet_size () - 8)))
c906108c 9657 {
1e3ff5ad
AC
9658 /* Bad caller may have sent forbidden characters. */
9659 gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9660 *p2++ = annex[i];
c906108c
SS
9661 i++;
9662 }
1e3ff5ad
AC
9663 *p2 = '\0';
9664 gdb_assert (annex[i] == '\0');
c906108c 9665
6d820c5c 9666 i = putpkt (rs->buf);
c5aa993b 9667 if (i < 0)
2ed4b548 9668 return TARGET_XFER_E_IO;
c906108c 9669
6d820c5c
DJ
9670 getpkt (&rs->buf, &rs->buf_size, 0);
9671 strcpy ((char *) readbuf, rs->buf);
c906108c 9672
9b409511
YQ
9673 *xfered_len = strlen ((char *) readbuf);
9674 return TARGET_XFER_OK;
c906108c
SS
9675}
9676
08388c79
DE
9677static int
9678remote_search_memory (struct target_ops* ops,
9679 CORE_ADDR start_addr, ULONGEST search_space_len,
9680 const gdb_byte *pattern, ULONGEST pattern_len,
9681 CORE_ADDR *found_addrp)
9682{
f5656ead 9683 int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
08388c79
DE
9684 struct remote_state *rs = get_remote_state ();
9685 int max_size = get_memory_write_packet_size ();
9686 struct packet_config *packet =
9687 &remote_protocol_packets[PACKET_qSearch_memory];
0df8b418
MS
9688 /* Number of packet bytes used to encode the pattern;
9689 this could be more than PATTERN_LEN due to escape characters. */
08388c79 9690 int escaped_pattern_len;
0df8b418 9691 /* Amount of pattern that was encodable in the packet. */
08388c79
DE
9692 int used_pattern_len;
9693 int i;
9694 int found;
9695 ULONGEST found_addr;
9696
9697 /* Don't go to the target if we don't have to.
9698 This is done before checking packet->support to avoid the possibility that
9699 a success for this edge case means the facility works in general. */
9700 if (pattern_len > search_space_len)
9701 return 0;
9702 if (pattern_len == 0)
9703 {
9704 *found_addrp = start_addr;
9705 return 1;
9706 }
9707
9708 /* If we already know the packet isn't supported, fall back to the simple
9709 way of searching memory. */
9710
4082afcc 9711 if (packet_config_support (packet) == PACKET_DISABLE)
08388c79
DE
9712 {
9713 /* Target doesn't provided special support, fall back and use the
9714 standard support (copy memory and do the search here). */
9715 return simple_search_memory (ops, start_addr, search_space_len,
9716 pattern, pattern_len, found_addrp);
9717 }
9718
28439a30
PA
9719 /* Make sure the remote is pointing at the right process. */
9720 set_general_process ();
9721
08388c79
DE
9722 /* Insert header. */
9723 i = snprintf (rs->buf, max_size,
9724 "qSearch:memory:%s;%s;",
5af949e3 9725 phex_nz (start_addr, addr_size),
08388c79
DE
9726 phex_nz (search_space_len, sizeof (search_space_len)));
9727 max_size -= (i + 1);
9728
9729 /* Escape as much data as fits into rs->buf. */
9730 escaped_pattern_len =
124e13d9 9731 remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
08388c79
DE
9732 &used_pattern_len, max_size);
9733
9734 /* Bail if the pattern is too large. */
9735 if (used_pattern_len != pattern_len)
9b20d036 9736 error (_("Pattern is too large to transmit to remote target."));
08388c79
DE
9737
9738 if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9739 || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9740 || packet_ok (rs->buf, packet) != PACKET_OK)
9741 {
9742 /* The request may not have worked because the command is not
9743 supported. If so, fall back to the simple way. */
9744 if (packet->support == PACKET_DISABLE)
9745 {
9746 return simple_search_memory (ops, start_addr, search_space_len,
9747 pattern, pattern_len, found_addrp);
9748 }
9749 return -1;
9750 }
9751
9752 if (rs->buf[0] == '0')
9753 found = 0;
9754 else if (rs->buf[0] == '1')
9755 {
9756 found = 1;
9757 if (rs->buf[1] != ',')
10e0fa18 9758 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9759 unpack_varlen_hex (rs->buf + 2, &found_addr);
9760 *found_addrp = found_addr;
9761 }
9762 else
10e0fa18 9763 error (_("Unknown qSearch:memory reply: %s"), rs->buf);
08388c79
DE
9764
9765 return found;
9766}
9767
96baa820 9768static void
a30bf1f1 9769remote_rcmd (struct target_ops *self, const char *command,
d9fcf2fb 9770 struct ui_file *outbuf)
96baa820 9771{
d01949b6 9772 struct remote_state *rs = get_remote_state ();
2e9f7625 9773 char *p = rs->buf;
96baa820 9774
5d93a237 9775 if (!rs->remote_desc)
8a3fe4f8 9776 error (_("remote rcmd is only available after target open"));
96baa820 9777
23860348 9778 /* Send a NULL command across as an empty command. */
7be570e7
JM
9779 if (command == NULL)
9780 command = "";
9781
23860348 9782 /* The query prefix. */
2e9f7625
DJ
9783 strcpy (rs->buf, "qRcmd,");
9784 p = strchr (rs->buf, '\0');
96baa820 9785
3e43a32a
MS
9786 if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9787 > get_remote_packet_size ())
8a3fe4f8 9788 error (_("\"monitor\" command ``%s'' is too long."), command);
96baa820 9789
23860348 9790 /* Encode the actual command. */
a30bf1f1 9791 bin2hex ((const gdb_byte *) command, p, strlen (command));
96baa820 9792
6d820c5c 9793 if (putpkt (rs->buf) < 0)
8a3fe4f8 9794 error (_("Communication problem with target."));
96baa820
JM
9795
9796 /* get/display the response */
9797 while (1)
9798 {
2e9f7625
DJ
9799 char *buf;
9800
00bf0b85 9801 /* XXX - see also remote_get_noisy_reply(). */
5b37825d 9802 QUIT; /* Allow user to bail out with ^C. */
2e9f7625 9803 rs->buf[0] = '\0';
5b37825d
PW
9804 if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9805 {
9806 /* Timeout. Continue to (try to) read responses.
9807 This is better than stopping with an error, assuming the stub
9808 is still executing the (long) monitor command.
9809 If needed, the user can interrupt gdb using C-c, obtaining
9810 an effect similar to stop on timeout. */
9811 continue;
9812 }
2e9f7625 9813 buf = rs->buf;
96baa820 9814 if (buf[0] == '\0')
8a3fe4f8 9815 error (_("Target does not support this command."));
96baa820
JM
9816 if (buf[0] == 'O' && buf[1] != 'K')
9817 {
23860348 9818 remote_console_output (buf + 1); /* 'O' message from stub. */
96baa820
JM
9819 continue;
9820 }
9821 if (strcmp (buf, "OK") == 0)
9822 break;
7be570e7
JM
9823 if (strlen (buf) == 3 && buf[0] == 'E'
9824 && isdigit (buf[1]) && isdigit (buf[2]))
9825 {
8a3fe4f8 9826 error (_("Protocol error with Rcmd"));
7be570e7 9827 }
96baa820
JM
9828 for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9829 {
9830 char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
a744cf53 9831
96baa820
JM
9832 fputc_unfiltered (c, outbuf);
9833 }
9834 break;
9835 }
9836}
9837
fd79ecee
DJ
9838static VEC(mem_region_s) *
9839remote_memory_map (struct target_ops *ops)
9840{
9841 VEC(mem_region_s) *result = NULL;
9842 char *text = target_read_stralloc (&current_target,
9843 TARGET_OBJECT_MEMORY_MAP, NULL);
9844
9845 if (text)
9846 {
9847 struct cleanup *back_to = make_cleanup (xfree, text);
a744cf53 9848
fd79ecee
DJ
9849 result = parse_memory_map (text);
9850 do_cleanups (back_to);
9851 }
9852
9853 return result;
9854}
9855
c906108c 9856static void
fba45db2 9857packet_command (char *args, int from_tty)
c906108c 9858{
d01949b6 9859 struct remote_state *rs = get_remote_state ();
c906108c 9860
5d93a237 9861 if (!rs->remote_desc)
8a3fe4f8 9862 error (_("command can only be used with remote target"));
c906108c 9863
c5aa993b 9864 if (!args)
8a3fe4f8 9865 error (_("remote-packet command requires packet text as argument"));
c906108c
SS
9866
9867 puts_filtered ("sending: ");
9868 print_packet (args);
9869 puts_filtered ("\n");
9870 putpkt (args);
9871
6d820c5c 9872 getpkt (&rs->buf, &rs->buf_size, 0);
c906108c 9873 puts_filtered ("received: ");
6d820c5c 9874 print_packet (rs->buf);
c906108c
SS
9875 puts_filtered ("\n");
9876}
9877
9878#if 0
23860348 9879/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
c906108c 9880
a14ed312 9881static void display_thread_info (struct gdb_ext_thread_info *info);
c906108c 9882
a14ed312 9883static void threadset_test_cmd (char *cmd, int tty);
c906108c 9884
a14ed312 9885static void threadalive_test (char *cmd, int tty);
c906108c 9886
a14ed312 9887static void threadlist_test_cmd (char *cmd, int tty);
c906108c 9888
23860348 9889int get_and_display_threadinfo (threadref *ref);
c906108c 9890
a14ed312 9891static void threadinfo_test_cmd (char *cmd, int tty);
c906108c 9892
23860348 9893static int thread_display_step (threadref *ref, void *context);
c906108c 9894
a14ed312 9895static void threadlist_update_test_cmd (char *cmd, int tty);
c906108c 9896
a14ed312 9897static void init_remote_threadtests (void);
c906108c 9898
23860348 9899#define SAMPLE_THREAD 0x05060708 /* Truncated 64 bit threadid. */
c906108c
SS
9900
9901static void
fba45db2 9902threadset_test_cmd (char *cmd, int tty)
c906108c
SS
9903{
9904 int sample_thread = SAMPLE_THREAD;
9905
a3f17187 9906 printf_filtered (_("Remote threadset test\n"));
79d7f229 9907 set_general_thread (sample_thread);
c906108c
SS
9908}
9909
9910
9911static void
fba45db2 9912threadalive_test (char *cmd, int tty)
c906108c
SS
9913{
9914 int sample_thread = SAMPLE_THREAD;
79d7f229 9915 int pid = ptid_get_pid (inferior_ptid);
ba348170 9916 ptid_t ptid = ptid_build (pid, sample_thread, 0);
c906108c 9917
79d7f229 9918 if (remote_thread_alive (ptid))
c906108c
SS
9919 printf_filtered ("PASS: Thread alive test\n");
9920 else
9921 printf_filtered ("FAIL: Thread alive test\n");
9922}
9923
23860348 9924void output_threadid (char *title, threadref *ref);
c906108c
SS
9925
9926void
fba45db2 9927output_threadid (char *title, threadref *ref)
c906108c
SS
9928{
9929 char hexid[20];
9930
23860348 9931 pack_threadid (&hexid[0], ref); /* Convert threead id into hex. */
c906108c
SS
9932 hexid[16] = 0;
9933 printf_filtered ("%s %s\n", title, (&hexid[0]));
9934}
9935
9936static void
fba45db2 9937threadlist_test_cmd (char *cmd, int tty)
c906108c
SS
9938{
9939 int startflag = 1;
9940 threadref nextthread;
9941 int done, result_count;
9942 threadref threadlist[3];
9943
9944 printf_filtered ("Remote Threadlist test\n");
9945 if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9946 &result_count, &threadlist[0]))
9947 printf_filtered ("FAIL: threadlist test\n");
9948 else
9949 {
9950 threadref *scan = threadlist;
9951 threadref *limit = scan + result_count;
9952
9953 while (scan < limit)
9954 output_threadid (" thread ", scan++);
9955 }
9956}
9957
9958void
fba45db2 9959display_thread_info (struct gdb_ext_thread_info *info)
c906108c
SS
9960{
9961 output_threadid ("Threadid: ", &info->threadid);
9962 printf_filtered ("Name: %s\n ", info->shortname);
9963 printf_filtered ("State: %s\n", info->display);
9964 printf_filtered ("other: %s\n\n", info->more_display);
9965}
9966
9967int
fba45db2 9968get_and_display_threadinfo (threadref *ref)
c906108c
SS
9969{
9970 int result;
9971 int set;
9972 struct gdb_ext_thread_info threadinfo;
9973
9974 set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9975 | TAG_MOREDISPLAY | TAG_DISPLAY;
9976 if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9977 display_thread_info (&threadinfo);
9978 return result;
9979}
9980
9981static void
fba45db2 9982threadinfo_test_cmd (char *cmd, int tty)
c906108c
SS
9983{
9984 int athread = SAMPLE_THREAD;
9985 threadref thread;
9986 int set;
9987
9988 int_to_threadref (&thread, athread);
9989 printf_filtered ("Remote Threadinfo test\n");
9990 if (!get_and_display_threadinfo (&thread))
9991 printf_filtered ("FAIL cannot get thread info\n");
9992}
9993
9994static int
fba45db2 9995thread_display_step (threadref *ref, void *context)
c906108c
SS
9996{
9997 /* output_threadid(" threadstep ",ref); *//* simple test */
9998 return get_and_display_threadinfo (ref);
9999}
10000
10001static void
fba45db2 10002threadlist_update_test_cmd (char *cmd, int tty)
c906108c
SS
10003{
10004 printf_filtered ("Remote Threadlist update test\n");
10005 remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10006}
10007
10008static void
10009init_remote_threadtests (void)
10010{
3e43a32a
MS
10011 add_com ("tlist", class_obscure, threadlist_test_cmd,
10012 _("Fetch and print the remote list of "
10013 "thread identifiers, one pkt only"));
c906108c 10014 add_com ("tinfo", class_obscure, threadinfo_test_cmd,
1bedd215 10015 _("Fetch and display info about one thread"));
c906108c 10016 add_com ("tset", class_obscure, threadset_test_cmd,
1bedd215 10017 _("Test setting to a different thread"));
c906108c 10018 add_com ("tupd", class_obscure, threadlist_update_test_cmd,
1bedd215 10019 _("Iterate through updating all remote thread info"));
c906108c 10020 add_com ("talive", class_obscure, threadalive_test,
1bedd215 10021 _(" Remote thread alive test "));
c906108c
SS
10022}
10023
10024#endif /* 0 */
10025
f3fb8c85
MS
10026/* Convert a thread ID to a string. Returns the string in a static
10027 buffer. */
10028
10029static char *
117de6a9 10030remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
f3fb8c85 10031{
79d7f229 10032 static char buf[64];
82f73884 10033 struct remote_state *rs = get_remote_state ();
f3fb8c85 10034
7cee1e54
PA
10035 if (ptid_equal (ptid, null_ptid))
10036 return normal_pid_to_str (ptid);
10037 else if (ptid_is_pid (ptid))
ecd0ada5
PA
10038 {
10039 /* Printing an inferior target id. */
10040
10041 /* When multi-process extensions are off, there's no way in the
10042 remote protocol to know the remote process id, if there's any
10043 at all. There's one exception --- when we're connected with
10044 target extended-remote, and we manually attached to a process
10045 with "attach PID". We don't record anywhere a flag that
10046 allows us to distinguish that case from the case of
10047 connecting with extended-remote and the stub already being
10048 attached to a process, and reporting yes to qAttached, hence
10049 no smart special casing here. */
10050 if (!remote_multi_process_p (rs))
10051 {
10052 xsnprintf (buf, sizeof buf, "Remote target");
10053 return buf;
10054 }
10055
10056 return normal_pid_to_str (ptid);
82f73884 10057 }
ecd0ada5 10058 else
79d7f229 10059 {
ecd0ada5
PA
10060 if (ptid_equal (magic_null_ptid, ptid))
10061 xsnprintf (buf, sizeof buf, "Thread <main>");
901f9912 10062 else if (rs->extended && remote_multi_process_p (rs))
de0d863e
DB
10063 if (ptid_get_lwp (ptid) == 0)
10064 return normal_pid_to_str (ptid);
10065 else
10066 xsnprintf (buf, sizeof buf, "Thread %d.%ld",
10067 ptid_get_pid (ptid), ptid_get_lwp (ptid));
ecd0ada5
PA
10068 else
10069 xsnprintf (buf, sizeof buf, "Thread %ld",
ba348170 10070 ptid_get_lwp (ptid));
79d7f229
PA
10071 return buf;
10072 }
f3fb8c85
MS
10073}
10074
38691318
KB
10075/* Get the address of the thread local variable in OBJFILE which is
10076 stored at OFFSET within the thread local storage for thread PTID. */
10077
10078static CORE_ADDR
117de6a9
PA
10079remote_get_thread_local_address (struct target_ops *ops,
10080 ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
38691318 10081{
4082afcc 10082 if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
38691318
KB
10083 {
10084 struct remote_state *rs = get_remote_state ();
6d820c5c 10085 char *p = rs->buf;
82f73884 10086 char *endp = rs->buf + get_remote_packet_size ();
571dd617 10087 enum packet_result result;
38691318
KB
10088
10089 strcpy (p, "qGetTLSAddr:");
10090 p += strlen (p);
82f73884 10091 p = write_ptid (p, endp, ptid);
38691318
KB
10092 *p++ = ',';
10093 p += hexnumstr (p, offset);
10094 *p++ = ',';
10095 p += hexnumstr (p, lm);
10096 *p++ = '\0';
10097
6d820c5c
DJ
10098 putpkt (rs->buf);
10099 getpkt (&rs->buf, &rs->buf_size, 0);
3e43a32a
MS
10100 result = packet_ok (rs->buf,
10101 &remote_protocol_packets[PACKET_qGetTLSAddr]);
571dd617 10102 if (result == PACKET_OK)
38691318
KB
10103 {
10104 ULONGEST result;
10105
6d820c5c 10106 unpack_varlen_hex (rs->buf, &result);
38691318
KB
10107 return result;
10108 }
571dd617 10109 else if (result == PACKET_UNKNOWN)
109c3e39
AC
10110 throw_error (TLS_GENERIC_ERROR,
10111 _("Remote target doesn't support qGetTLSAddr packet"));
38691318 10112 else
109c3e39
AC
10113 throw_error (TLS_GENERIC_ERROR,
10114 _("Remote target failed to process qGetTLSAddr request"));
38691318
KB
10115 }
10116 else
109c3e39
AC
10117 throw_error (TLS_GENERIC_ERROR,
10118 _("TLS not supported or disabled on this target"));
38691318
KB
10119 /* Not reached. */
10120 return 0;
10121}
10122
711e434b
PM
10123/* Provide thread local base, i.e. Thread Information Block address.
10124 Returns 1 if ptid is found and thread_local_base is non zero. */
10125
70221824 10126static int
bd7ae0f5 10127remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
711e434b 10128{
4082afcc 10129 if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
711e434b
PM
10130 {
10131 struct remote_state *rs = get_remote_state ();
10132 char *p = rs->buf;
10133 char *endp = rs->buf + get_remote_packet_size ();
10134 enum packet_result result;
10135
10136 strcpy (p, "qGetTIBAddr:");
10137 p += strlen (p);
10138 p = write_ptid (p, endp, ptid);
10139 *p++ = '\0';
10140
10141 putpkt (rs->buf);
10142 getpkt (&rs->buf, &rs->buf_size, 0);
10143 result = packet_ok (rs->buf,
10144 &remote_protocol_packets[PACKET_qGetTIBAddr]);
10145 if (result == PACKET_OK)
10146 {
10147 ULONGEST result;
10148
10149 unpack_varlen_hex (rs->buf, &result);
10150 if (addr)
10151 *addr = (CORE_ADDR) result;
10152 return 1;
10153 }
10154 else if (result == PACKET_UNKNOWN)
10155 error (_("Remote target doesn't support qGetTIBAddr packet"));
10156 else
10157 error (_("Remote target failed to process qGetTIBAddr request"));
10158 }
10159 else
10160 error (_("qGetTIBAddr not supported or disabled on this target"));
10161 /* Not reached. */
10162 return 0;
10163}
10164
29709017
DJ
10165/* Support for inferring a target description based on the current
10166 architecture and the size of a 'g' packet. While the 'g' packet
10167 can have any size (since optional registers can be left off the
10168 end), some sizes are easily recognizable given knowledge of the
10169 approximate architecture. */
10170
10171struct remote_g_packet_guess
10172{
10173 int bytes;
10174 const struct target_desc *tdesc;
10175};
10176typedef struct remote_g_packet_guess remote_g_packet_guess_s;
10177DEF_VEC_O(remote_g_packet_guess_s);
10178
10179struct remote_g_packet_data
10180{
10181 VEC(remote_g_packet_guess_s) *guesses;
10182};
10183
10184static struct gdbarch_data *remote_g_packet_data_handle;
10185
10186static void *
10187remote_g_packet_data_init (struct obstack *obstack)
10188{
10189 return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
10190}
10191
10192void
10193register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
10194 const struct target_desc *tdesc)
10195{
10196 struct remote_g_packet_data *data
10197 = gdbarch_data (gdbarch, remote_g_packet_data_handle);
10198 struct remote_g_packet_guess new_guess, *guess;
10199 int ix;
10200
10201 gdb_assert (tdesc != NULL);
10202
10203 for (ix = 0;
10204 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10205 ix++)
10206 if (guess->bytes == bytes)
10207 internal_error (__FILE__, __LINE__,
9b20d036 10208 _("Duplicate g packet description added for size %d"),
29709017
DJ
10209 bytes);
10210
10211 new_guess.bytes = bytes;
10212 new_guess.tdesc = tdesc;
10213 VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
10214}
10215
d962ef82
DJ
10216/* Return 1 if remote_read_description would do anything on this target
10217 and architecture, 0 otherwise. */
10218
10219static int
10220remote_read_description_p (struct target_ops *target)
10221{
10222 struct remote_g_packet_data *data
f5656ead 10223 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
d962ef82
DJ
10224
10225 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10226 return 1;
10227
10228 return 0;
10229}
10230
29709017
DJ
10231static const struct target_desc *
10232remote_read_description (struct target_ops *target)
10233{
10234 struct remote_g_packet_data *data
f5656ead 10235 = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
29709017 10236
d962ef82
DJ
10237 /* Do not try this during initial connection, when we do not know
10238 whether there is a running but stopped thread. */
10239 if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
2117c711 10240 return target->beneath->to_read_description (target->beneath);
d962ef82 10241
29709017
DJ
10242 if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
10243 {
10244 struct remote_g_packet_guess *guess;
10245 int ix;
10246 int bytes = send_g_packet ();
10247
10248 for (ix = 0;
10249 VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10250 ix++)
10251 if (guess->bytes == bytes)
10252 return guess->tdesc;
10253
10254 /* We discard the g packet. A minor optimization would be to
10255 hold on to it, and fill the register cache once we have selected
10256 an architecture, but it's too tricky to do safely. */
10257 }
10258
2117c711 10259 return target->beneath->to_read_description (target->beneath);
29709017
DJ
10260}
10261
a6b151f1
DJ
10262/* Remote file transfer support. This is host-initiated I/O, not
10263 target-initiated; for target-initiated, see remote-fileio.c. */
10264
10265/* If *LEFT is at least the length of STRING, copy STRING to
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_string (char **buffer, int *left, char *string)
10271{
10272 int len = strlen (string);
10273
10274 if (len > *left)
10275 error (_("Packet too long for target."));
10276
10277 memcpy (*buffer, string, len);
10278 *buffer += len;
10279 *left -= len;
10280
10281 /* NUL-terminate the buffer as a convenience, if there is
10282 room. */
10283 if (*left)
10284 **buffer = '\0';
10285}
10286
10287/* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10288 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10289 decrease *LEFT. Otherwise raise an error. */
10290
10291static void
10292remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10293 int len)
10294{
10295 if (2 * len > *left)
10296 error (_("Packet too long for target."));
10297
10298 bin2hex (bytes, *buffer, len);
10299 *buffer += 2 * len;
10300 *left -= 2 * len;
10301
10302 /* NUL-terminate the buffer as a convenience, if there is
10303 room. */
10304 if (*left)
10305 **buffer = '\0';
10306}
10307
10308/* If *LEFT is large enough, convert VALUE to hex and add it to
10309 *BUFFER, update *BUFFER to point to the new end of the buffer, and
10310 decrease *LEFT. Otherwise raise an error. */
10311
10312static void
10313remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10314{
10315 int len = hexnumlen (value);
10316
10317 if (len > *left)
10318 error (_("Packet too long for target."));
10319
10320 hexnumstr (*buffer, value);
10321 *buffer += len;
10322 *left -= len;
10323
10324 /* NUL-terminate the buffer as a convenience, if there is
10325 room. */
10326 if (*left)
10327 **buffer = '\0';
10328}
10329
10330/* Parse an I/O result packet from BUFFER. Set RETCODE to the return
10331 value, *REMOTE_ERRNO to the remote error number or zero if none
10332 was included, and *ATTACHMENT to point to the start of the annex
10333 if any. The length of the packet isn't needed here; there may
10334 be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10335
10336 Return 0 if the packet could be parsed, -1 if it could not. If
10337 -1 is returned, the other variables may not be initialized. */
10338
10339static int
10340remote_hostio_parse_result (char *buffer, int *retcode,
10341 int *remote_errno, char **attachment)
10342{
10343 char *p, *p2;
10344
10345 *remote_errno = 0;
10346 *attachment = NULL;
10347
10348 if (buffer[0] != 'F')
10349 return -1;
10350
10351 errno = 0;
10352 *retcode = strtol (&buffer[1], &p, 16);
10353 if (errno != 0 || p == &buffer[1])
10354 return -1;
10355
10356 /* Check for ",errno". */
10357 if (*p == ',')
10358 {
10359 errno = 0;
10360 *remote_errno = strtol (p + 1, &p2, 16);
10361 if (errno != 0 || p + 1 == p2)
10362 return -1;
10363 p = p2;
10364 }
10365
10366 /* Check for ";attachment". If there is no attachment, the
10367 packet should end here. */
10368 if (*p == ';')
10369 {
10370 *attachment = p + 1;
10371 return 0;
10372 }
10373 else if (*p == '\0')
10374 return 0;
10375 else
10376 return -1;
10377}
10378
10379/* Send a prepared I/O packet to the target and read its response.
10380 The prepared packet is in the global RS->BUF before this function
10381 is called, and the answer is there when we return.
10382
10383 COMMAND_BYTES is the length of the request to send, which may include
10384 binary data. WHICH_PACKET is the packet configuration to check
10385 before attempting a packet. If an error occurs, *REMOTE_ERRNO
10386 is set to the error number and -1 is returned. Otherwise the value
10387 returned by the function is returned.
10388
10389 ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10390 attachment is expected; an error will be reported if there's a
10391 mismatch. If one is found, *ATTACHMENT will be set to point into
10392 the packet buffer and *ATTACHMENT_LEN will be set to the
10393 attachment's length. */
10394
10395static int
10396remote_hostio_send_command (int command_bytes, int which_packet,
10397 int *remote_errno, char **attachment,
10398 int *attachment_len)
10399{
10400 struct remote_state *rs = get_remote_state ();
10401 int ret, bytes_read;
10402 char *attachment_tmp;
10403
5d93a237 10404 if (!rs->remote_desc
4082afcc 10405 || packet_support (which_packet) == PACKET_DISABLE)
a6b151f1
DJ
10406 {
10407 *remote_errno = FILEIO_ENOSYS;
10408 return -1;
10409 }
10410
10411 putpkt_binary (rs->buf, command_bytes);
10412 bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10413
10414 /* If it timed out, something is wrong. Don't try to parse the
10415 buffer. */
10416 if (bytes_read < 0)
10417 {
10418 *remote_errno = FILEIO_EINVAL;
10419 return -1;
10420 }
10421
10422 switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10423 {
10424 case PACKET_ERROR:
10425 *remote_errno = FILEIO_EINVAL;
10426 return -1;
10427 case PACKET_UNKNOWN:
10428 *remote_errno = FILEIO_ENOSYS;
10429 return -1;
10430 case PACKET_OK:
10431 break;
10432 }
10433
10434 if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10435 &attachment_tmp))
10436 {
10437 *remote_errno = FILEIO_EINVAL;
10438 return -1;
10439 }
10440
10441 /* Make sure we saw an attachment if and only if we expected one. */
10442 if ((attachment_tmp == NULL && attachment != NULL)
10443 || (attachment_tmp != NULL && attachment == NULL))
10444 {
10445 *remote_errno = FILEIO_EINVAL;
10446 return -1;
10447 }
10448
10449 /* If an attachment was found, it must point into the packet buffer;
10450 work out how many bytes there were. */
10451 if (attachment_tmp != NULL)
10452 {
10453 *attachment = attachment_tmp;
10454 *attachment_len = bytes_read - (*attachment - rs->buf);
10455 }
10456
10457 return ret;
10458}
10459
80152258
PA
10460/* Invalidate the readahead cache. */
10461
10462static void
10463readahead_cache_invalidate (void)
10464{
10465 struct remote_state *rs = get_remote_state ();
10466
10467 rs->readahead_cache.fd = -1;
10468}
10469
10470/* Invalidate the readahead cache if it is holding data for FD. */
10471
10472static void
10473readahead_cache_invalidate_fd (int fd)
10474{
10475 struct remote_state *rs = get_remote_state ();
10476
10477 if (rs->readahead_cache.fd == fd)
10478 rs->readahead_cache.fd = -1;
10479}
10480
15a201c8
GB
10481/* Set the filesystem remote_hostio functions that take FILENAME
10482 arguments will use. Return 0 on success, or -1 if an error
10483 occurs (and set *REMOTE_ERRNO). */
10484
10485static int
10486remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
10487{
10488 struct remote_state *rs = get_remote_state ();
10489 int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
10490 char *p = rs->buf;
10491 int left = get_remote_packet_size () - 1;
10492 char arg[9];
10493 int ret;
10494
10495 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10496 return 0;
10497
10498 if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
10499 return 0;
10500
10501 remote_buffer_add_string (&p, &left, "vFile:setfs:");
10502
10503 xsnprintf (arg, sizeof (arg), "%x", required_pid);
10504 remote_buffer_add_string (&p, &left, arg);
10505
10506 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
10507 remote_errno, NULL, NULL);
10508
10509 if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
10510 return 0;
10511
10512 if (ret == 0)
10513 rs->fs_pid = required_pid;
10514
10515 return ret;
10516}
10517
12e2a5fd 10518/* Implementation of to_fileio_open. */
a6b151f1
DJ
10519
10520static int
cd897586 10521remote_hostio_open (struct target_ops *self,
07c138c8 10522 struct inferior *inf, const char *filename,
4313b8c0
GB
10523 int flags, int mode, int warn_if_slow,
10524 int *remote_errno)
a6b151f1
DJ
10525{
10526 struct remote_state *rs = get_remote_state ();
10527 char *p = rs->buf;
10528 int left = get_remote_packet_size () - 1;
10529
4313b8c0
GB
10530 if (warn_if_slow)
10531 {
10532 static int warning_issued = 0;
10533
10534 printf_unfiltered (_("Reading %s from remote target...\n"),
10535 filename);
10536
10537 if (!warning_issued)
10538 {
10539 warning (_("File transfers from remote targets can be slow."
10540 " Use \"set sysroot\" to access files locally"
10541 " instead."));
10542 warning_issued = 1;
10543 }
10544 }
10545
15a201c8
GB
10546 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10547 return -1;
10548
a6b151f1
DJ
10549 remote_buffer_add_string (&p, &left, "vFile:open:");
10550
10551 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10552 strlen (filename));
10553 remote_buffer_add_string (&p, &left, ",");
10554
10555 remote_buffer_add_int (&p, &left, flags);
10556 remote_buffer_add_string (&p, &left, ",");
10557
10558 remote_buffer_add_int (&p, &left, mode);
10559
10560 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10561 remote_errno, NULL, NULL);
10562}
10563
12e2a5fd 10564/* Implementation of to_fileio_pwrite. */
a6b151f1
DJ
10565
10566static int
0d866f62
TT
10567remote_hostio_pwrite (struct target_ops *self,
10568 int fd, const gdb_byte *write_buf, int len,
a6b151f1
DJ
10569 ULONGEST offset, int *remote_errno)
10570{
10571 struct remote_state *rs = get_remote_state ();
10572 char *p = rs->buf;
10573 int left = get_remote_packet_size ();
10574 int out_len;
10575
80152258
PA
10576 readahead_cache_invalidate_fd (fd);
10577
a6b151f1
DJ
10578 remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10579
10580 remote_buffer_add_int (&p, &left, fd);
10581 remote_buffer_add_string (&p, &left, ",");
10582
10583 remote_buffer_add_int (&p, &left, offset);
10584 remote_buffer_add_string (&p, &left, ",");
10585
124e13d9 10586 p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
a6b151f1
DJ
10587 get_remote_packet_size () - (p - rs->buf));
10588
10589 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10590 remote_errno, NULL, NULL);
10591}
10592
80152258
PA
10593/* Helper for the implementation of to_fileio_pread. Read the file
10594 from the remote side with vFile:pread. */
a6b151f1
DJ
10595
10596static int
80152258
PA
10597remote_hostio_pread_vFile (struct target_ops *self,
10598 int fd, gdb_byte *read_buf, int len,
10599 ULONGEST offset, int *remote_errno)
a6b151f1
DJ
10600{
10601 struct remote_state *rs = get_remote_state ();
10602 char *p = rs->buf;
10603 char *attachment;
10604 int left = get_remote_packet_size ();
10605 int ret, attachment_len;
10606 int read_len;
10607
10608 remote_buffer_add_string (&p, &left, "vFile:pread:");
10609
10610 remote_buffer_add_int (&p, &left, fd);
10611 remote_buffer_add_string (&p, &left, ",");
10612
10613 remote_buffer_add_int (&p, &left, len);
10614 remote_buffer_add_string (&p, &left, ",");
10615
10616 remote_buffer_add_int (&p, &left, offset);
10617
10618 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10619 remote_errno, &attachment,
10620 &attachment_len);
10621
10622 if (ret < 0)
10623 return ret;
10624
bc20a4af 10625 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
a6b151f1
DJ
10626 read_buf, len);
10627 if (read_len != ret)
10628 error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10629
10630 return ret;
10631}
10632
80152258
PA
10633/* Serve pread from the readahead cache. Returns number of bytes
10634 read, or 0 if the request can't be served from the cache. */
10635
10636static int
10637remote_hostio_pread_from_cache (struct remote_state *rs,
10638 int fd, gdb_byte *read_buf, size_t len,
10639 ULONGEST offset)
10640{
10641 struct readahead_cache *cache = &rs->readahead_cache;
10642
10643 if (cache->fd == fd
10644 && cache->offset <= offset
10645 && offset < cache->offset + cache->bufsize)
10646 {
10647 ULONGEST max = cache->offset + cache->bufsize;
10648
10649 if (offset + len > max)
10650 len = max - offset;
10651
10652 memcpy (read_buf, cache->buf + offset - cache->offset, len);
10653 return len;
10654 }
10655
10656 return 0;
10657}
10658
10659/* Implementation of to_fileio_pread. */
10660
10661static int
10662remote_hostio_pread (struct target_ops *self,
10663 int fd, gdb_byte *read_buf, int len,
10664 ULONGEST offset, int *remote_errno)
10665{
10666 int ret;
10667 struct remote_state *rs = get_remote_state ();
10668 struct readahead_cache *cache = &rs->readahead_cache;
10669
10670 ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10671 if (ret > 0)
10672 {
10673 cache->hit_count++;
10674
10675 if (remote_debug)
10676 fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
10677 pulongest (cache->hit_count));
10678 return ret;
10679 }
10680
10681 cache->miss_count++;
10682 if (remote_debug)
10683 fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
10684 pulongest (cache->miss_count));
10685
10686 cache->fd = fd;
10687 cache->offset = offset;
10688 cache->bufsize = get_remote_packet_size ();
10689 cache->buf = xrealloc (cache->buf, cache->bufsize);
10690
10691 ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
10692 cache->offset, remote_errno);
10693 if (ret <= 0)
10694 {
10695 readahead_cache_invalidate_fd (fd);
10696 return ret;
10697 }
10698
10699 cache->bufsize = ret;
10700 return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
10701}
10702
12e2a5fd 10703/* Implementation of to_fileio_close. */
a6b151f1
DJ
10704
10705static int
df39ea25 10706remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
a6b151f1
DJ
10707{
10708 struct remote_state *rs = get_remote_state ();
10709 char *p = rs->buf;
10710 int left = get_remote_packet_size () - 1;
10711
80152258
PA
10712 readahead_cache_invalidate_fd (fd);
10713
a6b151f1
DJ
10714 remote_buffer_add_string (&p, &left, "vFile:close:");
10715
10716 remote_buffer_add_int (&p, &left, fd);
10717
10718 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10719 remote_errno, NULL, NULL);
10720}
10721
12e2a5fd 10722/* Implementation of to_fileio_unlink. */
a6b151f1
DJ
10723
10724static int
dbbca37d 10725remote_hostio_unlink (struct target_ops *self,
07c138c8
GB
10726 struct inferior *inf, const char *filename,
10727 int *remote_errno)
a6b151f1
DJ
10728{
10729 struct remote_state *rs = get_remote_state ();
10730 char *p = rs->buf;
10731 int left = get_remote_packet_size () - 1;
10732
15a201c8
GB
10733 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10734 return -1;
10735
a6b151f1
DJ
10736 remote_buffer_add_string (&p, &left, "vFile:unlink:");
10737
10738 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10739 strlen (filename));
10740
10741 return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10742 remote_errno, NULL, NULL);
10743}
10744
12e2a5fd 10745/* Implementation of to_fileio_readlink. */
b9e7b9c3
UW
10746
10747static char *
fab5aa7c 10748remote_hostio_readlink (struct target_ops *self,
07c138c8
GB
10749 struct inferior *inf, const char *filename,
10750 int *remote_errno)
b9e7b9c3
UW
10751{
10752 struct remote_state *rs = get_remote_state ();
10753 char *p = rs->buf;
10754 char *attachment;
10755 int left = get_remote_packet_size ();
10756 int len, attachment_len;
10757 int read_len;
10758 char *ret;
10759
15a201c8
GB
10760 if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
10761 return NULL;
10762
b9e7b9c3
UW
10763 remote_buffer_add_string (&p, &left, "vFile:readlink:");
10764
10765 remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10766 strlen (filename));
10767
10768 len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10769 remote_errno, &attachment,
10770 &attachment_len);
10771
10772 if (len < 0)
10773 return NULL;
10774
10775 ret = xmalloc (len + 1);
10776
bc20a4af
PA
10777 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10778 (gdb_byte *) ret, len);
b9e7b9c3
UW
10779 if (read_len != len)
10780 error (_("Readlink returned %d, but %d bytes."), len, read_len);
10781
10782 ret[len] = '\0';
10783 return ret;
10784}
10785
12e2a5fd 10786/* Implementation of to_fileio_fstat. */
0a93529c
GB
10787
10788static int
10789remote_hostio_fstat (struct target_ops *self,
10790 int fd, struct stat *st,
10791 int *remote_errno)
10792{
10793 struct remote_state *rs = get_remote_state ();
10794 char *p = rs->buf;
10795 int left = get_remote_packet_size ();
10796 int attachment_len, ret;
10797 char *attachment;
10798 struct fio_stat fst;
10799 int read_len;
10800
464b0089
GB
10801 remote_buffer_add_string (&p, &left, "vFile:fstat:");
10802
10803 remote_buffer_add_int (&p, &left, fd);
10804
10805 ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10806 remote_errno, &attachment,
10807 &attachment_len);
10808 if (ret < 0)
0a93529c 10809 {
464b0089
GB
10810 if (*remote_errno != FILEIO_ENOSYS)
10811 return ret;
10812
0a93529c
GB
10813 /* Strictly we should return -1, ENOSYS here, but when
10814 "set sysroot remote:" was implemented in August 2008
10815 BFD's need for a stat function was sidestepped with
10816 this hack. This was not remedied until March 2015
10817 so we retain the previous behavior to avoid breaking
10818 compatibility.
10819
10820 Note that the memset is a March 2015 addition; older
10821 GDBs set st_size *and nothing else* so the structure
10822 would have garbage in all other fields. This might
10823 break something but retaining the previous behavior
10824 here would be just too wrong. */
10825
10826 memset (st, 0, sizeof (struct stat));
10827 st->st_size = INT_MAX;
10828 return 0;
10829 }
10830
0a93529c
GB
10831 read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10832 (gdb_byte *) &fst, sizeof (fst));
10833
10834 if (read_len != ret)
10835 error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10836
10837 if (read_len != sizeof (fst))
10838 error (_("vFile:fstat returned %d bytes, but expecting %d."),
10839 read_len, (int) sizeof (fst));
10840
10841 remote_fileio_to_host_stat (&fst, st);
10842
10843 return 0;
10844}
10845
12e2a5fd 10846/* Implementation of to_filesystem_is_local. */
e3dd7556
GB
10847
10848static int
10849remote_filesystem_is_local (struct target_ops *self)
10850{
10851 /* Valgrind GDB presents itself as a remote target but works
10852 on the local filesystem: it does not implement remote get
10853 and users are not expected to set a sysroot. To handle
10854 this case we treat the remote filesystem as local if the
10855 sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
10856 does not support vFile:open. */
a3be80c3 10857 if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
e3dd7556
GB
10858 {
10859 enum packet_support ps = packet_support (PACKET_vFile_open);
10860
10861 if (ps == PACKET_SUPPORT_UNKNOWN)
10862 {
10863 int fd, remote_errno;
10864
10865 /* Try opening a file to probe support. The supplied
10866 filename is irrelevant, we only care about whether
10867 the stub recognizes the packet or not. */
07c138c8 10868 fd = remote_hostio_open (self, NULL, "just probing",
4313b8c0 10869 FILEIO_O_RDONLY, 0700, 0,
e3dd7556
GB
10870 &remote_errno);
10871
10872 if (fd >= 0)
10873 remote_hostio_close (self, fd, &remote_errno);
10874
10875 ps = packet_support (PACKET_vFile_open);
10876 }
10877
10878 if (ps == PACKET_DISABLE)
10879 {
10880 static int warning_issued = 0;
10881
10882 if (!warning_issued)
10883 {
10884 warning (_("remote target does not support file"
10885 " transfer, attempting to access files"
10886 " from local filesystem."));
10887 warning_issued = 1;
10888 }
10889
10890 return 1;
10891 }
10892 }
10893
10894 return 0;
10895}
10896
a6b151f1
DJ
10897static int
10898remote_fileio_errno_to_host (int errnum)
10899{
10900 switch (errnum)
10901 {
10902 case FILEIO_EPERM:
10903 return EPERM;
10904 case FILEIO_ENOENT:
10905 return ENOENT;
10906 case FILEIO_EINTR:
10907 return EINTR;
10908 case FILEIO_EIO:
10909 return EIO;
10910 case FILEIO_EBADF:
10911 return EBADF;
10912 case FILEIO_EACCES:
10913 return EACCES;
10914 case FILEIO_EFAULT:
10915 return EFAULT;
10916 case FILEIO_EBUSY:
10917 return EBUSY;
10918 case FILEIO_EEXIST:
10919 return EEXIST;
10920 case FILEIO_ENODEV:
10921 return ENODEV;
10922 case FILEIO_ENOTDIR:
10923 return ENOTDIR;
10924 case FILEIO_EISDIR:
10925 return EISDIR;
10926 case FILEIO_EINVAL:
10927 return EINVAL;
10928 case FILEIO_ENFILE:
10929 return ENFILE;
10930 case FILEIO_EMFILE:
10931 return EMFILE;
10932 case FILEIO_EFBIG:
10933 return EFBIG;
10934 case FILEIO_ENOSPC:
10935 return ENOSPC;
10936 case FILEIO_ESPIPE:
10937 return ESPIPE;
10938 case FILEIO_EROFS:
10939 return EROFS;
10940 case FILEIO_ENOSYS:
10941 return ENOSYS;
10942 case FILEIO_ENAMETOOLONG:
10943 return ENAMETOOLONG;
10944 }
10945 return -1;
10946}
10947
10948static char *
10949remote_hostio_error (int errnum)
10950{
10951 int host_error = remote_fileio_errno_to_host (errnum);
10952
10953 if (host_error == -1)
10954 error (_("Unknown remote I/O error %d"), errnum);
10955 else
10956 error (_("Remote I/O error: %s"), safe_strerror (host_error));
10957}
10958
a6b151f1
DJ
10959static void
10960remote_hostio_close_cleanup (void *opaque)
10961{
10962 int fd = *(int *) opaque;
10963 int remote_errno;
10964
df39ea25 10965 remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
a6b151f1
DJ
10966}
10967
10968void
10969remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10970{
10971 struct cleanup *back_to, *close_cleanup;
10972 int retcode, fd, remote_errno, bytes, io_size;
10973 FILE *file;
10974 gdb_byte *buffer;
10975 int bytes_in_buffer;
10976 int saw_eof;
10977 ULONGEST offset;
5d93a237 10978 struct remote_state *rs = get_remote_state ();
a6b151f1 10979
5d93a237 10980 if (!rs->remote_desc)
a6b151f1
DJ
10981 error (_("command can only be used with remote target"));
10982
614c279d 10983 file = gdb_fopen_cloexec (local_file, "rb");
a6b151f1
DJ
10984 if (file == NULL)
10985 perror_with_name (local_file);
7c8a8b04 10986 back_to = make_cleanup_fclose (file);
a6b151f1 10987
07c138c8 10988 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
cd897586 10989 remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
a6b151f1 10990 | FILEIO_O_TRUNC),
4313b8c0 10991 0700, 0, &remote_errno);
a6b151f1
DJ
10992 if (fd == -1)
10993 remote_hostio_error (remote_errno);
10994
10995 /* Send up to this many bytes at once. They won't all fit in the
10996 remote packet limit, so we'll transfer slightly fewer. */
10997 io_size = get_remote_packet_size ();
10998 buffer = xmalloc (io_size);
10999 make_cleanup (xfree, buffer);
11000
11001 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11002
11003 bytes_in_buffer = 0;
11004 saw_eof = 0;
11005 offset = 0;
11006 while (bytes_in_buffer || !saw_eof)
11007 {
11008 if (!saw_eof)
11009 {
3e43a32a
MS
11010 bytes = fread (buffer + bytes_in_buffer, 1,
11011 io_size - bytes_in_buffer,
a6b151f1
DJ
11012 file);
11013 if (bytes == 0)
11014 {
11015 if (ferror (file))
11016 error (_("Error reading %s."), local_file);
11017 else
11018 {
11019 /* EOF. Unless there is something still in the
11020 buffer from the last iteration, we are done. */
11021 saw_eof = 1;
11022 if (bytes_in_buffer == 0)
11023 break;
11024 }
11025 }
11026 }
11027 else
11028 bytes = 0;
11029
11030 bytes += bytes_in_buffer;
11031 bytes_in_buffer = 0;
11032
0d866f62
TT
11033 retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11034 fd, buffer, bytes,
3e43a32a 11035 offset, &remote_errno);
a6b151f1
DJ
11036
11037 if (retcode < 0)
11038 remote_hostio_error (remote_errno);
11039 else if (retcode == 0)
11040 error (_("Remote write of %d bytes returned 0!"), bytes);
11041 else if (retcode < bytes)
11042 {
11043 /* Short write. Save the rest of the read data for the next
11044 write. */
11045 bytes_in_buffer = bytes - retcode;
11046 memmove (buffer, buffer + retcode, bytes_in_buffer);
11047 }
11048
11049 offset += retcode;
11050 }
11051
11052 discard_cleanups (close_cleanup);
df39ea25 11053 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11054 remote_hostio_error (remote_errno);
11055
11056 if (from_tty)
11057 printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
11058 do_cleanups (back_to);
11059}
11060
11061void
11062remote_file_get (const char *remote_file, const char *local_file, int from_tty)
11063{
11064 struct cleanup *back_to, *close_cleanup;
cea39f65 11065 int fd, remote_errno, bytes, io_size;
a6b151f1
DJ
11066 FILE *file;
11067 gdb_byte *buffer;
11068 ULONGEST offset;
5d93a237 11069 struct remote_state *rs = get_remote_state ();
a6b151f1 11070
5d93a237 11071 if (!rs->remote_desc)
a6b151f1
DJ
11072 error (_("command can only be used with remote target"));
11073
07c138c8 11074 fd = remote_hostio_open (find_target_at (process_stratum), NULL,
4313b8c0
GB
11075 remote_file, FILEIO_O_RDONLY, 0, 0,
11076 &remote_errno);
a6b151f1
DJ
11077 if (fd == -1)
11078 remote_hostio_error (remote_errno);
11079
614c279d 11080 file = gdb_fopen_cloexec (local_file, "wb");
a6b151f1
DJ
11081 if (file == NULL)
11082 perror_with_name (local_file);
7c8a8b04 11083 back_to = make_cleanup_fclose (file);
a6b151f1
DJ
11084
11085 /* Send up to this many bytes at once. They won't all fit in the
11086 remote packet limit, so we'll transfer slightly fewer. */
11087 io_size = get_remote_packet_size ();
11088 buffer = xmalloc (io_size);
11089 make_cleanup (xfree, buffer);
11090
11091 close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11092
11093 offset = 0;
11094 while (1)
11095 {
a3be983c
TT
11096 bytes = remote_hostio_pread (find_target_at (process_stratum),
11097 fd, buffer, io_size, offset, &remote_errno);
a6b151f1
DJ
11098 if (bytes == 0)
11099 /* Success, but no bytes, means end-of-file. */
11100 break;
11101 if (bytes == -1)
11102 remote_hostio_error (remote_errno);
11103
11104 offset += bytes;
11105
11106 bytes = fwrite (buffer, 1, bytes, file);
11107 if (bytes == 0)
11108 perror_with_name (local_file);
11109 }
11110
11111 discard_cleanups (close_cleanup);
df39ea25 11112 if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
a6b151f1
DJ
11113 remote_hostio_error (remote_errno);
11114
11115 if (from_tty)
11116 printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
11117 do_cleanups (back_to);
11118}
11119
11120void
11121remote_file_delete (const char *remote_file, int from_tty)
11122{
11123 int retcode, remote_errno;
5d93a237 11124 struct remote_state *rs = get_remote_state ();
a6b151f1 11125
5d93a237 11126 if (!rs->remote_desc)
a6b151f1
DJ
11127 error (_("command can only be used with remote target"));
11128
dbbca37d 11129 retcode = remote_hostio_unlink (find_target_at (process_stratum),
07c138c8 11130 NULL, remote_file, &remote_errno);
a6b151f1
DJ
11131 if (retcode == -1)
11132 remote_hostio_error (remote_errno);
11133
11134 if (from_tty)
11135 printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
11136}
11137
11138static void
11139remote_put_command (char *args, int from_tty)
11140{
11141 struct cleanup *back_to;
11142 char **argv;
11143
d1a41061
PP
11144 if (args == NULL)
11145 error_no_arg (_("file to put"));
11146
11147 argv = gdb_buildargv (args);
a6b151f1
DJ
11148 back_to = make_cleanup_freeargv (argv);
11149 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11150 error (_("Invalid parameters to remote put"));
11151
11152 remote_file_put (argv[0], argv[1], from_tty);
11153
11154 do_cleanups (back_to);
11155}
11156
11157static void
11158remote_get_command (char *args, int from_tty)
11159{
11160 struct cleanup *back_to;
11161 char **argv;
11162
d1a41061
PP
11163 if (args == NULL)
11164 error_no_arg (_("file to get"));
11165
11166 argv = gdb_buildargv (args);
a6b151f1
DJ
11167 back_to = make_cleanup_freeargv (argv);
11168 if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
11169 error (_("Invalid parameters to remote get"));
11170
11171 remote_file_get (argv[0], argv[1], from_tty);
11172
11173 do_cleanups (back_to);
11174}
11175
11176static void
11177remote_delete_command (char *args, int from_tty)
11178{
11179 struct cleanup *back_to;
11180 char **argv;
11181
d1a41061
PP
11182 if (args == NULL)
11183 error_no_arg (_("file to delete"));
11184
11185 argv = gdb_buildargv (args);
a6b151f1
DJ
11186 back_to = make_cleanup_freeargv (argv);
11187 if (argv[0] == NULL || argv[1] != NULL)
11188 error (_("Invalid parameters to remote delete"));
11189
11190 remote_file_delete (argv[0], from_tty);
11191
11192 do_cleanups (back_to);
11193}
11194
11195static void
11196remote_command (char *args, int from_tty)
11197{
635c7e8a 11198 help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
a6b151f1
DJ
11199}
11200
b2175913 11201static int
19db3e69 11202remote_can_execute_reverse (struct target_ops *self)
b2175913 11203{
4082afcc
PA
11204 if (packet_support (PACKET_bs) == PACKET_ENABLE
11205 || packet_support (PACKET_bc) == PACKET_ENABLE)
40ab02ce
MS
11206 return 1;
11207 else
11208 return 0;
b2175913
MS
11209}
11210
74531fed 11211static int
2a9a2795 11212remote_supports_non_stop (struct target_ops *self)
74531fed
PA
11213{
11214 return 1;
11215}
11216
03583c20 11217static int
2bfc0540 11218remote_supports_disable_randomization (struct target_ops *self)
03583c20
UW
11219{
11220 /* Only supported in extended mode. */
11221 return 0;
11222}
11223
8a305172 11224static int
86ce2668 11225remote_supports_multi_process (struct target_ops *self)
8a305172
PA
11226{
11227 struct remote_state *rs = get_remote_state ();
a744cf53 11228
901f9912
UW
11229 /* Only extended-remote handles being attached to multiple
11230 processes, even though plain remote can use the multi-process
11231 thread id extensions, so that GDB knows the target process's
11232 PID. */
11233 return rs->extended && remote_multi_process_p (rs);
8a305172
PA
11234}
11235
70221824 11236static int
782b2b07
SS
11237remote_supports_cond_tracepoints (void)
11238{
4082afcc 11239 return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
782b2b07
SS
11240}
11241
3788aec7 11242static int
efcc2da7 11243remote_supports_cond_breakpoints (struct target_ops *self)
3788aec7 11244{
4082afcc 11245 return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
3788aec7
LM
11246}
11247
70221824 11248static int
7a697b8d
SS
11249remote_supports_fast_tracepoints (void)
11250{
4082afcc 11251 return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
7a697b8d
SS
11252}
11253
0fb4aa4b
PA
11254static int
11255remote_supports_static_tracepoints (void)
11256{
4082afcc 11257 return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
0fb4aa4b
PA
11258}
11259
1e4d1764
YQ
11260static int
11261remote_supports_install_in_trace (void)
11262{
4082afcc 11263 return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
1e4d1764
YQ
11264}
11265
d248b706 11266static int
7d178d6a 11267remote_supports_enable_disable_tracepoint (struct target_ops *self)
d248b706 11268{
4082afcc
PA
11269 return (packet_support (PACKET_EnableDisableTracepoints_feature)
11270 == PACKET_ENABLE);
d248b706
KY
11271}
11272
3065dfb6 11273static int
6de37a3a 11274remote_supports_string_tracing (struct target_ops *self)
3065dfb6 11275{
4082afcc 11276 return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
3065dfb6
SS
11277}
11278
d3ce09f5 11279static int
78eff0ec 11280remote_can_run_breakpoint_commands (struct target_ops *self)
d3ce09f5 11281{
4082afcc 11282 return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
d3ce09f5
SS
11283}
11284
35b1e5cc 11285static void
ecae04e1 11286remote_trace_init (struct target_ops *self)
35b1e5cc
SS
11287{
11288 putpkt ("QTinit");
11289 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99 11290 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11291 error (_("Target does not support this command."));
11292}
11293
11294static void free_actions_list (char **actions_list);
11295static void free_actions_list_cleanup_wrapper (void *);
11296static void
11297free_actions_list_cleanup_wrapper (void *al)
11298{
11299 free_actions_list (al);
11300}
11301
11302static void
11303free_actions_list (char **actions_list)
11304{
11305 int ndx;
11306
11307 if (actions_list == 0)
11308 return;
11309
11310 for (ndx = 0; actions_list[ndx]; ndx++)
11311 xfree (actions_list[ndx]);
11312
11313 xfree (actions_list);
11314}
11315
409873ef
SS
11316/* Recursive routine to walk through command list including loops, and
11317 download packets for each command. */
11318
11319static void
11320remote_download_command_source (int num, ULONGEST addr,
11321 struct command_line *cmds)
11322{
11323 struct remote_state *rs = get_remote_state ();
11324 struct command_line *cmd;
11325
11326 for (cmd = cmds; cmd; cmd = cmd->next)
11327 {
0df8b418 11328 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11329 strcpy (rs->buf, "QTDPsrc:");
11330 encode_source_string (num, addr, "cmd", cmd->line,
11331 rs->buf + strlen (rs->buf),
11332 rs->buf_size - strlen (rs->buf));
11333 putpkt (rs->buf);
11334 remote_get_noisy_reply (&target_buf, &target_buf_size);
11335 if (strcmp (target_buf, "OK"))
11336 warning (_("Target does not support source download."));
11337
11338 if (cmd->control_type == while_control
11339 || cmd->control_type == while_stepping_control)
11340 {
11341 remote_download_command_source (num, addr, *cmd->body_list);
11342
0df8b418 11343 QUIT; /* Allow user to bail out with ^C. */
409873ef
SS
11344 strcpy (rs->buf, "QTDPsrc:");
11345 encode_source_string (num, addr, "cmd", "end",
11346 rs->buf + strlen (rs->buf),
11347 rs->buf_size - strlen (rs->buf));
11348 putpkt (rs->buf);
11349 remote_get_noisy_reply (&target_buf, &target_buf_size);
11350 if (strcmp (target_buf, "OK"))
11351 warning (_("Target does not support source download."));
11352 }
11353 }
11354}
11355
35b1e5cc 11356static void
548f7808 11357remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
35b1e5cc 11358{
bba74b36 11359#define BUF_SIZE 2048
e8ba3115 11360
35b1e5cc 11361 CORE_ADDR tpaddr;
409873ef 11362 char addrbuf[40];
bba74b36 11363 char buf[BUF_SIZE];
35b1e5cc
SS
11364 char **tdp_actions;
11365 char **stepping_actions;
11366 int ndx;
11367 struct cleanup *old_chain = NULL;
11368 struct agent_expr *aexpr;
11369 struct cleanup *aexpr_chain = NULL;
11370 char *pkt;
e8ba3115 11371 struct breakpoint *b = loc->owner;
d9b3f62e 11372 struct tracepoint *t = (struct tracepoint *) b;
35b1e5cc 11373
dc673c81 11374 encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
e8ba3115
YQ
11375 old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
11376 tdp_actions);
11377 (void) make_cleanup (free_actions_list_cleanup_wrapper,
11378 stepping_actions);
11379
11380 tpaddr = loc->address;
11381 sprintf_vma (addrbuf, tpaddr);
bba74b36
YQ
11382 xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
11383 addrbuf, /* address */
11384 (b->enable_state == bp_enabled ? 'E' : 'D'),
11385 t->step_count, t->pass_count);
e8ba3115
YQ
11386 /* Fast tracepoints are mostly handled by the target, but we can
11387 tell the target how big of an instruction block should be moved
11388 around. */
11389 if (b->type == bp_fast_tracepoint)
11390 {
11391 /* Only test for support at download time; we may not know
11392 target capabilities at definition time. */
11393 if (remote_supports_fast_tracepoints ())
35b1e5cc 11394 {
6b940e6a
PL
11395 if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
11396 NULL))
bba74b36 11397 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
6b940e6a 11398 gdb_insn_length (loc->gdbarch, tpaddr));
35b1e5cc 11399 else
e8ba3115
YQ
11400 /* If it passed validation at definition but fails now,
11401 something is very wrong. */
11402 internal_error (__FILE__, __LINE__,
11403 _("Fast tracepoint not "
11404 "valid during download"));
35b1e5cc 11405 }
e8ba3115
YQ
11406 else
11407 /* Fast tracepoints are functionally identical to regular
11408 tracepoints, so don't take lack of support as a reason to
11409 give up on the trace run. */
11410 warning (_("Target does not support fast tracepoints, "
11411 "downloading %d as regular tracepoint"), b->number);
11412 }
11413 else if (b->type == bp_static_tracepoint)
11414 {
11415 /* Only test for support at download time; we may not know
11416 target capabilities at definition time. */
11417 if (remote_supports_static_tracepoints ())
0fb4aa4b 11418 {
e8ba3115 11419 struct static_tracepoint_marker marker;
0fb4aa4b 11420
e8ba3115
YQ
11421 if (target_static_tracepoint_marker_at (tpaddr, &marker))
11422 strcat (buf, ":S");
0fb4aa4b 11423 else
e8ba3115 11424 error (_("Static tracepoint not valid during download"));
0fb4aa4b 11425 }
e8ba3115
YQ
11426 else
11427 /* Fast tracepoints are functionally identical to regular
11428 tracepoints, so don't take lack of support as a reason
11429 to give up on the trace run. */
11430 error (_("Target does not support static tracepoints"));
11431 }
11432 /* If the tracepoint has a conditional, make it into an agent
11433 expression and append to the definition. */
11434 if (loc->cond)
11435 {
11436 /* Only test support at download time, we may not know target
11437 capabilities at definition time. */
11438 if (remote_supports_cond_tracepoints ())
35b1e5cc 11439 {
e8ba3115
YQ
11440 aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11441 aexpr_chain = make_cleanup_free_agent_expr (aexpr);
bba74b36
YQ
11442 xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11443 aexpr->len);
e8ba3115
YQ
11444 pkt = buf + strlen (buf);
11445 for (ndx = 0; ndx < aexpr->len; ++ndx)
11446 pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11447 *pkt = '\0';
11448 do_cleanups (aexpr_chain);
35b1e5cc 11449 }
e8ba3115
YQ
11450 else
11451 warning (_("Target does not support conditional tracepoints, "
11452 "ignoring tp %d cond"), b->number);
11453 }
35b1e5cc 11454
d9b3f62e 11455 if (b->commands || *default_collect)
e8ba3115
YQ
11456 strcat (buf, "-");
11457 putpkt (buf);
11458 remote_get_noisy_reply (&target_buf, &target_buf_size);
11459 if (strcmp (target_buf, "OK"))
11460 error (_("Target does not support tracepoints."));
35b1e5cc 11461
e8ba3115
YQ
11462 /* do_single_steps (t); */
11463 if (tdp_actions)
11464 {
11465 for (ndx = 0; tdp_actions[ndx]; ndx++)
35b1e5cc 11466 {
e8ba3115 11467 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11468 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11469 b->number, addrbuf, /* address */
11470 tdp_actions[ndx],
11471 ((tdp_actions[ndx + 1] || stepping_actions)
11472 ? '-' : 0));
e8ba3115
YQ
11473 putpkt (buf);
11474 remote_get_noisy_reply (&target_buf,
11475 &target_buf_size);
11476 if (strcmp (target_buf, "OK"))
11477 error (_("Error on target while setting tracepoints."));
35b1e5cc 11478 }
e8ba3115
YQ
11479 }
11480 if (stepping_actions)
11481 {
11482 for (ndx = 0; stepping_actions[ndx]; ndx++)
35b1e5cc 11483 {
e8ba3115 11484 QUIT; /* Allow user to bail out with ^C. */
bba74b36
YQ
11485 xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11486 b->number, addrbuf, /* address */
11487 ((ndx == 0) ? "S" : ""),
11488 stepping_actions[ndx],
11489 (stepping_actions[ndx + 1] ? "-" : ""));
e8ba3115
YQ
11490 putpkt (buf);
11491 remote_get_noisy_reply (&target_buf,
11492 &target_buf_size);
11493 if (strcmp (target_buf, "OK"))
11494 error (_("Error on target while setting tracepoints."));
35b1e5cc 11495 }
e8ba3115 11496 }
409873ef 11497
4082afcc 11498 if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
e8ba3115 11499 {
f00aae0f 11500 if (b->location != NULL)
409873ef 11501 {
e8ba3115 11502 strcpy (buf, "QTDPsrc:");
f00aae0f
KS
11503 encode_source_string (b->number, loc->address, "at",
11504 event_location_to_string (b->location),
11505 buf + strlen (buf), 2048 - strlen (buf));
e8ba3115
YQ
11506 putpkt (buf);
11507 remote_get_noisy_reply (&target_buf, &target_buf_size);
11508 if (strcmp (target_buf, "OK"))
11509 warning (_("Target does not support source download."));
409873ef 11510 }
e8ba3115
YQ
11511 if (b->cond_string)
11512 {
11513 strcpy (buf, "QTDPsrc:");
11514 encode_source_string (b->number, loc->address,
11515 "cond", b->cond_string, buf + strlen (buf),
11516 2048 - strlen (buf));
11517 putpkt (buf);
11518 remote_get_noisy_reply (&target_buf, &target_buf_size);
11519 if (strcmp (target_buf, "OK"))
11520 warning (_("Target does not support source download."));
11521 }
11522 remote_download_command_source (b->number, loc->address,
11523 breakpoint_commands (b));
35b1e5cc 11524 }
e8ba3115
YQ
11525
11526 do_cleanups (old_chain);
35b1e5cc
SS
11527}
11528
1e4d1764 11529static int
a52a8357 11530remote_can_download_tracepoint (struct target_ops *self)
1e4d1764 11531{
1e51243a
PA
11532 struct remote_state *rs = get_remote_state ();
11533 struct trace_status *ts;
11534 int status;
11535
11536 /* Don't try to install tracepoints until we've relocated our
11537 symbols, and fetched and merged the target's tracepoint list with
11538 ours. */
11539 if (rs->starting_up)
11540 return 0;
11541
11542 ts = current_trace_status ();
8bd200f1 11543 status = remote_get_trace_status (self, ts);
1e4d1764
YQ
11544
11545 if (status == -1 || !ts->running_known || !ts->running)
11546 return 0;
11547
11548 /* If we are in a tracing experiment, but remote stub doesn't support
11549 installing tracepoint in trace, we have to return. */
11550 if (!remote_supports_install_in_trace ())
11551 return 0;
11552
11553 return 1;
11554}
11555
11556
35b1e5cc 11557static void
559d2b81
TT
11558remote_download_trace_state_variable (struct target_ops *self,
11559 struct trace_state_variable *tsv)
35b1e5cc
SS
11560{
11561 struct remote_state *rs = get_remote_state ();
00bf0b85 11562 char *p;
35b1e5cc 11563
bba74b36
YQ
11564 xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11565 tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11566 tsv->builtin);
00bf0b85
SS
11567 p = rs->buf + strlen (rs->buf);
11568 if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11569 error (_("Trace state variable name too long for tsv definition packet"));
9f1b45b0 11570 p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
00bf0b85 11571 *p++ = '\0';
35b1e5cc
SS
11572 putpkt (rs->buf);
11573 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11574 if (*target_buf == '\0')
11575 error (_("Target does not support this command."));
11576 if (strcmp (target_buf, "OK") != 0)
11577 error (_("Error on target while downloading trace state variable."));
35b1e5cc
SS
11578}
11579
d248b706 11580static void
46670d57
TT
11581remote_enable_tracepoint (struct target_ops *self,
11582 struct bp_location *location)
d248b706
KY
11583{
11584 struct remote_state *rs = get_remote_state ();
11585 char addr_buf[40];
11586
11587 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11588 xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11589 location->owner->number, addr_buf);
d248b706
KY
11590 putpkt (rs->buf);
11591 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11592 if (*rs->buf == '\0')
11593 error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11594 if (strcmp (rs->buf, "OK") != 0)
11595 error (_("Error on target while enabling tracepoint."));
11596}
11597
11598static void
780b049c
TT
11599remote_disable_tracepoint (struct target_ops *self,
11600 struct bp_location *location)
d248b706
KY
11601{
11602 struct remote_state *rs = get_remote_state ();
11603 char addr_buf[40];
11604
11605 sprintf_vma (addr_buf, location->address);
bba74b36
YQ
11606 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11607 location->owner->number, addr_buf);
d248b706
KY
11608 putpkt (rs->buf);
11609 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11610 if (*rs->buf == '\0')
11611 error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11612 if (strcmp (rs->buf, "OK") != 0)
11613 error (_("Error on target while disabling tracepoint."));
11614}
11615
35b1e5cc 11616static void
583f9a86 11617remote_trace_set_readonly_regions (struct target_ops *self)
35b1e5cc
SS
11618{
11619 asection *s;
81b9b86e 11620 bfd *abfd = NULL;
35b1e5cc 11621 bfd_size_type size;
608bcef2 11622 bfd_vma vma;
35b1e5cc 11623 int anysecs = 0;
c2fa21f1 11624 int offset = 0;
35b1e5cc
SS
11625
11626 if (!exec_bfd)
11627 return; /* No information to give. */
11628
11629 strcpy (target_buf, "QTro");
9779ab84 11630 offset = strlen (target_buf);
35b1e5cc
SS
11631 for (s = exec_bfd->sections; s; s = s->next)
11632 {
11633 char tmp1[40], tmp2[40];
c2fa21f1 11634 int sec_length;
35b1e5cc
SS
11635
11636 if ((s->flags & SEC_LOAD) == 0 ||
0df8b418 11637 /* (s->flags & SEC_CODE) == 0 || */
35b1e5cc
SS
11638 (s->flags & SEC_READONLY) == 0)
11639 continue;
11640
11641 anysecs = 1;
81b9b86e 11642 vma = bfd_get_section_vma (abfd, s);
35b1e5cc 11643 size = bfd_get_section_size (s);
608bcef2
HZ
11644 sprintf_vma (tmp1, vma);
11645 sprintf_vma (tmp2, vma + size);
c2fa21f1
HZ
11646 sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11647 if (offset + sec_length + 1 > target_buf_size)
11648 {
4082afcc 11649 if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
864ac8a7 11650 warning (_("\
c2fa21f1
HZ
11651Too many sections for read-only sections definition packet."));
11652 break;
11653 }
bba74b36
YQ
11654 xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11655 tmp1, tmp2);
c2fa21f1 11656 offset += sec_length;
35b1e5cc
SS
11657 }
11658 if (anysecs)
11659 {
11660 putpkt (target_buf);
11661 getpkt (&target_buf, &target_buf_size, 0);
11662 }
11663}
11664
11665static void
e2d1aae3 11666remote_trace_start (struct target_ops *self)
35b1e5cc
SS
11667{
11668 putpkt ("QTStart");
11669 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11670 if (*target_buf == '\0')
11671 error (_("Target does not support this command."));
11672 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11673 error (_("Bogus reply from target: %s"), target_buf);
11674}
11675
11676static int
8bd200f1 11677remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
35b1e5cc 11678{
953b98d1 11679 /* Initialize it just to avoid a GCC false warning. */
f652de6f 11680 char *p = NULL;
0df8b418 11681 /* FIXME we need to get register block size some other way. */
00bf0b85 11682 extern int trace_regblock_size;
bd3eecc3
PA
11683 enum packet_result result;
11684
4082afcc 11685 if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
bd3eecc3 11686 return -1;
a744cf53 11687
00bf0b85
SS
11688 trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11689
049dc89b
JK
11690 putpkt ("qTStatus");
11691
492d29ea 11692 TRY
67f41397
JK
11693 {
11694 p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11695 }
492d29ea 11696 CATCH (ex, RETURN_MASK_ERROR)
67f41397 11697 {
598d3636
JK
11698 if (ex.error != TARGET_CLOSE_ERROR)
11699 {
11700 exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11701 return -1;
11702 }
11703 throw_exception (ex);
67f41397 11704 }
492d29ea 11705 END_CATCH
00bf0b85 11706
bd3eecc3
PA
11707 result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11708
00bf0b85 11709 /* If the remote target doesn't do tracing, flag it. */
bd3eecc3 11710 if (result == PACKET_UNKNOWN)
00bf0b85 11711 return -1;
35b1e5cc 11712
00bf0b85 11713 /* We're working with a live target. */
f5911ea1 11714 ts->filename = NULL;
00bf0b85 11715
00bf0b85 11716 if (*p++ != 'T')
35b1e5cc
SS
11717 error (_("Bogus trace status reply from target: %s"), target_buf);
11718
84cebc4a
YQ
11719 /* Function 'parse_trace_status' sets default value of each field of
11720 'ts' at first, so we don't have to do it here. */
00bf0b85
SS
11721 parse_trace_status (p, ts);
11722
11723 return ts->running;
35b1e5cc
SS
11724}
11725
70221824 11726static void
db90e85c 11727remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
f196051f
SS
11728 struct uploaded_tp *utp)
11729{
11730 struct remote_state *rs = get_remote_state ();
f196051f
SS
11731 char *reply;
11732 struct bp_location *loc;
11733 struct tracepoint *tp = (struct tracepoint *) bp;
bba74b36 11734 size_t size = get_remote_packet_size ();
f196051f
SS
11735
11736 if (tp)
11737 {
11738 tp->base.hit_count = 0;
11739 tp->traceframe_usage = 0;
11740 for (loc = tp->base.loc; loc; loc = loc->next)
11741 {
11742 /* If the tracepoint was never downloaded, don't go asking for
11743 any status. */
11744 if (tp->number_on_target == 0)
11745 continue;
bba74b36
YQ
11746 xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11747 phex_nz (loc->address, 0));
f196051f
SS
11748 putpkt (rs->buf);
11749 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11750 if (reply && *reply)
11751 {
11752 if (*reply == 'V')
11753 parse_tracepoint_status (reply + 1, bp, utp);
11754 }
11755 }
11756 }
11757 else if (utp)
11758 {
11759 utp->hit_count = 0;
11760 utp->traceframe_usage = 0;
bba74b36
YQ
11761 xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11762 phex_nz (utp->addr, 0));
f196051f
SS
11763 putpkt (rs->buf);
11764 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11765 if (reply && *reply)
11766 {
11767 if (*reply == 'V')
11768 parse_tracepoint_status (reply + 1, bp, utp);
11769 }
11770 }
11771}
11772
35b1e5cc 11773static void
74499f1b 11774remote_trace_stop (struct target_ops *self)
35b1e5cc
SS
11775{
11776 putpkt ("QTStop");
11777 remote_get_noisy_reply (&target_buf, &target_buf_size);
ad91cd99
PA
11778 if (*target_buf == '\0')
11779 error (_("Target does not support this command."));
11780 if (strcmp (target_buf, "OK") != 0)
35b1e5cc
SS
11781 error (_("Bogus reply from target: %s"), target_buf);
11782}
11783
11784static int
bd4c6793
TT
11785remote_trace_find (struct target_ops *self,
11786 enum trace_find_type type, int num,
cc5925ad 11787 CORE_ADDR addr1, CORE_ADDR addr2,
35b1e5cc
SS
11788 int *tpp)
11789{
11790 struct remote_state *rs = get_remote_state ();
bba74b36 11791 char *endbuf = rs->buf + get_remote_packet_size ();
35b1e5cc
SS
11792 char *p, *reply;
11793 int target_frameno = -1, target_tracept = -1;
11794
e6e4e701
PA
11795 /* Lookups other than by absolute frame number depend on the current
11796 trace selected, so make sure it is correct on the remote end
11797 first. */
11798 if (type != tfind_number)
11799 set_remote_traceframe ();
11800
35b1e5cc
SS
11801 p = rs->buf;
11802 strcpy (p, "QTFrame:");
11803 p = strchr (p, '\0');
11804 switch (type)
11805 {
11806 case tfind_number:
bba74b36 11807 xsnprintf (p, endbuf - p, "%x", num);
35b1e5cc
SS
11808 break;
11809 case tfind_pc:
bba74b36 11810 xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
35b1e5cc
SS
11811 break;
11812 case tfind_tp:
bba74b36 11813 xsnprintf (p, endbuf - p, "tdp:%x", num);
35b1e5cc
SS
11814 break;
11815 case tfind_range:
bba74b36
YQ
11816 xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11817 phex_nz (addr2, 0));
35b1e5cc
SS
11818 break;
11819 case tfind_outside:
bba74b36
YQ
11820 xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11821 phex_nz (addr2, 0));
35b1e5cc
SS
11822 break;
11823 default:
9b20d036 11824 error (_("Unknown trace find type %d"), type);
35b1e5cc
SS
11825 }
11826
11827 putpkt (rs->buf);
2f65bcb7 11828 reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
ad91cd99
PA
11829 if (*reply == '\0')
11830 error (_("Target does not support this command."));
35b1e5cc
SS
11831
11832 while (reply && *reply)
11833 switch (*reply)
11834 {
11835 case 'F':
f197e0f1
VP
11836 p = ++reply;
11837 target_frameno = (int) strtol (p, &reply, 16);
11838 if (reply == p)
11839 error (_("Unable to parse trace frame number"));
e6e4e701
PA
11840 /* Don't update our remote traceframe number cache on failure
11841 to select a remote traceframe. */
f197e0f1
VP
11842 if (target_frameno == -1)
11843 return -1;
35b1e5cc
SS
11844 break;
11845 case 'T':
f197e0f1
VP
11846 p = ++reply;
11847 target_tracept = (int) strtol (p, &reply, 16);
11848 if (reply == p)
11849 error (_("Unable to parse tracepoint number"));
35b1e5cc
SS
11850 break;
11851 case 'O': /* "OK"? */
11852 if (reply[1] == 'K' && reply[2] == '\0')
11853 reply += 2;
11854 else
11855 error (_("Bogus reply from target: %s"), reply);
11856 break;
11857 default:
11858 error (_("Bogus reply from target: %s"), reply);
11859 }
11860 if (tpp)
11861 *tpp = target_tracept;
e6e4e701 11862
262e1174 11863 rs->remote_traceframe_number = target_frameno;
35b1e5cc
SS
11864 return target_frameno;
11865}
11866
11867static int
4011015b
TT
11868remote_get_trace_state_variable_value (struct target_ops *self,
11869 int tsvnum, LONGEST *val)
35b1e5cc
SS
11870{
11871 struct remote_state *rs = get_remote_state ();
11872 char *reply;
11873 ULONGEST uval;
11874
e6e4e701
PA
11875 set_remote_traceframe ();
11876
bba74b36 11877 xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
35b1e5cc
SS
11878 putpkt (rs->buf);
11879 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11880 if (reply && *reply)
11881 {
11882 if (*reply == 'V')
11883 {
11884 unpack_varlen_hex (reply + 1, &uval);
11885 *val = (LONGEST) uval;
11886 return 1;
11887 }
11888 }
11889 return 0;
11890}
11891
00bf0b85 11892static int
dc3decaf 11893remote_save_trace_data (struct target_ops *self, const char *filename)
00bf0b85
SS
11894{
11895 struct remote_state *rs = get_remote_state ();
11896 char *p, *reply;
11897
11898 p = rs->buf;
11899 strcpy (p, "QTSave:");
11900 p += strlen (p);
11901 if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11902 error (_("Remote file name too long for trace save packet"));
9f1b45b0 11903 p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
00bf0b85
SS
11904 *p++ = '\0';
11905 putpkt (rs->buf);
ad91cd99 11906 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
d6c5869f 11907 if (*reply == '\0')
ad91cd99
PA
11908 error (_("Target does not support this command."));
11909 if (strcmp (reply, "OK") != 0)
11910 error (_("Bogus reply from target: %s"), reply);
00bf0b85
SS
11911 return 0;
11912}
11913
11914/* This is basically a memory transfer, but needs to be its own packet
11915 because we don't know how the target actually organizes its trace
11916 memory, plus we want to be able to ask for as much as possible, but
11917 not be unhappy if we don't get as much as we ask for. */
11918
11919static LONGEST
88ee6f45
TT
11920remote_get_raw_trace_data (struct target_ops *self,
11921 gdb_byte *buf, ULONGEST offset, LONGEST len)
00bf0b85
SS
11922{
11923 struct remote_state *rs = get_remote_state ();
11924 char *reply;
11925 char *p;
11926 int rslt;
11927
11928 p = rs->buf;
11929 strcpy (p, "qTBuffer:");
11930 p += strlen (p);
11931 p += hexnumstr (p, offset);
11932 *p++ = ',';
11933 p += hexnumstr (p, len);
11934 *p++ = '\0';
11935
11936 putpkt (rs->buf);
11937 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11938 if (reply && *reply)
11939 {
11940 /* 'l' by itself means we're at the end of the buffer and
11941 there is nothing more to get. */
11942 if (*reply == 'l')
11943 return 0;
11944
11945 /* Convert the reply into binary. Limit the number of bytes to
11946 convert according to our passed-in buffer size, rather than
11947 what was returned in the packet; if the target is
11948 unexpectedly generous and gives us a bigger reply than we
11949 asked for, we don't want to crash. */
11950 rslt = hex2bin (target_buf, buf, len);
11951 return rslt;
11952 }
11953
11954 /* Something went wrong, flag as an error. */
11955 return -1;
11956}
11957
35b1e5cc 11958static void
37b25738 11959remote_set_disconnected_tracing (struct target_ops *self, int val)
35b1e5cc
SS
11960{
11961 struct remote_state *rs = get_remote_state ();
11962
4082afcc 11963 if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
33da3f1c 11964 {
ad91cd99
PA
11965 char *reply;
11966
bba74b36 11967 xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
33da3f1c 11968 putpkt (rs->buf);
ad91cd99
PA
11969 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11970 if (*reply == '\0')
33da3f1c 11971 error (_("Target does not support this command."));
ad91cd99
PA
11972 if (strcmp (reply, "OK") != 0)
11973 error (_("Bogus reply from target: %s"), reply);
33da3f1c
SS
11974 }
11975 else if (val)
11976 warning (_("Target does not support disconnected tracing."));
35b1e5cc
SS
11977}
11978
dc146f7c
VP
11979static int
11980remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11981{
11982 struct thread_info *info = find_thread_ptid (ptid);
a744cf53 11983
fe978cb0
PA
11984 if (info && info->priv)
11985 return info->priv->core;
dc146f7c
VP
11986 return -1;
11987}
11988
4daf5ac0 11989static void
736d5b1f 11990remote_set_circular_trace_buffer (struct target_ops *self, int val)
4daf5ac0
SS
11991{
11992 struct remote_state *rs = get_remote_state ();
ad91cd99 11993 char *reply;
4daf5ac0 11994
bba74b36 11995 xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
4daf5ac0 11996 putpkt (rs->buf);
ad91cd99
PA
11997 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11998 if (*reply == '\0')
4daf5ac0 11999 error (_("Target does not support this command."));
ad91cd99
PA
12000 if (strcmp (reply, "OK") != 0)
12001 error (_("Bogus reply from target: %s"), reply);
4daf5ac0
SS
12002}
12003
b3b9301e 12004static struct traceframe_info *
a893e81f 12005remote_traceframe_info (struct target_ops *self)
b3b9301e
PA
12006{
12007 char *text;
12008
12009 text = target_read_stralloc (&current_target,
12010 TARGET_OBJECT_TRACEFRAME_INFO, NULL);
12011 if (text != NULL)
12012 {
12013 struct traceframe_info *info;
12014 struct cleanup *back_to = make_cleanup (xfree, text);
12015
12016 info = parse_traceframe_info (text);
12017 do_cleanups (back_to);
12018 return info;
12019 }
12020
12021 return NULL;
12022}
12023
405f8e94
SS
12024/* Handle the qTMinFTPILen packet. Returns the minimum length of
12025 instruction on which a fast tracepoint may be placed. Returns -1
12026 if the packet is not supported, and 0 if the minimum instruction
12027 length is unknown. */
12028
12029static int
0e67620a 12030remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
405f8e94
SS
12031{
12032 struct remote_state *rs = get_remote_state ();
12033 char *reply;
12034
e886a173
PA
12035 /* If we're not debugging a process yet, the IPA can't be
12036 loaded. */
12037 if (!target_has_execution)
12038 return 0;
12039
12040 /* Make sure the remote is pointing at the right process. */
12041 set_general_process ();
12042
bba74b36 12043 xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
405f8e94
SS
12044 putpkt (rs->buf);
12045 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12046 if (*reply == '\0')
12047 return -1;
12048 else
12049 {
12050 ULONGEST min_insn_len;
12051
12052 unpack_varlen_hex (reply, &min_insn_len);
12053
12054 return (int) min_insn_len;
12055 }
12056}
12057
f6f899bf 12058static void
4da384be 12059remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
f6f899bf 12060{
4082afcc 12061 if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
f6f899bf
HAQ
12062 {
12063 struct remote_state *rs = get_remote_state ();
12064 char *buf = rs->buf;
12065 char *endbuf = rs->buf + get_remote_packet_size ();
12066 enum packet_result result;
12067
12068 gdb_assert (val >= 0 || val == -1);
12069 buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12070 /* Send -1 as literal "-1" to avoid host size dependency. */
12071 if (val < 0)
12072 {
12073 *buf++ = '-';
12074 buf += hexnumstr (buf, (ULONGEST) -val);
12075 }
12076 else
12077 buf += hexnumstr (buf, (ULONGEST) val);
12078
12079 putpkt (rs->buf);
12080 remote_get_noisy_reply (&rs->buf, &rs->buf_size);
12081 result = packet_ok (rs->buf,
12082 &remote_protocol_packets[PACKET_QTBuffer_size]);
12083
12084 if (result != PACKET_OK)
12085 warning (_("Bogus reply from target: %s"), rs->buf);
12086 }
12087}
12088
f196051f 12089static int
d9e68a2c
TT
12090remote_set_trace_notes (struct target_ops *self,
12091 const char *user, const char *notes,
ca623f82 12092 const char *stop_notes)
f196051f
SS
12093{
12094 struct remote_state *rs = get_remote_state ();
12095 char *reply;
12096 char *buf = rs->buf;
12097 char *endbuf = rs->buf + get_remote_packet_size ();
12098 int nbytes;
12099
12100 buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12101 if (user)
12102 {
12103 buf += xsnprintf (buf, endbuf - buf, "user:");
9f1b45b0 12104 nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
f196051f
SS
12105 buf += 2 * nbytes;
12106 *buf++ = ';';
12107 }
12108 if (notes)
12109 {
12110 buf += xsnprintf (buf, endbuf - buf, "notes:");
9f1b45b0 12111 nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
f196051f
SS
12112 buf += 2 * nbytes;
12113 *buf++ = ';';
12114 }
12115 if (stop_notes)
12116 {
12117 buf += xsnprintf (buf, endbuf - buf, "tstop:");
9f1b45b0 12118 nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
f196051f
SS
12119 buf += 2 * nbytes;
12120 *buf++ = ';';
12121 }
12122 /* Ensure the buffer is terminated. */
12123 *buf = '\0';
12124
12125 putpkt (rs->buf);
12126 reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
12127 if (*reply == '\0')
12128 return 0;
12129
12130 if (strcmp (reply, "OK") != 0)
12131 error (_("Bogus reply from target: %s"), reply);
12132
12133 return 1;
12134}
12135
d1feda86 12136static int
2c152180 12137remote_use_agent (struct target_ops *self, int use)
d1feda86 12138{
4082afcc 12139 if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
d1feda86
YQ
12140 {
12141 struct remote_state *rs = get_remote_state ();
12142
12143 /* If the stub supports QAgent. */
bba74b36 12144 xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
d1feda86
YQ
12145 putpkt (rs->buf);
12146 getpkt (&rs->buf, &rs->buf_size, 0);
12147
12148 if (strcmp (rs->buf, "OK") == 0)
12149 {
12150 use_agent = use;
12151 return 1;
12152 }
12153 }
12154
12155 return 0;
12156}
12157
12158static int
fe38f897 12159remote_can_use_agent (struct target_ops *self)
d1feda86 12160{
4082afcc 12161 return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
d1feda86
YQ
12162}
12163
9accd112
MM
12164struct btrace_target_info
12165{
12166 /* The ptid of the traced thread. */
12167 ptid_t ptid;
f4abbc16
MM
12168
12169 /* The obtained branch trace configuration. */
12170 struct btrace_config conf;
9accd112
MM
12171};
12172
f4abbc16
MM
12173/* Reset our idea of our target's btrace configuration. */
12174
12175static void
12176remote_btrace_reset (void)
12177{
12178 struct remote_state *rs = get_remote_state ();
12179
12180 memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
12181}
12182
9accd112
MM
12183/* Check whether the target supports branch tracing. */
12184
12185static int
043c3577 12186remote_supports_btrace (struct target_ops *self, enum btrace_format format)
9accd112 12187{
4082afcc 12188 if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
9accd112 12189 return 0;
4082afcc 12190 if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
9accd112
MM
12191 return 0;
12192
043c3577
MM
12193 switch (format)
12194 {
12195 case BTRACE_FORMAT_NONE:
12196 return 0;
12197
12198 case BTRACE_FORMAT_BTS:
12199 return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
b20a6524
MM
12200
12201 case BTRACE_FORMAT_PT:
12202 /* The trace is decoded on the host. Even if our target supports it,
12203 we still need to have libipt to decode the trace. */
12204#if defined (HAVE_LIBIPT)
12205 return (packet_support (PACKET_Qbtrace_pt) == PACKET_ENABLE);
12206#else /* !defined (HAVE_LIBIPT) */
12207 return 0;
12208#endif /* !defined (HAVE_LIBIPT) */
043c3577
MM
12209 }
12210
12211 internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
9accd112
MM
12212}
12213
f4abbc16
MM
12214/* Synchronize the configuration with the target. */
12215
12216static void
12217btrace_sync_conf (const struct btrace_config *conf)
12218{
d33501a5
MM
12219 struct packet_config *packet;
12220 struct remote_state *rs;
12221 char *buf, *pos, *endbuf;
12222
12223 rs = get_remote_state ();
12224 buf = rs->buf;
12225 endbuf = buf + get_remote_packet_size ();
12226
12227 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
12228 if (packet_config_support (packet) == PACKET_ENABLE
12229 && conf->bts.size != rs->btrace_config.bts.size)
12230 {
12231 pos = buf;
12232 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12233 conf->bts.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 BTS buffer size: %s"), buf + 2);
12242 else
12243 error (_("Failed to configure the BTS buffer size."));
12244 }
12245
12246 rs->btrace_config.bts.size = conf->bts.size;
12247 }
b20a6524
MM
12248
12249 packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
12250 if (packet_config_support (packet) == PACKET_ENABLE
12251 && conf->pt.size != rs->btrace_config.pt.size)
12252 {
12253 pos = buf;
12254 pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
12255 conf->pt.size);
12256
12257 putpkt (buf);
12258 getpkt (&buf, &rs->buf_size, 0);
12259
12260 if (packet_ok (buf, packet) == PACKET_ERROR)
12261 {
12262 if (buf[0] == 'E' && buf[1] == '.')
12263 error (_("Failed to configure the trace buffer size: %s"), buf + 2);
12264 else
12265 error (_("Failed to configure the trace buffer size."));
12266 }
12267
12268 rs->btrace_config.pt.size = conf->pt.size;
12269 }
f4abbc16
MM
12270}
12271
12272/* Read the current thread's btrace configuration from the target and
12273 store it into CONF. */
12274
12275static void
12276btrace_read_config (struct btrace_config *conf)
12277{
12278 char *xml;
12279
12280 xml = target_read_stralloc (&current_target,
b20a6524 12281 TARGET_OBJECT_BTRACE_CONF, "");
f4abbc16
MM
12282 if (xml != NULL)
12283 {
12284 struct cleanup *cleanup;
12285
12286 cleanup = make_cleanup (xfree, xml);
12287 parse_xml_btrace_conf (conf, xml);
12288 do_cleanups (cleanup);
12289 }
12290}
12291
9accd112
MM
12292/* Enable branch tracing. */
12293
12294static struct btrace_target_info *
f4abbc16
MM
12295remote_enable_btrace (struct target_ops *self, ptid_t ptid,
12296 const struct btrace_config *conf)
9accd112
MM
12297{
12298 struct btrace_target_info *tinfo = NULL;
b20a6524 12299 struct packet_config *packet = NULL;
9accd112
MM
12300 struct remote_state *rs = get_remote_state ();
12301 char *buf = rs->buf;
12302 char *endbuf = rs->buf + get_remote_packet_size ();
12303
b20a6524
MM
12304 switch (conf->format)
12305 {
12306 case BTRACE_FORMAT_BTS:
12307 packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
12308 break;
12309
12310 case BTRACE_FORMAT_PT:
12311 packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
12312 break;
12313 }
12314
12315 if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12316 error (_("Target does not support branch tracing."));
12317
f4abbc16
MM
12318 btrace_sync_conf (conf);
12319
9accd112
MM
12320 set_general_thread (ptid);
12321
12322 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12323 putpkt (rs->buf);
12324 getpkt (&rs->buf, &rs->buf_size, 0);
12325
12326 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12327 {
12328 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12329 error (_("Could not enable branch tracing for %s: %s"),
12330 target_pid_to_str (ptid), rs->buf + 2);
12331 else
12332 error (_("Could not enable branch tracing for %s."),
12333 target_pid_to_str (ptid));
12334 }
12335
8d749320 12336 tinfo = XCNEW (struct btrace_target_info);
9accd112
MM
12337 tinfo->ptid = ptid;
12338
f4abbc16
MM
12339 /* If we fail to read the configuration, we lose some information, but the
12340 tracing itself is not impacted. */
492d29ea
PA
12341 TRY
12342 {
12343 btrace_read_config (&tinfo->conf);
12344 }
12345 CATCH (err, RETURN_MASK_ERROR)
12346 {
12347 if (err.message != NULL)
12348 warning ("%s", err.message);
12349 }
12350 END_CATCH
f4abbc16 12351
9accd112
MM
12352 return tinfo;
12353}
12354
12355/* Disable branch tracing. */
12356
12357static void
25e95349
TT
12358remote_disable_btrace (struct target_ops *self,
12359 struct btrace_target_info *tinfo)
9accd112
MM
12360{
12361 struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
12362 struct remote_state *rs = get_remote_state ();
12363 char *buf = rs->buf;
12364 char *endbuf = rs->buf + get_remote_packet_size ();
12365
4082afcc 12366 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12367 error (_("Target does not support branch tracing."));
12368
12369 set_general_thread (tinfo->ptid);
12370
12371 buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
12372 putpkt (rs->buf);
12373 getpkt (&rs->buf, &rs->buf_size, 0);
12374
12375 if (packet_ok (rs->buf, packet) == PACKET_ERROR)
12376 {
12377 if (rs->buf[0] == 'E' && rs->buf[1] == '.')
12378 error (_("Could not disable branch tracing for %s: %s"),
12379 target_pid_to_str (tinfo->ptid), rs->buf + 2);
12380 else
12381 error (_("Could not disable branch tracing for %s."),
12382 target_pid_to_str (tinfo->ptid));
12383 }
12384
12385 xfree (tinfo);
12386}
12387
12388/* Teardown branch tracing. */
12389
12390static void
1777056d
TT
12391remote_teardown_btrace (struct target_ops *self,
12392 struct btrace_target_info *tinfo)
9accd112
MM
12393{
12394 /* We must not talk to the target during teardown. */
12395 xfree (tinfo);
12396}
12397
12398/* Read the branch trace. */
12399
969c39fb 12400static enum btrace_error
39c49f83 12401remote_read_btrace (struct target_ops *self,
734b0e4b 12402 struct btrace_data *btrace,
969c39fb 12403 struct btrace_target_info *tinfo,
9accd112
MM
12404 enum btrace_read_type type)
12405{
12406 struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
12407 struct remote_state *rs = get_remote_state ();
969c39fb 12408 struct cleanup *cleanup;
9accd112
MM
12409 const char *annex;
12410 char *xml;
12411
4082afcc 12412 if (packet_config_support (packet) != PACKET_ENABLE)
9accd112
MM
12413 error (_("Target does not support branch tracing."));
12414
12415#if !defined(HAVE_LIBEXPAT)
12416 error (_("Cannot process branch tracing result. XML parsing not supported."));
12417#endif
12418
12419 switch (type)
12420 {
864089d2 12421 case BTRACE_READ_ALL:
9accd112
MM
12422 annex = "all";
12423 break;
864089d2 12424 case BTRACE_READ_NEW:
9accd112
MM
12425 annex = "new";
12426 break;
969c39fb
MM
12427 case BTRACE_READ_DELTA:
12428 annex = "delta";
12429 break;
9accd112
MM
12430 default:
12431 internal_error (__FILE__, __LINE__,
12432 _("Bad branch tracing read type: %u."),
12433 (unsigned int) type);
12434 }
12435
12436 xml = target_read_stralloc (&current_target,
b20a6524 12437 TARGET_OBJECT_BTRACE, annex);
969c39fb
MM
12438 if (xml == NULL)
12439 return BTRACE_ERR_UNKNOWN;
9accd112 12440
969c39fb 12441 cleanup = make_cleanup (xfree, xml);
734b0e4b 12442 parse_xml_btrace (btrace, xml);
969c39fb 12443 do_cleanups (cleanup);
9accd112 12444
969c39fb 12445 return BTRACE_ERR_NONE;
9accd112
MM
12446}
12447
f4abbc16
MM
12448static const struct btrace_config *
12449remote_btrace_conf (struct target_ops *self,
12450 const struct btrace_target_info *tinfo)
12451{
12452 return &tinfo->conf;
12453}
12454
ced63ec0 12455static int
5436ff03 12456remote_augmented_libraries_svr4_read (struct target_ops *self)
ced63ec0 12457{
4082afcc
PA
12458 return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
12459 == PACKET_ENABLE);
ced63ec0
GB
12460}
12461
9dd130a0
TT
12462/* Implementation of to_load. */
12463
12464static void
9cbe5fff 12465remote_load (struct target_ops *self, const char *name, int from_tty)
9dd130a0
TT
12466{
12467 generic_load (name, from_tty);
12468}
12469
c78fa86a
GB
12470/* Accepts an integer PID; returns a string representing a file that
12471 can be opened on the remote side to get the symbols for the child
12472 process. Returns NULL if the operation is not supported. */
12473
12474static char *
12475remote_pid_to_exec_file (struct target_ops *self, int pid)
12476{
12477 static char *filename = NULL;
835205d0
GB
12478 struct inferior *inf;
12479 char *annex = NULL;
c78fa86a
GB
12480
12481 if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12482 return NULL;
12483
12484 if (filename != NULL)
12485 xfree (filename);
12486
835205d0
GB
12487 inf = find_inferior_pid (pid);
12488 if (inf == NULL)
12489 internal_error (__FILE__, __LINE__,
12490 _("not currently attached to process %d"), pid);
12491
12492 if (!inf->fake_pid_p)
12493 {
12494 const int annex_size = 9;
12495
12496 annex = alloca (annex_size);
12497 xsnprintf (annex, annex_size, "%x", pid);
12498 }
12499
c78fa86a
GB
12500 filename = target_read_stralloc (&current_target,
12501 TARGET_OBJECT_EXEC_FILE, annex);
12502
12503 return filename;
12504}
12505
c906108c 12506static void
fba45db2 12507init_remote_ops (void)
c906108c 12508{
c5aa993b 12509 remote_ops.to_shortname = "remote";
c906108c 12510 remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
c5aa993b 12511 remote_ops.to_doc =
c906108c 12512 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
0d06e24b
JM
12513Specify the serial device it is connected to\n\
12514(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
c5aa993b
JM
12515 remote_ops.to_open = remote_open;
12516 remote_ops.to_close = remote_close;
c906108c 12517 remote_ops.to_detach = remote_detach;
6ad8ae5c 12518 remote_ops.to_disconnect = remote_disconnect;
c5aa993b 12519 remote_ops.to_resume = remote_resume;
c906108c
SS
12520 remote_ops.to_wait = remote_wait;
12521 remote_ops.to_fetch_registers = remote_fetch_registers;
12522 remote_ops.to_store_registers = remote_store_registers;
12523 remote_ops.to_prepare_to_store = remote_prepare_to_store;
c5aa993b 12524 remote_ops.to_files_info = remote_files_info;
c906108c
SS
12525 remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12526 remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
f7e6eed5
PA
12527 remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12528 remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12529 remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12530 remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
3c3bea1c
GS
12531 remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12532 remote_ops.to_stopped_data_address = remote_stopped_data_address;
283002cf
MR
12533 remote_ops.to_watchpoint_addr_within_range =
12534 remote_watchpoint_addr_within_range;
3c3bea1c
GS
12535 remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12536 remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12537 remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
480a3f21
PW
12538 remote_ops.to_region_ok_for_hw_watchpoint
12539 = remote_region_ok_for_hw_watchpoint;
3c3bea1c
GS
12540 remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12541 remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
c5aa993b 12542 remote_ops.to_kill = remote_kill;
9dd130a0 12543 remote_ops.to_load = remote_load;
c906108c 12544 remote_ops.to_mourn_inferior = remote_mourn;
2455069d 12545 remote_ops.to_pass_signals = remote_pass_signals;
9b224c5e 12546 remote_ops.to_program_signals = remote_program_signals;
c906108c 12547 remote_ops.to_thread_alive = remote_thread_alive;
e8032dde 12548 remote_ops.to_update_thread_list = remote_update_thread_list;
0caabb7e 12549 remote_ops.to_pid_to_str = remote_pid_to_str;
cf759d3b 12550 remote_ops.to_extra_thread_info = remote_threads_extra_info;
10760264 12551 remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
c906108c 12552 remote_ops.to_stop = remote_stop;
bfedc46a 12553 remote_ops.to_interrupt = remote_interrupt;
abc56d60 12554 remote_ops.to_check_pending_interrupt = remote_check_pending_interrupt;
4b8a223f 12555 remote_ops.to_xfer_partial = remote_xfer_partial;
96baa820 12556 remote_ops.to_rcmd = remote_rcmd;
c78fa86a 12557 remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
49d03eab 12558 remote_ops.to_log_command = serial_log_command;
38691318 12559 remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
c906108c 12560 remote_ops.to_stratum = process_stratum;
c35b1492
PA
12561 remote_ops.to_has_all_memory = default_child_has_all_memory;
12562 remote_ops.to_has_memory = default_child_has_memory;
12563 remote_ops.to_has_stack = default_child_has_stack;
12564 remote_ops.to_has_registers = default_child_has_registers;
12565 remote_ops.to_has_execution = default_child_has_execution;
3e43a32a 12566 remote_ops.to_has_thread_control = tc_schedlock; /* can lock scheduler */
b2175913 12567 remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
c5aa993b 12568 remote_ops.to_magic = OPS_MAGIC;
fd79ecee 12569 remote_ops.to_memory_map = remote_memory_map;
a76d924d
DJ
12570 remote_ops.to_flash_erase = remote_flash_erase;
12571 remote_ops.to_flash_done = remote_flash_done;
29709017 12572 remote_ops.to_read_description = remote_read_description;
08388c79 12573 remote_ops.to_search_memory = remote_search_memory;
75c99385
PA
12574 remote_ops.to_can_async_p = remote_can_async_p;
12575 remote_ops.to_is_async_p = remote_is_async_p;
12576 remote_ops.to_async = remote_async;
75c99385
PA
12577 remote_ops.to_terminal_inferior = remote_terminal_inferior;
12578 remote_ops.to_terminal_ours = remote_terminal_ours;
74531fed 12579 remote_ops.to_supports_non_stop = remote_supports_non_stop;
8a305172 12580 remote_ops.to_supports_multi_process = remote_supports_multi_process;
03583c20
UW
12581 remote_ops.to_supports_disable_randomization
12582 = remote_supports_disable_randomization;
4bd7dc42 12583 remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
7313baad
UW
12584 remote_ops.to_fileio_open = remote_hostio_open;
12585 remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12586 remote_ops.to_fileio_pread = remote_hostio_pread;
9b15c1f0 12587 remote_ops.to_fileio_fstat = remote_hostio_fstat;
7313baad
UW
12588 remote_ops.to_fileio_close = remote_hostio_close;
12589 remote_ops.to_fileio_unlink = remote_hostio_unlink;
b9e7b9c3 12590 remote_ops.to_fileio_readlink = remote_hostio_readlink;
d248b706 12591 remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
3065dfb6 12592 remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
b775012e 12593 remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
d3ce09f5 12594 remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
35b1e5cc
SS
12595 remote_ops.to_trace_init = remote_trace_init;
12596 remote_ops.to_download_tracepoint = remote_download_tracepoint;
1e4d1764 12597 remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
3e43a32a
MS
12598 remote_ops.to_download_trace_state_variable
12599 = remote_download_trace_state_variable;
d248b706
KY
12600 remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12601 remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
35b1e5cc
SS
12602 remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12603 remote_ops.to_trace_start = remote_trace_start;
12604 remote_ops.to_get_trace_status = remote_get_trace_status;
f196051f 12605 remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
35b1e5cc
SS
12606 remote_ops.to_trace_stop = remote_trace_stop;
12607 remote_ops.to_trace_find = remote_trace_find;
3e43a32a
MS
12608 remote_ops.to_get_trace_state_variable_value
12609 = remote_get_trace_state_variable_value;
00bf0b85
SS
12610 remote_ops.to_save_trace_data = remote_save_trace_data;
12611 remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
3e43a32a
MS
12612 remote_ops.to_upload_trace_state_variables
12613 = remote_upload_trace_state_variables;
00bf0b85 12614 remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
405f8e94 12615 remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
35b1e5cc 12616 remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
4daf5ac0 12617 remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
f6f899bf 12618 remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
f196051f 12619 remote_ops.to_set_trace_notes = remote_set_trace_notes;
dc146f7c 12620 remote_ops.to_core_of_thread = remote_core_of_thread;
4a5e7a5b 12621 remote_ops.to_verify_memory = remote_verify_memory;
711e434b 12622 remote_ops.to_get_tib_address = remote_get_tib_address;
d914c394 12623 remote_ops.to_set_permissions = remote_set_permissions;
0fb4aa4b
PA
12624 remote_ops.to_static_tracepoint_marker_at
12625 = remote_static_tracepoint_marker_at;
12626 remote_ops.to_static_tracepoint_markers_by_strid
12627 = remote_static_tracepoint_markers_by_strid;
b3b9301e 12628 remote_ops.to_traceframe_info = remote_traceframe_info;
d1feda86
YQ
12629 remote_ops.to_use_agent = remote_use_agent;
12630 remote_ops.to_can_use_agent = remote_can_use_agent;
9accd112
MM
12631 remote_ops.to_supports_btrace = remote_supports_btrace;
12632 remote_ops.to_enable_btrace = remote_enable_btrace;
12633 remote_ops.to_disable_btrace = remote_disable_btrace;
12634 remote_ops.to_teardown_btrace = remote_teardown_btrace;
12635 remote_ops.to_read_btrace = remote_read_btrace;
f4abbc16 12636 remote_ops.to_btrace_conf = remote_btrace_conf;
ced63ec0
GB
12637 remote_ops.to_augmented_libraries_svr4_read =
12638 remote_augmented_libraries_svr4_read;
c906108c
SS
12639}
12640
12641/* Set up the extended remote vector by making a copy of the standard
12642 remote vector and adding to it. */
12643
12644static void
fba45db2 12645init_extended_remote_ops (void)
c906108c
SS
12646{
12647 extended_remote_ops = remote_ops;
12648
0f71a2f6 12649 extended_remote_ops.to_shortname = "extended-remote";
c5aa993b 12650 extended_remote_ops.to_longname =
c906108c 12651 "Extended remote serial target in gdb-specific protocol";
c5aa993b 12652 extended_remote_ops.to_doc =
c906108c 12653 "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
39237dd1
PA
12654Specify the serial device it is connected to (e.g. /dev/ttya).";
12655 extended_remote_ops.to_open = extended_remote_open;
c906108c
SS
12656 extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12657 extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
2d717e4f
DJ
12658 extended_remote_ops.to_detach = extended_remote_detach;
12659 extended_remote_ops.to_attach = extended_remote_attach;
b9c1d481 12660 extended_remote_ops.to_post_attach = extended_remote_post_attach;
82f73884 12661 extended_remote_ops.to_kill = extended_remote_kill;
03583c20
UW
12662 extended_remote_ops.to_supports_disable_randomization
12663 = extended_remote_supports_disable_randomization;
de0d863e 12664 extended_remote_ops.to_follow_fork = remote_follow_fork;
cbb8991c
DB
12665 extended_remote_ops.to_insert_fork_catchpoint
12666 = remote_insert_fork_catchpoint;
12667 extended_remote_ops.to_remove_fork_catchpoint
12668 = remote_remove_fork_catchpoint;
12669 extended_remote_ops.to_insert_vfork_catchpoint
12670 = remote_insert_vfork_catchpoint;
12671 extended_remote_ops.to_remove_vfork_catchpoint
12672 = remote_remove_vfork_catchpoint;
0f71a2f6
JM
12673}
12674
6426a772 12675static int
6a109b6b 12676remote_can_async_p (struct target_ops *ops)
6426a772 12677{
5d93a237
TT
12678 struct remote_state *rs = get_remote_state ();
12679
c6ebd6cf 12680 if (!target_async_permitted)
75c99385
PA
12681 /* We only enable async when the user specifically asks for it. */
12682 return 0;
12683
23860348 12684 /* We're async whenever the serial device is. */
5d93a237 12685 return serial_can_async_p (rs->remote_desc);
6426a772
JM
12686}
12687
12688static int
6a109b6b 12689remote_is_async_p (struct target_ops *ops)
6426a772 12690{
5d93a237
TT
12691 struct remote_state *rs = get_remote_state ();
12692
c6ebd6cf 12693 if (!target_async_permitted)
75c99385
PA
12694 /* We only enable async when the user specifically asks for it. */
12695 return 0;
12696
23860348 12697 /* We're async whenever the serial device is. */
5d93a237 12698 return serial_is_async_p (rs->remote_desc);
6426a772
JM
12699}
12700
2acceee2
JM
12701/* Pass the SERIAL event on and up to the client. One day this code
12702 will be able to delay notifying the client of an event until the
23860348 12703 point where an entire packet has been received. */
2acceee2 12704
2acceee2
JM
12705static serial_event_ftype remote_async_serial_handler;
12706
6426a772 12707static void
819cc324 12708remote_async_serial_handler (struct serial *scb, void *context)
6426a772 12709{
88b496c3
TT
12710 struct remote_state *rs = context;
12711
2acceee2
JM
12712 /* Don't propogate error information up to the client. Instead let
12713 the client find out about the error by querying the target. */
6a3753b3 12714 inferior_event_handler (INF_REG_EVENT, NULL);
2acceee2
JM
12715}
12716
74531fed
PA
12717static void
12718remote_async_inferior_event_handler (gdb_client_data data)
12719{
12720 inferior_event_handler (INF_REG_EVENT, NULL);
12721}
12722
2acceee2 12723static void
6a3753b3 12724remote_async (struct target_ops *ops, int enable)
2acceee2 12725{
5d93a237
TT
12726 struct remote_state *rs = get_remote_state ();
12727
6a3753b3 12728 if (enable)
2acceee2 12729 {
88b496c3 12730 serial_async (rs->remote_desc, remote_async_serial_handler, rs);
b7d2e916
PA
12731
12732 /* If there are pending events in the stop reply queue tell the
12733 event loop to process them. */
12734 if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12735 mark_async_event_handler (remote_async_inferior_event_token);
2acceee2
JM
12736 }
12737 else
b7d2e916
PA
12738 {
12739 serial_async (rs->remote_desc, NULL, NULL);
12740 clear_async_event_handler (remote_async_inferior_event_token);
12741 }
6426a772
JM
12742}
12743
5a2468f5 12744static void
c2d11a7d 12745set_remote_cmd (char *args, int from_tty)
5a2468f5 12746{
635c7e8a 12747 help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
5a2468f5
JM
12748}
12749
d471ea57
AC
12750static void
12751show_remote_cmd (char *args, int from_tty)
12752{
37a105a1 12753 /* We can't just use cmd_show_list here, because we want to skip
427c3a89 12754 the redundant "show remote Z-packet" and the legacy aliases. */
37a105a1
DJ
12755 struct cleanup *showlist_chain;
12756 struct cmd_list_element *list = remote_show_cmdlist;
79a45e25 12757 struct ui_out *uiout = current_uiout;
37a105a1
DJ
12758
12759 showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12760 for (; list != NULL; list = list->next)
12761 if (strcmp (list->name, "Z-packet") == 0)
12762 continue;
427c3a89
DJ
12763 else if (list->type == not_set_cmd)
12764 /* Alias commands are exactly like the original, except they
12765 don't have the normal type. */
12766 continue;
12767 else
37a105a1
DJ
12768 {
12769 struct cleanup *option_chain
12770 = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
a744cf53 12771
37a105a1
DJ
12772 ui_out_field_string (uiout, "name", list->name);
12773 ui_out_text (uiout, ": ");
427c3a89 12774 if (list->type == show_cmd)
5b9afe8a 12775 do_show_command ((char *) NULL, from_tty, list);
427c3a89
DJ
12776 else
12777 cmd_func (list, NULL, from_tty);
37a105a1
DJ
12778 /* Close the tuple. */
12779 do_cleanups (option_chain);
12780 }
427c3a89
DJ
12781
12782 /* Close the tuple. */
12783 do_cleanups (showlist_chain);
d471ea57 12784}
5a2468f5 12785
0f71a2f6 12786
23860348 12787/* Function to be called whenever a new objfile (shlib) is detected. */
dc8acb97
MS
12788static void
12789remote_new_objfile (struct objfile *objfile)
12790{
5d93a237
TT
12791 struct remote_state *rs = get_remote_state ();
12792
12793 if (rs->remote_desc != 0) /* Have a remote connection. */
36d25514 12794 remote_check_symbols ();
dc8acb97
MS
12795}
12796
00bf0b85
SS
12797/* Pull all the tracepoints defined on the target and create local
12798 data structures representing them. We don't want to create real
12799 tracepoints yet, we don't want to mess up the user's existing
12800 collection. */
12801
12802static int
ab6617cc 12803remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
d5551862 12804{
00bf0b85
SS
12805 struct remote_state *rs = get_remote_state ();
12806 char *p;
d5551862 12807
00bf0b85
SS
12808 /* Ask for a first packet of tracepoint definition. */
12809 putpkt ("qTfP");
12810 getpkt (&rs->buf, &rs->buf_size, 0);
12811 p = rs->buf;
12812 while (*p && *p != 'l')
d5551862 12813 {
00bf0b85
SS
12814 parse_tracepoint_definition (p, utpp);
12815 /* Ask for another packet of tracepoint definition. */
12816 putpkt ("qTsP");
12817 getpkt (&rs->buf, &rs->buf_size, 0);
12818 p = rs->buf;
d5551862 12819 }
00bf0b85 12820 return 0;
d5551862
SS
12821}
12822
00bf0b85 12823static int
181e3713
TT
12824remote_upload_trace_state_variables (struct target_ops *self,
12825 struct uploaded_tsv **utsvp)
d5551862 12826{
00bf0b85 12827 struct remote_state *rs = get_remote_state ();
d5551862 12828 char *p;
d5551862 12829
00bf0b85
SS
12830 /* Ask for a first packet of variable definition. */
12831 putpkt ("qTfV");
d5551862
SS
12832 getpkt (&rs->buf, &rs->buf_size, 0);
12833 p = rs->buf;
00bf0b85 12834 while (*p && *p != 'l')
d5551862 12835 {
00bf0b85
SS
12836 parse_tsv_definition (p, utsvp);
12837 /* Ask for another packet of variable definition. */
12838 putpkt ("qTsV");
d5551862
SS
12839 getpkt (&rs->buf, &rs->buf_size, 0);
12840 p = rs->buf;
12841 }
00bf0b85 12842 return 0;
d5551862
SS
12843}
12844
c1e36e3e
PA
12845/* The "set/show range-stepping" show hook. */
12846
12847static void
12848show_range_stepping (struct ui_file *file, int from_tty,
12849 struct cmd_list_element *c,
12850 const char *value)
12851{
12852 fprintf_filtered (file,
12853 _("Debugger's willingness to use range stepping "
12854 "is %s.\n"), value);
12855}
12856
12857/* The "set/show range-stepping" set hook. */
12858
12859static void
12860set_range_stepping (char *ignore_args, int from_tty,
12861 struct cmd_list_element *c)
12862{
5d93a237
TT
12863 struct remote_state *rs = get_remote_state ();
12864
c1e36e3e
PA
12865 /* Whene enabling, check whether range stepping is actually
12866 supported by the target, and warn if not. */
12867 if (use_range_stepping)
12868 {
5d93a237 12869 if (rs->remote_desc != NULL)
c1e36e3e 12870 {
4082afcc 12871 if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
c1e36e3e
PA
12872 remote_vcont_probe (rs);
12873
4082afcc 12874 if (packet_support (PACKET_vCont) == PACKET_ENABLE
c1e36e3e
PA
12875 && rs->supports_vCont.r)
12876 return;
12877 }
12878
12879 warning (_("Range stepping is not supported by the current target"));
12880 }
12881}
12882
c906108c 12883void
fba45db2 12884_initialize_remote (void)
c906108c 12885{
ea9c271d 12886 struct remote_state *rs;
9a7071a8 12887 struct cmd_list_element *cmd;
6f937416 12888 const char *cmd_name;
ea9c271d 12889
0f71a2f6 12890 /* architecture specific data */
2bc416ba 12891 remote_gdbarch_data_handle =
23860348 12892 gdbarch_data_register_post_init (init_remote_state);
29709017
DJ
12893 remote_g_packet_data_handle =
12894 gdbarch_data_register_pre_init (remote_g_packet_data_init);
d01949b6 12895
ea9c271d
DJ
12896 /* Initialize the per-target state. At the moment there is only one
12897 of these, not one per target. Only one target is active at a
cf792862
TT
12898 time. */
12899 remote_state = new_remote_state ();
ea9c271d 12900
c906108c
SS
12901 init_remote_ops ();
12902 add_target (&remote_ops);
12903
12904 init_extended_remote_ops ();
12905 add_target (&extended_remote_ops);
cce74817 12906
dc8acb97 12907 /* Hook into new objfile notification. */
06d3b283 12908 observer_attach_new_objfile (remote_new_objfile);
5f4cf0bb
YQ
12909 /* We're no longer interested in notification events of an inferior
12910 when it exits. */
12911 observer_attach_inferior_exit (discard_pending_stop_replies);
dc8acb97 12912
b803fb0f 12913 /* Set up signal handlers. */
934b9bac 12914 async_sigint_remote_token =
b803fb0f 12915 create_async_signal_handler (async_remote_interrupt, NULL);
934b9bac 12916 async_sigint_remote_twice_token =
6d549500 12917 create_async_signal_handler (async_remote_interrupt_twice, NULL);
b803fb0f 12918
c906108c
SS
12919#if 0
12920 init_remote_threadtests ();
12921#endif
12922
722247f1 12923 stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
23860348 12924 /* set/show remote ... */
d471ea57 12925
1bedd215 12926 add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
5a2468f5
JM
12927Remote protocol specific variables\n\
12928Configure various remote-protocol specific variables such as\n\
1bedd215 12929the packets being used"),
cff3e48b 12930 &remote_set_cmdlist, "set remote ",
23860348 12931 0 /* allow-unknown */, &setlist);
1bedd215 12932 add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
5a2468f5
JM
12933Remote protocol specific variables\n\
12934Configure various remote-protocol specific variables such as\n\
1bedd215 12935the packets being used"),
cff3e48b 12936 &remote_show_cmdlist, "show remote ",
23860348 12937 0 /* allow-unknown */, &showlist);
5a2468f5 12938
1a966eab
AC
12939 add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12940Compare section data on target to the exec file.\n\
95cf3b38
DT
12941Argument is a single section name (default: all loaded sections).\n\
12942To compare only read-only loaded sections, specify the -r option."),
c906108c
SS
12943 &cmdlist);
12944
1a966eab
AC
12945 add_cmd ("packet", class_maintenance, packet_command, _("\
12946Send an arbitrary packet to a remote target.\n\
c906108c
SS
12947 maintenance packet TEXT\n\
12948If GDB is talking to an inferior via the GDB serial protocol, then\n\
12949this command sends the string TEXT to the inferior, and displays the\n\
12950response packet. GDB supplies the initial `$' character, and the\n\
1a966eab 12951terminating `#' character and checksum."),
c906108c
SS
12952 &maintenancelist);
12953
7915a72c
AC
12954 add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12955Set whether to send break if interrupted."), _("\
12956Show whether to send break if interrupted."), _("\
12957If set, a break, instead of a cntrl-c, is sent to the remote target."),
9a7071a8 12958 set_remotebreak, show_remotebreak,
e707bbc2 12959 &setlist, &showlist);
9a7071a8
JB
12960 cmd_name = "remotebreak";
12961 cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12962 deprecate_cmd (cmd, "set remote interrupt-sequence");
12963 cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12964 cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12965 deprecate_cmd (cmd, "show remote interrupt-sequence");
12966
12967 add_setshow_enum_cmd ("interrupt-sequence", class_support,
3e43a32a
MS
12968 interrupt_sequence_modes, &interrupt_sequence_mode,
12969 _("\
9a7071a8
JB
12970Set interrupt sequence to remote target."), _("\
12971Show interrupt sequence to remote target."), _("\
12972Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12973 NULL, show_interrupt_sequence,
12974 &remote_set_cmdlist,
12975 &remote_show_cmdlist);
12976
12977 add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12978 &interrupt_on_connect, _("\
12979Set whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12980Show whether interrupt-sequence is sent to remote target when gdb connects to."), _(" \
12981If set, interrupt sequence is sent to remote target."),
12982 NULL, NULL,
12983 &remote_set_cmdlist, &remote_show_cmdlist);
c906108c 12984
23860348 12985 /* Install commands for configuring memory read/write packets. */
11cf8741 12986
1a966eab
AC
12987 add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12988Set the maximum number of bytes per memory write packet (deprecated)."),
11cf8741 12989 &setlist);
1a966eab
AC
12990 add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12991Show the maximum number of bytes per memory write packet (deprecated)."),
11cf8741
JM
12992 &showlist);
12993 add_cmd ("memory-write-packet-size", no_class,
1a966eab
AC
12994 set_memory_write_packet_size, _("\
12995Set the maximum number of bytes per memory-write packet.\n\
12996Specify the number of bytes in a packet or 0 (zero) for the\n\
12997default packet size. The actual limit is further reduced\n\
12998dependent on the target. Specify ``fixed'' to disable the\n\
12999further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13000 &remote_set_cmdlist);
13001 add_cmd ("memory-read-packet-size", no_class,
1a966eab
AC
13002 set_memory_read_packet_size, _("\
13003Set the maximum number of bytes per memory-read packet.\n\
13004Specify the number of bytes in a packet or 0 (zero) for the\n\
13005default packet size. The actual limit is further reduced\n\
13006dependent on the target. Specify ``fixed'' to disable the\n\
13007further restriction and ``limit'' to enable that restriction."),
11cf8741
JM
13008 &remote_set_cmdlist);
13009 add_cmd ("memory-write-packet-size", no_class,
13010 show_memory_write_packet_size,
1a966eab 13011 _("Show the maximum number of bytes per memory-write packet."),
11cf8741
JM
13012 &remote_show_cmdlist);
13013 add_cmd ("memory-read-packet-size", no_class,
13014 show_memory_read_packet_size,
1a966eab 13015 _("Show the maximum number of bytes per memory-read packet."),
11cf8741 13016 &remote_show_cmdlist);
c906108c 13017
b3f42336 13018 add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
7915a72c
AC
13019 &remote_hw_watchpoint_limit, _("\
13020Set the maximum number of target hardware watchpoints."), _("\
13021Show the maximum number of target hardware watchpoints."), _("\
13022Specify a negative limit for unlimited."),
3e43a32a
MS
13023 NULL, NULL, /* FIXME: i18n: The maximum
13024 number of target hardware
13025 watchpoints is %s. */
b3f42336 13026 &remote_set_cmdlist, &remote_show_cmdlist);
480a3f21
PW
13027 add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
13028 &remote_hw_watchpoint_length_limit, _("\
13029Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
13030Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
13031Specify a negative limit for unlimited."),
13032 NULL, NULL, /* FIXME: i18n: The maximum
13033 length (in bytes) of a target
13034 hardware watchpoint is %s. */
13035 &remote_set_cmdlist, &remote_show_cmdlist);
b3f42336 13036 add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
7915a72c
AC
13037 &remote_hw_breakpoint_limit, _("\
13038Set the maximum number of target hardware breakpoints."), _("\
13039Show the maximum number of target hardware breakpoints."), _("\
13040Specify a negative limit for unlimited."),
3e43a32a
MS
13041 NULL, NULL, /* FIXME: i18n: The maximum
13042 number of target hardware
13043 breakpoints is %s. */
b3f42336 13044 &remote_set_cmdlist, &remote_show_cmdlist);
501eef12 13045
1b493192
PA
13046 add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
13047 &remote_address_size, _("\
4d28ad1e
AC
13048Set the maximum size of the address (in bits) in a memory packet."), _("\
13049Show the maximum size of the address (in bits) in a memory packet."), NULL,
1b493192
PA
13050 NULL,
13051 NULL, /* FIXME: i18n: */
13052 &setlist, &showlist);
c906108c 13053
ca4f7f8b
PA
13054 init_all_packet_configs ();
13055
444abaca 13056 add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
bb572ddd 13057 "X", "binary-download", 1);
0f71a2f6 13058
444abaca 13059 add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
bb572ddd 13060 "vCont", "verbose-resume", 0);
506fb367 13061
89be2091
DJ
13062 add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
13063 "QPassSignals", "pass-signals", 0);
13064
9b224c5e
PA
13065 add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
13066 "QProgramSignals", "program-signals", 0);
13067
444abaca 13068 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
bb572ddd 13069 "qSymbol", "symbol-lookup", 0);
dc8acb97 13070
444abaca 13071 add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
bb572ddd 13072 "P", "set-register", 1);
d471ea57 13073
444abaca 13074 add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
bb572ddd 13075 "p", "fetch-register", 1);
b96ec7ac 13076
444abaca 13077 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
bb572ddd 13078 "Z0", "software-breakpoint", 0);
d471ea57 13079
444abaca 13080 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
bb572ddd 13081 "Z1", "hardware-breakpoint", 0);
d471ea57 13082
444abaca 13083 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
bb572ddd 13084 "Z2", "write-watchpoint", 0);
d471ea57 13085
444abaca 13086 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
bb572ddd 13087 "Z3", "read-watchpoint", 0);
d471ea57 13088
444abaca 13089 add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
bb572ddd 13090 "Z4", "access-watchpoint", 0);
d471ea57 13091
0876f84a
DJ
13092 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
13093 "qXfer:auxv:read", "read-aux-vector", 0);
802188a7 13094
c78fa86a
GB
13095 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
13096 "qXfer:exec-file:read", "pid-to-exec-file", 0);
13097
23181151
DJ
13098 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
13099 "qXfer:features:read", "target-features", 0);
13100
cfa9d6d9
DJ
13101 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
13102 "qXfer:libraries:read", "library-info", 0);
13103
2268b414
JK
13104 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
13105 "qXfer:libraries-svr4:read", "library-info-svr4", 0);
13106
fd79ecee
DJ
13107 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
13108 "qXfer:memory-map:read", "memory-map", 0);
13109
0e7f50da
UW
13110 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
13111 "qXfer:spu:read", "read-spu-object", 0);
13112
13113 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
13114 "qXfer:spu:write", "write-spu-object", 0);
13115
07e059b5
VP
13116 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
13117 "qXfer:osdata:read", "osdata", 0);
13118
dc146f7c
VP
13119 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
13120 "qXfer:threads:read", "threads", 0);
13121
4aa995e1
PA
13122 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
13123 "qXfer:siginfo:read", "read-siginfo-object", 0);
13124
13125 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
13126 "qXfer:siginfo:write", "write-siginfo-object", 0);
13127
b3b9301e
PA
13128 add_packet_config_cmd
13129 (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
eb9fe518 13130 "qXfer:traceframe-info:read", "traceframe-info", 0);
b3b9301e 13131
169081d0
TG
13132 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
13133 "qXfer:uib:read", "unwind-info-block", 0);
13134
444abaca 13135 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
38691318 13136 "qGetTLSAddr", "get-thread-local-storage-address",
38691318
KB
13137 0);
13138
711e434b
PM
13139 add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
13140 "qGetTIBAddr", "get-thread-information-block-address",
13141 0);
13142
40ab02ce
MS
13143 add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
13144 "bc", "reverse-continue", 0);
13145
13146 add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
13147 "bs", "reverse-step", 0);
13148
be2a5f71
DJ
13149 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
13150 "qSupported", "supported-packets", 0);
13151
08388c79
DE
13152 add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
13153 "qSearch:memory", "search-memory", 0);
13154
bd3eecc3
PA
13155 add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
13156 "qTStatus", "trace-status", 0);
13157
15a201c8
GB
13158 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
13159 "vFile:setfs", "hostio-setfs", 0);
13160
a6b151f1
DJ
13161 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
13162 "vFile:open", "hostio-open", 0);
13163
13164 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
13165 "vFile:pread", "hostio-pread", 0);
13166
13167 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
13168 "vFile:pwrite", "hostio-pwrite", 0);
13169
13170 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
13171 "vFile:close", "hostio-close", 0);
13172
13173 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
13174 "vFile:unlink", "hostio-unlink", 0);
13175
b9e7b9c3
UW
13176 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
13177 "vFile:readlink", "hostio-readlink", 0);
13178
0a93529c
GB
13179 add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
13180 "vFile:fstat", "hostio-fstat", 0);
13181
2d717e4f
DJ
13182 add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
13183 "vAttach", "attach", 0);
13184
13185 add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
13186 "vRun", "run", 0);
13187
a6f3e723
SL
13188 add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
13189 "QStartNoAckMode", "noack", 0);
13190
82f73884
PA
13191 add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
13192 "vKill", "kill", 0);
13193
0b16c5cf
PA
13194 add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
13195 "qAttached", "query-attached", 0);
13196
782b2b07 13197 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
3e43a32a
MS
13198 "ConditionalTracepoints",
13199 "conditional-tracepoints", 0);
3788aec7
LM
13200
13201 add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
13202 "ConditionalBreakpoints",
13203 "conditional-breakpoints", 0);
13204
d3ce09f5
SS
13205 add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
13206 "BreakpointCommands",
13207 "breakpoint-commands", 0);
13208
7a697b8d
SS
13209 add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
13210 "FastTracepoints", "fast-tracepoints", 0);
782b2b07 13211
409873ef
SS
13212 add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
13213 "TracepointSource", "TracepointSource", 0);
13214
d914c394
SS
13215 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
13216 "QAllow", "allow", 0);
13217
0fb4aa4b
PA
13218 add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
13219 "StaticTracepoints", "static-tracepoints", 0);
13220
1e4d1764
YQ
13221 add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
13222 "InstallInTrace", "install-in-trace", 0);
13223
0fb4aa4b
PA
13224 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
13225 "qXfer:statictrace:read", "read-sdata-object", 0);
13226
78d85199
YQ
13227 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
13228 "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
13229
03583c20
UW
13230 add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
13231 "QDisableRandomization", "disable-randomization", 0);
13232
d1feda86
YQ
13233 add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
13234 "QAgent", "agent", 0);
13235
f6f899bf
HAQ
13236 add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
13237 "QTBuffer:size", "trace-buffer-size", 0);
13238
9accd112
MM
13239 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
13240 "Qbtrace:off", "disable-btrace", 0);
13241
13242 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
b20a6524
MM
13243 "Qbtrace:bts", "enable-btrace-bts", 0);
13244
13245 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
13246 "Qbtrace:pt", "enable-btrace-pt", 0);
9accd112
MM
13247
13248 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
13249 "qXfer:btrace", "read-btrace", 0);
13250
f4abbc16
MM
13251 add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
13252 "qXfer:btrace-conf", "read-btrace-conf", 0);
13253
d33501a5
MM
13254 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
13255 "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
13256
73b8c1fd
PA
13257 add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
13258 "multiprocess-feature", "multiprocess-feature", 0);
13259
f7e6eed5
PA
13260 add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
13261 "swbreak-feature", "swbreak-feature", 0);
13262
13263 add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
13264 "hwbreak-feature", "hwbreak-feature", 0);
13265
89245bc0
DB
13266 add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
13267 "fork-event-feature", "fork-event-feature", 0);
13268
13269 add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
13270 "vfork-event-feature", "vfork-event-feature", 0);
13271
b20a6524
MM
13272 add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
13273 "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
13274
0b736949
DB
13275 /* Assert that we've registered "set remote foo-packet" commands
13276 for all packet configs. */
ca4f7f8b
PA
13277 {
13278 int i;
13279
13280 for (i = 0; i < PACKET_MAX; i++)
13281 {
13282 /* Ideally all configs would have a command associated. Some
13283 still don't though. */
13284 int excepted;
13285
13286 switch (i)
13287 {
13288 case PACKET_QNonStop:
ca4f7f8b
PA
13289 case PACKET_EnableDisableTracepoints_feature:
13290 case PACKET_tracenz_feature:
13291 case PACKET_DisconnectedTracing_feature:
13292 case PACKET_augmented_libraries_svr4_read_feature:
936d2992
PA
13293 case PACKET_qCRC:
13294 /* Additions to this list need to be well justified:
13295 pre-existing packets are OK; new packets are not. */
ca4f7f8b
PA
13296 excepted = 1;
13297 break;
13298 default:
13299 excepted = 0;
13300 break;
13301 }
13302
13303 /* This catches both forgetting to add a config command, and
13304 forgetting to remove a packet from the exception list. */
13305 gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
13306 }
13307 }
13308
37a105a1
DJ
13309 /* Keep the old ``set remote Z-packet ...'' working. Each individual
13310 Z sub-packet has its own set and show commands, but users may
13311 have sets to this variable in their .gdbinit files (or in their
13312 documentation). */
e9e68a56 13313 add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
7915a72c
AC
13314 &remote_Z_packet_detect, _("\
13315Set use of remote protocol `Z' packets"), _("\
13316Show use of remote protocol `Z' packets "), _("\
3b64bf98 13317When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
7915a72c 13318packets."),
e9e68a56 13319 set_remote_protocol_Z_packet_cmd,
3e43a32a
MS
13320 show_remote_protocol_Z_packet_cmd,
13321 /* FIXME: i18n: Use of remote protocol
13322 `Z' packets is %s. */
e9e68a56 13323 &remote_set_cmdlist, &remote_show_cmdlist);
449092f6 13324
a6b151f1
DJ
13325 add_prefix_cmd ("remote", class_files, remote_command, _("\
13326Manipulate files on the remote system\n\
13327Transfer files to and from the remote target system."),
13328 &remote_cmdlist, "remote ",
13329 0 /* allow-unknown */, &cmdlist);
13330
13331 add_cmd ("put", class_files, remote_put_command,
13332 _("Copy a local file to the remote system."),
13333 &remote_cmdlist);
13334
13335 add_cmd ("get", class_files, remote_get_command,
13336 _("Copy a remote file to the local system."),
13337 &remote_cmdlist);
13338
13339 add_cmd ("delete", class_files, remote_delete_command,
13340 _("Delete a remote file."),
13341 &remote_cmdlist);
13342
2d717e4f
DJ
13343 remote_exec_file = xstrdup ("");
13344 add_setshow_string_noescape_cmd ("exec-file", class_files,
13345 &remote_exec_file, _("\
13346Set the remote pathname for \"run\""), _("\
13347Show the remote pathname for \"run\""), NULL, NULL, NULL,
13348 &remote_set_cmdlist, &remote_show_cmdlist);
13349
c1e36e3e
PA
13350 add_setshow_boolean_cmd ("range-stepping", class_run,
13351 &use_range_stepping, _("\
13352Enable or disable range stepping."), _("\
13353Show whether target-assisted range stepping is enabled."), _("\
13354If on, and the target supports it, when stepping a source line, GDB\n\
13355tells the target to step the corresponding range of addresses itself instead\n\
13356of issuing multiple single-steps. This speeds up source level\n\
13357stepping. If off, GDB always issues single-steps, even if range\n\
13358stepping is supported by the target. The default is on."),
13359 set_range_stepping,
13360 show_range_stepping,
13361 &setlist,
13362 &showlist);
13363
449092f6
CV
13364 /* Eventually initialize fileio. See fileio.c */
13365 initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
79d7f229 13366
ba348170 13367 /* Take advantage of the fact that the TID field is not used, to tag
79d7f229 13368 special ptids with it set to != 0. */
ba348170
PA
13369 magic_null_ptid = ptid_build (42000, -1, 1);
13370 not_sent_ptid = ptid_build (42000, -2, 1);
13371 any_thread_ptid = ptid_build (42000, 0, 1);
35b1e5cc
SS
13372
13373 target_buf_size = 2048;
13374 target_buf = xmalloc (target_buf_size);
c906108c 13375}
10760264 13376
This page took 3.655538 seconds and 4 git commands to generate.